Index: src/common/bin/gnuboat-log-analyser
===================================================================
--- src/common/bin/gnuboat-log-analyser	(revision 9f5877dc45dcf00238a6d2e688fcc536e3373191)
+++ src/common/bin/gnuboat-log-analyser	(revision 5e16955853266e68c24fd278d8f0c96f74f4120c)
@@ -19,4 +19,5 @@
 
 import os
+import pathlib
 import argparse
 import sys
@@ -25,4 +26,5 @@
 import csv
 import xml.etree.ElementTree as ET
+import tempfile
 from osgeo import ogr
 from osgeo import osr
@@ -30,4 +32,6 @@
 from osgeo import gdalconst
 import shutil
+import progressbar
+from time import process_time
 
 from gnuboat_common.datahandler import loghandler, logdataset
@@ -52,4 +56,8 @@
 		self._output_file = output_file
 		self._stage = None
+		self._resultsets = 0
+		
+	def count(self):
+		return self._resultsets
 		
 	def stage_set(self, stage):
@@ -65,4 +73,5 @@
 		water_depth = dataset.water_depth() - self._stage
 		self._output_file.writerow({"lon": dataset.longitude(), "lat": dataset.latitude(), "water_depth": water_depth})
+		self._resultsets += 1
 
 def tile_width(zoomlevel):
@@ -80,4 +89,5 @@
 	output_directory = None
 	statistics = False
+	tile_sizes = [256]
 	
 	gdal.UseExceptions()
@@ -88,8 +98,14 @@
 	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)
+	parser.add_argument('-v', '--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, default=density_min,
+						help='Minimum points per {} squaremetre is needed to create a valid depth information'.format(density_base))
+	parser.add_argument('-z', '--zoomlevels', dest='zoom_range', nargs=2, default=[10, 19], type=int,
+						help='Creates tiles for the specified range of zoomlevels')
+	parser.add_argument('--high-res', dest='high_res', action='store_true',
+						help='Creates tiles with 512 pixel per tile additionally to the 256 pixel per tile tiles')
+	parser.add_argument('-m', '--raster_file_max', dest='raster_file_size_max', default=1024, type=int,
+						help='Maximum size of temporary raster Tifs for tile generation in MB')
 	arguments = parser.parse_args(argv)
 
@@ -97,5 +113,5 @@
 		print('ERROR: No input file specified')
 		sys.exit(2)
-	#elif not os.path.exists(arguments.input_file):
+	elif not os.path.exists(arguments.input_file):
 		print('ERROR: Specified input file does not exists: {}'.format(arguments.input_file))
 		sys.exit(3)
@@ -114,18 +130,16 @@
 	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)
-	
+	
+	if arguments.zoom_range is not None:
+		zoom_range = arguments.zoom_range
+	
+	if arguments.high_res is not None:
+		tile_sizes.append(512)
+		
+	if arguments.raster_file_size_max is not None:
+		raster_file_size_max = arguments.raster_file_size_max
+		
+	# create temporary directory
+	temp_directory = tempfile.mkdtemp(prefix='gnuboat-log-analyser')
 
 	with open(input_file_path, 'r') as input_file:
@@ -133,5 +147,5 @@
 	
 	source_data_layer = "tmp_corrected_joined_points"
-	corrected_joined_point_cloud_file_path = os.path.join(output_directory, "{}.csv".format(source_data_layer))
+	corrected_joined_point_cloud_file_path = os.path.join(temp_directory, "{}.csv".format(source_data_layer))
 	try:
 		output_file = open(corrected_joined_point_cloud_file_path, 'w')
@@ -149,5 +163,6 @@
 	print("Correcting and combining {} log files".format(len(logfiles)))
 	for logfile in logfiles:
-		stage = logfile["stage"]
+		gaugeHeight = logfile["gaugeHeight"]
+		referenceWaterLevelGaugeHeight = logfile["referenceWaterLevelGaugeHeight"]
 		log_file_path = logfile["file"]
 		
@@ -157,10 +172,16 @@
 		# check stage
 		try:
-			stage = float(stage)
+			gaugeHeight = float(gaugeHeight)
 		except ValueError:
