function dyna
% help
% Dyna V 3.18 (developping)

global log_file_name log_file_id sequence project_name layer_name launch_directory...
    main_frame graph_frame panel_messages send_messages_box ...
    lstbox_control_multilayer lst_layer_to_constrain_with lst_layer...
    linscale ratio_mag_inverted calculation_done_flag...
    unpolarized linear circular data_control sign th2Q ...
    Kerr_sigma Kerr_pi edtxmax edtxmin x_min x_max...
    nb_param lst_param lbxParam_to_optim box_optimization_output...
    btnStartStop btnAccept btnReset btnDelete btnResetParam...
    edtTolFun edtTolX edtMaxFunEvals edtMaxIter ...
    text_to_send  list_to_stamp line_to_delete ...
    plot_function out_param twopi final_value

%%
%%%%%%%%%%%%%%%%%%%%%%%%
%%%    STRUCTURES    %%%
%%%    DEFINITIONS   %%%
%%%%%%%%%%%%%%%%%%%%%%%%

shift = struct('x',{[-20 0 20]},'y',{[1e-10 1 1e10]},'bkg',{[0 1e-8 1e-5]});

data = struct('name',' nodata','adjust',shift,'values',{[]},'post_values',{[]},'optim_values',{[]},'intervall',{[]});%,'error_function_flag',{[]}

calc = struct('adjust',shift,'R',{[]},'exp_phase',{[]},'Q',{[]},'M_final',{[]},'M_final_phi',{[]},'reflectivity',{[]},'post_reflectivity',{[]},'adjusted_results',{[]},'ratio',{[]},'diff',{[]},'imprint',{[]});

SF  = struct('cf',{[]},'mf',{[]},'cf2',{[]});

sim =  struct('number_string',{'sim #1 :'},'number',{1},'formalism',{1},'typescan',{1},'energy',{[600 700 0.1]},'angle',{[1 90 0.1 0.1]},'Q',{0.1},'slength',{1},'sthickness',{1},'pol',{[1 0]}, 'pol_out',{[1 1]},'pol_analyzer',{[2 1]},'plot_ratio',{0},'plot_diff',{0},'function',{@F0_ef});

layer = struct('name',{'layer'},'m',{1},'density',{[0.05 0.1 0.15]},'thickness',{[10 20 30]},'roughness',{[0 3 5]},'MMS',{[0 1 1]},'phi',{[0 0 90]},'gamma',{[0 0 90]},'AS',{[0 0 1]});

%%
%%%%%%%%%%%%%%%%%%%%%%%%
%%%                  %%%
%%%    DEFAULT       %%%
%%%    INITIAL       %%%
%%%    VALUES        %%%
%%%                  %%%
%%%%%%%%%%%%%%%%%%%%%%%%
twopi=2*pi;
list_to_stamp={sprintf('')};
nb_param=0;to_fit=1;
param_fittable={'density','thickness','roughness','MMS','AS','phi','gamma'};
optimization_method='Simplex';

date_now = clock;
date_now = strcat(num2str(date_now(1)),'_',num2str(date_now(2)),'_', num2str(date_now(3)));
log_file_name=strcat('messages.log');
log_file_id=fopen(log_file_name,'w');

default_data=data;
default_calc=calc;
default_sim=sim;
old_layer=layer;

launch_directory = pwd;
datafile_directory = pwd;
project_directory = pwd; % add a test for the presence of the directories

unpolarized=0;linear=0;circular=1;

ratio_mag_inverted=1;
Kerr_sigma=0; Kerr_pi=0;
linscale=0; sign=1; % for flip toggle of ratio
th2Q=0; % toggle degree and A-1

x_min='0'; x_max='90'; text_to_send= 'fit output window';
data_control=1;
calculation_done_flag=0;
on_the_fly_sync = 1; % on the fly sync is set on by default
calc_now=0; % to perform a calculation when on the fly sync is off

