function extract_from2D

% GUI to extract data from Bruker EPR 2D experiment (.YGF).
% Extracted data 
% - 1D spectra (averaged or seprated) 
% - 2D experiment (if following selected spectra)
% in Bruker format and/or ascii 
%
% EE mai 2020
% juin 2020 bug cancel chemin de sauvegarde
% janv 2021 - extraction 2D Bruker possible si indices ne suivent pas
%           - extraction 2D avec regroupement regulier de spectre
% oct 2025: ytick=NaN => ytick=[]

clear;close;clc;
%% GUI
versionyearall=version('-release');
versionyear=str2double(versionyearall(1:4)); %annee version matlab

if versionyear>=2025
    tickNaN=[];
else
    tickNaN=NaN;
end



hGUIextractfrom2D=figure();
scrszpix = get(0,'ScreenSize'); %taille ecran [left, bottom, width, height] en pixels
set(hGUIextractfrom2D,'Units','pixels','Outerposition',[scrszpix(3)/3 0.2*scrszpix(4) 750 400],...,...
    'Name','Extract from 2D','Menubar', 'none', 'Toolbar', 'none',...%'resize','off',...
    'NumberTitle','off',...'DoubleBuffer','on','CloseRequestFcn',@closeSimLabel,...
    'color',get(0,'DefaultUicontrolBackgroundColor'));

hpanelin = uipanel(...
        'Parent',hGUIextractfrom2D,...
        'Title','Input','TitlePosition','centertop','FontSize',12,...
        'Position',[0.01 0.01 0.5-0.01 1-0.01]);
hpanelout = uipanel(...
        'Parent',hGUIextractfrom2D,...,
        'Title','Output','TitlePosition','centertop','FontSize',12,...
        'Position',[0.5+0.01 0.01 0.5-0.02 1-0.01]);

ftsz=14;%fontsize en pixels
    
%% input %%%%%%%%%%%%%
uicontrol('Style','text','Units','Normalized','pos',[0.0 0.92 0.18 0.06],...
    'parent',hpanelin,'String','Input file','HorizontalAlignment','right',...'BackgroundColor','c',...
    'fontunits','pixels','fontsize',ftsz,'TooltipString','2D file for extraction');

hfilein=uicontrol('Style','text','Units','Normalized','pos',[0.2 0.92 0.5 0.06],'BackgroundColor','w',...
    'parent',hpanelin,'String','','HorizontalAlignment','left',...
    'fontunits','pixels','fontsize',ftsz);

uicontrol('Style','pushbutton','Units','Normalized','pos',[0.73 0.90 0.24 0.1],...'BackgroundColor','w',...
    'parent',hpanelin,'String','Get 2D file','Callback', @get2Dfile,'fontunits','pixels','fontsize',ftsz,'tooltipstring','Get Kinetic file');

hgraphe=axes('parent',hpanelin,'Position',[0.02 0.22 0.85 0.62],...%'OuterPosition',[0 0.25 1 0.75],
               'Ytick',tickNaN,'Box','on','Xtick',tickNaN);
          % title(hgraphe,'toto')

hslidindex = uicontrol(...
        'Parent',hpanelin,...
        'Units','normalized',...
        'BackgroundColor',[0.9 0.9 0.9],...
        'Callback',@dispspec,...{@cllbckslidtime,1}
        'Position',[0.91 0.22 0.05 0.62],...
        'Style','slider',...
        'enable','off',...
        'value',1,...
        'Min',1);

hchk = uicontrol(...
        'Parent',hpanelin,...
        'Style','checkbox',...
        'Units','normalized',...
        'FontUnits','pixels',...
        'Callback',@includeinextraction,...        'FontSize',ftsz,...
        'Position',[0.82 0.78 0.04 0.04],...        'String','Include',...
        'TooltipString','Include in extraction',...
        'enable','off',...
        'Value',0);
    
uicontrol(... 
        'Parent',hpanelin,...
        'Units','normalized',...
        'FontUnits','pixels',...
        'HorizontalAlignment','center',...'BackgroundColor','w',...
        'FontSize',ftsz,...
        'Position',[0.02 0.01 0.5 0.07],...
        'String','Spectrum index to extract',...
        'Style','text');
       
hindex2select = uicontrol(...
        'Parent',hpanelin,...
        'Units','normalized',...
        'FontUnits','pixels',...
        'BackgroundColor','w',...
        'Callback',@index2select,...
        'HorizontalAlignment','left',...
        'FontSize',ftsz,...
        'Position',[0.53 0.01 0.4 0.08],...
        'TooltipString',sprintf('Use Matlab style index without [ ] and press enter.\nDelete and press enter to initialize.'),...
        'enable','off',...
        'Style','edit');%timeenable);
    

        
%% output %%%%%%%%%%%%%


