%fname='20140127/data_SPESO_2014-01-27_21-15-31_dec.txt.gz'
%basename='./';

% loadDataFile('20140306/data_SPESO_2014-03-06_15-39-52_dec.txt.gz')

function [data,rateValue,timeCorrection]=loadDataFile(fname)
basename='./';

%%% Check if the file name starts with the directory
if (strcmp(fname(1:3),'201'))
    disp('Name is OK')
else
    if (strcmp(fname(1:4),'data'))
        fname = [ fname(12:15) fname(17:18) fname(20:21) '/' fname ];
        disp('fname rewritten as');
        fname
    else
        fname
        disp('Unknown name format... This may not be OK!!!');
    end
end

filename=[ basename fname ];
[res,txt]=system(['gzip -d -c ' filename ]);
if (~(res==0))
    error([ 'Error while opening file ' filename '. Error code: ' num2str(res) ])
end

rangename=strrep(filename,'_dec','_range');
[res,txtrange]=system(['gzip -d -c ' rangename ]);
if (~(res==0))
    error([ 'Error while opening file ' rangename '. Error code: ' num2str(res) ])
end

base_save_file_name=strrep(strrep(filename,'_dec.txt.gz',''),char(10),'');


if (strcmp(txtrange(1:5),'rate='))
    rateValue=str2num(txtrange(6:end));
else
    txtrange(1:5)
    error('Incorrect range file');
end

%error('test') 

%size(txt)

%char(txt)

tAfterTriger=0.02;

data=str2num(char(txt));
nData=size(data,1);

durationOneSample=(rateValue*16/(2*3e8))*1.0426; %1/s                                          
                                          %samplesOneMsec=0.001/(rateValue*16/(2*3e8));
samplesOneMsec=0.001/(durationOneSample);
timeRange=[1:nData]*durationOneSample;

timeInMsBetweenTrigger=320;


%%%Fit 50Hz on the trigger line
clear x
beta(1)=mean( data(:,16));
beta(2)=max( data(:,16))-min(data(:,16));
beta(3)=1/(20*samplesOneMsec/(2*pi));
beta(4)=-250;
betaInit=beta;
beta=nlinfit(1:nData, smooth(data(:,16))', @(b,x)(b(1)+b(2).*sin(b(3).*x + b(4))), beta)
figure(9016)
clf
xRange=1:1*20*samplesOneMsec;
hold on
plot(xRange, data(xRange,16)','r')
plot(xRange,(beta(1)+beta(2).*sin(beta(3).*xRange + beta(4))), 'b')
plot(xRange,(betaInit(1)+betaInit(2).*sin(betaInit(3).*xRange + betaInit(4))), 'g')
xRange2=xRange+ceil((500*samplesOneMsec));
plot(xRange, data(xRange2,16)','--r')
plot(xRange,(beta(1)+beta(2).*sin(beta(3).*xRange2 + beta(4))), '--b')
plot(xRange,(betaInit(1)+betaInit(2).*sin(betaInit(3).*xRange2 + betaInit(4))), '--m')

xRange=1:nData;
sum(abs(data(xRange,16)'-(beta(1)+beta(2).*sin(beta(3).*xRange + beta(4)))))


figure(9116)
clf
xRange=1:10*20*samplesOneMsec;
hold on
plot(xRange,data(xRange,16)'-(beta(1)+beta(2).*sin(beta(3).*xRange + beta(4))), 'b')

figure(9216)
clf
xRange=1:nData;
hold on
plot(xRange,data(xRange,16)'-(beta(1)+beta(2).*sin(beta(3).*xRange + beta(4))), 'b')

iloop=16;
    figure(9300+iloop)
    clf
    hold on
    plotRange=[ceil(326*samplesOneMsec):ceil(327*samplesOneMsec)];
    plotRange=[ceil(0.001*samplesOneMsec):ceil(30*samplesOneMsec)];
    plot(plotRange*(rateValue*16/(2*3e8)),data(plotRange,iloop)'-(beta(1)+beta(2).*sin(beta(3).*plotRange + beta(4))),'r')
    plotRange2=plotRange+ceil(timeInMsBetweenTrigger*samplesOneMsec);
        plot(plotRange*(rateValue*16/(2*3e8)),data(plotRange2,iloop)'-(beta(1)+beta(2).*sin(beta(3).*plotRange2 + beta(4))),'b')
    plotRange2=plotRange2+ceil(timeInMsBetweenTrigger*samplesOneMsec);
        plot(plotRange*(rateValue*16/(2*3e8)),data(plotRange2,iloop)'-(beta(1)+beta(2).*sin(beta(3).*plotRange2 + beta(4))),'g')
    plotRange2=plotRange2+ceil(timeInMsBetweenTrigger*samplesOneMsec);
            plot(plotRange*(rateValue*16/(2*3e8)),data(plotRange2,iloop)'-(beta(1)+beta(2).*sin(beta(3).*plotRange2 + beta(4))),'c')
    grid on         

    %    beta(3)-betaInit(3)
    timeCorrection=beta(3)/betaInit(3)
    %    2*(beta(3)-betaInit(3))/(beta(3)+betaInit(3))
    

    %%% Correct the timing taking into account the 50Hz fit
    durationOneSample=durationOneSample*timeCorrection; %1/s                                          
                                          %samplesOneMsec=0.001/(rateValue*16/(2*3e8));
samplesOneMsec=0.001/(durationOneSample);
timeRange=[1:nData]*durationOneSample;


    pAfterTrigger=ceil(20*samplesOneMsec);
    
    %for iloop=[16 8 12 15 13 10 14 ]
for iloop=1:16
    
    figure(iloop)
    clf
    plot(pAfterTrigger:nData,data(pAfterTrigger:end,iloop))
    grid on
    print('-dpng',[ base_save_file_name '_channel_' num2str(iloop) '.png' ]);

    
    %    for tloop=1:4
    for tloop=1:-1
    allStartTimeMs=[ 20 30 38 40] ;
    allEndTimeMs=[ 200 75 45 41];

            startTimeMs=allStartTimeMs(tloop);
    endTimeMs=allEndTimeMs(tloop);

    figure((tloop*100)+iloop)
    clf    
        hold on
        title({strrep(fname,'_',' ');['Plot from ' num2str(startTimeMs) ' ms to '  num2str(endTimeMs) ' ms']});
    nTriggerPlusTime=floor(((nData)-(endTimeMs*samplesOneMsec))/(timeInMsBetweenTrigger*samplesOneMsec));
    for jloop=1:nTriggerPlusTime   
        plotRange=[ceil(startTimeMs*samplesOneMsec):ceil(startTimeMs*samplesOneMsec)+(endTimeMs-startTimeMs)*samplesOneMsec];
        dataRange=plotRange+floor(((jloop-1)*(timeInMsBetweenTrigger*samplesOneMsec)));
        plot(plotRange*durationOneSample,data(dataRange,iloop),getCol(jloop))
    end
    grid on    
    if ((tloop==1)||(tloop==4))
    print('-dpng',[ base_save_file_name '_channel_' num2str(iloop) '_folded_from_'  num2str(startTimeMs) 'ms_to_'  num2str(endTimeMs) '_ms.png' ]);
    end
end


end %function