% INITIAL PROJECT
project_name='W/Si from Elements of Modern X-ray Physics Als-Nielsen and Mc Morrow';
layer(1) = struct('name',{'W'},'m',{10},'density',{[0.0 0.1085 0.11]},'thickness',{[5 10 20]},'roughness',{[0 0 5]},'MMS',{[0 0 1]},'phi',{[0 0 90]},'gamma',{[0 0 90]},'AS',{[0 0 1]});
layer(2) = struct('name',{'Si'},'m',{10},'density',{[0.0 0.0829 0.1]},'thickness',{[20 40 50]},'roughness',{[0 0 5]},'MMS',{[0 0 1]},'phi',{[0 0 90]},'gamma',{[0 0 90]},'AS',{[0 0 1]});
layer(3) = struct('name',{'Si'},'m',{1},'density',{[0.01 0.0829 0.1]},'thickness',{[0 0 1]},'roughness',{[0 0 5]},'MMS',{[0 0 1]},'phi',{[0 0 90]},'gamma',{[0 0 90]},'AS',{[0 0 1]});
sim(1).energy=[8047 8100 1];
sim(1).angle=[0 2 0.001 0];
sim(1).sthickness=0;
default_layer=layer;
%%
%%%%%%%%%%%%%%%%%%%%%%%%
%%%                  %%%
%%%    CALLBACK      %%%
%%%    FUNCTIONS     %%%
%%%                 %%%
%%%%%%%%%%%%%%%%%%%%%%%%
%%called from the graphic interface

    function callers_Menu_Callback(hObject,~)
        
        ii=get(lst_sim,'Value');
        if ~project_directory
            project_directory=launch_directory;
        end
        
        switch get(hObject,'Tag')
            % SIM %
            case 'Add' % add Sim
                
                nb_list_sim=length(sim)+1;
                sim(nb_list_sim)=sim(ii); %copy active sim into new one
                sim(nb_list_sim).number_string=sprintf('sim #%i ',nb_list_sim);
                sim(nb_list_sim).number = nb_list_sim;
                calc(nb_list_sim)=calc(ii);
                data(nb_list_sim)=data(ii);
                Stamp_Sim_Panel(nb_list_sim);
                [calc(nb_list_sim),data(nb_list_sim),SF(nb_list_sim)]=preallocate(sim(nb_list_sim),calc(nb_list_sim),data(nb_list_sim),layer,0);
                calculate(nb_list_sim);
                
            case 'Delete' % delete Sim
                
                ii_to_delete=ii;
                
                if ii_to_delete < length(sim)
                    for kk=ii_to_delete:length(sim)-1
                        sim(kk)=sim(kk+1);
                        sim(kk).number_string=sprintf('sim #%i ',kk);
                        sim(kk).number=kk;
                        data(kk)=data(kk+1);
                        calc(kk)=calc(kk+1);
                    end
                    next=ii_to_delete;
                else
                    next=ii_to_delete-1;
                end
                calc(length(sim))=[];
                data(length(sim))=[];
                sim(length(sim)) =[];% structure size nb-1
                Stamp_Sim_Panel(next);
                [calc(next),data(next),SF(next)]=preallocate(sim(next),calc(next),data(next),layer,0);
                calculate(next);
           
            case 'on-the-fly sync' % toggle sync to avoid lagtime in heavy calculations
                on_the_fly_sync = ~on_the_fly_sync;
  
            case 'calc now' % performs calculations when on the fly sync on
                calc_now=1;
                calculate(ii)
                calc_now=0;
            
                % DATA %   
            case 'ImportData'
                
                if ~datafile_directory
                    datafile_directory=project_directory;
                end
                
                cd(datafile_directory);
                
                [datafile, datafile_directory]=uigetfile('*.*','Dyna: load data file');
                
                if datafile ~= 0
                    data(ii).name = datafile;
                    data(ii).values=load([datafile_directory, datafile])';
                    cd(launch_directory)
                    data(ii).intervall=[data(ii).values(1,1) data(ii).values(1,length(data(ii).values(1,:)))];
                    set(edtxmin,'String',data(ii).intervall(1));
                    set(edtxmax,'String',data(ii).intervall(2));
                    [calc(ii),data(ii)]=dyna_plot(calc(ii),sim(ii),data(ii),0);
                    Stamp_Sim_Panel(ii)
                end
                
                cd(launch_directory)
                
            case 'tth_to_th'
                data(ii).values(1,:) = data(ii).values(1,:)/2;
                [calc(ii),data(ii)]=dyna_plot(calc(ii),sim(ii),data(ii),0);
                
            case 'th_to_tth'
                
                data(ii).values(1,:) = 2*data(ii).values(1,:);
                [calc(ii),data(ii)]=dyna_plot(calc(ii),sim(ii),data(ii),0);
                
            case 'Q_to_th'
                data(ii).values(1,:) = 180/pi*asin(data(ii).values(1,:)/sim(ii).energy(1)*12398.42/4/pi);
                [calc(ii),data(ii)]=dyna_plot(calc(ii),sim(ii),data(ii),0);
                
            case 'q_to_th'
                data(ii).values(1,:) = 180/pi*asin(data(ii).values(1,:)/sim(ii).energy(1)*12398.42/2);
                [calc(ii),data(ii)]=dyna_plot(calc(ii),sim(ii),data(ii),0);
                
            case 'th_to_Q'
                data(ii).values(1,:) =(4*pi*sim(ii).energy(1)/12398.42)*sind(data(ii).values(1,:));
                [calc(ii),data(ii)]=dyna_plot(calc(ii),sim(ii),data(ii),0);
                
            case 'th_to_q'
                data(ii).values(1,:)
                data(ii).values(1,:) = 2*sim(ii).energy(1)/12398.42*sind(data(ii).values(1,:));
                [calc(ii),data(ii)]=dyna_plot(calc(ii),sim(ii),data(ii),0);
                
            case 'DeleteData'
                data(ii).values=[];
                data(ii).optim_values=[];
                data(ii).post_values=[];data(ii).intervall=[0 0];
                data(ii).name='nodata';
                calculate(ii);%??
                [calc(ii),data(ii)]=dyna_plot(calc(ii),sim(ii),data(ii),0);
                Stamp_Sim_Panel(ii)
                
            case 'Help'
                help
                
            case 'About'
                figure_about_dyna = figure('Visible','on','Units','normalized','Position',[0.25,0.25,.5,.5],'Name','dyna Messages','Toolbar','none','MenuBar','none');
                
                uicontrol('Parent',figure_about_dyna,'Style','text','String',fileread('about_dyna.txt'),'Units','normalized','HorizontalAlignment','left','Position',[0 0 1 1]);
            
            case 'Log'
                
                 figure_Log = figure('Visible','on','Units','normalized','Position',[0.25,0.25,.5,.5],'Name','Running Time Messages','Toolbar','none','MenuBar','none');
                
                uicontrol('Parent',figure_Log,'Style','text','String',fileread('messages.log'),'Units','normalized','HorizontalAlignment','left','Position',[0 0 1 1]);
                
            case 'Close'
                
                selection = questdlg(['Close ' get(main_frame,'Name') '?'],['Close ' get(main_frame,'Name') '...'],'Yes','No','Yes');
                if strcmp(selection,'No')
                    return;
                end
                delete(main_frame);
                clear all;
                
            case 'Open'
                
                clear layer sim data calc
                
                if ~project_directory
                    project_directory=launch_directory;
                end
                
                old_project_directory=project_directory;
                
                cd(project_directory);
                
                [project_name,project_directory] =...
                    uigetfile('*.mat','dyna: opening existing project');
                
                if ~project_directory %manage cancelation
                    project_directory=old_project_directory;
                end
                
                datafile_directory=project_directory;
                cd(launch_directory);
                
                if ~isequal(project_name, 0)
                    S=load([project_directory,project_name]);
                    calculation_done_flag=0;
                    layer=S.layer; sim=S.sim;calc=S.calc;data=S.data;
                    stamp_multilayer(layer);
                    Stamp_Sim_Panel(1);
                    make_sequence; %
                    [calc(1),data(1),SF(1)]=...
                        preallocate(sim(1),calc(1),data(1),layer,0);
                    calculate(1);
                    cd(launch_directory);
                else
                    cd(launch_directory);
                    messages='Cancel Open Project';
                    send_messages(messages);
                end
                 
                case 'Open_Old_Version'
                
                clear layer sim data calc
                
                layer=default_layer;
                sim=default_sim;
                data=default_data;
                calc=default_calc;
                
                if ~project_directory
                    project_directory=launch_directory;
                end
                
                old_project_directory=project_directory;
                
                cd(project_directory);
                
                [project_name,project_directory] =...
                    uigetfile('*.mat','dyna: opening existing project');
                
                if ~project_directory %manage cancelation
                    project_directory=old_project_directory;
                end
                
                datafile_directory=project_directory;
                cd(launch_directory);
                
                if ~isequal(project_name, 0)
                    S=load([project_directory,project_name]);
                    calculation_done_flag=0;
                    layer=S.layer;
                    sim=S.sim;
                    calc=S.calc;
                    data=S.data;
                    % ADD NEW STRUCTURE ENTRIES
                    for ii=1:1:length(sim) % IN SIM
                        sim(ii).plot_ratio=0;
                        sim(ii).plot_diff=0;
                        switch (3*(sim(ii).formalism-1)+sim(ii).typescan)
                            
                            case 1
                                sim(ii).function=@F0_ef;
                                
                            case 2
                                sim(ii).function=@F0_af;
                                
                            case 3
                                sim(ii).function=@F0_qf;
                                
                            case 4
                                sim(ii).function=@F0F1_ef;
                                
                            case 5
                                sim(ii).function=@F0F1_af;
                                
                            case 6
                                sim(ii).function=@F0F1_qf;
                                
                            case 7
                                sim(ii).function=@F0F2_Parratt_ef;
                                
                            case 8
                                sim(ii).function=@F0F2_Parratt_af;
                                
                            case 9
                                sim(ii).function=@F0F2_Parratt_qf;
                        end
                    if(~strcmp(data(ii).name,'nodata'))
                        data(ii).intervall=[data(ii).values(1,1) data(ii).values(1,length(data(ii).values(1,:)))];    
                    end
                    calc(ii).diff=[];
                    end
                    
                    stamp_multilayer(layer);
                    Stamp_Sim_Panel(1);
                    make_sequence; %
                    [calc(1),data(1),SF(1)]=...
                        preallocate(sim(1),calc(1),data(1),layer,0);
                    calculate(1);
                    cd(launch_directory);
                    
                else
                    cd(launch_directory);
                    messages='Cancel Open Project';
                    send_messages(messages);
                end
                
            case 'New'
                
                clear sim data calc layer
                sim=default_sim;
                data=default_data;
                calc=default_calc;
                layer=default_layer;
                old_layer=layer;
                project_name='';
                cla(graph_frame,'reset');
                set(graph_frame,'Color',[0.992 0.918 0.796]);
                Stamp_Sim_Panel(1);
                stamp_multilayer(layer);
                
            case 'Save'
                
                old_project_directory=project_directory;
                old_project_name=project_name;
                cd(project_directory);
                if ~project_name
                    project_name='tmp_name';
                end
                save_file=[project_directory project_name];
                if ~save_file
                    messages = sprintf('save cancelled');
                    cd(launch_directory);
                    send_messages(messages);
                    project_directory=old_project_directory;
                    project_name=old_project_name;
                else
                    save(save_file,'sim','layer','data','calc');
                    cd(launch_directory);
                    messages = sprintf('Project saved to %10s',save_file);
                    send_messages(messages);
                end
                cd(launch_directory);
                
            case 'SaveAs'
                
                old_project_directory=project_directory;
                old_project_name=project_name;
                cd(project_directory);
                if ~project_name
                    project_name='tmp_name';
                end
                [project_name,project_directory] =...
                    uiputfile('*.mat','saving project',project_name);
                save_file=[project_directory project_name];
                
                if ~save_file
                    messages = sprintf('save cancelled');
                    cd(launch_directory);
                    send_messages(messages);
                    project_directory=old_project_directory;
                    project_name=old_project_name;
                else
                    save(save_file,'sim','layer','data','calc');
                    cd(launch_directory);
                    messages = sprintf('Project saved to %10s',save_file);
                    send_messages(messages);
                end
                cd(launch_directory);

            case 'Save_As_Layer'
                
                old_project_directory=project_directory;
                old_layer_name=layer_name;
                cd(project_directory);
                if ~layer_name
                    layer_name='tmp_name';
                end
                [layer_name,project_directory] =...
                    uiputfile('*.mat','saving layer',layer_name);
                save_file=[project_directory layer_name];
                
                if ~save_file
                    messages = sprintf('save cancelled');
                    cd(launch_directory);
                    send_messages(messages);
                    project_directory=old_project_directory;
                    layer_name=old_layer_name;
                else
                    save(save_file,'layer');
                    cd(launch_directory);
                    messages = sprintf('Layer saved to %10s',save_file);
                    send_messages(messages);
                end
                cd(launch_directory);
                
            case 'Import_Layer'
                
                if ~project_directory
                    project_directory=launch_directory;
                end
                
                old_project_directory=project_directory;
                cd(project_directory);
                [layer_name,project_directory] =...
                    uigetfile('*.mat','dyna: importing layer');
                if ~project_directory %manage cancelation
                    project_directory=old_project_directory;
                end
                datafile_directory=project_directory;
                cd(launch_directory);
                
                S=load([project_directory,layer_name]);                    
                layer=S.layer;
                stamp_multilayer(layer);
                make_sequence; %
                [calc(ii),data(ii),SF(ii)]=...
                     preallocate(sim(ii),calc(ii),data(ii),layer,0);
                calculate(ii);
                cd(launch_directory);
                
            case 'mag_to_pol'
                %sim(ii).plot_ratio = 1;
                ratio_mag_inverted = ~ratio_mag_inverted;
                calc(ii)=post(calc(ii),sim(ii));
                [calc(ii),data(ii)]=dyna_plot(calc(ii),sim(ii),data(ii),0);
                
            case 'ratio_ref_toggle'
                sim(ii).plot_ratio = ~sim(ii).plot_ratio;
                sim(ii).plot_diff=0;
                Kerr_pi = 0;
                Kerr_sigma = 0;
                calc(ii) = post(calc(ii),sim(ii));
                [calc(ii),data(ii)]=dyna_plot(calc(ii),sim(ii),data(ii),0);
                
            case 'diff_ref_toggle'

                sim(ii).plot_diff = ~sim(ii).plot_diff;
                sim(ii).plot_ratio=0;
                Kerr_pi = 0;
                Kerr_sigma = 0;
                calc(ii) = post(calc(ii),sim(ii));
                [calc(ii),data(ii)]=dyna_plot(calc(ii),sim(ii),data(ii),0);
                
            case'Kerr_pi_toggle'

                Kerr_pi = ~Kerr_pi;
                sim(ii).plot_ratio=0;
                Kerr_sigma=0;
                calc(ii)=post(calc(ii),sim(ii));
                [calc(ii),data(ii)]=dyna_plot(calc(ii),sim(ii),data(ii),0);
                
            case 'Kerr_sigma_toggle'

                Kerr_sigma = ~Kerr_sigma;
                sim(ii).plot_ratio=0;
                Kerr_pi=0;
                calc(ii)=post(calc(ii),sim(ii));
                [calc(ii),data(ii)]=dyna_plot(calc(ii),sim(ii),data(ii),0);
                
            case 'print'
                print
                
            case 'linlog'
                linscale=~linscale;
                [calc(ii),data(ii)]=dyna_plot(calc(ii),sim(ii),data(ii),0);
                
            case 'flip'
                sign=-sign;
                [calc(ii),data(ii)]=dyna_plot(calc(ii),sim(ii),data(ii),0);
                
            case 'data_cursor'
                
                if dcm_state
                    datacursormode on
                    dcm_state=0;
                else
                    datacursormode off
                    dcm_state=1;
                end
                
            case 'th2Q'

                th2Q=1-th2Q;
                [calc(ii),data(ii)] = dyna_plot(calc(ii),sim(ii),data(ii),0);
                
            case 'grid'

                grid
                
            case 'zoom'

                zoom
                
            case 'legend'

                legend('toggle')
                
            case 'results_to_file'
                
                cd(project_directory);
                print_number=print_number+1;
                save_name=sprintf('%s%s', datestr(now,1), '.txt');
                [save_name,Results_Directory]=uiputfile(save_name,'Save Results into File as : ');
                
                if ~Results_Directory % manage cancellation
                    Results_Directory=project_directory;
                end
                
                if ~save_name
                else
                  cd(Results_Directory);
                  % Removed BEGIN 
                  % tmp=calc(ii).adjusted_results;
                  % save(save_name,'tmp','-ASCII');
                  % Removed END
                  % modified by Ingrid Hallsteinsen BEGIN

                  for ii=1:1:length(sim)
                      results_to_save_name=sprintf('%i_%s%i_%s', print_number,'SIM', ii, save_name);
                      figure_to_save_name=sprintf('%i_%s%i_%s',print_number,'SIM', ii, datestr(now,1));
                      layers_to_save_name=sprintf('%i_%s_%s',print_number,'layers', datestr(now,1));
                                      
                      figure(3)
                      if sim(ii).plot_ratio == 0 
                 
                          tmp=calc(ii).adjusted_results';
                          save(results_to_save_name,'tmp','-ASCII');

                          semilogy(tmp(:,1),tmp(:,2));
                          hold on
                          if ~isempty(data(ii).values)
                              semilogy(data(ii).values(1,:)',data(ii).values(2,:)')
                          end                  
                      else
                          tmp=calc(ii).ratio';
                          save(results_to_save_name,'tmp','-ASCII');
                          plot(tmp(:,1),tmp(:,2));
                          hold on
                          if ~isempty(data(ii).values)
                              plot(data(ii).values(1,:)',data(ii).values(2,:)')
                          end
                      end
                      print('-f3','-depsc',figure_to_save_name);
                      close
                      clear tmp

                  end
                                 
                    layertmp = struct2table(layer);
                    writetable(layertmp, layers_to_save_name, 'Delimiter', '\t');
 
                    TString = evalc('disp(layertmp)');
                    TString = strrep(TString,'<strong>','\bf');
                    TString = strrep(TString,'</strong>','\rm');
                    TString = strrep(TString,'_','\_');
                    FixedWidth = get(0,'FixedWidthFontName');

                    figure(3)
                    annotation(gcf, 'Textbox','String',TString,'Interpreter','Tex',...
                    'FontName',FixedWidth,'Units','Normalized');
                    print('-f3','-depsc',layers_to_save_name);
                    close  

                    clear layertmp          
                  % modified by Ingrid Hallsteinsen END 

                end
                cd(launch_directory);
                
            case 'ratio_to_file'
                
                cd(project_directory);
                results_to_save_name=sprintf('%s10_dyna_RATIO_results', datestr(now,1));
                [results_to_save_name,Results_Directory]=uiputfile(results_to_save_name,'Save Results into File as : ');
                if ~Results_Directory % manage cancellation
                    Results_Directory=project_directory;
                end
                cd(Results_Directory);
                if ~results_to_save_name
                else
                   tmp=calc(ii).ratio;
                   save(results_to_save_name,'tmp','-ASCII');
                   clear tmp
                end
                cd(launch_directory);
                
            case 'diff_to_file'
                cd(project_directory);
                results_to_save_name=sprintf('%s10_dyna_DIFF_results', datestr(now,1));
                [results_to_save_name,Results_Directory]=uiputfile(results_to_save_name,'Save Results into File as : ');
                if ~Results_Directory % manage cancellation
                    Results_Directory=project_directory;
                end
                cd(Results_Directory);
                 if ~results_to_save_name
                 else
                     tmp=calc(ii).diff;
                     save(results_to_save_name,'tmp','-ASCII');
                     clear tmp
                 end
                 cd(launch_directory);
                
            case 'iplusiminus_to_file'
                cd(project_directory);
                results_to_save_name=sprintf('%s10_dyna_results', datestr(now,1));
                [results_to_save_name,Results_Directory]=uiputfile(results_to_save_name,'Save Results into File as : ');
                cd(Results_Directory);
                if ~results_to_save_name
                else
                    tmp = [calc(ii).adjusted_results(1,:)',calc(ii).adjusted_results(2,:)',calc(ii).adjusted_results(3,:)];
                    save(results_to_save_name,'tmp','-ASCII');
                    clear tmp
                end
                cd(launch_directory);
                
            case 'fig_to_ps'
                
                cd(project_directory);
                print_number=print_number+1;
                figure_to_print_name=sprintf('%s10_dyna_%i', datestr(now,1), print_number);
                [figure_to_print_name,Results_Directory]=uiputfile(figure_to_print_name,'Save file name');
                f=figure(3);set(f,'Visible','Off');
                h=copyobj(graph_frame,f);
                set(h,'Position',[0.1 0.1 .8 .8]);
                cd(Results_Directory);
                print('-f3','-depsc',figure_to_print_name);
                clear h;
                clear tmp
                cd(launch_directory);
                
            case 'fig_to_jpeg'
                
                cd(project_directory);
                print_number=print_number+1;
                figure_to_print_name=sprintf('%s10_dyna_%i', datestr(now,1), print_number);
                [figure_to_print_name,Results_Directory]=uiputfile(figure_to_print_name,'Print into file');
                f=figure(3);
                set(f,'Visible','On');
                figure_to_print=copyobj(graph_frame,f);
                set(figure_to_print,'Position',[0.1 0.1 .8 .8]);
                cd(Results_Directory);
                print('-f3','-djpeg',figure_to_print_name);
                close(f);
                clear figure_to_print
                clear tmp
                cd(launch_directory);
                
            case 'to_ps'
                
                print_number=print_number+1;
                figure_to_print_name=sprintf('%s10_workspace_%i', datestr(now,1), print_number);
                [figure_to_print_name,Results_Directory]=uiputfile(figure_to_print_name,'Save file name');
                cd(Results_Directory);
                print('-depsc',figure_to_print_name);
                clear tmp
                cd(launch_directory);
                
            case 'to_jpeg'
                
                print_number=print_number+1;
                figure_to_print_name=sprintf('%s10_workspace_%i', datestr(now,1), print_number);
                cd(project_directory);
                [figure_to_print_name,Results_Directory]=uiputfile(figure_to_print_name,'Save file name');
                cd(Results_Directory);
                print('-djpeg',figure_to_print_name);
                clear tmp
                cd(launch_directory);
        end
        
    end

    function callers_Exp_Callback(hObject,~,~)
        ii_sim=get(lst_sim,'Value'); % changing something on sim # ii
        caller = get(hObject,'Tag');
        
        switch caller %2 kinds: redimensionning needed or not needed
            
            case 'LstExpParam' % choosing simulation
                Stamp_Sim_Panel(ii_sim);
                [calc(ii_sim),data(ii_sim),SF(ii_sim)]=preallocate(sim(ii_sim),calc(ii_sim),data(ii_sim),layer,0);
                calc(ii_sim).imprint=fun_imprint(ii_sim); %supposes that calculation was done
                calculate(ii_sim);
                
            case 'Choosing_Function'
                
                switch get(lst_formalism,'Value')
      %         switch (3*(sim(n).formalism-1)+sim(n).typescan)

                    case 1
                        sim(ii_sim).typescan=1;sim(ii_sim).formalism=1;
                        sim(ii_sim).function=@F0_ef;
                    
                    case 2
                        sim(ii_sim).typescan=2;sim(ii_sim).formalism=1;
                        sim(ii_sim).function=@F0_af;

                    case 3
                        sim(ii_sim).typescan=3;sim(ii_sim).formalism=1;
                        sim(ii_sim).function=@F0_qf;

                    case 4
                        sim(ii_sim).typescan=1;sim(ii_sim).formalism=2;
                        sim(ii_sim).function=@F0F1_ef;

                    case 5
                        sim(ii_sim).typescan=2;sim(ii_sim).formalism=2;
                        sim(ii_sim).function=@F0F1_af;

                    case 6
                        sim(ii_sim).typescan=3;sim(ii_sim).formalism=2;
                        sim(ii_sim).function=@F0F1_qf;
                        
                    case 7
                        sim(ii_sim).typescan=1;sim(ii_sim).formalism=3;
                        sim(ii_sim).function=@F0F2_Parratt_ef;
                        
                    case 8
                        sim(ii_sim).typescan=2;sim(ii_sim).formalism=3;
                        sim(ii_sim).function=@F0F2_Parratt_af;
                        
                    case 9
                        sim(ii_sim).typescan=3;sim(ii_sim).formalism=3;
                        sim(ii_sim).function=@F0F2_Parratt_qf;
                        
                end
                [calc(ii_sim),data(ii_sim),SF(ii_sim)]=...
                preallocate(sim(ii_sim),calc(ii_sim),data(ii_sim),layer,0);
                calc(ii_sim).imprint=fun_imprint(ii_sim);
                calculate(ii_sim);
                
            case 'box_energy'
                sim(ii_sim).energy(1) = str2double(get(box_energy1,'String'));
                sim(ii_sim).energy(2) = str2double(get(box_energy2,'String'));
                sim(ii_sim).energy(3) = str2double(get(box_energy_step,'String'));
                [calc(ii_sim),data(ii_sim),SF(ii_sim)]=...
                preallocate(sim(ii_sim),calc(ii_sim),data(ii_sim),layer,0);
                calc(ii_sim).imprint=fun_imprint(ii_sim);
                calculate(ii_sim);
                
            case 'box_theta'
                sim(ii_sim).angle(4) = str2double(get(box_theta_resolution,'String'));
                sim(ii_sim).angle(1) = str2double(get(box_theta1,'String'));
                sim(ii_sim).angle(2) = str2double(get(box_theta2,'String'));
                sim(ii_sim).angle(3) = str2double(get(box_theta_step,'String'));
                [calc(ii_sim),data(ii_sim),SF(ii_sim)]=...
                preallocate(sim(ii_sim),calc(ii_sim),data(ii_sim),layer,0);
                calc(ii_sim).imprint=fun_imprint(ii_sim);
                calculate(ii_sim)
                
            case 'box_Q1'
                sim(ii_sim).Q=str2double(get(box_Q1,'String'));
                [calc(ii_sim),data(ii_sim),SF(ii_sim)]=...
                preallocate(sim(ii_sim),calc(ii_sim),data(ii_sim),layer,0);
                calculate(ii_sim)
                
            case 'Imprint'
                sim(ii_sim).sthickness=str2double(get(box_beam_thickness,'String'));
                sim(ii_sim).slength=str2double(get(box_sample_length,'String'));
                calc(ii_sim).imprint=fun_imprint(ii_sim);
                calc(ii_sim)=post(calc(ii_sim),sim(ii_sim));
                [calc(ii_sim),data(ii_sim)]=dyna_plot(calc(ii_sim),sim(ii_sim),data(ii_sim),0);
                
            case 'Polarization'
                list_called=get(hObject,'String');
                caller=list_called{get(hObject,'Value')};
                
                switch caller
                    
                    case 'unpolarized'
                        sim(ii_sim).pol=[1 1]/sqrt(2);sim(ii_sim).pol_analyzer(1)=1;
                        
                    case 'LINEAR SIGMA'
                        
                        sim(ii_sim).pol=[1 0];sim(ii_sim).pol_analyzer(1)=2;
                        
                    case 'LINEAR PI'
                        
                        sim(ii_sim).pol=[0 1];sim(ii_sim).pol_analyzer(1)=3;
                        
                    case 'CIRCULAR +'
                        
                        sim(ii_sim).pol=-[1 1i]/sqrt(2);
                        sim(ii_sim).pol_analyzer(1)=4;
                        
                    case 'CIRCULAR -'
                        
                        sim(ii_sim).pol=[1 -1i]/sqrt(2);
                        sim(ii_sim).pol_analyzer(1)=5;
                        
                    case 'no outgoing analyzer'
                        sim(ii_sim).pol_out=[1 1];sim(ii_sim).pol_analyzer(2)=1;
                        
                    case 'SIGMA analyzer'
                        sim(ii_sim).pol_out=[1 0];sim(ii_sim).pol_analyzer(2)=2;
                        
                    case 'PI analyzer'
                        sim(ii_sim).pol_out=[0 1];sim(ii_sim).pol_analyzer(2)=3;
                        
                    case 'specified'
                        messages = sprintf('%10s: specified: NOT YET IMPLEMENTED',...
                            datestr(now));
                        send_messages(messages);
                end
                
                calc(ii_sim)=post(calc(ii_sim),sim(ii_sim)); %
                [calc(ii_sim),data(ii_sim)]=dyna_plot(calc(ii_sim),sim(ii_sim),data(ii_sim),0); % for on-the-fly change of the polarizations
        end
        
        Stamp_Sim_Panel(ii_sim)%ii not exported out of case?
    end

    function callers_shift_control(hObject,~)
        ii=get(lst_sim,'Value');
        caller=get(hObject,'Tag');
        switch caller
            
            case 'data_x_shift_min'
                data(ii).adjust.x(1)=str2double(get(hObject,'String'));
                set(data_slider_x_shift,'Min',str2double(get(hObject,'String')));
                
            case 'data_box_x_shift'
                data(ii).adjust.x(2)=str2double(get(hObject,'String'));
                set(data_slider_x_shift,'Value',str2double(get(hObject,'String')));
                
            case 'data_slider_x_shift'
                data(ii).adjust.x(2)=get(hObject,'Value');
                set(data_box_x_shift,'String',num2str(get(hObject,'Value')));
                
            case 'data_x_shift_max'
                data(ii).adjust.x(3)=str2double(get(hObject,'String'));
                set(data_slider_x_shift,'Max',str2double(get(hObject,'String')));
                
            case 'data_box_normalization_min'
                data(ii).adjust.y(1)=str2double(get(hObject,'String'));
                set(data_slider_normalization,'Min',str2double(get(hObject,'String')));
                  
            case 'data_slider_normalization'
                data(ii).adjust.y(2)=get(hObject,'Value');
                set(data_box_normalization,'String',num2str(get(hObject,'Value')));
                
            case 'data_box_normalization'
                data(ii).adjust.y(2)=str2double(get(hObject,'String'));
                set(data_slider_normalization,'Value',str2double(get(hObject,'String')));
                
            case 'data_box_normalization_max'
                data(ii).adjust.y(3)=str2double(get(hObject,'String'));
                set(data_slider_normalization,'Max',str2double(get(hObject,'String')));
                
            case 'data_box_bkg_min'
                data(ii).adjust.bkg(1)=str2double(get(hObject,'String'));
                set(data_slider_bkg,'Min',str2double(get(hObject,'String')));
                
            case 'data_slider_bkg'
                data(ii).adjust.bkg(2)=get(hObject,'Value');
                set(data_box_bkg,'String',num2str(get(hObject,'Value')));
                
            case 'data_box_bkg'
                data(ii).adjust.bkg(2)=str2double(get(hObject,'String'));
                set(data_slider_bkg,'Value',str2double(get(hObject,'String')));
                
            case 'data_box_bkg_max'
                data(ii).adjust.bkg(3)=str2double(get(hObject,'String'));
                set(data_slider_bkg,'Max',str2double(get(hObject,'String')));
                
            case 'calc_x_shift_min'
                calc(ii).adjust.x(1)=str2double(get(hObject,'String'));
                set(calc_slider_x_shift,'Min',str2double(get(hObject,'String')));
                
            case 'calc_box_x_shift'
                calc(ii).adjust.x(2)=str2double(get(hObject,'String'));
                set(calc_slider_x_shift,'Value',str2double(get(hObject,'String')));
                
            case 'calc_slider_x_shift'
                calc(ii).adjust.x(2)=get(hObject,'Value');
                set(calc_box_x_shift,'String',num2str(get(hObject,'Value')));
                
            case 'calc_calc_x_shift_max'
                calc(ii).adjust.x(3)=str2double(get(hObject,'String'));
                set(calc_slider_x_shift,'Max',str2double(get(hObject,'String')));
                
            case 'calc_box_normalization_min'
                calc(ii).adjust.y(1)=str2double(get(hObject,'String'));
                set(calc_slider_normalization,'Min',str2double(get(hObject,'String')));
                
            case 'calc_slider_normalization'
                calc(ii).adjust.y(2)=get(hObject,'Value');
                set(calc_box_normalization,'String',num2str(get(hObject,'Value')));
                
            case 'calc_box_normalization'
                calc(ii).adjust.y(2)=str2double(get(hObject,'String'));
                set(calc_slider_normalization,'Value',str2double(get(hObject,'String')));
                
            case 'calc_box_normalization_max'
                calc(ii).adjust.y(3)=str2double(get(hObject,'String'));
                set(calc_slider_normalization,'Max',str2double(get(hObject,'String')));
                
            case 'calc_box_bkg_min'
                calc(ii).adjust.bkg(1)=str2double(get(hObject,'String'));
                set(calc_slider_bkg,'Min',str2double(get(hObject,'String')));
                
            case 'calc_slider_bkg'
                calc(ii).adjust.bkg(2)=get(hObject,'Value');
                set(calc_box_bkg,'String',num2str(get(hObject,'Value')));
                
            case 'calc_box_bkg'
                calc(ii).adjust.bkg(2)=str2double(get(hObject,'String'));
                set(calc_slider_bkg,'Value',str2double(get(hObject,'String')));
                
            case 'calc_box_bkg_max'
                calc(ii).adjust.bkg(3)=str2double(get(hObject,'String'));
                set(calc_slider_bkg,'Max',str2double(get(hObject,'String')));
                
        end
       
        [calc(ii),data(ii)]=dyna_plot(calc(ii),sim(ii),data(ii),0);
        
    end

    function callers_Multilayer_Callback(hObject,~,~)
        ii_sim=get(lst_sim,'Value');
        layer_number=get(lstbox_control_multilayer,'Value');
        
        caller=get(hObject,'Tag');
        
        switch caller
            
            case 'lstbox_control_multilayer'
                
                fill_multilayer_boxes(layer_number);
                
                
            case 'name'
                
                layer(layer_number).name=get(hObject,'String');
                if make_sequence
                    [calc(ii_sim),data(ii_sim),SF(ii_sim)]=...
                        preallocate(sim(ii_sim),calc(ii_sim),...
                        data(ii_sim),layer,0);
                    calc(ii_sim).imprint=fun_imprint(ii_sim);
                    calculate(ii_sim); % on_the_fly calculation
                
                end
                
            case 'm'
               
                layer(layer_number).m=str2num(get(hObject,'String'));
                if make_sequence
                    [calc(ii_sim),data(ii_sim),SF(ii_sim)]=...
                        preallocate(sim(ii_sim),calc(ii_sim),data(ii_sim),layer,0);
                    calculate(ii_sim); % on_the_fly calculation
                end
                
            case 'Insert'
                
                kk=1; tmp_layer=layer;
                for k=1:length(layer) 
                    layer(kk)=tmp_layer(k);
                    if k == layer_number
                        kk=kk+1;
                        layer(kk)=tmp_layer(k);
                    end
                    kk=kk+1;
                end
                stamp_multilayer(layer);
                
                if make_sequence
                    [calc(ii_sim),data(ii_sim),SF(ii_sim)]=...
                        preallocate(sim(ii_sim),calc(ii_sim),data(ii_sim),layer,0);
                    calculate(ii_sim);% on_the_fly calculation
                end
                
                clear tmp_layer
                
            case 'Delete'
                
                layer(layer_number)=[];
                set(lstbox_control_multilayer,'Value',1);
                stamp_multilayer(layer);
                if make_sequence
                    [calc(ii_sim),data(ii_sim),SF(ii_sim)]=...
                        preallocate(sim(ii_sim),calc(ii_sim),data(ii_sim),layer,0);
                    calculate(ii_sim);% on_the_fly calculation
                end
                
            otherwise
                
                parameter_name=get(hObject,'Tag');
                
                if strcmp(get(hObject,'Style'),'slider')
                    parameter_value=num2str(get(hObject,'Value'));
                else
                    parameter_value=get(hObject,'String');
                end
                
                evalc(strcat('layer(layer_number).',...
                    parameter_name,'=',parameter_value));
                fill_multilayer_boxes(layer_number); %
                calculate(ii_sim) %TODO should not be calculating if only a limit is changed
        end
        
        stamp_multilayer(layer);
        old_layer=layer;
        
    end

    function fill_multilayer_boxes(llayer)
        
        set(box_set_name,'String',layer(llayer).name);
        set(box_set_multiplicity,'String',layer(llayer).m);
        set(box_set_density_min,'String',layer(llayer).density(1));
        set(box_set_density,'String',layer(llayer).density(2));
        set(box_set_density_max,'String',layer(llayer).density(3));
        set(box_set_thickness_min,'String',layer(llayer).thickness(1));
        set(box_set_thickness,'String',layer(llayer).thickness(2));
        set(box_set_thickness_max,'String',layer(llayer).thickness(3));
        set(box_set_roughness_min,'String',layer(llayer).roughness(1));
        set(box_set_roughness,'String',layer(llayer).roughness(2));
        set(box_set_roughness_max,'String',layer(llayer).roughness(3));
        set(box_set_MMS_min,'String',layer(llayer).MMS(1));
        set(box_set_MMS,'String',layer(llayer).MMS(2));
        set(box_set_MMS_max,'String',layer(llayer).MMS(3));
        set(box_set_AS_min,'String',layer(llayer).AS(1));
        set(box_set_AS,'String',layer(llayer).AS(2));
        set(box_set_AS_max,'String',layer(llayer).AS(3));
        set(box_set_phi_min,'String',layer(llayer).phi(1));
        set(box_set_phi,'String',layer(llayer).phi(2));
        set(box_set_phi_max,'String',layer(llayer).phi(3));
        set(box_set_gamma_min,'String',layer(llayer).gamma(1));
        set(box_set_gamma,'String',layer(llayer).gamma(2));
        set(box_set_gamma_max,'String',layer(llayer).gamma(3));
        set(slider_density,'Min',layer(llayer).density(1));
        set(slider_density,'Value',layer(llayer).density(2));
        set(slider_density,'Max',layer(llayer).density(3));
        set(slider_thickness,'Min',layer(llayer).thickness(1));
        set(slider_thickness,'Value',layer(llayer).thickness(2));
        set(slider_thickness,'Max',layer(llayer).thickness(3));
        set(slider_roughness,'Min',layer(llayer).roughness(1));
        set(slider_roughness,'Value',layer(llayer).roughness(2));
        set(slider_roughness,'Max',layer(llayer).roughness(3));
        set(slider_MMS,'Min',layer(llayer).MMS(1));
        set(slider_MMS,'Value',layer(llayer).MMS(2));
        set(slider_MMS,'Max',layer(llayer).MMS(3));
        set(slider_AS,'Min',layer(llayer).AS(1));
        set(slider_AS,'Value',layer(llayer).AS(2));
        set(slider_AS,'Max',layer(llayer).AS(3));
        set(slider_phi,'Min',layer(llayer).phi(1));
        set(slider_phi,'Value',layer(llayer).phi(2));
        set(slider_phi,'Max',layer(llayer).phi(3));
        set(slider_gamma,'Min',layer(llayer).gamma(1));
        set(slider_gamma,'Value',layer(llayer).gamma(2));
        set(slider_gamma,'Max',layer(llayer).gamma(3));
    end

    function callers_Optim_Callback(hObject,~,~)
      
        caller=get(hObject,'Tag');
        ii=get(lst_sim,'Value');
        
        switch caller
            % one manages a list of parameters to fit 'list_to_stamp'
            case 'Optim_method'
                
                get(lst_optimization_method,'Value');
                
                
            case 'Add_Param'
                
                chosen_layer=get(lst_layer,'Value');
                chosen_param=get(lst_param,'Value');
                
                if to_fit
                    tmp='f';
                    chosen_layer_to_constrain_with=chosen_layer;
                    A='*';
                    B='*';
                else
                    tmp='c';
                    chosen_layer_to_constrain_with=get(lst_layer_to_constrain_with,'Value');
                    A=get(edtA,'String');
                    B=get(edtB,'String');
                end
                
                nb_param=nb_param+1;
                list_to_stamp(nb_param)=...
                    {sprintf('%i %8s %10s %5s %1s %i %s %s',...
                    chosen_layer,...
                    layer(chosen_layer).name,...
                    param_fittable{chosen_param},...
                    num2str(layer(chosen_layer).(param_fittable{chosen_param})(2)),...
                    tmp,...
                    chosen_layer_to_constrain_with,...
                    A,...
                    B...
                    )};
                set(lbxParam_to_optim,'String',list_to_stamp);
                clear tmp;
                
            case  'Master'
                
                set(lst_layer_to_constrain_with,'Enable','off');
                set(edtA,'Enable','off');
                set(edtB,'Enable','off');
                to_fit=1;
                
            case 'Constrain'
                set(lst_layer_to_constrain_with,'Enable','on');
                set(edtA,'Enable','on');
                set(edtB,'Enable','on');
                to_fit=0;
                
            case 'Delete_Param'
                
                jj=1;
                if length(list_to_stamp)==1
                    list_to_stamp={sprintf('')};
                    set(lbxParam_to_optim,'Value',1);
                    set(lbxParam_to_optim,'String',list_to_stamp);
                else
                    for ii=1:length(list_to_stamp)
                        if ii ~= line_to_delete
                            list_to_stamp_tmp(jj)=list_to_stamp(ii);
                            jj=jj+1;
                        end
                    end
                    list_to_stamp=list_to_stamp_tmp;
                    set(lbxParam_to_optim,'Value',1);
                    set(lbxParam_to_optim,'String',list_to_stamp);
                end
                nb_param=nb_param-1;
                if nb_param<0 % in case delete button is hit while nothing to del
                    nb_param=0;
                end
                clear jj
                
            case 'lbxParam_to_optim'
                
                set(btnDelete,'Enable','on');
                line_to_delete=get(lbxParam_to_optim,'Value');
                set(btnResetParam,'Enable','on');
            
            case 'edtIntervall'
                data(ii).intervall(1)=str2double(get(edtxmin,'String'));
                data(ii).intervall(2)=str2double(get(edtxmax,'String'));
                
                
            case 'Accept'
                
                stamp_multilayer(layer);
                
            case 'Reset_Param'
                % determine layer and param to reset and read attributes
                ii=get(lbxParam_to_optim,'Value');
                tmp=textscan(list_to_stamp{ii},'%s',8);
                chosen_layer= str2double(tmp{1}{1});
                % set layer to the pre-optimization value
                layer(chosen_layer).(tmp{1}{3})(2)=...
                    old_layer(chosen_layer).(tmp{1}{3})(2);
                % update list_to_stamp
                list_to_stamp(ii)=...
                    {sprintf('%s %s %s %f %s %s %s %s',tmp{1}{1},...
                    tmp{1}{2},tmp{1}{3},layer(chosen_layer).(tmp{1}{3})(2),...
                    tmp{1}{5},tmp{1}{6},tmp{1}{7},tmp{1}{8})};
                % print list_to_stamp for user
                set(lbxParam_to_optim,'String',list_to_stamp);
                
            case 'Reset_All'
                % see Reset_Param
                layer=old_layer;
                
                for ii=1:length(list_to_stamp)
                    tmp=textscan(list_to_stamp{ii},'%s',8);
                    chosen_layer= str2double(tmp{1}{1});
                    list_to_stamp(ii)=...
                        {sprintf('%s %s %s %f %s %s %s %s',tmp{1}{1},...
                        tmp{1}{2},tmp{1}{3},layer(chosen_layer).(tmp{1}{3})(2),...
                        tmp{1}{5},tmp{1}{6},tmp{1}{7},tmp{1}{8})};
                end
                
                set(lbxParam_to_optim,'String',list_to_stamp);
                
            case 'Start_Stop'
                % this function first check whether the users did not ask
                % to stop the procedure in case it creates a list of
                % parameters to refine, with the corresponding layer number
                % its name, the parameter to refine, and the initial value
                % of the parameter. It also define the old_layer.
                
                if (strcmp(get(btnStartStop,'String'),'Start'))
                    set(btnStartStop,'String','Stop');
                    set(btnStartStop,'Value',1);
                    %
                    old_layer=layer; %to be used when "reset" is called
                    list_param_to_optimize=[];
                    list_param_to_constrain=[];
                    jj=1;kk=1;
                    for ii=1:length(list_to_stamp)
                        tmp(ii)=textscan(list_to_stamp{ii},'%s',8);
                        
                        if tmp{ii}{5}=='c'
                            list_param_to_constrain(jj).layer=tmp{ii}{1};
                            list_param_to_constrain(jj).name=tmp{ii}{2};
                            list_param_to_constrain(jj).param=tmp{ii}{3};
                            list_param_to_constrain(jj).layer_master=tmp{ii}{6};
                            list_param_to_constrain(jj).A=tmp{ii}{7};
                            list_param_to_constrain(jj).B=tmp{ii}{8};
                            jj=jj+1;
                        else
                            list_param_to_optimize(kk).layer=tmp{ii}{1};
                            list_param_to_optimize(kk).name=tmp{ii}{2};
                            list_param_to_optimize(kk).param=tmp{ii}{3};
                            list_param_to_optimize(kk).value=tmp{ii}{4};
                            kk=kk+1;
                        end
                    end
                    clear tmp
                    for ii=1:length(sim)
                        [calc(ii),data(ii),SF(ii)]=...
                            preallocate(sim(ii),calc(ii),data(ii),layer,1);
                        calc(ii).imprint=fun_imprint(ii);
                    end
                    
                    % TODO: set a sublist of sims to use
                    layer=optimize(sim,data,calc,layer,SF,list_param_to_optimize,list_param_to_constrain);
                    
                    % required so as to use shift control directly
                    % one can however remove each plotting to only leave
                    % one of them
                    for ii=1:length(sim)
                        Stamp_Sim_Panel(ii);
                        [calc(ii),data(ii),SF(ii)]=preallocate(sim(ii),calc(ii),data(ii),layer,0);
                        calc(ii).imprint=fun_imprint(ii);
                        calculate(ii);
                        calc(ii)=post(calc(ii),sim(ii));
                        [calc(ii),data(ii)]=dyna_plot(calc(ii),sim(ii),data(ii),0);
                        pause(2);
                    end
                else
                    set(btnStartStop,'String','Start');
                    set(btnStartStop,'Value',0);
                end
        end
    end

    function Mag_Button_Callback(hObject,~)
        if (get(set_all_menu,'Value')-1)
            layer_number=1:length(layer);
        else
            layer_number=get(lstbox_control_multilayer,'Value');
        end
        s=get(hObject,'Tag');
        for ii=layer_number %
        if strcmp(s,'phi(2)')
            layer(ii).phi(2)=str2double(get(hObject,'String'));
        end
        if strcmp(s,'gamma(2)')
            layer(ii).gamma(2)=str2double(get(hObject,'String'));  
        end
        if strcmp(s,'POL')
           layer(ii).phi(2)=0;
           layer(ii).gamma(2)=0;
        end
        if strcmp(s,'LONG')
           layer(ii).phi(2)=90;
           layer(ii).gamma(2)=90;
        end
        if strcmp(s,'PERP')
           layer(ii).phi(2)=90;
           layer(ii).gamma(2)=0;
        end
        fill_multilayer_boxes(ii)
        end
        stamp_multilayer(layer)
        calculate(get(lst_sim,'Value'))
    end

