function checkcurie
% exctraction automatique d'une courbe de curie (AT=f(T)) a partir des spectres
% d'un dossier, sur raie derivee (default), positive ou negative.
% normalisation automatique / nb de scan,amplitude de modulation, gain
% recepteur temps de conversion et puissance
% Ajustement possible des amplitudes trouvees automatiquement.
% sauvegarde de la courbe
% !!!! pas de vérification des largeurs !!!!
% tempertaure dans le titre: XXK (majuscule)
% EE jan 2021
% EE pas de menu
% EE jan2022: sauvegarde figure en tif plutot que bmp
% EE avr2023: pbl plage des sliders
% EE oct2025: compatibilite avec Matlab2025

clear;close;clc;

%version easyspin
try
    easyinfo=easyspin; %seult a partir de  easyspin 6.0.0
    easyversion=str2double(easyinfo.Version(1));
catch 
    easyversion=5; %avant easyspin 6.0.0
end

%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

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


linetype={'Derivative';'Positive';'Negative'}; 
linetypeval=[]; %default
htitcurve=hinit; %handle courbe titrage
hcurrent=hinit; %handle du point rouge du point de la courbe  correspondant au spectre courant
hline=hinit; %handle de la ligne horizontale de l'amplitude du as prep
htext=hinit; %handle du texte 'As Prep.'
hLF=hinit; %handle rectangle bruit bas champ
hHF=hinit; %handle rectangle bruit haut champ
hsig=hinit; %handle rectangle signal
h_linesup=hinit; %handle ligne superieure
h_lineinf=hinit; %handle ligne inferieure
hlinetype=hinit; %handle popup menu

%tdelay=0; %init delay (s)

%% chargement des donnees
chemin=pwd;%uigetdir(pwd); % chemin du repertoire contenant les fichiers des spectres
dir_struct_mat=dir(fullfile(chemin,'*.mat')); % structure contenant le nom de fichier.mat 
reload=false; %par defaut nouveau chargement
if ~isempty(dir_struct_mat) 
    choice = questdlg('Do you want to load previously processed data?','','Yes','No','Yes');          
    switch choice
      case 'Yes'
          if numel(dir_struct_mat)==1
              file2load=dir_struct_mat.name;
          else
              file2load=uigetfile(fullfile(chemin,'*.mat'),'Select previously processed data to Open');
          end
          if not(isnumeric(file2load)) %no cancel;
            load(file2load);
            reload=true;
            disp(['Load ',file2load]);
            nbspec=numel(data);
          end
    end
   
end
if ~reload    
        dir_struct=dir(fullfile(chemin,'*.DSC')); % structure contenant les noms de fichier.DSC  
        nbspec=numel(dir_struct);
        if nbspec>1
        for k=1:nbspec
            data(k).name=dir_struct(k,1).name;%nom du fichier
            [B,spec,par]=eprload(fullfile(chemin,data(k).name));
            data(k).B=B/10;%B en mT
            MA=par.B0MA;%amplitude de modulation (T)
            nbsc=par.AVGS;%nb de scan
            RG=par.RCAG; %gain récepteur(dB)
    	    ST=par.SPTP; %sample time=conversion time (s)
            PWR=par.MWPW; %puissance (W)
            data(k).spec=spec/MA/nbsc/ST*10^(-RG/20)/sqrt(PWR);%normalisation du signal par nb de scan, amplitude de modulation, gain récepteur, temps de conversion, sqrt(puissance)

                %extraction de la temperature, 
            titre=par.TITL;
            posmV=strfind(titre,'K '); %position du 'K'
            if isempty(posmV) %pas de temperature: spectre ignore
                data(k).Temp=NaN; 
                disp(['INFO.: ',data(k).name(1:end-4),' is ignored (no temperature found in the title).']);
            else
                titre1=titre(1:posmV-1); %titre avant 'K'

                posspace=strfind(titre1,' '); %position du ou des espaces dans chaine titre1
                data(k).Temp=str2double(titre1(posspace(end)+1:end)); %temperature (K)
            end