uicontrol(... 
        'Parent',hpanelout,...
        'Units','normalized',...
        'FontUnits','pixels',...        
        'HorizontalAlignment','left',...        'BackgroundColor','w',...
        'FontSize',ftsz,...
        'Position',[0.02 0.9 0.75 0.06],...
        'String','Output directory for result files',...
        'Style','text');

hpath2save = uicontrol(...
        'Parent',hpanelout,...
        'Units','normalized',...
        'FontUnits','pixels',...
        'BackgroundColor','w',...  'Callback',@index2select,...
        'HorizontalAlignment','left',...
        'FontSize',ftsz,...
        'Position',[0.02 0.83 0.96 0.06],...
        'Style','text');%timeenable);

% hsamedir=uicontrol('Style','pushbutton','Units','Normalized','pos',[0.35 0.7 0.3 0.1],...'BackgroundColor','w',...
%     'parent',hpanelout,'String','Use same dir.','Callback', {@setpath2save,1},'fontunits','pixels','fontsize',ftsz,...
%     'Tooltipstring','Use same directory as input 2D file.','enable','off');

hbrowse=uicontrol('Style','pushbutton','Units','Normalized','pos',[0.68 0.7 0.3 0.1],...'BackgroundColor','w',...
    'parent',hpanelout,'String','Browse','Callback', @setpath2save,'fontunits','pixels','fontsize',ftsz,'enable','off');



uicontrol(... 
        'Parent',hpanelout,...
        'Units','normalized',...
        'FontUnits','pixels',...        
        'HorizontalAlignment','left',...'BackgroundColor','w',...
        'FontSize',ftsz,...
        'Position',[0.02 0.62 0.4 0.06],...
        'String','Name pattern',...
        'Style','text');

hfileout = uicontrol(...
        'Parent',hpanelout,...
        'Units','normalized',...
        'FontUnits','pixels',...
        'BackgroundColor','w',... 
        'Callback',@newfilenameout,...
        'HorizontalAlignment','left',...
        'FontSize',ftsz,...
        'Position',[0.02 0.55 0.96 0.06],...
        'Style','edit',...
        'enable','off');

uicontrol(... 
        'Parent',hpanelout,...
        'Units','normalized',...
        'FontUnits','pixels',...        
        'HorizontalAlignment','right',...'BackgroundColor','w',...
        'FontSize',ftsz*0.8,...
        'Position',[0.02 0.48 0.96 0.06],...
        'String','NNN : old file name, no extension / # : spectrum number',...
        'Style','text');
    
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
hpanelradioD=uibuttongroup(...
        'Parent',hpanelout,...
        'BorderType','none',...'etchedin',...'none',...
        'Title','',...
        'Position',[0.1 0.02 0.2 0.4],...
        'SelectionChangeFcn',@chooseD);%,...        'SelectionChangeFcn',@visible_or_hide,...'OldSelectedObject',[]);

h1D = uicontrol(...
        'Parent',hpanelradioD,...
        'Style','radiobutton',...
        'Units','normalized',...
        'Position',[0.1 0.7 1 0.1],...
        'String','1D','enable','off',...
        'FontUnits','pixels',...'BackgroundColor','w',...
        'FontSize',ftsz);%,... 'TooltipString','Display the component spectrum');%,...
    
h2D = uicontrol(...
        'Parent',hpanelradioD,...
        'Style','radiobutton',...
        'Units','normalized',...
        'Position',[0.1 0.2 1 0.1],...
        'String','2D','enable','off',...
        'FontUnits','pixels',...'BackgroundColor','w',...
        'FontSize',ftsz);%,... 'TooltipString','Display the component spectrum');%,...

%    % 'Callback',@(hObject,eventdata)SimLabel_componentX_export('visible_Callback',hObject,eventdata,guidata(hObject)),...
%%%%%%%%%%%%%%%%%%%%%%%%%%%

hpanelradio1Dtype=uibuttongroup(...
        'Parent',hpanelout,...'BackgroundColor','m',...
        'BorderType','none',...'etchedin',...
        'Title','',...
        'Position',[0.22 0.24 0.3 0.15],...
        'SelectionChangeFcn',@choosetype);%,...        'SelectionChangeFcn',@visible_or_hide,...'OldSelectedObject',[]);

hsep1 = uicontrol(...
        'Parent',hpanelradio1Dtype,...
        'Style','radiobutton',...
        'Units','normalized',...
        'Position',[0.1 0.7 1 0.3],...
        'String','Separate files','enable','off',...
        'FontUnits','pixels',...'BackgroundColor','w',...
        'FontSize',0.8*ftsz);%,... 'TooltipString','Display the component spectrum');%,...
    
hav1 = uicontrol(...
        'Parent',hpanelradio1Dtype,...
        'Style','radiobutton',...
        'Units','normalized',...
        'Position',[0.1 0.28 1 0.3],...
        'String','Sum (1 file)','enable','off',...
        'FontUnits','pixels',...'..
        'FontSize',0.8*ftsz);%, 'TooltipString','Only one file generated.');%,...
