Index: src/python/bin/gnuboat
===================================================================
--- src/python/bin/gnuboat	(revision 939b309ad4838fcf9c5483348431961751e734f8)
+++ src/python/bin/gnuboat	(revision 6fbf79028c71339d302c497460271d748fe5b6b4)
@@ -27,7 +27,8 @@
 from pytz import timezone
 import pytz
-import getopt
+import argparse
 import sys
 import pynmea2
+import traceback
 
 from gnuboat import daemon
@@ -43,4 +44,6 @@
 logdir = "/var/log/gnuboat"
 logperiod = 2
+logverbose = False
+logsystemtime = False
 displayperiod = 5
 
@@ -70,20 +73,27 @@
     print "  gnuboat -r PATH_TO_RRD_DATABAE_FILE -s PATH_TO_SHUTDOWN_REQUEST_FILE [-l [LOG_UPDATE_PERIOD] [-d DISPLAY_UPDATE_PERIOD] [-o PATH_TO_NMEA1983_LOG]"
     print ""
-    print "  -h --help              Display this help"
-    print "  -r --rrdfile           Path to the rrd database used by the webservice to serve the clients"
-    print "  -s --shutdownfile      Path to the shutdown request file, used by the webservice to request a shutdown of the system running gnuboat"
-    print "  -l --logperiod         Time in seconds to update the logs"
-    print "  -d --displayperiod     Timein seconds to update the display"
-    print "  -o --output            Directory where the log files are stored (e.g. the NMEA0183 log files)"
+    print "  -h  --help              Display this help"
+    print "  -r  --rrdfile           Path to the rrd database used by the webservice to serve the clients"
+    print "  -s  --shutdownfile      Path to the shutdown request file, used by the webservice to request a shutdown of the system running gnuboat"
+    print "  -l  --logperiod         Time in seconds to update the logs"
+    print "  -lv --log-verbose       Log verbose information to nmea log file (Enables -ls and adds RMC sentences, with invalid GPS state, on non fixes"
+    print "  -ls --log-system-time   Add to enable prefixing every logline with the system time (Default off)"
+    print "  -d  --displayperiod     Timein seconds to update the display"
+    print "  -o  --output            Directory where the log files are stored (e.g. the NMEA0183 log files)"
 
 def log(gpsFix, gpsTime, gpsStatus, latitude, latitudeDirection, longitude,
-        longitudeDirection, courseOverGround, speedOverGround, waterDepth, waterTemperature, transducerValid):
+        longitudeDirection, courseOverGround, speedOverGround, waterDepth, waterTemperature, transducerValid, logVerbose, logSystemTime):
     global logdir
     global nmeafile
     global nmeaFileDate
-    
+
     # Only log, if we have a gps fix
     if gpsFix < 2:
-        return
+        if not logVerbose:
+            return
+        gpsStatus = 'V'
+        mode = 'N'
+        if gpsTime is None:
+            gpsTime = datetime.datetime.utcnow()
     
     nmeaFileDateShould = datetime.datetime.utcnow().strftime("%Y-%m-%d")
@@ -99,13 +109,33 @@
             print "Could not open the logfile: %s" % error
             sys.exit(2)
