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:])
Index: src/common/gnuboat_common/spatial/tilegenerator.py
===================================================================
--- src/common/gnuboat_common/spatial/tilegenerator.py	(revision 9f5877dc45dcf00238a6d2e688fcc536e3373191)
+++ src/common/gnuboat_common/spatial/tilegenerator.py	(revision 5e16955853266e68c24fd278d8f0c96f74f4120c)
@@ -26,4 +26,116 @@
 import subprocess
 import math
+import copy
+
+try:
+	from dataclasses import dataclass
+	
+	#@dataclass
+	#class TileWidth:
+		#"""
+			#tile_size: The tile size in Pixel,
+			#longitude: The width of the Tile in decimal degrees
+			#latitude:  The height of the Tile in decimal degrees
+		#"""
+		#tile_size: int
+		#longitude: float
+		#latitude: float
+	
+	@dataclass
+	class ResultPath:
+		"""
+			path: Absolute path of the created results
+			prefixes: Dict with meaningful prefixes in the path. e.g. {'tile_size': '512', 'density': '10_100'}
+		"""
+		path: str
+		prefixes: dict
+		
+except ImportError:
+	#class TileWidth:
+		#"""
+			#Workaround for @dataclass, until python 3.7 is available in main distros
+		#"""
+		#def __init__(self, tile_size, longitude, latitude):
+			#self.tile_size = tile_size
+			#self.longitude = longitude
+			#self.latitude = latitude
+	
+	class ResultPath:
+		"""
+			path: Absolute path of the created results
+			prefixes: Dict with meaningful prefixes in the path. e.g. {'tile_size': '512', 'density': '10_100'}
+		"""
+		def __init__(self, path, prefixes):
+			self.path = path
+			self.prefixes = prefixes
+
+class ZoomRange(dict):
+	def __init__(self, minimum, maximum):
+		super(ZoomRange, self).__init__({'minimum': minimum, 'maximum': maximum})
+		
+	def minimum(self):
+		return self['minimum']
+	
+	def maximum(self):
+		return self['maximum']
+	
+	def from_dict(dictionary):
+		return ZoomRange(dictionary['minimum'], dictionary['maximum'])
+
+class LngLatBbox(dict):
+	def __init__(self, east, south, west, north):
+		super(LngLatBbox, self).__init__({'east': east, 'south': south, 'west': west, 'north': north})
+		
+	def east(self):
+		return self['east']
+	
+	def south(self):
+		return self['south']
+	
+	def west(self):
+		return self['west']
+	
+	def north(self):
+		return self['north']
+		
+	def to_mercantile_bbox(self):
+		return mercantile.LngLatBbox(self.west(), self.south(), self.east(), self.north())
+	
+	def from_mercantile_bbox(mercantile_bbox):
+		return LngLatBbox(mercantile_bbox.east, mercantile_bbox.south, mercantile_bbox.west, mercantile_bbox.north)
+	
+	def from_dict(dictionary):
+		return LngLatBbox(dictionary['east'], dictionary['south'], dictionary['west'], dictionary['north'])
+
+class RasterSlice(dict):
+	"""
+		lng_lat_box: LngLatBbox
+		zoom_range: ZoomRange
+		tile_size: The tile size in Pixel,
+		grid_width: The width of the resulting rastr
+		grid_height:  The height of the resulting rastr
+		
+		It's derived from dict to be json serialisable
+	"""
+	def __init__(self, lng_lat_box, zoom_range, tile_size, grid_width, grid_height):
+		super(RasterSlice, self).__init__({'lng_lat_box': lng_lat_box, 'zoom_range': zoom_range, 'tile_size': tile_size, 'grid_width': grid_width, 'grid_height': grid_height})
+		
+	def lng_lat_box(self):
+		return self['lng_lat_box']
+	
+	def zoom_range(self):
+		return self['zoom_range']
+	
+	def tile_size(self):
+		return self['tile_size']
+	
+	def grid_width(self):
+		return self['grid_width']
+	
+	def grid_height(self):
+		return self['grid_height']
+	
+	def from_dict(dictionary):
+		return RasterSlice(LngLatBbox.from_dict(dictionary['lng_lat_box']), ZoomRange.from_dict(dictionary['zoom_range']), dictionary['tile_size'], dictionary['grid_width'], dictionary['grid_height'])
 
 class TileGenerator:
@@ -35,7 +147,6 @@
 		- nodata_value = Value used for pixels without valid data
 	"""
-	def __init__(self, tile_sizes = [256, 512], zoom_range = [14, 19], densities = [10, 100], density_base = 100, nodata_value = -999.0, debug=False):
+	def __init__(self, tile_sizes = [256, 512], densities = [10, 100], density_base = 100, nodata_value = -999.0, debug=False):
 		self._tile_sizes = tile_sizes
-		self._zoom_range = zoom_range
 		self._densities = densities
 		self._density_base = density_base
@@ -54,14 +165,82 @@
 		ogr.UseExceptions()
 
-	def run(self, input_file, output_directory, tile_sizes = None, zoom_range = None, densities = None, density_base = None, nodata_value = None):
+	def fit_extent_to_tiles(self, lng_lat_box, zoom_range):
+		"""
+			Enlarges the extent (given by lng_lat_box) to the borders of the tiles
+			lng_lat_box is of Type LngLatBbox
+		"""
+		tile_bounding = mercantile.bounding_tile(lng_lat_box.west, lng_lat_box.south, lng_lat_box.east, lng_lat_box.north)
+		if tile_bounding.z > zoom_range.minimum():
+			return LngLatBbox.from_mercantile_bbox(mercantile.bounds(mercantile.parent(tile_bounding, zoom=zoom_range.minimum())))
+		else:
+			return LngLatBbox.from_mercantile_bbox(mercantile.bounds(tile_bounding))
+
+	def slices(self, input_file, zoom_range, tile_sizes = None, raster_file_size_max = 1024 * 1024 * 1024 * 8):
+		"""
+			Slice the complete area of input_file into smaller pieces,
+			so that each created raster file is smaller than raster_file_size_max
+			and cut into pieces at the borders of tiles and not thorugh tiles.
+			It returns an array of latitude longitude boxes representaing the borders, per slice.
+		"""
+		if tile_sizes is None:
+			tile_sizes = self._tile_sizes
+		
+		datasource = self._datasource_open(input_file)
+		source_layer = datasource.GetLayerByIndex(0)
+		west, east, south, north = source_layer.GetExtent()
+		
+		raster_slices = []
+		for tile_size in tile_sizes:
+			# fitting to tile borders
+			lng_lat_box = self.fit_extent_to_tiles(mercantile.LngLatBbox(west, south, east, north), zoom_range)
+			tiles_zoom_min = mercantile.tiles(lng_lat_box.west(), lng_lat_box.south(), lng_lat_box.east(), lng_lat_box.north(), zoom_range.minimum())
+					
+			# calculating size of raster file for GDT_Float32 = 24bits (at least the tif'S seen at my pc)
+			tile_count_max =  math.floor(raster_file_size_max / (tile_size**2 * 24))
+			delta_zoom = math.floor(math.log(tile_count_max) / math.log(4))
+			steps = math.floor((zoom_range.maximum() - zoom_range.minimum()) / delta_zoom)
+			zoom_steps = []
+			step = zoom_range.minimum()
+			while step < zoom_range.maximum():
+				zoom_steps.append(step)
+				if step + math.floor(1.5 * delta_zoom) > zoom_range.maximum():
+					break
+				step += delta_zoom
+			for tile in tiles_zoom_min:
+				raster_slices += self._slice_tile(tile, zoom_steps, zoom_range.maximum(), tile_count_max, tile_size)
+		return raster_slices
+
+	def _slice_tile(self, parent_tile, zoom_steps, zoom_total_max, tiles_per_slice, tile_size):
+		if len(zoom_steps) < 1:
+			raise ValueError('No zoomsteps given to slice tile generation')
+		zoom_min = zoom_steps[0]
+		if len(zoom_steps) < 2:
+			zoom_max = zoom_total_max
+		else:
+			zoom_max = zoom_steps[1] - 1
+		
+		raster_slices = []
+		lng_lat_box = mercantile.bounds(parent_tile) 
+		width = math.sqrt(4**(zoom_max - zoom_min)) * tile_size
+		if width != round(width):
+			raise ValueError('Found a slice, with incomplete tiles')
+		raster_slice = RasterSlice(LngLatBbox.from_mercantile_bbox(lng_lat_box), ZoomRange(zoom_min, zoom_max), tile_size, width, width)
+		raster_slices.append(raster_slice)
+		if len(zoom_steps) > 1:
+			zoom_steps_new = copy.deepcopy(zoom_steps)
+			zoom_steps_new.pop(0)
+			zoom_min_new = zoom_steps_new[0]
+			for child in mercantile.children(parent_tile, zoom=zoom_min_new):
+				raster_slices += self._slice_tile(child, zoom_steps_new, zoom_total_max, tiles_per_slice, tile_size)
+		return raster_slices
+
+
+	def run(self, input_file, output_directory, tile_slice, densities = None, density_base = None, nodata_value = None):
 		"""
 			Runs all nescessary steps to create the tiles.
 			All default parameters equal to none are replaced by the one of the object
 			input_file = vrt source file used as a base for all steps to creating the tiles