%%%%%%%%%%%%%%%%%%%%%%
hpanelradio2Dtype=uibuttongroup(...
        'Parent',hpanelout,...'BackgroundColor','w',....
        'BorderType','none',...'etchedin',...
        'Title','',...
        'Position',[0.22 0.04 0.3 0.15],...
        'SelectionChangeFcn',@choosetype);%,...        'SelectionChangeFcn',@visible_or_hide,...'OldSelectedObject',[]);

hsep2 = uicontrol(...
        'Parent',hpanelradio2Dtype,...
        'Style','radiobutton',...
        'Units','normalized',...
        'Position',[0.1 0.7 1 0.3],...
        'String','Classical','enable','off',...
        'FontUnits','pixels',...'BackgroundColor','w',...
        'FontSize',0.8*ftsz, 'TooltipString','One 2D file generated.');%,...
    
hav2 = uicontrol(...
        'Parent',hpanelradio2Dtype,...
        'Style','radiobutton',...
        'Units','normalized',...
        'Position',[0.1 0.28 1 0.3],...
        'String','Group spectra','enable','off',...
        'FontUnits','pixels',...'BackgroundColor','w',...
        'FontSize',0.8*ftsz, 'TooltipString','Only available with following index');%,...
    
hnbspc2sum = uicontrol(...
        'Parent',hpanelradio2Dtype,...
        'Units','normalized',...
        'FontUnits','pixels',...
        'BackgroundColor','w',... 
        'Callback',@setnbspc2sum,...
        'HorizontalAlignment','left',...
        'FontSize',0.8*ftsz,...
        'Position',[0.4 0 0.2 0.3],...
        'string','10',...
        'Style','edit',...
        'visible','off',...
        'TooltipString','Amount of Spectra to group (sum)');
    
%%%%%%%%%%%%%%%%%%%%%%%%%%%
hextract=uicontrol('Style','pushbutton','Units','Normalized','pos',[0.73 0.02 0.25 0.2],...'BackgroundColor','w',...
    'parent',hpanelout,'String','Extract','Callback', @extract,'fontunits','pixels','fontsize',ftsz,'FontWeight','bold','enable','on');

hchkASCII = uicontrol(...
        'Parent',hpanelout,...
        'Style','checkbox',...
        'Units','normalized',...
        'FontUnits','pixels',...'Callback',@includeinextraction,...        'FontSize',ftsz,...
        'Position',[0.77 0.27 0.2 0.04],...'backgroundcolor','w',...
        'String','ASCII',...
        'fontsize',ftsz,...
        'TooltipString','To generate ASCII .txt file(s).',...
        'enable','on',...
        'Value',0);

hchkBruker = uicontrol(...
        'Parent',hpanelout,...
        'Style','checkbox',...
        'Units','normalized',...
        'FontUnits','pixels',...'Callback',@includeinextraction,...        'FontSize',ftsz,...
        'Position',[0.77 0.37 0.2 0.04],...'backgroundcolor','w',...
        'String','Bruker',...
        'fontsize',ftsz,...
        'TooltipString','To generate Bruker format file(s).',...
        'enable','on',...
        'Value',0);
    
hdone=uicontrol(... 
        'Parent',hpanelout,...
        'Units','normalized',...
        'FontUnits','pixels',...        
        'HorizontalAlignment','right',...'BackgroundColor','w',...
        'FontSize',ftsz,...
        'ForegroundColor','r',...
        'Position',[0.02 0.02 0.69 0.06],...
        'Style','text',...
        'visible','off');
    
%% initialisation des variables %%%%%%%%%%%%%

file2D=''; %nom du pectre 2D sans extension
path2file2D=''; %chemin du spetre 2D
path2save='';%chemin pour sauvegarde

B=[];%champ magnetique
yinit=[];%signal RPE 2D initial
par2D=[];%structure parametres d'enregistrements
starttime=[]; %s temps de debut d'acquisition de chaque spectre
freq=[];%GHz
acqtime=[];
nbspc=[];%nombre de spectres dans 2D
nbscan=[];%nb de scan par spectre
stepmax=0.1; %pas max du slider
dispindex=1; %indice du spectre affiche
include=0;%indice a inclure ou pas dans l'extraction
%handle d'initialisation
versionyear=version('-date');
versionyear=str2double(versionyear(end-4:end)); %annee version matlab
if versionyear>=2014
        hinit=gobjects; %handle=structure
else
        hinit=NaN; %handle=double
end
hspecdisp=hinit;
unselectcolor=[251 229 214]./255;
selectcolor=[226 240 217]./255;



