function [rwdataph]=uf_ph(rwdata,nZFT,artefact_range)
% This program has been created by Ludmilla Guduff, Jean-Nicolas Dumez and Corentin Jacquemmoz, 
% CEISAM, CNRS, Université de Nantes, France
% The authors are not responsible for the results obtained with this program
% This program can be used, modified and shared as long as the authors are
% credited and the program is share under the same conditions
% Please do not delete this header from the file.
% Function used to phase ufDOSY data atomatically. Can be replaced with the
% manual phasing with phase_gui

maxval=(max(abs(sum(rwdata,2))));
maxind=find(abs(sum(rwdata,2))==maxval);

for ll=1:size(rwdata,1)
    
    testph=(rwdata(ll,:));
    m=720;
    phc1 = linspace(-360,360,m);
    phc0 = linspace(-360,360,m);
    maxsig=0;n1=1;n0=1;
    minsig1=-inf;
    minsig2=-inf;
    c = pi/180;
    
    
    for kk = 1:m
        wdata2 = testph .* ...
            exp(1i*c*(phc0(kk)+(linspace(-0.5,0.5,nZFT))));
        
        wdata2=imag(wdata2);
        localmin2=min(wdata2(1:800));
        localmax=max(wdata2(1:800));
%         localmin2=min(wdata2([1:artefact_range(1) artefact_range(end):end]));
%         localmax=max(wdata2([1:artefact_range(1) artefact_range(end):end]));
        
        if (localmin2>minsig2)
            minsig2=localmin2;
            n0=kk;
            
        end
        
    end
    phc0=phc0(n0);
    
    for k = 1:m
        wdata1 = testph .* ...
            exp(1i*c*(phc0+phc1(k)*(linspace(-0.5,0.5,nZFT))));
        
        wdata1=imag(wdata1);
        localmin1=min(wdata1(1:800));
        localmax=max(wdata1(1:800));
%         localmin1=min(wdata1([1:artefact_range(1) artefact_range(end):end]));
%         localmax=max(wdata1([1:artefact_range(1) artefact_range(end):end]));
        if (localmin1>minsig1)
            minsig1=localmin1;
            n1=k;
            
        end
        
    end
    phc1=phc1(n1);
    
    testph1 = testph .*exp(1i*c*(phc0+phc1*(linspace(-0.5,0.5,nZFT))));
    
   % Baseline correction 
bsline=@(m) sum(abs(testph1-m));
p=0;
newm=fminsearch(bsline,p);
testph1=testph1-newm;  
    
    rwdataph(ll,:)=testph1;
    
    
    
    clear testph1
    clear testph
    
        
end

end