%%%%%%%%%%%%%%%%%%%%%%%%
%%%                  %%%
%%%    FUNCTIONS     %%%
%%%                  %%%
%%%%%%%%%%%%%%%%%%%%%%%%

    function Stamp_Sim_Panel(n)
        
        if sim(n).typescan==1 % Fix Energy, setting Angle1 Anlge2 AngleStep
            linscale = 0;
            enable_angle1='on';enable_angle2='on';
            enable_energy='off';enable_Q='off';
        end
        
        if sim(n).typescan==2 % Fix Angle, setting E1 E2 EStep
            linscale = 1;
            enable_angle1='on';enable_angle2='off';
            enable_energy='on';enable_Q='off';
        end
        
        if sim(n).typescan==3 % Fix Q, setting E1 E2 EStep
            linscale = 1;
            enable_angle1='off';enable_angle2='off';
            enable_energy='on';enable_Q='on';
        end
       
        set(lst_sim,'String', strcat({sim.number_string},' ',{data.name}),'Value',n);
        set(lst_formalism,'Value',(3*(sim(n).formalism-1)+sim(n).typescan));
        set(box_energy1,'String', num2str(sim(n).energy(1)));
        set(box_energy2,'String', num2str(sim(n).energy(2)),'enable',enable_energy);
        set(box_energy_step,'String',num2str(sim(n).energy(3)),'enable', enable_energy);
        set(box_theta1,'enable',enable_angle1,'String',num2str(sim(n).angle(1)));
        set(box_theta2,'enable',enable_angle2,'String',num2str(sim(n).angle(2)));
        set(box_theta_step,'enable',enable_angle2,'String',num2str(sim(n).angle(3)));
        set(box_theta_resolution,'enable',enable_angle2,'String',num2str(sim(n).angle(4)));
        set(box_Q1,'enable',enable_Q,'String',num2str(sim(n).Q));
        set(box_beam_thickness,'String',num2str(sim(n).sthickness));
        set(box_sample_length,'String',num2str(sim(n).slength));
        set(lst_polarization,'Value',sim(n).pol_analyzer(1));
        set(lst_analyzer,'Value',sim(n).pol_analyzer(2));
       
        set(data_box_normalization_min,'String',num2str(data(n).adjust.y(1)))
        set(data_box_normalization,'String',num2str(data(n).adjust.y(2)))
        set(data_box_normalization_max,'String',num2str(data(n).adjust.y(3)))
        set(data_slider_normalization,'Min',data(n).adjust.y(1));
        set(data_slider_normalization,'Value',data(n).adjust.y(2));
        set(data_slider_normalization,'Max',data(n).adjust.y(3));

        set(data_box_bkg_min,'String',num2str(data(n).adjust.bkg(1)));
        set(data_box_bkg,'String',num2str(data(n).adjust.bkg(2)));
        set(data_box_bkg_max,'String',num2str(data(n).adjust.bkg(3)));
        set(data_slider_bkg,'Min',data(n).adjust.bkg(1));
        set(data_slider_bkg,'Value',data(n).adjust.bkg(2));
        set(data_slider_bkg,'Max',data(n).adjust.bkg(3));
        
        set(data_box_x_shift_min,'String',num2str(data(n).adjust.x(1)));
        set(data_box_x_shift,'String',num2str(data(n).adjust.x(2)));
        set(data_box_x_shift_max,'String',num2str(data(n).adjust.x(3)));
        set(data_slider_x_shift,'Min',data(n).adjust.x(1));
        set(data_slider_x_shift,'Value',data(n).adjust.x(2));
        set(data_slider_x_shift,'Max',data(n).adjust.x(3));
        
        set(calc_box_normalization_min,'String',num2str(calc(n).adjust.y(1)))
        set(calc_box_normalization,'String',num2str(calc(n).adjust.y(2)))
        set(calc_box_normalization_max,'String',num2str(calc(n).adjust.y(3)))
        set(calc_slider_normalization,'Min',calc(n).adjust.y(1));
        set(calc_slider_normalization,'Value',calc(n).adjust.y(2));
        set(calc_slider_normalization,'Max',calc(n).adjust.y(3));
        
        set(calc_box_bkg_min,'String',num2str(calc(n).adjust.bkg(1)));
        set(calc_box_bkg,'String',num2str(calc(n).adjust.bkg(2)));
        set(calc_box_bkg_max,'String',num2str(calc(n).adjust.bkg(3)));
        set(calc_slider_bkg,'Min',calc(n).adjust.bkg(1));
        set(calc_slider_bkg,'Value',calc(n).adjust.bkg(2));
        set(calc_slider_bkg,'Max',calc(n).adjust.bkg(3));
        
        set(calc_slider_x_shift,'Min',calc(n).adjust.x(1));
        set(calc_slider_x_shift,'Value',calc(n).adjust.x(2));
        set(calc_slider_x_shift,'Max',calc(n).adjust.x(3));
        set(calc_box_x_shift_min,'String',num2str(calc(n).adjust.x(1)));
        set(calc_box_x_shift,'String',num2str(calc(n).adjust.x(2)));
        set(calc_box_x_shift_max,'String',num2str(calc(n).adjust.x(3)));

    end

    function stamp_multilayer(llayer)
        
        tmp=cell(1,length(llayer));
        
        % creates the line for each layer ...
        for k=1:length(llayer)
            input_line=sprintf(...
                '  %i |  %8s |  %i | %4.2f %6.3f %4.2f | %6.1f %6.1f %6.1f | %3.1f %3.1f %3.1f | %4.2f %4.2f %4.2f | %4.2f %4.2f %4.2f |  %2i %2i %2i |  %2i %2i %2i',...
                k,llayer(k).name,llayer(k).m,llayer(k).density(1),llayer(k).density(2),...
                llayer(k).density(3),llayer(k).thickness(1),llayer(k).thickness(2),...
                llayer(k).thickness(3),llayer(k).roughness(1),...
                llayer(k).roughness(2),llayer(k).roughness(3),llayer(k).MMS(1),...
                llayer(k).MMS(2),llayer(k).MMS(3),llayer(k).AS(1),llayer(k).AS(2),...
                llayer(k).AS(3),llayer(k).phi(1),layer(k).phi(2),layer(k).phi(3),...
                llayer(k).gamma(1),llayer(k).gamma(2),llayer(k).gamma(3));
            tmp(k)={input_line};
        end
 
        % ... and writes the lines in the listbox
        set(lstbox_control_multilayer,'String',tmp);
        
        % update layers names in optimization window
        set(lst_layer,'String',{layer(:).name});
        set(lst_layer_to_constrain_with,'String',{layer(:).name});
        
    end

    function send_messages(messages)
        messages = sprintf('%10s: %s \n', datestr(now),messages);
        set(send_messages_box,'String',messages);
        fprintf(log_file_id,messages);
    end

    function sequence_ready=make_sequence(~,~)
        % establishes the sequence of layers in a multilayer from the sequence of
        % names and the multiplicities associated with
        
        multiplicities = [];
        for ii=1:length(layer)
            multiplicities = [multiplicities layer(ii).m];
        end
        
        sequence=[1];subsequence=[];multisubsequence=[];
        
        ii=1;
        m=0; % multiplicity?
        
        while(ii<length(layer)+1)
            subsequence=ii+1; % +1 because vaccuum is set to 1
            while (ii<length(layer))&&((multiplicities(ii+1)==multiplicities(ii)));
                m=1; % there is a sequence to repeat
                subsequence=[subsequence ii+2]; % building the sequence to repeat, ii+2 because vaccuum is set to 1
                ii=ii+1; % next layer to test
            end
            
            if m==1 % there is a sequence to repeat
                for jj=1:multiplicities(ii)
                    multisubsequence = [multisubsequence subsequence]; % building the sequence
                end
            else
                multisubsequence = [subsequence];
            end
            sequence = [sequence multisubsequence]; % progressing on the whole sequence
            subsequence=[];  multisubsequence=[]; m=0;
            ii=ii+1;
        end
        
        sequence_name='vacuum ';
        
        if sum(multiplicities(:))==numel(sequence)-1
            for ii=1:sum(multiplicities(:))
                sequence_name = [sequence_name sprintf('%s ',layer(sequence(ii+1)-1).name)];
            end
            
            messages = sprintf('%10s: Multilayer sequence is:\n %s\n', datestr(now), sequence_name);
            send_messages(messages);
            sequence_ready=1;
            clear subsequence multisubsequence messages
        else
            messages = sprintf('%10s: Multilayer is not ready', datestr(now));
            send_messages(messages);
            sequence_ready=0;          
        end
        
    end

    function l_imprint=fun_imprint(n)
        
        imprint_ratio = sim(n).slength/sim(n).sthickness;
        
        if sim(n).typescan==1
            l_imprint=  min(sin(calc(n).reflectivity(1,:))*imprint_ratio,1);
        else
            l_imprint=  min(sind(sim(n).angle(1))*imprint_ratio,1);
        end
    end

    function help
        % help on help
        help_location=sprintf('%s/Help/help_files/parent.html',pwd);
        web (help_location, '-helpbrowser')
    end

    function layer = optimize(sim,data,calc,layer,SF,list_param_to_optimize,list_param_to_constrain)
        
       % SETUP FIT
        optimization_options=optimset('Display','on', ...
            'TolFun',str2double(get(edtTolFun,'String')),'TolX',...
            str2double(get(edtTolX,'String')), ...
            'MaxFunEvals',str2double(get(edtMaxFunEvals,'String')),...
            'MaxIter',str2double(get(edtMaxIter,'String')), ...
            'OutputFcn',@myoutput);
        
          p=zeros(1,length(list_param_to_optimize));
        
        LB=[];UB=[];next_lowest_bound=0;next_uppest_bound=0;
        
        for l_ii=1:length(list_param_to_optimize) %LIMITS
            p(l_ii)=str2double(list_param_to_optimize(l_ii).value);
            evalc(strcat('next_lowest_bound = layer(str2num(list_param_to_optimize(l_ii).layer)).',list_param_to_optimize(l_ii).param,'(1)'));
            evalc(strcat('next_uppest_bound = layer(str2num(list_param_to_optimize(l_ii).layer)).',list_param_to_optimize(l_ii).param,'(3)'));
            LB = [LB next_lowest_bound];
            UB = [UB next_uppest_bound];
        end
        
        %% Defining error functions
        
        function err=err1(calc,data) % energy scan
            intervall=((data.optim_values(1,:)>data.intervall(1)) & (data.optim_values(1,:)<data.intervall(2)));
            err=sum ( intervall(1,:).*...
                ((calc.adjusted_results(2,:))-data.optim_values(2,:)).^2./...
                (data.optim_values(2,:).^2+1e-10));
        end
        
        function err=err2(calc,data) % reflectivity
            intervall=((data.optim_values(1,:)>data.intervall(1)) & (data.optim_values(1,:)<data.intervall(2)));
            err=sum ( intervall(1,:).*...
                ( (log10(calc.adjusted_results(2,:)+1e-20)-log10(data.optim_values(2,:))).^2));
        end
        
        function err=err3(calc,data) % RATIO
            intervall=((data.optim_values(1,:)>data.intervall(1)) & (data.optim_values(1,:)<data.intervall(2)));
            err=sum(intervall(1,:).*(calc.ratio(2,:)-data.optim_values(2,:)).^2);
        end
        
        function err=err4(calc,data) % Diff
            intervall=((data.optim_values(1,:)>data.intervall(1)) & (data.optim_values(1,:)<data.intervall(2)));
            err=sum(intervall(1,:).*(calc.diff(2,:)-data.optim_values(2,:)).^2);
        end   
             
        %% RUN FIT
        [~,~,~,output] = fminsearchbnd(@error_function,p,LB,UB,optimization_options);
        
        %% TRY TO MAKE THIS FUNCTION RUN FASTER
        function err=error_function(parameter)
            % the error function is calculated using adjusted_results
            
            out_param=parameter; % for list_to_stamp update at each iter
            % set layer(n).param to value chosen by optimization procedure
            for kk=1:length(parameter)
                layer(str2double(list_param_to_optimize(kk).layer)).(list_param_to_optimize(kk).param)(2)=parameter(kk);
            end
            % set constrained layer(n).param
            for kk=1:length(list_param_to_constrain)
                layer(str2double(list_param_to_constrain(kk).layer))...
                    .(list_param_to_constrain(kk).param)(2)=...
                    str2double(list_param_to_constrain(kk).A)...
                    *layer(str2double(list_param_to_constrain(kk).layer_master))...
                    .(list_param_to_constrain(kk).param)(2)...
                    +str2double(list_param_to_constrain(kk).B);
            end
            
            % CALCULATE
            err=0;
            for jj =1:length(sim)           
                calc(jj)=sim(jj).function(calc(jj),sim(jj),layer,SF(jj),sequence);
                calc(jj)=post(calc(jj),sim(jj)); %  calculates adjusted_results (including conv.) from 'reflectivity'
                calc(jj)=dyna_plot(calc(jj),sim(jj),data(jj),jj);
                
                % CALCULATE ERROR
                if sim(jj).plot_ratio
                    calculate_err = @err3;
                elseif sim(jj).plot_diff
                    calculate_err= @err4;
                else
                    if sim(jj).typescan == 1 % Which error functions to use
                   calculate_err = @err2;
                    else
                   calculate_err = @err1;
                    end
                end
                err=err+calculate_err(calc(jj),data(jj));
            end
        end
        
        %% OUTPUT RESULTS and MESSAGES
        function stop=myoutput(~,optimValues,state)
            global ii_iter;
            switch state
                case 'init'
                    stop=false;ii_iter=0;
                case 'iter'   % Make updates to plot or guis as needed.
                    if optimValues.iteration>ii_iter*2
                        ii_iter=ii_iter+1;
                        info=sprintf('updated every 2 iterations\nIteration           %i\nNumber of function evaluation %i \nBest function value %f',...
                            optimValues.iteration,optimValues.funccount,optimValues.fval);
                        final_value=optimValues.fval;
                        
                        set(box_optimization_output,'String',info);
                        
                        for jj=1:length(list_param_to_optimize)
                            list_to_stamp(jj)={sprintf('%s %6s %5s %4.3f f %s %s %s',...
                                list_param_to_optimize(jj).layer,...
                                list_param_to_optimize(jj).name,...
                                list_param_to_optimize(jj).param,...
                                out_param(jj),....
                                list_param_to_optimize(jj).layer,...
                                '*','*')};
                        end
                        for jj=length(list_param_to_optimize)+1:length(list_param_to_optimize)+length(list_param_to_constrain)
                            ii=jj-length(list_param_to_optimize);
                            A=str2double(list_param_to_constrain(ii).A);
                            B=str2double(list_param_to_constrain(ii).B);
                            list_to_stamp(jj)={sprintf('%s %6s %5s %4.3f c %i %s %s',...
                                list_param_to_constrain(ii).layer,...
                                list_param_to_constrain(ii).name,...
                                list_param_to_constrain(ii).param,...
                                A*layer(str2double(list_param_to_constrain(ii).layer_master)).(list_param_to_constrain(ii).param)(2)+B,...
                                str2double(list_param_to_constrain(ii).layer_master),...
                                list_param_to_constrain(ii).A,...
                                list_param_to_constrain(ii).B...
                                )};
                        end
                        
                        set(lbxParam_to_optim,'String',list_to_stamp,'FontSize',11);
                        drawnow % take a lot of time
                    end
                    
                    if (get(btnStartStop,'Value')==1)
                        stop=false;
                    else
                        stop=true;
                    end
                    
                case 'interrupt'
                    stop=true;
                case 'stop'
                    stop=true;
                case 'done'
                    stop=true;
                otherwise
                    stop=true;
            end
            
        end
        
        message=sprintf(' %s \n\n %s \n\n Number of function evaluation: %i \n\n Number of Iterations: %i \n\n final function value: %f',...
            datestr(now),output.algorithm,output.funcCount,output.iterations,final_value);
        
        set(btnAccept,'Enable','on');set(btnReset,'Enable','on');
        set(btnStartStop,'String','Start');set(btnStartStop,'Value',1);
        set(box_optimization_output,'String',message);
        
    end

    function [lcalc,ldata,lSF]= preallocate(lsim,lcalc,ldata,layer,optim_flag)
    
  % local variables: x_points (user points) x_calc_points (program points)
  %% f f2 m ee (scattering factors)
  
        if optim_flag % x abscisse from data
            
            if lsim.typescan==1
                jj=1;
                
                ldata.optim_values=[];% CHECK & TODO
                
                for ii= 1:length(ldata.post_values(1,:))
                    if (ldata.post_values(1,ii) >= lsim.angle(4)) && (ldata.post_values(1,ii) <= 90-lsim.angle(4))
                        ldata.optim_values(:,jj) = ldata.post_values(:,ii);
                        jj=jj+1;
                    end
                end
                x_points = ldata.optim_values;
                
                if lsim.angle(4) > 0 % IF RESOLUTION
                    x_calc_points =pi/180*...
                        [ldata.optim_values(1,:)-lsim.angle(4)...
                        ldata.optim_values(1,:) ldata.optim_values(1,:)+lsim.angle(4)];
                else
                    x_calc_points = pi /180* ldata.optim_values(1,:);
                end
                
            else % energy scan
                
                x_points=ldata.post_values(1,:);
                x_calc_points=x_points;
                ldata.optim_values=ldata.post_values;
                
            end
            
        else % x abscisse from user
            
            if lsim.typescan==1
                %in degrees used to plot
                x_points = (max(lsim.angle(4),lsim.angle(1)):lsim.angle(3):min(90-lsim.angle(4),lsim.angle(2)));
                
                if lsim.angle(4) > 0
                    %in rad used to calc (consider changing to degrees)
                    x_calc_points = [x_points-lsim.angle(4) x_points x_points+lsim.angle(4)]/180*pi;
                    
                else
                    
                    x_calc_points =  x_points/180*pi;% x_calc_point in radians
                    
                end
                
            else
                
                x_points=lsim.energy(1):lsim.energy(3):lsim.energy(2);
                x_calc_points=x_points; % same calc and user points
                
            end
            
        end
        
        % INITIALIZES THE ARRAYS FILLED BY RESULTS CALCULATION FUNCTIONS
        
        lcalc.M_final=zeros(2,2,length(x_calc_points));
        
        if lsim.formalism == 2
            lcalc.M_final_phi=zeros(2,2,length(x_calc_points));
            lcalc.reflectivity=[x_calc_points;zeros(1,length(x_calc_points));...
                zeros(1,length(x_calc_points))];%in radians or eV
            lcalc.post_reflectivity = [x_points;zeros(1,length(x_points));...
                zeros(1,length(x_points))];%in degrees or eV
            lcalc.adjusted_results = [x_points;zeros(1,length(x_points));...
                zeros(1,length(x_points))];%in degrees or eV
        else
            lcalc.R = zeros(2,length(x_calc_points),length(sequence));
            lcalc.exp_phase = zeros(2,length(x_calc_points),length(layer)+1);
            lcalc.Q = zeros(2,length(x_calc_points),length(layer)+1);
            
            lcalc.reflectivity=[x_calc_points;zeros(1,length(x_calc_points))];
            lcalc.post_reflectivity = [x_points;zeros(1,length(x_points))];
            lcalc.adjusted_results = [x_points;zeros(1,length(x_points))];
        end
        
        % CALCULATES SCATTERING FACTORS
        if lsim.typescan==1 % angle scan
            ee=lsim.energy(1);
        else %
            ee=x_points;
        end
        lSF.cf=zeros(length(layer),length(ee));
        lSF.mf=zeros(length(layer),length(ee));
        lSF.cf2=zeros(length(layer),length(ee));
          
        % TODO loading a huge file may take time and fills the memory
        % TODO n different layers made of a same material (but different thickness,mag,...) are still loaded n times

        for jj=1:length(layer)
            f_file=sprintf('../Tables/cf/%s.cf',layer(jj).name);
            f=load(f_file);
            lSF.cf(jj+1,:)=interp1(f(:,1),f(:,2),ee(:))-1i*interp1(f(:,1),f(:,3),ee(:));
            
            f_file=sprintf('../Tables/mf/%s.mf',layer(jj).name);
            f=load(f_file);
            lSF.mf(jj+1,:)=interp1(f(:,1),f(:,2),ee(:))-1i*interp1(f(:,1),f(:,3),ee(:));
            
            f_file=sprintf('../Tables/cf2/%s.cf2',layer(jj).name);
            f=load(f_file);
            lSF.cf2(jj+1,:)=interp1(f(:,1),f(:,2),ee(:))-1i*interp1(f(:,1),f(:,3),ee(:));          
        end
        calculation_done_flag=0;
        cd(launch_directory);
    end

    function lcalc=post(lcalc,lsim)
        % post: this subroutine is also used during
        % the optimization procedure
        % Applies initial polarization conditions, and analyzer
        % Convoluates for angular resolution
        
        if lsim.formalism==2
            
            if ratio_mag_inverted %ratio_mag_inverted=1 is H inverted
                % lsim.pol(1) is incident photon sigma component

                % lcalc.M_final(1,1,:) is sig-sig channel
                % lcalc.M_final(1,2,:) is sig-pi channel
		
		% outgoing sigma channel
                pol_state_M(1,:) = lcalc.M_final(1,1,:) * lsim.pol(1) +...
                    lcalc.M_final(1,2,:) * lsim.pol(2);

		% outgoing pi channel
                pol_state_M(2,:) = lcalc.M_final(2,1,:) * lsim.pol(1) +...
                    lcalc.M_final(2,2,:) * lsim.pol(2);

                % lcalc.reflectivity(2,:) is +H

                lcalc.reflectivity(2,:) = abs(lsim.pol_out(1) *pol_state_M(1,:)) .^2 +...
                    abs(lsim.pol_out(2)*pol_state_M(2,:)) .^2;
                pol_state_M_phi(1,:) = lcalc.M_final_phi(1,1,:) * lsim.pol(1) +...
                    lcalc.M_final_phi(1,2,:) * lsim.pol(2);
                pol_state_M_phi(2,:) = lcalc.M_final_phi(2,1,:) * lsim.pol(1) +...
                    lcalc.M_final_phi(2,2,:) * lsim.pol(2);

                % lcalc.reflectivity(3,:) is -H
    
            lcalc.reflectivity(3,:) = abs(lsim.pol_out(1)*pol_state_M_phi(1,:)).^2 +...
                    abs(lsim.pol_out(2)*pol_state_M_phi(2,:)).^2;
            else
                
                pol_state_M(1,:) = -(lcalc.M_final(1,1,:) + lcalc.M_final(1,2,:) *1i)/sqrt(2);
                pol_state_M(2,:) = -(lcalc.M_final(2,1,:) + lcalc.M_final(2,2,:) *1i)/sqrt(2);

                % lcalc.reflectivity(2,:) is C+

                lcalc.reflectivity(2,:) = abs(lsim.pol_out(1) *pol_state_M(1,:)) .^2 +...
                    abs(lsim.pol_out(2)*pol_state_M(2,:)) .^2;
                pol_state_M(1,:) = (lcalc.M_final(1,1,:) - lcalc.M_final(1,2,:) *1i)/sqrt(2);
                pol_state_M(2,:) = (lcalc.M_final(2,1,:) - lcalc.M_final(2,2,:) *1i)/sqrt(2);

                % lcalc.reflectivity(3,:) is C-

                lcalc.reflectivity(3,:) = abs(lsim.pol_out(1)*pol_state_M(1,:)).^2 +...
                    abs(lsim.pol_out(2) *pol_state_M(2,:)).^2;

            end
            
            if  Kerr_sigma

                lcalc.reflectivity(2,:) = real(lcalc.M_final(1,2,:)./lcalc.M_final(1,1,:));% Kerr rotation
                lcalc.reflectivity(3,:) = imag(lcalc.M_final(1,2,:)./lcalc.M_final(1,1,:));% Kerr ellepticity

            end

            if  Kerr_pi

                lcalc.reflectivity(2,:) = real(lcalc.M_final(2,1,:)./lcalc.M_final(2,2,:));% Kerr rotation
                lcalc.reflectivity(3,:) = imag(lcalc.M_final(2,1,:)./lcalc.M_final(2,2,:));% Kerr ellepticity

            end
            
            lcalc.reflectivity(2,:) = lcalc.reflectivity(2,:).*lcalc.imprint(:)';%? replace lcalc.reflectivity by imprint in preallocation
            lcalc.reflectivity(3,:) = lcalc.reflectivity(3,:).*lcalc.imprint(:)';
            
        else
            
            pol_state_M(1,:) = lcalc.M_final(1,1,:) * lsim.pol(1) +...
                lcalc.M_final(1,2,:) * lsim.pol(2); % sigma out
            pol_state_M(2,:) = lcalc.M_final(2,1,:) * lsim.pol(1) +...
                lcalc.M_final(2,2,:) * lsim.pol(2); % pi out
            lcalc.reflectivity(2,:) = (abs(lsim.pol_out(1) *pol_state_M(1,:)) .^2 +...
                abs(lsim.pol_out(2) *pol_state_M(2,:)) .^2).*lcalc.imprint(:)';
            
        end
        %%
        
        nb_x_points=length(lcalc.reflectivity(1,:));
        
        if (lsim.typescan==1) && (lsim.angle(4) > 0)
            lcalc.post_reflectivity(2,:)=...
                0.25*lcalc.reflectivity(2,1:nb_x_points/3)...
                +0.5*lcalc.reflectivity(2,nb_x_points/3+1:2*nb_x_points/3)...
                +0.25*lcalc.reflectivity(2,2*nb_x_points/3+1:nb_x_points);
            
            if lsim.formalism==2
                lcalc.post_reflectivity(3,:)=...
                    0.25*lcalc.reflectivity(3,1:nb_x_points/3)...
                    +0.5*lcalc.reflectivity(3,nb_x_points/3+1:2*nb_x_points/3)...
                    +0.25*lcalc.reflectivity(3,2*nb_x_points/3+1:nb_x_points);
            end
            
        else
            lcalc.post_reflectivity(2,:)=lcalc.reflectivity(2,:); 
            if lsim.formalism==2
                lcalc.post_reflectivity(3,:)=lcalc.reflectivity(3,:);
            end
            
        end
    end

    function [lcalc,ldata]=dyna_plot(lcalc,lsim,ldata,optim_flag)
        % the adjusments require calc and data to be returned
        % some calculations and then plots
        
        % DEFINING PLOT FUNCTIONS
        if optim_flag == 0 % supposes plot function already defined at fit stage
            plot_function=@semilogy;
            if lsim.typescan==2
                plot_function=@plot;
            end
        end
        
        % ON THE FLY or in OPTIM USER'S X AND Y ADJUSTMENTS ON CALC
        if th2Q
           lcalc.adjusted_results(1,:)= ...
                2*sind(lcalc.post_reflectivity(1,:)+lcalc.adjust.x(2))...
                *lsim.energy(1)/12398.42;
        else
           lcalc.adjusted_results(1,:)= ...
               lcalc.post_reflectivity(1,:)+lcalc.adjust.x(2);
        end
        
        lcalc.adjusted_results(2,:)=...
            lcalc.adjust.y(2)*(lcalc.post_reflectivity(2,:)+...
            lcalc.adjust.bkg(2));

        if (lsim.formalism == 2)
            lcalc.adjusted_results(3,:) =...
                lcalc.adjust.y(2)*(lcalc.post_reflectivity(3,:)+...
                lcalc.adjust.bkg(2));
            if lsim.plot_ratio
                 lcalc.ratio=... % needs to be here bc of bkg
                    [lcalc.adjusted_results(1,:);sign*...
                    (lcalc.adjusted_results(3,:)-lcalc.adjusted_results(2,:))./ ...
                    (lcalc.adjusted_results(3,:)+lcalc.adjusted_results(2,:))];
            elseif lsim.plot_diff
                 lcalc.diff=... % needs to be here bc of bkg
                    [lcalc.adjusted_results(1,:);sign*...
                    (lcalc.adjusted_results(3,:)-lcalc.adjusted_results(2,:))];
            end
        end
        
        % PLOTTING
        if optim_flag == get(lst_sim,'Value') || optim_flag == 0
        if (lsim.formalism == 1) || (lsim.formalism == 3)
            plot_function(graph_frame,...
                lcalc.adjusted_results(1,:),lcalc.adjusted_results(2,:),'b');
        else
            if lsim.plot_ratio
                plot(graph_frame,lcalc.adjusted_results(1,:),lcalc.ratio(2,:),'b');
            elseif lsim.plot_diff
                plot(graph_frame,lcalc.adjusted_results(1,:),lcalc.diff(2,:),'b');
            else
               plot_function(graph_frame,...
                    lcalc.adjusted_results(1,:),lcalc.adjusted_results(2,:),'b',...
                    lcalc.adjusted_results(1,:),lcalc.adjusted_results(3,:),'r');
            end
        end
        end
        
        % IF DATA
        if ~isempty(ldata.values)
           if optim_flag == 0 % ON THE FLY ADJUSTMENT while not in optim loop
                if lsim.formalism == 2
                    if lsim.plot_ratio || lsim.plot_diff
                        ldata.post_values=[ldata.values(1,:)+ldata.adjust.x(2);...
                            ldata.values(2,:)];
                    else
                        ldata.post_values=[ldata.values(1,:)+ldata.adjust.x(2);...
                            (ldata.values(2,:)-ldata.adjust.bkg(2))*ldata.adjust.y(2)];
                    end
                else
                    ldata.post_values=[ldata.values(1,:) + ldata.adjust.x(2);...
                        (ldata.values(2,:)-ldata.adjust.bkg(2))*ldata.adjust.y(2)];
                end
                
                if th2Q
                    ldata.post_values(1,:)=2*sin((ldata.values(1,:) +...
                        ldata.adjust.x(2))/180*pi)*lsim.energy(1)/12398.42;
                end
                set(edtxmin,'String',ldata.intervall(1))
                set(edtxmax,'String',ldata.intervall(2))
            end
            
            if optim_flag==get(lst_sim,'Value') || optim_flag==0
                hold on;
            plot_function(graph_frame,ldata.post_values(1,:),...
                ldata.post_values(2,:),...
                'k','Marker','o','MarkerSize',2,'MarkerFaceColor','k');
            hold off;
            end
        end
        
        % LABELS AND LEGENDS SET EXCEPT WHILE FITTING
        if optim_flag == 0
          if lsim.typescan == 1
                if th2Q
                    xlabel('Q/2pi (A-1)');
                else
                    xlabel('th (deg)');
                end
            else
                xlabel('Energy (eV)');
          end
            
          if lsim.plot_ratio
                ylabel('ratio');
                if ratio_mag_inverted
                    set_legend='ratio -H - +H / -H + +H';
                else
                    set_legend='ratio C- - C+ / C- + C+';
                end
                
          elseif lsim.plot_diff
                ylabel('diff');
                if ratio_mag_inverted
                    set_legend='diff H inverted';
                else
                    set_legend='diff C- - C+';
                end
          else
                ylabel(graph_frame,'reflectivity');
                if lsim.formalism == 2 % magnetism
                    if ~isempty(ldata.values)
                        set_legend={'I+','I-',strrep(ldata.name,'_','\_')};
                    else
                        set_legend={'I+','I-'};
                    end
                else
                    if ~isempty(ldata.values)
                        set_legend={'I',strrep(ldata.name,'_','\_')};
                    else
                        set_legend='I';
                    end
                end
          end
          set(graph_frame,'Color',[0.992 0.918 0.796]);
          legend(set_legend);
          title(strcat('PROJECT: ',strrep(project_name,'_','\_'),'  SIM: ',lsim.number_string,' DATA: ',strrep(ldata.name,'_','\_')));
        end
    end

    function calculate(n) % called from GUI, not while OPTIMIZATION 
        if on_the_fly_sync || calc_now 
            % performs n^th simulation
            messages = sprintf('%10s: Performing Calculation using %s formalism\n', datestr(now),formalism{get(lst_formalism,'Value')});
            fprintf(log_file_id,messages);
            set(send_messages_box, 'String', messages);
            drawnow % really needed to make the message appear
            %tic
            calc(n)=sim(n).function(calc(n),sim(n),layer,SF(n),sequence);
            %toc
            calculation_done_flag=1;
            calc(n)=post(calc(n),sim(n));
            [calc(n),data(n)]=dyna_plot(calc(n), sim(n), data(n),0);
            messages = sprintf('%10s: Calculation performed\n', datestr(now));
            fprintf(log_file_id, messages);
            set(send_messages_box, 'String', messages);
        else
            messages = sprintf('%10s: on-the-fly sync is off, cntrl-C or cmd-C to calculate \n', datestr(now));
            set(send_messages_box, 'String', messages);
        end    
    end