-		"""
-		if tile_sizes is None:
-			tile_sizes = self._tile_sizes
-		if zoom_range is None:
-			zoom_range = self._zoom_range
+			Returns an array of paths with the created tiles if successfull
+		"""
 		if densities is None:
 			densities = self._densities
@@ -72,9 +251,5 @@
 		
 		# get source boundaries (Envelope / Extent)
-		datasource = ogr.Open(input_file)
-		if datasource is None:
-			raise FileNotFoundError('Could not open input file {}'.format(input_file))
-		if datasource.GetLayerCount() < 1:
-			raise ReferenceError('No layers in input file') 
+		datasource = self._datasource_open(input_file)
 		source_layer = datasource.GetLayerByIndex(0)
 		source_x_min, source_x_max, source_y_min, source_y_max = source_layer.GetExtent()
@@ -88,42 +263,36 @@
 		radius_y = circle_radius / lat_metre_max
 		
+		tile_result_paths = []
 		for density_min in densities:
-			for tile_size in tile_sizes:
-				gridding_algorithm = 'average:radius1={}:radius2={}:angle=0.0:min_points={}:nodata={}'.format(radius_x, radius_y, density_min, nodata_value)
+			gridding_algorithm = 'average:radius1={}:radius2={}:angle=0.0:min_points={}:nodata={}'.format(radius_x, radius_y, density_min, nodata_value)
+			if self._debug:
+				print("Run for density {} and {} tile size:".format(density_min, tile_slice.tile_size()))
+				print("  Statistics:")
+				print("    Found {} Points".format(source_layer.GetFeatureCount()))
+				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))
 				