%% functions of input %%%%%%%%%%%%%

    function get2Dfile(~,~)
       [file2Dexp,path2file2D]=uigetfile('*.YGF','Extract spectra from'); %ouverture boite de dialogue dans repertoire courant 
       if file2Dexp~=0
           set(hfilein,'string',file2Dexp,'TooltipString',fullfile(path2file2D,file2Dexp));
            file2D=file2Dexp(1:end-4); %nom du pectre 2D sans extension
            
            %%%% chargement des données %%%%
            [x,yinit,par2D]=eprload(fullfile(path2file2D,[file2D,'.DSC']));
            B=x{1,1}; %champ corrigé en G
            starttime=x{1,2}; %s temps de debut d'acquisition de chaque spectre
            freq=par2D.MWFQ*1e-9;%GHz
           
            nbscan=par2D.AVGS; %nb de scan/spectre
            while nbscan==0  %si manip arretee avant la fin AVGS=0
                nbscan=str2double(inputdlg(sprintf('Enter the scan number per spectrum:\n(Stop before finishing?)'),'',1,{'1'}));
            end
             acqtime=str2double(par2D.SweepTime(1:end-2))*nbscan; %s temps d'acquisition d'un spectre
            %%% plot
            nbspc=size(yinit,2);
            include=zeros(1,nbspc);
            stepmin=1/nbspc;
            if stepmax<1/nbspc
                stepmax=stepmin;
            end
            set(hslidindex,'value',1,'Max',nbspc,'sliderstep',[stepmin stepmax],'enable','on');
            set([hchk, hindex2select,hbrowse,h1D,h2D,hfileout],'enable','on');
            set(hindex2select,'string','');%init si reload
            set(hslidindex,'value',1);%init si reload
            if get(h1D,'value')%init si reload
                set([hsep1,hav1],'enable','on');
            end
            dispspec %plot spectre 1
            dispfileout
            if isempty(get(hpath2save,'string'))% si ~reload
                path2save=path2file2D;
                set(hpath2save,'string',path2save,'Tooltipstring',path2save);
            end
       end
    end

    function dispspec(~,~)
        if ishandle(hspecdisp)
            delete(hspecdisp);
        end
        dispindex=round(get(hslidindex,'value'));
        hspecdisp=plot(hgraphe,B,yinit(:,dispindex),'k');
        title(hgraphe,[num2str(dispindex),' / ',num2str(nbspc)]);
        ymin=min(yinit(:,dispindex));
        ymax=max(yinit(:,dispindex));
        if ymin==ymax
            ymax=0.9;
            ymin=-0.9;
        end
        set(hgraphe,'xlim',[B(1) B(end)],'ylim',1.1*[ymin ymax],'ytick',tickNaN);
        xlabel('Magnetic Field [G]')
        set(hchk,'value',include(dispindex));
        if include(dispindex)
            set(hgraphe,'color',selectcolor)
        else
            set(hgraphe,'color',unselectcolor)
        end
    end

    function includeinextraction(~,~)
        include(dispindex)=get(hchk,'value');
        set(hindex2select,'string',simplewritring(find(include))); %affichage des indices selectionnes
        if include(dispindex)
            set(hgraphe,'color',selectcolor)
        else
            set(hgraphe,'color',unselectcolor)
        end
    end

    function index2select(~,~)
        
        index2includestr=get(hindex2select,'string');
        include=include*0;

        try 
            
            eval(['include([',index2includestr,'])=1;']);
            eval(['include(setdiff(1:end,[',index2includestr,']))=0;']); %autres spectres non inclus
            %index2include=eval(['[',index2includestr,']']);
            
            set(hindex2select,'string',simplewritring(find(include))); %maj affichage des indices selectionnes
            index2include=find(include);

            if index2include(end)>nbspc
                set(hindex2select,'string','');
            end
     
        catch
            set(hindex2select,'string','');

        end


        set(hchk,'value',include(dispindex));
        if include(dispindex)
            set(hgraphe,'color',selectcolor)
        else
            set(hgraphe,'color',unselectcolor)
        end
    end


    function indexstr=simplewritring(index) % [1 2 3 4] devient '1:4' ie % simplifier ecriture des indices si valeurs se suivent
        indexstr='';
        nbind=numel(index);
        k=1;
        while k<=nbind
            if k+1<nbind && k+2<=nbind
                if (index(k)+1==index(k+1)) && (index(k)+2==index(k+2))
                    n=1;
                    while k+n<=nbind
                        if index(k)+n==index(k+n)
                            n0=n;
                            n=n+1;
                        else
                        	n=nbind;
                        end
                    end
                    indexstr=[indexstr,' ',num2str(index(k)),':',num2str(index(k+n0))];
                    k=k+n0+1;
                else
                    indexstr=[indexstr,' ',num2str(index(k))];
                    k=k+1;
                end
            else
                indexstr=[indexstr,' ',num2str(index(k))];
                k=k+1;
            end

        end
        indexstr=indexstr(2:end);%suppression du 1er espace
    end

