function ConvertRMC_to_GGA( inputFile, outputFile, altitudeInMeters )
% ConvertRMC_to_GGA
%   Convert file of NMEA $GPRMC messages to a file of $GPGGA messages
%   for input to a scenario generation process.
%   (C) 2010, Agilent Technologies
%
% $GPRMC message does not contain alititude information
% so we need to generate some altitude data.  In this case a constant
% altitude is used.
finp=fopen(inputFile, 'r');
fout=fopen(outputFile, 'w');
done=0;
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 $GPRMC line it looks something like this:
   % $GPRMC,072043,A,4805.2556,N,827.0432,E,0.0,115.9,140410,0.4,E,S*06
   if strncmp(line, '$GPRMC', 6) == 1
       % extract parameters from $GPRMC sentence
       x=line;
       [t,x]=strtok(x,','); % $GPRMC
       [tod,x]=strtok(x,','); % time of day
       [sts,x]=strtok(x,','); % status, A for good fix, V for bad fix 
       [lat,x]=strtok(x,','); % latitude
       [latns,x]=strtok(x,','); % N or S
       [lon,x]=strtok(x,','); % longitude
       [lonew,x]=strtok(x,','); % E or W
       
       % construct $GPGGA line that looks something like this using data
       % extracted from the $GPRMC line, as well as the input fixed altitude
       %
       % $GPGGA,072043,4805.2556,N,827.0432,E,1,05,1.5,303.000000,M,0,M,,0000*5A
       fixq=(sts=='A'); % 1 for valid, 0 for invalid
       ggacmd=[...
           '$GPGGA',',', ...
           tod,',', ...
           lat,',', ...
           latns,',', ...
           lon,',', ...
           lonew,',', ...
           sprintf('%d',fixq),',', ...
           '05,1.5,', ...
           sprintf('%f',altitudeInMeters),',', ...
           'M,0,M,,0000' ];

       % 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 %while
fclose(finp);
fclose(fout);

