Index: src/webapp/webservice/inc/Config.php
===================================================================
--- src/webapp/webservice/inc/Config.php	(revision 82b4b491c7371d5ccbe62b1575cb7107fb837208)
+++ 	(revision )
@@ -1,63 +1,0 @@
-<?php
-/*
-    Copyright (C) 2016 - 2017 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/>.
-*/
-
-$configFile = __DIR__ ."/../config/config.php";
-if(file_exists($configFile))
-	include($configFile);
-else{
-	error_log("No config file ". $configFile ." not found!");
-	$config = array();
-}
-
-/**
- * @brief Loads the configuration from webservice/config/config.php (if file exists) and provides the settings for usage
- */
-class Config {
-	public function __construct(){
-		global $config;
-		$this->_config = $config;
-	}
-
-	public function databaseFile(){
-		return $this->dataDirectory() ."gnuboat.rrd";
-	}
-
-	public function shutdownRequestFile(){
-		if(array_key_exists("shutdownfile", $this->_config))
-			return $this->_config["shutdownfile"];
-		return "/var/spool/gnuboat/shutdown.request";
-	}
-
-	public function dataDirectory(){
-		if(array_key_exists("datadirectory", $this->_config))
-			return addTrailingSlash($this->_config["datadirectory"]);
-		return "/var/lib/gnuboat/";
-	}
-
-	private static function addTrailingSlash($path){
-		$length = strlen($path);
-		if(substr($path, $length - 1, 1) != "/"){
-			return $path ."/";
-		}
-		return $path;
-	}
-
-	private $_config;
-}
-
-?>
Index: src/webapp/webservice/inc/GnuBoat/Config.php
===================================================================
--- src/webapp/webservice/inc/GnuBoat/Config.php	(revision c455d7bd76a1b1cf6fd2e61bbf1062cc1be95af0)
+++ src/webapp/webservice/inc/GnuBoat/Config.php	(revision c455d7bd76a1b1cf6fd2e61bbf1062cc1be95af0)
@@ -0,0 +1,76 @@
+<?php
+/*
+    Copyright (C) 2016 - 2017 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/>.
+*/
+
+namespace GNUBoat;
+
+/**
+ * @brief Loads the configuration from webservice/config/config.php (if file exists) and provides the settings for usage
+ */
+class Config
+{
+	public function __construct()
+	{
+		$configFile = __DIR__ ."/../config/config.php";
+		if(file_exists($configFile)){
+			include($configFile);
+			$this->_config = $config;
+		}
+		else{
+			$this->_config = array();
+		}
+	}
+
+	public function databaseFile()
+	{
+		return $this->dataDirectory() ."gnuboat.rrd";
+	}
+
+	public function shutdownRequestFile()
+	{
+		if(array_key_exists("shutdownfile", $this->_config))
+			return $this->_config["shutdownfile"];
+		return "/var/spool/gnuboat/shutdown.request";
+	}
+
+	public function dataDirectory()
+	{
+		if(array_key_exists("datadirectory", $this->_config))
+			return addTrailingSlash($this->_config["datadirectory"]);
+		return "/var/lib/gnuboat/";
+	}
+
+	public function logDirectory()
+	{
+		if(array_key_exists("logdirectory", $this->_config))
+			return addTrailingSlash($this->_config["logdirectory"]);
+		return "/var/log/gnuboat/";
+	}
+
+	private static function addTrailingSlash($path)
+	{
+		$length = strlen($path);
+		if(substr($path, $length - 1, 1) != "/"){
+			return $path ."/";
+		}
+		return $path;
+	}
+
+	private $_config;
+}
+
+?>
Index: src/webapp/webservice/inc/GnuBoat/Service.php
===================================================================
--- src/webapp/webservice/inc/GnuBoat/Service.php	(revision c455d7bd76a1b1cf6fd2e61bbf1062cc1be95af0)
+++ src/webapp/webservice/inc/GnuBoat/Service.php	(revision c455d7bd76a1b1cf6fd2e61bbf1062cc1be95af0)
@@ -0,0 +1,49 @@
+<?php
+/*
+    Copyright (C) 2017 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/>.
+*/
+
+namespace GnuBoat;
+
+/**
+  * @brief Base class to handle provides Services
+  */
+abstract class Service
+{
+	function __construct($debug = 0)
+	{
+		$this->setDebug($debug);
+	}
+
+	public function setDebug($debug)
+	{
+		$this->_debug = $debug;
+	}
+	
+	public function debug()
+	{
+		return $this->_debug;
+	}
+	
+	/**
+	  * @brief Function used to process and generate the needed output
+	  */
+	abstract public function process();
+
+	private $_debug;
+}
+
+?>
Index: src/webapp/webservice/inc/GnuBoat/ServiceData.php
===================================================================
--- src/webapp/webservice/inc/GnuBoat/ServiceData.php	(revision c455d7bd76a1b1cf6fd2e61bbf1062cc1be95af0)
+++ src/webapp/webservice/inc/GnuBoat/ServiceData.php	(revision c455d7bd76a1b1cf6fd2e61bbf1062cc1be95af0)
@@ -0,0 +1,168 @@
+<?php
+/*
+    Copyright (C) 2016 - 2017 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/>.
+*/
+
+namespace GnuBoat;
+
+require_once(__DIR__ ."/../autoloader.php");
+
+class ServiceData extends Service
+{
+	function __construct()
+	{
+		parent::__construct();
+		// configure roundings per value (key) and precision (value)
+		$this->_configRound = array
+		(
+			"latitude" => 5,
+			"longitude" => 5,
+			"speedthroughwater" => 1,
+			"speedoverground" => 1,
+			"waterdepth" => 1,
+			"watertemperature" => 1,
+		);
+	}
+	
+	public function process()
+	{
+		$debug = $this->debug();
+		$config = new Config();
+		$dbFile = $config->databaseFile();
+
+		$result = array();
+		$result["lastvalid"] = array();
+		$result["track"] = array();
+
+		if(!file_exists($dbFile)){
+			echo json_encode("");
+			if($debug > 0)
+				echo "Database file ". $dbFile ." does not exist!";
+			error_log("Database file ". $dbFile ." does not exist");
+			exit;
+		}
+		// Fetch entries of the last 30s with maximum (available) resolution of 2s
+		$this->addRrdData($dbFile, "2", "240", $result, $lastValid);
+		if($lastValid){
+			$result["lastvalid"] = $lastValid;
+		}
+		// Fetch entries of the last 1h with maximum (available) resolution of 10s
+		$this->addRrdData($dbFile, "10", "36000", $result, $lastTime);
+		// Fetch entries of the last 24h with maximum (available) resolution of 60s
+		$this->addRrdData($dbFile, "60", "86400", $result, $lastTime);
+
+		if($debug > 0){
+			echo json_encode($result,  JSON_PRETTY_PRINT) ."\n";
+		}
+		else{
+			header('Content-Type: application/json');
+			echo json_encode($result) ."\n";
+		}
+	}
+
+	private function addRrdData($dbFile, $interval, $period, &$result, &$lastValid){
+		$debug = $this->debug();
+		$lastValid = false;
+
+		$endTime = floor(time() / $interval) * $interval;
+		$startTime = $endTime - $period;
+		$data = rrd_fetch($dbFile, array("AVERAGE", "--resolution", $interval, "--start", $startTime, "--end", $endTime));
+		// $data = rrd_fetch($dbFile, array("AVERAGE", "--resolution", $interval, "--start", "-". $period, "--end", "start+". $period, "--align-start"));
+		if($data === false){
+			echo json_encode($result);
+			$message = "Failure reading rrd database ". $dbFile .": ". rrd_error(); 
+			if($debug > 0)
+				echo $message;
+			else
+				error_log($message);
+			return;
+		}
+
+		if($debug > 2){
+			echo "<pre>";
+			var_dump($data);
+			echo "</pre>";
+		}
+
+		$data = $data["data"];
+
+		// transform them into json format
+		$i = 0;
+		$lastValid = -1;
+		$keys = array_keys($data);
+		$keyTimeframes = $keys[0];
+		$itemCount = count($keys);
+		if($itemCount < 0 ){
+			error_log("No keys in fetched rrd data from ". $dbFile);
+			echo json_encode("");
+			exit;
+		}
+		$timeframesCount = count($data[$keyTimeframes]);
+		if($debug > 0){
+			echo "<p>Variables: ". $itemCount ."; Timeframes: ". $timeframesCount ."</p>\n";
+		}
+		foreach($data[$keys[0]] as $timeframe => $value){
+			$allValid = true;
+			$gpsFix = false;
+			$tmp = array();
+			foreach($keys as $key){
+				if($key == "gpsfix"){
+					switch($data[$key][$timeframe]){
+						case 2:
+							$tmp[$key] = "2D";
+							$gpsFix = true;
+							break;
+						case 3:
+							$tmp[$key] = "3D";
+							$gpsFix = true;
+							break;
+						default:
+							$tmp[$key] = "-";
+					}
+				}
+				else{
+					$tmp[$key] = $data[$key][$timeframe];
+					if(!is_numeric($tmp[$key]) || is_nan($tmp[$key])){
+						$allValid = false;
+						if($debug > 1){
+							echo "Invalid value ". $key ." (". $tmp[$key] .") at time ". $time ."<br/>";
+						}
+					}
+					elseif(array_key_exists($key, $this->_configRound) && is_integer($this->_configRound[$key]))
+						$tmp[$key] = round($tmp[$key], $this->_configRound[$key]);
+				}
+			}
+			// only add the timeframe to the track, if the values are valid and we had a gps fix at that time
+			if($allValid){
+				$lastValid = $tmp;
+				if($gpsFix){
+					if(!array_key_exists($timeframe, $result["track"])){
+						$result["track"][$timeframe] = $tmp;
+					}
+				}
+			}
+			else{
+				if($debug > 1){
+					echo "Failed <pre>";
+					var_dump($tmp);
+					echo "</pre>\n";
+				}
+			}
+		}
+		ksort($result["track"]);
+	}
+}
+?>
Index: src/webapp/webservice/inc/GnuBoat/ServiceLogFiles.php
===================================================================
--- src/webapp/webservice/inc/GnuBoat/ServiceLogFiles.php	(revision c455d7bd76a1b1cf6fd2e61bbf1062cc1be95af0)
+++ src/webapp/webservice/inc/GnuBoat/ServiceLogFiles.php	(revision c455d7bd76a1b1cf6fd2e61bbf1062cc1be95af0)
@@ -0,0 +1,115 @@
+<?php
+/*
+    Copyright (C) 2017 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/>.
+*/
+
+namespace GnuBoat;
+
+require_once(__DIR__ ."/../autoloader.php");
+
+class ServiceLogFiles extends Service
+{
+	function __construct()
+	{
+		parent::__construct();
+	}
+
+	public function process()
+	{
+		$debug = $this->debug();
+		$config = new Config();
+
+		if(!array_key_exists("logfilesSelected", $_POST)){
+			// return list with available log files
+			$files = glob($config->logDirectory() ."*.log");
+			array_walk($files, 'GnuBoat\ServiceLogFiles::stripLogDirectory');
+
+			header('Content-Type: application/json');
+			if($debug > 0){
+				echo json_encode($files,  JSON_PRETTY_PRINT) ."\n";
+			}
+			else{
+				echo json_encode($files) ."\n";
+			}
+		}
+		else{
+			// prepare a download of available log files
+			$files = $_POST["logfilesSelected"];
+			if(count($files) < 1){
+				return;
+			}
+			elseif(count($files) == 1){
+				$content = file_get_contents($config->logDirectory() . $files[0]);
+				if($content === false){
+					echo "<html><head></head><body>Failed to read logfile ". $files[0] ."</body></html>";
+				}
+			
+				header('Content-Type: text/plain');
+				header('Content-disposition: attachment; filename="'. $files[0] .'"');
+				header('Content-Length: ' . filesize($config->logDirectory() . $files[0]));
+				echo $content;
+			}
+			else{
+				$date = new \DateTime('NOW');
+				$archiveName = "gnuboat-logs-". $date->format("Y-m-d");
+			
+				// provide files as zip file
+				$tmpArchive = tempnam(sys_get_temp_dir(), $archiveName);
+				$zip = new \ZipArchive();
+				if($zip->open($tmpArchive, \ZipArchive::CREATE) !== TRUE){
+					echo "<html><head></head><body>Failed to create zip file</body></html>";
+					return;
+				}
+				foreach($files as $file){
+					if($zip->addFile($config->logDirectory() . $file, $archiveName ."/". $file) !== true){
+						$zip->close();
+						echo "<html><head></head><body>Failed to add logfile ". $file ." to the zip file</body></html>";
+						return;
+					}
+				}
+				if($zip->close() !== true){
+						echo "<html><head></head><body>Failed to save zip file</body></html>";
+						return;
+				}
+				
+				echo "<html><head></head><body>Failed to add logfile ". $file ." to the zip file</body></html>";
+				
+				//Send zip folder
+				while (ob_get_level()) {
+					ob_end_clean();
+				}
+				ob_start();
+				header('Content-Type: application/zip');
+				header('Content-Transfer-Encoding: Binary');
+				header('Content-disposition: attachment; filename=' . $archiveName . '.zip');
+				header('Content-Length: ' . filesize($tmpArchive));
+				ob_flush();
+				ob_clean();
+				readfile($tmpArchive);
+				unlink($tmpArchive);
+				return;
+			}
+		}
+	}
+
+	public static function stripLogDirectory(&$item, $key)
+	{
+		$config = new Config();
+		$item = str_replace($config->logDirectory(), "", $item);
+	}
+}
+
+?>
Index: src/webapp/webservice/inc/GnuBoat/ServiceMap.php
===================================================================
--- src/webapp/webservice/inc/GnuBoat/ServiceMap.php	(revision c455d7bd76a1b1cf6fd2e61bbf1062cc1be95af0)
+++ src/webapp/webservice/inc/GnuBoat/ServiceMap.php	(revision c455d7bd76a1b1cf6fd2e61bbf1062cc1be95af0)
@@ -0,0 +1,135 @@
+<?php
+/*
+    Copyright (C) 2016 - 2017 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/>.
+*/
+
+namespace GnuBoat;
+
+require_once(__DIR__ ."/../autoloader.php");
+
+class ServiceMap extends Service
+{
+	function __construct()
+	{
+		parent::__construct();
+	}
+
+	public function process()
+	{
+		header('Content-type: application/json');
+
+		$result["error"] = 1;
+		$result["errormessage"] = "Unknown Error";
+
+		if(!array_key_exists("mapName", $_POST)){
+			$result["error"] = 1;
+			$result["errormessage"] = "Please specify map name (no value)";
+			echo json_encode($result);
+			return;
+		}
+		$mapName = $_POST["mapName"];
+		if(empty($mapName) || $mapName == ""){
+			$result["error"] = 1;
+			$result["errormessage"] = "Please specifiy map name (empty value)";
+			echo json_encode($result);
+			return;
+		}
+
+		$mapDirectory = __DIR__ ."/../../maps";
+		if(!array_key_exists("mapFile", $_FILES)){
+			$result["error"] = 1;
+			$result["errormessage"] = "No map file recieved";
+			echo json_encode($result);
+			return;
+		}
+		if (!isset($_FILES['mapFile']['error']) || is_array($_FILES['mapFile']['error'])){
+			$result["error"] = 1;
+			$result["errormessage"] = "Invalid parameters";
+			echo json_encode($result);
+			return;
+		}
+		switch ($_FILES['mapFile']['error']) {
+			case UPLOAD_ERR_OK:
+				break;
+			case UPLOAD_ERR_NO_FILE:
+				$result["error"] = 1;
+				$result["errormessage"] = "No file sent";
+				echo json_encode($result);
+				return;
+			case UPLOAD_ERR_INI_SIZE:
+			case UPLOAD_ERR_FORM_SIZE:
+				$result["error"] = 1;
+				$result["errormessage"] = "Exceeded filesize limit.";
+				echo json_encode($result);
+				return;
+			default:
+				$result["error"] = 1;
+				$result["errormessage"] = "Unknown PHP Error";
+				echo json_encode($result);
+				return;
+		}
+		$mapFileName = $mapDirectory ."/". sha1_file($_FILES['mapFile']['tmp_name']) .".mbtiles";
+		if(move_uploaded_file($_FILES['mapFile']['tmp_name'], $mapFileName)){
+			if(!chmod($mapFileName, 0755)){
+				$result["error"] = 1;
+				$result["errormessage"] = "Could not change permissions of the map file";
+			}
+			else{
+				// correct map metadata
+				$resultRename = $this->setMapName($mapFileName, $mapName);
+				if($resultRename[0] === true){
+					$result["error"] = 0;
+					$result["errormessage"] = "";
+				}
+				else{
+					$result["error"] = 1;
+					$result["errormessage"] = $resultRename[1];
+				}
+			}
+		}
+		else {
+			$result["error"] = 1;
+			$result["errormessage"] = "Could not move map in place";
+		}
+		echo json_encode($result);
+	}
+	
+	private function setMapName($mbTilesFile, $mapName)
+	{
+		if(!is_file($mbTilesFile))
+			return array(false, "setMapName - Map file not found: ". $mbTilesFile);
+		if(empty($mapName) || $mapName == "")
+			return array(false, "setMapName - Map name empty");
+		try{
+			$databaseConnection = new \PDO("sqlite:". $mbTilesFile);
+			$databaseConnection->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
+			
+			$columnName = "name";
+			$query = $databaseConnection->prepare("UPDATE metadata SET value=:value WHERE name=:name");
+			$query->bindParam(":name", $columnName);
+			$query->bindParam(":value", $mapName);
+			if($query->execute() !== true){
+				return array(false, "setMapName - Could not update metadata");
+			}
+			return array(true, "");
+		}
+		catch(\PDOException $e){
+			return array(false, "setMapName - Database error: ". $e->getMessage());
+		}
+	}
+}
+
+?>
Index: src/webapp/webservice/inc/GnuBoat/ServiceShutdown.php
===================================================================
--- src/webapp/webservice/inc/GnuBoat/ServiceShutdown.php	(revision c455d7bd76a1b1cf6fd2e61bbf1062cc1be95af0)
+++ src/webapp/webservice/inc/GnuBoat/ServiceShutdown.php	(revision c455d7bd76a1b1cf6fd2e61bbf1062cc1be95af0)
@@ -0,0 +1,61 @@
+<?php
+/*
+    Copyright (C) 2016 - 2017 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/>.
+*/
+
+namespace GnuBoat;
+
+require_once(__DIR__ ."/../autoloader.php");
+
+class ServiceShutdown extends Service
+{
+	function __construct()
+	{
+		parent::__construct();
+	}
+	
+	public function process()
+	{
+		$debug = $this->debug();
+		$config = new Config();
+
+		$handle = @fopen($config->shutdownRequestFile(), "w");
+		if($handle === false){
+			$message = "Could not create file (". $config->shutdownRequestFile() .") to indicate shutdown to the daemon.";
+			if($debug > 0)
+				echo $message;
+			error_log($message);
+			$result["shutdownstart"] = -1;
+			$result["errormessage"] = $message;
+		}
+		else{
+			$shutdownTime = new \DateTime('NOW');
+			$shutdownTime->modify("+15 seconds");
+			fwrite($handle, $shutdownTime->format(\DateTime::ATOM));
+			$result["shutdownstart"] = $shutdownTime->format(\DateTime::ATOM);
+		}
+
+		header('Content-Type: application/json');
+		if($debug > 0){
+			echo json_encode($result,  JSON_PRETTY_PRINT) ."\n";
+		}
+		else{
+			echo json_encode($result) ."\n";
+		}
+	}
+}
+
+?>
Index: src/webapp/webservice/inc/GnuBoat/Webservice.php
===================================================================
--- src/webapp/webservice/inc/GnuBoat/Webservice.php	(revision c455d7bd76a1b1cf6fd2e61bbf1062cc1be95af0)
+++ src/webapp/webservice/inc/GnuBoat/Webservice.php	(revision c455d7bd76a1b1cf6fd2e61bbf1062cc1be95af0)
@@ -0,0 +1,60 @@
+<?php
+/*
+    Copyright (C) 2016 - 2017 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/>.
+*/
+
+namespace GnuBoat;
+
+require_once(__DIR__ ."/../autoloader.php");
+
+class WebService
+{
+	function __construct()
+	{
+		$this->_requests = array();
+		$this->_requests["data"] = "GnuBoat\ServiceData";
+		$this->_requests["shutdown"] = "GnuBoat\ServiceShutdown";
+		$this->_requests["logfiles"] = "GnuBoat\ServiceLogFiles";
+		$this->_requests["map"] = "GnuBoat\ServiceMap";
+	}
+
+	public function process()
+	{
+		$debug = 0;
+		if(is_array($_GET) && array_key_exists("debug", $_GET))
+			$debug = $_GET["debug"];
+
+		$request = array_keys($this->_requests)[0];
+		if(is_array($_GET) && array_key_exists("request", $_GET)){
+			$request = $_GET["request"];
+		}
+
+		if(!array_key_exists($request, $this->_requests)){
+			$result["error"] = 1;
+			$result["errormessage"] = "Request ". $request ." not implemented";
+			
+			header('Content-Type: application/json');
+			echo json_encode($result) ."\n";
+			return;
+		}
+
+		call_user_func(array(new $this->_requests[$request], "process"));
+	}
+
+	private $_requests;
+}
+
+?>
Index: src/webapp/webservice/inc/autoloader.php
===================================================================
--- src/webapp/webservice/inc/autoloader.php	(revision c455d7bd76a1b1cf6fd2e61bbf1062cc1be95af0)
+++ src/webapp/webservice/inc/autoloader.php	(revision c455d7bd76a1b1cf6fd2e61bbf1062cc1be95af0)
@@ -0,0 +1,29 @@
+<?php
+/*
+    Copyright (C) 2017 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/>.
+*/
+
+function gnuboatAutoloader($class)
+{
+	$parts = explode('\\', $class);
+	$fileName = __DIR__ ."/". join("/", $parts) .".php";
+	if(file_exists($fileName))
+		require_once($fileName);
+}
+
+spl_autoload_register("gnuboatAutoloader");
+
+?>
Index: src/webapp/webservice/index.php
===================================================================
--- src/webapp/webservice/index.php	(revision 82b4b491c7371d5ccbe62b1575cb7107fb837208)
+++ src/webapp/webservice/index.php	(revision c455d7bd76a1b1cf6fd2e61bbf1062cc1be95af0)
@@ -17,174 +17,8 @@
 */
 