%% functions of output %%%%%%%%%%%%%
    function setpath2save(~,~)
        newpath2save=uigetdir(path2file2D);
        if ~isnumeric(newpath2save) %0 cancel
            path2save=newpath2save;
        end
        set(hpath2save,'string',path2save,'tooltipstring',path2save);
    end
 
    function chooseD(~,~) %callback radio choix dimension
       if get(h1D,'value')
           set([hsep1,hav1],'enable','on');
           set([hsep2,hav2],'enable','off');
           set(hnbspc2sum,'visible','off');
       else
           set([hsep1,hav1],'enable','off');
           set([hsep2,hav2],'enable','on');
           if get(hav2,'value')
              set(hnbspc2sum,'visible','on');
           end
       end
        dispfileout
    end

    function choosetype(~,~) %callback radio choix type: separate or average
        dispfileout
        if get(hav2,'value')
           set(hnbspc2sum,'visible','on');
        else
            set(hnbspc2sum,'visible','off');
        end

    end

    function dispfileout %affichage du nom de sortie et maj du tooltip
        if get(h1D,'value')
            if get(hsep1,'value')
                str2disp='NNN_scan#';
            else
                %get(hav1,'value')
                str2disp='NNN_averaged_scans';
            end
        else
           if get(hsep2,'value')
                str2disp='NNN_reduced';
           else
              % get(hav1,'value')
                str2disp=['NNN_grouping',get(hnbspc2sum,'string')];
            end
           
        end
       set(hfileout,'string',str2disp,'tooltipstring',generatefilenameout(str2disp,0));
    end

    function strout=generatefilenameout(str,k)
        %k=0: affichage sur GUI k!=0: nom reel pour sauvegarde
        stroutinit=strrep(str,'NNN',file2D); %remplace variable NNN par le nom du spectre init reste #
        indexofhtag=strfind(stroutinit,'#');
        if k==0
            if isempty(indexofhtag)
                strout=['Output name : ',stroutinit];
            else
                stroutinit(indexofhtag)='2';
                strout=['Output name: ',stroutinit,' (example)'];
            end
        else
            if ~isempty(indexofhtag)
                str2insert=num2str(k); %numero du spectre a inserer dans le nom
                strout=strrep(stroutinit,'#',str2insert);
            else
                strout=stroutinit;
            end
            
        end
    end

    function newfilenameout(~,~) %si nouveau nom de sortie entre a la main
        dispstr=get(hfileout,'string');
        set(hfileout,'string',dispstr,'tooltipstring',generatefilenameout(dispstr,0));
    end


    function setnbspc2sum(~,~)
        num2sum=str2double(get(hnbspc2sum,'string'));
       if ~isnumeric(num2sum) || floor(num2sum)~=num2sum || num2sum==0
            num2sum=10;
            set(hnbspc2sum,'string','10');
       end
       str2disp=['NNN_grouping',num2str(num2sum)];
       set(hfileout,'string',str2disp,'tooltipstring',generatefilenameout(str2disp,0));
     end
%% extraction
    function extract(~,~)
        outputformat=[get(hchkBruker,'value'),get(hchkASCII,'value')];
        if ~isempty(path2save) && sum(include)~=0 && sum(outputformat)>0 %un chemin pour la sauvegarde, des spectres , format de sortie selectionnes
            index2extract=find(include);
            indicateur2D=1; %extraction 2D OK par defaut