-				tile_resolution = self._tile_width(tile_size, zoom_range[1])
-				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))
-				
-				if self._debug:
-					print("Run for density {} and {} tile size:".format(density_min, tile_size))
-					print("  Statistics:")
-					print("    Found {} Points".format(source_layer.GetFeatureCount()))
-					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))
-					
-				# create the grid data
-				raster_file = self.raster_create(input_file, source_layer_name, target_x_res, target_y_res, gridding_algorithm)
-				# hillshade
-				hillshade_file = self.hillshade_create(raster_file)
-				# color relief
-				color_relief_file = self.color_relief_create(raster_file)
-				# slopeshade
-				slopeshade_file = os.path.join(output_directory, 'water_depth_slopeshade.tif')
-				slopeshade_file = self.slopeshade_create(raster_file, slopeshade_file)
-				# merge color relief and hillshade
-				merged_file = os.path.join(output_directory, 'water_depth_{}_{}.tif'.format(density_min, density_base))
-				self.merge_color_relief_hillshade(color_relief_file, hillshade_file, merged_file)
-				# create the tiles
-				title = 'GNUBoat {} datasets per {} squaremetre, Tilesize: {}'.format(density_min, density_base, tile_size)
-				tiles_output = os.path.join(output_directory, '{}_{}/{}'.format(density_min, density_base, tile_size))
-				self.tiles_create(merged_file, title, tile_size, tiles_output)
-
-	def raster_create(self, input_file, layers, width, height, gridding_algorithm, nodata_value=None, output_file='/vsimem/water_depth.tif'):
+			# create the grid data
+			raster_file = self.raster_create(input_file, source_layer_name, tile_slice, gridding_algorithm)
+			# hillshade
+			hillshade_file = self.hillshade_create(raster_file)
+			# color relief
+			color_relief_file = self.color_relief_create(raster_file)
+			# slopeshade
+			slopeshade_file = os.path.join(output_directory, 'water_depth_slopeshade.tif')
+			slopeshade_file = self.slopeshade_create(raster_file, slopeshade_file)
+			# merge color relief and hillshade
+			merged_file = os.path.join(output_directory, 'water_depth_{}_{}.tif'.format(density_min, density_base))
+			self.merge_color_relief_hillshade(color_relief_file, hillshade_file, merged_file)
+			# create the tiles
+			title = 'GNUBoat {} datasets per {} squaremetre, Tilesize: {}'.format(density_min, density_base, tile_slice.tile_size())
+			prefix_density = '{}_{}'.format(density_min, density_base)
+			tiles_output = os.path.join(output_directory, '{}/{}'.format(prefix_density, tile_slice.tile_size()))
+			self.tiles_create(merged_file, title, tile_slice.tile_size(), tiles_output, zoom_range = tile_slice.zoom_range())
+			tile_result_paths.append(ResultPath(tiles_output, {'tile_size': str(tile_slice.tile_size()), 'density': prefix_density}))
+		return tile_result_paths
+
+	def raster_create(self, input_file, layers, tile_slice, gridding_algorithm, nodata_value=None, output_file='/vsimem/water_depth.tif'):
 		"""
 			Rastering the data from source file into a tif.
@@ -137,9 +306,11 @@
 			outputType = gdal.GDT_Float32,
 			format = "GTiff",
-			width = width,
-			height = height,
+			width = tile_slice.grid_width(),
+			height = tile_slice.grid_height(),
 			outputSRS = "WGS84",
+			outputBounds = [tile_slice.lng_lat_box().east(), tile_slice.lng_lat_box().south(), tile_slice.lng_lat_box().west(), tile_slice.lng_lat_box().north()],
 			noData = nodata_value,
 			layers = layers,
+			#spatFilter = (tile_slice.lng_lat_box().east(), tile_slice.lng_lat_box().south(), tile_slice.lng_lat_box().west(), tile_slice.lng_lat_box().north()), 
 			algorithm = gridding_algorithm
 		)
@@ -187,20 +358,38 @@
 		return output_file
 
-	def tiles_create(self, input_file, title, tile_size, output_directory, zoom_range = None):
-		if zoom_range is None:
-			zoom_range = self._zoom_range
-		
-		tile_zoom_option = "-".join(map(str, zoom_range))
+	def tiles_create(self, input_file, title, tile_size, output_directory, zoom_range):
+		tile_zoom_option = '{}-{}'.format(zoom_range.minimum(), zoom_range.maximum())
 		# using the patched (tilesize) gdal2tiles.py script here, until the upstream version mades it in the distros
 		subprocess.run(['gdal2tiles-gnuboat.py', '-q', '-w', 'none', '--tilesize={}'.format(tile_size), '-z', tile_zoom_option, '-t', title, input_file, output_directory], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
 
-	def _tile_width(self, tile_size, zoomlevel):
-		lng_lat_box = mercantile.bounds(mercantile.Tile(1, 1, zoomlevel))
-		tiles = math.sqrt(self._tile_number(zoomlevel))
-		#print ({"tile_size": tile_size, "longitude": 360.0/tiles, "latitude": 180.0/tiles})
-		return {"tile_size": tile_size, "longitude": abs(lng_lat_box.west - lng_lat_box.east), "latitude": abs(lng_lat_box.north - lng_lat_box.south)}
-
-	def _tile_number(self, zoomlevel):
-		return 2**(zoomlevel*2)
+	def move_tiles_in_place(self, source_path, target_path):
+		if not os.path.exists(target_path):
+			target_parent = os.path.dirname(target_path)
+			if not os.path.exists(target_parent):
+				os.makedirs(target_parent)
+			shutil.copytree(source_path, target_path)
+			return
+		for item in os.listdir(source_path):
+			src = os.path.join(source_path, item)
+			if os.path.isdir(src):
+				target_path_new = os.path.join(target_path, item)
+				if os.path.exists(target_path_new):
+					self.move_tiles_in_place(src, target_path_new)
+				else:
+					if not os.path.exists(target_path):
+						os.makedirs(target_path)
+					shutil.copytree(src, target_path_new)
+			else:
+				if not os.path.exists(target_path):
+					os.makedirs(target_path)
+				shutil.copy(src, target_path)
+
+	def _datasource_open(self, source_file):
+		datasource = ogr.Open(source_file)
+		if datasource is None:
+			raise FileNotFoundError('Could not open input file {}'.format(source_file))
+		if datasource.GetLayerCount() < 1:
+			raise ReferenceError('No layers in input file') 
+		return datasource
 
 	#def contours_create():
Index: src/common/setup.py
===================================================================
--- src/common/setup.py	(revision 9f5877dc45dcf00238a6d2e688fcc536e3373191)
+++ src/common/setup.py	(revision 5e16955853266e68c24fd278d8f0c96f74f4120c)
@@ -35,5 +35,5 @@
 setup(
   name="gnuboat_common",
-  version="0.4.6",
+  version="0.4.7",
   maintainer="EngSaS - Langenbach",
   maintainer_email="info@engsas.de",
@@ -44,5 +44,5 @@
   #package_dir={'': ''},
   packages=find_packages(),
-  scripts=["bin/gnuboat-log-converter", "bin/gnuboat-log-analyser", "bin/gdal2tiles-gnuboat.py"],
+  scripts=["bin/gnuboat-log-converter", "bin/gnuboat-log-analyser", "bin/gnuboat-log-uploader", "bin/gdal2tiles-gnuboat.py"],
   long_description=README_TEXT,
   install_requires=reqs_install,