%             %extraction du n° tube et n° spectre
%             pos_=strfind(data(k).name,'_');%position du '_' dans nom de fichier genre 15A12_06.DSC 
%             data(k).tube=data(k).name(pos_-2:pos_-1); %numero du tube
%             data(k).numspec=data(k).name(pos_+1:pos_+2); %numero du spectre 

            pasB=data(k).B(2)-data(k).B(1);%pas du champ
            data(k).B1min=floor(data(k).B(1))+pasB;%plage de champ pour tenir compte du bruit (bas champ)
            data(k).B1max=floor(data(k).B(1))+pasB;

            [data(k).imin1,data(k).imax1]=getindex([data(k).B1min data(k).B1max],k); %indice pour plage bas champ 

            data(k).B2min=floor(data(k).B(end));%plage de champ pour tenir compte du bruit (haut champ)
            data(k).B2max=floor(data(k).B(end));
            [data(k).imin2,data(k).imax2]=getindex([data(k).B2min data(k).B2max],k); %indice pour plage haut champ 

            data(k).Bsmin=floor(data(k).B(1)+(data(k).B(end)-data(k).B(1))/4);%plage de champ du signal
            data(k).Bsmax=floor(data(k).B(1)+3*(data(k).B(end)-data(k).B(1))/4);
            [data(k).imins,data(k).imaxs]=getindex([data(k).Bsmin data(k).Bsmax],k); %indice pour plage du signal 

            data(k).ysup=posline(k,'sup'); %ordonnee ligne superieure
            data(k).yinf=posline(k,'inf'); %ordonnee ligne inferieure
            if isnan(data(k).Temp)
                data(k).amp=NaN;
            else
                data(k).amp=data(k).ysup-data(k).yinf;
            end
            
        %     if data(k).amp==0
        %         data(k).amp=max(spec)-min(spec);
        %     end
            clear B spec par MA nbsc RG ST titre titre1 posspace PWR
        end

        else
                error('No data...');

        end
        [~,order]=sort([data(:).Temp]); %ordonner selon potentiels croissants (si NaN, a la fin)
        data=data(order);
      
end

if not(isnumeric(chemin)) %no cancel;

%% figure 
hsatmain=figure(1);
scrszpix = get(0,'ScreenSize'); %taille ecran [left, bottom, width, height] en pixels
%scrszcm=scrszpix/get(0,'screenpixelsperinch')*2.54; %1inch=2.54cm  taille ecran en cm

set(hsatmain,'Units','pixels','Outerposition',...    
    [scrszpix(3)/3 0.2*scrszpix(4) 1000 scrszpix(4)*0.8],...
    'Name','Curie Check','Menubar', 'none', 'Toolbar', 'none',...%'resize','off',...
    'NumberTitle','off',...'DoubleBuffer','on',...'CloseRequestFcn',@closeSimLabel,...
    'color',get(0,'DefaultUicontrolBackgroundColor'));

%         %%%% pour ne garder que les outils zoomin, zoomout et main
% hToolbar = findall(hsatmain,'tag','FigureToolBar'); %handle toolbar
% halltoolbar=allchild(hToolbar);%tous les handles de la toolbar
% hzoomin=findall(halltoolbar,'TooltipString','Zoom In');
% hzoomout=findall(halltoolbar,'TooltipString','Zoom Out');
% hhand=findall(halltoolbar,'TooltipString','Pan');
% halltoolbar(halltoolbar==hzoomin)=[];%supprime 1 handle a conserver
% halltoolbar(halltoolbar==hzoomout)=[];%supprime 1 handle a conserver
% halltoolbar(halltoolbar==hhand)=[];%supprime 1 handle a conserver
% set(halltoolbar,'visible','off')

%%% graphes spectres exp %%%
hspecaxes=axes('parent',hsatmain,'Position',[0.01 0.33 0.58 0.64],...
                'Box','on');
hslidsup=uicontrol('Style','slider','Units','Normalized','pos',[0.595 0.84 0.02 0.13],'BackgroundColor',[0.9 0.9 0.9],...
    'parent',hsatmain,'String',num2str(0),'Callback', @slidsup,'TooltipString','Adjust up line for amplitude extraction','SliderStep',[0.1/40 1/40]);%'fontunits','pixels','fontsize',ftsz,...
   % 'Min',-20,'Max',+20);%,'Value',0,'SliderStep',[0.1/40 1/40]);
   