-                
-    nmeafile.write("%s\r\n" % str(pynmea2.RMC('GN', 'RMC',
-                                              (gpsTime.strftime("%H%M%S"), gpsStatus, '%09.4f' % latitude,
-                                               latitudeDirection, '%010.4f' % longitude, longitudeDirection,
-                                               '%04.1f' % speedOverGround, '%04.1f' % courseOverGround,
-                                               gpsTime.strftime("%d%m%y"), '', '', mode))))
+
+    latitude = degreesDecimalToNmea(latitude)
+    longitude = degreesDecimalToNmea(longitude)
+
+    logstring = "%s\r\n" % str(pynmea2.RMC('GN', 'RMC',
+                                                  (gpsTime.strftime("%H%M%S"), gpsStatus,
+                                                   '%02d%s' % (latitude['degrees'], latitude['minutes'])
+                                                   latitudeDirection,
+                                                   '%03d%s' % (longitude['degrees'], longitude['minutes']),
+                                                   longitudeDirection,
+                                                   '%04.1f' % speedOverGround, '%04.1f' % courseOverGround,
+                                                   gpsTime.strftime("%d%m%y"), '', '', mode)))
+    if logsystemtime:
+        logstring = "%s: %s" % (datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S"), logstring)
+
+    try:                
+        nmeafile.write(logstring)
+    except:
+        print "Failed writing to logfile %s" % nmeaLogFile
+        print(traceback.format_exc())
+
     if transducerValid:
         nmeafile.write("%s\r\n" % str(pynmea2.DPT('SD', 'DPT', ('%05.2f' % waterDepth, '00.00'))))
         nmeafile.write("%s\r\n" % str(pynmea2.MTW('YX', 'MTW', ('%04.1f' % waterTemperature, 'C'))))
+
+def degreesDecimalToNmea(decimalDegrees):
+    degrees = math.floor(decimalDegrees)
+    minutes = 60.0 * (decimalDegrees - degrees)
+    return { 'degrees': degrees, 'minutes': minutes}
 
 def main(argv):
@@ -113,31 +143,42 @@
     global shutdownfile
     global logperiod
+    global logverbose
+    global logsystemtime
     global displayperiod
     global logdir
     global nmeafile
 
-    try:
-        opts, args = getopt.getopt(argv, "hr:s:l:d:o:", [
-                                   "help", "rrdfile=", "shutdownfile=", "logperiod=", "displayperiod=", "output="])
-    except getopt.GetoptError:
-        usage()
-        sys.exit(2)
-
-    for option, argument in opts:
-        if option == ("-h", "--help"):
-            usage()
-            sys.exit()
-        elif option in ("-r", "--rrdfile"):
-            rrdfile = argument
-        elif option in ("-s", "--shutdownfile"):
-            shutdownfile = argument
-        elif option in ("-l", "--logperiod"):
-            logperiod = argument
-        elif option in ("-d", "--displayperiod"):
-            displayperiod = argument
-        elif option in ("-o", "--output"):
-            logdir = argument
-        else:
-            assert False, "unhandled option"
+    parser = argparse.ArgumentParser(description="Collects the data from canboat and gpsd and writes them to the rrd database and the nmea log file")
+    parser.add_argument('-r', '--rrdfile', dest='rrd_file', metavar='rrd_file', type=str,
+                        help='Path to the rrd database used by the webservice to serve the clients', default=rrdfile)
+    parser.add_argument('-s', '--shutdownfile', dest='shutdown_file', metavar='shutdown_file', type=str,
+                        help='Path to the shutdown request file, used by the webservice to request a shutdown of the system running gnuboat', default=shutdownfile)
+    parser.add_argument('-lp', '--logperiod', dest='log_period', metavar='log_period', type=int,
+                        help='Time in seconds to update the logs', default=logperiod)
+    parser.add_argument('-lv', '--log-verbose', action='store_true', dest='log_verbose',
+                        help='Log verbose information to nmea log file (Enables -ls and adds RMC sentences, with invalid GPS state, on non fixes (Default off)')
+    parser.add_argument('-ls', '--log-system-time', action='store_true', dest='log_system_time',
+                        help='Add to enable prefixing every logline with the system time (Default off)')
+    parser.add_argument('-d', '--displayperiod', dest='display_period', metavar='display_period', type=int,
+                        help='Time in seconds to update the display', default=displayperiod)
+    parser.add_argument('-o', '--output', dest='output', metavar='output', type=str,
+                        help='Directory where the log files are stored (e.g. the NMEA0183 log files)', default=logdir)
+    arguments = parser.parse_args(argv)
+   
+    if arguments.rrd_file is not None:
+        rrdfile = arguments.rrd_file
+    if arguments.shutdown_file is not None:
+        shutdownfile = arguments.shutdown_file
+    if arguments.log_period is not None:
+        logperiod = arguments.log_period   
+    if arguments.log_verbose is not None:
+        logverbose = arguments.log_verbose
+        logsystemtime = True
+    if arguments.log_system_time is not None and arguments.log_verbose is None:
+        logsystemtime = arguments.log_system_time
+    if arguments.display_period is not None:
+        displayperiod = arguments.display_period
+    if arguments.output is not None:
+        logdir = arguments.output
 
     if not os.path.exists(os.path.dirname(rrdfile)):
@@ -197,5 +238,5 @@
             log(gpsFix, gpsp.timeUtc(), gpsp.status(), latitude, gpsp.latitudeDirection(),
                 longitude, gpsp.longitudeDirection(), courseOverGround, speedOverGround,
-                waterDepth, waterTemperature, n2kd.waterDepthValid())
+                waterDepth, waterTemperature, n2kd.waterDepthValid(), logverbose, logsystemtime)
             
             # display data