-			print("Stage is not convertible into float for file {}. Skipping the file".format(log_file_path))
+			print("gaugeHeight is not convertible into float for file {}. Skipping the file".format(log_file_path))
+			continue
+		try:
+			referenceWaterLevelGaugeHeight = float(referenceWaterLevelGaugeHeight)
+		except ValueError:
+			print("referenceWaterLevelGaugeHeight 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)
+		difference = referenceWaterLevelGaugeHeight - gaugeHeight
+		csv_callback.stage_set(difference)
 		result = log_handler.gnuboat_read_file(log_file_path, csv_callback.callback)
 		if result.messages():
@@ -169,10 +190,11 @@
 			sys.exit(5)
 		
-		print("  {} correct and joined with stage {}".format(log_file_path, stage))
+		print("  {} correct and joined with difference {:.3f}m".format(log_file_path, difference))
 	output_file.close()
-
-	print("Creating output files")
+	print ('  Processed {} points'.format(csv_callback.count()))
+
+	print("Generating tiles")
 	# create ogr file info
-	source_xml_file = os.path.join(output_directory, "tmp_ogr_input_file.vrt")
+	source_xml_file = os.path.join(temp_directory, "tmp_ogr_input_file.vrt")
 	try:
 		output_file = open(source_xml_file, 'wb')
@@ -192,7 +214,48 @@
 	xml_tree.write(output_file, encoding="UTF-8", xml_declaration=False)
 	output_file.close()
-
-	tilegen = tilegenerator.TileGenerator(zoom_range=5-19, debug=statistics)
-	tilegen.run(source_xml_file, output_directory)
+	
+	# 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)
+	
+	# get source boundaries (Envelope / Extent)
+	datasource = ogr.Open(source_xml_file)
+	if datasource is None:
+		raise FileNotFoundError('Could not open input file {}'.format(source_xml_file))
+	if datasource.GetLayerCount() < 1:
+		raise ReferenceError('No layers in input file') 
+	source_layer = datasource.GetLayerByIndex(0)
+	source_x_min, source_x_max, source_y_min, source_y_max = source_layer.GetExtent()
+
+	tilegen = tilegenerator.TileGenerator(tile_sizes = tile_sizes, densities = [density_min], density_base = density_base, debug=statistics)
+	slices = tilegen.slices(source_xml_file, tilegenerator.ZoomRange(zoom_range[0], zoom_range[1]), raster_file_size_max = raster_file_size_max * 1024 * 1024 * 8)
+	slices_count = len(slices)
+	print('Generated {} slices for rastering'.format(slices_count))
+	
+	t1_start = process_time() 
+	print('Rastering slices and generating tiles')
+	with progressbar.ProgressBar(max_value=slices_count, redirect_stdout=True) as bar:
+		i = 1
+		for tile_slice in slices:
+			if statistics:
+				print(' Generating tiles for slice {} in {}'.format(i, temp_directory))
+			result_paths = tilegen.run(source_xml_file, temp_directory, tile_slice)
+			for path in result_paths:
+				tilegen.move_tiles_in_place(path.path, os.path.join(output_directory, path.prefixes['density'], path.prefixes['tile_size']))
+			bar.update(i)
+			i += 1
+	t1_stop = process_time() 
+	print('  Tooks {:.2f} hours'.format((t1_stop - t1_start) / 60 / 60))
+
+	# delete temporary directory
+	shutil.rmtree(temp_directory)
+	
+	print('Generated tiles in {}'.format(output_directory))
 
 	sys.exit(0)
Index: src/common/bin/gnuboat-log-uploader
===================================================================
--- src/common/bin/gnuboat-log-uploader	(revision 5e16955853266e68c24fd278d8f0c96f74f4120c)
+++ src/common/bin/gnuboat-log-uploader	(revision 5e16955853266e68c24fd278d8f0c96f74f4120c)
@@ -0,0 +1,197 @@
+#!/usr/bin/python
+# -*- coding: utf-8 -*-
+'''
+    Copyright (C) 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 sys
+import json
+import requests
+import argparse
+
+class Log:
+	"""
+		Workaround for @dataclass, until python 3.7 is available in main distros
+	"""
+	def __init__(self, water_id, device_id, gauge_id, gauge_height, comment, logfile):
+		self.water_id = water_id
+		self.device_id = device_id
+		self.gauge_id = gauge_id
+		self.gauge_height = gauge_height
+		self.comment = comment
+		self.logfile = logfile
+		
+	def log_creation(self):
+		return {
+			'water': self.water_id,
+			'device': self.device_id,
+			'gauge': self.gauge_id,
+			'gaugeHeight': self.gauge_height,
+			'comment': self.comment
+		}
+
+def to_int(value_string):
+	try:
+		return int(value_string)
+	except:
+		return None
+
+def to_float(value_string):
+	try:
+		return float(value_string)
+	except:
+		return None
+
+def header(api_key):
+	return {
+		'X-API-KEY': api_key
+	#	'Content-type': 'multipart/form-data'
+	}
+
+def create_log(log, url, api_key):
+	response = requests.post(url,
+		json = log.log_creation(),
+		headers = header(api_key)
+	)
+	
+	if response.status_code != 200:
+		print('ERROR: Could not create LogMetaData for logfile {}'.format(log.logfile))
+		print('  Response status code: {}'.format(response.status_code))
+		print('  Response:             \n{}'.format(response.text))
+		print('  Request headers:      {}'.format(response.request.headers))
+		print('  Request body:         {}'.format(response.request.body))
+		sys.exit(5)
+		
+	data = response.json()
+	if not 'logId' in data:
+		print('ERROR: No log id returned')
+		sys.exit(6)
+	return data["logId"]
+
+def upload_log(log_id, log, url, api_key):
+	fileContent = open(log.logfile, 'rb')
+	headers = header(api_key)
+	headers["Accept"] = "application/json"
+	response = requests.post(
+		"{}/{}".format(url, log_id),
+		data = fileContent,
+		headers = headers
+	)
+	if response.status_code != 200:
+		print('ERROR: Could not upload log for logfile {}'.format(log.logfile))
+		print("Response status code: {}".format(response.status_code))
+		print("Response:             \n{}".format(response.text))
+		sys.exit(7)
+
+def main(argv):
+	input_file_path = None
+	url = None
+	api_key = None
+	
+	parser = argparse.ArgumentParser(description='Uploads logfiles to GNUBoat server')
+	parser.add_argument('input_file', metavar='input_file_path', type=str,
+						help='JSON file with water, gauge, device, logfiles and correction data to be processed')
+	parser.add_argument('-s', '--server', dest='server', type=str,
+                        help='Server host and port to upload the logsfiles to')
+	parser.add_argument('-k', '--api-key', dest='api_key', type=str,
+                        help='API Key for authorisation')
+	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.server is None:
+		print('ERROR: No server specified')
+		sys.exit(2)
+	else:
+		url = 'http://{}/mapservice/v1/logs'.format(arguments.server)
+		
+	if arguments.api_key is None:
+		print('ERROR: No API key specified')
+		sys.exit(2)
+	else:
+		api_key = arguments.api_key
+		
+	logs_checked = []
+	print('Checking input from {}'.format(input_file_path))
+	with open(input_file_path, 'r') as input_file:
+		logs = json.load(input_file)
+		for log in logs:
+			if not 'water' in log:
+				print('ERROR: No water in log {}'.format(json.dumps(log)))
+				sys.exit(4)
+			water_id = to_int(log['water'])
+			if not water_id:
+				print('ERROR: Could not convert water to int {}'.format(log['water']))
+				sys.exit(4)
+			
+			if not 'gauge' in log:
+				print('ERROR: No gauge in log {}'.format(json.dumps(log)))
+				sys.exit(4)
+			gauge_id = to_int(log['gauge'])
+			if not gauge_id:
+				print('ERROR: Could not convert gauge to int {}'.format(log['gauge']))
+				sys.exit(4)
+				
+			if not 'device' in log:
+				print('ERROR: No device in log {}'.format(json.dumps(log)))
+				sys.exit(4)
+			device_id = to_int(log['device'])
+			if not device_id:
+				print('ERROR: Could not convert device to int {}'.format(log['device']))
+				sys.exit(4)
+				
+			if not 'gaugeHeight' in log:
+				print('ERROR: No gaugeHeight in log {}'.format(json.dumps(log)))
+				sys.exit(4)
+			gauge_height = to_float(log['gaugeHeight'])
+			if not gauge_height:
+				print('ERROR: Could not convert gaugeHeight to float {}'.format(log['gaugeHeight']))
+				sys.exit(4)
+				
+			if not 'file' in log:
+				print('ERROR: No file in log {}'.format(json.dumps(log)))
+				sys.exit(4)
+				
+			comment = ''
+			if 'comment' in log:
+				comment = log['comment']
+			
+			logfile = os.path.join(os.path.dirname(__file__), log['file'])
+			if not os.path.exists(logfile):
+				logfile_rel = os.path.join(os.path.dirname(input_file_path), log['file'])
+				if not os.path.exists(logfile_rel):
+					print('ERROR: Logfile not found at {} or {}'.format(logfile, logfile_rel))
+					sys.exit(4)
+				else:
+					logfile = logfile_rel
+			logs_checked.append(Log(water_id, device_id, gauge_id, gauge_height, comment, logfile))
+	
+	print('Uploading {} logs'.format(len(logs_checked)))
+	for log in logs_checked:
+		log_id = create_log(log, url, api_key)
+		upload_log(log_id, log, url, api_key)
+		print(' Finished {}'.format(log.logfile))
+
+if __name__ == "__main__":
+	main(sys.argv[1:])