hslidinf=uicontrol('Style','slider','Units','Normalized','pos',[0.595 0.33 0.02 0.13],'BackgroundColor',[0.9 0.9 0.9],...
    'parent',hsatmain,'String',num2str(0),'Callback', @slidinf,'TooltipString','Adjust bottom line for amplitude extraction','SliderStep',[0.1/40 1/40]);



%%% graphes courbe de saturation => Curie %%%
hsataxes=axes('parent',hsatmain,'Position',[0.64 0.5 0.35 0.47],...
                'Ytick',tickNaN,'Box','on');%,'Xtick',tickNaN);

   
%%% liste des spectres experimentaux
hlist=uicontrol('Style','listbox','Units','Normalized','pos',[0.64 0.01 0.35 0.38],...
    'parent',hsatmain,'max',1,'min',0,'Callback',@dispexp,'fontunits','pixels',...'fontsize',ftsz,...
    'backgroundcolor','w','string',{data(:).name},'value',1,'fontsize',13);
if reload
    str2disp=['Previously saved data = ',file2load];
else
    out=regexp(chemin,filesep,'split');%pour separer les disques et dossiers du chemin et n'afficher que le dernier
        str2disp=['Directory of data = ',out{end}];
end

hpath=uicontrol('Style','text','Units','Normalized','pos',[0.64 0.40 0.35 0.02],...
    'parent',hsatmain,'String',str2disp,'HorizontalAlignment','center','tooltipstring',chemin);


        
%%% panel noise
hpanelnoise = uipanel('Parent',hsatmain,'FontWeight','bold','Title','Noise',...
        'Position',[0.02 0.12 0.35 0.15],'Units','Normalized',...
        'FontUnits','pixels','FontSize',16,'FontWeight','bold');
    %low field
uicontrol('Style','text','Units','Normalized','pos',[0.05 0.7 0.33 0.2],...'BackgroundColor','w',....
    'parent',hpanelnoise,'String','Low Field: from','HorizontalAlignment','center','fontsize',11);
hB1min=uicontrol('Parent',hpanelnoise,...
        'Units','normalized',...
        'FontUnits','pixels',...
        'BackgroundColor','w',...
        'Callback',@dispnoiserange,...
        'FontSize',13,'foregroundcolor','b',...
        'Position',[0.39 0.69 0.15 0.21],...
        'Style','edit',...
    'TooltipString','No noise in the considered range if min=max.');
uicontrol('Style','text','Units','Normalized','pos',[0.54 0.7 0.15 0.2],...'BackgroundColor','w',....
    'parent',hpanelnoise,'String','mT to','HorizontalAlignment','center','fontsize',11);    
hB1max=uicontrol('Parent',hpanelnoise,...
        'Units','normalized',...
        'FontUnits','pixels',...
        'BackgroundColor','w',...
        'Callback',@dispnoiserange,...
        'FontSize',13,'foregroundcolor','b',...
        'Position',[0.69 0.69 0.15 0.21],...
        'Style','edit',...
        'TooltipString','No noise in the considered range if min=max.');
uicontrol('Style','text','Units','Normalized','pos',[0.84 0.7 0.1 0.2],...'BackgroundColor','w',....
    'parent',hpanelnoise,'String','mT','HorizontalAlignment','center','fontsize',11);    

    %high field
uicontrol('Style','text','Units','Normalized','pos',[0.05 0.25 0.33 0.2],...'BackgroundColor','w',....
    'parent',hpanelnoise,'String','High Field: from','HorizontalAlignment','center','fontsize',11);
hB2min=uicontrol('Parent',hpanelnoise,...
        'Units','normalized',...
        'FontUnits','pixels',...
        'BackgroundColor','w',...
        'Callback',@dispnoiserange,...
        'FontSize',13,'foregroundcolor','b',...
        'Position',[0.39 0.24 0.15 0.21],...
        'Style','edit',...
    'TooltipString','No noise in the considered range if min=max.');
uicontrol('Style','text','Units','Normalized','pos',[0.54 0.25 0.15 0.2],...'BackgroundColor','w',....
    'parent',hpanelnoise,'String','mT to','HorizontalAlignment','center','fontsize',11);    
hB2max=uicontrol('Parent',hpanelnoise,...
        'Units','normalized',...
        'FontUnits','pixels',...
        'BackgroundColor','w',...
        'Callback',@dispnoiserange,...
        'FontSize',13,'foregroundcolor','b',...
        'Position',[0.69 0.24 0.15 0.21],...
        'Style','edit',...
        'TooltipString','No noise in the considered range if min=max.');
