function change_GGA_start_time(inputFile, outputFile, startHrs, startMin, startSec)
% change_GGA_start_time - change the starting time of
% a GGA trajectory file.
%
% Dean Gienger, Agilent Technologies, 2010 Aug 4
finp=fopen(inputFile,'r');
fout=fopen(outputFile,'w');
done=0;

fileStartTime=-1;
newStartTime=startHrs*60*60 + startMin*60 + startSec;

while done==0
    % read line from the input file
   line=fgets(finp);
   if ~ischar(line)
       break; % break out of loop when end - of - file
   end
   % if it's a $GPGGA line it looks something like this:
   % $GPGGA,072043,4805.2556,N,827.0432,E,1,05,1.5,303.000000,M,0,M,,0000*5A

   if strncmp(line, '$GPGGA', 6) == 1
       if fileStartTime == -1
           % get first start time
           x=line;
           [t,x]=strtok(x,','); % $GPGGA
           [tod,x]=strtok(x,','); % time of day
           fileStartTime=60*60*sscanf(tod(1:2),'%d')+60*sscanf(tod(3:4),'%d')+sscanf(tod(5:6),'%d');
           if length(tod) > 6; fileStartTime = fileStartTime + sscanf(tod(7:length(tod)),'%f'); end;
           fprintf(1,'Start time %f\n', fileStartTime);
       end
       % extract parameters from $GPGGA sentence
       x=line;
       [t,x]=strtok(x,','); % $GPGGA
       [tod,x]=strtok(x,','); % time of day
       ggatime=60*60*sscanf(tod(1:2),'%d')+60*sscanf(tod(3:4),'%d')+sscanf(tod(5:6),'%d');
       if length(tod) > 6; ggatime = ggatime + sscanf(tod(7:length(tod)),'%f'); end;
       ggatime=ggatime-fileStartTime+newStartTime;
       ggahrs=fix(ggatime/3600);
       ggatime=ggatime-ggahrs*3600;
       ggamin=fix(ggatime/60);
       ggatime=ggatime-ggamin*60;
       ggasec=fix(ggatime);
       ggatime=ggatime-ggasec;
       ggamsec=fix(ggatime*1000);
       tod=sprintf('%02d%02d%02d.%03d',ggahrs,ggamin,ggasec,ggamsec);
       ggacmd=['$GPGGA,' tod x(1:length(x)-5)];
       
       % compute checksum, XOR of all characters between $ and *
       xs=0;
       for i=2:length(ggacmd)
         xs=bitxor(xs,floor(ggacmd(i)));
       end
       xs=bitand(xs,255);
       % build full $GPGGA sentence with checksum appended
       gga_sentence=strcat(ggacmd,'*',sprintf('%02X',xs));

       fprintf(fout,'%s\n', gga_sentence);
   end
end
fclose(finp);
fclose(fout);