-require_once(__DIR__ ."/inc/Config.php");
-$config = new Config();
-$dbFile = $config->databaseFile();
+require_once(__DIR__ ."/inc/autoloader.php");
 
-define("REQUEST_DATA", "data");
-define("REQUEST_SHUTDOWN", "shutdown");
-
-
-// configure roundings per value (key) and precision (value)
-$configRound = array
-(
-	"latitude" => 5,
-	"longitude" => 5,
-	"speedthroughwater" => 1,
-	"speedoverground" => 1,
-	"waterdepth" => 1,
-	"watertemperature" => 1,
-);
-
-function addRrdData($interval, $period, &$result, &$lastValid){
-	global $dbFile;
-	global $debug;
-	global $configRound;
-	$lastValid = false;
-
-	$endTime = floor(time() / $interval) * $interval;
-	$startTime = $endTime - $period;
-	$data = rrd_fetch($dbFile, array("AVERAGE", "--resolution", $interval, "--start", $startTime, "--end", $endTime));
-	// $data = rrd_fetch($dbFile, array("AVERAGE", "--resolution", $interval, "--start", "-". $period, "--end", "start+". $period, "--align-start"));
-	if($data === false){
-		echo json_encode($result);
-		$message = "Failure reading rrd database ". $dbFile .": ". rrd_error(); 
-		if($debug > 0)
-			echo $message;
-		else
-			error_log($message);
-		return;
-	}
-
-	if($debug > 2){
-		echo "<pre>";
-		var_dump($data);
-		echo "</pre>";
-	}
-
-	$data = $data["data"];
-
-	// transform them into json format
-	$i = 0;
-	$lastValid = -1;
-	$keys = array_keys($data);
-	$keyTimeframes = $keys[0];
-	$itemCount = count($keys);
-	if($itemCount < 0 ){
-		error_log("No keys in fetched rrd data from ". $dbFile);
-		echo json_encode("");
-		exit;
-	}
-	$timeframesCount = count($data[$keyTimeframes]);
-	if($debug > 0){
-		echo "<p>Variables: ". $itemCount ."; Timeframes: ". $timeframesCount ."</p>\n";
-	}
-	foreach($data[$keys[0]] as $timeframe => $value){
-		$allValid = true;
-		$gpsFix = false;
-		$tmp = array();
-		foreach($keys as $key){
-			if($key == "gpsfix"){
-				switch($data[$key][$timeframe]){
-					case 2:
-						$tmp[$key] = "2D";
-						$gpsFix = true;
-						break;
-					case 3:
-						$tmp[$key] = "3D";
-						$gpsFix = true;
-						break;
-					default:
-						$tmp[$key] = "-";
-				}
-			}
-			else{
-				$tmp[$key] = $data[$key][$timeframe];
-				if(!is_numeric($tmp[$key]) || is_nan($tmp[$key])){
-					$allValid = false;
-					if($debug > 1){
-						echo "Invalid value ". $key ." (". $tmp[$key] .") at time ". $time ."<br/>";
-					}
-				}
-				elseif(array_key_exists($key, $configRound) && is_integer($configRound[$key]))
-					$tmp[$key] = round($tmp[$key], $configRound[$key]);
-			}
-		}
-		// only add the timeframe to the track, if the values are valid and we had a gps fix at that time
-		if($allValid){
-			$lastValid = $tmp;
-			if($gpsFix){
-				if(!array_key_exists($timeframe, $result["track"])){
-					$result["track"][$timeframe] = $tmp;
-				}
-			}
-		}
-		else{
-			if($debug > 1){
-				echo "Failed <pre>";
-				var_dump($tmp);
-				echo "</pre>\n";
-			}
-		}
-	}
- 	ksort($result["track"]);
-}
-
-$debug = 0;
-if(array_key_exists("debug", $_GET))
-	$debug = $_GET["debug"];
-
-$request = REQUEST_DATA;
-if(array_key_exists("request", $_GET)){
-	$request = $_GET["request"];
-}
-
-if($debug == 0)
-	header('Content-Type: application/json');
-
-$result = array();
-if($request == REQUEST_SHUTDOWN){
-	$handle = @fopen($config->shutdownRequestFile(), "w");
-	if($handle === false){
-		$message = "Could not create file (". $config->shutdownRequestFile() .") to indicate shutdown to the daemon (Timezone: ". date_default_timezone_get() .")";
-		if($debug > 0)
-			echo $message;
-		error_log($message);
-		$result["shutdownstart"] = -1;
-	}
-	else{
-		$shutdownTime = new DateTime('NOW');
-		$shutdownTime->modify("+15 seconds");
-		fwrite($handle, $shutdownTime->format(DateTime::ISO8601));
-		$result["shutdownstart"] = $shutdownTime->format(DateTime::ISO8601);
-	}
-}
-elseif($request == REQUEST_DATA){
-	$result["lastvalid"] = array();
-	$result["track"] = array();
-
-	if(!file_exists($dbFile)){
-		echo json_encode("");
-		if($debug > 0)
-			echo "Database file ". $dbFile ." does not exist!";
-		error_log("Database file ". $dbFile ." does not exist");
-		exit;
-	}
-	// Fetch entries of the last 30s with maximum (available) resolution of 2s
-	addRrdData("2", "240", $result, $lastValid);
-	if($lastValid){
-		$result["lastvalid"] = $lastValid;
-	}
-	// Fetch entries of the last 1h with maximum (available) resolution of 10s
- 	addRrdData("10", "36000", $result, $lastTime);
- 	// Fetch entries of the last 24h with maximum (available) resolution of 60s
- 	addRrdData("60", "86400", $result, $lastTime);
-}
-
-if($debug > 0){
-	echo json_encode($result,  JSON_PRETTY_PRINT) ."\n";
-}
-else{
-	echo json_encode($result) ."\n";
-}
+$webservice = new GnuBoat\Webservice();
+$webservice->process();
 
 ?>