uicontrol('Style','text','Units','Normalized','pos',[0.84 0.25 0.1 0.2],...'BackgroundColor','w',....
    'parent',hpanelnoise,'String','mT','HorizontalAlignment','center','fontsize',11);  


%%% panel signal
hpanelsignal = uipanel('Parent',hsatmain,'FontWeight','bold','Title','Signal',...
        'Position',[0.38 0.12 0.25 0.15],'Units','Normalized',...
        'FontUnits','pixels','FontSize',16,'FontWeight','bold');

uicontrol('Style','text','Units','Normalized','pos',[0.1 0.7 0.2 0.2],...'BackgroundColor','w',....
    'parent',hpanelsignal,'String','From','HorizontalAlignment','center','fontsize',11);
hBsmin=uicontrol('Parent',hpanelsignal,...
        'Units','normalized',...
        'FontUnits','pixels',...
        'BackgroundColor','w',...
        'Callback',@dispnoiserange,...
        'FontSize',13,'foregroundcolor',[0 0.7 0],...
        'Position',[0.34 0.69 0.15 0.21],...
        'Style','edit');
uicontrol('Style','text','Units','Normalized','pos',[0.49 0.7 0.2 0.2],...'BackgroundColor','w',....
    'parent',hpanelsignal,'String','mT to','HorizontalAlignment','center','fontsize',11);    
hBsmax=uicontrol('Parent',hpanelsignal,...
        'Units','normalized',...
        'FontUnits','pixels',...
        'BackgroundColor','w',...
        'Callback',@dispnoiserange,...
        'FontSize',13,'foregroundcolor',[0 0.7 0],...
        'Position',[0.69 0.69 0.15 0.21],...
        'Style','edit');
uicontrol('Style','text','Units','Normalized','pos',[0.84 0.7 0.1 0.2],...'BackgroundColor','w',....
    'parent',hpanelsignal,'String','mT','HorizontalAlignment','center','fontsize',11);    


hlinetype=uicontrol(...
        'Parent',hpanelsignal,...
        'FontUnits','pixels',...
        'FontSize',13,...
        'BackgroundColor','w',...
        'Units','normalized',...
        'Callback',@setlinetype,...
        'Position',[0.2 0.2 0.35 0.3],...[0.2 0.25 0.35 0.15],...
        'String',linetype,...
        'Style','popupmenu');%,...
        %'Value',1);

if isempty(linetypeval)
    linetypeval=1;
    disp('The signal type is unknown. The default one is indicated (Derivative) and could be wrong.');
end
set(hlinetype,'value',linetypeval);        
        
uicontrol('Style','text','Units','Normalized','pos',[0.55 0.2 0.15 0.3],...'BackgroundColor','w',....
    'parent',hpanelsignal,'String','line','HorizontalAlignment','center','fontsize',11); 


uicontrol('Style','pushbutton','String','Send to all spectra','Units','Normalized','HorizontalAlignment','center',...
    'pos',[0.02 0.05 0.1 0.05],'parent',hsatmain,'Callback', @sent,...
    'fontunits','pixels','fontsize',11);

uicontrol('Style','pushbutton','String','Save data','Units','Normalized','HorizontalAlignment','center',...
    'pos',[0.3 0.05 0.1 0.05],'parent',hsatmain,'Callback', @savesat,...
    'fontunits','pixels','fontsize',11);


%%% + et -

uicontrol('Style', 'pushbutton', 'String', 'Down','Units','Normalized','Position', [0.59 0.01 0.05 0.05],...
    'parent',hsatmain,'Callback',{@plus_or_minus_fctn,'+'},'tooltipstring','Change spectrum');
uicontrol('Style', 'pushbutton', 'String', 'Up','Units','Normalized','Position', [0.59 0.06 0.05 0.05],...
    'parent',hsatmain,'Callback', {@plus_or_minus_fctn,'-'},'tooltipstring','Change spectrum');

pause(0.01)
dispexp(hlist)

end