Index: src/python/bin/gnuboat-log-converter
===================================================================
--- src/python/bin/gnuboat-log-converter	(revision 939b309ad4838fcf9c5483348431961751e734f8)
+++ src/python/bin/gnuboat-log-converter	(revision 6fbf79028c71339d302c497460271d748fe5b6b4)
@@ -24,13 +24,15 @@
 from enum import Enum
 import csv
+import re
+import tempfile
+import subprocess
 
 class Format(Enum):
     CSV = 1
-
-input_file_path = None
-output_file_path = None
-output_format_option = None
-output_format = Format.CSV
-errors_ignore = False
+    NMEA0183 = 2
+    GPX = 3
+
+regex_nmea_sentence = re.compile(r"^([^\$!]{0,})([\$!]{1}[\w]{2}[\w]{3}[^\*]+\*[\da-zA-Z]+)$")
+regex_nmea_position = re.compile(r"^([0-9]+)([0-9]{2}\.[0-9]+)$")
 
 def toFloat(string, current_row):
@@ -44,5 +46,131 @@
            return 0
 
+def nmeaToDecimalDegrees(nmea_value, current_row):
+    global regex_nmea_position
+
+    if toFloat(nmea_value, current_row) == 0:
+        return 0
+
+    matches = regex_nmea_position.match(nmea_value)
+    if matches is None:
+        print 'INFO: Failed to convert position value from line %s into decimal degrees: %s' % (current_row, nmea_value)
+        return
+    decimalDegrees = toFloat(matches.group(1), current_row)
+    decimalMinutes = toFloat(matches.group(2), current_row)
+    return decimalDegrees + (decimalMinutes / 60.0)
+
+def convertToCsv(input_file_path, output_file_path, errors_ignore, strip_time):
+    global regex_nmea_sentence
+
+    try:
+        output_file = open(output_file_path, 'w', 0)
+    except IOError as error:
+        print "ERROR: Could not open the output file: %s" % error
+        sys.exit(3)
+
+    output_file_csv = None
+    fields = ['datetime', 'gps_status', 'latitude', 'latitude_direction', 'longitude',
+              'longitude_direction', 'speed_over_ground', 'course_over_ground' ,
+              'water_depth', 'water_temperature']
+    output_file_csv = csv.DictWriter(output_file, delimiter=' ', quotechar='"',
+                                     quoting=csv.QUOTE_NONNUMERIC, fieldnames=fields)
+    output_file_csv.writeheader()
+
+    # reading input file
+    try:
+        input_file = open(input_file_path, 'r')
+    except IOError as error:
+        print "ERROR: Could not open the input file: %s" % error
+        sys.exit(3)
+    current_row = 1
+    last_row = None
+    for line in input_file:
+        line = line.strip()
+        matches = regex_nmea_sentence.match(line)
+        if matches is None:
+            print 'INFO: Failed to parse nmea sentence (%s) at line %s\n' % (line, current_row)
+            if not errors_ignore:
+                input_file.close()
+                output_file.close()
+                sys.exit(4)
+        else:
+            nmea_sentence = pynmea2.parse(matches.group(2))
+            if nmea_sentence.sentence_type == 'RMC':
+                if last_row is not None:
+                    output_file_csv.writerow(last_row)
+                last_row = {'datetime': '%s %s' % (nmea_sentence.datestamp, nmea_sentence.timestamp),
+                            'gps_status': nmea_sentence.status,
+                            'latitude': nmeaToDecimalDegrees(nmea_sentence.lat, current_row),
+                            'latitude_direction': nmea_sentence.lat_dir,
+                            'longitude': nmeaToDecimalDegrees(nmea_sentence.lon, current_row),
+                            'longitude_direction': nmea_sentence.lon_dir,
+                            'speed_over_ground': toFloat(nmea_sentence.spd_over_grnd, current_row),
+                            'course_over_ground': toFloat(nmea_sentence.true_course, current_row),
+                            'water_depth': None,
+                            'water_temperature': None}
+            elif nmea_sentence.sentence_type == 'DBT' and last_row is not None:
+                last_row['water_depth'] = toFloat(nmea_sentence.depth_meters, current_row)
+            elif nmea_sentence.sentence_type == 'MTW' and last_row is not None:
+                last_row['water_temperature'] = toFloat(nmea_sentence.temperature, current_row)
+            current_row += 1
+    if last_row is not None:
+        output_file_csv.writerow(last_row)
+    output_file.close()
+    input_file.close()
+
+def convertToNmea0183(input_file_path, output_file_path, errors_ignore, strip_time):
+    global regex_nmea_sentence
+
+    try:
+        output_file = open(output_file_path, 'w', 0)
+    except IOError as error:
+        print "ERROR: Could not open the output file: %s" % error
+        sys.exit(3)
+
+    # reading input file
+    try:
+        input_file = open(input_file_path, 'r')
+    except IOError as error:
+        print "ERROR: Could not open the input file: %s" % error
+        sys.exit(3)
+    current_row = 1
+    last_row = None
+    for line in input_file:
+        line = line.strip()
+        matches = regex_nmea_sentence.match(line)
+        if matches is None:
+            print 'INFO: Failed to parse nmea sentence (%s) at line %s\n' % (line, current_row)
+            if not errors_ignore:
+                input_file.close()
+                output_file.close()
+                sys.exit(4)
+        else:
+            nmea_sentence = pynmea2.parse(matches.group(2))
+            output_string = str(nmea_sentence)
+            if not strip_time and matches.group(1):
+                output_string = '%s%s' % (matches.group(1), output_string) 
+            output_file.write("%s\r\n" % str(output_string))
+    output_file.close()
+    input_file.close()
+    
+def convertToGpx(input_file_path, output_file_path, errors_ignore, strip_time):
+    global regex_nmea_sentence
+    
+    # make sure, nmea input file, does not have timestamps in front of the nmea
+    # sentences
+    [nmea_without_timestamps_handle, nmea_without_timestamp_file_path] = tempfile.mkstemp(text=True)
+    convertToNmea0183(input_file_path, nmea_without_timestamp_file_path, errors_ignore, True)
+    
+    subprocess.call(['gpsbabel', '-i', 'nmea', '-f', nmea_without_timestamp_file_path, '-o', 'gpx', '-F', output_file_path])
+    os.remove(nmea_without_timestamp_file_path)
+
 def main(argv):
