% saves a CSV file with the relevant variables (for Research Bulletin)
% open the figure with the subplots
% then run this (assuming the figure is number 1)
%NB need to open the figure from .fig file and run this before doing
%anything to the figure, otherwise data won't be in its place
clear all
fig_numb=1;
data=graph_extract_data(fig_numb);
nmtxt=get(fig_numb,'FileName');
variables=[2,3,8,9];

sz=[];

for jj=variables;
    mx=[];
    for kk=1:size(data,1)-1;
        sz=[sz;length(data{kk,jj})];
    end
    mxsz=max(sz);
    for kk=1:size(data,1)-1;
        if sz(kk)==mxsz && any(data{kk,jj})
            mx=[mx,data{kk,jj}];
        end
    end
    eval(['g.',regexprep(char(data(end,jj)),'\s|\(|\)',''),'=mx;']);
    
end

nmsg=fieldnames(g);
tmp=[];
numvar=size(eval(['g.',char(nmsg(1))]),2)-1;
for kk=1:length(nmsg);
tmp=[tmp,char(nmsg(kk))];
for jj=1:numvar
       tmp=[tmp,', " " '];
end
end
tmp2=repmat([',Full-Integration, ',' Capital-Autarky '],1,length(nmsg)-1);
tmp2=[['Full-Integration, ',' Capital-Autarky '],tmp2];

nmtxt=[nmtxt(1:end-4),'.csv'];
fid=fopen(nmtxt,'w+');
fprintf(fid,'%s\n',tmp);
fclose(fid);
fid=fopen(nmtxt,'a+');
fprintf(fid,'%s\n',tmp2);
mx=struct2array(g);
dlmwrite(nmtxt,mx,'-append','delimiter',',');