%%
%%%%%%%%%%%%%%%%%%%%%%
%%%%               %%%
%%%%      GUI      %%%
%%%%               %%%
%%%%%%%%%%%%%%%%%%%%%%
set(0,'Units','normalized');
get(0,'ScreenSize');
defaultBackground = get(0,'defaultUicontrolBackgroundColor');

%% TWO FRAMES
main_frame = figure('Name','Dyna','Visible','off','Units','normalized','Position',[0,0,1,1],'Toolbar','none','MenuBar','none','Visible','on','Color',[.494 .494 .494]);
graph_frame = axes('parent',main_frame,'Units','normalized','Box','on','Color',[0.992 0.918 0.796],'XColor',[0 0 0],'YColor',[0 0 0],'YScale','log','FontSize',10,'Position',[0.405 0.36 0.575 0.61]);

%% MENU BAR
print_number=0; dcm_state=0;

dynaMenu=uimenu('Parent',main_frame,'HandleVisibility','callback','Label','Dyna');

uimenu('Parent',dynaMenu,'Label','Help','Separator','on','HandleVisibility','callback','Accelerator','H','Callback', @callers_Menu_Callback,'Tag','Help');

uimenu('Parent', dynaMenu,'Label','Log of runtime messages','Separator','on','HandleVisibility','callback', 'Tag','Log','Callback', @callers_Menu_Callback);