%             indicateurBruker2D=0; %sauvegarde Bruker 2D non demandee (pour message)
%             indicateurASCII2D=0; %sauvegarde ASCII 2D non demandee (pour message)

            %%%%%%%%%%%%%%%%%%%%%%%
            %%%%%% 1D %%%%%%%%%%%%%
            %%%%%%%%%%%%%%%%%%%%%%%
            
            if get(h1D,'value')
                
                %%%%%%%%%%%%%% separate %%%%%%%%%%%%%%
                if get(hsep1,'value')
                    for k=index2extract
                        spec=yinit(:,k); %extraction de la colonne index2extract
                        file2create=generatefilenameout(get(hfileout,'string'),k);
                        %%%% sauvegarde format spectro .DSC .DTA %%%%%%%
                        if get(hchkBruker,'value')
                            eprsave(fullfile(path2save,file2create),B,spec,['spectrum ',num2str(k),' extracted from 2D ',file2D],freq)
                            %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                            fid=fopen(fullfile(path2save,[file2create,'.DSC']),'r');
                            fid2=fopen(fullfile(path2save,[file2create,'_temp.DSC']),'w');      

                            %remplacement DATE et TIME
                            while ~feof(fid)
                                s=fgetl(fid);
                                if numel(s)>5 && strcmp(s(1:4),'DATE')
                                    fprintf(fid2,'%s\t%s\n','DATE',par2D.DATE);
                                elseif numel(s)>5 && strcmp(s(1:4),'TIME')
                                    fprintf(fid2,'%s\t%s\n','TIME',datestr((starttime(k)+acqtime)/86400,'HH:MM:SS')); %-datenum(datestr(acqtime/2/86400,'HH:MM:SS'))
                                else
                                    fprintf(fid2,'%s\n',s);
                                end
                            end

                            %ajout nouveaux champs
                            fprintf(fid2,'%s\t%s\n','B0MA',num2str(par2D.B0MA));
                            fprintf(fid2,'%s\t%s\n','AVGS',num2str(nbscan));
                            fprintf(fid2,'%s\t%s\n','MWPW',num2str(par2D.MWPW));
                            fprintf(fid2,'%s\t%s\n','SweepTime',par2D.SweepTime);

                            fclose(fid);
                            fclose(fid2);

                            delete(fullfile(path2save,[file2create,'.DSC']));
                            movefile(fullfile(path2save,[file2create,'_temp.DSC']),fullfile(path2save,[file2create,'.DSC']));
                        end
                        %%% sauvegarde ascii (.txt)  %%%%
                        if get(hchkASCII,'value')
                            fid3=fopen(fullfile(path2save,[file2create,'.txt']),'w');
                            for i=1:numel(B)
                                            fprintf(fid3,'%12.3f\t',B(i)); 
                                            fprintf(fid3,'%12.4e\n',spec(i));
                            end
                            fclose(fid3);
                        end
                        %%%%%%%%%%%%%%%%%%%%%%%%%%
                    end
                end
                                
                
                %%%%%%%%%%%%%% average %%%%%%%%%%%%%%
                if get(hav1,'value')
                    y2Dred=yinit(:,index2extract);
                    y2save=mean(y2Dred,2);
                    file2create=generatefilenameout(get(hfileout,'string'),1);
                    %%% sauvegarde Bruker (.DSC .DTA)  %%%%
                    if get(hchkBruker,'value')
                        eprsave(fullfile(path2save,file2create),B,y2save,['averaged spectra [',get(hindex2select,'string'),'] extracted from 2D ',file2D],freq)
                        %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                        fid=fopen(fullfile(path2save,[file2create,'.DSC']),'r');
                        fid2=fopen(fullfile(path2save,[file2create,'_temp.DSC']),'w'); 
                        while ~feof(fid)
                            s=fgetl(fid);
                             if numel(s)>5 && strcmp(s(1:4),'DATE')
                                fprintf(fid2,'%s\t%s\n','DATE',[s(9:10),'/',s(6:7),'/',s(12:13)]);
            %                 elseif numel(s)>5 && strcmp(s(1:4),'TIME')
            %                     fprintf(fid2,'%s\t%s\n','TIME',datestr((starttime(scan2extract(k))+acqtime)/86400,'HH:MM:SS')); %-datenum(datestr(acqtime/2/86400,'HH:MM:SS'))
                             else
                                fprintf(fid2,'%s\n',s);
                             end
                        end


                        %ajout nouveaux champs
                        fprintf(fid2,'%s\t%s\n','B0MA',num2str(par2D.B0MA));
                        fprintf(fid2,'%s\t%s\n','AVGS',num2str(nbscan));
                        fprintf(fid2,'%s\t%s\n','MWPW',num2str(par2D.MWPW));
                        fprintf(fid2,'%s\t%s\n','SweepTime',par2D.SweepTime);

                        fclose(fid);
                        fclose(fid2);

                        delete(fullfile(path2save,[file2create,'.DSC']));
                        movefile(fullfile(path2save,[file2create,'_temp.DSC']),fullfile(path2save,[file2create,'.DSC']));
                    end
                    %%%% sauvegarde ascii (.txt)  %%%%
                    if get(hchkASCII,'value')
                        fid3=fopen(fullfile(path2save,[file2create,'.txt']),'w');
                        for i=1:numel(B)
                                        fprintf(fid3,'%12.3f\t',B(i)); 
                                        fprintf(fid3,'%12.4e\n',y2save(i));
                        end
                        fclose(fid3);
                    end
                    
                end
            end
            
            
            %%%%%%%%%%%%%%%%%%%%%%%%%
            %%%%%% 2D %%%%%%%%%%%%%
            %%%%%%%%%%%%%%%%%%%%%%%
            
            if get(h2D,'value')
                if numel(index2extract)>1
                    
                    
                    %%%%%%%%%%%%%% classical %%%%%%%%%%%%%%
                    if get(hsep2,'value')
                        %indexstr=get(hindex2select,'string'); %indice à extraire version simplewriting
                        y2Dred=yinit(:,index2extract);
                        file2create=generatefilenameout(get(hfileout,'string'),1);
                         %%%% sauvegarde format spectro .DSC .DTA .YGF %%%%%%%
                        if get(hchkBruker,'value')
                            eprsave(fullfile(path2save,file2create),{B,starttime(index2extract)},y2Dred,['2D experiment extracted from 2D ',file2D,' [',get(hindex2select,'string'),']'],freq)

                            %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                            fid=fopen(fullfile(path2save,[file2create,'.DSC']),'r');
                            fid2=fopen(fullfile(path2save,[file2create,'_temp.DSC']),'w');      

                            %remplacement DATE et TIME
                            while ~feof(fid)
                                s=fgetl(fid);
                                if numel(s)>5 && strcmp(s(1:4),'DATE')
                                    fprintf(fid2,'%s\t%s\n','DATE',par2D.DATE);
                                elseif numel(s)>5 && strcmp(s(1:4),'TIME')
                                    fprintf(fid2,'%s\t%s\n','TIME',par2D.TIME); %idem DSC initial
                                else
                                    fprintf(fid2,'%s\n',s);
                                end
                            end

                            %ajout nouveaux champs
                            fprintf(fid2,'%s\t%s\n','B0MA',num2str(par2D.B0MA));
                            fprintf(fid2,'%s\t%s\n','AVGS',num2str(nbscan));
                            fprintf(fid2,'%s\t%s\n','MWPW',num2str(par2D.MWPW));
                            fprintf(fid2,'%s\t%s\n','SweepTime',par2D.SweepTime);

                            fclose(fid);
                            fclose(fid2);

                            delete(fullfile(path2save,[file2create,'.DSC']));
                            movefile(fullfile(path2save,[file2create,'_temp.DSC']),fullfile(path2save,[file2create,'.DSC']));
                            
