%Copyright (c) 2010, Luuk J.G.W. van Wilderen
%
%save_figs_data.m

function save_figs_data
%Saving of (open) figures and data

%Defined in fit_data
global filename model nr_svd_comps comps dispersfilename
global Par_fix_spectra_matrix Par_fix_switch obj analysis
global Par_fix_time IRF Par_fix_IRF SVDcontrib_switch Par_fix_time_zero
global Par_fix_OD_offset Error_switch_lin_spectra
%Defined in plot_figs
global svd_comp_perc
%Defined in globfit_bio_gui
global ydata RESNORM OUTPUT sing_val V opt_specs y_fit opt_times opt_pars
global ci_times_errorbars ci_other start_pars start_pars_lin 
global time_fix_counter
%Defined in globfun_bio
global spectra_std opt_pars_lin opt_pars_lin_std decays RESIDUAL
%Defined in dispersion_IRF_calc
global delay_shift_curve

PathName=pwd;
directory_name_data_figs=uigetdir(PathName,'Select folder');
if directory_name_data_figs==0
    error('Saving figures aborted by user');
end
cd (directory_name_data_figs);
clear directory_name_data_figs

if isempty(opt_specs)==0
    %Only save spectra, traces, etc. if global fit has been performed. 
    %These are not generated if only the dispersion is estimated.

    if Error_switch_lin_spectra==0
        save fit_spec.dat opt_specs -ascii                  %Spectra
    elseif Error_switch_lin_spectra==1
        opt_specs_err=[opt_specs spectra_std'];
        save fit_spec_err.dat opt_specs_err -ascii          %Spectra including errors
    end
    save conc_prof.dat decays -ascii                        %Concentration profiles
    res_spec=sum(RESIDUAL,1);
    save res_spec.dat res_spec -ascii                       %Residuals of fit in spectral domain
    res_time=sum(RESIDUAL,2);
    save res_time.dat res_time -ascii                       %Residuals of fit in time domain
    
    dlmwrite ('fit_pars.txt',num2str(datestr(clock)),'delimiter','','-append')
    dlmwrite ('fit_pars.txt',['Datafile: ',strcat(PathName,filename)],'delimiter','','-append')
    dlmwrite ('fit_pars.txt',['Loaded model: ',model],'delimiter','','-append')
    dlmwrite ('fit_pars.txt',['Iterations needed: ',num2str(OUTPUT.iterations)],'delimiter','','-append')
    if nr_svd_comps==0
        dlmwrite ('fit_pars.txt','Global fit of all data','delimiter','','-append')
        save fit_trace.dat y_fit -ascii                     %Fitted data
    elseif nr_svd_comps~=0
        dlmwrite ('fit_pars.txt',['Global fit of ',num2str(nr_svd_comps),' SVD components'],'delimiter','','-append')
        
        if SVDcontrib_switch==0
            save fit_trace_svd.dat y_fit -ascii             %Fitted left singular values (traces)
        elseif SVDcontrib_switch==1
            save fit_trace_svd_weighted.dat y_fit -ascii    %Fitted left singular values (weighted traces)
        end
        
        trace_svd=ydata(:,1:nr_svd_comps);
        save trace_svd.dat trace_svd -ascii                 %Raw singular values (traces)
        
        if SVDcontrib_switch==0
            svd_spectra=V(:,1:nr_svd_comps);
            save svd_spectra.dat svd_spectra -ascii         %Right singular values (spectra, not fitted!)
        elseif SVDcontrib_switch==1
            for i=1:nr_svd_comps
                svd_spectra(:,i)=sing_val(i)*V(:,i);
            end
            save svd_spectra_weighted.dat svd_spectra -ascii     %Right singular values (weighted spectra, not fitted!)
        end
        
        save sing_val_svd.dat sing_val -ascii               %Singular values
        clear svd_spectra trace_svd
    end
    if size(Par_fix_spectra_matrix,2)==2 && Par_fix_switch==1
        for s=1:size(Par_fix_spectra_matrix,1)
            dlmwrite ('fit_pars.txt',['Spectrum of state ',num2str(Par_fix_spectra_matrix(s,1)),' is equal to ',num2str(Par_fix_spectra_matrix(2))],'delimiter','','-append')
        end
        clear s
    end
    dlmwrite ('fit_pars.txt','      Input reactions:','delimiter','','-append')
    for i=1:size(obj.reactions,1)
        dlmwrite ('fit_pars.txt',obj.reactions(i).reaction,'delimiter','','-append')
    end
    dlmwrite ('fit_pars.txt','  Reaction rates used:','delimiter','','-append')
    for i=1:size(obj.reactions,1)
        dlmwrite ('fit_pars.txt',obj.reactions(i).ReactionRate,'delimiter','','-append')
    end
    clear i
    dlmwrite ('fit_pars.txt','    Input populations:','delimiter','','-append')
    for i=1:size(obj.species,1)
        dlmwrite ('fit_pars.txt',cat(2,obj.species(i).name,' ',num2str(obj.species(i).initialAmount)),'delimiter','','-append')
    end
    clear i
    
    if analysis==1
        dlmwrite ('fit_pars.txt','Optimised parameters PARALLEL model','delimiter','','-append')
    elseif analysis==2
        dlmwrite ('fit_pars.txt','Optimised parameters SEQUENTIAL model','delimiter','','-append')
    elseif analysis==3
        dlmwrite ('fit_pars.txt','Optimised paramete TARGET model','delimiter','','-append')
    end
    if Par_fix_OD_offset==0
        dlmwrite ('fit_pars.txt',[            '        OD offset: ',num2str(opt_pars_lin)],'delimiter','','-append')
    elseif Par_fix_OD_offset==1
        dlmwrite ('fit_pars.txt',[            '        OD offset: ',num2str(start_pars_lin),' (fixed)'],'delimiter','','-append')
    end
    if Par_fix_time_zero==0
        dlmwrite ('fit_pars.txt',[        '        time zero: ',num2str(opt_pars(comps+1-time_fix_counter))],'delimiter','','-append')
    elseif Par_fix_time_zero==1
        dlmwrite ('fit_pars.txt',[        '        time zero: ',num2str(start_pars(comps+1)),' (fixed)'],'delimiter','','-append')
    end
    if sum(Par_fix_time)==0
        dlmwrite ('fit_pars.txt',[        '   Time constants: ',num2str(opt_times)],'delimiter','','-append')
    elseif  sum(Par_fix_time)>0 && length(Par_fix_time)<comps
        dlmwrite ('fit_pars.txt',[        '   Time constants: ',num2str(opt_times),' (Index fixed component(s): ',num2str(Par_fix_time),')'],'delimiter','','-append')
    elseif length(Par_fix_time)==comps
        dlmwrite ('fit_pars.txt',[        '   Time constants: ',num2str(opt_times),' (All fixed)'],'delimiter','','-append')
    end
    if length(IRF)==2 && IRF(2)~=0
        if Par_fix_IRF==0
            dlmwrite ('fit_pars.txt',[    '  IRF (FWHM, t0):  ',num2str(opt_pars(comps+2-time_fix_counter-Par_fix_time_zero:comps+3-time_fix_counter-Par_fix_time_zero))],'delimiter','','-append')
        elseif Par_fix_IRF==1
            dlmwrite ('fit_pars.txt',[    '  IRF (FWHM, t0):  ',num2str(start_pars(comps+2-Par_fix_time_zero:comps+3-Par_fix_time_zero)),' (fixed)'],'delimiter','','-append')
        end
    end
    
    dlmwrite ('fit_pars.txt',[        'Note that there are fixed parameters'],'delimiter','','-append')
    dlmwrite ('fit_pars.txt',[            '   Error (+/-STD): ',num2str(ci_times_errorbars(1:comps)')],'delimiter','','-append')
    if Par_fix_time_zero==1  && Par_fix_OD_offset==0
        dlmwrite ('fit_pars.txt',[        '    Error (OD,t0): ',num2str(opt_pars_lin_std),' 0'],'delimiter','','-append')
    elseif Par_fix_time_zero==0 && Par_fix_OD_offset==0
        dlmwrite ('fit_pars.txt',[        '    Error (OD,t0): ',num2str(opt_pars_lin_std),' ',num2str(ci_other(1,2)'-opt_pars(comps+1-time_fix_counter))],'delimiter','','-append')
    elseif Par_fix_time_zero==0 && Par_fix_OD_offset==1
        dlmwrite ('fit_pars.txt',[        '    Error (OD,t0): 0 ',num2str(ci_other(1,2)'-opt_pars(comps+1-time_fix_counter))],'delimiter','','-append')
    elseif Par_fix_time_zero==1 && Par_fix_OD_offset==1
        dlmwrite ('fit_pars.txt',[        '    Error (OD,t0): 0 0'],'delimiter','','-append')
    end
    if Par_fix_switch==1
        if length(IRF)==2 && Par_fix_IRF==0
            dlmwrite ('fit_pars.txt',[    'Er.IRF(FWHM, t0):  ',num2str(ci_other(2:3,2)'-opt_pars(comps+2-time_fix_counter-Par_fix_time_zero:comps+3-time_fix_counter-Par_fix_time_zero))],'delimiter','','-append')
        elseif  length(IRF)==2 && Par_fix_IRF==1
            dlmwrite ('fit_pars.txt',[    'Er.IRF(FWHM, t0):  0 0'],'delimiter','','-append')
        end
    elseif Par_fix_switch==0
        if length(IRF)==2 && Par_fix_IRF==0
            dlmwrite ('fit_pars.txt',[    'Er.IRF(FWHM, t0):  ',num2str(ci_other(2:3,2)'-opt_pars(comps+2-time_fix_counter-Par_fix_time_zero:comps+3-time_fix_counter-Par_fix_time_zero))],'delimiter','','-append')
        end
    end
    
    if nr_svd_comps>0 %Needs 'svd_comp_perc' calculated by plot_figs
        dlmwrite ('fit_pars.txt',['First ',num2str(nr_svd_comps),' singular values : ',num2str(sing_val(1:nr_svd_comps)')],'delimiter','','-append')
        if SVDcontrib_switch==1
            dlmwrite ('fit_pars.txt',['Contribution per species to data (%): ',num2str(svd_comp_perc)],'delimiter','','-append')
        end
    end
    dlmwrite ('fit_pars.txt',[            '         Residual: ',num2str(RESNORM)],'delimiter','','-append')
    dlmwrite ('fit_pars.txt',' ','-append')
    
    if exist('delay_shift_curve')==1 && isempty(delay_shift_curve)==0
        save dispersion_curve.dat delay_shift_curve -ascii   
    end
end
if exist('delay_shift_curve')==1 && isempty(delay_shift_curve)==0
    save dispersion_curve.dat delay_shift_curve -ascii                 %Dispersion as function of pixel/wavelength
end

%Saving open figures
if isempty(findobj('Name','Loaded_raw_data'))==0
    saveas (findobj('Name','Loaded_raw_data'),'raw_data.fig')
end
if isempty(findobj('Name','Explore raw data'))==0
    saveas (findobj('Name','Explore raw data'),'raw_data_explorer.fig')
end
if isempty(findobj('Name','Dispersion estimation'))==0
    saveas (findobj('Name','Dispersion estimation'),'dispers_estim.fig')
end
if isempty(findobj('Name','Loaded dispersion curve'))==0
    saveas (findobj('Name','Loaded dispersion curve'),'loaded_dispers.fig')
end
if isempty(findobj('Name','Raw data Concentration profiles'))==0
    saveas (findobj('Name','Raw data Concentration profiles'),'raw_conc_prof.fig')
end
if isempty(findobj('Name','trace1'))==0
    saveas (findobj('Name','trace1'),'trace1.fig')
end
if isempty(findobj('Name','spectra'))==0
    saveas (findobj('Name','spectra'),'spectra.fig')
end
if isempty(findobj('Name','trace2'))==0
    saveas (findobj('Name','trace2'),'trace2.fig')
end
if isempty(findobj('Name','trace3'))==0
    saveas (findobj('Name','trace3'),'trace3.fig')
end
if isempty(findobj('Name','trace4'))==0
    saveas (findobj('Name','trace4'),'trace4.fig')
end
if isempty(findobj('Name','trace5'))==0
    saveas (findobj('Name','trace5'),'trace5.fig')
end
if isempty(findobj('Name','trace6'))==0
    saveas (findobj('Name','trace6'),'trace6.fig')
end
if isempty(findobj('Name','Explore fit'))==0
    saveas (findobj('Name','Explore fit'),'fit_explorer.fig')
end
if isempty(findobj('Name','residuals'))==0
    saveas (findobj('Name','residuals'),'residuals.fig')
end
saveas(findobj('Name','Globe_Toolbox v1.00'),'gui.jpg')
