%gpsskew.m

clear;
inFile = ('gpsskew.txt');
inFID = fopen(inFile);
i=1;

while ~feof(inFID)
    inString = fgets(inFID);
    inFields = strsplit(inString, '\t', 'CollapseDelimiters', false);

  
    cpuDateTimeNum(i) = datenum(strcat(inFields{2}, 'T', inFields{3}));
    
    gpsFields = strsplit(inFields{38},',','CollapseDelimiters', false);
    gpst(i)=str2double(gpsFields{3});
    
    
    i=i+1;
end

fclose(inFID);


hh = fix(gpst/10000);

mm = gpst-(hh*10000);
mm = fix(mm/100);

ss = gpst-(hh*10000)-(mm*100);


day=28;

gpsDateTimeNum(1) = datenum([2016,6,day,hh(1),mm(1),ss(1)]);
tdif(1) = etime(   datevec(gpsDateTimeNum(1)),  datevec(cpuDateTimeNum(1))    );
elapsed_t(1) = etime( datevec(cpuDateTimeNum(1)), datevec(cpuDateTimeNum(1)) );

for i = 2:1:size(gpst,2)
    if(hh(i)<hh(i-1))
        day=29;
    end
    gpsDateTimeNum(i) = datenum([2016,6,day,hh(i),mm(i),ss(i)]);
    tdif(i) = etime(   datevec(gpsDateTimeNum(i)),  datevec(cpuDateTimeNum(i))    );
    elapsed_t(i) = etime( datevec(cpuDateTimeNum(i)), datevec(cpuDateTimeNum(1)) );
end

tdif=tdif/3600; %hours
elapsed_t = elapsed_t/3600; %hours
plot(elapsed_t,tdif,'o');
title('CPU clock skew');
xlabel('Elapsed mission time in hours');
ylabel('gps time - cpu time in hours');
grid on;
%plot(1:1:size(gpsDateTimeNum,2),gpsDateTimeNum);

 p = polyfit(elapsed_t,tdif,1);
 outstr = sprintf('%3.2f hours/hour skew',p(1));
 
 text(8,2,outstr);
 y(1) = p(2);
 y(2) = p(2) + p(1)*max(elapsed_t);
 
 x = [ 0 max(elapsed_t)];
 hold on;
 plot(x,y,'r--');
 
 