clear all
close all

s = serialport("COM4", 115200);

utmstruct = defaultm('utm');
utmstruct.zone = utmzone(36.0, -121.0);
wgs84 = wgs84Ellipsoid;
ellipsoid = [wgs84.SemimajorAxis wgs84.Eccentricity];
utmstruct.geoid = ellipsoid;
utm.struct = defaultm(utmstruct);

%%
fixCount = 0;
run = true;

while( run )
    gotGGA = false;
    while (~gotGGA)
        gpsLine = readline(s);
        if (contains(gpsLine, "GGA"))
            gotGGA = true;
            fixCount = fixCount + 1;
        end
    end
   
    %%
    ggaFields = split(gpsLine, ',');
    latString = ggaFields(3);
    decPtIndex = strfind(latString, ".");
    latMin = str2double(extractAfter(latString, decPtIndex-3));
    latDeg = str2double(extractBefore(latString, decPtIndex-2));
    latDD = latDeg + latMin / 60.0;
    if(ggaFields(4) == "S")
        latDD = -1.0 * latDD;
    end
    latDD = latDD + (fixCount * 0.00005);
    fix(fixCount).latDD = latDD;
    
    
    lonString = ggaFields(5);
    decPtIndex = strfind(lonString, ".");
    lonMin = str2double(extractAfter(lonString, decPtIndex-3));
    lonDeg = str2double(extractBefore(lonString, decPtIndex-2));
    lonDD = lonDeg + lonMin / 60.0;
    if(ggaFields(6) == "W")
        lonDD = -1.0 * lonDD;
    end
    lonDD = lonDD + (fixCount * 0.00005);
    fix(fixCount).lonDD = lonDD;
    
    [fix(fixCount).easting, fix(fixCount).northing] = mfwdtran(utm.struct, fix(fixCount).latDD, fix(fixCount).lonDD);
    
    timeStamp = datetime(ggaFields(2), 'InputFormat', 'HHmmss.SS');
    fix(fixCount).timeStamp = timeStamp;
    
    fprintf(1, '%5.0f\t%s\t%8.6f\t%8.6f\t%s', fixCount, fix(fixCount).timeStamp, fix(fixCount).latDD, fix(fixCount).lonDD, gpsLine)
    
    gps2kmlTrack(fix, 'TestFolder');
end