uimenu('Parent',dynaMenu,'Label','About Dyna','Separator','on','HandleVisibility','callback', 'Tag', 'About','Callback', @callers_Menu_Callback);

uimenu('Parent',dynaMenu,'Label','Close','Separator','on','HandleVisibility','callback', 'Accelerator','W','Tag','Close','Callback', @callers_Menu_Callback);

% PROJECT

ProjectMenu=uimenu('Parent',main_frame,'HandleVisibility','callback','Label','Project');

uimenu('Parent',ProjectMenu,'Label','Open','Accelerator','O','HandleVisibility','callback','Tag','Open','Callback', @callers_Menu_Callback);

uimenu('Parent',ProjectMenu,'Label','Open Old Version (V3.01 -> V3.07)','Accelerator','O','HandleVisibility','callback', 'Tag','Open_Old_Version','Callback', @callers_Menu_Callback);

uimenu('Parent',ProjectMenu,'Label','New','Accelerator','N','HandleVisibility','callback', 'Tag','New','Callback', @callers_Menu_Callback);

uimenu('Parent',ProjectMenu,'Label','Save','Accelerator','S','HandleVisibility','callback', 'Tag','Save','Callback', @callers_Menu_Callback);

uimenu('Parent',ProjectMenu,'Label','Save as ...','HandleVisibility','callback','Tag','SaveAs','Callback', @callers_Menu_Callback);

