%
% A GNAT Macro reading in a series of Varian data and extracting phase
% parameters as a function of gradient level, plot and/or save the data in 
% Matlab or Excel format. The purpuse was to study the phase dependence of 
% gradient amplitude in DOSY experiments
%
% 1. Read in the data, looping of experiment numeber
% 2. Set Fourier number, window function and FT data
% 3. Set phases to zero, and do an automatic zero order phase correction
% 4. Collect the data for all gradient levels
% 5. Plot the data and allow for user defined save in either Matlab or
%    Excel (csv) format.
% 
% MN 26 Feb 2018

%Set the defult directory

TmpVar.ImpDir='/Users/mbdssln2/MNDocs/General NMR Analysis Tolbox/MacroExampleData/phase dependence/2018-Jan_toMN/';

TmpVar.nfids=5;
TmpVar.k=1;
TmpVar.phases=zeros(TmpVar.nfids,NmrData.arraydim); %make array for output data
while TmpVar.k<=TmpVar.nfids
    %make numbered files as *.fid
    TmpVar.FidDir=[TmpVar.ImpDir num2str(TmpVar.k) '.fid'];
    %import the FID data
    Import_Varian([],[],TmpVar.FidDir);             
    
    %set the Gaussian window function
    TmpVar.gf=NmrData.at/2;
    set(hCheckGw,'Value',1);
    set(hEditGw,'Enable','On');
    set(hEditGw,'string',num2str(TmpVar.gf));
    
    %set Fourier number and FT
    set(hEditFn,'string',num2str(NmrData.np*4));
    FTButton_Callback();
    
    %Set first and zero order phases to 0
    NmrData.lp=0;
    NmrData.rp=0;
    guidata(hMainFigure,NmrData); %need to save NmrData
    PhaseSpectrum(NmrData.rp, NmrData.lp,1);
    
    %Set phase scope to phase individual increments
    set(hScopeGroup,'SelectedObject',hRadioScopeIndividual)
    
    %Loop though all spectra in array   
   
    TmpVar.p=1;
    while TmpVar.p<=NmrData.arraydim
        %use the correct array number
         set(hEditFlipSpec,'String', num2str(TmpVar.p));
         EditFlipSpec_Callback();
        %phase zeroth order only
        ButtonAutophase0_Callback();
        %collect the data
        TmpVar.tmp=str2double(get(hEditPh0,'String'));
        disp(get(hEditPh0,'String')); %print variable to Matlab window
        TmpVar.phases(TmpVar.k,TmpVar.p)=TmpVar.tmp;
        TmpVar.p=TmpVar.p+1;
    end
    
    
    TmpVar.k=TmpVar.k+1;
    
end
    %plot the result
    figure
    plot(TmpVar.phases')
    
    %save the data in Matlab format as set by user
    [TmpVar.filename, TmpVar.pathname] = uiputfile('*.mat','Save output data');
    TmpVar.filepath=[TmpVar.pathname TmpVar.filename];
    save(TmpVar.filepath,'TmpVar','-v7.3'); %saving in Matlab format needs to save the whole TmpVar structure
    
    
    
     %save the data in XL format as set by user
    [TmpVar.filename, TmpVar.pathname] = uiputfile('*.xls','Save output data');
    TmpVar.filepath=[TmpVar.pathname TmpVar.filename];
    xlswrite(TmpVar.filepath,TmpVar.phases); %saving in XL format save the phases matrix 
    
    