%%
function dispexp(hobject,~) %affichage spectre  
    rang=get(hobject,'value'); %numero du spectre dans la liste
    
    hspec=plot(hspecaxes,data(rang).B,data(rang).spec,'k','linewidth',2);
    set(hspecaxes,'xlim',[data(rang).B(1) data(rang).B(end)],'Ytick',tickNaN,...
    'ylim',1.1*[min(data(rang).spec) max(data(rang).spec)]);
    xlabel(hspecaxes,'Magnetic Field [mT]');
    
    
    set(hB1min,'string',num2str(data(rang).B1min));
    set(hB1max,'string',num2str(data(rang).B1max));
    set(hB2min,'string',num2str(data(rang).B2min));
    set(hB2max,'string',num2str(data(rang).B2max));
    set(hBsmin,'string',num2str(data(rang).Bsmin));
    set(hBsmax,'string',num2str(data(rang).Bsmax));
    %set(hlinetype,'value',data(rang).linetypeval);
    
    %rectangles pour bruit et signal
    hLF=disprect('B1',rang); %noise low field
    hHF=disprect('B2',rang); %noise high field
    hsig=disprect('Bs',rang); %signal
    
    %lines pour extraction amplitude
    [imins,imaxs]=getindex([data(rang).Bsmin data(rang).Bsmax],rang);
    h_linesup=line([data(rang).B(imins) data(rang).B(imaxs)],data(rang).ysup*[1 1],'color','m','parent',hspecaxes);
    h_lineinf=line([data(rang).B(imins) data(rang).B(imaxs)],data(rang).yinf*[1 1],'color','m','parent',hspecaxes);

    %init sliders
    maxrange=max(data(rang).spec(imins:imaxs));
    minrange=min(data(rang).spec(imins:imaxs));
    set(hslidsup,'value',data(rang).ysup,'max',maxrange+0.4*sign(maxrange)*maxrange,'min',minrange);
    set(hslidinf,'value',data(rang).yinf,'max',maxrange,'min',minrange-0.4*sign(minrange)*minrange);

    if isnan(data(rang).Temp)
        pot2disp='no temperature';
    else
        pot2disp=[num2str(data(rang).Temp),' K'];
    end
    title(hspecaxes,[pot2disp,' / Amp.*Temp. = ',num2str(data(rang).amp*data(rang).Temp,'%3.2e')]);
%pause
    dispsat() %affichage courbe de saturation => cinetique
end

function dispsat() %affichage courbe de saturation => AT=f(T)
    if ishandle(htitcurve)
        delete(htitcurve)
    end
    if ishandle(hcurrent)
        delete(hcurrent)
    end
    if ishandle(hline)
        delete(hline)
        delete(htext);
    end
    
    htitcurve=plot([data.Temp],[data.amp].*[data.Temp],'ob','parent',hsataxes);hold on
    set(htitcurve,'ButtonDownFcn',@MouseleftclicksatCllbck);
    xlabel('T [K]');
    ylabel('EPR Amp.*T [a.u.]');
    title('A*T=f(T)');    
    % point du spectre courant en rouge
    rang=get(hlist,'value');
    hcurrent=plot(data(rang).Temp,data(rang).amp*data(rang).Temp,'ob','MarkerFaceColor','m');
    
%     %ligne horizontale: amplitude du as prep
%     rangasprep=find(isnan([data(:).E]), 1);
%     rangeE=get(hsataxes,'xlim');
%     rangeamp=get(hsataxes,'ylim');
%     if ~isempty(rangasprep)
%         hline=plot(rangeE,[1 1]*data(rangasprep).amp,':k');
%         htext=text(rangeE(1)+0.1*(rangeE(2)-rangeE(1)),data(rangasprep).amp+0.02*(rangeamp(2)-rangeamp(1)),'As Prep.'); 
%     end
%     if rang==rangasprep
%         set(hline,'color','m','linewidth',2);
%         set(htext,'color','m');
%     end
end

function [imin,imax]=getindex(rangeB,rang) %recherche des indices de la plage de champ à considérer 
    i=1;

    while data(rang).B(i)<rangeB(1)
        i=i+1;
    end;
    imin=i;
    while data(rang).B(i)<rangeB(2)
        i=i+1;
    end;
    imax=i;
end

