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,
Index: src/mapservice/openapi.yaml
===================================================================
--- src/mapservice/openapi.yaml	(revision 9f5877dc45dcf00238a6d2e688fcc536e3373191)
+++ src/mapservice/openapi.yaml	(revision 5e16955853266e68c24fd278d8f0c96f74f4120c)
@@ -317,4 +317,5 @@
                 - 90.136111
                 - 29.934722
+              referenceWaterLevelGaugeHeight: 5.1
       responses:
         '201':
@@ -530,5 +531,7 @@
           $ref: '#/components/responses/NotFound'
     post:
-      description: Creates a new log from given meta data. The log entries itself, must be uploaded per /logs/{log_id}
+      description: >-
+        Creates a new log from given meta data. The log entries itself, must be
+        uploaded per /logs/{log_id}
       tags:
         - logs
@@ -659,4 +662,70 @@
         '404':
           $ref: '#/components/responses/NotFound'
+  '/tiles/gnuboat/{accuracy}/{resolution}/{zoom}/{x_tile}/{y_tile}.png':
+    get:
+      description: 'Returns the map tile x_tile, y_tile at Zoomlevel zoom'
+      tags:
+        - tiles
+      summary: Represents a tile
+      operationId: tilesTileGet
+      parameters:
+        - name: accuracy
+          in: path
+          description: Accuracy of generated tiles
+          required: true
+          schema:
+            title: >-
+              Accuracy of the tiles (for a higher accuracy more measured points per square meter are needed to generate a pixel of water depth)
+            type: string
+            enum:
+              - 'high'
+              - 'low'
+        - name: resolution
+          in: path
+          description: Resolution of the tiles
+          required: true
+          schema:
+            title: >-
+              Tile Resolution (Pixel per Tile) (Placed here, because
+              codegenerator could use Enums in components/schemas
+            type: integer
+            format: int32
+            enum:
+              - 256
+              - 512
+        - name: zoom
+          in: path
+          description: Zoomlevel
+          required: true
+          schema:
+            $ref: '#/components/schemas/tileZoomlevel'
+        - name: x_tile
+          in: path
+          description: Number of the tile in x dimension
+          required: true
+          schema:
+            $ref: '#/components/schemas/itemId'
+        - name: y_tile
+          in: path
+          description: Number of the tile in y dimension
+          required: true
+          schema:
+            $ref: '#/components/schemas/itemId'
+      responses:
+        '200':
+          description: OK
+          content:
+            image/*:
+              schema:
+                type: string
+                format: binary
+                #contentEncoding: base64
+                #contentMediaType: image/png
+        '400':
+          $ref: '#/components/responses/BadRequest'
+        '404':
+          $ref: '#/components/responses/NotFound'
+        '500':
+          $ref: '#/components/responses/InternalServerError'
 components:
   securitySchemes:
@@ -688,5 +757,5 @@
       title: Item ID
       type: integer
-      format: int32
+      format: int64
     itemName:
       title: Item Name
@@ -851,4 +920,9 @@
       items:
         $ref: '#/components/schemas/Water'
+    ReferenceWaterLevelGaugeHeight:
+      title: Gauge Height of reference water level of a Gauge
+      description: The gauge height (stage) for reference water level. The reference water level is the water level, the depth on the map is shown at. Therefore, the water depth of a LogEntry is transformed to this referenceWaterLevel, with help of the gaugeHeight of the Log related to the LogEntry.
+      type: number
+      format: float
     Gauge:
       title: Gauge
@@ -863,4 +937,6 @@
         location:
           $ref: '#/components/schemas/point'
+        referenceWaterLevelGaugeHeight:
+          $ref: '#/components/schemas/ReferenceWaterLevelGaugeHeight'
         logs:
           $ref: '#/components/schemas/logs'
@@ -871,4 +947,5 @@
         - name
         - location
+        - referenceWaterLevelGaugeHeight
     GaugeCreation:
       title: Gauge for Creation
@@ -879,4 +956,6 @@
         location:
           $ref: '#/components/schemas/point'
+        referenceWaterLevelGaugeHeight:
+          $ref: '#/components/schemas/ReferenceWaterLevelGaugeHeight'
         water:
           $ref: '#/components/schemas/itemBase'
@@ -906,4 +985,6 @@
             manager:
               $ref: '#/components/schemas/username'
+            referenceWaterLevelGaugeHeight:
+              $ref: '#/components/schemas/ReferenceWaterLevelGaugeHeight'
             comment:
               $ref: '#/components/schemas/comment'
@@ -956,5 +1037,5 @@
         $ref: '#/components/schemas/Device'
     GaugeHeight:
-      title: 'Absolute water height (stage) of the gauge, at the time of measuring'
+      title: 'Gauge height (stage) of the gauge, at the time of measuring'
       type: number
       format: float
@@ -1085,4 +1166,10 @@
         - geometry
         - properties
+    tileZoomlevel:
+      title: Zoomlevel of requested Tile
+      type: integer
+      format: int32
+      minimum: 0
+      maximum: 19
     HttpError:
       title: HTTP Error Response Object
@@ -1188,4 +1275,5 @@
           - 90.136111
           - 29.934722
+        referenceWaterLevelGaugeHeight: 5.1
         comment: Gauge for Mississippi in New Orleans
     Gauges:
@@ -1197,4 +1285,5 @@
             - 90.136111
             - 29.934722
+          referenceWaterLevelGaugeHeight: 5.1
       summary: A sample list of gauges
     GaugeGeoJson:
@@ -1209,4 +1298,5 @@
             name: New Orleans
             manager: jane
+            referenceWaterLevelGaugeHeight: 5.1
             comment: Gauge for Mississippi in New Orleans
     GaugesGeoJson:
@@ -1221,4 +1311,5 @@
               name: New Orleans
               manager: jane
+              referenceWaterLevelGaugeHeight: 5.1
               comment: Gauge for Mississippi in New Orleans
       summary: A sample list of gauges in GeoJson format
@@ -1349,5 +1440,14 @@
               $ref: '#/components/examples/HttpError'
     NotFound:
-      description: Water with given Id not found
+      description: Item with given Id not found
+      content:
+        application/problem+json:
+          schema:
+            $ref: '#/components/schemas/HttpError'
+          examples:
+            HttpError:
+              $ref: '#/components/examples/HttpError'
+    InternalServerError:
+      description: Internal Server Error (HTTP Code 500)
       content:
         application/problem+json:
@@ -1368,2 +1468,4 @@
   - name: logs
     description: 'All actions used to manage logs of an water, device, gauge or user'
+  - name: tiles
+    description: Tile serving
Index: src/mapservice/src/server_impl/Config.py
===================================================================
--- src/mapservice/src/server_impl/Config.py	(revision 9f5877dc45dcf00238a6d2e688fcc536e3373191)
+++ src/mapservice/src/server_impl/Config.py	(revision 5e16955853266e68c24fd278d8f0c96f74f4120c)
@@ -15,4 +15,9 @@
     along with this program.  If not, see <http://www.gnu.org/licenses/>.
 '''
+
+from celery.schedules import crontab
+from pathlib import Path
+import os
+
 class Config(object):
 	DEBUG = False
@@ -27,4 +32,17 @@
 	CELERY_BROKER_URL = 'pyamqp://guest@localhost//'
 	CELERY_IMPORTS = ("openapi_server.server_impl.tasks")
+	# pixel size of tiles to be generated
+	TILES_SIZES = [256, 512]
+	# Min required data points to get no nodata value in a raster pixel
+	TILES_DENSITIES = [10, 100]
+	TILES_DENSITY_BASEE = 100
+	# How many years are data points allowed to be old, before they are excluded from calculations
+	TILES_POINT_AGE_MAX = 10
+	# log_process generates tiles for this zoom range. all lower zoomlevels (0 - x) are generated by a periodic task (s. TILES_LITTLE_ZOOM_SCHEDULE option).
+	# Those zoomlevels are not rendered by log_process(), because they contain few details, but large areas
+	TILES_ZOOM_RANGE = {'minimum': 10, 'maximum': 19}
+	# schedule, when to run the job to generate tiles for low zoomlevels (up to 0 - 13),
+	# As format see https://docs.celeryproject.org/en/stable/userguide/periodic-tasks.html#crontab-schedules
+	TILES_LITTLE_ZOOM_SCHEDULE = crontab(hour=3, minute=0) # execute daily at 3 a`clock
 
 class ProductionConfig(Config):
@@ -38,8 +56,8 @@
 	HOST = 'localhost'
 	SERVER_NAME = 'localhost:8080'
+	TILES_CACHE_PATH = os.path.join(Path.home(), '.cache/gnuboat/tiles')
+	TILES_SIZES = [256]
 
-class TestingConfig(Config):
+class TestingConfig(DevelopmentConfig):
 	TESTING = True
-	DEBUG = False
-	CREATE_TEST_DATABASE = True
-	MAPSERVICE_WEBCLIENT = 'http://localhost:8081'
+	
Index: src/mapservice/src/server_impl/HttpErrors.py
===================================================================
--- src/mapservice/src/server_impl/HttpErrors.py	(revision 9f5877dc45dcf00238a6d2e688fcc536e3373191)
+++ src/mapservice/src/server_impl/HttpErrors.py	(revision 5e16955853266e68c24fd278d8f0c96f74f4120c)
@@ -1,4 +1,4 @@
 '''
-    Copyright (C) 2019 EngSaS - Engineering Solutions and Services Langenbach. All rights reserved.
+    Copyright (C) 2019 - 2020 EngSaS - Engineering Solutions and Services Langenbach. All rights reserved.
 
     This program is free software: you can redistribute it and/or modify
@@ -16,5 +16,5 @@
 '''
 
-from werkzeug.exceptions import BadRequest, Unauthorized, NotFound
+from werkzeug.exceptions import BadRequest, Unauthorized, NotFound, InternalServerError
 from connexion.exceptions import ProblemException 
 
@@ -30,2 +30,6 @@
 	def __init__(self, type="not-found", title="Resouce not found", detail="The requested resource was not found", instance=None, **kwargs):
 		super(MapserviceNotFound, self).__init__(status=404, title=title, detail=detail, type=type, instance=instance, **kwargs)
+
+class MapserviceInternalServerError(ProblemException, InternalServerError):
+	def __init__(self, type="internal-server-error", title=None, detail=None, instance=None, **kwargs):
+		super(MapserviceInternalServerError, self).__init__(status=500, title="Internal Server Error", detail=detail, type=type, instance=instance, **kwargs)
Index: src/mapservice/src/server_impl/controllers/LogsController.py
===================================================================
--- src/mapservice/src/server_impl/controllers/LogsController.py	(revision 9f5877dc45dcf00238a6d2e688fcc536e3373191)
+++ src/mapservice/src/server_impl/controllers/LogsController.py	(revision 5e16955853266e68c24fd278d8f0c96f74f4120c)
@@ -19,5 +19,5 @@
 from ..database.Model import User, Log, LogEntry, Water, Device, Gauge, ProcessingStatus, Queue, db
 from ..HttpErrors import MapserviceBadRequest, MapserviceUnauthorized, MapserviceNotFound
-from ..tasks.tasks import log_parse
+from ..tasks.tasks import log_process
 
 def logs_get(submitter=None, order_by=None, offset=None, limit=None):
@@ -115,5 +115,5 @@
 	
 	# request log parsing
-	log_parse.delay(log.id, body.decode())
+	log_process.delay(log.id, body.decode())
 	
 	return log.meta_data()
Index: src/mapservice/src/server_impl/controllers/TilesController.py
===================================================================
--- src/mapservice/src/server_impl/controllers/TilesController.py	(revision 5e16955853266e68c24fd278d8f0c96f74f4120c)
+++ src/mapservice/src/server_impl/controllers/TilesController.py	(revision 5e16955853266e68c24fd278d8f0c96f74f4120c)
@@ -0,0 +1,51 @@
+'''
+    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 connexion
+import flask
+import os
+
+from ..HttpErrors import MapserviceInternalServerError, MapserviceBadRequest, MapserviceNotFound
+
+def tiles_tile_get(accuracy, resolution, zoom, x_tile, y_tile):
+	if not 'TILES_CACHE_PATH' in flask.current_app.config or not os.access(flask.current_app.config['TILES_CACHE_PATH'], os.R_OK):
+		raise MapserviceInternalServerError(detail='TILES_CACHE_PATH not configured or not accessible')
+	tiles_cache_path = flask.current_app.config['TILES_CACHE_PATH']
+	
+	if not 'TILES_DENSITIES' in flask.current_app.config:
+		raise MapserviceInternalServerError(details='TILES_DENSITIES not configured')
+	tiles_densities = flask.current_app.config['TILES_DENSITIES']
+	
+	if not 'TILES_DENSITY_BASEE' in flask.current_app.config:
+		raise MapserviceInternalServerError(details='TILES_DENSITY_BASEE not configured')
+	tiles_densitiy_base = flask.current_app.config['TILES_DENSITY_BASEE']
+	
+	if accuracy == 'high':
+		accuracy = '{}_{}'.format(max(tiles_densities), tiles_densitiy_base)
+	elif accuracy == 'low':
+		accuracy = '{}_{}'.format(min(tiles_densities), tiles_densitiy_base)
+	else:
+		raise MapserviceBadRequest(details='No valid accuracy requested. Valid are high, low. Requested was: {}'.format(accuracy))
+	
+	tile_path = os.path.join(tiles_cache_path, '{}/{}/{}/{}/{}.png'.format(accuracy, resolution, zoom, x_tile, y_tile))
+	if not os.path.isfile(tile_path):
+		raise MapserviceNotFound(detail='Tile ({}, {}) for accuracy {} with resolution {} at zoomlevel {} not found'.format(x_tile, y_tile, accuracy, resolution, zoom))
+	else:
+		response = flask.send_file(tile_path, mimetype='image/png', as_attachment=True, attachment_filename='{}.png'.format(y_tile))
+		response.direct_passthrough = False
+		#response.headers['Content-Transfer-Encoding']='base64'
+		return response
Index: src/mapservice/src/server_impl/controllers/WatersController.py
===================================================================
--- src/mapservice/src/server_impl/controllers/WatersController.py	(revision 9f5877dc45dcf00238a6d2e688fcc536e3373191)
+++ src/mapservice/src/server_impl/controllers/WatersController.py	(revision 5e16955853266e68c24fd278d8f0c96f74f4120c)
@@ -87,5 +87,5 @@
 	
 	location = 'SRID=4326;POINT({:.6} {:.6})'.format(gauge_creation.location[0], gauge_creation.location[1])
-	gauge = Gauge(name=gauge_creation.name, manager=user, water=water, location=location, comment=gauge_creation.comment)
+	gauge = Gauge(name=gauge_creation.name, manager=user, water=water, location=location, reference_water_level_gauge_height=gauge_creation.reference_water_level_gauge_height, comment=gauge_creation.comment)
 	db.session.add(gauge)
 	db.session.commit()
Index: src/mapservice/src/server_impl/database/Model.py
===================================================================
--- src/mapservice/src/server_impl/database/Model.py	(revision 9f5877dc45dcf00238a6d2e688fcc536e3373191)
+++ src/mapservice/src/server_impl/database/Model.py	(revision 5e16955853266e68c24fd278d8f0c96f74f4120c)
@@ -146,4 +146,5 @@
 	# POINT(Lon Lat)
 	location = db.Column(Geometry(geometry_type='POINT', srid=4326, management=True))
+	reference_water_level_gauge_height = db.Column(db.Float, nullable = False)
 	comment = db.Column(db.String(255))
 	#osm_id = db.Column(db.Integer)
@@ -159,4 +160,5 @@
 		location = wkb_to_dict(obj.location)
 		result['location'] = [location['longitude'], location['latitude']]
+		result['referenceWaterLevelGaugeHeight'] = obj.reference_water_level_gauge_height
 		if obj.water:
 			result['water'] = { 'label': obj.water.name, 'id': obj.water.id }
@@ -179,5 +181,6 @@
 			},
 			'properties': {
-				'name': obj.name
+				'name': obj.name,
+				'referenceWaterLevelGaugeHeight': obj.reference_water_level_gauge_height
 			}
 		}
@@ -342,4 +345,5 @@
 		selectable=select(
 			[
+				Log.id,
 				Log.submitter_id,
 				Log.water_id,
@@ -441,5 +445,5 @@
 			new_orleans = query[0]
 		else:
-			new_orleans = Gauge(name='New Orleans', manager=test_user_jane, water=mississippi, location='SRID=4326;POINT(-90.136111 29.934722)')
+			new_orleans = Gauge(name='New Orleans', manager=test_user_jane, water=mississippi, location='SRID=4326;POINT(-90.136111 29.934722)', reference_water_level_gauge_height=3)
 			db.session.add(new_orleans)
 			db.session.commit()
@@ -450,5 +454,5 @@
 			pfuhlersee_gauge = query[0]
 		else:
-			pfuhlersee_gauge = Gauge(name='Stairs at Kiosk', manager=test_user_jane, water=pfuhlersee, location='SRID=4326;POINT(10.0427 48.4275)', comment='Level zero is the level of the step where the handrail is fixed.')
+			pfuhlersee_gauge = Gauge(name='Stairs at Kiosk', manager=test_user_jane, water=pfuhlersee, location='SRID=4326;POINT(10.0427 48.4275)', reference_water_level_gauge_height=0.4, comment='Level zero is the level of the step where the handrail is fixed.')
 			db.session.add(pfuhlersee_gauge)
 			db.session.commit()
Index: src/mapservice/src/server_impl/tasks/tasks.py
===================================================================
--- src/mapservice/src/server_impl/tasks/tasks.py	(revision 9f5877dc45dcf00238a6d2e688fcc536e3373191)
+++ src/mapservice/src/server_impl/tasks/tasks.py	(revision 5e16955853266e68c24fd278d8f0c96f74f4120c)
@@ -16,12 +16,29 @@
 '''
 import celery
+import flask
 from flask import render_template, url_for
 import datetime
 from flask_mail import Message
+import os
+from dateutil.relativedelta import relativedelta
+import math
+import xml.etree.ElementTree as ET
+import subprocess
+import tempfile
+import shutil
+
+from osgeo import ogr
+from osgeo import osr
+from osgeo import gdal
+from osgeo import gdalconst
+import mercantile
 
 from gnuboat_common.datahandler import loghandler
+from gnuboat_common.spatial import tilegenerator
+from gnuboat_common.spatial.tilegenerator import RasterSlice, LngLatBbox, ZoomRange
 
 from .. import mail, celery as celery_app
 from ..database.Model import User, Log, LogEntry, Water, ProcessingStatus, Queue, db
+from .tileconfig import TileConfig
 
 class LogEntryCallback:
@@ -59,22 +76,82 @@
 			self._end = entry_datetime
 
-def queue_delete(log):
-	if not queue.delete():
-		app.logger.error('Could not delete queue for log {}'.format(log.id))
-	db.session.commit()
-
-def update_log_state(log, status):
-	processing_state = ProcessingStatus.query.filter_by(label=status).all()
-	if len(processing_state) != 1:
-		app.logger.error('Processing status {} not found database'.format(status))
-		return
-	processing_state = processing_state[0]
-	log.processingstatus = processing_state
-	db.session.add(log)
-	db.session.commit()
-	
-def cleanup_error(log):
-	update_log_state(log, 'Error')
-	queue_delete(log)
+class LogsLocked(Exception):
+	pass
+
+class SliceJob(dict):
+	"""
+		Summarize all data needed to generate the tiles for a slice
+		and also to cleanup the whole generation chain afterwards
+		
+		tile_slice: The slice, which should be rastered
+		query: query used in the vrt source file
+		log_id: Id of the log, initiating the job (before slicing)
+		envelope: Enlarged envelope of the complete job (TileGenerator.LngLatBbox)
+		
+		It's derived from dict to be json serialisable
+	"""
+	def __init__(self, tile_slice, query, log_id, envelope):
+		super(SliceJob, self).__init__({'tile_slice': tile_slice, 'query': query, 'log_id': log_id, 'envelope': envelope})
+		
+	def tile_slice(self):
+		return self['tile_slice']
+	
+	def query(self):
+		return self['query']
+	
+	def log_id(self):
+		return self['log_id']
+	
+	def envelope(self):
+		return self['envelope']
+	
+	def from_dict(dictionary):
+		return SliceJob(RasterSlice.from_dict(dictionary['tile_slice']), dictionary['query'], dictionary['log_id'], LngLatBbox.from_dict(dictionary['envelope']))
+
+# query to get all logentries in the enlarged envelope, younger than age_date
+query = """SELECT MakePointZ(ST_x(entries.location), ST_y(entries.location), (entries.water_depth + (logs.gauge_height - gauges.reference_water_level_gauge_height)), ST_srid(entries.location))
+FROM logentries as entries, logs, gauges
+WHERE entries.log_id=logs.id AND gauges.id=logs.gauge_id
+	AND ST_Within(entries.location, Envelope(MakeLine(PointFromText("POINT({longitude_west} {latitude_south})", {epsg_code}), PointFromText("POINT({longitude_east} {latitude_north})", {epsg_code}))))
+	AND entries.datetime > \"{age_date}\""""
+
+# query for retrieving processing state of affected logentries
+query_select_processing_state = """SELECT COUNT(id) FROM logs
+WHERE processing_state={processing_state} AND id IN (
+	SELECT log_id FROM logentries WHERE
+		ST_Within(logentries.location, Envelope(MakeLine(PointFromText("POINT({longitude_west} {latitude_south})", {epsg_code}), PointFromText("POINT({longitude_east} {latitude_north})", {epsg_code}))))
+		AND datetime {age_condition} \"{age_date}\"
+		GROUP BY log_id)"""
+	
+# query for updateting processing state of all affected logentries
+query_update_processing_state = """UPDATE logs SET processing_state={processing_state}
+WHERE id IN (
+	SELECT log_id FROM logentries WHERE
+		ST_Within(logentries.location, Envelope(MakeLine(PointFromText("POINT({longitude_west} {latitude_south})", {epsg_code}), PointFromText("POINT({longitude_east} {latitude_north})", {epsg_code}))))
+		AND datetime {age_condition} \"{age_date}\"
+		GROUP BY log_id)"""
+
+query_logs = """SELECT logentries.log_id, COUNT(logentries.id) as entries
+FROM logentries
+WHERE ST_Within(logentries.location, Envelope(MakeLine(PointFromText("POINT({longitude_west} {latitude_south})", {epsg_code}), PointFromText("POINT({longitude_east} {latitude_north})", {epsg_code}))))
+	AND logentries.datetime > \"{age_date}\" GROUP BY log_id"""
+
+@celery_app.on_after_configure.connect
+def setup_periodic_tasks(sender, **kwargs):
+	if not 'TILES_LITTLE_ZOOM_SCHEDULE' in flask.current_app.config:
+		flask.current_app.logger.error('TILES_LITTLE_ZOOM_SCHEDULE not configured')
+		return False
+	
+	sender.add_periodic_task(flask.current_app.config['TILES_LITTLE_ZOOM_SCHEDULE'], log_generate_tile_little_zoom.s())
+
+@celery_app.task
+def log_process(log_id, log_content):
+	"""
+		Chain for processing a new log
+		1. Parse the log and add it to the datapase (s. log_parse)
+		2. Generate tiles out of the new and old data (s. log_slice)
+	"""
+	chain = log_parse.s(log_id, log_content) | log_slice.s()
+	chain()
 
 @celery_app.task
@@ -82,30 +159,12 @@
 	"""Background task to parse new logs"""
 	
-	log = Log.query.filter_by(id=log_id).all()
-	if len(log) != 1:
-		app.logger.warn("Could not find log {}".format(log_id))
-		return False
-	log = log[0]
-	
-	update_log_state(log, 'Parsing')
-	
-	water_link = '{}'.format(url_for('/mapservice/v1.openapi_server_controllers_waters_controller_waters_get_by_id', id=log.water.id, _external=True))
+	log = log_by_id(log_id)
+	update_log_state(log_id, 'Parsing')
 	
 	queue = Queue.query.filter_by(log_id=log.id).all()
 	if len(queue) != 1:
-		message = Message("Error parsing log file", recipients=[log.submitter.email])
-		message.html = render_template('log_parsing_error.html',
-			first_name=log.submitter.first_name,
-			queue_date=queue_date.isoformat('T'),
-			water_link=water_link,
-			water_name=log.water.name,
-			errors="No queue for log file")
-		mail.send(message)
-		
-		app.logger.warn("Could not find queue for log {}".format(log.id))
-		
-		cleanup_error(log)
-		
-		return False
+		mail_error(log_id, 'No queue for log file')
+		cleanup_error(log_id)
+		raise LookupError('Could not find queue for log {}'.format(log.id))
 	queue = queue[0]
 	queue_date = queue.datetime
@@ -115,33 +174,11 @@
 	result = log_handler.gnuboat_read(log_content.splitlines(), log_callback.callback, False, False)
 	if not result.success():
-		message = Message("Error parsing log file", recipients=[log.submitter.email])
-		message.html = render_template('log_parsing_error.html',
-			first_name=log.submitter.first_name,
-			queue_date=queue_date.isoformat('T'),
-			water_link=water_link,
-			water_name=log.water.name,
-			errors=result.errors())
-		mail.send(message)
-		
-		app.logger.info('Could not parse logfile {}: {}'.format(log.id, '\n'.join(result.errors())))
-		
-		cleanup_error(log)
-		
-		return False
+		mail_error(log_id, result.errors())
+		cleanup_error(log_id)
+		raise SyntaxError('Could not parse logfile {}: {}'.format(log.id, '\n'.join(result.errors())))
 	if not log_callback.valid():
-		message = Message("Error parsing log file", recipients=[log.submitter.email])
-		message.html = render_template('log_parsing_error.html',
-			first_name=log.submitter.first_name,
-			queue_date=queue_date.isoformat('T'),
-			water_link=water_link,
-			water_name=log.water.name,
-			errors="Log has no entries")
-		mail.send(message)
-		
-		app.logger.info('Could not parse logfile {}: {}'.format(log.id, 'Log has no entries'))
-		
-		cleanup_error(log)
-		
-		return True
+		mail_error(log_id, 'Log has no entries')
+		cleanup_error(log_id)
+		raise SyntaxError('Could not parse logfile {}: {}'.format(log.id, 'Log has no entries'))
 	
 	for entry in log_callback.entries():
@@ -154,25 +191,394 @@
 	queue.datetime = datetime.datetime.now(datetime.timezone.utc)
 	db.session.add(queue)
+	db.session.commit()
 	
 	# update state and start / end time of the log, gained from log parsing
 	log.start = log_callback.start()
 	log.end = log_callback.end()
-	update_log_state(log, 'Queued for Processing')
-	
-	message = Message("Error parsing log file", recipients=[log.submitter.email])
+	update_log_state(log_id, 'Queued for Processing')
+	
+	message = Message("Parsed log file successfully", recipients=[log.submitter.email])
 	message.html = render_template('log_parsed.html',
 		first_name=log.submitter.first_name,
 		queue_date=queue_date.isoformat('T'),
-		water_link=water_link,
+		water_link='{}'.format(url_for('/mapservice/v1.openapi_server_controllers_waters_controller_waters_get_by_id', id=log.water.id, _external=True)),
 		water_name=log.water.name)
 	mail.send(message)
 	
-	# request processing
-	log_process.delay(log.id)
-	
+	return log_id
+
+@celery_app.task(autoretry_for=(LogsLocked,), default_retry_delay=1800)
+def log_slice(log_id):
+	"""
+		Background task to process new logs
+		If another job is already processing the same logs, a LogsLocked Exception
+		is raised and an auto retry after 30 minutes is triggered.
+	"""
+	try:
+		tiles_config = get_tile_config()
+	except Exception as error:
+		update_log_state(log_id, 'Error')
+		raise error
+	try:
+		sqlalchemy_database_uri = get_database_uri()
+	except Exception as error:
+		update_log_state(log_id, 'Error')
+		raise error
+
+	processing_state_processing = processing_state_get('Processing')
+	processing_state_deployed = processing_state_get('Deployed')
+	processing_state_to_old = processing_state_get('To Old')
+	processing_state_error = processing_state_get('Error')
+	
+	try:
+		tile_cache_create(tiles_config)
+	except Exception as error:
+		update_log_state(log_id, 'Error')
+		raise error
+
+	tilegen = tilegenerator.TileGenerator(tile_sizes = tiles_config.sizes, densities = tiles_config.densities, density_base = tiles_config.densitiy_base)
+	
+	newer_than = datetime.datetime.utcnow() - relativedelta(years=tiles_config.points_age_max)
+	
+	# Extend envelope of source log to the next tile borders
+	connection = ogr.Open(sqlalchemy_database_uri, gdal.GA_ReadOnly)
+	if connection is None:
+		flask.current_app.logger.error('Could not open database connection')
+		return False
+	envelope = connection.ExecuteSQL("SELECT envelope FROM logview WHERE id={}".format(log_id))
+	west, east, south, north = envelope.GetExtent()
+	envelope_spatial_ref = envelope.GetSpatialRef()
+	epsg_code = envelope_spatial_ref.GetAuthorityCode(None)
+	input_epsg = "{}:{}".format(envelope_spatial_ref.GetAuthorityName(None), epsg_code)
+	envelope_enlarged = tilegen.fit_extent_to_tiles(mercantile.LngLatBbox(west, south, east, north), tiles_config.zoom_range)
+	
+	# Check that none of the affected logs are currently processed by another job
+	result = db.engine.execute(query_select_processing_state.format(processing_state=processing_state_processing.id, epsg_code=epsg_code,
+		longitude_west=envelope_enlarged.west(), latitude_south=envelope_enlarged.south(),
+		longitude_east=envelope_enlarged.east(), latitude_north=envelope_enlarged.north(),
+		age_condition=">", age_date=newer_than.isoformat('T'))).first()
+	if result[0] > 0:
+		# there are logs, which are currently processed by another job
+		raise LogsLocked('{} logs are currently processed by another job'.format(result[0]))
+	
+	# just for informational purpose
+	if flask.current_app.debug:
+		result = db.engine.execute(query_logs.format(processing_state=processing_state_processing.id, epsg_code=epsg_code,
+			longitude_west=envelope_enlarged.west(), latitude_south=envelope_enlarged.south(),
+			longitude_east=envelope_enlarged.east(), latitude_north=envelope_enlarged.north(),
+			age_date=newer_than.isoformat('T')))
+		count_logentries = 0
+		logs = 0
+		for rows in result:
+			logs += 1
+			count_logentries += rows[1]
+		flask.current_app.logger.info('Processing log {}, found {} datasets from {} logs in enlarged envelope younger than {}'.format(log_id, count_logentries, logs, newer_than.isoformat('T')))
+	
+	# update processing state of logentries, which will be processed
+	db.engine.execute(query_update_processing_state.format(processing_state=processing_state_processing.id, epsg_code=epsg_code,
+		longitude_west=envelope_enlarged.west(), latitude_south=envelope_enlarged.south(),
+		longitude_east=envelope_enlarged.east(), latitude_north=envelope_enlarged.north(),
+		age_condition=">", age_date=newer_than.isoformat('T')))
+	db.session.commit()
+	# update processing state of logentries, which are to old
+	db.engine.execute(query_update_processing_state.format(processing_state=processing_state_to_old.id, epsg_code=epsg_code,
+		longitude_west=envelope_enlarged.west(), latitude_south=envelope_enlarged.south(),
+		longitude_east=envelope_enlarged.east(), latitude_north=envelope_enlarged.north(),
+		age_condition="<=", age_date=newer_than.isoformat('T')))
+	db.session.commit()
+	
+	data_query = query.format(epsg_code=epsg_code,
+			longitude_west=envelope_enlarged.west(), latitude_south=envelope_enlarged.south(),
+			longitude_east=envelope_enlarged.east(), latitude_north=envelope_enlarged.north(),
+			age_date=newer_than.isoformat('T'))
+
+	# create temporary directory
+	try:
+		datasource_file = datasource_vrt_create(data_query)
+	except Exception as error:
+		flask.current_app.logger.error('Could not open the output file for the ogr data source description: {}'.format(error))
+		db.engine.execute(query_update_processing_state.format(processing_state=processing_state_error.id, epsg_code=epsg_code,
+			longitude_west=envelope_enlarged.west(), latitude_south=envelope_enlarged.south(),
+			longitude_east=envelope_enlarged.east(), latitude_north=envelope_enlarged.north(),
+			age_condition=">", age_date=newer_than.isoformat('T')))
+		db.session.commit()
+		raise error
+	
+	slices = tilegen.slices(datasource_file, zoom_range = tiles_config.zoom_range)
+	slice_jobs = []
+	for tile_slice in slices:
+		slice_jobs.append(SliceJob(tile_slice, data_query, log_id, envelope_enlarged))
+	os.remove(datasource_file)
+	
+	if flask.current_app.debug:
+		flask.current_app.logger.info('Created {} tasks to process log {}'.format(len(slice_jobs), log_id))
+	
+	celery.chord([log_generate_tiles.s(slice_job) for slice_job in slice_jobs], log_cleanup.s()).delay()
 	return True
 
 @celery_app.task
-def log_process(log_id):
-	"""Background task to process new logs"""
+def log_generate_tiles(slice_job):
+	try:
+		tiles_config = get_tile_config()
+	except Exception as error:
+		update_log_state(log_id, 'Error')
+		raise error
+	try:
+		sqlalchemy_database_uri = get_database_uri()
+	except Exception as error:
+		update_log_state(log_id, 'Error')
+		raise error
+
+	slice_job = SliceJob.from_dict(slice_job)
+
+	processing_state_processing = processing_state_get('Processing')
+	processing_state_deployed = processing_state_get('Deployed')
+	processing_state_to_old = processing_state_get('To Old')
+	processing_state_error = processing_state_get('Error')
+	
+	# create temporary directory
+	try:
+		datasource_file = datasource_vrt_create(slice_job.query())
+	except Exception as error:
+		flask.current_app.logger.error('Could not open the output file for the ogr data source description: {}'.format(error))
+		raise error
+
+	temp_directory = tempfile.mkdtemp(prefix='gnuboat-tasks')
+	
+	tilegen = tilegenerator.TileGenerator(tile_sizes = tiles_config.sizes, densities = tiles_config.densities, density_base = tiles_config.densitiy_base)
+	try:
+		result_paths = tilegen.run(datasource_file, temp_directory, slice_job.tile_slice())
+	except CalledProcessError as e:
+		flask.current_app.logger.error('Could not generate tiles. {} exited with the error: {}'.format(e.cmd, e.returncode))
+		flask.current_app.logger.error('Output of gdal2tiles: {}'.format(e.output))
+		db.engine.execute(query_update_processing_state.format(processing_state=processing_state_error.id, epsg_code=epsg_code,
+			longitude_west=slice_job.envelope.west(), latitude_south=slice_job.envelope.south(),
+			longitude_east=slice_job.envelope.east(), latitude_north=slice_job.envelope.north(),
+			age_condition=">", age_date=newer_than.isoformat('T')))
+		db.session.commit()
+		raise e
+	except Exception as e:
+		flask.current_app.logger.error('Could not raster the data and generate tiles. Error: {}'.format(repr(e)))
+		db.engine.execute(query_update_processing_state.format(processing_state=processing_state_error.id, epsg_code=epsg_code,
+			longitude_west=slice_job.envelope.west(), latitude_south=slice_job.envelope.south(),
+			longitude_east=slice_job.envelope.east(), latitude_north=slice_job.envelope.north(),
+			age_condition=">", age_date=newer_than.isoformat('T')))
+		db.session.commit()
+		raise e
+	
+	for path in result_paths:
+		tilegen.move_tiles_in_place(path.path, os.path.join(tiles_config.cache_path, path.prefixes['density'], path.prefixes['tile_size']))
+		
+	# delete temporary directory
+	shutil.rmtree(temp_directory)
+	os.remove(datasource_file)
+	
+	return slice_job
+
+@celery_app.task
+def log_cleanup(slice_jobs):
+	log_id = None
+	envelope = None
+	for slice_job in slice_jobs:
+		slice_job = SliceJob.from_dict(slice_job)
+		if envelope is None:
+			envelope = slice_job.envelope
+		if log_id is None:
+			log_id = slice_job.log_id
+
+	# update processing state of logentries, to deployed
+	db.engine.execute(query_update_processing_state.format(processing_state=processing_state_deployed.id, epsg_code=epsg_code,
+		longitude_west=envelope.west, latitude_south=envelope.south,
+		longitude_east=envelope.east, latitude_north=envelope.north,
+		age_condition=">", age_date=newer_than.isoformat('T')))
+	queue_delete(log_id)
+	db.session.commit()
+	
+	log = log = log_by_id(log_id)
+	message = Message("Parsed log file successfully", recipients=[log.submitter.email])
+	message.html = render_template('log_processed.html',
+		first_name=log.submitter.first_name,
+		queue_date=queue_date.isoformat('T'),
+		water_link='{}'.format(url_for('/mapservice/v1.openapi_server_controllers_waters_controller_waters_get_by_id', id=log.water.id, _external=True)),
+		water_name=log.water.name)
+	mail.send(message)
+
+@celery_app.task
+def log_generate_tile_little_zoom():
+	"""
+		Generate all little zoomlevels, which are not process per log with log_process
+	"""
+	flask.current_app.logger.info('Recreating tiles for little zoomlevels')
+	try:
+		tiles_config = get_tile_config()
+	except Exception as error:
+		update_log_state(log_id, 'Error')
+		raise error
+	try:
+		sqlalchemy_database_uri = get_database_uri()
+	except Exception as error:
+		update_log_state(log_id, 'Error')
+		raise error
+
+	processing_state_processing = processing_state_get('Processing')
+	processing_state_deployed = processing_state_get('Deployed')
+	processing_state_to_old = processing_state_get('To Old')
+	processing_state_error = processing_state_get('Error')
+
+	try:
+		tile_cache_create(tiles_config)
+	except Exception as error:
+		update_log_state(log_id, 'Error')
+		raise error
+
+	zoom_range_little_zoom = [0, tiles_config.zoom_range[1]]
+	
+	# create temporary directory
+	temp_directory = tempfile.mkdtemp()
+	
+	newer_than = datetime.datetime.utcnow() - relativedelta(years=tiles_config.points_age_max)
+	
+	## query to get all logentries in the world, younger than age_date
+	query = """SELECT MakePointZ(ST_x(entries.location), ST_y(entries.location), (entries.water_depth + (logs.gauge_height - gauges.reference_water_level_gauge_height)), ST_srid(entries.location))
+FROM logentries as entries, logs, gauges
+WHERE entries.log_id=logs.id AND gauges.id=logs.gauge_id AND entries.datetime > \"{age_date}\""""
+	
+	try:
+		datasource_file = datasource_vrt_create(temp_directory, query.format(epsg_code=epsg_code, longitude_west=tile_bounds_min.west,
+			latitude_south=tile_bounds_min.south, longitude_east=tile_bounds_max.east,
+			latitude_north=tile_bounds_max.north,
+			age_date=newer_than.isoformat('T')))
+	except Exception as error:
+		flask.current_app.logger.error('Could not open the output file for the ogr data source description: {}'.format(error))
+		raise error
+	
+	tilegen = tilegenerator.TileGenerator(tile_sizes = tiles_config.sizes, zoom_range = zoom_range_little_zoom, densities = tiles_config.densities, density_base = tiles_config.densitiy_base)
+	try:
+		resuls_paths = tilegen.run(datasource_file, temp_directory)
+	except CalledProcessError as e:
+		flask.current_app.logger.error('Could not generate tiles. {} exited with the error: {}'.format(e.cmd, e.returncode))
+		flask.current_app.logger.error('Output of gdal2tiles: {}'.format(e.output))
+		raise e
+	except Exception as e:
+		flask.current_app.logger.error('Could not raster the data and generate tiles. Error: {}'.format(repr(e)))
+		raise e
+	
+	for path in result_paths:
+		move_tiles_cache(resuls_paths, tiles_config.cache_path)
+	
+	flask.current_app.logger.info('Recreated tiles for little zoomlevels')
+	
+	# delete temporary directory
+	shutil.rmtree(temp_directory)
+	
 	return True
+
+def log_by_id(log_id):
+	log = Log.query.filter_by(id=log_id).all()
+	if len(log) != 1:
+		flask.current_app.logger.warn('Could not find log {}'.format(log_id))
+		raise LookupError('Could not find log {}'.format(log_id))
+	return log[0]
+
+def queue_delete(log_id):
+	if not queue.filter_by(log_id=log_id).delete():
+		flask.current_app.logger.error('Could not delete queue for log {}'.format(log.id))
+	db.session.commit()
+
+def processing_state_get(status):
+	processing_state = ProcessingStatus.query.filter_by(label=status).all()
+	if len(processing_state) != 1:
+		flask.current_app.logger.error('Processing status {} not found database'.format(status))
+		raise LookupError('Processing status {} not found database'.format(status))
+	return processing_state[0]
+
+def update_log_state(log_id, status):
+	processing_state = processing_state_get(status)
+	log = log_by_id(log_id)
+	log.processingstatus = processing_state
+	db.session.add(log)
+	db.session.commit()
+	
+def cleanup_error(log_id):
+	update_log_state(log_id, 'Error')
+	queue_delete(log_id)
+
+def mail_error(log_id, error_message):
+	log = log_by_id(log_id)
+	queue = Queue.query.filter_by(log_id=log.id).all()
+	if len(queue) != 1:
+		queue_date = ''
+	else:
+		queue_date = queue[0].isoformat('T')
+	
+	message = Message("Error parsing log file", recipients=[log.submitter.email])
+	message.html = render_template('log_parsing_error.html',
+		first_name=log.submitter.first_name,
+		queue_date=queue_date,
+		water_link='{}'.format(url_for('/mapservice/v1.openapi_server_controllers_waters_controller_waters_get_by_id', id=log.water.id, _external=True)),
+		water_name=log.water.name,
+		errors=error_message)
+	mail.send(message)
+
+def get_database_uri():
+	if not 'SQLALCHEMY_DATABASE_URI' in flask.current_app.config:
+		raise ImportError('SQLALCHEMY_DATABASE_URI not configured')
+	return flask.current_app.config['SQLALCHEMY_DATABASE_URI']
+
+def get_tile_config():
+	if not 'TILES_CACHE_PATH' in flask.current_app.config:
+		flask.current_app.logger.error('TILES_CACHE_PATH not configured')
+		raise ImportError('TILES_CACHE_PATH not configured')
+	
+	if not 'TILES_SIZES' in flask.current_app.config:
+		flask.current_app.logger.error('TILES_SIZES not configured')
+		raise ImportError('TILES_SIZES not configured')
+	
+	if not 'TILES_DENSITIES' in flask.current_app.config:
+		flask.current_app.logger.error('TILES_DENSITIES not configured')
+		raise ImportError('TILES_DENSITIES not configured')
+	
+	if not 'TILES_DENSITY_BASEE' in flask.current_app.config:
+		flask.current_app.logger.error('TILES_DENSITY_BASEE not configured')
+		raise ImportError('TILES_DENSITY_BASEE not configured')
+	
+	if not 'TILES_POINT_AGE_MAX' in flask.current_app.config:
+		flask.current_app.logger.error('TILES_POINT_AGE_MAX not configured')
+		raise ImportError('TILES_POINT_AGE_MAX not configured')
+	
+	if not 'TILES_ZOOM_RANGE' in flask.current_app.config:
+		flask.current_app.logger.error('TILES_ZOOM_RANGE not configured')
+		raise ImportError('TILES_ZOOM_RANGE not configured')
+	
+	return TileConfig(flask.current_app.config['TILES_CACHE_PATH'],
+		flask.current_app.config['TILES_SIZES'], flask.current_app.config['TILES_DENSITIES'],
+		flask.current_app.config['TILES_DENSITY_BASEE'], flask.current_app.config['TILES_POINT_AGE_MAX'],
+		ZoomRange.from_dict(flask.current_app.config['TILES_ZOOM_RANGE']))
+
+def tile_cache_create(tiles_config):
+	# create tile cache directory, if it does not exists
+	if not os.path.exists(tiles_config.cache_path):
+		# Path does not exist, try to create it
+		os.makedirs(tiles_config.cache_path)
+	elif not os.access(tiles_config.cache_path, os.W_OK):
+		raise PermissionError('TILES_CACHE_PATH {} is not writeable'.format(tiles_config.cache_path))
+
+def datasource_vrt_create(query):
+	# Create Datasource for SQL database
+	output = tempfile.NamedTemporaryFile(mode='wb', prefix='gnuboat-tasks', suffix='.vrt', delete=False)
+	xml_data_source = ET.Element("OGRVRTDataSource")
+	xml_layer = ET.SubElement(xml_data_source, "OGRVRTLayer", {"name": "tmp_corrected_joined_points"})
+	xml_source = ET.SubElement(xml_layer, 'SrcDataSource')
+	xml_source.text = get_database_uri()
+	xml_source_sql = ET.SubElement(xml_layer, "SrcSQL")
+	xml_source_sql.text = query
+	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, encoding="UTF-8", xml_declaration=False)
+	output.close()
+	return os.path.join(tempfile.gettempdir(), output.name)
+
Index: src/mapservice/src/server_impl/tasks/tileconfig.py
===================================================================
--- src/mapservice/src/server_impl/tasks/tileconfig.py	(revision 5e16955853266e68c24fd278d8f0c96f74f4120c)
+++ src/mapservice/src/server_impl/tasks/tileconfig.py	(revision 5e16955853266e68c24fd278d8f0c96f74f4120c)
@@ -0,0 +1,42 @@
+# -*- 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/>.
+'''
+
+try:
+	from dataclasses import dataclass
+	
+	@dataclass
+	class TileConfig:
+		cache_path: str
+		sizes: Array[int]
+		densities: Array[int]
+		densitiy_base: int
+		points_age_max: int
+		zoom_range: Array[int]
+		
+except ImportError:
+	class TileConfig:
+		"""
+			Workaround for @dataclass, until python 3.7 is available in main distros
+		"""
+		def __init__(self, cache_path, sizes, densities, densitiy_base, points_age_max, zoom_range):
+			self.cache_path = cache_path
+			self.sizes = sizes
+			self.densities = densities
+			self.densitiy_base = densitiy_base
+			self.points_age_max = points_age_max
+			self.zoom_range = zoom_range
Index: src/mapservice/templates/log_processed.html
===================================================================
--- src/mapservice/templates/log_processed.html	(revision 5e16955853266e68c24fd278d8f0c96f74f4120c)
+++ src/mapservice/templates/log_processed.html	(revision 5e16955853266e68c24fd278d8f0c96f74f4120c)
@@ -0,0 +1,3 @@
+<p>Hello {{first_name}},</p>
+<p>we successfully processed your uploaded log file queued at {{queue_date}} for water <a href="{{water_link}}">{{water_name}}</a>. The new tiles are deployed already.</p>
+<p>Thank you for activly contributing to GNUBoat,<br>Your GNUBoat team</p>