uimenu('Parent',ProjectMenu,'Label','Save Layer as ...','HandleVisibility','callback', 'Tag','Save_As_Layer','Callback', @callers_Menu_Callback);

uimenu('Parent',ProjectMenu,'Label','Import Layer ...','HandleVisibility','callback', 'Tag','Import_Layer','Callback', @callers_Menu_Callback);

RatioMenu=uimenu('Parent', main_frame,'HandleVisibility','callback','Label','Ratio');

uimenu('Parent',RatioMenu,'Label','Ratio/Reflectivity Toggle','Accelerator','R','HandleVisibility','callback', 'Tag','ratio_ref_toggle','Callback', @callers_Menu_Callback);

uimenu('Parent',RatioMenu,'Label','Difference/Reflectivity Toggle','Accelerator','D','HandleVisibility','callback','Tag','diff_ref_toggle','Callback', @callers_Menu_Callback);

uimenu('Parent',RatioMenu,'Label','Kerr_pi','Accelerator','P','HandleVisibility','callback', 'Tag','Kerr_pi_toggle','Callback', @callers_Menu_Callback);

uimenu('Parent',RatioMenu,'Label','Kerr_sigma','Accelerator','K','HandleVisibility','callback','Tag','Kerr_sigma_toggle','Callback', @callers_Menu_Callback);

uimenu('Parent',RatioMenu,'Label','Magnetization or Polarization Reversed','Accelerator','M','HandleVisibility','callback', 'Tag','mag_to_pol','Callback', @callers_Menu_Callback);

%% GRAPH MENU
GraphMenu=uimenu('Parent', main_frame,'HandleVisibility','callback','Label','Graph');

uimenu('Parent',GraphMenu,'Label','Linear/Log Toggle', 'Accelerator','L','Tag','linlog','HandleVisibility','callback','Callback', @callers_Menu_Callback);

uimenu('Parent',GraphMenu,'Label','Flip sign', 'Accelerator','F','Tag','flip','HandleVisibility','callback','Callback', @callers_Menu_Callback);

uimenu('Parent', GraphMenu,'Label','toggle degree and ang-1', 'Accelerator','Q','HandleVisibility','callback', 'Tag', 'th2Q','Callback', @callers_Menu_Callback);

uimenu('Parent',GraphMenu,'Label','Legend', 'HandleVisibility','callback','Tag','legend','Callback', @callers_Menu_Callback);

uimenu('Parent',GraphMenu,'Label','Grid on/off','Tag','grid','Accelerator','G','HandleVisibility','callback','Callback', @callers_Menu_Callback);

uimenu('Parent',GraphMenu,'Label','Zoom','Accelerator','Z','Tag','zoom','HandleVisibility','callback','Callback', @callers_Menu_Callback);

uimenu('Parent',GraphMenu,'Label','Data Cursor','HandleVisibility','callback','Tag','data_cursor','Callback', @callers_Menu_Callback);

%% SIM MENU
SimMenu=uimenu('Parent',main_frame,'HandleVisibility','callback','Label','Sims');
uimenu('Parent',SimMenu,'Label','Add','HandleVisibility','callback', 'Tag','Add','Callback', @callers_Menu_Callback);
uimenu('Parent',SimMenu,'Label','Delete','HandleVisibility','callback', 'Tag','Delete','Callback', @callers_Menu_Callback);
uimenu('Parent',SimMenu,'Label','On-the-fly sync Toggle','HandleVisibility','callback', 'Tag','on-the-fly sync','Callback', @callers_Menu_Callback);
uimenu('Parent',SimMenu,'Label','calc','Accelerator','C','HandleVisibility','callback', 'Tag','calc now','Callback', @callers_Menu_Callback);

%% DATA MENU
DataMenu=uimenu('Parent',main_frame,'HandleVisibility','callback','Label','Data');

uimenu('Parent',DataMenu,'Label','Data Panel (under construction)','HandleVisibility','callback','Tag','Data Panel','Callback', @callers_Menu_Callback);

uimenu('Parent',DataMenu,'Label','Import Data', 'Accelerator','I','HandleVisibility','callback','Tag','ImportData','Callback', @callers_Menu_Callback);

uimenu('Parent',DataMenu,'Label','Delete Data','HandleVisibility','callback','Tag','DeleteData','Callback', @callers_Menu_Callback);

uimenu('Parent',DataMenu,'Label','2theta -> theta','Separator','on','HandleVisibility','callback','Tag','tth_to_th','Callback', @callers_Menu_Callback);

uimenu('Parent',DataMenu,'Label','theta -> 2theta','HandleVisibility','callback','Tag','th_to_tth','Callback', @callers_Menu_Callback);

uimenu('Parent',DataMenu,'Label','Q -> theta','HandleVisibility','callback','Tag','Q_to_th','Callback', @callers_Menu_Callback);

uimenu('Parent',DataMenu,'Label','q -> theta','HandleVisibility','callback','Tag','q_to_th','Callback', @callers_Menu_Callback);

uimenu('Parent',DataMenu,'Label','theta -> Q','HandleVisibility','callback','Tag','th_to_Q','Callback', @callers_Menu_Callback);

uimenu('Parent',DataMenu,'Label','theta -> q=Q/2pi','HandleVisibility','callback','Tag','th_to_q','Callback', @callers_Menu_Callback);

%% EXPORT MENU BAR
ExportMenu   = uimenu('Parent', main_frame,'HandleVisibility','callback','Label','Export');

uimenu('Parent', ExportMenu,'Label','Save Results to file','Accelerator','E','HandleVisibility','callback','Tag','results_to_file','Callback', @callers_Menu_Callback);

uimenu('Parent', ExportMenu,'Label','Save Ratio to file','HandleVisibility','callback','Tag','ratio_to_file','Callback', @callers_Menu_Callback);

uimenu('Parent', ExportMenu,'Label','Save Diff to file','HandleVisibility','callback','Tag','diff_to_file','Callback', @callers_Menu_Callback);

uimenu('Parent', ExportMenu,'Label','Save IPlus to file','HandleVisibility','callback', 'Tag','iplusiminus_to_file','Callback', @callers_Menu_Callback);

uimenu('Parent',ExportMenu,'Label','Export Figure to PostScript','Accelerator','X','HandleVisibility','callback', 'Tag','fig_to_ps', 'Callback', @callers_Menu_Callback);

uimenu('Parent',ExportMenu,'Label','Export Figure to JPEG','HandleVisibility','callback','Tag','fig_to_jpeg','Callback', @callers_Menu_Callback);

uimenu('Parent',ExportMenu,'Label','Print Worspace','Accelerator','P','Tag','print','HandleVisibility','callback','Callback', @callers_Menu_Callback);

uimenu('Parent',ExportMenu,'Label','Export Workspace to PostScript','HandleVisibility','callback','Callback', @callers_Menu_Callback);

uimenu('Parent',ExportMenu,'Label','Export Workspace to JPEG','HandleVisibility','callback', 'Tag', 'to_jpeg','Callback', @callers_Menu_Callback);

% MENU BAR ENDS %%

% BEGINS ALL PANEL INIT
panel_exp = uipanel('Units','normalized','Position',[.005 .68 .36 .315],'BackgroundColor',defaultBackground);

panel_optimization=uipanel('Units','normalized','Position',[.005 .315 .36 .36],'BackgroundColor',defaultBackground);

panel_multilayer=uipanel('Units','normalized','Position',[.005 .06 .99 .25],'BackgroundColor',defaultBackground);

panel_messages=uipanel('Units','normalized','Position',[.005 .01 .99 .045],'BackgroundColor',defaultBackground);
% ENDS ALL PANEL INIT

% MESSAGE PANEL
send_messages_box = uicontrol('Parent',panel_messages,'Units','normalized','FontSize', 10,'Position',[0 0 1 1],'Style','text','HorizontalAlignment','left','String','');

%% BEGINS SIMULATION PANEL

lst_sim=uicontrol('Parent',panel_exp,'Units','normalized','FontSize',10,'Style','popupmenu','FontSize',10,'Position',[0.01 .9 .5 .075],'BackgroundColor',[1 1 1],'Tag','LstExpParam','Callback',@callers_Exp_Callback,'String',strcat({sim.number_string},' ',{data.name}),'Value',1);

formalism={'Formalism Parratt Fix Energy','Formalism Parratt Fix Angle','Formalism Parratt Fix Q','Formalism Magnetism Fix Energy','Formalism Magnetism Fix Angle','Formalism Magnetism Fix Q','Formalism Anisotropy Fix Energy','Formalism Anisotropy Fix Angle','Formalism Anisotropy Fix Q'};

lst_formalism = uicontrol('Parent',panel_exp,'Units','normalized', 'FontSize', 10,'Style','popupmenu','BackgroundColor',[1 1 1], 'Position',[0.55 .88 .44 .095],'Callback',@callers_Exp_Callback,'Tag', 'Choosing_Function','String',formalism,'Value', 1);

uicontrol('Parent',panel_exp,'Units','normalized','FontSize',10,'Position',[.005 .62 .08 .1],'String','Energy', 'Style','text');

uicontrol('Parent',panel_exp,'Units','normalized','FontSize',10,'Position',[.005 .5 .08 .1],'String','Angle', 'Style','text');

uicontrol('Parent',panel_exp,'Units','normalized','FontSize',10,'Position',[.005 .35 .08 .1],'String','Q', 'Style','text');

uicontrol('Parent',panel_exp,'Units','normalized','FontSize',10,'Position',[.1 .72 .1 .1],'String','Start','Style','text');

uicontrol('Parent',panel_exp,'Units','normalized','FontSize',10,'Position',[.21 .72 .1 .1],'String','End', 'Style','text');

uicontrol('Parent',panel_exp,'Units','normalized','FontSize',10,'Position',[.32 .72 .1 .1],'String','Step', 'Style','text');

uicontrol('Parent',panel_exp,'Units','normalized','FontSize',10,'Position',[.43 .72 .15 .1],'String','Resolution', 'Style','text');

box_energy1=uicontrol('Parent',panel_exp,'Units','normalized','Position',[.1 .62 .1 .12],'BackgroundColor',[1 1 1],'FontSize',10,'Enable','on','Style','edit','Tag','box_energy','Callback',@callers_Exp_Callback,'String', sim(1).energy(1));

box_energy2=uicontrol('Parent',panel_exp,'Units','normalized','BackgroundColor',[1 1 1],'FontSize',10, 'Position',[.21 .62 .1 .12],'Enable','off','Style','edit', 'Tag','box_energy','Callback',@callers_Exp_Callback,'String',sim(1).energy(2));

box_energy_step=uicontrol('Parent',panel_exp,'Units','normalized', 'BackgroundColor',[1 1 1],'FontSize',10,'Enable','off', 'Position',[.32 .62 .1 .12],'TooltipString','Step scan energy','Style','edit', 'Tag','box_energy','Callback',@callers_Exp_Callback,'String', sim(1).energy(3));

box_theta1=uicontrol('Parent',panel_exp,	'Units','normalized','BackgroundColor',[1 1 1],'FontSize',10, 'Position',[.1 .49 .1 .12],'String', sim(1).angle(1), 'Style','edit','Enable','on','TooltipString','Start scan incident theta angle >0','Tag','box_theta','Callback',@callers_Exp_Callback);

box_theta2=uicontrol('Parent',panel_exp,'Units','normalized','BackgroundColor',[1 1 1],'FontSize',10, 'Position',[.21 .49 .1 .12],'String',sim(1).angle(2), 'Style','edit','Enable','on','TooltipString','End scan incident theta angle','Tag','box_theta','Callback',@callers_Exp_Callback);

box_theta_step=uicontrol('Parent',panel_exp,'Units','normalized','BackgroundColor',[1 1 1],'FontSize',10, 'Position',[.32 .49 .1 .12],'String', sim(1).angle(3), 'Style','edit','Enable','on','TooltipString','Step scan incident theta angle','Tag','box_theta','Callback',@callers_Exp_Callback);

