%
% A Macro to correct a change in frequency for a series of FIDs. The TSP
% peak is set to 0 ppm for all elements
%
%
%The original Bruker data has first been imported into GNAT and saved in GNAT Matlab format




% Open the data
TmpVar.ImpFID1='/Users/mbdssln2/MNDocs/General NMR Analysis Tolbox/MacroExampleData/CorrectFrequency/TempCalib.mat';
Open_data( [], [], TmpVar.ImpFID1)

% set the spectral window
xlim([-1 1])


% Use absolute value display to avoid phase problems, when fidning peak max
set(hAbsPhaseGroup,'SelectedObject',hRadioAbs)
GroupAbsPhase_Callback();


% Get the data with the current spectral window and threshold
TmpVar.input.thresflag=0;
TmpVar.analyzedata=PrepareAnalyzeData(TmpVar.input);
%disp(size(TmpVar.analyzedata.SPECTRA))

% Get the frequencies for the tallest peak in the window, for all array
% elements
TmpVar.freq=zeros(1,NmrData.arraydim); %create structure to collect data
 %set the threshold as a percentage of the max
TmpVar.th=20;

TmpVar.k=1;

while TmpVar.k<=NmrData.arraydim
      disp((TmpVar.k))
    %Peak pick the each increment
    [ TmpVar.peaks]=peakpick_mn(real(TmpVar.analyzedata.SPECTRA(:,TmpVar.k)),TmpVar.th);
    if isempty(TmpVar.peaks)
        %No peak is detected in this element
        TmpVar.freq(TmpVar.k)=NaN;
    else
        %Find the highest peak
        TmpVar.amp=TmpVar.analyzedata.SPECTRA(TmpVar.peaks(1).max,TmpVar.k);
        TmpVar.ampmax=1;
        TmpVar.p=1;
        while TmpVar.p<=length(TmpVar.peaks)
            TmpVar.testamp=TmpVar.analyzedata.SPECTRA(TmpVar.peaks(k).max,TmpVar.k);
            if TmpVar.testamp>TmpVar.amp
                TmpVar.ampmax=TmpVar.p;
            end
            TmpVar.p=TmpVar.p+1;
        end
        %save the frequency of the highest peak
        TmpVar.freq(TmpVar.k)=TmpVar.analyzedata.Ppmscale(TmpVar.peaks(TmpVar.ampmax).max);
    end
    
    TmpVar.k=TmpVar.k+1;
end

%Apply the frequency shift

TmpVar.desired_ppm=0; %the desired ppm shift for all aligen peaks
TmpVar.fshift=TmpVar.freq-TmpVar.desired_ppm;
TmpVar.fshift=TmpVar.fshift*NmrData.sfrq;


TmpVar.Timescale=linspace(0,NmrData.at,NmrData.np)';
TmpVar.tmpfid=NmrData.FID;

TmpVar.k=1;
TmpVar.lp=-str2double(get(hEditPh1,'String'));
while TmpVar.k<=NmrData.arraydim
    TmpVar.tmp=exp(1i.*TmpVar.fshift(TmpVar.k)*2*pi.*TmpVar.Timescale);
    TmpVar.tmpfid(:,TmpVar.k)= TmpVar.tmpfid(:,TmpVar.k).*TmpVar.tmp;
    TmpVar.k=TmpVar.k+1;
end

NmrData.FID=TmpVar.tmpfid;

%save the data
guidata(hMainFigure,NmrData);


% Revert to phase sensitive and FT
set(hAbsPhaseGroup,'SelectedObject',hRadioPhase)
GroupAbsPhase_Callback();
FTButton_Callback();

%Phase the data separately for each increment
set(hScopeGroup,'SelectedObject',hRadioScopeIndividual)
GroupScope_Callback();
%FTButton_Callback();
TmpVar.k=1;
while TmpVar.k<=NmrData.arraydim
    set(hEditFlipSpec,'String',num2str(TmpVar.k));
    EditFlipSpec_Callback
    ButtonAutophase_Callback();     
    TmpVar.k=TmpVar.k+1;
end