%                             fid4=fopen(fullfile(path2save,[file2create,'.YGF']),'r');
%                             if fid4==-1 %le fichier YGF n'existe pas
%                                 fid4=fopen(fullfile(path2save,[file2create,'.YGF']),'w');
%                             end
%                             fclose(fid4);

                        end


                        %%%% sauvegarde ascii (.txt)  %%%%
                        if get(hchkASCII,'value')
                            nbcol=numel(index2extract);
                            nbligne=max([numel(B) numel(starttime(index2extract))]);
                            data=cell(nbligne+1,nbcol+2);%init data: cell array: 1ere ligne nature des donnees, 1ere colonne: B / 2e colonne: temps / 3e colonne et suivantes: spectres
                            data(1,1:2)={'x1','x2'};
                            for i=1:nbcol
                                data(1,i+2)={['data/x1 (',num2str(index2extract(i)),')']};
                            end
                            data(2:numel(B)+1,1)=num2cell(B'); %x1=B 1ere ligne=info
                            data(2:numel(starttime(index2extract))+1,2)=num2cell(starttime(index2extract)); %x2=starttime
                            for i=1:nbcol
                                data(2:numel(B)+1,i+2)=num2cell(y2Dred(:,i)); %x1=B 1ere ligne=info
                            end
                            idx = cellfun(@isempty,data); % Find the indexes of empty cell
                            data(idx) = {' '};

                            fid3=fopen(fullfile(path2save,[file2create,'.txt']),'w');
                             for j=1:nbcol+1
                                   fprintf(fid3,'%13s\t',data{1,j}); 
                            end
                             fprintf(fid3,'%13s\n',data{1,nbcol+2});
                              for i=2:nbligne+1
                                  for j=1:nbcol+1
                                      if isnumeric(data{i,j})
                                         fprintf(fid3,'%13.4e\t',data{i,j});
                                     else
                                        fprintf(fid3,'%13s\t',data{i,j}); %si cellule vide (' ')
                                      end
                                  end
                                 if isnumeric(data{i,nbcol+2})
                                        fprintf(fid3,'%13.4e\n',data{i,nbcol+2});
                                 else
                                        fprintf(fid3,'%13s\n',data{i,nbcol+2}); %si cellule vide (' ')
                                 end
    % 
                              end
                            fclose(fid3);

     %                       indicateurASCII2D=1; %sauvegarde ASCII 2D faite
                        end
                        indicateur2D=1;
                    end
                    
                    
                    %%%%%%%% average: regroupement de spectres %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
                 
                    if get(hav2,'value')
                        for k=1:numel(index2extract)-1 %pour verifier que les indices donnes se suivent
                              testindex(k)=index2extract(k+1)-index2extract(k);
                        end
                        num2sum=str2double(get(hnbspc2sum,'string')); %est bien un entier>0: test dans setnbspc2sum()
                        if isequal(testindex,ones(1,numel(testindex))) && num2sum<=numel(index2extract)/2 
                            %2 indices consecutifs se suivent && au moins 2 sommes intermediaires possibles
                            %y2Dred=yinit(:,index2extract);
                            file2create=generatefilenameout(get(hfileout,'string'),1);    
                            
                            ii=0;
                            for k=index2extract(1):num2sum:index2extract(end)
                                ii=ii+1;
                                if k+num2sum-1<=index2extract(end)
                                    y2Dintersum(:,ii)=sum(yinit(:,k:k+num2sum-1),2);%/num2sum;
                                    timeintersum(ii)=starttime(k);
                                end
                            end
                            
                            
                            %%%% sauvegarde format spectro .DSC .DTA .YGF %%%%%%%
                            if get(hchkBruker,'value')

                                eprsave(fullfile(path2save,file2create),{B,timeintersum},y2Dintersum,['2D experiment extracted from 2D ',file2D,' [grouping spectra ',num2str(num2sum),' by ',num2str(num2sum),']'],freq)
                               
                                %bug eprsave 3e val
                                
                                
                                
                                fid=fopen(fullfile(path2save,[file2create,'.DSC']),'r');
                                fid2=fopen(fullfile(path2save,[file2create,'_temp.DSC']),'w');    

                                %remplacement DATE et TIME
                                while ~feof(fid)
                                    s=fgetl(fid);
                                    if numel(s)>5 && strcmp(s(1:4),'DATE')
                                        fprintf(fid2,'%s\t%s\n','DATE',par2D.DATE);
                                    elseif numel(s)>5 && strcmp(s(1:4),'TIME')
                                        fprintf(fid2,'%s\t%s\n','TIME',par2D.TIME); %idem DSC initial
                                    else
                                        fprintf(fid2,'%s\n',s);
                                    end
                                end

                                %ajout nouveaux champs
                                fprintf(fid2,'%s\t%s\n','B0MA',num2str(par2D.B0MA));

                                fprintf(fid2,'%s\t%s\n','AVGS',num2str(num2sum)); % !!!!!!!!!!

                                fprintf(fid2,'%s\t%s\n','MWPW',num2str(par2D.MWPW));
                                fprintf(fid2,'%s\t%s\n','SweepTime',par2D.SweepTime);%!!!!!!!!!!!

                                fclose(fid);
                                fclose(fid2);

                                delete(fullfile(path2save,[file2create,'.DSC']));
                                movefile(fullfile(path2save,[file2create,'_temp.DSC']),fullfile(path2save,[file2create,'.DSC']));

%                                 fid4=fopen(fullfile(path2save,[file2create,'.YGF']),'r');
%                                 if fid4==-1 %le fichier YGF n'existe pas
%                                     fid4=fopen(fullfile(path2save,[file2create,'.YGF']),'w');
%                                 end
%                                 fclose(fid4);
                                
                                
                            end

                            %%%% sauvegarde ascii (.txt)  %%%%
                            if get(hchkASCII,'value')
                                nbcol=numel(timeintersum);
                                nbligne=max([numel(B) numel(timeintersum)]);
                                data=cell(nbligne+1,nbcol+2);%init data: cell array: 1ere ligne nature des donnees, 1ere colonne: B / 2e colonne: temps / 3e colonne et suivantes: spectres
                                data(1,1:2)={'x1','x2'};
                                for i=1:nbcol
                                    data(1,i+2)={['data/x1 (',num2str(i),')']};
                                end
                                data(2:numel(B)+1,1)=num2cell(B'); %x1=B 1ere ligne=info
                                data(2:numel(timeintersum)+1,2)=num2cell(timeintersum); %x2=starttime
                                for i=1:nbcol
                                    data(2:numel(B)+1,i+2)=num2cell(y2Dintersum(:,i)); %x1=B 1ere ligne=info
                                end
                                idx = cellfun(@isempty,data); % Find the indexes of empty cell
                                data(idx) = {' '};

                                fid3=fopen(fullfile(path2save,[file2create,'.txt']),'w');
                                 for j=1:nbcol+1
                                       fprintf(fid3,'%13s\t',data{1,j}); 
                                end
                                 fprintf(fid3,'%13s\n',data{1,nbcol+2});
                                  for i=2:nbligne+1
                                      for j=1:nbcol+1
                                          if isnumeric(data{i,j})
                                             fprintf(fid3,'%13.4e\t',data{i,j});
                                         else
                                            fprintf(fid3,'%13s\t',data{i,j}); %si cellule vide (' ')
                                          end
                                      end
                                     if isnumeric(data{i,nbcol+2})
                                            fprintf(fid3,'%13.4e\n',data{i,nbcol+2});
                                     else
                                            fprintf(fid3,'%13s\n',data{i,nbcol+2}); %si cellule vide (' ')
                                     end
        % 
                                  end
                                fclose(fid3);

                            end

                        else
                            indicateur2D=0; %extraction 2D non faite
                        end

                    end
                else
                     indicateur2D=0; %extraction 2D non faite
                end
            end
            if indicateur2D %sauvegarde 2D OK par defaut
                set(hdone,'visible','on','string','Done!')
            else
                set(hdone,'visible','on','string','Not done: bad index!')
            end                
         
            pause(2)
            set(hdone,'visible','off')
            clear data
            
            
        else
            set(hdone,'visible','on','string','Information is missing.')
            pause(2)
            set(hdone,'visible','off');
        end
        
    end

end