% paths={'D:\georg\work\delta_undulator_me\20130612_1630run4_15mmpsec\';
%     'D:\georg\work\delta_undulator_me\20130612_1607run1_5mmpsec\'
%     'D:\georg\work\delta_undulator_me\20130612_1615run2_5mmpsec\'
%     'D:\georg\work\delta_undulator_me\20130612_1624run3_10mmpsec\'
%     'D:\georg\work\delta_undulator_me\20130612_1636run5_20mmpsec\'};
paths={'J:\MagServe\MagData\LCLS\Undulator\DeltaPrototype\20140506_test\'};
stepsize=0.05; % nominal distance between triggers

for pnum=1:length(paths)
    
    pathn=paths{pnum};
    
    filesus=dir([pathn '*.bmp']);
    di=[];
    for i=1:length(filesus)
        di(i)=filesus(i).datenum;
    end
    
    [s, idx]=sort(di);
    
    files=filesus(idx);
    
    pos=[];
    for i=1:length(files)
        str=(files(i).name);
        id=strfind(str,'.BMP');
        str(id:end)=[];
        id=strfind(str,'_');
        if id
            str(id)='.';
        end
        pos(i)=str2double(str(2:end));
    end
    
    l=length(files);
    n=floor(l/10);
    filesref=files(n:n:end);
    
    filepos=fopen([pathn 'pos.dat']);
    zeile=fgetl(filepos);
    lambda=sscanf(zeile,'%f');
    lambda=lambda(end);
    count=0;
    ipos=[];
    while(~feof(filepos))
        zeile=fgetl(filepos);
        if ~isempty(zeile)
            count=count+1;
            ipos(count,:)=sscanf(zeile,'%u %lu');
        end
    end
    fclose(filepos);
    
    ipos([21171],:)=[]; %remove additional triggers
    
    idxr=find(ipos(:,1)~=0);
    iposr=ipos(idxr,:);
    
    dpos=diff(iposr(:,2));
    
    idp=(dpos>5e6);
    idn=(dpos<-5e6);
    idc=-idp+idn;
    poscorrection=[0; cumsum(idc)*2^24];
    ipos(idxr,2)=ipos(idxr,2)+poscorrection;
    ipos(:,2)=ipos(:,2)*lambda;
    idx=find(ipos(:,1)==0);
    ipos(idx,2)=NaN;
    ipos(1:200,2)=NaN;
    ipos(end-200:end,2)=NaN;
    
    trigm=length(ipos);
    nominalpos=-[(1:200)*0 (1:trigm-400)*stepsize (1:200)*0]; % these are the noiminal position
    idx=find(~isnan(ipos(:,2)));
    avgnom=median(ipos(idx,2)-nominalpos(idx)');
    nominalpos=nominalpos+avgnom;
    
    figure
    plot(ipos(:,1),(ipos(:,2)-nominalpos')*1000)
    xlabel('Trigger #')
    ylabel('meas-nominal [\mum]')
    
    fftsoly=[];
    fftsolx=[];
    for j=1:length(filesref)
        imo=imread([pathn filesref(j).name]);
        IMO=imo(:,:,1);
        for i=1:length(files)
            disp([length(files) j i])
            
            im1=imread([pathn files(i).name]);
            IM1=im1(:,:,1);
            
            output = dftregistration(fft2(IMO),fft2(IM1),10);
            
            fftsoly(j,i)=output(3);
            fftsolx(j,i)=output(4);
            %     IM1=im1(:,:,1);
            %     sumIM=sum(sum(IM1));
            %     y(i)=sum((sum(IM1').*[1:1200]))/sumIM;
            %     x(i)=sum((sum(IM1 ).*[1:1600]))/sumIM;
        end
    end
    save([pathn 'compd'],'fftsoly','fftsolx','ipos','nominalpos')
end

