Index: src/common/README
===================================================================
--- src/common/README	(revision ec9e811865ae57c33a65e0c0ebd697938333b06f)
+++ src/common/README	(revision ec9e811865ae57c33a65e0c0ebd697938333b06f)
@@ -0,0 +1,1 @@
+GNUBoat python module with content used by other GNUBoat python modules
Index: src/common/bin/gnuboat-log-analyser
===================================================================
--- src/common/bin/gnuboat-log-analyser	(revision ec9e811865ae57c33a65e0c0ebd697938333b06f)
+++ src/common/bin/gnuboat-log-analyser	(revision ec9e811865ae57c33a65e0c0ebd697938333b06f)
@@ -0,0 +1,314 @@
+#!/usr/bin/python
+# -*- coding: utf-8 -*-
+'''
+    Copyright (C) 2018 - 2020 EngSaS - Engineering Solutions and Services Langenbach. All rights reserved.
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+'''
+
+import os
+import argparse
+import sys
+import math
+import json
+import csv
+import xml.etree.ElementTree as ET
+from osgeo import ogr
+from osgeo import osr
+from osgeo import gdal
+from osgeo import gdalconst
+import shutil
+
+from gnuboat_common.datahandler import loghandler, logdataset
+
+# -999 is a workaround, as long gdal python api does not handle addAlpha
+colors = {
+	-999: "255 255 255",
+	0: "0 0 139",
+	2: "30 144 255",
+	6: "173 216 230",
+	10: "240 248 255"
+}
+input_epsg = 'EPSG:4326'
+target_nodata_value = -999.0
+target_zoomlevel = 19
+density_min = 10 # number of points per density_base squaremetres needed to set a value different from nodata
+density_base = 100 # squaremetre used as base for density_min
+
+class CsvCallback:
+	def __init__(self, output_file):
+		self._output_file = output_file
+		self._stage = None
+		
+	def stage_set(self, stage):
+		self._stage = stage
+
+	def callback(self, dataset):
+		if self._stage is None:
+			print("No stage set! Skipping dataset...")
+			return
+		# only add points with a water depth set
+		if dataset.water_depth() is None:
+			return
+		water_depth = dataset.water_depth() - self._stage
+		self._output_file.writerow({"lon": dataset.longitude(), "lat": dataset.latitude(), "water_depth": water_depth})
+
+def tile_width(zoomlevel):
+	tile_size = 256
+	tiles = math.sqrt(tile_number(zoomlevel))
+	return {"tile_size": tile_size, "longitude": 360.0/tiles, "latitude": 180.0/tiles}
+
+def tile_number(zoomlevel):
+	return 2**(zoomlevel*2)
+
+def main(argv):
+	global color, input_epsg, target_nodata_value, target_zoomlevel, density_min, density_base
+
+	input_file_path = None
+	output_directory = None
+	statistics = False
+	
+	gdal.UseExceptions()
+
+	parser = argparse.ArgumentParser(description='Generates the digital terrain model from gnuboat logfiles')
+	parser.add_argument('input_file', metavar='input_file_path', type=str,
+						help='JSON file with logfiles and correction data to be processed')
+	parser.add_argument('output_directory', metavar='output_directory', type=str,
+						help='Write the Digital Terrain Model into this directory (output)')
+	parser.add_argument('-s', '--statistics', dest='statistics', action='store_true',
+                        help='Print some statistics of the input and result datasets')
+	parser.add_argument('-p', '--points-min', dest='points_min', type=int,
+                        help='Print min points per {} squaremetre'.format(density_base), default=density_min)
+	arguments = parser.parse_args(argv)
+
+	if arguments.input_file is None:
+		print('ERROR: No input file specified')
+		sys.exit(2)
+	#elif not os.path.exists(arguments.input_file):
+		print('ERROR: Specified input file does not exists: {}'.format(arguments.input_file))
+		sys.exit(3)
+	else:
+		input_file_path = arguments.input_file
+		
+	if arguments.output_directory is None:
+		print('ERROR: No output file specified')
+		sys.exit(2)
+	else:
+		output_directory = arguments.output_directory
+	
+	if arguments.statistics is not None:
+		statistics = arguments.statistics
+		
+	if arguments.points_min is not None:
+		density_min = arguments.points_min
+		
+	gdal_file_contours = os.path.join(output_directory, 'contours_{}_{}'.format(density_min, density_base))
+	print("Cleaning up / Preparing output directory")
+	if os.path.exists(output_directory):
+		for root, dirs, files in os.walk(output_directory):
+			for f in files:
+				os.unlink(os.path.join(root, f))
+			for d in dirs:
+				shutil.rmtree(os.path.join(root, d))
+	else:
+		os.makedirs(output_directory)
+	if os.path.exists(gdal_file_contours):
+		shutil.rmtree(gdal_file_contours)
+	
+
+	with open(input_file_path, 'r') as input_file:
+		logfiles = json.load(input_file)
+	
+	source_data_layer = "tmp_corrected_joined_points"
+	corrected_joined_point_cloud_file_path = os.path.join(output_directory, "{}.csv".format(source_data_layer))
+	try:
+		output_file = open(corrected_joined_point_cloud_file_path, 'w')
+	except IOError as error:
+		print('ERROR: Could not open the output file for the corrected, joined point cloud: {}'.format(error))
+		sys.exit(4)
+	output_file_csv = None
+	fields = ['lon', 'lat', 'water_depth']
+	output_file_csv = csv.DictWriter(output_file, delimiter=',', quotechar='"',
+										fieldnames=fields)
+	output_file_csv.writeheader()
+	csv_callback = CsvCallback(output_file_csv)
+	log_handler = loghandler.LogHandler()
+
+	print("Correcting and combining {} log files".format(len(logfiles)))
+	for logfile in logfiles:
+		stage = logfile["stage"]
+		log_file_path = logfile["file"]
+		
+		# building the log file path
+		if not os.path.isabs(log_file_path):
+			log_file_path = "{}/{}".format(os.path.dirname(input_file_path), log_file_path)
+		# check stage
+		try:
+			stage = float(stage)
+		except ValueError:
+			print("Stage is not convertible into float for file {}. Skipping the file".format(log_file_path))
+			continue
+		# parse, correct and append log file
+		csv_callback.stage_set(stage)
+		result = log_handler.gnuboat_read_file(log_file_path, csv_callback.callback)
+		if result.messages():
+			print('\n'.join(result.errors()))
+		if not result.success():
+			sys.exit(5)
+		
+		print("  {} correct and joined with stage {}".format(log_file_path, stage))
+	output_file.close()
+
+	print("Creating output files")
+	# create ogr file info
+	source_xml_file = os.path.join(output_directory, "tmp_ogr_input_file.vrt")
+	try:
+		output_file = open(source_xml_file, 'wb')
+	except IOError as error:
+		print('ERROR: Could not open the output file for the ogr data source description: {}'.format(error))
+		sys.exit(4)
+	xml_data_source = ET.Element("OGRVRTDataSource")
+	xml_layer = ET.SubElement(xml_data_source, "OGRVRTLayer", {"name": source_data_layer})
+	xml_source = ET.SubElement(xml_layer, "SrcDataSource")
+	xml_source.text = corrected_joined_point_cloud_file_path
+	xml_geometry_type = ET.SubElement(xml_layer, "GeometryType")
+	xml_geometry_type.text = "wkbPoint"
+	xml_layer_system = ET.SubElement(xml_layer, "LayerSRS")
+	xml_layer_system.text = input_epsg
+	xml_geometry_field = ET.SubElement(xml_layer, "GeometryField", {"encoding": "PointFromColumns", "x": "lon", "y": "lat", "z": "water_depth"})
+	xml_tree = ET.ElementTree(xml_data_source)
+	xml_tree.write(output_file, encoding="UTF-8", xml_declaration=False)
+	output_file.close()
+
+	# processing data with gdal
+	ogr.UseExceptions()
+	source_data = ogr.Open(source_xml_file)
+	source_layer = source_data.GetLayer(source_data_layer)
+	source_x_min, source_x_max, source_y_min, source_y_max = source_layer.GetExtent()
+		
+	# create the grid data
+	gdal_file = "/vsimem/water_depth.tif"
+	tile_resolution = tile_width(target_zoomlevel)
+	target_x_res = int(tile_resolution["tile_size"] / tile_resolution["longitude"] * (source_x_max - source_x_min))
+	target_y_res = int(tile_resolution["tile_size"] / tile_resolution["latitude"] * (source_y_max - source_y_min))
+	
+	lon_metre_max = 60 * 1852 * math.cos(math.radians(min(source_y_min, source_y_max))) # metre / degree
+	lat_metre_max = 111694 # metre / degree
+	
+	circle_radius = math.sqrt(density_base) / math.pi
+	radius_x = circle_radius / lon_metre_max
+	radius_y = circle_radius / lat_metre_max
+	gridding_algorithm = "average:radius1={}:radius2={}:angle=0.0:min_points={}:nodata={}".format(radius_x, radius_y, density_min, target_nodata_value)
+	
+	if statistics:
+		print("Source statistics:")
+		print("  source EPSG: {}".format(input_epsg))
+		print("  extents (x_min, y_min, x_max, y_max): {}, {}, {}, {}".format(source_x_min, source_y_min, source_x_max, source_y_max))
+		degree_per_pixel_lon = tile_resolution["longitude"] / tile_resolution["tile_size"]
+		degree_per_pixel_lat = tile_resolution["latitude"] / tile_resolution["tile_size"]
+		print("  degree / pixel x and y: {}, {}".format(degree_per_pixel_lon, degree_per_pixel_lat))
+		print("  metre / pixel x and y: {}, {}".format(degree_per_pixel_lon * lon_metre_max, degree_per_pixel_lat * lat_metre_max))
+		print("  Min density per squaredegree: {}".format(density_min * density_base / lon_metre_max / lat_metre_max))
+		print("  Min density per pixel: {}".format(density_min * density_base / (degree_per_pixel_lon * lon_metre_max) / (degree_per_pixel_lat * lat_metre_max)))
+		print("  gridding algorithm {}".format(gridding_algorithm))
+	
+	grid_options = gdal.GridOptions(
+		outputType = gdal.GDT_Float32,
+		format = "GTiff",
+		width = target_x_res,
+		height = target_y_res,
+		outputSRS = "WGS84",
+		noData = target_nodata_value,
+		layers = source_data_layer,
+		#algorithm = "invdist:power=2.0:smoothing=0.0:radius1=0.0:radius2=0.0:angle=0.0:max_points=0:min_points=0:nodata={}".format(target_nodata_value)
+		algorithm = gridding_algorithm
+	)
+	gdal.Grid(gdal_file, source_xml_file, options = grid_options)
+	print("  Created raster Grid in memory")
+	
+	# hillshade
+	gdal_file_hillshade  = '/vsimem/water_depth_hillshade.tif'
+	gdal.DEMProcessing(gdal_file_hillshade, gdal_file, "hillshade", options = gdal.DEMProcessingOptions(format = "GTiff", zFactor = -1))
+	print("  Created hillshade in memory")
+	
+	# color relief
+	gdal_file_color_relief = '/vsimem/water_depth_color_relief.tif'
+	gdal_file_color_relief_config = os.path.join(output_directory, "tmp_water_depth_color_relief_config.txt")
+	with open(gdal_file_color_relief_config, 'w') as color_config:
+		for depth in colors:
+			color_config.write("{} {}\n".format(depth, colors[depth]))
+	gdal.DEMProcessing(gdal_file_color_relief, gdal_file, "color-relief", options = gdal.DEMProcessingOptions(format = "GTiff", colorFilename = gdal_file_color_relief_config), addAlpha = True)
+	print("  Created color relief in memory")
+	
+	# slopeshade
+	gdal_file_slopeshade  = os.path.join(output_directory, "water_depth_slopeshade.tif")
+	gdal_file_slopeshade_tmp = "/vsimem/tmp_water_depth_slopeshade.tif"
+	gdal_file_slopeshade_config = os.path.join(output_directory, "tmp_water_depth_slopeshade_config.txt")
+	with open(gdal_file_slopeshade_config, 'w') as shade_config:
+		shade_config.write("0 255 255 255\n")
+		shade_config.write("90 0 0 0\n")
+		shade_config.write("270 0 0 0\n")
+		shade_config.write("360 255 255 255\n")
+	gdal.DEMProcessing(gdal_file_slopeshade_tmp, gdal_file, "slope", options = gdal.DEMProcessingOptions(format = "GTiff"), slopeFormat = 'degree', zeroForFlat = True, addAlpha = True)
+	gdal.DEMProcessing(gdal_file_slopeshade, gdal_file_slopeshade_tmp, "color-relief", options = gdal.DEMProcessingOptions(format = "GTiff", colorFilename = gdal_file_slopeshade_config), addAlpha = True)
+	print("  Created slope shade in {}".format(gdal_file_slopeshade))
+	
+	
+	# generate contour lines
+	# @todo Cut Tifs / warp
+	contour_input = gdal.Open(gdal_file, gdalconst.GA_ReadOnly)
+	contour_input_band = contour_input.GetRasterBand(1)
+	#Generate layer to save Contourlines in
+	contour_output = ogr.GetDriverByName("ESRI Shapefile").CreateDataSource(gdal_file_contours)
+	proj = osr.SpatialReference()
+	proj.SetWellKnownGeogCS(input_epsg)
+	for depth in colors:
+		contour_layer = contour_output.CreateLayer('contour_{}_{}_{}'.format(density_min, density_base, depth), srs = proj)
+		field_definition = ogr.FieldDefn("ID", ogr.OFTInteger)
+		contour_layer.CreateField(field_definition)
+		field_definition = ogr.FieldDefn("elev", ogr.OFTReal)
+		contour_layer.CreateField(field_definition)
+		#Generate Contourlines
+		gdal.ContourGenerate(contour_input_band, depth, 0, [], 0, 0, contour_layer, 0, 1)
+	contour_output = None
+	del contour_output
+	
+	# combining hillshade and color relief
+	
+	
+	# cropping the tifs
+	#gdal.Warp('/tmp/gnuboat/test.tif', gdal_file_color_relief, options = gdal.WarpOptions(format = 'GTiff', dstAlpha = True, srcNodata = "255 255 255", dstNodata = target_nodata_value, cutlineDSName = '/tmp/gnuboat/contours/contour-0.shp', cutlineLayer="contour-0", cropToCutline=True))
+
+	# dstNodata is a workaround for not working addAlpha in color-relief
+	gdal_final_result = '/tmp/gnuboat/water_depth_{}_{}.tif'.format(density_min, density_base)
+	gdal_color_relief_alpha_tmp = '/vsimem/tmp_color_relief.tif'
+	gdal.Warp(gdal_final_result, [gdal_file_color_relief, gdal_file_hillshade], options = gdal.WarpOptions(format = 'GTiff', dstAlpha = False, dstNodata = "255 255 255"))
+
+	# generate tiles
+	tile_zoom_option = "0-19"
+	tile_commands = [
+		#combined
+		{"file": gdal_final_result, "title": 'GNUBoat {} datasets per {} squaremetre'.format(density_min, density_base), "output": 'gnuboat_{}_{}'.format(density_min, density_base)},
+	]
+	print("Expanding {} tifs to tiles".format(len(tile_commands)))
+	for tile_command in tile_commands:
+		title = tile_command["title"]
+		output = os.path.join(output_directory, tile_command["output"])
+		os.system('gdal2tiles.py -q -w none -z {} -t "GNUBoat {}" {} {}'.format(tile_zoom_option, title, tile_command["file"], output))
+		print("  Created tiles for {} in {}".format(title, output))
+
+	sys.exit(0)
+
+if __name__ == "__main__":
+	main(sys.argv[1:])
Index: src/common/bin/gnuboat-log-converter
===================================================================
--- src/common/bin/gnuboat-log-converter	(revision ec9e811865ae57c33a65e0c0ebd697938333b06f)
+++ src/common/bin/gnuboat-log-converter	(revision ec9e811865ae57c33a65e0c0ebd697938333b06f)
@@ -0,0 +1,185 @@
+#!/usr/bin/python
+# -*- coding: utf-8 -*-
+'''
+    Copyright (C) 2016 - 2020 EngSaS - Engineering Solutions and Services Langenbach. All rights reserved.
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+'''
+
+import os
+import argparse
+import sys
+import pynmea2
+from enum import Enum
+import csv
+import tempfile
+import subprocess
+
+from gnuboat_common.datahandler import loghandler, logdataset
+
+class Format(Enum):
+    CSV = 1
+    NMEA0183 = 2
+    GPX = 3
+
+class CsvCallback:
+    def __init__(self, output_file):
+        self._output_file = output_file
+
+    def callback(self, dataset):
+        self._output_file.writerow(dataset.to_dict())
+
+def convertToCsv(input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time):
+    try:
+        output_file = open(output_file_path, 'w')
+    except IOError as error:
+        print('ERROR: Could not open the output file: {}'.format(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()
+
+    csv_callback = CsvCallback(output_file_csv)
+    log_handler = loghandler.LogHandler()
+    result = log_handler.gnuboat_read_file(input_file_path, csv_callback.callback, checksums_fix, errors_ignore)
+    if result.messages():
+        print('\n'.join(result.errors()))
+    output_file.close()
+
+def convertToNmea0183(input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time):
+    try:
+        output_file = open(output_file_path, 'w')
+    except IOError as error:
+        print('ERROR: Could not open the output file: {}'.format(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: {}'.format(error))
+        sys.exit(3)
+        
+    log_handler = loghandler.LogHandler()
+    current_row = 1
+    last_row = None
+    for line in input_file:
+        nmea_sentence = log_handler.parse_nmea_sentence(line, checksums_fix)
+        if nmea_sentence is None:
+            print('INFO: Failed to parse nmea sentence ({}) at line {}'.format(line.strip(), current_row))
+            if not errors_ignore:
+                input_file.close()
+                output_file.close()
+                sys.exit(4)
+        else:
+            output_string = str(nmea_sentence['nmea_sentence'])
+            if not strip_time and nmea_sentence['log_timestamp']:
+                output_string = '{}{}'.format(nmea_sentence['log_timestamp'], output_string)
+            output_file.write('{}\r\n'.format(str(output_string)))
+        current_row += 1
+    output_file.close()
+    input_file.close()
+    
+def convertToGpx(input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time):
+    # 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, checksums_fix, 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:
+      formats.append(file_format.name)
+
+    parser = argparse.ArgumentParser(description='Convert gnuboat logfiles into other formats')
+    parser.add_argument('-f', '--format', dest='output_format', type=str,
+                        help='Format of the output file.', choices=formats, default='CSV')
+    parser.add_argument('-i', '--ignore-errors', dest='errors_ignore', action='store_false',
+                        help='Ignore any errors reading the log file')
+    parser.add_argument('-c', '--checksums-fix', dest='checksums_fix', action='store_true',
+                        help='Ignore all checksums (and replace them with a new correct one, if needed)')
+    parser.add_argument('input_file', metavar='input_file_path', type=str,
+                        help='File to be converted (input)')
+    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)
+   
+    if arguments.output_format is not None:
+        format_found = False
+        for file_format in Format:
+            if file_format.name == arguments.output_format:
+               output_format = file_format.value
+               format_found = True
+        if not format_found:
+            print('ERROR: Invalid input format specified: {}'.format(arguments.output_format))
+            sys.exit(1)
+
+    if arguments.errors_ignore is not None:
+        errors_ignore = arguments.errors_ignore
+        
+    if arguments.checksums_fix is not None:
+        checksums_fix = arguments.checksums_fix
+        
+    if arguments.strip_time is not None:
+        strip_time = arguments.strip_time
+            
+    if arguments.input_file is None:
+        print('ERROR: No input file specified')
+        sys.exit(2)
+    #elif not os.path.exists(arguments.input_file):
+        print('ERROR: Specified input file does not exists: {}'.format(arguments.input_file))
+        sys.exit(3)
+    else:
+        input_file_path = arguments.input_file
+        
+    if arguments.output_file is None:
+        print('ERROR: No output file specified')
+        sys.exit(2)
+    elif not os.path.exists(os.path.dirname(arguments.output_file)):
+        print('ERROR: Specified directory of output file does not exists: {}'.format(arguments.output_file))
+        sys.exit(3)
+    else:
+        output_file_path = arguments.output_file
+
+    if output_format == Format.CSV.value: 
+        convertToCsv(input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time)
+    elif output_format == Format.NMEA0183.value:
+        convertToNmea0183(input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time)
+    elif output_format == Format.GPX.value:
+        convertToGpx(input_file_path, output_file_path, errors_ignore, checksums_fix, strip_time)
+    else:
+        print('ERROR: Undefined output format!\n')
+        sys.exit(1)
+
+    sys.exit(0)
+
+if __name__ == "__main__":
+    main(sys.argv[1:])
Index: src/common/gnuboat_common/__init__.py
===================================================================
--- src/common/gnuboat_common/__init__.py	(revision ec9e811865ae57c33a65e0c0ebd697938333b06f)
+++ src/common/gnuboat_common/__init__.py	(revision ec9e811865ae57c33a65e0c0ebd697938333b06f)
@@ -0,0 +1,19 @@
+# -*- coding: utf-8 -*-
+'''
+    Copyright (C) 2017 - 2020 EngSaS - Engineering Solutions and Services Langenbach. All rights reserved.
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+'''
+from .datahandler.loghandler import LogHandler
+from .datahandler.logdataset import LogDataset
Index: src/common/gnuboat_common/datahandler/__init__.py
===================================================================
--- src/common/gnuboat_common/datahandler/__init__.py	(revision ec9e811865ae57c33a65e0c0ebd697938333b06f)
+++ src/common/gnuboat_common/datahandler/__init__.py	(revision ec9e811865ae57c33a65e0c0ebd697938333b06f)
@@ -0,0 +1,22 @@
+# -*- coding: utf-8 -*-
+'''
+    Copyright (C) 2018 - 2020 EngSaS - Engineering Solutions and Services Langenbach. All rights reserved.
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+'''
+
+from .loghandler import LogHandler
+from .logdataset import LogDataset
+
+__all__ = ["loghandler", "logdataset"]
Index: src/common/gnuboat_common/datahandler/logdataset.py
===================================================================
--- src/common/gnuboat_common/datahandler/logdataset.py	(revision ec9e811865ae57c33a65e0c0ebd697938333b06f)
+++ src/common/gnuboat_common/datahandler/logdataset.py	(revision ec9e811865ae57c33a65e0c0ebd697938333b06f)
@@ -0,0 +1,135 @@
+    # -*- coding: utf-8 -*-
+'''
+    Copyright (C) 2016 - 2018 EngSaS - Engineering Solutions and Services Langenbach. All rights reserved.
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+'''
+
+from datetime import datetime, timezone
+from collections import namedtuple
+
+Location = namedtuple('Location', 'latitude longitude')
+
+"""@class Dataset of a log entry
+"""
+class LogDataset:
+	def __init__(self, datetime = None, gps_status = None, latitude = None, latitude_direction = None,
+					longitude = None, longitude_direction = None, speed_over_ground = None,
+					course_over_ground = None, water_depth = None, water_temperature = None):
+		self._datetime = datetime
+		self._gps_status = gps_status
+		self._latitude = latitude
+		self._latitude_direction = latitude_direction
+		self._longitude = longitude
+		self._longitude_direction = longitude_direction
+		self._speed_over_ground = speed_over_ground
+		self._course_over_ground = course_over_ground
+		self._water_depth = water_depth
+		self._water_temperature = water_temperature
+	
+	def datetime(self):
+		return self._datetime
+	
+	def datetime_object(self):
+		if self.datetime() is None:
+			return None
+		return datetime.strptime(self.datetime(), "%Y-%m-%d %H:%M:%S").replace(tzinfo=timezone.utc)
+	
+	def datetime_set(self, datetime):
+		self._datetime = datetime
+	
+	def gps_status(self):
+		return self._gps_status
+	
+	def gps_status_set(self, status):
+		self._gps_status = status
+	
+	def latitude(self):
+		return self._latitude
+	
+	def latitude_set(self, latitude):
+		self._latitude = latitude
+		
+	def latitude_direction(self):
+		return self._latitude_direction
+	
+	def latitude_direction_set(self, direction):
+		self._latitude_direction = direction
+		
+	def longitude(self):
+		return self._longitude
+	
+	def longitude_set(self, longitude):
+		self._longitude = longitude
+		
+	def longitude_direction(self):
+		return self._longitude_direction
+	
+	def longitude_direction_set(self, direction):
+		self._longitude_direction = direction
+		
+	def location(self):
+		if self.latitude_direction() is None:
+			return None
+		elif self.latitude_direction() == 'N':
+			latitude = self.latitude()
+		elif self.latitude_direction() == 'S':
+			latitude = -1.0 * self.latitude()
+		else:
+			return None
+		if self.longitude_direction() is None:
+			return None
+		elif self.longitude_direction() == 'E':
+			longitude = self.longitude()
+		elif self.longitude_direction() == 'W':
+			longitude = -1.0 * self.longitude()
+		else:
+			return None
+		return Location(latitude, longitude)
+	
+	def speed_over_ground(self):
+		return self._speed_over_ground
+	
+	def speed_over_ground_set(self, speed):
+		self._speed_over_ground = speed
+		
+	def course_over_ground(self):
+		return self._course_over_ground
+	
+	def course_over_ground_set(self, course):
+		self._course_over_ground = course
+		
+	def water_depth(self):
+		return self._water_depth
+	
+	def water_depth_set(self, depth):
+		self._water_depth = depth
+		
+	def water_temperature(self):
+		return self._water_temperature
+	
+	def water_temperature_set(self, temperature):
+		self._water_temperature = temperature
+		
+	def to_dict(self):
+		return {'datetime': self.datetime(),
+				'gps_status': self.gps_status(),
+				'latitude': self.latitude(),
+				'latitude_direction': self.latitude_direction(),
+				'longitude': self.longitude(),
+				'longitude_direction': self.longitude_direction(),
+				'speed_over_ground': self.speed_over_ground(),
+				'course_over_ground': self.course_over_ground(),
+				'water_depth': self.water_depth(),
+				'water_temperature': self.water_temperature()}
Index: src/common/gnuboat_common/datahandler/loghandler.py
===================================================================
--- src/common/gnuboat_common/datahandler/loghandler.py	(revision ec9e811865ae57c33a65e0c0ebd697938333b06f)
+++ src/common/gnuboat_common/datahandler/loghandler.py	(revision ec9e811865ae57c33a65e0c0ebd697938333b06f)
@@ -0,0 +1,224 @@
+    # -*- coding: utf-8 -*-
+'''
+    Copyright (C) 2016 - 2020 EngSaS - Engineering Solutions and Services Langenbach. All rights reserved.
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+'''
+
+import os
+import re
+import pynmea2
+import datetime
+from pytz import timezone
+import traceback
+import math
+
+from gnuboat_common.datahandler import logdataset
+
+class LogParsingResult:
+	def __init__(self):
+		self._success = False
+		self._errors = []
+	
+	def error_add(self, error):
+		self._errors.append(error)
+	
+	def errors(self):
+		return self._errors
+	
+	def messages(self):
+		if len(self._errors) > 0:
+			return True
+		return False
+	
+	def succeeded(self, status):
+		self._success = status
+	
+	def success(self):
+		return self._success
+
+"""@class LogHandler
+"""
+class LogHandler:
+	def __init__(self, log_directory = None):
+		self._regex_nmea_sentence = re.compile(r"^([^\$!]{0,})([\$!]{1}[\w]{2}[\w]{3}[^\*]+\*[\da-zA-Z]+)$")
+		self._regex_nmea_sentence_without_checksum = re.compile(r"^([^\$!]{0,})([\$!]{1}[\w]{2}[\w]{3}[^\*]+)\*[\da-zA-Z]+$")
+		self._regex_nmea_position_latitude = re.compile(r"^([0-9]{2})([0-9]{2}\.[0-9]+)$")
+		self._regex_nmea_position_longitude = re.compile(r"^([0-9]{3})([0-9]{2}\.[0-9]+)$")
+		self._log_directory = log_directory
+		self._nmea_file = None
+		self._nmea_file_date = None
+	
+	def gnuboat_write(self, gps_fix, gps_time, dataset, transducer_valid, log_verbose, log_system_time):
+		# Only log, if we have a gps fix
+		if gps_fix < 2:
+			if not log_verbose:
+				return
+			gps_status = 'V'
+			mode = 'N'
+			if gps_time is None:
+				gps_time = datetime.datetime.utcnow()
+		
+		nmea_file_date_should = datetime.datetime.utcnow().strftime("%Y-%m-%d")
+		mode = 'A'
+		if self._nmea_file == None or self._nmea_file_date is None or self._nmea_file_date != nmea_file_date_should:
+			if self._nmea_file:
+					self._nmea_file.close()
+			try:
+				self._nmea_file_date = nmea_file_date_should
+				nmea_log_file = 'nmea0183-{}.log'.format(self._nmea_file_date)
+				self._nmea_file = open(os.path.join(self._log_directory, nmea_log_file), 'a', 0)
+			except IOError as error:
+				print('Could not open the logfile: {}'.format(error))
+				return False
+		else:
+			nmea_log_file = self._nmea_file.name
+
+		latitude = self._degreesDecimalToNmea(dataset.latitude())
+		longitude = self._degreesDecimalToNmea(dataset.longitude())
+
+		logsystemtime = ""
+		if log_system_time:
+			logsystemtime = '{}: '.format(datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S"))
+			
+		try:
+			self._nmea_file.write('{}{}\r\n'.format(logsystemtime, str(pynmea2.RMC('GN', 'RMC',
+														(gps_time.strftime("%H%M%S"), dataset.gps_status(),
+														'{:02d}{:07.4f}'.format(latitude['degrees'], latitude['minutes']),
+														dataset.latitude_direction(),
+														'{:03d}{:07.4f}'.format(longitude['degrees'], longitude['minutes']),
+														dataset.longitude_direction(),
+														'{:04.1f}'.format(dataset.speed_over_ground()), '{:04.1f}'.format(dataset.course_over_ground()),
+														gps_time.strftime("%d%m%y"), '', '', mode)))))
+			if transducer_valid:
+				self._nmea_file.write('{}{}\r\n'.format(logsystemtime, str(pynmea2.DPT('SD', 'DPT', ('{:05.2f}'.format(dataset.water_depth()), '00.00')))))
+				self._nmea_file.write('{}{}\r\n'.format(logsystemtime, str(pynmea2.MTW('YX', 'MTW', ('{:04.1f}'.format(dataset.water_temperature()), 'C')))))
+			return True
+		except:
+			print('Failed writing to logfile {}'.format(nmea_log_file))
+			print(traceback.format_exc())
+			return False
+		return False
+	
+	def gnuboat_close(self):
+		if self._nmea_file:
+			self._nmea_file.close()
+	
+	def parse_nmea_sentence(self, line, checksum_ingore = False):
+		line = line.strip()
+		if checksum_ingore:
+			matches = self._regex_nmea_sentence_without_checksum.match(line)
+		else:
+			matches = self._regex_nmea_sentence.match(line)
+		if matches is None:
+			return None
+		return {'log_timestamp': matches.group(1), 'nmea_sentence': pynmea2.parse(matches.group(2), not checksum_ingore)}
+	
+	"""	Reads the original gnuboat log files and calls a callable function on all complete LogDataset
+		callback must be of a function wich excepts the LogDataset as a parameter.
+	"""
+	def gnuboat_read_file(self, input_file_path, callback, checksums_fix = False, errors_ignore = False):
+		result = LogParsingResult()
+		
+		# reading input file
+		try:
+			input_file = open(input_file_path, 'r')
+		except IOError as error:
+			result.error_add('ERROR: Could not open the input file: {}'.format(error))
+			result.succeeded(False)
+			return result
+		result = self.gnuboat_read(input_file, callback, checksums_fix, errors_ignore = False)
+		input_file.close()
+		return result
+
+	"""	Reads the original gnuboat log from input_list and calls a callable function on all complete LogDataset
+		callback must be of a function wich excepts the LogDataset as a parameter.
+	"""
+	def gnuboat_read(self, input_list, callback, checksums_fix = False, errors_ignore = False):
+		result = LogParsingResult()
+		
+		current_row = 1
+		last_row = None
+		for line in input_list:
+			nmea_sentence = self.parse_nmea_sentence(line, checksums_fix)
+			if nmea_sentence is None:
+				result.error_add('INFO: Failed to parse nmea sentence ({}) at line {}'.format(line.strip(), current_row))
+				if not errors_ignore:
+					result.succeeded(False)
+					return result
+			else:
+				nmea_sentence = nmea_sentence['nmea_sentence']
+				if nmea_sentence.sentence_type == 'RMC':
+					if last_row is not None:
+						callback(last_row)
+					last_row = logdataset.LogDataset()
+					last_row.datetime_set('{} {}'.format(nmea_sentence.datestamp, nmea_sentence.timestamp))
+					last_row.gps_status_set(nmea_sentence.status)
+					last_row.latitude_set(self._nmeaLatitudeToDecimalDegrees(nmea_sentence.lat, current_row))
+					last_row.latitude_direction_set(nmea_sentence.lat_dir)
+					last_row.longitude_set(self._nmeaLongitudeToDecimalDegrees(nmea_sentence.lon, current_row))
+					last_row.longitude_direction_set(nmea_sentence.lon_dir)
+					last_row.speed_over_ground_set(self._to_float(nmea_sentence.spd_over_grnd, current_row))
+					last_row.course_over_ground_set(self._to_float(nmea_sentence.true_course, current_row))
+					last_row.water_depth_set(None)
+					last_row.water_temperature_set(None)
+				elif nmea_sentence.sentence_type == 'DPT' and last_row is not None:
+					last_row.water_depth_set(self._to_float(nmea_sentence.depth, current_row))
+				elif nmea_sentence.sentence_type == 'MTW' and last_row is not None:
+					last_row.water_temperature_set(self._to_float(nmea_sentence.temperature, current_row))
+			current_row += 1
+		if last_row is not None:
+			callback(last_row)
+		result.succeeded(True)
+		return result
+
+	def _to_float(self, string, current_row):
+		try:
+			return float(string)
+		except ValueError as error:
+			try:
+				return int(string)
+			except ValueError as error:
+				print('INFO: Failed to convert value from line {} into numeric: {}\n      Message: {}'.format(current_row, string, error))
+				return 0
+
+	def _nmeaLatitudeToDecimalDegrees(self, nmea_value, current_row):
+		if self._to_float(nmea_value, current_row) == 0:
+			return 0
+
+		matches = self._regex_nmea_position_latitude.match(nmea_value)
+		if matches is None:
+			print('INFO: Failed to convert latitude position value from line {} into decimal degrees: {}'.format(current_row, nmea_value))
+			return
+		decimalDegrees = self._to_float(matches.group(1), current_row)
+		decimalMinutes = self._to_float(matches.group(2), current_row)
+		return decimalDegrees + (decimalMinutes / 60.0)
+
+	def _nmeaLongitudeToDecimalDegrees(self, nmea_value, current_row):
+		if self._to_float(nmea_value, current_row) == 0:
+			return 0
+
+		matches = self._regex_nmea_position_longitude.match(nmea_value)
+		if matches is None:
+			print('INFO: Failed to convert longitude position value from line {} into decimal degrees: {}'.format(current_row, nmea_value))
+			return
+		decimalDegrees = self._to_float(matches.group(1), current_row)
+		decimalMinutes = self._to_float(matches.group(2), current_row)
+		return decimalDegrees + (decimalMinutes / 60.0)
+
+
+	def _degreesDecimalToNmea(self, decimalDegrees):
+		degrees = int(math.floor(decimalDegrees))
+		minutes = 60.0 * (decimalDegrees - degrees)
+		return { 'degrees': degrees, 'minutes': minutes}
Index: src/common/setup.py
===================================================================
--- src/common/setup.py	(revision ec9e811865ae57c33a65e0c0ebd697938333b06f)
+++ src/common/setup.py	(revision ec9e811865ae57c33a65e0c0ebd697938333b06f)
@@ -0,0 +1,49 @@
+#!/usr/bin/python
+# -*- coding: utf-8 -*-
+'''
+    Copyright (C) 2017 - 2020 EngSaS - Engineering Solutions and Services Langenbach. All rights reserved.
+
+    This program is free software: you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation, either version 3 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License
+    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+'''
+import os
+from setuptools import setup, find_packages
+
+readme = open('README', 'r')
+README_TEXT = readme.read()
+readme.close()
+#NEEDS_PYTEST = {'pytest', 'test', 'ptr'}.intersection(sys.argv)
+#PYTEST_RUNNER = ['pytest-runner'] if NEEDS_PYTEST else []
+reqs_install = [
+	"python-dateutil",
+	"pytz",
+	"pynmea2",
+	"gdal",
+]
+
+setup(
+  name="gnuboat_common",
+  version="0.4.6",
+  maintainer="EngSaS - Langenbach",
+  maintainer_email="info@engsas.de",
+  description=("Tools shared by gunboat python packages"),
+  license="GNU General Public License v3 or later (GPLv3+)",
+  keywords="",
+  url="http://trac.engsas.de/gnuboat",
+  #package_dir={'': ''},
+  packages=find_packages(),
+  scripts=["bin/gnuboat-log-converter", "bin/gnuboat-log-analyser"],
+  long_description=README_TEXT,
+  install_requires=reqs_install,
+# setup_requires=[] + PYTEST_RUNNER,
+)
Index: src/common/tox.ini
===================================================================
--- src/common/tox.ini	(revision ec9e811865ae57c33a65e0c0ebd697938333b06f)
+++ src/common/tox.ini	(revision ec9e811865ae57c33a65e0c0ebd697938333b06f)
@@ -0,0 +1,9 @@
+[tox]
+envlist = py36
+#skipsdist = True
+
+[testenv]
+deps =
+	pytest
+commands =
+	pytest