function dispnoiserange(~,~) %callback des edit des plages de champ pour bruit et signal
    if ishandle(hLF)
        delete(hLF)
    end
    if ishandle(hHF)
        delete(hHF)
    end
    if ishandle(hsig)
        delete(hsig)
    end
    if ishandle(h_linesup)
        delete(h_linesup)
    end
    if ishandle(h_lineinf)
        delete(h_lineinf)
    end
    rang=get(hlist,'value');
    data(rang).B1min=str2double(get(hB1min,'string'));%plage de champ pour tenir compte du bruit (bas champ)
    data(rang).B1max=str2double(get(hB1max,'string'));
    [data(rang).imin1,data(rang).imax1]=getindex([data(rang).B1min data(rang).B1max],rang); %indice pour plage bas champ 

    data(rang).B2min=str2double(get(hB2min,'string'));%plage de champ pour tenir compte du bruit (haut champ)
    data(rang).B2max=str2double(get(hB2max,'string'));
    [data(rang).imin2,data(rang).imax2]=getindex([data(rang).B2min data(rang).B2max],rang); %indice pour plage haut champ 
   
    data(rang).Bsmin=str2double(get(hBsmin,'string'));%plage de champ du signal
    data(rang).Bsmax=str2double(get(hBsmax,'string'));
   [data(rang).imins,data(rang).imaxs]=getindex([data(rang).Bsmin data(rang).Bsmax],rang); %indice pour plage du signal 

     %rectangles pour bruit et signal
    hLF=disprect('B1',rang); %noise low field
    hHF=disprect('B2',rang); %noise high field
    hsig=disprect('Bs',rang); %signal

    
    %maj
    data(rang).ysup=posline(rang,'sup'); %ordonnee ligne superieure
    data(rang).yinf=posline(rang,'inf'); %ordonnee ligne inferieure
    data(rang).amp=data(rang).ysup-data(rang).yinf;
        
    %lines pour extraction amplitude
    [imins,imaxs]=getindex([data(rang).Bsmin data(rang).Bsmax],rang);
    h_linesup=line([data(rang).B(imins) data(rang).B(imaxs)],data(rang).ysup*[1 1],'color','m','parent',hspecaxes);
    h_lineinf=line([data(rang).B(imins) data(rang).B(imaxs)],data(rang).yinf*[1 1],'color','m','parent',hspecaxes);
    % maj sliders
    set(hslidsup,'value',data(rang).ysup);
    set(hslidinf,'value',data(rang).yinf);
    
    
    dispsat() %affichage courbe de saturation => courbe de titrage
end

function h=disprect(fieldB,rang) %affichage des rectangles pour visu des plages
    [imin,imax]=getindex([data(rang).([fieldB,'min']) data(rang).([fieldB,'max'])],rang);
    if imin==imax
        amp=max(data(rang).spec)-min(data(rang).spec);
        pos=[data(rang).([fieldB,'min']) -amp/10 0.01 amp/5];
    else
        amp=max(data(rang).spec(imin:imax))-min(data(rang).spec(imin:imax));
        pos=[data(rang).([fieldB,'min']) min(data(rang).spec(imin:imax))...
             data(rang).([fieldB,'max'])-data(rang).([fieldB,'min'])...
             amp];
    end
    switch fieldB
        case 'B1'
            color='b';
        case 'B2'
            color='b';
        case 'Bs'
            color=[0 0.7 0];
            graphe_lim=get(hspecaxes,'Ylim');
            pos([2 4])= [0.95*graphe_lim(1) 0.95*(graphe_lim(2)-graphe_lim(1))];
        
    end
    
    h=rectangle('parent',hspecaxes,'position',pos,'Edgecolor',color);
end