+    input_file_path = None
+    output_file_path = None
+    output_format_option = None
+    output_format = Format.CSV
+    errors_ignore = False
+    strip_time = False
+	
     formats = []
     for file_format in Format:
@@ -58,4 +186,6 @@
     parser.add_argument('output_file', metavar='output_file_path', type=str,
                         help='Write the converted content to file (output)')
+    parser.add_argument('--strip-time', dest='strip_time', action='store_true',
+                        help='Removes timestamp in front of the nmea sentence, if it is there')
     arguments = parser.parse_args(argv)
    
@@ -67,15 +197,18 @@
                format_found = True
         if not format_found:
-            print 'Invalid input format specified: %s' % arguments.output_format
+            print 'ERROR: Invalid input format specified: %s' % arguments.output_format
             sys.exit(1)
 
     if arguments.errors_ignore is not None:
         errors_ignore = arguments.errors_ignore
+        
+    if arguments.strip_time is not None:
+        strip_time = arguments.strip_time
             
     if arguments.input_file is None:
-        print 'No input file specified'
+        print 'ERROR: No input file specified'
         sys.exit(2)
     elif not os.path.exists(arguments.input_file):
-        print 'Specified input file does not exists: %s' % arguments.input_file
+        print 'ERROR: Specified input file does not exists: %s' % arguments.input_file
         sys.exit(3)
     else:
@@ -83,58 +216,22 @@
         
     if arguments.output_file is None:
-        print 'No output file specified'
+        print 'ERROR: No output file specified'
         sys.exit(2)
     elif not os.path.exists(os.path.dirname(arguments.output_file)):
-        print 'Specified directory of output file does not exists: %s' % arguments.output_file
+        print 'ERROR: Specified directory of output file does not exists: %s' % arguments.output_file
         sys.exit(3)
     else:
         output_file_path = arguments.output_file
 
-    try:
-        output_file = open(output_file_path, 'w', 0)
-    except IOError as error:
-        print "Could not open the output file: %s" % error
-        sys.exit(3)
-        
-    output_file_csv = None
-    if output_format == Format.CSV.value:
-        fields = ['datetime', 'gps_status', 'latitude', 'latitude_direction', 'longitude',
-                  'longitude_direction', 'speed_over_ground', 'course_over_ground' ,
-                  'water_depth', 'water_temperature']
-        output_file_csv = csv.DictWriter(output_file, delimiter=' ', quotechar='"',
-                                         quoting=csv.QUOTE_NONNUMERIC, fieldnames=fields)
-        output_file_csv.writeheader()
-
-    # reading input file
-    nmea_errors='raise'
-    if errors_ignore:
-        nmea_errors='ignore'
-    nmea_file = pynmea2.NMEAFile(input_file_path)
-    current_row = 1
-    last_row = None
-    for nmea_sentence in nmea_file:
-        if output_format == Format.CSV.value:
-            if nmea_sentence.sentence_type == 'RMC':
-                if last_row is not None:
-                    output_file_csv.writerow(last_row)
-                last_row = {'datetime': '%s %s' % (nmea_sentence.datestamp, nmea_sentence.timestamp),
-                            'gps_status': nmea_sentence.status,
-                            'latitude': toFloat(nmea_sentence.lat, current_row),
-                            'latitude_direction': nmea_sentence.lat_dir,
-                            'longitude': toFloat(nmea_sentence.lon, current_row),
-                            'longitude_direction': nmea_sentence.lon_dir,
-                            'speed_over_ground': toFloat(nmea_sentence.spd_over_grnd, current_row),
-                            'course_over_ground': toFloat(nmea_sentence.true_course, current_row),
-                            'water_depth': None,
-                            'water_temperature': None}
-            elif nmea_sentence.sentence_type == 'DBT' and last_row is not None:
-                last_row['water_depth'] = toFloat(nmea_sentence.depth_meters, current_row)
-            elif nmea_sentence.sentence_type == 'MTW' and last_row is not None:
-                last_row['water_temperature'] = toFloat(nmea_sentence.temperature, current_row)
-        current_row += 1
-    if last_row is not None:
-        output_file_csv.writerow(last_row)  
-        
-    output_file.close()
+    if output_format == Format.CSV.value: 
+        convertToCsv(input_file_path, output_file_path, errors_ignore, strip_time)
+    elif output_format == Format.NMEA0183.value:
+        convertToNmea0183(input_file_path, output_file_path, errors_ignore, strip_time)
+    elif output_format == Format.GPX.value:
+        convertToGpx(input_file_path, output_file_path, errors_ignore, strip_time)
+    else:
+        print "ERROR: Undefined output format!\n";
+        sys.exit(1)
+
     sys.exit(0)
 