box_theta_resolution=uicontrol('Parent',panel_exp,'Units','normalized','BackgroundColor',[1 1 1], 'Enable','on','Enable','on', 'FontSize',10, 'Position',[.43 .49 .1 .12],'String', sim(1).angle(4), 'Style','edit', 'Tag','box_theta','TooltipString','Divergence Angle (only for energy fix analysis)','Callback',@callers_Exp_Callback);

box_Q1 = uicontrol('Parent',panel_exp,	'Units','normalized','BackgroundColor',[1 1 1],'FontSize',10, 'Position',[.1 .36 .1 .12], 'String', num2str(sim(1).Q), 'Style','edit','Enable','off','CallBack',@callers_Exp_Callback,'Tag','box_Q1','TooltipString','q = 2 sin th / lamda');

polarization={'unpolarized', 'LINEAR SIGMA', 'LINEAR PI', 'CIRCULAR +','CIRCULAR -', 'specified'};

analyzer={'no outgoing analyzer', 'SIGMA analyzer', 'PI analyzer'};

lst_polarization=uicontrol('Parent',panel_exp,'Units','normalized','FontSize', 10,'BackgroundColor',[1 1 1],'Position',[0.62 .74 .3 .1],'String', polarization, 'Tag','Polarization','Style','popupmenu','Callback',@callers_Exp_Callback,'Value',4); % set by default

lst_analyzer=uicontrol('Parent',panel_exp,'Units','normalized','FontSize', 10,'BackgroundColor',[1 1 1],'Position',[0.62 .62 .3 .1],'String', analyzer,'Style','popupmenu','Tag','Polarization','Callback',@callers_Exp_Callback,'Value',1);

uicontrol('Parent',panel_exp,	'Units','normalized','FontSize',10, 'Position',[.55 .5 .25 .09],'String','Beam thickness','Style','text');

uicontrol('Parent',panel_exp,	'Units','normalized','FontSize',10, 'Position',[.55 .4 .25 .09],'String','Sample length', 'Style','text');

box_beam_thickness = uicontrol('Parent',panel_exp,'Units','normalized','BackgroundColor',[1 1 1],'FontSize',10,'Position',[.82 .515 .1 .075],'String', sim(1).sthickness, 'Style','edit', 'Enable','on','CallBack',@callers_Exp_Callback,'Tag','Imprint','TooltipString','Imprint = Beam thickness/Sample length (thickness and length: same units)');

box_sample_length = uicontrol('Parent',panel_exp,'Units','normalized','BackgroundColor',[1 1 1],'FontSize', 10,'Position',[.82 .42 .1 .075],'String', sim(1).slength, 'Style','edit','Enable','on','CallBack',@callers_Exp_Callback,'Tag','Imprint','TooltipString','Imprint (no unit) = Beam thickness/Sample length (same units!)');

uicontrol('Parent',panel_exp,'Style','text','FontWeight','bold','String','Normalization (DATA/CALC)','Units','normalized','Position',[.08 .28 .3 .075]);

data_box_normalization_max=uicontrol('Parent',panel_exp,'Style','edit','Units','normalized','BackgroundColor',[1 1 1],  'FontSize',10, 'FontWeight','normal','Position',[.215 .215 .1 .075],'String', data(1).adjust.y(3),'Enable','on','Callback',@callers_shift_control,'Tag','data_box_normalization_max');

data_box_normalization_min=uicontrol('Parent',panel_exp,'Style','edit','Units','normalized','BackgroundColor',[1 1 1],'FontSize',10,'FontWeight','normal','Position',[.005 .215 .1 .075],'String', data(1).adjust.y(1),'Enable','on','Callback',@callers_shift_control,'Tag','data_box_normalization_min');

data_box_normalization=uicontrol('Parent',panel_exp,'Style','edit','Units','normalized', 'BackgroundColor',[1 1 1],'FontSize',10, 'FontWeight','bold','Position',[.11 .215  .1 .075],'String', num2str(data(1).adjust.y(2)),'Enable','on','Callback',@callers_shift_control,'Tag','data_box_normalization');

data_slider_normalization=uicontrol('Parent',panel_exp,'Style','slider','Min', data(1).adjust.y(1), 'Value', data(1).adjust.y(2),'Max', data(1).adjust.y(3), 'SliderStep',[.001 .01],'Units','normalized','Position', [.005 .15 .31 .06],'Callback',@callers_shift_control,'Tag','data_slider_normalization');

calc_box_normalization_max=uicontrol('Parent',panel_exp,'Units','normalized','BackgroundColor',[1 1 1],  'FontSize',10, 'FontWeight','normal','Position',[.215 .07 .1 .075],'String', calc(1).adjust.y(3),'Enable','on', 'Style','edit','Callback',@callers_shift_control,'Tag','calc_box_normalization_max');

calc_box_normalization_min=uicontrol('Parent',panel_exp,'Units','normalized','BackgroundColor',[1 1 1],'FontSize',10,'FontWeight','normal','Position',[.005 .07 .1 .075],'String', calc(1).adjust.y(1),'Enable','on', 'Style','edit','Callback',@callers_shift_control,'Tag','calc_box_normalization_min');

calc_box_normalization=uicontrol('Parent',panel_exp,'Style','edit','Units','normalized', 'BackgroundColor',[1 1 1],'FontSize',10, 'FontWeight','bold','Position',[.11 .07 .1 .075],'String', num2str(calc(1).adjust.y(2)),'Enable','on','Callback',@callers_shift_control,'Tag','calc_box_normalization');

calc_slider_normalization=uicontrol('Parent',panel_exp,'Style','slider','Min', calc(1).adjust.y(1),'Value', calc(1).adjust.y(2),'Max', calc(1).adjust.y(3),'SliderStep',[.001 .01],'Units','normalized','Position', [.005 .005 .31 .06],'Callback',@callers_shift_control,'Tag','calc_slider_normalization');

uicontrol('Parent',panel_exp,'Units','normalized','Style','text', 'FontWeight','bold','String','Background (DATA/CALC)','Position',[.335 .28 .3 .075]);

data_box_bkg_max=uicontrol('Parent',panel_exp,'Units','normalized','BackgroundColor',[1 1 1], 'FontSize',10,  'FontWeight','normal','Position',[.54 .215 .1 .075], 'String', data(1).adjust.bkg(2), 'Enable','on','Style','edit','Callback',@callers_shift_control,'Tag','data_box_bkg_max');

data_box_bkg_min=uicontrol('Parent',panel_exp,'Units','normalized','BackgroundColor',[1 1 1],'FontSize',10,'FontWeight','normal','Position',[.33 .215 .1 .075],'String', data(1).adjust.bkg(1), 'Enable','on','Style','edit','Callback',@callers_shift_control,'Tag','data_box_bkg_min');

data_box_bkg=uicontrol('Parent',panel_exp,'Units','normalized','BackgroundColor',[1 1 1],'FontSize',10,'FontWeight','bold','Position',[.435 .215 .1 .075],'String', num2str(data(1).adjust.bkg(2)),'Enable','on','Style','edit','Callback',@callers_shift_control,'Tag','data_box_bkg');

data_slider_bkg=uicontrol('Parent',panel_exp,'Style','slider','Max',data(1).adjust.bkg(3),'Min',data(1).adjust.bkg(1),'Value',data(1).adjust.bkg(2),'SliderStep',[.001 .01],'Units','normalized','Position', [.33 .15 .31 .06],'Callback',@callers_shift_control,'Tag','data_slider_bkg');

calc_box_bkg_max=uicontrol('Parent',panel_exp,'Units','normalized','BackgroundColor',[1 1 1], 'FontSize',10,  'FontWeight','normal','Position',[.54 .07 .1 .075], 'String', calc(1).adjust.bkg(3), 'Enable','on','Style','edit','Callback',@callers_shift_control,'Tag','calc_box_bkg_max');

calc_box_bkg_min=uicontrol('Parent',panel_exp,'Units','normalized','BackgroundColor',[1 1 1],'FontSize',10,'FontWeight','normal','Position',[.33 .07 .1 .075],'String', calc(1).adjust.bkg(1), 'Enable','on','Style','edit','Callback',@callers_shift_control,'Tag','calc_box_bkg_min');

calc_box_bkg=uicontrol('Parent',panel_exp,'Units','normalized','BackgroundColor',[1 1 1],'FontSize',10,'FontWeight','bold','Position',[.435 .07 .1 .075],'String', num2str(calc(1).adjust.bkg(2)),'Enable','on','Style','edit','Callback',@callers_shift_control,'Tag','calc_box_bkg');

calc_slider_bkg=uicontrol('Parent',panel_exp,'Style','slider','Max',calc(1).adjust.bkg(3),'Min',calc(1).adjust.bkg(1),'Value',calc(1).adjust.bkg(2),'SliderStep',[.001 .01],'Units','normalized','Position', [.33 .005 .31 .06],'Callback',@callers_shift_control,'Tag','calc_slider_bkg');

uicontrol('Parent',panel_exp,'Style','text','FontWeight','bold','String','X shift (DATA/CALC)' ,'Units','normalized','Position',[.66 .28 .3 .075]);

data_box_x_shift_max=uicontrol('Parent',panel_exp,'Units','normalized','BackgroundColor',[1 1 1],'FontSize',10,'FontWeight','normal','Position',[.87 .215 .1 .075],'String',data(1).adjust.x(3),'Enable','on','Style','edit','Callback',@callers_shift_control,'Tag','data_x_shift_max');

data_box_x_shift_min=uicontrol('Parent',panel_exp,'Units','normalized','BackgroundColor',[1 1 1],'FontSize',10,'FontWeight','normal','Position',[.66 .215 .1 .075],'String', data(1).adjust.x(1),'Enable','on','Style','edit','Callback',@callers_shift_control,'Tag','data_x_shift_min');

data_box_x_shift=uicontrol('Parent',panel_exp,'Style','edit','Units','normalized','BackgroundColor',[1 1 1],'FontSize',10,'FontWeight','bold','Position',[.765 .215 .1 .075],'String', 0,'Enable','on','Callback',@callers_shift_control,'Tag','data_box_x_shift');

data_slider_x_shift=uicontrol('Parent',panel_exp,'Style','slider','Max',data(1).adjust.x(3),'Min', data(1).adjust.x(1),'Value',data(1).adjust.x(2),'SliderStep',[.0025 .025],'Units','normalized','Position', [.66 .15 .31 .06],'Callback',@callers_shift_control,'Tag','data_slider_x_shift');

calc_box_x_shift_max=uicontrol('Parent',panel_exp,'Units','normalized','BackgroundColor',[1 1 1],'FontSize',10,'FontWeight','normal','Position',[.87 .07 .1 .075],'String',calc(1).adjust.x(3),'Enable','on','Style','edit','Callback',@callers_shift_control,'Tag','calc_x_shift_max');

calc_box_x_shift_min=uicontrol('Parent',panel_exp,'Units','normalized','BackgroundColor',[1 1 1],'FontSize',10,'FontWeight','normal','Position',[.66 .07 .1 .075],'String', calc(1).adjust.x(1),'Enable','on','Style','edit','Callback',@callers_shift_control,'Tag','calc_x_shift_min');

calc_box_x_shift=uicontrol('Parent',panel_exp,'Units','normalized','BackgroundColor',[1 1 1],'FontSize',10,'FontWeight','bold','Position',[.765 .07 .1 .075],'String', 0,'Enable','on','Style','edit','Callback',@callers_shift_control,'Tag','calc_box_x_shift');

calc_slider_x_shift=uicontrol('Parent',panel_exp,'Style','slider','Max',calc(1).adjust.x(3),'Min', calc(1).adjust.x(1),'Value',calc(1).adjust.x(2),'SliderStep',[.0025 .025],'Units','normalized','Position', [.66 .005 .31 .06],'Callback',@callers_shift_control,'Tag','calc_slider_x_shift');

% ENDS EXPERIMENTAL/SIMULATION PANEL
%% BEGINS MULTILAYER PANEL
pos_delta_x = .005; pos_x = .042;

set_all_menu=uicontrol('Style','popup','parent',panel_multilayer,'Units','normalized','Position',[.8 .29 .13 .04],'String',{'set current layer mag to','set all layers mag to'});

uicontrol('Style','pushbutton','parent',panel_multilayer,'Units','normalized','Position',[.935 .14 .02 .1],'Tag','POL','String','POL','Callback',@Mag_Button_Callback);

uicontrol('Style','pushbutton','parent',panel_multilayer,'Units','normalized','Position',[.955 .14 .02 .1],'Tag','PERP','String','PERP','Callback',@Mag_Button_Callback);
 
uicontrol('Style','pushbutton','parent',panel_multilayer,'Units','normalized','Position',[.975 .14 .02 .1],'Tag','LONG','String','LONG','Callback',@Mag_Button_Callback);

box_set_phi = uicontrol('Parent',panel_multilayer,'Units','normalized','BackgroundColor',[1 1 1],'FontSize',10,'FontWeight','bold','Position',[.82 .14 .02 .1],'String','','Enable','on','Style','edit','Tag','phi(2)','Callback',@Mag_Button_Callback); 

box_set_gamma = uicontrol('Parent',panel_multilayer,'Units','normalized', 'BackgroundColor',[1 1 1], 'FontSize',10,'FontWeight','bold','Position',[.89 .14 .02 .1],'String','','Enable','on','Style','edit','Tag','gamma(2)','Callback',@Mag_Button_Callback);

box_set_phi_min = uicontrol('Parent',panel_multilayer,'Units','normalized','BackgroundColor',[1 1 1], 'FontSize',10,'FontWeight','normal','Position',[.8 .14 .02 .1],'String','','Enable','on','Style','edit','Tag','phi(1)','Callback',@callers_Multilayer_Callback);

box_set_phi_max = uicontrol('Parent',panel_multilayer,'Units','normalized','BackgroundColor',[1 1 1],'FontSize',10,'FontWeight','normal','Position',[.84 .14 .02 .1],'String', '', 'Enable','on','Style','edit','Tag','phi(3)','Callback',@callers_Multilayer_Callback);

box_set_gamma_min = uicontrol('Parent',panel_multilayer,'Units','normalized','BackgroundColor',[1 1 1], 'FontSize',10,'FontWeight','normal','Position',[.87 .14 .02 .1],'String', '', 'Enable','on','Style','edit','Tag','gamma(1)','Callback',@callers_Multilayer_Callback);

box_set_gamma_max = uicontrol('Parent',panel_multilayer,'Units','normalized','BackgroundColor',[1 1 1],'FontSize',10,'FontWeight','normal','Position',[.91 .14 .02 .1],'String', '', 'Enable','on','Style','edit','Tag','gamma(3)','Callback',@callers_Multilayer_Callback);

slider_phi = uicontrol('Parent',panel_multilayer,'Style','slider','Max',90,'Min',0,'Value',0,'SliderStep',[1/90 5/90],'Units','normalized','Position',[.8 .04 .06 .075],'Tag','phi(2)','Callback',@callers_Multilayer_Callback);

slider_gamma = uicontrol('Parent',panel_multilayer,'Style','slider','Max',90,'Min',0,'Value',0,'SliderStep',[1/90 5/90],'Units','normalized','Position',[.87 .04 .06 .075],'Tag','gamma(2)','Callback',@callers_Multilayer_Callback);

hat=sprintf('        Name    m   Density [mol/cm3]        Thickness         Roughness          MMS            AS          phi (MMS)    gamma (MMS)');

uicontrol('Parent',panel_multilayer,'Units','normalized','BackgroundColor',[1 1 1],'Position',[0.01 .88 .98 .1],'Style','listbox','String',hat,'Min',0,'Max',1, 'FontName','Monospaced','FontSize',10,'Value',1);

lstbox_control_multilayer = uicontrol('Parent',panel_multilayer,'Units','normalized','BackgroundColor',[1 1 1],'Position',[0.01 .35 .98 .5],'Style','listbox', 'Min',0,'Max',1,'Callback',@callers_Multilayer_Callback,'Tag','lstbox_control_multilayer','FontName','Monospaced','FontSize',10,'Value',1);

uicontrol('Parent',panel_multilayer,'Units','normalized','Position',[pos_delta_x .25 .12 .08],'String','Look Up Database', 'Callback',@database_panel,'TooltipString','Database');

box_set_name = uicontrol('Parent',panel_multilayer,'Units','normalized','BackgroundColor',[1 1 1], 'FontSize',10, 'FontWeight','bold','Position',[pos_delta_x .14 .08 .1],'String', '', 'Enable','on','Style','edit','Tag','name','Callback',@callers_Multilayer_Callback);