function y=posline(rang,arg) %ordonnee de  line arg='sup' ou 'inf'
        amp_bruit1=NaN; %amplitude bruit bas champ
        std1=NaN; %deviation standard bruit bas champ
        amp_bruit2=NaN; %amplitude bruit haut champ
        std2=NaN; %deviation standard bruit haut champ
        if data(rang).B1min~=data(rang).B1max %noise a bas champ
            maxbruit1=max(data(rang).spec(data(rang).imin1:data(rang).imax1));
            minbruit1=min(data(rang).spec(data(rang).imin1:data(rang).imax1));
            amp_bruit1=maxbruit1-minbruit1;
            std1=std(data(rang).spec(data(rang).imin1:data(rang).imax1));
        end
        if data(rang).B2min~=data(rang).B2max %noise a haut champ
            maxbruit2=max(data(rang).spec(data(rang).imin2:data(rang).imax2));
            minbruit2=min(data(rang).spec(data(rang).imin2:data(rang).imax2));
            amp_bruit2=maxbruit2-minbruit2;
            std2=std(data(rang).spec(data(rang).imin2:data(rang).imax2));
        end
        if ishandle(hlinetype)
            linetypeval=get(hlinetype,'value');
        else 
            linetypeval=1; %par defaut derivative line
        end
        switch arg
            case 'sup' %ordonnee superieur
                if linetypeval==3 %raie negative
                    y=0;
                else
                    maxspec=max(data(rang).spec(data(rang).imins:data(rang).imaxs));
                    % amplitude moyenne bruit
                    amp_bruit_all=[amp_bruit1 amp_bruit2];
                    amp_bruit_all(isnan(amp_bruit_all))=[]; %supprime les NaN
                    amp_bruit=mean(amp_bruit_all); %NaN si isempty(amp_bruit)
                    if isnan(amp_bruit) 
                        amp_bruit=0;
                    end
                    % deviation standard moyenne bruit
                    std_bruit_all=[std1 std2];
                    std_bruit_all(isnan(std_bruit_all))=[]; %supprime les NaN
                    std_bruit=mean(std_bruit_all); %NaN si isempty(std_bruit)
                    if isnan(std_bruit)
                        std_bruit=0;
                    end
                     y=maxspec-mean([amp_bruit/2 std_bruit]);
                end
                
            case 'inf' %ordonnee inferieur
                if linetypeval==2 %raie positive
                    y=0;
                else
                    minspec=min(data(rang).spec(data(rang).imins:data(rang).imaxs));
                    % amplitude moyenne bruit
                    amp_bruit_all=[amp_bruit1 amp_bruit2];
                    amp_bruit_all(isnan(amp_bruit_all))=[]; %supprime les NaN
                    amp_bruit=mean(amp_bruit_all); %NaN si isempty(amp_bruit)
                    if isnan(amp_bruit) 
                        amp_bruit=0;
                    end
                    % deviation standard moyenne bruit
                    std_bruit_all=[std1 std2];
                    std_bruit_all(isnan(std_bruit_all))=[]; %supprime les NaN
                    std_bruit=mean(std_bruit_all); %NaN si isempty(std_bruit)
                    if isnan(std_bruit)
                        std_bruit=0;
                    end
                     y=minspec+mean([amp_bruit/2 std_bruit]);
               
                end
                
        end
                
end

function slidsup(hObject,~)
    rang=get(hlist,'value');
    data(rang).ysup=get(hObject,'value');
    data(rang).amp=abs(data(rang).ysup-data(rang).yinf);
    dispexp(hlist)
end

function slidinf(hObject,~)
    rang=get(hlist,'value');
    data(rang).yinf=get(hObject,'value');
    data(rang).amp=abs(data(rang).ysup-data(rang).yinf);
    dispexp(hlist)
end


function sent(~,~)
    rang=get(hlist,'value');
    for n=1:nbspec
        data(n).B1min=data(rang).B1min;%plage de champ pour tenir compte du bruit (bas champ)
        data(n).B1max=data(rang).B1max;
        data(n).imin1=data(rang).imin1;
        data(n).imax1=data(rang).imax1; %indice pour plage bas champ 

        data(n).B2min=data(rang).B2min;%plage de champ pour tenir compte du bruit (haut champ)
        data(n).B2max=data(rang).B2max;
        data(n).imin2=data(rang).imin2;
        data(n).imax2=data(rang).imax2; %indice pour plage haut champ 

        data(n).Bsmin=data(rang).Bsmin;%plage de champ du signal
        data(n).Bsmax=data(rang).Bsmax;
        data(n).imins=data(rang).imins;
        data(n).imaxs=data(rang).imaxs; %indice pour plage du signal 

        data(n).ysup=posline(n,'sup'); %ordonnee ligne superieure
        data(n).yinf=posline(n,'inf'); %ordonnee ligne inferieure
        data(n).amp=data(n).ysup-data(n).yinf;
    end
    
    %dispsat()
    dispexp(hlist)
end

function savesat(~,~)
    %%% sauvegarde fichier txt
 
    [fnametxt,path2save]=uiputfile(fullfile(chemin,'*.txt'));
  if ~isnumeric(fnametxt) %no cancel
    fid=fopen(fullfile(path2save,fnametxt),'w');
    fprintf(fid,'%8s\t','T');