Index: src/webapp/webservice/mapupload.php
===================================================================
--- src/webapp/webservice/mapupload.php	(revision 82b4b491c7371d5ccbe62b1575cb7107fb837208)
+++ 	(revision )
@@ -1,120 +1,0 @@
-<?php
-/*
-    Copyright (C) 2016 - 2017 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/>.
-*/
-
-function setMapName($mbTilesFile, $mapName)
-{
-	if(!is_file($mbTilesFile))
-		return array(false, "setMapName - Map file not found: ". $mbTilesFile);
-	if(empty($mapName) || $mapName == "")
-		return array(false, "setMapName - Map name empty");
-	try{
-		$databaseConnection = new PDO("sqlite:". $mbTilesFile);
-		$databaseConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
-		
-		$columnName = "name";
-		$query = $databaseConnection->prepare("UPDATE metadata SET value=:value WHERE name=:name");
-		$query->bindParam(":name", $columnName);
-		$query->bindParam(":value", $mapName);
-		if($query->execute() !== true){
-			return array(false, "setMapName - Could not update metadata");
-		}
-		return array(true, "");
-	}
-	catch(PDOException $e){
-		return array(false, "setMapName - Database error: ". $e->getMessage());
-	}
-}
-
-header('Content-type: application/json');
-
-$result["error"] = 1;
-$result["errormessage"] = "Unknown Error";
-
-if(!array_key_exists("mapName", $_POST)){
-	$result["error"] = 1;
-	$result["errormessage"] = "Please specify map name (no value)";
-	echo json_encode($result);
-	return;
-}
-$mapName = $_POST["mapName"];
-if(empty($mapName) || $mapName == ""){
-	$result["error"] = 1;
-	$result["errormessage"] = "Please specifiy map name (empty value)";
-	echo json_encode($result);
-	return;
-}
-
-$mapDirectory = __DIR__ ."/maps";
-if(!array_key_exists("mapFile", $_FILES)){
-	$result["error"] = 1;
-	$result["errormessage"] = "No map file recieved";
-	echo json_encode($result);
-	return;
-}
-if (!isset($_FILES['mapFile']['error']) || is_array($_FILES['mapFile']['error'])){
-	$result["error"] = 1;
-	$result["errormessage"] = "Invalid parameters";
-	echo json_encode($result);
-	return;
-}
-switch ($_FILES['mapFile']['error']) {
-	case UPLOAD_ERR_OK:
-		break;
-	case UPLOAD_ERR_NO_FILE:
-		$result["error"] = 1;
-		$result["errormessage"] = "No file sent";
-		echo json_encode($result);
-		return;
-	case UPLOAD_ERR_INI_SIZE:
-	case UPLOAD_ERR_FORM_SIZE:
-		$result["error"] = 1;
-		$result["errormessage"] = "Exceeded filesize limit.";
-		echo json_encode($result);
-		return;
-	default:
-		$result["error"] = 1;
-		$result["errormessage"] = "Unknown PHP Error";
-		echo json_encode($result);
-		return;
-}
-$mapFileName = $mapDirectory ."/". sha1_file($_FILES['mapFile']['tmp_name']) .".mbtiles";
-if(move_uploaded_file($_FILES['mapFile']['tmp_name'], $mapFileName)){
-	if(!chmod($mapFileName, 0755)){
-		$result["error"] = 1;
-		$result["errormessage"] = "Could not change permissions of the map file";
-	}
-	else{
-		// correct map metadata
-		$resultRename = setMapName($mapFileName, $mapName);
-		if($resultRename[0] === true){
-			$result["error"] = 0;
-			$result["errormessage"] = "";
-		}
-		else{
-			$result["error"] = 1;
-			$result["errormessage"] = $resultRename[1];
-		}
-	}
-}
-else {
-	$result["error"] = 1;
-	$result["errormessage"] = "Could not move map in place";
-}
-echo json_encode($result);
-
-?>
Index: src/webapp/webservice/tests/ServiceTest.php
===================================================================
--- src/webapp/webservice/tests/ServiceTest.php	(revision c455d7bd76a1b1cf6fd2e61bbf1062cc1be95af0)
+++ src/webapp/webservice/tests/ServiceTest.php	(revision c455d7bd76a1b1cf6fd2e61bbf1062cc1be95af0)
@@ -0,0 +1,72 @@
+<?php
+/*
+    Copyright (C) 2017 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/>.
+*/
+
+//  enable in php 7
+// declare(Strict_types=1);
+
+/**
+  * @brief Covers index.php tests
+  */
+final class ServiceTest extends PHPUnit_Framework_TestCase
+{
+	/**
+	  * @runInSeparateProcess
+	  */
+	public function testData()
+	{
+		$webservice = new GnuBoat\Webservice();
+		$this->assertInstanceOf(GnuBoat\Webservice::class, $webservice);
+		$_POST["request"] = "data";
+		$webservice->process();
+	}
+
+	/**
+	  * @runInSeparateProcess
+	  */
+	public function testLogFiles()
+	{
+		$webservice = new GnuBoat\Webservice();
+		$this->assertInstanceOf(GnuBoat\Webservice::class, $webservice);
+		$_POST["request"] = "logfiles";
+		$webservice->process();
+	}
+	
+	/**
+	  * @runInSeparateProcess
+	  */
+	public function testShutdown()
+	{
+		$webservice = new GnuBoat\Webservice();
+		$this->assertInstanceOf(GnuBoat\Webservice::class, $webservice);
+		$_POST["request"] = "shutdown";
+		$webservice->process();
+	}
+	
+	/**
+	  * @runInSeparateProcess
+	  */
+	public function testMap()
+	{
+		$webservice = new GnuBoat\Webservice();
+		$this->assertInstanceOf(GnuBoat\Webservice::class, $webservice);
+		$_POST["request"] = "map";
+		$webservice->process();
+	}
+}
+
+?>