box_set_multiplicity = uicontrol('Parent',panel_multilayer,'Units','normalized','BackgroundColor',[1 1 1],'FontSize',10,'FontWeight','bold','Position',[pos_delta_x+1.6*pos_x .14 .04 .1],'String', '','Enable','on','Style','edit','Tag','m','Callback',@callers_Multilayer_Callback);

box_set_density_min = uicontrol('Parent',panel_multilayer,'Units','normalized','BackgroundColor',[1 1 1], 'FontSize',10, 'FontWeight','normal','Position',[pos_delta_x+3*pos_x .14 .04 .1], 'String','','Enable','on','Style','edit','Tag','density(1)','Callback',@callers_Multilayer_Callback);

box_set_density = uicontrol('Parent',panel_multilayer,'Units','normalized','BackgroundColor',[1 1 1], 'FontSize',10, 'FontWeight','bold','Position',[pos_delta_x+3*pos_x+.04 .14 .04 .1],'String', '', 'Enable','on','Style','edit','Tag','density(2)','Callback',@callers_Multilayer_Callback);

box_set_density_max = uicontrol('Parent',panel_multilayer,'Units','normalized','BackgroundColor',[1 1 1], 'FontSize',10,'FontWeight','normal','String', '', 'Enable','on','Position',[pos_delta_x+3*pos_x+0.08 .14 .04 .1],'Style','edit','Tag','density(3)','Callback',@callers_Multilayer_Callback);

box_set_thickness_min = uicontrol('Parent',panel_multilayer,'Units','normalized', 'BackgroundColor',[1 1 1],'FontSize',10, 'FontWeight','normal','String', '','Position',[pos_delta_x+6*pos_x .14 .04 .1],'Enable','on','Style','edit','Tag','thickness(1)','Callback',@callers_Multilayer_Callback);

box_set_thickness = uicontrol('Parent',panel_multilayer,'Units','normalized', 'BackgroundColor',[1 1 1],'FontSize',10, 'FontWeight','bold','Position',[pos_delta_x+6*pos_x+.04 .14 .04 .1],'String', '', 'Enable','on','Style','edit','Tag','thickness(2)','Callback',@callers_Multilayer_Callback);

box_set_thickness_max = uicontrol('Parent',panel_multilayer,'Units','normalized', 'BackgroundColor',[1 1 1],'FontSize',10, 'FontWeight','normal','Position',[pos_delta_x+6*pos_x+0.08 .14 .04 .1],'String', '', 'Enable','on','Style','edit','Tag','thickness(3)','Callback',@callers_Multilayer_Callback);

box_set_roughness_min = uicontrol('Parent',panel_multilayer,'Units','normalized', 'BackgroundColor',[1 1 1],'FontSize',10, 'FontWeight','normal','Position',[pos_delta_x+9*pos_x .14 .04 .1],'String', '', 'Enable','on','Style','edit','Tag','roughness(1)','Callback',@callers_Multilayer_Callback);

box_set_roughness = uicontrol('Parent',panel_multilayer,'Units','normalized','BackgroundColor',[1 1 1], 'FontSize',10,'FontWeight','bold','Position',[pos_delta_x+9*pos_x+.04 .14 .04 .1],'String', '', 'Enable','on','Style','edit','Tag','roughness(2)','Callback',@callers_Multilayer_Callback);

box_set_roughness_max = uicontrol('Parent',panel_multilayer,'Units','normalized','BackgroundColor',[1 1 1],'FontSize',10,'FontWeight','normal','Position',[pos_delta_x+9*pos_x+0.08 .14 .04 .1],'String','','Enable','on','Style','edit','Tag','roughness(3)','Callback',@callers_Multilayer_Callback);

box_set_MMS_min = uicontrol('Parent',panel_multilayer,'Units','normalized','BackgroundColor',[1 1 1],'FontSize',10,'FontWeight','normal','Position',[pos_delta_x+12*pos_x .14 .04 .1],'String', '', 'Enable','on','Style','edit','Tag','MMS(1)','Callback',@callers_Multilayer_Callback);

box_set_MMS = uicontrol('Parent',panel_multilayer,'Units','normalized','BackgroundColor',[1 1 1], 'FontSize',10,'FontWeight','bold','Position',[pos_delta_x+12*pos_x+.04 .14 .04 .1],'String', '', 'Enable','on','Style','edit','Tag','MMS(2)','Callback',@callers_Multilayer_Callback);

box_set_MMS_max = uicontrol('Parent',panel_multilayer,'Units','normalized','BackgroundColor',[1 1 1], 'FontSize',10,'FontWeight','normal','Position',[pos_delta_x+12*pos_x+0.08 .14 .04 .1],'String','', 'Enable','on','Style','edit','Tag','MMS(3)','Callback',@callers_Multilayer_Callback);

box_set_AS_min = uicontrol('Parent',panel_multilayer,'Units','normalized','BackgroundColor',[1 1 1], 'FontSize',10,'FontWeight','normal','Position',[pos_delta_x+15*pos_x .14 .04 .1],'String','', 'Enable','on','Style','edit','Tag','AS(1)','Callback',@callers_Multilayer_Callback);

box_set_AS = uicontrol('Parent',panel_multilayer,'Units','normalized','BackgroundColor',[1 1 1],'FontSize',10,'FontWeight','bold','Position',[pos_delta_x+15*pos_x+.04 .14 .04 .1],'String','', 'Enable','on','Style','edit','Tag','AS(2)','Callback',@callers_Multilayer_Callback);

box_set_AS_max = uicontrol('Parent',panel_multilayer,'Units','normalized','BackgroundColor',[1 1 1],'FontSize',10,'FontWeight','normal','Position',[pos_delta_x+15*pos_x+0.08 .14 .04 .1],'String','','Enable','on','Style','edit','Tag','AS(3)','Callback',@callers_Multilayer_Callback);

slider_density = uicontrol('Parent',panel_multilayer,'Style','slider','Max',1,'Min',0,'Value',.5, 'SliderStep',[0.001 0.005],'Units','normalized','Position', [pos_delta_x+3*pos_x .04 .12 .075],'Tag','density(2)','Callback',@callers_Multilayer_Callback);

slider_thickness = uicontrol('Parent',panel_multilayer,'Style','slider','Max',100,'Min',0,'Value',25,'SliderStep',[0.01 0.1],'Units','normalized','Position',[pos_delta_x+6*pos_x .04 .12 .075],'Tag','thickness(2)','Callback',@callers_Multilayer_Callback);

slider_roughness = uicontrol('Parent',panel_multilayer,'Style','slider','Max',100,'Min',0,'Value',25,'SliderStep',[0.01 0.1],'Units','normalized','Position',[pos_delta_x+9*pos_x .04 .12 .075],'Tag','roughness(2)','Callback',@callers_Multilayer_Callback);

slider_MMS = uicontrol('Parent',panel_multilayer,'Style','slider','Max',1,'Min',0,'Value',0,'SliderStep',[0.01 0.1],'Units','normalized','Position',[pos_delta_x+12*pos_x .04 .12 .075],'Tag','MMS(2)','Callback',@callers_Multilayer_Callback);

slider_AS = uicontrol('Parent',panel_multilayer,'Style','slider','Max',1,'Min',0,'Value',0,'SliderStep',[0.1 0.1],'Units','normalized','Position',[pos_delta_x+15*pos_x .04 .12 .075],'Tag','AS(2)','Callback',@callers_Multilayer_Callback);

uicontrol('Parent',panel_multilayer,'Units','normalized','Position',[pos_delta_x .02 .055 .1],'String','Insert', 'Tag','Insert','Callback',@callers_Multilayer_Callback,'TooltipString','Insert Layer');

uicontrol('Parent',panel_multilayer,'Units','normalized','Position',[pos_delta_x+0.055 .02 .055 .1],'String','Delete', 'Tag', 'Delete','Callback',@callers_Multilayer_Callback,'TooltipString','Delete Layer');
% ENDS MULTILAYER PANEL

%% BEGINS OPTIMIZATION PANEL
uicontrol('Parent',panel_optimization,'Units','normalized','Position',[.01 .84 .45 .11],'FontSize',10,'FontWeight','bold','HorizontalAlignment','left','Style','text','String','Optimization Method :');

lst_optimization_method=uicontrol('Parent',panel_optimization,'Units','normalized','FontSize',8,'BackgroundColor',[1 1 1],'Position',[0.46 .84 .2 .11],'String',optimization_method,'String',optimization_method, 'Style','popupmenu','Callback',@callers_Optim_Callback,'Value',1);

btnStartStop=uicontrol('Parent',panel_optimization,'Units','normalized', 'Tag','Start_Stop','FontSize',8,'Position',[0.7 .88 .1 .09],'Callback',@callers_Optim_Callback,'String','Start','Value',1);

btnAccept=uicontrol('Parent',panel_optimization,'Units','normalized', 'Tag','Accept','FontSize',8,'Enable','off','Position',[0.85 .88 .1 .09],'Callback',@callers_Optim_Callback,'String','Accept');

uicontrol('Parent',panel_optimization,'Units','normalized','FontSize',8,'HorizontalAlignment','left','Position',[.05 .78 .1 .05],'String','TolFun','Style','text','TooltipString','Termination tolerance on the function value');

uicontrol('Parent',panel_optimization,'Units','normalized','FontSize',8,'HorizontalAlignment','left','Position',[.18 .78 .1 .05],'String','TolX','Style','text','TooltipString','Termination tolerance on the parameters value');

uicontrol('Parent',panel_optimization,'Units','normalized','FontSize',8,'HorizontalAlignment','left','Position',[.3 .78 .15 .05],'String','MaxFunEvals','Style','text','TooltipString','Maximum number of function evaluations allowed');

uicontrol('Parent',panel_optimization,'Units','normalized','FontSize',8,'HorizontalAlignment','left','Position',[.48 .78 .1 .05],'String','MaxIter','Style','text','TooltipString','Maximum number of iterations allowed');

edtTolFun=uicontrol('Parent',panel_optimization,'Units','normalized','BackgroundColor',[1 1 1],'FontSize',10,'HorizontalAlignment','right','Position',[.05 .72 .1 .07],'String','1e-6','Style','edit','TooltipString','Termination tolerance on the function value');

edtTolX=uicontrol('Parent',panel_optimization,'Units','normalized','BackgroundColor',[1 1 1], 'FontSize',10,'HorizontalAlignment','right', 'Position',[.18 .72 .1 .07],'String','1e-2','Style','edit','TooltipString','Termination tolerance on the parameters value');

edtMaxFunEvals=uicontrol('Parent',panel_optimization,'Units','normalized', 'BackgroundColor',[1 1 1],'FontSize',10,'HorizontalAlignment','right','Position',[.33 .72 .1 .07],'String','200','Style','edit','TooltipString','Maximum number of function evaluations allowed');

edtMaxIter=uicontrol('Parent',panel_optimization,'Units','normalized', 'BackgroundColor',[1 1 1],'FontSize',10,'HorizontalAlignment','right','Position',[.48 .72 .1 .07],'String','200','Style','edit','TooltipString','Maximum number of iterations allowed');

uicontrol('Parent',panel_optimization,'Units','normalized','Position',[.01 .61 .4 .07],'FontSize',10,'FontWeight','bold','Style','text','HorizontalAlignment','left','String','Effective Intervall:');

uicontrol('Parent',panel_optimization,'Units','normalized', 'FontSize',8, 'HorizontalAlignment','left','Position',[.45 .62 .12 .05],'String','X min:','Style','text');

edtxmin=uicontrol('Parent',panel_optimization,'Units','normalized', 'BackgroundColor',[1 1 1],'FontSize',10, 'HorizontalAlignment','right','Position',[.57 .63 .08 .05],'String',x_min, 'Style','edit','Callback',@callers_Optim_Callback,'TooltipString','X min for refinement', 'Tag', 'edtIntervall');

uicontrol('Parent',panel_optimization,'Units','normalized', 'FontSize',8,'HorizontalAlignment','left','Position',[.66 .62 .12 .05],'String','X max:', 'Style','text');

edtxmax=uicontrol('Parent',panel_optimization,'Units','normalized', 'BackgroundColor',[1 1 1],'FontSize',10, 'HorizontalAlignment','right','Position',[.79 .63 .08 .05], 'String',x_max,'Style','edit', 'TooltipString','X max for refinement','Tag','edtIntervall','Callback',@callers_Optim_Callback);

lst_layer=uicontrol('Parent',panel_optimization,'Units','normalized', 'FontSize',10,'BackgroundColor',[1 1 1], 'Position',[0.02 .42 .16 .15],'String','', 'Style','popupmenu','Value',1);

lst_param=uicontrol('Parent',panel_optimization,'Units','normalized', 'FontSize',10,'BackgroundColor',[1 1 1], 'Position',[0.18 .42 .17 .15],'String',param_fittable, 'Style','popupmenu','Value',1);

uicontrol('Parent',panel_optimization,'Units','normalized', 'Tag','Master','Enable','on','Callback',@callers_Optim_Callback,'FontSize',8, 'Position',[0.38 .525 .1 .05],'String','Indpt','Value',1);

uicontrol('Parent',panel_optimization,'Units','normalized', 'Tag','Constrain','Enable','on','Callback',@callers_Optim_Callback,'FontSize',8, 'Position',[0.38 .475 .1 .05],'String','Constrain','Value',0);

lst_layer_to_constrain_with=uicontrol('Parent',panel_optimization,'Units','normalized', 'Enable','off','FontSize',8, 'BackgroundColor',[1 1 1],'Position',[0.5 .42 .15 .15], 'String','','Style','popupmenu','Value',1);

uicontrol('Parent',panel_optimization,'Units','normalized', 'Enable','off','FontSize',8, 'HorizontalAlignment','left','Position',[.67 .5 .02 .05], 'String','X','Style','text', 'TooltipString','multiplicative constant');

edtA=uicontrol('Parent',panel_optimization,'Units','normalized', 'Enable','off','BackgroundColor',[1 1 1],'FontSize',10, 'HorizontalAlignment','right','Position',[.69 .51 .07 .05],'String','1','Style','edit','TooltipString', 'any multiplicative number');

uicontrol('Parent',panel_optimization,'Units','normalized', 'Enable','off','FontSize',8, 'HorizontalAlignment','left','Position',[.78 .5 .02 .05],'String','+', 'Style','text','TooltipString','additive constant');

edtB=uicontrol('Parent',panel_optimization,'Units','normalized', 'Enable','off','BackgroundColor',[1 1 1],'FontSize',10,'HorizontalAlignment','right','Position',[.81 .51 .07 .05],'String','0','Style','edit','TooltipString','any aditive constant');

uicontrol('Parent',panel_optimization,'Units','normalized', 'Tag','Add_Param','Callback',@callers_Optim_Callback,'FontSize',8, 'Position',[0.9 .5 .09 .075],'String','Add');

lbxParam_to_optim=uicontrol('Parent',panel_optimization,'Units','normalized','FontSize',8, 'BackgroundColor',[1 1 1],'Position',[0.01 0.01 .52 .45],'Style','listbox','Min',0,'Max',1,'Value',1,'tag','lbxParam_to_optim','Callback',@callers_Optim_Callback);

btnDelete=uicontrol('Parent',panel_optimization,'Units','normalized', 'Tag','Delete_Param','Callback',@callers_Optim_Callback,'FontSize',8,'Position',[0.55 .35 .08 .075],'String','Del','Enable','off');

btnResetParam=uicontrol('Parent',panel_optimization,'Units','normalized', 'Tag','Reset_Param','Callback',@callers_Optim_Callback,'Enable','off','FontSize',8,'Position',[0.55 .25 .08 .075],'String','Reset');

btnReset=uicontrol('Parent',panel_optimization,'Units','normalized', 'Tag','Reset_All','Callback',@callers_Optim_Callback,'Enable','off', 'FontSize',8,'Position',[0.55 .15 .08 .1],'String','Reset\n All');

box_optimization_output= uicontrol('Parent',panel_optimization,'Units','normalized','HorizontalAlignment','left','FontSize',10,'ForegroundColor','g','BackgroundColor','k','Position',[0.64 0.01 .35 .45],'Style','text','String', text_to_send,'Tag','box_optimization_output','Value',1);
% END OPTIMIZATION PANEL

% INITIALIZING
stamp_multilayer(layer);
make_sequence;
[calc(1),data(1),SF(1)]=preallocate(sim(1),calc(1),data(1),layer,0);
calc(1).imprint=fun_imprint(1);
calculate(1);
end