%     fprintf(fid,'%6s\t','Tube');
%     fprintf(fid,'%6s\t','Record');
    fprintf(fid,'%12s\t','Amplitude');
    fprintf(fid,'%12s\n','File name');
    fprintf(fid,'%8s\t','[K]');
    fprintf(fid,'%6s\t','[ ]');
    fprintf(fid,'%6s\t','[ ]');
    fprintf(fid,'%12s\t','[ ]');
    fprintf(fid,'%12s\n','[ ]');
    for i=1:nbspec
        taillename(i)=numel(data(i).name);
    end
    maxname=max(taillename);
    for i=1:nbspec
        if isnan(data(i).Temp)
            fprintf(fid,'%8s\t','unknown'); %potentiel
        else
            fprintf(fid,'%8.0f\t',data(i).Temp); %potentiel
        end
        %fprintf(fid,'%6s\t',data(i).tube); %tube
        %fprintf(fid,'%6s\t',data(i).numspec); %numero du spectre 
        fprintf(fid,'%12.5e\t',data(i).amp);
        fprintf(fid,['%',num2str(maxname),'s\n'],data(i).name);
    end
    fclose(fid);
    
    % save plot
    figure2save=figure;%(max(findobj('type','figure'))+1); %pour ne pas superposer des figures 
    set(figure2save,'Units','pixels','Name','Kinetic','NumberTitle','on','visible','on',...
            'Position',[300 300 400 400],'Menubar', 'figure','Toolbar', 'figure');
    hnew=copyobj(hsataxes,figure2save);%graphe(=axes)+legend copier dans nouvelle figure
    set(hnew,'units','normalized','position',[0.15 0.12 0.8 0.8])%,...
    title(hnew,['AT=f(T): ',fnametxt(1:end-4)],'interpreter','none');
    
    hcircle=findobj(hnew,'MarkerFaceColor','m');
    hlinem=findobj(hnew,'Color','m');
    if ishandle(hcircle)
        set(hcircle,'MarkerFaceColor','none');
    end
    if ishandle(hlinem)
        set(hlinem,'Color','k');
    end
    
    
    set(figure2save,'visible','on');
    saveas(figure2save,fullfile(path2save,[fnametxt(1:end-3),'tif']));
    saveas(figure2save,fullfile(path2save,[fnametxt(1:end-3),'fig']));
    delete(figure2save);
    
    %save data
    save(fullfile(path2save,[fnametxt(1:end-3),'mat']),'data','linetypeval');%,'tdelay');
  end
end

function setlinetype(~,~)
      for n=1:nbspec
          data(n).ysup=posline(n,'sup'); %ordonnee ligne superieure
          data(n).yinf=posline(n,'inf'); %ordonnee ligne inferieure
          data(n).amp=data(n).ysup-data(n).yinf;
      end
      dispexp(hlist);

end

function plus_or_minus_fctn(~,~,strsign) %strsign='+' ou '-'
    rang=get(hlist,'value');
   switch strsign
       case '+'
           if rang~=nbspec
               rang=rang+1;
           end         
           
       case '-'
           if rang~=1
               rang=rang-1;
           end   
   end
   set(hlist,'value',rang);
   dispexp(hlist);    

end
function MouseleftclicksatCllbck(~,~)
    delete(hcurrent)
    p = get(hsataxes,'CurrentPoint');
    p = p(1,1:2);
%     if isempty(find(p)) %p ne contient pas de zero
         minsearch=[abs(([data.Temp]-p(1))./[data.Temp]);abs(([data.amp].*[data.Temp]-p(2))./[data.amp]./[data.Temp])];
%     else
%         minsearch=[abs([data.Temp]-p(1));abs([data.amp].*[data.Temp]-p(2))];
%     end
    [~,rang]=min(sum(minsearch,1));%min(abs([data.time]+tdelay-p(1)));%recherche du rang avec valeur de temps la plus proche
    hcurrent=plot(data(rang).Temp,data(rang).amp*data(rang).Temp,'ob','MarkerFaceColor','m','parent',hsataxes);
    set(hlist,'value',rang);
    dispexp(hlist,[]);
    
    %
end

end