Преглед на файлове

Merge branch 'master' of http://nordh.xyz:8300/Axel/ATG

Axel Nordh преди 3 години
родител
ревизия
9e30fa0410

+ 1 - 2
ATG/.classpath

@@ -6,9 +6,8 @@
 			<attribute name="maven.pomderived" value="true"/>
 		</attributes>
 	</classpathentry>
-	<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-18">
+	<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-11">
 		<attributes>
-			<attribute name="module" value="true"/>
 			<attribute name="maven.pomderived" value="true"/>
 		</attributes>
 	</classpathentry>

+ 3 - 3
ATG/.settings/org.eclipse.jdt.core.prefs

@@ -1,8 +1,8 @@
 eclipse.preferences.version=1
 org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled
-org.eclipse.jdt.core.compiler.codegen.targetPlatform=18
+org.eclipse.jdt.core.compiler.codegen.targetPlatform=11
 org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve
-org.eclipse.jdt.core.compiler.compliance=18
+org.eclipse.jdt.core.compiler.compliance=11
 org.eclipse.jdt.core.compiler.debug.lineNumber=generate
 org.eclipse.jdt.core.compiler.debug.localVariable=generate
 org.eclipse.jdt.core.compiler.debug.sourceFile=generate
@@ -12,4 +12,4 @@ org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
 org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
 org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=warning
 org.eclipse.jdt.core.compiler.release=enabled
-org.eclipse.jdt.core.compiler.source=18
+org.eclipse.jdt.core.compiler.source=11

+ 2 - 2
ATG/pom.xml

@@ -27,7 +27,7 @@
      <dependency>
 	 <groupId>com.google.guava</groupId>
 	 <artifactId>guava</artifactId>
-	 <version>30.0-jre</version>
+	 <version>31.1-jre</version>
 	</dependency>
 	<dependency>
  	   <groupId>net.sourceforge.htmlunit</groupId>
@@ -38,7 +38,7 @@
 	<dependency>
     	<groupId>mysql</groupId>
     	<artifactId>mysql-connector-java</artifactId>
-    	<version>8.0.28</version>
+    	<version>8.0.30</version>
 	</dependency>
 
 	<dependency>

+ 447 - 0
ATG/src/controllers/AutoPickerController.java

@@ -0,0 +1,447 @@
+package controllers;
+
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.ResourceBundle;
+import java.util.stream.Collectors;
+
+import database.DriverDB;
+import database.Ekipage;
+import database.Horse;
+import javafx.application.Platform;
+import javafx.beans.value.ChangeListener;
+import javafx.beans.value.ObservableValue;
+import javafx.collections.ObservableList;
+import javafx.fxml.FXML;
+import javafx.fxml.Initializable;
+import javafx.scene.control.Button;
+import javafx.scene.control.CheckBox;
+import javafx.scene.control.DatePicker;
+import javafx.scene.control.Tab;
+import javafx.scene.control.TabPane;
+import javafx.scene.layout.Pane;
+import javafx.scene.layout.VBox;
+import objects.Result;
+
+public class AutoPickerController implements Initializable {
+	@FXML DatePicker datePicker;
+	@FXML Button submitButton;
+	@FXML TabPane locationTabs;
+	@FXML Pane mainContentPane;
+	@FXML Button autoPickButton;
+
+	List<Tab> tracksList = new ArrayList<>();
+	private int checkedCount = 0;
+	private List<Result> todaysRaces = new ArrayList<>();
+	private Map<String, Integer> selectedRaceNumbers = new HashMap<>();
+
+	private Map<String, Float> pointMultiplier = new HashMap<>();
+
+	@Override public void initialize(URL arg0, ResourceBundle arg1) {
+		datePicker.valueProperty().addListener((observable, oldValue, newValue) -> {
+			if (newValue == null) {
+				submitButton.setDisable(true);
+			} else {
+				submitButton.setDisable(false);
+			}
+		});
+		buildPointMultiplier();
+	}
+
+	private void buildPointMultiplier() {
+		pointMultiplier.put("driverTimeAll", 0.23f);
+	}
+
+	@FXML public void submitAction() {
+		submitButton.setDisable(true);
+		todaysRaces.clear();
+		selectedRaceNumbers.clear();
+		tracksList.clear();
+
+		Platform.runLater(() -> {
+			todaysRaces.addAll(
+					Result.convertHorseRaceDataList(DatabaseController.getInstance().getRacesFromDate(datePicker.getValue().toString(), false)));
+
+			List<String> tracks = todaysRaces.stream().map(Result::getTrackName).distinct().collect(Collectors.toList());
+
+			createTabs(tracks);
+			addRacesToTabs();
+
+			submitButton.setDisable(false);
+		});
+	}
+
+	@FXML public void autoPickAction() {
+		List<Result> selectedRaces = getSelectedRaces();
+		selectedRaceNumbers = selectedRaceNumbers.entrySet().stream().sorted(Map.Entry.comparingByValue())
+				.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
+		selectedRaceNumbers.forEach((k, v) -> {
+			List<Result> firstRace = selectedRaces.stream()
+					.filter(p -> p.getTrackName().equals(k.substring(0, k.indexOf("-"))) && p.getRaceNumber() == v).collect(Collectors.toList());
+			pickBest(firstRace);
+		});
+	}
+
+	private void pickBest(List<Result> firstRace) {
+		final int topLimit = 2;
+		final Horse horseDb = Horse.getInstance();
+		final DriverDB driverDb = DriverDB.getInstance();
+		final Ekipage ekipageDb = Ekipage.getInstance();
+		for (Result res : firstRace) {
+
+			// SET Driver averages
+			res.setAvgTimeDriverAll(driverDb.avarageTime(res.getDriverId(), res.getRaceDate()).getRes());
+			res.setAvgTimeDriverDistanceAll(driverDb.avarageTimeByDistance(res.getDriverId(), res.getDistance(), res.getRaceDate()).getRes());
+			res.setAvgTimeDriverDistanceLast5(driverDb.avarageTimeByDistance(res.getDriverId(), res.getDistance(), 5, res.getRaceDate()).getRes());
+			res.setAvgTimeDriverDistanceLast10(driverDb.avarageTimeByDistance(res.getDriverId(), res.getDistance(), 10, res.getRaceDate()).getRes());
+			res.setAvgTimeDriverDistanceLast15(driverDb.avarageTimeByDistance(res.getDriverId(), res.getDistance(), 15, res.getRaceDate()).getRes());
+			res.setAvgTimeDriverLast5(driverDb.avarageTimeWithLimit(res.getDriverId(), 5, res.getRaceDate()).getRes());
+			res.setAvgTimeDriverLast10(driverDb.avarageTimeWithLimit(res.getDriverId(), 10, res.getRaceDate()).getRes());
+			res.setAvgTimeDriverLast15(driverDb.avarageTimeWithLimit(res.getDriverId(), 15, res.getRaceDate()).getRes());
+			res.setAvgPositionDriverAll(driverDb.avaragePlacement(res.getDriverId(), res.getRaceDate()).getRes());
+			res.setAvgPositionDriverDistanceAll(
+					driverDb.avaragePlacementByDistance(res.getDriverId(), res.getDistance(), res.getRaceDate()).getRes());
+			res.setAvgPositionDriverDistanceLast5(
+					driverDb.avaragePlacementByDistance(res.getDriverId(), res.getDistance(), 5, res.getRaceDate()).getRes());
+			res.setAvgPositionDriverDistanceLast10(
+					driverDb.avaragePlacementByDistance(res.getDriverId(), res.getDistance(), 10, res.getRaceDate()).getRes());
+			res.setAvgPositionDriverDistanceLast15(
+					driverDb.avaragePlacementByDistance(res.getDriverId(), res.getDistance(), 15, res.getRaceDate()).getRes());
+			res.setAvgPositionDriverLast5(driverDb.avaragePlacementWithLimit(res.getDriverId(), 5, res.getRaceDate()).getRes());
+			res.setAvgPositionDriverLast10(driverDb.avaragePlacementWithLimit(res.getDriverId(), 10, res.getRaceDate()).getRes());
+			res.setAvgPositionDriverLast15(driverDb.avaragePlacementWithLimit(res.getDriverId(), 15, res.getRaceDate()).getRes());
+
+			// SET Horse averages
+			res.setAvgTimeHorseAll(horseDb.avarageTime(res.getHorseId(), res.getRaceDate()).getRes());
+			res.setAvgTimeHorseDistanceAll(horseDb.avarageTimeByDistance(res.getHorseId(), res.getDistance(), res.getRaceDate()).getRes());
+			res.setAvgTimeHorseDistanceLast5(horseDb.avarageTimeByDistance(res.getHorseId(), res.getDistance(), 5, res.getRaceDate()).getRes());
+			res.setAvgTimeHorseDistanceLast10(horseDb.avarageTimeByDistance(res.getHorseId(), res.getDistance(), 10, res.getRaceDate()).getRes());
+			res.setAvgTimeHorseDistanceLast15(horseDb.avarageTimeByDistance(res.getHorseId(), res.getDistance(), 15, res.getRaceDate()).getRes());
+			res.setAvgTimeHorseLast5(horseDb.avarageTimeWithLimit(res.getHorseId(), 5, res.getRaceDate()).getRes());
+			res.setAvgTimeHorseLast10(horseDb.avarageTimeWithLimit(res.getHorseId(), 10, res.getRaceDate()).getRes());
+			res.setAvgTimeHorseLast15(horseDb.avarageTimeWithLimit(res.getHorseId(), 15, res.getRaceDate()).getRes());
+			res.setAvgPositionHorseAll(horseDb.avaragePlacement(res.getHorseId(), res.getRaceDate()).getRes());
+			res.setAvgPositionHorseDistanceAll(horseDb.avaragePlacementByDistance(res.getHorseId(), res.getDistance(), res.getRaceDate()).getRes());
+			res.setAvgPositionHorseDistanceLast5(
+					horseDb.avaragePlacementByDistance(res.getHorseId(), res.getDistance(), 5, res.getRaceDate()).getRes());
+			res.setAvgPositionHorseDistanceLast10(
+					horseDb.avaragePlacementByDistance(res.getHorseId(), res.getDistance(), 10, res.getRaceDate()).getRes());
+			res.setAvgPositionHorseDistanceLast15(
+					horseDb.avaragePlacementByDistance(res.getHorseId(), res.getDistance(), 15, res.getRaceDate()).getRes());
+			res.setAvgPositionHorseLast5(horseDb.avaragePlacementWithLimit(res.getHorseId(), 5, res.getRaceDate()).getRes());
+			res.setAvgPositionHorseLast10(horseDb.avaragePlacementWithLimit(res.getHorseId(), 10, res.getRaceDate()).getRes());
+			res.setAvgPositionHorseLast15(horseDb.avaragePlacementWithLimit(res.getHorseId(), 15, res.getRaceDate()).getRes());
+
+			// SET Combined averages
+			res.setAvgTimeCombinedAll(ekipageDb.avarageTime(res.getDriverId(), res.getHorseId(), res.getRaceDate()).getRes());
+			res.setAvgTimeCombinedDistanceAll(
+					ekipageDb.avarageTimeByDistance(res.getDriverId(), res.getHorseId(), res.getDistance(), res.getRaceDate()).getRes());
+			res.setAvgTimeCombinedDistanceLast5(
+					ekipageDb.avarageTimeByDistance(res.getDriverId(), res.getHorseId(), res.getDistance(), 5, res.getRaceDate()).getRes());
+			res.setAvgTimeCombinedDistanceLast10(
+					ekipageDb.avarageTimeByDistance(res.getDriverId(), res.getHorseId(), res.getDistance(), 10, res.getRaceDate()).getRes());
+			res.setAvgTimeCombinedDistanceLast15(
+					ekipageDb.avarageTimeByDistance(res.getDriverId(), res.getHorseId(), res.getDistance(), 15, res.getRaceDate()).getRes());
+			res.setAvgTimeCombinedLast5(ekipageDb.avarageTimeWithLimit(res.getDriverId(), res.getHorseId(), 5, res.getRaceDate()).getRes());
+			res.setAvgTimeCombinedLast10(ekipageDb.avarageTimeWithLimit(res.getDriverId(), res.getHorseId(), 10, res.getRaceDate()).getRes());
+			res.setAvgTimeCombinedLast15(ekipageDb.avarageTimeWithLimit(res.getDriverId(), res.getHorseId(), 15, res.getRaceDate()).getRes());
+			res.setAvgPositionCombinedAll(ekipageDb.avaragePlacement(res.getDriverId(), res.getHorseId(), res.getRaceDate()).getRes());
+			res.setAvgPositionCombinedDistanceAll(
+					ekipageDb.avaragePlacementByDistance(res.getDriverId(), res.getHorseId(), res.getDistance(), res.getRaceDate()).getRes());
+			res.setAvgPositionCombinedDistanceLast5(
+					ekipageDb.avaragePlacementByDistance(res.getDriverId(), res.getHorseId(), res.getDistance(), 5, res.getRaceDate()).getRes());
+			res.setAvgPositionCombinedDistanceLast10(
+					ekipageDb.avaragePlacementByDistance(res.getDriverId(), res.getHorseId(), res.getDistance(), 10, res.getRaceDate()).getRes());
+			res.setAvgPositionCombinedDistanceLast15(
+					ekipageDb.avaragePlacementByDistance(res.getDriverId(), res.getHorseId(), res.getDistance(), 15, res.getRaceDate()).getRes());
+			res.setAvgPositionCombinedLast5(ekipageDb.avaragePlacementWithLimit(res.getDriverId(), res.getHorseId(), 5, res.getRaceDate()).getRes());
+			res.setAvgPositionCombinedLast10(
+					ekipageDb.avaragePlacementWithLimit(res.getDriverId(), res.getHorseId(), 10, res.getRaceDate()).getRes());
+			res.setAvgPositionCombinedLast15(
+					ekipageDb.avaragePlacementWithLimit(res.getDriverId(), res.getHorseId(), 15, res.getRaceDate()).getRes());
+		}
+
+		// List sorted by driver
+		List<Result> driverTimeAllSorted = firstRace.stream()
+				.sorted((r1, r2) -> compareDoubleZeroLast(r1.getAvgTimeDriverAll(), r2.getAvgTimeDriverAll())).collect(Collectors.toList());
+		List<Result> driverTimeLast5Sorted = firstRace.stream()
+				.sorted((r1, r2) -> compareDoubleZeroLast(r1.getAvgTimeDriverLast5(), r2.getAvgTimeDriverLast5())).collect(Collectors.toList());
+		List<Result> driverTimeLast10Sorted = firstRace.stream()
+				.sorted((r1, r2) -> compareDoubleZeroLast(r1.getAvgTimeDriverLast10(), r2.getAvgTimeDriverLast10())).collect(Collectors.toList());
+		List<Result> driverTimeLast15Sorted = firstRace.stream()
+				.sorted((r1, r2) -> compareDoubleZeroLast(r1.getAvgTimeDriverLast15(), r2.getAvgTimeDriverLast15())).collect(Collectors.toList());
+		List<Result> driverTimeDistanceAllSorted = firstRace.stream()
+				.sorted((r1, r2) -> compareDoubleZeroLast(r1.getAvgTimeDriverDistanceAll(), r2.getAvgTimeCombinedDistanceAll()))
+				.collect(Collectors.toList());
+		List<Result> driverTimeDistanceLast5Sorted = firstRace.stream()
+				.sorted((r1, r2) -> compareDoubleZeroLast(r1.getAvgTimeDriverDistanceLast5(), r2.getAvgTimeDriverDistanceLast5()))
+				.collect(Collectors.toList());
+		List<Result> driverTimeDistanceLast10Sorted = firstRace.stream()
+				.sorted((r1, r2) -> compareDoubleZeroLast(r1.getAvgTimeDriverDistanceLast10(), r2.getAvgTimeDriverDistanceLast10()))
+				.collect(Collectors.toList());
+		List<Result> driverTimeDistanceLast15Sorted = firstRace.stream()
+				.sorted((r1, r2) -> compareDoubleZeroLast(r1.getAvgTimeDriverDistanceLast15(), r2.getAvgTimeDriverDistanceLast15()))
+				.collect(Collectors.toList());
+		List<Result> driverPositionAllSorted = firstRace.stream()
+				.sorted((r1, r2) -> compareDoubleZeroLast(r1.getAvgPositionDriverAll(), r2.getAvgPositionDriverAll())).collect(Collectors.toList());
+		List<Result> driverPositionLast5Sorted = firstRace.stream()
+				.sorted((r1, r2) -> compareDoubleZeroLast(r1.getAvgPositionDriverLast5(), r2.getAvgPositionDriverLast5()))
+				.collect(Collectors.toList());
+		List<Result> driverPositionLast10Sorted = firstRace.stream()
+				.sorted((r1, r2) -> compareDoubleZeroLast(r1.getAvgPositionDriverLast10(), r2.getAvgPositionDriverLast10()))
+				.collect(Collectors.toList());
+		List<Result> driverPositionLast15Sorted = firstRace.stream()
+				.sorted((r1, r2) -> compareDoubleZeroLast(r1.getAvgPositionDriverLast15(), r2.getAvgPositionDriverLast15()))
+				.collect(Collectors.toList());
+		List<Result> driverPositionDistanceAllSorted = firstRace.stream()
+				.sorted((r1, r2) -> compareDoubleZeroLast(r1.getAvgPositionDriverDistanceAll(), r2.getAvgPositionCombinedDistanceAll()))
+				.collect(Collectors.toList());
+		List<Result> driverPositionDistanceLast5Sorted = firstRace.stream()
+				.sorted((r1, r2) -> compareDoubleZeroLast(r1.getAvgPositionDriverDistanceLast5(), r2.getAvgPositionDriverDistanceLast5()))
+				.collect(Collectors.toList());
+		List<Result> driverPositionDistanceLast10Sorted = firstRace.stream()
+				.sorted((r1, r2) -> compareDoubleZeroLast(r1.getAvgPositionDriverDistanceLast10(), r2.getAvgPositionDriverDistanceLast10()))
+				.collect(Collectors.toList());
+		List<Result> driverPositionDistanceLast15Sorted = firstRace.stream()
+				.sorted((r1, r2) -> compareDoubleZeroLast(r1.getAvgPositionDriverDistanceLast15(), r2.getAvgPositionDriverDistanceLast15()))
+				.collect(Collectors.toList());
+
+		// List sorted by horse
+		List<Result> horseTimeAllSorted = firstRace.stream()
+				.sorted((r1, r2) -> compareDoubleZeroLast(r1.getAvgTimeHorseAll(), r2.getAvgTimeHorseAll())).collect(Collectors.toList());
+		List<Result> horseTimeLast5Sorted = firstRace.stream()
+				.sorted((r1, r2) -> compareDoubleZeroLast(r1.getAvgTimeHorseLast5(), r2.getAvgTimeHorseLast5())).collect(Collectors.toList());
+		List<Result> horseTimeLast10Sorted = firstRace.stream()
+				.sorted((r1, r2) -> compareDoubleZeroLast(r1.getAvgTimeHorseLast10(), r2.getAvgTimeHorseLast10())).collect(Collectors.toList());
+		List<Result> horseTimeLast15Sorted = firstRace.stream()
+				.sorted((r1, r2) -> compareDoubleZeroLast(r1.getAvgTimeHorseLast15(), r2.getAvgTimeHorseLast15())).collect(Collectors.toList());
+		List<Result> horseTimeDistanceAllSorted = firstRace.stream()
+				.sorted((r1, r2) -> compareDoubleZeroLast(r1.getAvgTimeHorseDistanceAll(), r2.getAvgTimeCombinedDistanceAll()))
+				.collect(Collectors.toList());
+		List<Result> horseTimeDistanceLast5Sorted = firstRace.stream()
+				.sorted((r1, r2) -> compareDoubleZeroLast(r1.getAvgTimeHorseDistanceLast5(), r2.getAvgTimeHorseDistanceLast5()))
+				.collect(Collectors.toList());
+		List<Result> horseTimeDistanceLast10Sorted = firstRace.stream()
+				.sorted((r1, r2) -> compareDoubleZeroLast(r1.getAvgTimeHorseDistanceLast10(), r2.getAvgTimeHorseDistanceLast10()))
+				.collect(Collectors.toList());
+		List<Result> horseTimeDistanceLast15Sorted = firstRace.stream()
+				.sorted((r1, r2) -> compareDoubleZeroLast(r1.getAvgTimeHorseDistanceLast15(), r2.getAvgTimeHorseDistanceLast15()))
+				.collect(Collectors.toList());
+		List<Result> horsePositionAllSorted = firstRace.stream()
+				.sorted((r1, r2) -> compareDoubleZeroLast(r1.getAvgPositionHorseAll(), r2.getAvgPositionHorseAll())).collect(Collectors.toList());
+		List<Result> horsePositionLast5Sorted = firstRace.stream()
+				.sorted((r1, r2) -> compareDoubleZeroLast(r1.getAvgPositionHorseLast5(), r2.getAvgPositionHorseLast5())).collect(Collectors.toList());
+		List<Result> horsePositionLast10Sorted = firstRace.stream()
+				.sorted((r1, r2) -> compareDoubleZeroLast(r1.getAvgPositionHorseLast10(), r2.getAvgPositionHorseLast10()))
+				.collect(Collectors.toList());
+		List<Result> horsePositionLast15Sorted = firstRace.stream()
+				.sorted((r1, r2) -> compareDoubleZeroLast(r1.getAvgPositionHorseLast15(), r2.getAvgPositionHorseLast15()))
+				.collect(Collectors.toList());
+		List<Result> horsePositionDistanceAllSorted = firstRace.stream()
+				.sorted((r1, r2) -> compareDoubleZeroLast(r1.getAvgPositionHorseDistanceAll(), r2.getAvgPositionCombinedDistanceAll()))
+				.collect(Collectors.toList());
+		List<Result> horsePositionDistanceLast5Sorted = firstRace.stream()
+				.sorted((r1, r2) -> compareDoubleZeroLast(r1.getAvgPositionHorseDistanceLast5(), r2.getAvgPositionHorseDistanceLast5()))
+				.collect(Collectors.toList());
+		List<Result> horsePositionDistanceLast10Sorted = firstRace.stream()
+				.sorted((r1, r2) -> compareDoubleZeroLast(r1.getAvgPositionHorseDistanceLast10(), r2.getAvgPositionHorseDistanceLast10()))
+				.collect(Collectors.toList());
+		List<Result> horsePositionDistanceLast15Sorted = firstRace.stream()
+				.sorted((r1, r2) -> compareDoubleZeroLast(r1.getAvgPositionHorseDistanceLast15(), r2.getAvgPositionHorseDistanceLast15()))
+				.collect(Collectors.toList());
+
+		// List sorted by combined
+		List<Result> combinedTimeAllSorted = firstRace.stream()
+				.sorted((r1, r2) -> compareDoubleZeroLast(r1.getAvgTimeCombinedAll(), r2.getAvgTimeCombinedAll())).collect(Collectors.toList());
+		List<Result> combinedTimeLast5Sorted = firstRace.stream()
+				.sorted((r1, r2) -> compareDoubleZeroLast(r1.getAvgTimeCombinedLast5(), r2.getAvgTimeCombinedLast5())).collect(Collectors.toList());
+		List<Result> combinedTimeLast10Sorted = firstRace.stream()
+				.sorted((r1, r2) -> compareDoubleZeroLast(r1.getAvgTimeCombinedLast10(), r2.getAvgTimeCombinedLast10())).collect(Collectors.toList());
+		List<Result> combinedTimeLast15Sorted = firstRace.stream()
+				.sorted((r1, r2) -> compareDoubleZeroLast(r1.getAvgTimeCombinedLast15(), r2.getAvgTimeCombinedLast15())).collect(Collectors.toList());
+		List<Result> combinedTimeDistanceAllSorted = firstRace.stream()
+				.sorted((r1, r2) -> compareDoubleZeroLast(r1.getAvgTimeCombinedDistanceAll(), r2.getAvgTimeCombinedDistanceAll()))
+				.collect(Collectors.toList());
+		List<Result> combinedTimeDistanceLast5Sorted = firstRace.stream()
+				.sorted((r1, r2) -> compareDoubleZeroLast(r1.getAvgTimeCombinedDistanceLast5(), r2.getAvgTimeCombinedDistanceLast5()))
+				.collect(Collectors.toList());
+		List<Result> combinedTimeDistanceLast10Sorted = firstRace.stream()
+				.sorted((r1, r2) -> compareDoubleZeroLast(r1.getAvgTimeCombinedDistanceLast10(), r2.getAvgTimeCombinedDistanceLast10()))
+				.collect(Collectors.toList());
+		List<Result> combinedTimeDistanceLast15Sorted = firstRace.stream()
+				.sorted((r1, r2) -> compareDoubleZeroLast(r1.getAvgTimeCombinedDistanceLast15(), r2.getAvgTimeCombinedDistanceLast15()))
+				.collect(Collectors.toList());
+		List<Result> combinedPositionAllSorted = firstRace.stream()
+				.sorted((r1, r2) -> compareDoubleZeroLast(r1.getAvgPositionCombinedAll(), r2.getAvgPositionCombinedAll()))
+				.collect(Collectors.toList());
+		List<Result> combinedPositionLast5Sorted = firstRace.stream()
+				.sorted((r1, r2) -> compareDoubleZeroLast(r1.getAvgPositionCombinedLast5(), r2.getAvgPositionCombinedLast5()))
+				.collect(Collectors.toList());
+		List<Result> combinedPositionLast10Sorted = firstRace.stream()
+				.sorted((r1, r2) -> compareDoubleZeroLast(r1.getAvgPositionCombinedLast10(), r2.getAvgPositionCombinedLast10()))
+				.collect(Collectors.toList());
+		List<Result> combinedPositionLast15Sorted = firstRace.stream()
+				.sorted((r1, r2) -> compareDoubleZeroLast(r1.getAvgPositionCombinedLast15(), r2.getAvgPositionCombinedLast15()))
+				.collect(Collectors.toList());
+		List<Result> combinedPositionDistanceAllSorted = firstRace.stream()
+				.sorted((r1, r2) -> compareDoubleZeroLast(r1.getAvgPositionCombinedDistanceAll(), r2.getAvgPositionCombinedDistanceAll()))
+				.collect(Collectors.toList());
+		List<Result> combinedPositionDistanceLast5Sorted = firstRace.stream()
+				.sorted((r1, r2) -> compareDoubleZeroLast(r1.getAvgPositionCombinedDistanceLast5(), r2.getAvgPositionCombinedDistanceLast5()))
+				.collect(Collectors.toList());
+		List<Result> combinedPositionDistanceLast10Sorted = firstRace.stream()
+				.sorted((r1, r2) -> compareDoubleZeroLast(r1.getAvgPositionCombinedDistanceLast10(), r2.getAvgPositionCombinedDistanceLast10()))
+				.collect(Collectors.toList());
+		List<Result> combinedPositionDistanceLast15Sorted = firstRace.stream()
+				.sorted((r1, r2) -> compareDoubleZeroLast(r1.getAvgPositionCombinedDistanceLast15(), r2.getAvgPositionCombinedDistanceLast15()))
+				.collect(Collectors.toList());
+
+		Map<String, List<Result>> sortedLists = new HashMap<>();
+		sortedLists.put("driverTimeAll", driverTimeAllSorted);
+		sortedLists.put("driverTimeLast5", driverTimeLast5Sorted);
+		sortedLists.put("driverTimeLast10", driverTimeLast10Sorted);
+		sortedLists.put("driverTimeLast15", driverTimeLast15Sorted);
+		sortedLists.put("driverTimeDistanceAll", driverTimeDistanceAllSorted);
+		sortedLists.put("driverTimeDistanceLast5", driverTimeDistanceLast5Sorted);
+		sortedLists.put("driverTimeDistanceLast10", driverTimeDistanceLast10Sorted);
+		sortedLists.put("driverTimeDistanceLast15", driverTimeDistanceLast15Sorted);
+		sortedLists.put("driverPositionAll", driverPositionAllSorted);
+		sortedLists.put("driverPositionLast5", driverPositionLast5Sorted);
+		sortedLists.put("driverPositionLast10", driverPositionLast10Sorted);
+		sortedLists.put("driverPositionLast15", driverPositionLast15Sorted);
+		sortedLists.put("driverPositionDistanceAll", driverPositionDistanceAllSorted);
+		sortedLists.put("driverPositionDistanceLast5", driverPositionDistanceLast5Sorted);
+		sortedLists.put("driverPositionDistanceLast10", driverPositionDistanceLast10Sorted);
+		sortedLists.put("driverPositionDistanceLast15", driverPositionDistanceLast15Sorted);
+
+		sortedLists.put("horseTimeAll", horseTimeAllSorted);
+		sortedLists.put("horseTimeLast5", horseTimeLast5Sorted);
+		sortedLists.put("horseTimeLast10", horseTimeLast10Sorted);
+		sortedLists.put("horseTimeLast15", horseTimeLast15Sorted);
+		sortedLists.put("horseTimeDistanceAll", horseTimeDistanceAllSorted);
+		sortedLists.put("horseTimeDistanceLast5", horseTimeDistanceLast5Sorted);
+		sortedLists.put("horseTimeDistanceLast10", horseTimeDistanceLast10Sorted);
+		sortedLists.put("horseTimeDistanceLast15", horseTimeDistanceLast15Sorted);
+		sortedLists.put("horsePositionAll", horsePositionAllSorted);
+		sortedLists.put("horsePositionLast5", horsePositionLast5Sorted);
+		sortedLists.put("horsePositionLast10", horsePositionLast10Sorted);
+		sortedLists.put("horsePositionLast15", horsePositionLast15Sorted);
+		sortedLists.put("horsePositionDistanceAll", horsePositionDistanceAllSorted);
+		sortedLists.put("horsePositionDistanceLast5", horsePositionDistanceLast5Sorted);
+		sortedLists.put("horsePositionDistanceLast10", horsePositionDistanceLast10Sorted);
+		sortedLists.put("horsePositionDistanceLast15", horsePositionDistanceLast15Sorted);
+
+		sortedLists.put("combinedTimeAll", combinedTimeAllSorted);
+		sortedLists.put("combinedTimeLast5", combinedTimeLast5Sorted);
+		sortedLists.put("combinedTimeLast10", combinedTimeLast10Sorted);
+		sortedLists.put("combinedTimeLast15", combinedTimeLast15Sorted);
+		sortedLists.put("combinedTimeDistanceAll", combinedTimeDistanceAllSorted);
+		sortedLists.put("combinedTimeDistanceLast5", combinedTimeDistanceLast5Sorted);
+		sortedLists.put("combinedTimeDistanceLast10", combinedTimeDistanceLast10Sorted);
+		sortedLists.put("combinedTimeDistanceLast15", combinedTimeDistanceLast15Sorted);
+		sortedLists.put("combinedPositionAll", combinedPositionAllSorted);
+		sortedLists.put("combinedPositionLast5", combinedPositionLast5Sorted);
+		sortedLists.put("combinedPositionLast10", combinedPositionLast10Sorted);
+		sortedLists.put("combinedPositionLast15", combinedPositionLast15Sorted);
+		sortedLists.put("combinedPositionDistanceAll", combinedPositionDistanceAllSorted);
+		sortedLists.put("combinedPositionDistanceLast5", combinedPositionDistanceLast5Sorted);
+		sortedLists.put("combinedPositionDistanceLast10", combinedPositionDistanceLast10Sorted);
+		sortedLists.put("combinedPositionDistanceLast15", combinedPositionDistanceLast15Sorted);
+
+		Map<Result, Float> topPicks = new HashMap<>();
+		for (Result result : firstRace) {
+			for (Entry<String, List<Result>> sortedList : sortedLists.entrySet()) {
+				if (sortedList.getValue().stream().limit(topLimit).anyMatch(res -> res.equals(result))) {
+					topPicks.merge(result, pointMultiplier.getOrDefault(sortedList.getKey(), 1f), Float::sum);
+				}
+			}
+		}
+
+		List<Entry<Result, Float>> sortedTopPicks = topPicks.entrySet().stream().sorted(Map.Entry.comparingByValue()).collect(Collectors.toList());
+
+		for (Entry<Result, Float> entry : sortedTopPicks) {
+			System.out.println(String.format("RaceNumber %s Driver %s Horse %s number of top results %s", entry.getKey().getRaceNumber(),
+					driverDb.getNameFromId(entry.getKey().getDriverId()), horseDb.getNameFromId(entry.getKey().getHorseId()), entry.getValue()));
+		}
+	}
+
+	private int compareDoubleZeroLast(float o1, float o2) {
+		if (o1 == 0.0 && o2 == 0.0) {
+			return 0;
+		}
+		if (o1 == 0.0) {
+			return 1;
+		}
+		if (o2 == 0.0) {
+			return -1;
+		}
+
+		return Float.compare(o1, o2);
+	}
+
+	private List<Result> getSelectedRaces() {
+		List<Result> result = new ArrayList<>();
+
+		ObservableList<Tab> tabs = locationTabs.getTabs();
+		for (Tab tab : tabs) {
+			List<Integer> raceNumbers = ((VBox) tab.getContent()).getChildren().stream().map(CheckBox.class::cast).filter(CheckBox::isSelected)
+					.map(CheckBox::getText).map(Integer::valueOf).collect(Collectors.toList());
+			int i = 1;
+			for (Integer rn : raceNumbers) {
+				selectedRaceNumbers.put(tab.getText() + "-" + i++, rn);
+			}
+			if (!selectedRaceNumbers.isEmpty()) {
+				result.addAll(todaysRaces.stream()
+						.filter(r -> r.getTrackName().equals(tab.getText()) && selectedRaceNumbers.values().contains(r.getRaceNumber()))
+						.collect(Collectors.toList()));
+			}
+		}
+
+		return result;
+	}
+
+	private void addRacesToTabs() {
+		for (Tab tab : tracksList) {
+			List<Integer> raceNumbers = todaysRaces.stream().filter(p -> p.getTrackName().equals(tab.getText())).map(Result::getRaceNumber).distinct()
+					.collect(Collectors.toList());
+
+			for (Integer raceNumber : raceNumbers) {
+				CheckBox rnCheckBox = new CheckBox(raceNumber.toString());
+				rnCheckBox.selectedProperty().addListener(new ChangeListener<Boolean>() {
+
+					@SuppressWarnings({ "rawtypes", "unchecked" })
+					@Override public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
+						if (newValue) { // checked
+							checkedCount++;
+							autoPickButton.setDisable(false);
+						} else {
+							checkedCount--;
+							if (checkedCount <= 0) {
+								checkedCount = 0;
+								autoPickButton.setDisable(true);
+							}
+						}
+					}
+				});
+				((VBox) tab.getContent()).getChildren().add(rnCheckBox);
+			}
+
+		}
+	}
+
+	private void createTabs(List<String> tracks) {
+		locationTabs.getTabs().removeAll(locationTabs.getTabs());
+		for (String track : tracks) {
+			Tab tab = new Tab(track);
+			VBox layout = new VBox();
+			tab.setContent(layout);
+			tracksList.add(tab);
+		}
+
+		locationTabs.getTabs().addAll(tracksList);
+	}
+}

+ 1618 - 1594
ATG/src/controllers/DatabaseController.java

@@ -34,1599 +34,1623 @@ import parsers.TravsportParser;
 
 public class DatabaseController {
 
-    private static final DatabaseController instance = new DatabaseController();
-
-    private static final String username = "atg";
-    private static final String password = "CvWKY34DqtlVgjt_9";
-    private static final String database = "atg";
-    private static final String url = "jdbc:mysql://nordh.xyz:3306/";
-    private static final String timezoneFix
-            = "?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";
-
-    private Connection conn;
-
-    protected DatabaseController() {
-        getConnection();
-    }
-
-    public static DatabaseController getInstance() {
-        return instance;
-    }
-
-    protected Connection getConnection() {
-        if (conn == null) {
-            try {
-                conn = DriverManager.getConnection(url + database + timezoneFix, username, password);
-            } catch (final SQLException e) {
-                throw new RuntimeException(e.getMessage(), e);
-            }
-        }
-        return conn;
-    }
-
-    public void insertResult(String trackShortCode, String date, int raceNumber, int lane, int distance, int result, float time,
-            String timeModifier, int shoes, int sulky, String driver, String trainer, String horseName, int travsportIdHorse,
-            int travsportIdTrainer, int travsportIdDriver, String raceType, int raceId) {
-        final String sql;
-        final boolean raceToday = date.equals(MainController.DATE_FORMAT.format(new Date()));
-        horseName = horseName.replaceAll("[^a-zåäöA-ZÅÄÖ0-9 ()\\.']", "");
-        driver = driver.replaceAll("[^a-zåäöA-ZÅÄÖ0-9] ()\\.'", "");
-        if (raceToday) {
-            sql = "INSERT INTO "
-                    + "`Results`(`TrackId`, `RaceDate`, `RaceNumber`, `Lane`, `Distance`, `Result`, `Time`, `TimeModifier`, "
-                    + "`Shoes`, `Sulky`, `DriverId`, `TrainerId`, `HorseId`, raceId, RaceType) "
-                    + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE id=id, Result = ?, Time = ?, RaceType = CONCAT(RaceType, ?), RaceId = ?";
-        } else {
-            sql = "INSERT INTO "
-                    + "`Results`(`TrackId`, `RaceDate`, `RaceNumber`, `Lane`, `Distance`, `Result`, `Time`, `TimeModifier`, "
-                    + "`Shoes`, `Sulky`, `DriverId`, `TrainerId`, `HorseId`, raceId) "
-                    + "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE id=id, Result = ?, Time = ?, RaceId = ?";
-        }
-
-        final int horseId = getHorseId(horseName, travsportIdHorse);
-        final int driverId = getDriverId(driver, travsportIdDriver);
-        final int trainerId = getTrainerId(trainer, travsportIdTrainer);
-        final int trackId = getTrackIdFromShortcode(trackShortCode);
-
-        if (horseId == -1 || driverId == -1) {
-            return;
-        }
-        try {
-            final PreparedStatement stat = getConnection().prepareStatement(sql);
-
-            stat.setInt(1, trackId);
-            stat.setString(2, date);
-            stat.setInt(3, raceNumber);
-            stat.setInt(4, lane);
-            stat.setInt(5, distance);
-            stat.setInt(6, result);
-            stat.setFloat(7, time);
-            stat.setString(8, timeModifier);
-            stat.setInt(9, shoes);
-            stat.setInt(10, sulky);
-            stat.setInt(11, driverId);
-            if (trainerId < 0) {
-                stat.setNull(12, Types.INTEGER);
-            } else {
-                stat.setInt(12, trainerId);
-            }
-            stat.setInt(13, horseId);
-            stat.setInt(14, result < 0 ? raceId : -1);
-
-            if (raceToday) {
-                stat.setString(15, raceType);
-
-                stat.setInt(16, result);
-                stat.setFloat(17, time);
-                stat.setString(18, ", " + raceType);
-                stat.setInt(19, raceId);
-            } else {
-                stat.setInt(15, result);
-                stat.setFloat(16, time);
-                stat.setInt(17, raceId);
-            }
-            stat.executeUpdate();
-
-        } catch (final SQLException e) {
-            System.out.println("Failing sql " + sql + "[ " + trackId + ", " + date + ", " + raceNumber + ", " + lane + ", "
-                    + distance + ", " + result + ", " + time + ", " + timeModifier + ", " + shoes + "," + sulky + ", " + driverId
-                    + ", " + trainerId + ", " + horseId + ", " + raceId + "]");
-            throw new RuntimeException(e.getMessage(), e);
-        }
-    }
-
-    private int insertNewName(String table, String name, int travsportId) { // travsportId inte generell, behövs en
-        // bättre lösning
-        final String sql = "INSERT INTO " + table + " (name, travsportId) VALUES (?, ?)";
-        int last_id = -1;
-        try {
-            final PreparedStatement stat = getConnection().prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
-            stat.setString(1, name);
-            stat.setInt(2, travsportId);
-
-            stat.executeUpdate();
-            final ResultSet generatedId = stat.getGeneratedKeys();
-            while (generatedId.next()) {
-                last_id = generatedId.getInt(1);
-            }
-
-        } catch (final SQLException e) {
-            throw new RuntimeException(e.getMessage(), e);
-        }
-        return last_id;
-    }
-
-    private int getTrackIdFromShortcode(String shortcode) {
-        final String trackSql = "SELECT id FROM Track WHERE shortCode = ?";
-        int trackId = -1;
-        try {
-            final PreparedStatement stat = getConnection().prepareStatement(trackSql);
-            stat.setString(1, shortcode);
-
-            final ResultSet rs = stat.executeQuery();
-            while (rs.next()) {
-                trackId = rs.getInt("id");
-            }
-        } catch (final SQLException e) {
-            throw new RuntimeException(e.getMessage(), e);
-        }
-
-        return trackId;
-    }
-
-    public int getHorseId(String horseName, int travsportId) {
-        horseName = horseName.replaceAll("[^a-zåäöA-ZÅÄÖ0-9 ()\\.']", "");
-        final String horseSql = "SELECT id FROM Horse WHERE name = ? OR travsportId = ?";
-        int horseId = -1;
-        try {
-            final PreparedStatement stat = getConnection().prepareStatement(horseSql);
-            stat.setString(1, horseName);
-            stat.setInt(2, travsportId);
-
-            final ResultSet rs = stat.executeQuery();
-            while (rs.next()) {
-                horseId = rs.getInt("id");
-            }
-            if (horseId == -1 && !Strings.isNullOrEmpty(horseName)) {
-                horseId = insertNewName("Horse", horseName, travsportId);
-            }
-        } catch (final SQLException e) {
-            throw new RuntimeException(e.getMessage(), e);
-        }
-
-        return horseId;
-    }
-
-    public int getHorseTravsportId(String horseName) {
-        final String sql = "SELECT travsportId FROM Horse WHERE name = ?";
-        int id = -1;
-
-        try {
-            final PreparedStatement stat = getConnection().prepareStatement(sql);
-            stat.setString(1, horseName);
-
-            final ResultSet rs = stat.executeQuery();
-
-            while (rs.next()) {
-                id = rs.getInt("travsportId");
-            }
-        } catch (final SQLException e) {
-            throw new RuntimeException(e.getMessage(), e);
-        }
-
-        return id;
-    }
-
-    public int getDriverId(String driverName, int travsportId) {
-        driverName = driverName.replaceAll("[^a-zA-Z0-9 ]", "");
-        final String driverSql = "SELECT id FROM Driver WHERE name = ? OR travsportId = ?";
-        int driverId = -1;
-        try {
-            final PreparedStatement stat = getConnection().prepareStatement(driverSql);
-            stat.setString(1, driverName);
-            stat.setInt(2, travsportId);
-
-            final ResultSet rs = stat.executeQuery();
-            while (rs.next()) {
-                driverId = rs.getInt("id");
-            }
-            if (driverId == -1 && !Strings.isNullOrEmpty(driverName)) {
-                driverId = insertNewName("Driver", driverName, travsportId);
-            }
-        } catch (final SQLException e) {
-            throw new RuntimeException(e.getMessage(), e);
-        }
-
-        return driverId;
-    }
-
-    private int getTrainerId(String trainerName, int travsportId) {
-        trainerName = trainerName.replaceAll("[^a-zA-Z0-9 ]", "");
-        final String trainerSql = "SELECT id FROM Trainer WHERE name = ? OR travsportId = ?";
-        int trainerId = -1;
-        try {
-            final PreparedStatement stat = getConnection().prepareStatement(trainerSql);
-            stat.setString(1, trainerName);
-            stat.setInt(2, travsportId);
-
-            final ResultSet rs = stat.executeQuery();
-            while (rs.next()) {
-                trainerId = rs.getInt("id");
-            }
-            if (trainerId == -1 && !Strings.isNullOrEmpty(trainerName)) {
-                trainerId = insertNewName("Trainer", trainerName, travsportId);
-            }
-        } catch (final SQLException e) {
-            throw new RuntimeException(e.getMessage(), e);
-        }
-
-        return trainerId;
-    }
-
-    public void setHorseTravsportId(int horseId, String horseName) {
-        final String sql = "UPDATE Horse SET travsportId = ? WHERE name = ?";
-
-        try {
-            final PreparedStatement stat = getConnection().prepareStatement(sql);
-            stat.setInt(1, horseId);
-            stat.setString(2, horseName);
-
-            stat.executeUpdate();
-        } catch (final SQLException e) {
-            throw new RuntimeException(e.getMessage(), e);
-        }
-    }
-
-    // Lane stats SELECT Lane, Count(*) FROM `Results` WHERE Result = 1 AND
-    // TimeModifier NOT like "%a%" GROUP BY Lane ORDER BY `Results`.`Lane` ASC
-    // SELECT Lane, (Count(*) / SUM(COUNT(*)) OVER()) * 100 AS Percent, Distance
-    // FROM `Results` WHERE Result = 1 AND TimeModifier NOT like '%a%' AND Lane > 0
-    // AND Distance IN (2140,2160) GROUP BY Lane, Distance ORDER BY `Results`.`Lane`
-    // ASC
-
-    public List<LaneWinObject> getAutostartWinPercents(ArrayList<String> distance) {
-        final List<LaneWinObject> resultList = Lists.newArrayList();
-        final String sql
-                = "SELECT Lane, (Count(*) / SUM(COUNT(*)) OVER()) * 100 AS Percent, distance FROM `Results` WHERE Result = 1 AND TimeModifier like '%a%' AND Lane > 0 AND Distance IN (?) GROUP BY Lane, Distance ORDER BY `Results`.`Lane` ASC";
-        try {
-            final PreparedStatement stat = getConnection().prepareStatement(sql);
-            stat.setString(1, String.join(",", distance));
-            final ResultSet rs = stat.executeQuery();
-
-            while (rs.next()) {
-                resultList.add(new LaneWinObject(rs.getInt("Lane"), rs.getInt("distance"), rs.getFloat("Percent")));
-            }
-
-        } catch (final SQLException e) {
-            throw new RuntimeException(e.getMessage(), e);
-        }
-
-        return resultList;
-    }
-
-    public List<LaneWinObject> getAutostartWinPercents(List<Integer> distances) {
-        return getAutostartWinPercents(
-                Lists.newArrayList(distances.stream().map(d -> d.toString()).collect(Collectors.toList())));
-    }
-
-    public List<LaneWinObject> getVoltstartWinPercents(ArrayList<String> distance) {
-        final List<LaneWinObject> resultList = Lists.newArrayList();
-        String sql
-                = "SELECT Lane, (Count(*) / SUM(COUNT(*)) OVER()) * 100 AS Percent, distance FROM `Results` WHERE Result = 1 AND TimeModifier NOT like '%a%' AND Lane > 0 AND Distance IN (?) GROUP BY Lane, Distance ORDER BY `Results`.`Lane` ASC";
-        try {
-            final String in = distance.stream().collect(Collectors.joining(",", "(", ")"));
-            sql = sql.replace("(?)", in);
-            final PreparedStatement stat = getConnection().prepareStatement(sql);
-            final ResultSet rs = stat.executeQuery();
-
-            while (rs.next()) {
-                resultList.add(new LaneWinObject(rs.getInt("Lane"), rs.getInt("distance"), rs.getFloat("Percent")));
-            }
-
-        } catch (final SQLException e) {
-            throw new RuntimeException(e.getMessage(), e);
-        }
-
-        return resultList;
-    }
-
-    public List<LaneWinObject> getVoltstartWinPercents(List<Integer> distance) {
-        return getVoltstartWinPercents(Lists.newArrayList(distance.stream().map(m -> m.toString()).collect(Collectors.toList())));
-    }
-
-    public List<HorseRaceData> getRacesFromDate(final String date, final boolean shouldUpdate) {
-        final List<HorseRaceData> results = new ArrayList<>();
-
-        final String sql = "SELECT r1.*, driver.name as DriverName, horse.name as HorseName, track.name as TrackName "
-                + "FROM Results r1 " + "INNER JOIN Driver as driver ON driverId = driver.id "
-                + "INNER JOIN Horse as horse ON HorseId = horse.id " + "INNER JOIN Track as track ON TrackId = track.id "
-                + "WHERE r1.RaceDate = ? " + " GROUP BY r1.horseId "
-                + "ORDER BY r1.TrackId DESC, r1.RaceDate DESC, `r1`.`RaceNumber` ASC";
-
-        try {
-            final PreparedStatement stat = getConnection().prepareStatement(sql);
-
-            stat.setString(1, date);
-
-            final ResultSet rs = stat.executeQuery();
-            while (rs.next()) {
-                final HorseRaceData rd = new HorseRaceData();
-                rd.setDistance(rs.getInt("Distance"));
-                rd.setDriverId(rs.getInt("DriverId"));
-                rd.setDriverName(rs.getString("DriverName"));
-                rd.setHorseName(rs.getString("HorseName"));
-                rd.setHorseId(rs.getInt("HorseId"));
-                rd.setTrainerId(rs.getInt("TrainerId"));
-                rd.setRaceNumber(rs.getInt("RaceNumber"));
-                rd.setTrackName(rs.getString("TrackName"));
-                rd.setRaceDate(rs.getString("RaceDate"));
-                rd.setLane(rs.getInt("Lane"));
-                rd.setResult(rs.getInt("Result"));
-                rd.setTime(rs.getFloat("Time"));
-                rd.setTimeModifier(rs.getString("TimeModifier"));
-                rd.setShoes(rs.getInt("Shoes"));
-                rd.setSulky(rs.getInt("Sulky"));
-
-                if (shouldUpdate) {
-                    if (rd.getAvgDriverTimeCount() < 20) {
-                        System.out.println("Uppdating driver " + rd.getDriverName() + "(" + rd.getDriverId() + ") travsport id: "
-                                + getDriverTravsportId(rd.getDriverName()) + "because race count was "
-                                + rd.getAvgDriverTimeCount());
-                        TravsportParser.getInstance().getDriverStatById(getDriverTravsportId(rd.getDriverName()),
-                                rd.getDriverName(),
-                                rs.getInt("raceId"));
-                    }
-
-                    if (rd.getAvgHorseTimeCount() < 5) {
-                        System.out.println("Uppdating horse " + rd.getHorseName() + "( " + rd.getHorseId() + ") travsport id: "
-                                + getHorseTravsportId(rd.getHorseName()) + " because race count was "
-                                + rd.getAvgHorseTimeCount());
-                        TravsportParser.getInstance().getHorseStatByIdJson(getHorseTravsportId(rd.getHorseName()),
-                                rd.getHorseName(),
-                                "",
-                                rs.getInt("raceId"));
-                    }
-                }
-
-                results.add(rd);
-            }
-        } catch (final SQLException e) {
-            // TODO Auto-generated catch block
-            e.printStackTrace();
-        }
-
-        return results;
-    }
-
-    public List<HorseRaceData> getTodaysRaces(String type, String date, boolean shouldUpdate) {
-        final String sql;
-        Date date2 = new Date();
-        try {
-            date2 = MainController.DATE_FORMAT.parse(date);
-        } catch (final ParseException e1) {
-            throw new RuntimeException(e1.getMessage(), e1);
-        }
-        final Calendar c = Calendar.getInstance();
-        c.setTime(date2);
-        c.add(Calendar.YEAR, -2);
-
-        if (Strings.isNullOrEmpty(type)) {
-            sql = "SELECT r1.*, driver.name as DriverName, horse.name as HorseName, track.name as TrackName " + "FROM Results r1 "
-                    + "				INNER JOIN Driver as driver ON driverId = driver.id "
-                    + "				INNER JOIN Horse as horse ON HorseId = horse.id "
-                    + "				INNER JOIN Track as track ON TrackId = track.id " + " WHERE r1.RaceDate = ? "
-                    + " GROUP BY r1.horseId " + "ORDER BY r1.TrackId DESC, r1.RaceDate DESC, `r1`.`RaceNumber` ASC";
-        } else {
-            sql = "SELECT r1.*, driver.name as DriverName, horse.name as HorseName, track.name as TrackName " + "FROM Results r1 "
-                    + "				INNER JOIN Driver as driver ON driverId = driver.id "
-                    + "				INNER JOIN Horse as horse ON HorseId = horse.id "
-                    + "				INNER JOIN Track as track ON TrackId = track.id " + " WHERE r1.RaceDate = ? "
-                    + " AND r1.RaceType LIKE ? " + " GROUP BY r1.horseId " + "ORDER BY r1.TrackId DESC, `r1`.`RaceNumber` ASC";
-        }
-
-        final List<HorseRaceData> results = new ArrayList<>();
-        try {
-            final PreparedStatement stat = getConnection().prepareStatement(sql);
-            if (Strings.isNullOrEmpty(type)) {
-                stat.setString(1, date);
-            } else {
-                stat.setString(1, date);
-                stat.setString(2, "%" + type + "%");
-            }
-
-            final ResultSet rs = stat.executeQuery();
-            while (rs.next()) {
-                final HorseRaceData rd = new HorseRaceData();
-                rd.setDistance(rs.getInt("Distance"));
-                rd.setDriverId(rs.getInt("DriverId"));
-                rd.setDriverName(rs.getString("DriverName"));
-                rd.setHorseName(rs.getString("HorseName"));
-                rd.setHorseId(rs.getInt("HorseId"));
-                rd.setTrainerId(rs.getInt("TrainerId"));
-                rd.setRaceNumber(rs.getInt("RaceNumber"));
-                rd.setTrackName(rs.getString("TrackName"));
-                rd.setRaceDate(rs.getString("RaceDate"));
-                rd.setLane(rs.getInt("Lane"));
-                rd.setResult(rs.getInt("Result"));
-                rd.setTime(rs.getFloat("Time"));
-                rd.setTimeModifier(rs.getString("TimeModifier"));
-                rd.setShoes(rs.getInt("Shoes"));
-                rd.setSulky(rs.getInt("Sulky"));
-
-                rd.setAvgHorseTime(getAvgTime(rd.getHorseId(), rd.getRaceDate(), -1, false),
-                        getHorseRaceCount(rd.getHorseId(), 0));
-                rd.setAvgDriverTime(getAvgTime(rd.getDriverId(), rd.getRaceDate(), -1, true),
-                        getDriverRaceCount(rd.getDriverId(), 0));
-                rd.setAvgHorseTimeByDistance(getAvgTime(rd.getHorseId(), rd.getRaceDate(), rd.getDistance(), false),
-                        getHorseRaceCount(rd.getHorseId(), rd.getDistance()));
-                rd.setAvgDriverTimeByDistance(getAvgTime(rd.getDriverId(), rd.getRaceDate(), rd.getDistance(), true),
-                        getDriverRaceCount(rd.getDriverId(), rd.getDistance()));
-
-                if (shouldUpdate) {
-                    if (rd.getAvgDriverTimeCount() < 20) {
-                        System.out.println("Uppdating driver " + rd.getDriverName() + "(" + rd.getDriverId() + ") travsport id: "
-                                + getDriverTravsportId(rd.getDriverName()) + "because race count was "
-                                + rd.getAvgDriverTimeCount());
-                        TravsportParser.getInstance().getDriverStatById(getDriverTravsportId(rd.getDriverName()),
-                                rd.getDriverName(),
-                                rs.getInt("raceId"));
-                    }
-
-                    if (rd.getAvgHorseTimeCount() < 5) {
-                        System.out.println("Uppdating horse " + rd.getHorseName() + "( " + rd.getHorseId() + ") travsport id: "
-                                + getHorseTravsportId(rd.getHorseName()) + " because race count was "
-                                + rd.getAvgHorseTimeCount());
-                        TravsportParser.getInstance().getHorseStatByIdJson(getHorseTravsportId(rd.getHorseName()),
-                                rd.getHorseName(),
-                                "",
-                                rs.getInt("raceId"));
-                    }
-                }
-
-                results.add(rd);
-            }
-        } catch (final SQLException e) {
-            throw new RuntimeException(e.getMessage(), e);
-        }
-
-        return results;
-    }
-
-    private float getAvgTime(int id, String date, int distance, boolean isDriver) {
-
-        float returnValue = 0f;
-        final String who = isDriver ? "DriverId" : "HorseId";
-        String sql = "SELECT AVG(time) as avg FROM Results WHERE " + who + " = ? AND RaceDate < ? AND RaceDate < DATE(NOW())";
-
-        if (distance > 0) {
-            sql += " AND Distance BETWEEN ? AND ?";
-        }
-
-        sql += " AND time > 0 ORDER BY RaceDate DESC";
-
-        try {
-            final PreparedStatement stat = getConnection().prepareStatement(sql);
-
-            stat.setInt(1, id);
-            stat.setString(2, date);
-            if (distance > 0) {
-                stat.setInt(3, distance - 50);
-                stat.setInt(4, distance + 50);
-            }
-
-            final ResultSet rs = stat.executeQuery();
-
-            while (rs.next()) {
-                returnValue = rs.getFloat("avg");
-            }
-        } catch (final SQLException e) {
-            throw new RuntimeException(e.getMessage(), e);
-        }
-
-        return returnValue;
-    }
-
-    public float getAvarageTimeForTrack(int trackId, int distance, int id, boolean isDriver) {
-        final float returnValue = 0f;
-        String sql = "SELECT AVG(time) as avgTime FROM Results WHERE TrackId = ?";
-
-        if (isDriver) {
-            sql += " AND DriverId = ?";
-        } else {
-            sql += " AND HorseId = ?";
-        }
-
-        if (distance > 0) {
-            sql += " AND Distance BETWEEN ? AND ?";
-        }
-
-        try {
-            final PreparedStatement stat = getConnection().prepareStatement(sql);
-            stat.setInt(1, trackId);
-            stat.setInt(2, id);
-            if (distance > 0) {
-                stat.setInt(3, distance - 50);
-                stat.setInt(4, distance + 50);
-            }
-
-            final ResultSet rs = stat.executeQuery();
-
-            while (rs.next()) {
-                rs.getFloat("avgTime");
-            }
-        } catch (final SQLException e) {
-            throw new RuntimeException(e.getMessage(), e);
-        }
-
-        return returnValue;
-    }
-
-    private int getHorseRaceCount(int horseId, int distance) {
-        int returnValue = 0;
-        final String sql;
-        if (distance > 0) {
-            sql = "SELECT Count(*) as c FROM Results WHERE HorseId = ? AND Distance = ? AND Time > 0";
-        } else {
-            sql = "SELECT Count(*) as c FROM Results WHERE HorseId = ? AND Time > 0";
-        }
-        try {
-            final PreparedStatement stat = getConnection().prepareStatement(sql);
-            if (distance > 0) {
-                stat.setInt(1, horseId);
-                stat.setInt(2, distance);
-            } else {
-                stat.setInt(1, horseId);
-            }
-            final ResultSet rs = stat.executeQuery();
-            while (rs.next()) {
-                returnValue = rs.getInt("c");
-            }
-        } catch (final SQLException e) {
-            throw new RuntimeException(e.getMessage(), e);
-        }
-        return returnValue;
-    }
-
-    private int getDriverRaceCount(int driverId, int distance) {
-        int returnValue = 0;
-        final String sql;
-        if (distance > 0) {
-            sql = "SELECT Count(*) as c FROM Results WHERE DriverId = ? AND Distance = ? AND Time > 0";
-        } else {
-            sql = "SELECT Count(*) as c FROM Results WHERE DriverId = ? AND Time > 0";
-        }
-        try {
-            final PreparedStatement stat = getConnection().prepareStatement(sql);
-            if (distance > 0) {
-                stat.setInt(1, driverId);
-                stat.setInt(2, distance);
-            } else {
-                stat.setInt(1, driverId);
-            }
-            final ResultSet rs = stat.executeQuery();
-            while (rs.next()) {
-                returnValue = rs.getInt("c");
-            }
-        } catch (final SQLException e) {
-            throw new RuntimeException(e.getMessage(), e);
-        }
-        return returnValue;
-    }
-
-    // Hämta statistik för häst, förare, kombinationen av dessa två, distans....
-    public SimpleEntry<Integer, Integer> getNumHorseGallop(int horseId) {
-        final String sql
-                = "SELECT COUNT(*) as total, SUM(IF(TimeModifier LIKE '%g%', 1, 0)) as gallop FROM `Results` WHERE HorseId = ?";
-        SimpleEntry<Integer, Integer> returnValue = null;
-
-        try {
-            final PreparedStatement stat = getConnection().prepareStatement(sql);
-            stat.setInt(1, horseId);
-
-            final ResultSet rs = stat.executeQuery();
-            while (rs.next()) {
-                returnValue = new SimpleEntry<>(rs.getInt("total"), rs.getInt("gallop"));
-            }
-        } catch (final SQLException e) {
-            throw new RuntimeException(e.getMessage(), e);
-        }
-
-        return returnValue;
-    }
-
-    // Hämta statistik för häst, förare, kombinationen av dessa två, distans....
-    public SimpleEntry<Integer, Integer> getNumDriverGallop(int driverId) {
-        final String sql
-                = "SELECT COUNT(*) as total, SUM(IF(TimeModifier LIKE '%g%', 1, 0)) as gallop FROM `Results` WHERE DriverId = ?";
-        SimpleEntry<Integer, Integer> returnValue = null;
-
-        try {
-            final PreparedStatement stat = getConnection().prepareStatement(sql);
-            stat.setInt(1, driverId);
-
-            final ResultSet rs = stat.executeQuery();
-            while (rs.next()) {
-                returnValue = new SimpleEntry<>(rs.getInt("total"), rs.getInt("gallop"));
-            }
-        } catch (final SQLException e) {
-            throw new RuntimeException(e.getMessage(), e);
-        }
-
-        return returnValue;
-    }
-
-    public int getDriverTravsportId(String driverFirstName, String driverLastName) {
-        int returnValue = -1;
-        final String sql = "SELECT travsportId FROM Driver WHERE name = ?";
-        try {
-            final PreparedStatement stat = getConnection().prepareStatement(sql);
-            stat.setString(1, driverLastName + " " + driverFirstName);
-
-            final ResultSet rs = stat.executeQuery();
-
-            while (rs.next()) {
-                returnValue = rs.getInt("travsportId");
-            }
-        } catch (final SQLException e) {
-            throw new RuntimeException(e.getMessage(), e);
-        }
-        return returnValue;
-    }
-
-    public int getDriverTravsportId(String driverName) {
-        int returnValue = -1;
-        final String sql = "SELECT travsportId FROM Driver WHERE name = ?";
-        try {
-            final PreparedStatement stat = getConnection().prepareStatement(sql);
-            stat.setString(1, driverName);
-
-            final ResultSet rs = stat.executeQuery();
-
-            while (rs.next()) {
-                returnValue = rs.getInt("travsportId");
-            }
-        } catch (final SQLException e) {
-            throw new RuntimeException(e.getMessage(), e);
-        }
-        return returnValue;
-    }
-
-    public void setDriverTravsportId(int driverId, String firstName, String lastName) {
-        final String sql = "UPDATE Driver SET travsportId = ? WHERE name = ?";
-        try {
-            final PreparedStatement stat = getConnection().prepareStatement(sql);
-            stat.setInt(1, driverId);
-            stat.setString(2, lastName + " " + firstName);
-
-            stat.executeUpdate();
-        } catch (final SQLException e) {
-            throw new RuntimeException(e.getMessage(), e);
-        }
-    }
-
-    public float getTrendLast5(HorseRaceData horseRaceData) {
-        final String combinedTrendSql
-                = "SELECT Time, (SELECT AVG(Time) FROM Results WHERE HorseId = ? AND DriverId = ? AND Distance = ?) as avgTime FROM Results WHERE HorseId = ? AND DriverId = ? AND Distance = ? AND Time > -1 ORDER BY RaceDate ASC limit 5";
-        final String DriverTrendSql
-                = "SELECT Time, (SELECT AVG(Time) FROM Results WHERE DriverId = ? AND Distance = ?) as avgTime FROM Results WHERE DriverId = ? AND Distance = ? AND Time > -1 ORDER BY RaceDate ASC limit 5";
-        final String horseTrendSql
-                = "SELECT Time, (SELECT AVG(Time) FROM Results WHERE HorseId = ? AND Distance = ?) as avgTime FROM Results WHERE HorseId = ? AND Distance = ? AND Time > -1  ORDER BY RaceDate ASC limit 5";
-
-        final int horseId = horseRaceData.getHorseId();
-        final int driverId = horseRaceData.getDriverId();
-        final int distance = horseRaceData.getDistance();
-
-        float avgHorseTime = -1f;
-        float avgDriverTime = -1f;
-        float avgCombinedTime = -1f;
-        float startHorseAvgTime = -1;
-        float startDriverAvgTime = -1;
-        float startCombinedAvgTime = -1;
-        try {
-            final PreparedStatement horseStat = getConnection()
-                    .prepareStatement(horseTrendSql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
-            horseStat.setInt(1, horseId);
-            horseStat.setInt(2, distance);
-            horseStat.setInt(3, horseId);
-            horseStat.setInt(4, distance);
-
-            final ResultSet horseRs = horseStat.executeQuery();
-            if (horseRs.next()) {
-                startHorseAvgTime = horseRs.getFloat("avgTime");
-                ;
-                horseRs.beforeFirst();
-                avgHorseTime = getTrendAvgTime(horseRs);
-                // This should be the return value for horse
-                System.out.println("Horse trend is " + (avgHorseTime - startHorseAvgTime));
-            } else {
-                System.out.println("No Horse trend found");
-            }
-
-            horseRs.close();
-            horseStat.close();
-
-            final PreparedStatement driverStat
-                    = conn.prepareStatement(DriverTrendSql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
-            driverStat.setInt(1, driverId);
-            driverStat.setInt(2, distance);
-            driverStat.setInt(3, driverId);
-            driverStat.setInt(4, distance);
-            final ResultSet driverRs = driverStat.executeQuery();
-
-            if (driverRs.next()) {
-                startDriverAvgTime = driverRs.getFloat("avgTime");
-                ;
-                driverRs.beforeFirst();
-                avgDriverTime = getTrendAvgTime(driverRs);
-                System.out.println("Driver trend is " + (avgDriverTime - startDriverAvgTime));
-            } else {
-                System.out.println("No driver trend found");
-            }
-
-            final PreparedStatement combinedStat
-                    = conn.prepareStatement(combinedTrendSql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
-
-            combinedStat.setInt(1, horseId);
-            combinedStat.setInt(2, driverId);
-            combinedStat.setInt(3, distance);
-            combinedStat.setInt(4, horseId);
-            combinedStat.setInt(5, driverId);
-            combinedStat.setInt(6, distance);
-            final ResultSet combinedRs = combinedStat.executeQuery();
-
-            if (combinedRs.next()) {
-                startCombinedAvgTime = combinedRs.getFloat("avgTime");
-                ;
-                combinedRs.beforeFirst();
-                avgCombinedTime = getTrendAvgTime(combinedRs);
-                System.out.println("Combined trend is " + (avgCombinedTime - startCombinedAvgTime));
-            } else {
-                System.out.println("No combined trend available");
-            }
-
-            if (avgHorseTime > -1 && avgDriverTime > -1) {
-                System.out.println("Combination of horse and driver: "
-                        + ((avgHorseTime - startHorseAvgTime) + (avgDriverTime - startDriverAvgTime)));
-            }
-            System.out.println("------");
-
-        } catch (final SQLException e) {
-            throw new RuntimeException(e.getMessage(), e);
-        }
-
-        return ((avgHorseTime - startHorseAvgTime) + (avgDriverTime - startDriverAvgTime)) / 2f;
-    }
-
-    private float getTrendAvgTime(final ResultSet rs) throws SQLException {
-        float returnValue = 0.0f;
-        while (rs.next()) {
-            if (returnValue == 0.0f) {
-                returnValue = rs.getFloat("avgTime");
-            }
-
-            if (returnValue == 0f) {
-                returnValue = rs.getFloat("Time");
-            }
-            final float diff = -(returnValue - rs.getFloat("Time"));
-            returnValue = returnValue + diff;
-        }
-        return returnValue;
-    }
-
-    public void updateResult(String horseName, String driverName, int result, String timeModifier, float timeValue, String date,
-            String type) {
-        final String sql = "UPDATE Results " + "SET " + "Result = ?, Time = ?, TimeModifier = ?" + "WHERE "
-                + "HorseId = (SELECT id FROM Horse WHERE name = ?) AND " + "DriverId = (SELECT id FROM Driver WHERE name = ?) AND"
-                + "RaceDate = ?";
-        try {
-            final PreparedStatement stat = getConnection().prepareStatement(sql);
-            stat.setInt(1, result);
-            stat.setFloat(2, timeValue);
-            stat.setString(3, timeModifier);
-            stat.setString(4, horseName);
-            stat.setString(5, driverName);
-            stat.setString(6, date);
-
-            final int res = stat.executeUpdate();
-
-            if (res != 1) {
-                System.out.println(
-                        "Updated " + res + " results for horse " + horseName + " and driver " + driverName + " at date " + date);
-            }
-
-        } catch (final SQLException e) {
-            throw new RuntimeException(e.getMessage(), e);
-        }
-
-    }
-
-    public String getTrackShortCodeByName(String trackName) {
-        final String sql = "SELECT shortcode FROM Track WHERE name = ?";
-        String trackcode = null;
-        try {
-            final PreparedStatement stat = getConnection().prepareStatement(sql);
-            stat.setString(1, trackName);
-
-            final ResultSet rs = stat.executeQuery();
-            while (rs.next()) {
-                trackcode = rs.getString("shortcode");
-            }
-        } catch (final SQLException e) {
-            throw new RuntimeException(e.getMessage(), e);
-        }
-        return trackcode;
-    }
-
-    public int getRaceCount(String what, int id) {
-        int returnValue = 0;
-        final String sql;
-        if (what.equals("Horse")) {
-            sql = "SELECT Count(*) as count FROM Results WHERE HorseId = ?";
-        } else if (what.equals("Driver")) {
-            sql = "SELECT Count(*) as count FROM Results WHERE DriverId = ?";
-        } else {
-            sql = "";
-        }
-
-        if (!Strings.isNullOrEmpty(sql)) {
-            try {
-                final PreparedStatement stat = getConnection().prepareStatement(sql);
-                stat.setInt(1, id);
-
-                final ResultSet rs = stat.executeQuery();
-                while (rs.next()) {
-                    returnValue = rs.getInt("count");
-                }
-
-            } catch (final SQLException e) {
-                throw new RuntimeException(e.getMessage(), e);
-            }
-        }
-        return returnValue;
-    }
-
-    public int getRaceId() {
-        final String sql
-                = "SELECT raceId FROM Results where raceId > -1 AND RaceDate < DATE(NOW()) ORDER BY RaceDate ASC LIMIT 1";
-        int returnValue = -1;
-        try {
-            final PreparedStatement stat = getConnection().prepareStatement(sql);
-            final ResultSet rs = stat.executeQuery();
-            while (rs.next()) {
-                returnValue = rs.getInt("raceId");
-            }
-        } catch (final SQLException e) {
-            throw new RuntimeException(e.getMessage(), e);
-        }
-
-        return returnValue;
-
-    }
-
-    public List<UpdateRaceRow> getRacesToUpdate(String date) {
-        final List<UpdateRaceRow> racesToUpdate = Lists.newArrayList();
-        final String sql
-                = "SELECT r.*, t.name as TrackName, t.id as TrackId FROM Results r INNER JOIN Track t ON r.trackId = t.id WHERE r.RaceDate = ? GROUP BY r.RaceDate, t.name, r.RaceNumber";
-
-        try {
-            final PreparedStatement stat = getConnection().prepareStatement(sql);
-            stat.setString(1, date);
-
-            final ResultSet rs = stat.executeQuery();
-
-            while (rs.next()) {
-                racesToUpdate.add(new UpdateRaceRow(rs.getInt("id"), rs.getString("RaceDate"), rs.getString("RaceType"),
-                        rs.getString("TimeModifier").contains("a"), rs.getInt("RaceNumber"), rs.getString("TrackName"),
-                        rs.getInt("TrackId")));
-            }
-        } catch (final SQLException e) {
-            throw new RuntimeException(e.getMessage(), e);
-        }
-
-        return racesToUpdate;
-
-    }
-
-    public void updateRaceInfo(int raceId, boolean isAutostart, String raceType, int raceNumber, String date, int trackId) {
-        final String sql = "UPDATE Results SET RaceType = ? WHERE raceId = ? AND RaceNumber = ? AND trackId = ? AND RaceDate = ?";
-        final String updateTimeModifier;
-        if (isAutostart) {
-            updateTimeModifier = "UPDATE `Results` SET TimeModifier = " + "IF(TimeModifier LIKE '%a%', " + "TimeModifier, "
-                    + "CONCAT(TimeModifier, 'a')) " + "WHERE RaceDate = ? AND RaceNumber = ? AND TrackId = ?";
-        } else {
-            updateTimeModifier = "UPDATE `Results` SET TimeModifier = " + "REPLACE(TimeModifier, 'a', '') "
-                    + "WHERE RaceDate = ? AND RaceNumber = ? AND TrackId = ?";
-        }
-
-        try {
-            PreparedStatement stat = getConnection().prepareStatement(sql);
-            stat.setString(1, raceType);
-            stat.setInt(2, raceId);
-            stat.setInt(3, raceNumber);
-            stat.setInt(4, trackId);
-            stat.setString(5, date);
-
-            stat.executeUpdate();
-
-            stat = getConnection().prepareStatement(updateTimeModifier);
-            stat.setString(1, date);
-            stat.setInt(2, raceNumber);
-            stat.setInt(3, trackId);
-
-            stat.executeUpdate();
-
-        } catch (final SQLException e) {
-            throw new RuntimeException(e.getMessage(), e);
-        }
-
-    }
-
-    public void updateFromRaceResults(int raceId, int result, float time, String timeModifier, int lane, int distance,
-            int horseTravsportId, int driverTravsportId, String raceDate, int raceNumber) {
-        final int horseId = getHorseId("", horseTravsportId);
-        final int driverId = getDriverId("", driverTravsportId);
-        final String sql
-                = "UPDATE Results SET Result = ?, Time = ?, TimeModifier = ?, DriverId = ?, raceId = -1 WHERE RaceDate = ? AND RaceId = ? AND RaceNumber = ? AND HorseId = ?";
-        if (horseId == -1 || driverId == -1) {
-            System.out.println("NOT UPDATING horseId " + horseId + " driver Id: " + driverId);
-            return;
-        }
-        try {
-
-            final PreparedStatement stat = getConnection().prepareStatement(sql);
-            stat.setInt(1, result);
-            stat.setFloat(2, time);
-            stat.setString(3, timeModifier);
-            stat.setInt(4, driverId);
-            stat.setString(5, raceDate);
-            stat.setInt(6, raceId);
-            stat.setInt(7, raceNumber);
-            stat.setInt(8, horseId);
-            // stat.setInt(7, lane);
-            // stat.setInt(8, distance);
-
-            stat.executeUpdate();
-
-        } catch (final SQLException e) {
-            throw new RuntimeException(e.getMessage(), e);
-        }
-
-    }
-
-    public void removeRaceIds(int raceId) {
-        final String sql = "UPDATE Results SET raceId = -1 WHERE RaceId = ?";
-        try {
-            final PreparedStatement statement = getConnection().prepareStatement(sql);
-            statement.setInt(1, raceId);
-
-            statement.executeUpdate();
-        } catch (final SQLException e) {
-            throw new RuntimeException(e.getMessage(), e);
-        }
-
-    }
-
-    public void setSetting(String name, String value) {
-        final String sql = "INSERT INTO Settings (name, value) VALUES (?, ?) ON DUPLICATE KEY UPDATE value = ?";
-        try {
-            final PreparedStatement stat = getConnection().prepareStatement(sql);
-            stat.setString(1, name);
-            stat.setString(2, value);
-            stat.setString(3, value);
-
-            stat.execute();
-        } catch (final SQLException e) {
-            throw new RuntimeException(e.getMessage(), e);
-        }
-    }
-
-    public String getSetting(String name) {
-        final String sql = "SELECT value FROM Settings WHERE name = ?";
-
-        String returnValue = "";
-        try {
-            final PreparedStatement stat = getConnection().prepareStatement(sql);
-            stat.setString(1, name);
-
-            final ResultSet rs = stat.executeQuery();
-            while (rs.next()) {
-                returnValue = rs.getString("value");
-            }
-        } catch (final SQLException e) {
-            throw new RuntimeException(e.getMessage(), e);
-        }
-
-        return returnValue;
-    }
-
-    public String getDriverLastRace(int driverId, int raceNumber) {
-        final String sql
-                = "SELECT RaceDate FROM Results WHERE (RaceDate < ? || (RaceDate = ? AND RaceNumber < ?)) AND DriverId = ? ORDER BY RaceDate DESC limit 1";
-        String lastRaceDate = "";
-        try {
-            final PreparedStatement stat = getConnection().prepareStatement(sql);
-            final String currentDate = MainController.DATE_FORMAT.format(new Date());
-            stat.setString(1, currentDate);
-            stat.setString(2, currentDate);
-            stat.setInt(3, raceNumber);
-            stat.setInt(4, driverId);
-
-            final ResultSet rs = stat.executeQuery();
-            while (rs.next()) {
-                lastRaceDate = rs.getString("RaceDate");
-            }
-        } catch (final SQLException e) {
-            throw new RuntimeException(e.getMessage(), e);
-        }
-
-        return lastRaceDate;
-    }
-
-    public float getAvgTimeByDriverAndDistance(int driverId, int distance, String date, int raceNumber) {
-        float returnValue = 0f;
-
-        // Get driver last raceDate
-        final String lastRaceDate = getDriverLastRace(driverId, raceNumber);
-
-        final LocalDate lastDate = LocalDate.parse(lastRaceDate);
-        final LocalDate parsedDate = LocalDate.parse(date);
-
-        final Long days = Duration.between(lastDate.atStartOfDay(), parsedDate.atStartOfDay()).toDays();
-
-        final String sql
-                = "SELECT currentDate.RaceDate as date, prevDate.RaceDate AS prev_date, DATEDIFF(currentDate.RaceDate, prevDate.RaceDate) as diff, "
-                        + "ROUND(AVG(currentDate.Time),2) as avgTime, COUNT(*), ROUND(AVG(currentDate.adjTime),2) as adjAvgTime "
-                        + "FROM " + "(SELECT (@row_number:=@row_number + 1) as RID, "
-                        + "IF (Time = -1, (SELECT MIN(Time) FROM (SELECT Time FROM Results WHERE TimeModifier NOT LIKE '%g%' ORDER BY Time DESC limit 5) abc), time) as adjTime, "
-                        + "Results.* FROM Results, "
-                        + "(SELECT @row_number:=0) as t WHERE DriverId = ? AND distance = ? AND RaceDate <= ? "
-                        + "ORDER BY RaceDate DESC ) AS currentDate "
-                        + "INNER JOIN (SELECT (@row_number2 := @row_number2 + 1) AS RID, RaceDate "
-                        + "FROM Results, (SELECT @row_number2:=0) AS t "
-                        + "WHERE DriverId = ? AND distance = ? AND RaceDate <= ? "
-                        + "ORDER BY RaceDate DESC LIMIT 99999 OFFSET 1) AS prevDate ON currentDate.RID = prevDate.RID "
-                        + "GROUP BY diff ORDER BY DIFF";
-
-        try {
-            final PreparedStatement stat = getConnection().prepareStatement(sql);
-            stat.setInt(1, driverId);
-            stat.setInt(2, distance);
-            stat.setString(3, lastRaceDate);
-            stat.setInt(4, driverId);
-            stat.setInt(5, distance);
-            stat.setString(6, lastRaceDate);
-
-            final ResultSet rs = stat.executeQuery();
-
-            while (rs.next()) {
-                if (rs.getInt("diff") == days) {
-                    returnValue = rs.getFloat("adjAvgTime");
-                    break;
-                }
-            }
-
-        } catch (final SQLException e) {
-            System.out.println("ERROR IN SQL " + sql + " \ndate " + lastRaceDate);
-            throw new RuntimeException(e.getMessage(), e);
-        }
-
-        return returnValue;
-    }
-
-    public void getTestDataToFile() {
-        final String sql = "SELECT * FROM Results WHERE RaceDate < ? AND RaceDate > ? ORDER BY RaceDate DESC";
-
-        final String delimiter = ";";
-        final String currentDate = MainController.DATE_FORMAT.format(new Date());
-
-        final File file = new File(System.getProperty("user.dir") + File.separator + "src/test/testFiles.csv");
-        try (final BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
-            final PreparedStatement stat
-                    = getConnection().prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
-            stat.setString(1, currentDate);
-            stat.setString(2, "2015-01-01");
-
-            final ResultSet rs = stat.executeQuery();
-
-            rs.last();
-            final int lastRow = rs.getRow();
-            rs.beforeFirst();
-
-            int i = 1;
-            while (rs.next()) {
-                final Result result = new Result(rs.getInt(1), rs.getInt(2), rs.getString(3), rs.getString(4), rs.getInt(5),
-                        rs.getInt(6), rs.getInt(7), rs.getInt(8), rs.getFloat(9), rs.getString(10), rs.getInt(11), rs.getInt(12),
-                        rs.getInt(13), rs.getInt(14), rs.getInt(15), rs.getInt(16));
-
-                final float avgHorseTime = getAvgTime(result.getHorseId(), result.getRaceDate(), -1, false);
-                final float avgHorseTimeDistance
-                        = getAvgTime(result.getHorseId(), result.getRaceDate(), result.getDistance(), false);
-                final float avgDriverTime = getAvgTime(result.getDriverId(), result.getRaceDate(), -1, true);
-                final float avgDriverTimeDistance
-                        = getAvgTime(result.getDriverId(), result.getRaceDate(), result.getDistance(), true);
-
-                writer.append(result.resultToFileString() + ";" + avgHorseTime + ";" + avgHorseTimeDistance + ";" + avgDriverTime
-                        + ";" + avgDriverTimeDistance + System.lineSeparator());
-
-                if (i % 1000 == 0) {
-                    System.out.println(LocalTime.now() + " Done with " + i++ + " of " + lastRow);
-                }
-            }
-
-        } catch (final SQLException | IOException e) {
-            throw new RuntimeException(e.getMessage(), e);
-        }
-
-    }
-
-    public int getLastRaceDaysHorse(int horseId, String raceDate, int raceNumber) {
-        int returnValue = 999;
-        final String sql = "SELECT DATEDIFF(?, startDate.RaceDate) as days, startDate.RaceDate, nextDate.RaceDate, RaceNumber "
-                + "FROM (SELECT (@row_number := @row_number + 1) AS orderNum, RaceDate, RaceNumber "
-                + "FROM Results, (SELECT @row_number:=0) AS t WHERE RaceDate <= ? AND HorseId = ? "
-                + "ORDER BY RaceDate DESC, RaceNumber DESC) AS startDate " + "INNER JOIN "
-                + "(SELECT (@row_number2 := @row_number2 + 1) AS orderNum, RaceDate "
-                + "FROM Results, (SELECT @row_number2 := 0) AS t WHERE RaceDate <= ? AND HorseId = ? "
-                + "ORDER BY RaceDate DESC, RaceNumber DESC " + "LIMIT 11 "
-                + "OFFSET 1) AS nextDate ON nextDate.orderNum = startDate.orderNum";
-        try {
-            final PreparedStatement stat = getConnection().prepareStatement(sql);
-
-            stat.setString(1, raceDate);
-            stat.setString(2, raceDate);
-            stat.setInt(3, horseId);
-            stat.setString(4, raceDate);
-            stat.setInt(5, horseId);
-            final ResultSet rs = stat.executeQuery();
-
-            boolean getNext = false;
-            while (rs.next()) {
-                if (getNext) {
-                    returnValue = rs.getInt("days");
-                    break;
-                }
-                if (rs.getString("RaceDate").equals(raceDate) && rs.getInt("RaceNumber") == raceNumber) {
-                    getNext = true;
-                }
-            }
-        } catch (final SQLException e) {
-            // TODO Auto-generated catch block
-            e.printStackTrace();
-        }
-        return returnValue;
-    }
-
-    public int getLastRaceDaysDriver(int driverId, String raceDate, int raceNumber) {
-        int returnValue = 999;
-
-        final String sql = "SELECT DATEDIFF(?, startDate.RaceDate) as days, startDate.RaceDate, nextDate.RaceDate, RaceNumber "
-                + "FROM (SELECT (@row_number := @row_number + 1) AS orderNum, RaceDate, RaceNumber "
-                + "FROM Results, (SELECT @row_number:=0) AS t WHERE RaceDate <= ? AND DriverId = ? "
-                + "ORDER BY RaceDate DESC, RaceNumber DESC) AS startDate " + "INNER JOIN "
-                + "(SELECT (@row_number2 := @row_number2 + 1) AS orderNum, RaceDate "
-                + "FROM Results, (SELECT @row_number2 := 0) AS t WHERE RaceDate <= ? AND DriverId = ? "
-                + "ORDER BY RaceDate DESC, RaceNumber DESC " + "LIMIT 11 "
-                + "OFFSET 1) AS nextDate ON nextDate.orderNum = startDate.orderNum";
-
-        try {
-            final CallableStatement stat = getConnection().prepareCall(sql);
-
-            stat.setString(1, raceDate);
-            stat.setString(2, raceDate);
-            stat.setInt(3, driverId);
-            stat.setString(4, raceDate);
-            stat.setInt(5, driverId);
-
-            final ResultSet rs = stat.executeQuery();
-
-            boolean getNext = false;
-            while (rs.next()) {
-                if (getNext) {
-                    returnValue = rs.getInt("days");
-                    break;
-                }
-                if (rs.getString("RaceDate").equals(raceDate) && rs.getInt("RaceNumber") == raceNumber) {
-                    getNext = true;
-                }
-            }
-        } catch (final SQLException e) {
-            // TODO Auto-generated catch block
-            e.printStackTrace();
-        }
-        return returnValue;
-    }
-
-    public int getLastRaceDaysBoth(int horseId, int driverId, String raceDate, int raceNumber) {
-        int returnValue = 999;
-
-        final String sql = "SELECT DATEDIFF(?, startDate.RaceDate) as days, startDate.RaceDate, nextDate.RaceDate, RaceNumber "
-                + "FROM (SELECT (@row_number := @row_number + 1) AS orderNum, RaceDate, RaceNumber "
-                + "FROM Results, (SELECT @row_number:=0) AS t WHERE RaceDate <= ? AND DriverId = ? AND HorseId = ? "
-                + "ORDER BY RaceDate DESC, RaceNumber DESC) AS startDate " + "INNER JOIN "
-                + "(SELECT (@row_number2 := @row_number2 + 1) AS orderNum, RaceDate "
-                + "FROM Results, (SELECT @row_number2 := 0) AS t WHERE RaceDate <= ? AND DriverId = ? AND HorseId = ? "
-                + "ORDER BY RaceDate DESC, RaceNumber DESC " + "LIMIT 11 "
-                + "OFFSET 1) AS nextDate ON nextDate.orderNum = startDate.orderNum";
-
-        try {
-            final PreparedStatement stat = getConnection().prepareStatement(sql);
-
-            stat.setString(1, raceDate);
-            stat.setString(2, raceDate);
-            stat.setInt(3, driverId);
-            stat.setInt(4, horseId);
-            stat.setString(5, raceDate);
-            stat.setInt(6, driverId);
-            stat.setInt(7, horseId);
-
-            final ResultSet rs = stat.executeQuery();
-
-            boolean getNext = false;
-            while (rs.next()) {
-                if (getNext) {
-                    returnValue = rs.getInt("days");
-                    break;
-                }
-                if (rs.getString("RaceDate").equals(raceDate) && rs.getInt("RaceNumber") == raceNumber) {
-                    getNext = true;
-                }
-            }
-        } catch (final SQLException e) {
-            // TODO Auto-generated catch block
-            e.printStackTrace();
-        }
-        return returnValue;
-    }
-
-    public ArrayList<DaysSinceLastRace> getDriverDaysSinceLastRaceStats(int driverId) {
-        final ArrayList<DaysSinceLastRace> daysStats = Lists.newArrayList();
-        final String sql
-                = "SELECT DATEDIFF(startDate.RaceDate, prevDate.RaceDate) as days, count(*) as count, SUM(if (startDate.result = 1,1,0)) as wins, SUM(if (startDate.result = 1,1,0)) / count(*) as percent "
-                        + "FROM (SELECT (@row_number := @row_number + 1) AS orderNum, RaceDate, Result, RaceNumber "
-                        + "FROM Results, (SELECT @row_number:=0) AS t " + "WHERE DriverId = ? "
-                        + "ORDER BY RaceDate DESC, RaceNumber ASC) as startDate " + "INNER JOIN "
-                        + "(SELECT (@row_number2 := @row_number2 + 1) AS orderNum, RaceDate "
-                        + "FROM Results, (SELECT @row_number2 := 0) AS t  " + "WHERE DriverId = ? "
-                        + "ORDER BY RaceDate DESC, RaceNumber ASC " + "LIMIT 100000 "
-                        + "OFFSET 1) AS prevDate ON startDate.orderNum = prevDate.orderNum GROUP BY days HAVING days <= 100 ORDER BY days ASC";
-
-        try {
-            final PreparedStatement stat = getConnection().prepareStatement(sql);
-
-            stat.setInt(1, driverId);
-            stat.setInt(2, driverId);
-
-            final ResultSet rs = stat.executeQuery();
-
-            while (rs.next()) {
-                daysStats.add(
-                        new DaysSinceLastRace(rs.getInt("days"), rs.getInt("count"), rs.getInt("wins"), rs.getFloat("percent")));
-            }
-
-        } catch (final SQLException e) {
-            e.printStackTrace();
-            throw new RuntimeException();
-        }
-
-        return daysStats;
-    }
-
-    public DaysSinceLastRace getDriverDaysSinceLastRaceStat(int driverId, int daysSinceLast) {
-        DaysSinceLastRace dayStat = null;
-        final String sql
-                = "SELECT DATEDIFF(startDate.RaceDate, prevDate.RaceDate) as days, count(*) as count, SUM(if (startDate.result = 1,1,0)) as wins, SUM(if (startDate.result = 1,1,0)) / count(*) as percent "
-                        + "FROM (SELECT (@row_number := @row_number + 1) AS orderNum, RaceDate, Result, RaceNumber "
-                        + "FROM Results, (SELECT @row_number:=0) AS t " + "WHERE DriverId = ? "
-                        + "ORDER BY RaceDate DESC, RaceNumber ASC) as startDate " + "INNER JOIN "
-                        + "(SELECT (@row_number2 := @row_number2 + 1) AS orderNum, RaceDate "
-                        + "FROM Results, (SELECT @row_number2 := 0) AS t  " + "WHERE DriverId = ? "
-                        + "ORDER BY RaceDate DESC, RaceNumber ASC " + "LIMIT 100000 "
-                        + "OFFSET 1) AS prevDate ON startDate.orderNum = prevDate.orderNum WHERE DATEDIFF(startDate.RaceDate, prevDate.RaceDate) = ?";
-
-        try {
-            final PreparedStatement stat = getConnection().prepareStatement(sql);
-
-            stat.setInt(1, driverId);
-            stat.setInt(2, driverId);
-            stat.setInt(3, daysSinceLast);
-
-            final ResultSet rs = stat.executeQuery();
-
-            while (rs.next()) {
-                dayStat = new DaysSinceLastRace(rs.getInt("days"), rs.getInt("count"), rs.getInt("wins"), rs.getFloat("percent"));
-            }
-
-        } catch (final SQLException e) {
-            e.printStackTrace();
-            throw new RuntimeException();
-        }
-
-        return dayStat;
-    }
-
-    public ArrayList<Integer> getDriverIds() {
-        final String sql = "SELECT DISTINCT(DriverId) as id FROM Results WHERE RaceDate > DATE_SUB(RaceDate, INTERVAL 6 MONTH)";
-        final ArrayList<Integer> driverIds = Lists.newArrayList();
-        try {
-            final PreparedStatement stat = getConnection().prepareStatement(sql);
-            final ResultSet rs = stat.executeQuery();
-
-            while (rs.next()) {
-                driverIds.add(rs.getInt("id"));
-            }
-
-        } catch (final SQLException e) {
-            // TODO Auto-generated catch block
-            e.printStackTrace();
-        }
-        return driverIds;
-    }
-
-    public String getLastResults(int id, int id2, String raceDate, int raceNumber, int limit, String type) {
-        String returnValue = "";
-        final String typeString;
-        if (type.equals("Horse")) {
-            typeString = "HorseId = ? AND ";
-        } else if (type.equals("Driver")) {
-            typeString = "DriverId = ? AND ";
-        } else if (type.equals("Both")) {
-            typeString = "DriverId = ? AND HorseId = ? AND ";
-        } else {
-            typeString = "";
-        }
-        final String sql = "SELECT AVG(IF (Result <= 0, 8, result)) as avg, GROUP_CONCAT(Result) as list FROM "
-                + "(SELECT result FROM Results " + "WHERE " + typeString + "RaceDate < ? " + "AND RaceDate < DATE(NOW()) "
-                + "ORDER BY RaceDate DESC, RaceNumber DESC " + "LIMIT ?) as t";
-
-        try {
-            final PreparedStatement stat = getConnection().prepareStatement(sql);
-            if (type.equals("Both")) {
-                stat.setInt(1, id);
-                stat.setInt(2, id2);
-                stat.setString(3, raceDate);
-                stat.setInt(4, limit);
-            } else {
-                stat.setInt(1, id);
-                stat.setString(2, raceDate);
-                stat.setInt(3, limit);
-            }
-            final ResultSet rs = stat.executeQuery();
-            while (rs.next()) {
-                float avg = rs.getFloat("avg");
-                final String dbList = rs.getString("list");
-                final ArrayList<String> list;
-                if (dbList == null) {
-                    list = new ArrayList<>();
-                } else {
-                    list = Lists.newArrayList(dbList.split(","));
-                }
-                if (list.size() < limit) {
-                    int newAvg = 0;
-                    for (final String res : list) {
-                        Integer resVal = Integer.valueOf(res);
-                        if (resVal <= 0) {
-                            resVal = 8;
-                        }
-                        newAvg += resVal;
-                    }
-                    for (int i = list.size(); i < limit; i++) {
-                        newAvg += 8;
-                    }
-                    avg = newAvg / (float) limit;
-                }
-                returnValue = String.valueOf(avg) + " (" + dbList + ")";
-            }
-
-        } catch (final SQLException e) {
-            e.printStackTrace();
-            throw new RuntimeException();
-        }
-        return returnValue;
-    }
-
-    public List<SimpleEntry<Integer, Float>> getTrackAvarages(String trackName, ArrayList<Integer> distances, String date, int id,
-            boolean isDriver) {
-        final List<SimpleEntry<Integer, Float>> res = Lists.newArrayList();
-        String typeString;
-        if (id > 0) {
-            if (isDriver) {
-                typeString = "AND DriverId = ? ";
-            } else {
-                typeString = "AND HorseId = ? ";
-            }
-        } else {
-            typeString = "";
-        }
-
-        String trackFilter;
-        if (Strings.isNullOrEmpty(trackName)) {
-            trackFilter = "";
-        } else {
-            trackFilter = "AND TrackId = (SELECT id FROM Track WHERE name = ?) ";
-        }
-
-        final String sql = "SELECT Lane, AVG(IF(Time <= 0,30,time)) as avg FROM Results " + "WHERE distance IN (?) " + trackFilter
-                + typeString + "AND RaceDate < ? " + "GROUP BY Lane " + "ORDER BY Lane ASC";
-
-        try {
-            final PreparedStatement stat = getConnection().prepareStatement(sql);
-            final String in = String.join(",", distances.stream().map(m -> m.toString()).collect(Collectors.toList()));
-            stat.setString(1, in);
-            if (Strings.isNullOrEmpty(trackName)) {
-                if (id > 0) {
-                    stat.setInt(2, id);
-                    stat.setString(3, date);
-                } else {
-                    stat.setString(2, date);
-                }
-
-            } else {
-                stat.setString(2, trackName);
-                if (id > 0) {
-                    stat.setInt(3, id);
-                    stat.setString(4, date);
-                } else {
-                    stat.setString(3, date);
-                }
-            }
-
-            final ResultSet rs = stat.executeQuery();
-            while (rs.next()) {
-                res.add(new SimpleEntry<>(rs.getInt("Lane"), rs.getFloat("avg")));
-            }
-
-        } catch (final SQLException e) {
-            // TODO Auto-generated catch block
-            e.printStackTrace();
-        }
-        return res;
-    }
-
-    public Float getTrackAvarage(String trackName, ArrayList<Integer> distances, String date, int id, boolean isDriver) {
-        Float res = 0f;
-        String typeString;
-        String distanceFilter;
-        if (id > 0) {
-            if (isDriver) {
-                typeString = "DriverId = ? AND ";
-            } else {
-                typeString = "HorseId = ? AND ";
-            }
-        } else {
-            typeString = "";
-        }
-
-        if (distances != null && !distances.isEmpty()) {
-            distanceFilter = " distance IN (?) AND ";
-        } else {
-            distanceFilter = "";
-        }
-
-        String trackFilter;
-        if (Strings.isNullOrEmpty(trackName)) {
-            trackFilter = "";
-        } else {
-            trackFilter = " TrackId = (SELECT id FROM Track WHERE name = ?) AND ";
-        }
-
-        final String sql = "SELECT AVG(IF(Time <= 0,30,time)) as avg FROM Results " + "WHERE " + typeString + distanceFilter
-                + trackFilter + "RaceDate < ?";
-
-        try {
-            final PreparedStatement stat = getConnection().prepareStatement(sql);
-
-            if (distances != null && !distances.isEmpty()) {
-                final String in = String.join(",", distances.stream().map(m -> m.toString()).collect(Collectors.toList()));
-
-                if (Strings.isNullOrEmpty(trackName)) {
-                    if (id > 0) {
-                        stat.setInt(1, id);
-                        stat.setString(2, in);
-                        stat.setString(3, date);
-
-                    } else {
-                        stat.setString(1, in);
-                        stat.setString(2, date);
-                    }
-                } else {
-                    if (id > 0) {
-                        stat.setInt(1, id);
-                        stat.setString(2, in);
-                        stat.setString(3, trackName);
-                        stat.setString(4, date);
-                    } else {
-                        stat.setString(1, in);
-                        stat.setString(2, trackName);
-                        stat.setString(3, date);
-                    }
-                }
-            } else {
-                if (Strings.isNullOrEmpty(trackName)) {
-                    if (id > 0) {
-                        stat.setInt(1, id);
-                        stat.setString(2, date);
-                    } else {
-                        stat.setString(1, date);
-                    }
-                } else {
-                    if (id > 0) {
-                        stat.setInt(1, id);
-                        stat.setString(2, trackName);
-                        stat.setString(3, date);
-                    } else {
-                        stat.setString(1, trackName);
-                        stat.setString(2, date);
-                    }
-                }
-            }
-            final ResultSet rs = stat.executeQuery();
-            while (rs.next()) { // Om inget resultat kör om utan track, markeras??
-                res = rs.getFloat("avg");
-            }
-
-            if (res <= 0 && !Strings.isNullOrEmpty(trackName)) {
-                res = getTrackAvarage("", distances, date, id, isDriver);
-                distances = null;
-            } else if (res <= 0 && Strings.isNullOrEmpty(trackName) && distances != null && !distances.isEmpty()) {
-                res = getTrackAvarage("", null, date, id, isDriver);
-            }
-
-        } catch (final SQLException e) {
-            // TODO Auto-generated catch block
-            e.printStackTrace();
-        }
-        return res;
-    }
-
-    public void setfullStatsCollected(String who, int travsportId, String date) {
-        String sql;
-        if ("horse".equals(who)) {
-            sql = "UPDATE Horse SET fullStatsCollected = ? WHERE travsportId = ?";
-        } else if ("driver".equals(who)) {
-            sql = "UPDATE Driver SET fullStatsCollected = ? WHERE travsportId = ?";
-        } else {
-            throw new RuntimeException("Unknown who: " + who);
-        }
-
-        try {
-            final PreparedStatement stat = getConnection().prepareStatement(sql);
-            stat.setString(1, date);
-            stat.setInt(2, travsportId);
-
-            stat.executeUpdate();
-        } catch (final SQLException e) {
-            // TODO Auto-generated catch block
-            e.printStackTrace();
-        }
-    }
-
-    public String getFullStatsCollected(String who, int travsportId) {
-        final String sql;
-        String result = null;
-        if ("horse".equals(who)) {
-            sql = "SELECT fullStatsCollected FROM Horse WHERE travsportId = ?";
-        } else if ("driver".equals(who)) {
-            sql = "SELECT fullStatsCollected FROM Driver WHERE travsportId = ?";
-        } else {
-            throw new RuntimeException("Failed to get Full stats");
-        }
-
-        try {
-            final PreparedStatement stat = getConnection().prepareStatement(sql);
-            stat.setInt(1, travsportId);
-
-            final ResultSet rs = stat.executeQuery();
-
-            while (rs.next()) {
-                result = rs.getString("fullStatsCollected");
-
-            }
-        } catch (final SQLException e) {
-            // TODO Auto-generated catch block
-            e.printStackTrace();
-        }
-
-        return result;
-    }
+	private static final DatabaseController instance = new DatabaseController();
+
+	private static final String username = "atg";
+	private static final String password = "CvWKY34DqtlVgjt_9";
+	private static final String database = "atg";
+	private static final String url = "jdbc:mysql://nordh.xyz:3306/";
+	private static final String timezoneFix = "?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";
+
+	private Connection conn;
+
+	protected DatabaseController() {
+		getConnection();
+	}
+
+	public static DatabaseController getInstance() {
+		return instance;
+	}
+
+	protected Connection getConnection() {
+		try {
+			if (conn == null || conn.isClosed()) {
+				conn = DriverManager.getConnection(url + database + timezoneFix, username, password);
+			}
+		} catch (final SQLException e) {
+			throw new RuntimeException(e.getMessage(), e);
+		}
+		return conn;
+	}
+
+	public void insertResult(String trackShortCode, String date, int raceNumber, int lane, int distance, int result, float time, String timeModifier,
+			int shoes, int sulky, String driver, String trainer, String horseName, int travsportIdHorse, int travsportIdTrainer,
+			int travsportIdDriver, String raceType, int raceId) {
+		final String sql;
+		final boolean raceToday = date.equals(MainController.DATE_FORMAT.format(new Date()));
+		horseName = horseName.replaceAll("[^a-z���A-Z���0-9 ()\\.']", "");
+		driver = driver.replaceAll("[^a-z���A-Z���0-9] ()\\.'", "");
+		if (raceToday) {
+			sql = "INSERT INTO " + "`Results`(`TrackId`, `RaceDate`, `RaceNumber`, `Lane`, `Distance`, `Result`, `Time`, `TimeModifier`, "
+					+ "`Shoes`, `Sulky`, `DriverId`, `TrainerId`, `HorseId`, raceId, RaceType) "
+					+ "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE id=id, Result = ?, Time = ?, RaceType = CONCAT(RaceType, ?), RaceId = ?";
+		} else {
+			sql = "INSERT INTO " + "`Results`(`TrackId`, `RaceDate`, `RaceNumber`, `Lane`, `Distance`, `Result`, `Time`, `TimeModifier`, "
+					+ "`Shoes`, `Sulky`, `DriverId`, `TrainerId`, `HorseId`, raceId) "
+					+ "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE id=id, Result = ?, Time = ?, RaceId = ?";
+		}
+
+		final int horseId = getHorseId(horseName, travsportIdHorse);
+		final int driverId = getDriverId(driver, travsportIdDriver);
+		final int trainerId = getTrainerId(trainer, travsportIdTrainer);
+		final int trackId = getTrackIdFromShortcode(trackShortCode);
+
+		if (horseId == -1 || driverId == -1) {
+			return;
+		}
+		try {
+			final PreparedStatement stat = getConnection().prepareStatement(sql);
+
+			stat.setInt(1, trackId);
+			stat.setString(2, date);
+			stat.setInt(3, raceNumber);
+			stat.setInt(4, lane);
+			stat.setInt(5, distance);
+			stat.setInt(6, result);
+			stat.setFloat(7, time);
+			stat.setString(8, timeModifier);
+			stat.setInt(9, shoes);
+			stat.setInt(10, sulky);
+			stat.setInt(11, driverId);
+			if (trainerId < 0) {
+				stat.setNull(12, Types.INTEGER);
+			} else {
+				stat.setInt(12, trainerId);
+			}
+			stat.setInt(13, horseId);
+			stat.setInt(14, result < 0 ? raceId : -1);
+
+			if (raceToday) {
+				stat.setString(15, raceType);
+
+				stat.setInt(16, result);
+				stat.setFloat(17, time);
+				stat.setString(18, ", " + raceType);
+				stat.setInt(19, raceId);
+			} else {
+				stat.setInt(15, result);
+				stat.setFloat(16, time);
+				stat.setInt(17, raceId);
+			}
+			stat.executeUpdate();
+
+		} catch (final SQLException e) {
+			System.out.println("Failing sql " + sql + "[ " + trackId + ", " + date + ", " + raceNumber + ", " + lane + ", " + distance + ", " + result
+					+ ", " + time + ", " + timeModifier + ", " + shoes + "," + sulky + ", " + driverId + ", " + trainerId + ", " + horseId + ", "
+					+ raceId + "]");
+			throw new RuntimeException(e.getMessage(), e);
+		}
+	}
+
+	private int insertNewName(String table, String name, int travsportId) { // travsportId inte generell, beh�vs en
+		// b�ttre l�sning
+		final String sql = "INSERT INTO " + table + " (name, travsportId) VALUES (?, ?)";
+		int last_id = -1;
+		try {
+			final PreparedStatement stat = getConnection().prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
+			stat.setString(1, name);
+			stat.setInt(2, travsportId);
+
+			stat.executeUpdate();
+			final ResultSet generatedId = stat.getGeneratedKeys();
+			while (generatedId.next()) {
+				last_id = generatedId.getInt(1);
+			}
+
+		} catch (final SQLException e) {
+			throw new RuntimeException(e.getMessage(), e);
+		}
+		return last_id;
+	}
+
+	private int getTrackIdFromShortcode(String shortcode) {
+		final String trackSql = "SELECT id FROM Track WHERE shortCode = ?";
+		int trackId = -1;
+		try {
+			final PreparedStatement stat = getConnection().prepareStatement(trackSql);
+			stat.setString(1, shortcode);
+
+			final ResultSet rs = stat.executeQuery();
+			while (rs.next()) {
+				trackId = rs.getInt("id");
+			}
+		} catch (final SQLException e) {
+			throw new RuntimeException(e.getMessage(), e);
+		}
+
+		return trackId;
+	}
+
+	public int getHorseId(String horseName, int travsportId) {
+		horseName = horseName.replaceAll("[^a-z���A-Z���0-9 ()\\.']", "");
+		final String horseSql = "SELECT id FROM Horse WHERE name = ? OR travsportId = ?";
+		int horseId = -1;
+		try {
+			final PreparedStatement stat = getConnection().prepareStatement(horseSql);
+			stat.setString(1, horseName);
+			stat.setInt(2, travsportId);
+
+			final ResultSet rs = stat.executeQuery();
+			while (rs.next()) {
+				horseId = rs.getInt("id");
+			}
+			if (horseId == -1 && !Strings.isNullOrEmpty(horseName)) {
+				horseId = insertNewName("Horse", horseName, travsportId);
+			}
+		} catch (final SQLException e) {
+			throw new RuntimeException(e.getMessage(), e);
+		}
+
+		return horseId;
+	}
+
+	public int getHorseTravsportId(String horseName) {
+		final String sql = "SELECT travsportId FROM Horse WHERE name = ?";
+		int id = -1;
+
+		try {
+			final PreparedStatement stat = getConnection().prepareStatement(sql);
+			stat.setString(1, horseName);
+
+			final ResultSet rs = stat.executeQuery();
+
+			while (rs.next()) {
+				id = rs.getInt("travsportId");
+			}
+		} catch (final SQLException e) {
+			throw new RuntimeException(e.getMessage(), e);
+		}
+
+		return id;
+	}
+
+	public int getDriverId(String driverName, int travsportId) {
+		driverName = driverName.replaceAll("[^a-zA-Z0-9 ]", "");
+		final String driverSql = "SELECT id FROM Driver WHERE name = ? OR travsportId = ?";
+		int driverId = -1;
+		try {
+			final PreparedStatement stat = getConnection().prepareStatement(driverSql);
+			stat.setString(1, driverName);
+			stat.setInt(2, travsportId);
+
+			final ResultSet rs = stat.executeQuery();
+			while (rs.next()) {
+				driverId = rs.getInt("id");
+			}
+			if (driverId == -1 && !Strings.isNullOrEmpty(driverName)) {
+				driverId = insertNewName("Driver", driverName, travsportId);
+			}
+		} catch (final SQLException e) {
+			throw new RuntimeException(e.getMessage(), e);
+		}
+
+		return driverId;
+	}
+
+	private int getTrainerId(String trainerName, int travsportId) {
+		trainerName = trainerName.replaceAll("[^a-zA-Z0-9 ]", "");
+		final String trainerSql = "SELECT id FROM Trainer WHERE name = ? OR travsportId = ?";
+		int trainerId = -1;
+		try {
+			final PreparedStatement stat = getConnection().prepareStatement(trainerSql);
+			stat.setString(1, trainerName);
+			stat.setInt(2, travsportId);
+
+			final ResultSet rs = stat.executeQuery();
+			while (rs.next()) {
+				trainerId = rs.getInt("id");
+			}
+			if (trainerId == -1 && !Strings.isNullOrEmpty(trainerName)) {
+				trainerId = insertNewName("Trainer", trainerName, travsportId);
+			}
+		} catch (final SQLException e) {
+			throw new RuntimeException(e.getMessage(), e);
+		}
+
+		return trainerId;
+	}
+
+	public void setHorseTravsportId(int horseId, String horseName) {
+		final String sql = "UPDATE Horse SET travsportId = ? WHERE name = ?";
+
+		try {
+			final PreparedStatement stat = getConnection().prepareStatement(sql);
+			stat.setInt(1, horseId);
+			stat.setString(2, horseName);
+
+			stat.executeUpdate();
+		} catch (final SQLException e) {
+			throw new RuntimeException(e.getMessage(), e);
+		}
+	}
+
+	// Lane stats SELECT Lane, Count(*) FROM `Results` WHERE Result = 1 AND
+	// TimeModifier NOT like "%a%" GROUP BY Lane ORDER BY `Results`.`Lane` ASC
+	// SELECT Lane, (Count(*) / SUM(COUNT(*)) OVER()) * 100 AS Percent, Distance
+	// FROM `Results` WHERE Result = 1 AND TimeModifier NOT like '%a%' AND Lane > 0
+	// AND Distance IN (2140,2160) GROUP BY Lane, Distance ORDER BY `Results`.`Lane`
+	// ASC
+
+	public List<LaneWinObject> getAutostartWinPercents(ArrayList<String> distance) {
+		final List<LaneWinObject> resultList = Lists.newArrayList();
+		final String sql = "SELECT Lane, (Count(*) / SUM(COUNT(*)) OVER()) * 100 AS Percent, distance FROM `Results` WHERE Result = 1 AND TimeModifier like '%a%' AND Lane > 0 AND Distance IN (?) GROUP BY Lane, Distance ORDER BY `Results`.`Lane` ASC";
+		try {
+			final PreparedStatement stat = getConnection().prepareStatement(sql);
+			stat.setString(1, String.join(",", distance));
+			final ResultSet rs = stat.executeQuery();
+
+			while (rs.next()) {
+				resultList.add(new LaneWinObject(rs.getInt("Lane"), rs.getInt("distance"), rs.getFloat("Percent")));
+			}
+
+		} catch (final SQLException e) {
+			throw new RuntimeException(e.getMessage(), e);
+		}
+
+		return resultList;
+	}
+
+	public List<LaneWinObject> getAutostartWinPercents(List<Integer> distances) {
+		return getAutostartWinPercents(Lists.newArrayList(distances.stream().map(d -> d.toString()).collect(Collectors.toList())));
+	}
+
+	public List<LaneWinObject> getVoltstartWinPercents(ArrayList<String> distance) {
+		final List<LaneWinObject> resultList = Lists.newArrayList();
+		String sql = "SELECT Lane, (Count(*) / SUM(COUNT(*)) OVER()) * 100 AS Percent, distance FROM `Results` WHERE Result = 1 AND TimeModifier NOT like '%a%' AND Lane > 0 AND Distance IN (?) GROUP BY Lane, Distance ORDER BY `Results`.`Lane` ASC";
+		try {
+			final String in = distance.stream().collect(Collectors.joining(",", "(", ")"));
+			sql = sql.replace("(?)", in);
+			final PreparedStatement stat = getConnection().prepareStatement(sql);
+			final ResultSet rs = stat.executeQuery();
+
+			while (rs.next()) {
+				resultList.add(new LaneWinObject(rs.getInt("Lane"), rs.getInt("distance"), rs.getFloat("Percent")));
+			}
+
+		} catch (final SQLException e) {
+			throw new RuntimeException(e.getMessage(), e);
+		}
+
+		return resultList;
+	}
+
+	public List<LaneWinObject> getVoltstartWinPercents(List<Integer> distance) {
+		return getVoltstartWinPercents(Lists.newArrayList(distance.stream().map(m -> m.toString()).collect(Collectors.toList())));
+	}
+
+	public List<HorseRaceData> getRacesFromDate(final String date, final boolean shouldUpdate) {
+		final List<HorseRaceData> results = new ArrayList<>();
+
+		final String sql = "SELECT r1.*, driver.name as DriverName, horse.name as HorseName, track.name as TrackName " + "FROM Results r1 "
+				+ "INNER JOIN Driver as driver ON driverId = driver.id " + "INNER JOIN Horse as horse ON HorseId = horse.id "
+				+ "INNER JOIN Track as track ON TrackId = track.id " + "WHERE r1.RaceDate = ? " + " GROUP BY r1.horseId "
+				+ "ORDER BY r1.TrackId DESC, r1.RaceDate DESC, `r1`.`RaceNumber` ASC";
+
+		try {
+			final PreparedStatement stat = getConnection().prepareStatement(sql);
+
+			stat.setString(1, date);
+
+			final ResultSet rs = stat.executeQuery();
+			while (rs.next()) {
+				final HorseRaceData rd = new HorseRaceData();
+				rd.setDistance(rs.getInt("Distance"));
+				rd.setDriverId(rs.getInt("DriverId"));
+				rd.setDriverName(rs.getString("DriverName"));
+				rd.setHorseName(rs.getString("HorseName"));
+				rd.setHorseId(rs.getInt("HorseId"));
+				rd.setTrainerId(rs.getInt("TrainerId"));
+				rd.setRaceNumber(rs.getInt("RaceNumber"));
+				rd.setTrackName(rs.getString("TrackName"));
+				rd.setRaceDate(rs.getString("RaceDate"));
+				rd.setLane(rs.getInt("Lane"));
+				rd.setResult(rs.getInt("Result"));
+				rd.setTime(rs.getFloat("Time"));
+				rd.setTimeModifier(rs.getString("TimeModifier"));
+				rd.setShoes(rs.getInt("Shoes"));
+				rd.setSulky(rs.getInt("Sulky"));
+
+				if (shouldUpdate) {
+					if (rd.getAvgDriverTimeCount() < 20) {
+						System.out.println("Uppdating driver " + rd.getDriverName() + "(" + rd.getDriverId() + ") travsport id: "
+								+ getDriverTravsportId(rd.getDriverName()) + "because race count was " + rd.getAvgDriverTimeCount());
+						TravsportParser.getInstance().getDriverStatById(getDriverTravsportId(rd.getDriverName()), rd.getDriverName(),
+								rs.getInt("raceId"));
+					}
+
+					if (rd.getAvgHorseTimeCount() < 5) {
+						System.out.println("Uppdating horse " + rd.getHorseName() + "( " + rd.getHorseId() + ") travsport id: "
+								+ getHorseTravsportId(rd.getHorseName()) + " because race count was " + rd.getAvgHorseTimeCount());
+						TravsportParser.getInstance().getHorseStatByIdJson(getHorseTravsportId(rd.getHorseName()), rd.getHorseName(), "",
+								rs.getInt("raceId"));
+					}
+				}
+
+				results.add(rd);
+			}
+		} catch (final SQLException e) {
+			e.printStackTrace();
+		}
+
+		return results;
+	}
+
+	public List<HorseRaceData> getTodaysRaces(String type, String date, boolean shouldUpdate) {
+		final String sql;
+		Date date2 = new Date();
+		try {
+			date2 = MainController.DATE_FORMAT.parse(date);
+		} catch (final ParseException e1) {
+			throw new RuntimeException(e1.getMessage(), e1);
+		}
+		final Calendar c = Calendar.getInstance();
+		c.setTime(date2);
+		c.add(Calendar.YEAR, -2);
+
+		if (Strings.isNullOrEmpty(type)) {
+			sql = "SELECT r1.*, driver.name as DriverName, horse.name as HorseName, track.name as TrackName " + "FROM Results r1 "
+					+ "				INNER JOIN Driver as driver ON driverId = driver.id "
+					+ "				INNER JOIN Horse as horse ON HorseId = horse.id "
+					+ "				INNER JOIN Track as track ON TrackId = track.id " + " WHERE r1.RaceDate = ? " + " GROUP BY r1.horseId "
+					+ "ORDER BY r1.TrackId DESC, r1.RaceDate DESC, `r1`.`RaceNumber` ASC";
+		} else {
+			sql = "SELECT r1.*, driver.name as DriverName, horse.name as HorseName, track.name as TrackName " + "FROM Results r1 "
+					+ "				INNER JOIN Driver as driver ON driverId = driver.id "
+					+ "				INNER JOIN Horse as horse ON HorseId = horse.id "
+					+ "				INNER JOIN Track as track ON TrackId = track.id " + " WHERE r1.RaceDate = ? " + " AND r1.RaceType LIKE ? "
+					+ " GROUP BY r1.horseId " + "ORDER BY r1.TrackId DESC, `r1`.`RaceNumber` ASC";
+		}
+
+		final List<HorseRaceData> results = new ArrayList<>();
+		try {
+			final PreparedStatement stat = getConnection().prepareStatement(sql);
+			if (Strings.isNullOrEmpty(type)) {
+				stat.setString(1, date);
+			} else {
+				stat.setString(1, date);
+				stat.setString(2, "%" + type + "%");
+			}
+
+			final ResultSet rs = stat.executeQuery();
+			while (rs.next()) {
+				final HorseRaceData rd = new HorseRaceData();
+				rd.setDistance(rs.getInt("Distance"));
+				rd.setDriverId(rs.getInt("DriverId"));
+				rd.setDriverName(rs.getString("DriverName"));
+				rd.setHorseName(rs.getString("HorseName"));
+				rd.setHorseId(rs.getInt("HorseId"));
+				rd.setTrainerId(rs.getInt("TrainerId"));
+				rd.setRaceNumber(rs.getInt("RaceNumber"));
+				rd.setTrackName(rs.getString("TrackName"));
+				rd.setRaceDate(rs.getString("RaceDate"));
+				rd.setLane(rs.getInt("Lane"));
+				rd.setResult(rs.getInt("Result"));
+				rd.setTime(rs.getFloat("Time"));
+				rd.setTimeModifier(rs.getString("TimeModifier"));
+				rd.setShoes(rs.getInt("Shoes"));
+				rd.setSulky(rs.getInt("Sulky"));
+
+				rd.setAvgHorseTime(getAvgTime(rd.getHorseId(), rd.getRaceDate(), -1, false), getHorseRaceCount(rd.getHorseId(), 0));
+				rd.setAvgDriverTime(getAvgTime(rd.getDriverId(), rd.getRaceDate(), -1, true), getDriverRaceCount(rd.getDriverId(), 0));
+				rd.setAvgHorseTimeByDistance(getAvgTime(rd.getHorseId(), rd.getRaceDate(), rd.getDistance(), false),
+						getHorseRaceCount(rd.getHorseId(), rd.getDistance()));
+				rd.setAvgDriverTimeByDistance(getAvgTime(rd.getDriverId(), rd.getRaceDate(), rd.getDistance(), true),
+						getDriverRaceCount(rd.getDriverId(), rd.getDistance()));
+
+				if (shouldUpdate) {
+					if (rd.getAvgDriverTimeCount() < 20) {
+						System.out.println("Uppdating driver " + rd.getDriverName() + "(" + rd.getDriverId() + ") travsport id: "
+								+ getDriverTravsportId(rd.getDriverName()) + "because race count was " + rd.getAvgDriverTimeCount());
+						TravsportParser.getInstance().getDriverStatById(getDriverTravsportId(rd.getDriverName()), rd.getDriverName(),
+								rs.getInt("raceId"));
+					}
+
+					if (rd.getAvgHorseTimeCount() < 5) {
+						System.out.println("Uppdating horse " + rd.getHorseName() + "( " + rd.getHorseId() + ") travsport id: "
+								+ getHorseTravsportId(rd.getHorseName()) + " because race count was " + rd.getAvgHorseTimeCount());
+						TravsportParser.getInstance().getHorseStatByIdJson(getHorseTravsportId(rd.getHorseName()), rd.getHorseName(), "",
+								rs.getInt("raceId"));
+					}
+				}
+
+				results.add(rd);
+			}
+		} catch (final SQLException e) {
+			throw new RuntimeException(e.getMessage(), e);
+		}
+
+		return results;
+	}
+
+	private float getAvgTime(int id, String date, int distance, boolean isDriver) {
+
+		float returnValue = 0f;
+		final String who = isDriver ? "DriverId" : "HorseId";
+		String sql = "SELECT AVG(time) as avg FROM Results WHERE " + who + " = ? AND RaceDate < ? AND RaceDate < DATE(NOW())";
+
+		if (distance > 0) {
+			sql += " AND Distance BETWEEN ? AND ?";
+		}
+
+		sql += " AND time > 0 ORDER BY RaceDate DESC";
+
+		try {
+			final PreparedStatement stat = getConnection().prepareStatement(sql);
+
+			stat.setInt(1, id);
+			stat.setString(2, date);
+			if (distance > 0) {
+				stat.setInt(3, distance - 50);
+				stat.setInt(4, distance + 50);
+			}
+
+			final ResultSet rs = stat.executeQuery();
+
+			while (rs.next()) {
+				returnValue = rs.getFloat("avg");
+			}
+		} catch (final SQLException e) {
+			throw new RuntimeException(e.getMessage(), e);
+		}
+
+		return returnValue;
+	}
+
+	public float getAvarageTimeForTrack(int trackId, int distance, int id, boolean isDriver) {
+		final float returnValue = 0f;
+		String sql = "SELECT AVG(time) as avgTime FROM Results WHERE TrackId = ?";
+
+		if (isDriver) {
+			sql += " AND DriverId = ?";
+		} else {
+			sql += " AND HorseId = ?";
+		}
+
+		if (distance > 0) {
+			sql += " AND Distance BETWEEN ? AND ?";
+		}
+
+		try {
+			final PreparedStatement stat = getConnection().prepareStatement(sql);
+			stat.setInt(1, trackId);
+			stat.setInt(2, id);
+			if (distance > 0) {
+				stat.setInt(3, distance - 50);
+				stat.setInt(4, distance + 50);
+			}
+
+			final ResultSet rs = stat.executeQuery();
+
+			while (rs.next()) {
+				rs.getFloat("avgTime");
+			}
+		} catch (final SQLException e) {
+			throw new RuntimeException(e.getMessage(), e);
+		}
+
+		return returnValue;
+	}
+
+	private int getHorseRaceCount(int horseId, int distance) {
+		int returnValue = 0;
+		final String sql;
+		if (distance > 0) {
+			sql = "SELECT Count(*) as c FROM Results WHERE HorseId = ? AND Distance = ? AND Time > 0";
+		} else {
+			sql = "SELECT Count(*) as c FROM Results WHERE HorseId = ? AND Time > 0";
+		}
+		try {
+			final PreparedStatement stat = getConnection().prepareStatement(sql);
+			if (distance > 0) {
+				stat.setInt(1, horseId);
+				stat.setInt(2, distance);
+			} else {
+				stat.setInt(1, horseId);
+			}
+			final ResultSet rs = stat.executeQuery();
+			while (rs.next()) {
+				returnValue = rs.getInt("c");
+			}
+		} catch (final SQLException e) {
+			throw new RuntimeException(e.getMessage(), e);
+		}
+		return returnValue;
+	}
+
+	private int getDriverRaceCount(int driverId, int distance) {
+		int returnValue = 0;
+		final String sql;
+		if (distance > 0) {
+			sql = "SELECT Count(*) as c FROM Results WHERE DriverId = ? AND Distance = ? AND Time > 0";
+		} else {
+			sql = "SELECT Count(*) as c FROM Results WHERE DriverId = ? AND Time > 0";
+		}
+		try {
+			final PreparedStatement stat = getConnection().prepareStatement(sql);
+			if (distance > 0) {
+				stat.setInt(1, driverId);
+				stat.setInt(2, distance);
+			} else {
+				stat.setInt(1, driverId);
+			}
+			final ResultSet rs = stat.executeQuery();
+			while (rs.next()) {
+				returnValue = rs.getInt("c");
+			}
+		} catch (final SQLException e) {
+			throw new RuntimeException(e.getMessage(), e);
+		}
+		return returnValue;
+	}
+
+	// H�mta statistik f�r h�st, f�rare, kombinationen av dessa tv�, distans....
+	public SimpleEntry<Integer, Integer> getNumHorseGallop(int horseId) {
+		final String sql = "SELECT COUNT(*) as total, SUM(IF(TimeModifier LIKE '%g%', 1, 0)) as gallop FROM `Results` WHERE HorseId = ?";
+		SimpleEntry<Integer, Integer> returnValue = null;
+
+		try {
+			final PreparedStatement stat = getConnection().prepareStatement(sql);
+			stat.setInt(1, horseId);
+
+			final ResultSet rs = stat.executeQuery();
+			while (rs.next()) {
+				returnValue = new SimpleEntry<>(rs.getInt("total"), rs.getInt("gallop"));
+			}
+		} catch (final SQLException e) {
+			throw new RuntimeException(e.getMessage(), e);
+		}
+
+		return returnValue;
+	}
+
+	// H�mta statistik f�r h�st, f�rare, kombinationen av dessa tv�, distans....
+	public SimpleEntry<Integer, Integer> getNumDriverGallop(int driverId) {
+		final String sql = "SELECT COUNT(*) as total, SUM(IF(TimeModifier LIKE '%g%', 1, 0)) as gallop FROM `Results` WHERE DriverId = ?";
+		SimpleEntry<Integer, Integer> returnValue = null;
+
+		try {
+			final PreparedStatement stat = getConnection().prepareStatement(sql);
+			stat.setInt(1, driverId);
+
+			final ResultSet rs = stat.executeQuery();
+			while (rs.next()) {
+				returnValue = new SimpleEntry<>(rs.getInt("total"), rs.getInt("gallop"));
+			}
+		} catch (final SQLException e) {
+			throw new RuntimeException(e.getMessage(), e);
+		}
+
+		return returnValue;
+	}
+
+	public int getDriverTravsportId(String driverFirstName, String driverLastName) {
+		int returnValue = -1;
+		final String sql = "SELECT travsportId FROM Driver WHERE name = ?";
+		try {
+			final PreparedStatement stat = getConnection().prepareStatement(sql);
+			stat.setString(1, driverLastName + " " + driverFirstName);
+
+			final ResultSet rs = stat.executeQuery();
+
+			while (rs.next()) {
+				returnValue = rs.getInt("travsportId");
+			}
+		} catch (final SQLException e) {
+			throw new RuntimeException(e.getMessage(), e);
+		}
+		return returnValue;
+	}
+
+	public int getDriverTravsportId(String driverName) {
+		int returnValue = -1;
+		final String sql = "SELECT travsportId FROM Driver WHERE name = ?";
+		try {
+			final PreparedStatement stat = getConnection().prepareStatement(sql);
+			stat.setString(1, driverName);
+
+			final ResultSet rs = stat.executeQuery();
+
+			while (rs.next()) {
+				returnValue = rs.getInt("travsportId");
+			}
+		} catch (final SQLException e) {
+			throw new RuntimeException(e.getMessage(), e);
+		}
+		return returnValue;
+	}
+
+	public void setDriverTravsportId(int driverId, String firstName, String lastName) {
+		final String sql = "UPDATE Driver SET travsportId = ? WHERE name = ?";
+		try {
+			final PreparedStatement stat = getConnection().prepareStatement(sql);
+			stat.setInt(1, driverId);
+			stat.setString(2, lastName + " " + firstName);
+
+			stat.executeUpdate();
+		} catch (final SQLException e) {
+			throw new RuntimeException(e.getMessage(), e);
+		}
+	}
+
+	public float getTrendLast5(HorseRaceData horseRaceData) {
+		final String combinedTrendSql = "SELECT Time, (SELECT AVG(Time) FROM Results WHERE HorseId = ? AND DriverId = ? AND Distance = ?) as avgTime FROM Results WHERE HorseId = ? AND DriverId = ? AND Distance = ? AND Time > -1 ORDER BY RaceDate ASC limit 5";
+		final String DriverTrendSql = "SELECT Time, (SELECT AVG(Time) FROM Results WHERE DriverId = ? AND Distance = ?) as avgTime FROM Results WHERE DriverId = ? AND Distance = ? AND Time > -1 ORDER BY RaceDate ASC limit 5";
+		final String horseTrendSql = "SELECT Time, (SELECT AVG(Time) FROM Results WHERE HorseId = ? AND Distance = ?) as avgTime FROM Results WHERE HorseId = ? AND Distance = ? AND Time > -1  ORDER BY RaceDate ASC limit 5";
+
+		final int horseId = horseRaceData.getHorseId();
+		final int driverId = horseRaceData.getDriverId();
+		final int distance = horseRaceData.getDistance();
+
+		float avgHorseTime = -1f;
+		float avgDriverTime = -1f;
+		float avgCombinedTime = -1f;
+		float startHorseAvgTime = -1;
+		float startDriverAvgTime = -1;
+		float startCombinedAvgTime = -1;
+		try {
+			final PreparedStatement horseStat = getConnection().prepareStatement(horseTrendSql, ResultSet.TYPE_SCROLL_INSENSITIVE,
+					ResultSet.CONCUR_READ_ONLY);
+			horseStat.setInt(1, horseId);
+			horseStat.setInt(2, distance);
+			horseStat.setInt(3, horseId);
+			horseStat.setInt(4, distance);
+
+			final ResultSet horseRs = horseStat.executeQuery();
+			if (horseRs.next()) {
+				startHorseAvgTime = horseRs.getFloat("avgTime");
+				;
+				horseRs.beforeFirst();
+				avgHorseTime = getTrendAvgTime(horseRs);
+				// This should be the return value for horse
+				System.out.println("Horse trend is " + (avgHorseTime - startHorseAvgTime));
+			} else {
+				System.out.println("No Horse trend found");
+			}
+
+			horseRs.close();
+			horseStat.close();
+
+			final PreparedStatement driverStat = conn.prepareStatement(DriverTrendSql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
+			driverStat.setInt(1, driverId);
+			driverStat.setInt(2, distance);
+			driverStat.setInt(3, driverId);
+			driverStat.setInt(4, distance);
+			final ResultSet driverRs = driverStat.executeQuery();
+
+			if (driverRs.next()) {
+				startDriverAvgTime = driverRs.getFloat("avgTime");
+				;
+				driverRs.beforeFirst();
+				avgDriverTime = getTrendAvgTime(driverRs);
+				System.out.println("Driver trend is " + (avgDriverTime - startDriverAvgTime));
+			} else {
+				System.out.println("No driver trend found");
+			}
+
+			final PreparedStatement combinedStat = conn.prepareStatement(combinedTrendSql, ResultSet.TYPE_SCROLL_INSENSITIVE,
+					ResultSet.CONCUR_READ_ONLY);
+
+			combinedStat.setInt(1, horseId);
+			combinedStat.setInt(2, driverId);
+			combinedStat.setInt(3, distance);
+			combinedStat.setInt(4, horseId);
+			combinedStat.setInt(5, driverId);
+			combinedStat.setInt(6, distance);
+			final ResultSet combinedRs = combinedStat.executeQuery();
+
+			if (combinedRs.next()) {
+				startCombinedAvgTime = combinedRs.getFloat("avgTime");
+				;
+				combinedRs.beforeFirst();
+				avgCombinedTime = getTrendAvgTime(combinedRs);
+				System.out.println("Combined trend is " + (avgCombinedTime - startCombinedAvgTime));
+			} else {
+				System.out.println("No combined trend available");
+			}
+
+			if (avgHorseTime > -1 && avgDriverTime > -1) {
+				System.out.println("Combination of horse and driver: " + ((avgHorseTime - startHorseAvgTime) + (avgDriverTime - startDriverAvgTime)));
+			}
+			System.out.println("------");
+
+		} catch (final SQLException e) {
+			throw new RuntimeException(e.getMessage(), e);
+		}
+
+		return ((avgHorseTime - startHorseAvgTime) + (avgDriverTime - startDriverAvgTime)) / 2f;
+	}
+
+	private float getTrendAvgTime(final ResultSet rs) throws SQLException {
+		float returnValue = 0.0f;
+		while (rs.next()) {
+			if (returnValue == 0.0f) {
+				returnValue = rs.getFloat("avgTime");
+			}
+
+			if (returnValue == 0f) {
+				returnValue = rs.getFloat("Time");
+			}
+			final float diff = -(returnValue - rs.getFloat("Time"));
+			returnValue = returnValue + diff;
+		}
+		return returnValue;
+	}
+
+	public void updateResult(String horseName, String driverName, int result, String timeModifier, float timeValue, String date, String type) {
+		final String sql = "UPDATE Results " + "SET " + "Result = ?, Time = ?, TimeModifier = ?" + "WHERE "
+				+ "HorseId = (SELECT id FROM Horse WHERE name = ?) AND " + "DriverId = (SELECT id FROM Driver WHERE name = ?) AND" + "RaceDate = ?";
+		try {
+			final PreparedStatement stat = getConnection().prepareStatement(sql);
+			stat.setInt(1, result);
+			stat.setFloat(2, timeValue);
+			stat.setString(3, timeModifier);
+			stat.setString(4, horseName);
+			stat.setString(5, driverName);
+			stat.setString(6, date);
+
+			final int res = stat.executeUpdate();
+
+			if (res != 1) {
+				System.out.println("Updated " + res + " results for horse " + horseName + " and driver " + driverName + " at date " + date);
+			}
+
+		} catch (final SQLException e) {
+			throw new RuntimeException(e.getMessage(), e);
+		}
+
+	}
+
+	public String getTrackShortCodeByName(String trackName) {
+		final String sql = "SELECT shortcode FROM Track WHERE name = ?";
+		String trackcode = null;
+		try {
+			final PreparedStatement stat = getConnection().prepareStatement(sql);
+			stat.setString(1, trackName);
+
+			final ResultSet rs = stat.executeQuery();
+			while (rs.next()) {
+				trackcode = rs.getString("shortcode");
+			}
+		} catch (final SQLException e) {
+			throw new RuntimeException(e.getMessage(), e);
+		}
+		return trackcode;
+	}
+
+	public int getRaceCount(String what, int id) {
+		int returnValue = 0;
+		final String sql;
+		if (what.equals("Horse")) {
+			sql = "SELECT Count(*) as count FROM Results WHERE HorseId = ?";
+		} else if (what.equals("Driver")) {
+			sql = "SELECT Count(*) as count FROM Results WHERE DriverId = ?";
+		} else {
+			sql = "";
+		}
+
+		if (!Strings.isNullOrEmpty(sql)) {
+			try {
+				final PreparedStatement stat = getConnection().prepareStatement(sql);
+				stat.setInt(1, id);
+
+				final ResultSet rs = stat.executeQuery();
+				while (rs.next()) {
+					returnValue = rs.getInt("count");
+				}
+
+			} catch (final SQLException e) {
+				throw new RuntimeException(e.getMessage(), e);
+			}
+		}
+		return returnValue;
+	}
+
+	public int getRaceId() {
+		final String sql = "SELECT raceId FROM Results where raceId > -1 AND RaceDate < DATE(NOW()) ORDER BY RaceDate ASC LIMIT 1";
+		int returnValue = -1;
+		try {
+			final PreparedStatement stat = getConnection().prepareStatement(sql);
+			final ResultSet rs = stat.executeQuery();
+			while (rs.next()) {
+				returnValue = rs.getInt("raceId");
+			}
+		} catch (final SQLException e) {
+			throw new RuntimeException(e.getMessage(), e);
+		}
+
+		return returnValue;
+
+	}
+
+	public List<UpdateRaceRow> getRacesToUpdate(String date) {
+		final List<UpdateRaceRow> racesToUpdate = Lists.newArrayList();
+		final String sql = "SELECT r.*, t.name as TrackName, t.id as TrackId FROM Results r INNER JOIN Track t ON r.trackId = t.id WHERE r.RaceDate = ? GROUP BY r.RaceDate, t.name, r.RaceNumber";
+
+		try {
+			final PreparedStatement stat = getConnection().prepareStatement(sql);
+			stat.setString(1, date);
+
+			final ResultSet rs = stat.executeQuery();
+
+			while (rs.next()) {
+				racesToUpdate.add(new UpdateRaceRow(rs.getInt("id"), rs.getString("RaceDate"), rs.getString("RaceType"),
+						rs.getString("TimeModifier").contains("a"), rs.getInt("RaceNumber"), rs.getString("TrackName"), rs.getInt("TrackId")));
+			}
+		} catch (final SQLException e) {
+			throw new RuntimeException(e.getMessage(), e);
+		}
+
+		return racesToUpdate;
+
+	}
+
+	public void updateRaceInfo(int raceId, boolean isAutostart, String raceType, int raceNumber, String date, int trackId) {
+		final String sql = "UPDATE Results SET RaceType = ? WHERE raceId = ? AND RaceNumber = ? AND trackId = ? AND RaceDate = ?";
+		final String updateTimeModifier;
+		if (isAutostart) {
+			updateTimeModifier = "UPDATE `Results` SET TimeModifier = " + "IF(TimeModifier LIKE '%a%', " + "TimeModifier, "
+					+ "CONCAT(TimeModifier, 'a')) " + "WHERE RaceDate = ? AND RaceNumber = ? AND TrackId = ?";
+		} else {
+			updateTimeModifier = "UPDATE `Results` SET TimeModifier = " + "REPLACE(TimeModifier, 'a', '') "
+					+ "WHERE RaceDate = ? AND RaceNumber = ? AND TrackId = ?";
+		}
+
+		try {
+			PreparedStatement stat = getConnection().prepareStatement(sql);
+			stat.setString(1, raceType);
+			stat.setInt(2, raceId);
+			stat.setInt(3, raceNumber);
+			stat.setInt(4, trackId);
+			stat.setString(5, date);
+
+			stat.executeUpdate();
+
+			stat = getConnection().prepareStatement(updateTimeModifier);
+			stat.setString(1, date);
+			stat.setInt(2, raceNumber);
+			stat.setInt(3, trackId);
+
+			stat.executeUpdate();
+
+		} catch (final SQLException e) {
+			throw new RuntimeException(e.getMessage(), e);
+		}
+
+	}
+
+	public void updateFromRaceResults(int raceId, int result, float time, String timeModifier, int lane, int distance, int horseTravsportId,
+			int driverTravsportId, String raceDate, int raceNumber) {
+		final int horseId = getHorseId("", horseTravsportId);
+		final int driverId = getDriverId("", driverTravsportId);
+		final String sql = "UPDATE Results SET Result = ?, Time = ?, TimeModifier = ?, DriverId = ?, raceId = -1 WHERE RaceDate = ? AND RaceId = ? AND RaceNumber = ? AND HorseId = ?";
+		if (horseId == -1 || driverId == -1) {
+			System.out.println("NOT UPDATING horseId " + horseId + " driver Id: " + driverId);
+			return;
+		}
+		try {
+
+			final PreparedStatement stat = getConnection().prepareStatement(sql);
+			stat.setInt(1, result);
+			stat.setFloat(2, time);
+			stat.setString(3, timeModifier);
+			stat.setInt(4, driverId);
+			stat.setString(5, raceDate);
+			stat.setInt(6, raceId);
+			stat.setInt(7, raceNumber);
+			stat.setInt(8, horseId);
+			// stat.setInt(7, lane);
+			// stat.setInt(8, distance);
+
+			stat.executeUpdate();
+
+		} catch (final SQLException e) {
+			throw new RuntimeException(e.getMessage(), e);
+		}
+
+	}
+
+	public void removeRaceIds(int raceId) {
+		final String sql = "UPDATE Results SET raceId = -1 WHERE RaceId = ?";
+		try {
+			final PreparedStatement statement = getConnection().prepareStatement(sql);
+			statement.setInt(1, raceId);
+
+			statement.executeUpdate();
+		} catch (final SQLException e) {
+			throw new RuntimeException(e.getMessage(), e);
+		}
+
+	}
+
+	public void setSetting(String name, String value) {
+		final String sql = "INSERT INTO Settings (name, value) VALUES (?, ?) ON DUPLICATE KEY UPDATE value = ?";
+		try {
+			final PreparedStatement stat = getConnection().prepareStatement(sql);
+			stat.setString(1, name);
+			stat.setString(2, value);
+			stat.setString(3, value);
+
+			stat.execute();
+		} catch (final SQLException e) {
+			throw new RuntimeException(e.getMessage(), e);
+		}
+	}
+
+	public String getSetting(String name) {
+		final String sql = "SELECT value FROM Settings WHERE name = ?";
+
+		String returnValue = "";
+		try {
+			final PreparedStatement stat = getConnection().prepareStatement(sql);
+			stat.setString(1, name);
+
+			final ResultSet rs = stat.executeQuery();
+			while (rs.next()) {
+				returnValue = rs.getString("value");
+			}
+		} catch (final SQLException e) {
+			throw new RuntimeException(e.getMessage(), e);
+		}
+
+		return returnValue;
+	}
+
+	public String getDriverLastRace(int driverId, int raceNumber) {
+		final String sql = "SELECT RaceDate FROM Results WHERE (RaceDate < ? || (RaceDate = ? AND RaceNumber < ?)) AND DriverId = ? ORDER BY RaceDate DESC limit 1";
+		String lastRaceDate = "";
+		try {
+			final PreparedStatement stat = getConnection().prepareStatement(sql);
+			final String currentDate = MainController.DATE_FORMAT.format(new Date());
+			stat.setString(1, currentDate);
+			stat.setString(2, currentDate);
+			stat.setInt(3, raceNumber);
+			stat.setInt(4, driverId);
+
+			final ResultSet rs = stat.executeQuery();
+			while (rs.next()) {
+				lastRaceDate = rs.getString("RaceDate");
+			}
+		} catch (final SQLException e) {
+			throw new RuntimeException(e.getMessage(), e);
+		}
+
+		return lastRaceDate;
+	}
+
+	public float getAvgTimeByDriverAndDistance(int driverId, int distance, String date, int raceNumber) {
+		float returnValue = 0f;
+
+		// Get driver last raceDate
+		final String lastRaceDate = getDriverLastRace(driverId, raceNumber);
+
+		final LocalDate lastDate = LocalDate.parse(lastRaceDate);
+		final LocalDate parsedDate = LocalDate.parse(date);
+
+		final Long days = Duration.between(lastDate.atStartOfDay(), parsedDate.atStartOfDay()).toDays();
+
+		final String sql = "SELECT currentDate.RaceDate as date, prevDate.RaceDate AS prev_date, DATEDIFF(currentDate.RaceDate, prevDate.RaceDate) as diff, "
+				+ "ROUND(AVG(currentDate.Time),2) as avgTime, COUNT(*), ROUND(AVG(currentDate.adjTime),2) as adjAvgTime " + "FROM "
+				+ "(SELECT (@row_number:=@row_number + 1) as RID, "
+				+ "IF (Time = -1, (SELECT MIN(Time) FROM (SELECT Time FROM Results WHERE TimeModifier NOT LIKE '%g%' ORDER BY Time DESC limit 5) abc), time) as adjTime, "
+				+ "Results.* FROM Results, " + "(SELECT @row_number:=0) as t WHERE DriverId = ? AND distance = ? AND RaceDate <= ? "
+				+ "ORDER BY RaceDate DESC ) AS currentDate " + "INNER JOIN (SELECT (@row_number2 := @row_number2 + 1) AS RID, RaceDate "
+				+ "FROM Results, (SELECT @row_number2:=0) AS t " + "WHERE DriverId = ? AND distance = ? AND RaceDate <= ? "
+				+ "ORDER BY RaceDate DESC LIMIT 99999 OFFSET 1) AS prevDate ON currentDate.RID = prevDate.RID " + "GROUP BY diff ORDER BY DIFF";
+
+		try {
+			final PreparedStatement stat = getConnection().prepareStatement(sql);
+			stat.setInt(1, driverId);
+			stat.setInt(2, distance);
+			stat.setString(3, lastRaceDate);
+			stat.setInt(4, driverId);
+			stat.setInt(5, distance);
+			stat.setString(6, lastRaceDate);
+
+			final ResultSet rs = stat.executeQuery();
+
+			while (rs.next()) {
+				if (rs.getInt("diff") == days) {
+					returnValue = rs.getFloat("adjAvgTime");
+					break;
+				}
+			}
+
+		} catch (final SQLException e) {
+			System.out.println("ERROR IN SQL " + sql + " \ndate " + lastRaceDate);
+			throw new RuntimeException(e.getMessage(), e);
+		}
+
+		return returnValue;
+	}
+
+	public void getTestDataToFile() {
+		final String sql = "SELECT * FROM Results WHERE RaceDate < ? AND RaceDate > ? ORDER BY RaceDate DESC";
+
+		final String delimiter = ";";
+		final String currentDate = MainController.DATE_FORMAT.format(new Date());
+
+		final File file = new File(System.getProperty("user.dir") + File.separator + "src/test/testFiles.csv");
+		try (final BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
+			final PreparedStatement stat = getConnection().prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
+			stat.setString(1, currentDate);
+			stat.setString(2, "2015-01-01");
+
+			final ResultSet rs = stat.executeQuery();
+
+			rs.last();
+			final int lastRow = rs.getRow();
+			rs.beforeFirst();
+
+			int i = 1;
+			while (rs.next()) {
+				final Result result = new Result(rs.getInt(1), rs.getInt(2), rs.getString(3), rs.getString(4), rs.getInt(5), rs.getInt(6),
+						rs.getInt(7), rs.getInt(8), rs.getFloat(9), rs.getString(10), rs.getInt(11), rs.getInt(12), rs.getInt(13), rs.getInt(14),
+						rs.getInt(15), rs.getInt(16));
+
+				final float avgHorseTime = getAvgTime(result.getHorseId(), result.getRaceDate(), -1, false);
+				final float avgHorseTimeDistance = getAvgTime(result.getHorseId(), result.getRaceDate(), result.getDistance(), false);
+				final float avgDriverTime = getAvgTime(result.getDriverId(), result.getRaceDate(), -1, true);
+				final float avgDriverTimeDistance = getAvgTime(result.getDriverId(), result.getRaceDate(), result.getDistance(), true);
+
+				writer.append(result.resultToFileString() + ";" + avgHorseTime + ";" + avgHorseTimeDistance + ";" + avgDriverTime + ";"
+						+ avgDriverTimeDistance + System.lineSeparator());
+
+				if (i % 1000 == 0) {
+					System.out.println(LocalTime.now() + " Done with " + i++ + " of " + lastRow);
+				}
+			}
+
+		} catch (final SQLException | IOException e) {
+			throw new RuntimeException(e.getMessage(), e);
+		}
+
+	}
+
+	public int getLastRaceDaysHorse(int horseId, String raceDate, int raceNumber) {
+		int returnValue = 999;
+		final String sql = "SELECT DATEDIFF(?, startDate.RaceDate) as days, startDate.RaceDate, nextDate.RaceDate, RaceNumber "
+				+ "FROM (SELECT (@row_number := @row_number + 1) AS orderNum, RaceDate, RaceNumber "
+				+ "FROM Results, (SELECT @row_number:=0) AS t WHERE RaceDate <= ? AND HorseId = ? "
+				+ "ORDER BY RaceDate DESC, RaceNumber DESC) AS startDate " + "INNER JOIN "
+				+ "(SELECT (@row_number2 := @row_number2 + 1) AS orderNum, RaceDate "
+				+ "FROM Results, (SELECT @row_number2 := 0) AS t WHERE RaceDate <= ? AND HorseId = ? " + "ORDER BY RaceDate DESC, RaceNumber DESC "
+				+ "LIMIT 11 " + "OFFSET 1) AS nextDate ON nextDate.orderNum = startDate.orderNum";
+		try {
+			final PreparedStatement stat = getConnection().prepareStatement(sql);
+
+			stat.setString(1, raceDate);
+			stat.setString(2, raceDate);
+			stat.setInt(3, horseId);
+			stat.setString(4, raceDate);
+			stat.setInt(5, horseId);
+			final ResultSet rs = stat.executeQuery();
+
+			boolean getNext = false;
+			while (rs.next()) {
+				if (getNext) {
+					returnValue = rs.getInt("days");
+					break;
+				}
+				if (rs.getString("RaceDate").equals(raceDate) && rs.getInt("RaceNumber") == raceNumber) {
+					getNext = true;
+				}
+			}
+		} catch (final SQLException e) {
+			e.printStackTrace();
+		}
+		return returnValue;
+	}
+
+	public int getLastRaceDaysDriver(int driverId, String raceDate, int raceNumber) {
+		int returnValue = 999;
+
+		final String sql = "SELECT DATEDIFF(?, startDate.RaceDate) as days, startDate.RaceDate, nextDate.RaceDate, RaceNumber "
+				+ "FROM (SELECT (@row_number := @row_number + 1) AS orderNum, RaceDate, RaceNumber "
+				+ "FROM Results, (SELECT @row_number:=0) AS t WHERE RaceDate <= ? AND DriverId = ? "
+				+ "ORDER BY RaceDate DESC, RaceNumber DESC) AS startDate " + "INNER JOIN "
+				+ "(SELECT (@row_number2 := @row_number2 + 1) AS orderNum, RaceDate "
+				+ "FROM Results, (SELECT @row_number2 := 0) AS t WHERE RaceDate <= ? AND DriverId = ? " + "ORDER BY RaceDate DESC, RaceNumber DESC "
+				+ "LIMIT 11 " + "OFFSET 1) AS nextDate ON nextDate.orderNum = startDate.orderNum";
+
+		try {
+			final CallableStatement stat = getConnection().prepareCall(sql);
+
+			stat.setString(1, raceDate);
+			stat.setString(2, raceDate);
+			stat.setInt(3, driverId);
+			stat.setString(4, raceDate);
+			stat.setInt(5, driverId);
+
+			final ResultSet rs = stat.executeQuery();
+
+			boolean getNext = false;
+			while (rs.next()) {
+				if (getNext) {
+					returnValue = rs.getInt("days");
+					break;
+				}
+				if (rs.getString("RaceDate").equals(raceDate) && rs.getInt("RaceNumber") == raceNumber) {
+					getNext = true;
+				}
+			}
+		} catch (final SQLException e) {
+			e.printStackTrace();
+		}
+		return returnValue;
+	}
+
+	public int getLastRaceDaysBoth(int horseId, int driverId, String raceDate, int raceNumber) {
+		int returnValue = 999;
+
+		final String sql = "SELECT DATEDIFF(?, startDate.RaceDate) as days, startDate.RaceDate, nextDate.RaceDate, RaceNumber "
+				+ "FROM (SELECT (@row_number := @row_number + 1) AS orderNum, RaceDate, RaceNumber "
+				+ "FROM Results, (SELECT @row_number:=0) AS t WHERE RaceDate <= ? AND DriverId = ? AND HorseId = ? "
+				+ "ORDER BY RaceDate DESC, RaceNumber DESC) AS startDate " + "INNER JOIN "
+				+ "(SELECT (@row_number2 := @row_number2 + 1) AS orderNum, RaceDate "
+				+ "FROM Results, (SELECT @row_number2 := 0) AS t WHERE RaceDate <= ? AND DriverId = ? AND HorseId = ? "
+				+ "ORDER BY RaceDate DESC, RaceNumber DESC " + "LIMIT 11 " + "OFFSET 1) AS nextDate ON nextDate.orderNum = startDate.orderNum";
+
+		try {
+			final PreparedStatement stat = getConnection().prepareStatement(sql);
+
+			stat.setString(1, raceDate);
+			stat.setString(2, raceDate);
+			stat.setInt(3, driverId);
+			stat.setInt(4, horseId);
+			stat.setString(5, raceDate);
+			stat.setInt(6, driverId);
+			stat.setInt(7, horseId);
+
+			final ResultSet rs = stat.executeQuery();
+
+			boolean getNext = false;
+			while (rs.next()) {
+				if (getNext) {
+					returnValue = rs.getInt("days");
+					break;
+				}
+				if (rs.getString("RaceDate").equals(raceDate) && rs.getInt("RaceNumber") == raceNumber) {
+					getNext = true;
+				}
+			}
+		} catch (final SQLException e) {
+			e.printStackTrace();
+		}
+		return returnValue;
+	}
+
+	public ArrayList<DaysSinceLastRace> getDriverDaysSinceLastRaceStats(int driverId) {
+		final ArrayList<DaysSinceLastRace> daysStats = Lists.newArrayList();
+		final String sql = "SELECT DATEDIFF(startDate.RaceDate, prevDate.RaceDate) as days, count(*) as count, SUM(if (startDate.result = 1,1,0)) as wins, SUM(if (startDate.result = 1,1,0)) / count(*) as percent "
+				+ "FROM (SELECT (@row_number := @row_number + 1) AS orderNum, RaceDate, Result, RaceNumber "
+				+ "FROM Results, (SELECT @row_number:=0) AS t " + "WHERE DriverId = ? " + "ORDER BY RaceDate DESC, RaceNumber ASC) as startDate "
+				+ "INNER JOIN " + "(SELECT (@row_number2 := @row_number2 + 1) AS orderNum, RaceDate "
+				+ "FROM Results, (SELECT @row_number2 := 0) AS t  " + "WHERE DriverId = ? " + "ORDER BY RaceDate DESC, RaceNumber ASC "
+				+ "LIMIT 100000 "
+				+ "OFFSET 1) AS prevDate ON startDate.orderNum = prevDate.orderNum GROUP BY days HAVING days <= 100 ORDER BY days ASC";
+
+		try {
+			final PreparedStatement stat = getConnection().prepareStatement(sql);
+
+			stat.setInt(1, driverId);
+			stat.setInt(2, driverId);
+
+			final ResultSet rs = stat.executeQuery();
+
+			while (rs.next()) {
+				daysStats.add(new DaysSinceLastRace(rs.getInt("days"), rs.getInt("count"), rs.getInt("wins"), rs.getFloat("percent")));
+			}
+
+		} catch (final SQLException e) {
+			e.printStackTrace();
+			throw new RuntimeException();
+		}
+
+		return daysStats;
+	}
+
+	public DaysSinceLastRace getDriverDaysSinceLastRaceStat(int driverId, int daysSinceLast) {
+		DaysSinceLastRace dayStat = null;
+		final String sql = "SELECT DATEDIFF(startDate.RaceDate, prevDate.RaceDate) as days, count(*) as count, SUM(if (startDate.result = 1,1,0)) as wins, SUM(if (startDate.result = 1,1,0)) / count(*) as percent "
+				+ "FROM (SELECT (@row_number := @row_number + 1) AS orderNum, RaceDate, Result, RaceNumber "
+				+ "FROM Results, (SELECT @row_number:=0) AS t " + "WHERE DriverId = ? " + "ORDER BY RaceDate DESC, RaceNumber ASC) as startDate "
+				+ "INNER JOIN " + "(SELECT (@row_number2 := @row_number2 + 1) AS orderNum, RaceDate "
+				+ "FROM Results, (SELECT @row_number2 := 0) AS t  " + "WHERE DriverId = ? " + "ORDER BY RaceDate DESC, RaceNumber ASC "
+				+ "LIMIT 100000 "
+				+ "OFFSET 1) AS prevDate ON startDate.orderNum = prevDate.orderNum WHERE DATEDIFF(startDate.RaceDate, prevDate.RaceDate) = ?";
+
+		try {
+			final PreparedStatement stat = getConnection().prepareStatement(sql);
+
+			stat.setInt(1, driverId);
+			stat.setInt(2, driverId);
+			stat.setInt(3, daysSinceLast);
+
+			final ResultSet rs = stat.executeQuery();
+
+			while (rs.next()) {
+				dayStat = new DaysSinceLastRace(rs.getInt("days"), rs.getInt("count"), rs.getInt("wins"), rs.getFloat("percent"));
+			}
+
+		} catch (final SQLException e) {
+			e.printStackTrace();
+			throw new RuntimeException();
+		}
+
+		return dayStat;
+	}
+
+	public ArrayList<Integer> getDriverIds() {
+		final String sql = "SELECT DISTINCT(DriverId) as id FROM Results WHERE RaceDate > DATE_SUB(RaceDate, INTERVAL 6 MONTH)";
+		final ArrayList<Integer> driverIds = Lists.newArrayList();
+		try {
+			final PreparedStatement stat = getConnection().prepareStatement(sql);
+			final ResultSet rs = stat.executeQuery();
+
+			while (rs.next()) {
+				driverIds.add(rs.getInt("id"));
+			}
+
+		} catch (final SQLException e) {
+			e.printStackTrace();
+		}
+		return driverIds;
+	}
+
+	public String getLastResults(int id, int id2, String raceDate, int raceNumber, int limit, String type) {
+		String returnValue = "";
+		final String typeString;
+		if (type.equals("Horse")) {
+			typeString = "HorseId = ? AND ";
+		} else if (type.equals("Driver")) {
+			typeString = "DriverId = ? AND ";
+		} else if (type.equals("Both")) {
+			typeString = "DriverId = ? AND HorseId = ? AND ";
+		} else {
+			typeString = "";
+		}
+		final String sql = "SELECT AVG(IF (Result <= 0, 8, result)) as avg, GROUP_CONCAT(Result) as list FROM " + "(SELECT result FROM Results "
+				+ "WHERE " + typeString + "RaceDate < ? " + "AND RaceDate < DATE(NOW()) " + "ORDER BY RaceDate DESC, RaceNumber DESC "
+				+ "LIMIT ?) as t";
+
+		try {
+			final PreparedStatement stat = getConnection().prepareStatement(sql);
+			if (type.equals("Both")) {
+				stat.setInt(1, id);
+				stat.setInt(2, id2);
+				stat.setString(3, raceDate);
+				stat.setInt(4, limit);
+			} else {
+				stat.setInt(1, id);
+				stat.setString(2, raceDate);
+				stat.setInt(3, limit);
+			}
+			final ResultSet rs = stat.executeQuery();
+			while (rs.next()) {
+				float avg = rs.getFloat("avg");
+				final String dbList = rs.getString("list");
+				final ArrayList<String> list;
+				if (dbList == null) {
+					list = new ArrayList<>();
+				} else {
+					list = Lists.newArrayList(dbList.split(","));
+				}
+				if (list.size() < limit) {
+					int newAvg = 0;
+					for (final String res : list) {
+						Integer resVal = Integer.valueOf(res);
+						if (resVal <= 0) {
+							resVal = 8;
+						}
+						newAvg += resVal;
+					}
+					for (int i = list.size(); i < limit; i++) {
+						newAvg += 8;
+					}
+					avg = newAvg / (float) limit;
+				}
+				returnValue = String.valueOf(avg) + " (" + dbList + ")";
+			}
+
+		} catch (final SQLException e) {
+			e.printStackTrace();
+			throw new RuntimeException();
+		}
+		return returnValue;
+	}
+
+	public List<SimpleEntry<Integer, Float>> getTrackAvarages(String trackName, ArrayList<Integer> distances, String date, int id, boolean isDriver) {
+		final List<SimpleEntry<Integer, Float>> res = Lists.newArrayList();
+		String typeString;
+		if (id > 0) {
+			if (isDriver) {
+				typeString = "AND DriverId = ? ";
+			} else {
+				typeString = "AND HorseId = ? ";
+			}
+		} else {
+			typeString = "";
+		}
+
+		String trackFilter;
+		if (Strings.isNullOrEmpty(trackName)) {
+			trackFilter = "";
+		} else {
+			trackFilter = "AND TrackId = (SELECT id FROM Track WHERE name = ?) ";
+		}
+
+		final String sql = "SELECT Lane, AVG(IF(Time <= 0,30,time)) as avg FROM Results " + "WHERE distance IN (?) " + trackFilter + typeString
+				+ "AND RaceDate < ? " + "GROUP BY Lane " + "ORDER BY Lane ASC";
+
+		try {
+			final PreparedStatement stat = getConnection().prepareStatement(sql);
+			final String in = String.join(",", distances.stream().map(m -> m.toString()).collect(Collectors.toList()));
+			stat.setString(1, in);
+			if (Strings.isNullOrEmpty(trackName)) {
+				if (id > 0) {
+					stat.setInt(2, id);
+					stat.setString(3, date);
+				} else {
+					stat.setString(2, date);
+				}
+
+			} else {
+				stat.setString(2, trackName);
+				if (id > 0) {
+					stat.setInt(3, id);
+					stat.setString(4, date);
+				} else {
+					stat.setString(3, date);
+				}
+			}
+
+			final ResultSet rs = stat.executeQuery();
+			while (rs.next()) {
+				res.add(new SimpleEntry<>(rs.getInt("Lane"), rs.getFloat("avg")));
+			}
+
+		} catch (final SQLException e) {
+			e.printStackTrace();
+		}
+		return res;
+	}
+
+	public Float getTrackAvarage(String trackName, ArrayList<Integer> distances, String date, int id, boolean isDriver) {
+		Float res = 0f;
+		String typeString;
+		String distanceFilter;
+		if (id > 0) {
+			if (isDriver) {
+				typeString = "DriverId = ? AND ";
+			} else {
+				typeString = "HorseId = ? AND ";
+			}
+		} else {
+			typeString = "";
+		}
+
+		if (distances != null && !distances.isEmpty()) {
+			distanceFilter = " distance IN (?) AND ";
+		} else {
+			distanceFilter = "";
+		}
+
+		String trackFilter;
+		if (Strings.isNullOrEmpty(trackName)) {
+			trackFilter = "";
+		} else {
+			trackFilter = " TrackId = (SELECT id FROM Track WHERE name = ?) AND ";
+		}
+
+		final String sql = "SELECT AVG(IF(Time <= 0,30,time)) as avg FROM Results " + "WHERE " + typeString + distanceFilter + trackFilter
+				+ "RaceDate < ?";
+
+		try {
+			final PreparedStatement stat = getConnection().prepareStatement(sql);
+
+			if (distances != null && !distances.isEmpty()) {
+				final String in = String.join(",", distances.stream().map(m -> m.toString()).collect(Collectors.toList()));
+
+				if (Strings.isNullOrEmpty(trackName)) {
+					if (id > 0) {
+						stat.setInt(1, id);
+						stat.setString(2, in);
+						stat.setString(3, date);
+
+					} else {
+						stat.setString(1, in);
+						stat.setString(2, date);
+					}
+				} else {
+					if (id > 0) {
+						stat.setInt(1, id);
+						stat.setString(2, in);
+						stat.setString(3, trackName);
+						stat.setString(4, date);
+					} else {
+						stat.setString(1, in);
+						stat.setString(2, trackName);
+						stat.setString(3, date);
+					}
+				}
+			} else {
+				if (Strings.isNullOrEmpty(trackName)) {
+					if (id > 0) {
+						stat.setInt(1, id);
+						stat.setString(2, date);
+					} else {
+						stat.setString(1, date);
+					}
+				} else {
+					if (id > 0) {
+						stat.setInt(1, id);
+						stat.setString(2, trackName);
+						stat.setString(3, date);
+					} else {
+						stat.setString(1, trackName);
+						stat.setString(2, date);
+					}
+				}
+			}
+			final ResultSet rs = stat.executeQuery();
+			while (rs.next()) { // Om inget resultat k�r om utan track, markeras??
+				res = rs.getFloat("avg");
+			}
+
+			if (res <= 0 && !Strings.isNullOrEmpty(trackName)) {
+				res = getTrackAvarage("", distances, date, id, isDriver);
+				distances = null;
+			} else if (res <= 0 && Strings.isNullOrEmpty(trackName) && distances != null && !distances.isEmpty()) {
+				res = getTrackAvarage("", null, date, id, isDriver);
+			}
+
+		} catch (final SQLException e) {
+			e.printStackTrace();
+		}
+		return res;
+	}
+
+	public void setfullStatsCollected(String who, int travsportId, String date) {
+		String sql;
+		if ("horse".equals(who)) {
+			sql = "UPDATE Horse SET fullStatsCollected = ? WHERE travsportId = ?";
+		} else if ("driver".equals(who)) {
+			sql = "UPDATE Driver SET fullStatsCollected = ? WHERE travsportId = ?";
+		} else {
+			throw new RuntimeException("Unknown who: " + who);
+		}
+
+		try {
+			final PreparedStatement stat = getConnection().prepareStatement(sql);
+			stat.setString(1, date);
+			stat.setInt(2, travsportId);
+
+			stat.executeUpdate();
+		} catch (final SQLException e) {
+			e.printStackTrace();
+		}
+	}
+
+	public String getFullStatsCollected(String who, int travsportId) {
+		final String sql;
+		String result = null;
+		if ("horse".equals(who)) {
+			sql = "SELECT fullStatsCollected FROM Horse WHERE travsportId = ?";
+		} else if ("driver".equals(who)) {
+			sql = "SELECT fullStatsCollected FROM Driver WHERE travsportId = ?";
+		} else {
+			throw new RuntimeException("Failed to get Full stats");
+		}
+
+		try {
+			final PreparedStatement stat = getConnection().prepareStatement(sql);
+			stat.setInt(1, travsportId);
+
+			final ResultSet rs = stat.executeQuery();
+
+			while (rs.next()) {
+				result = rs.getString("fullStatsCollected");
+
+			}
+		} catch (final SQLException e) {
+			e.printStackTrace();
+		}
+
+		return result;
+	}
+
+	public void setTestRaceData(Result race) {
+		String sql = "INSERT INTO `testTable`(`driverId`, `horseId`, `resultId`, "
+				+ "`avgHorseTimeTotal`, `avgHorseTimeLast5`, `avgHorseTimeLast10`, `avgHorseTimeLast15`, "
+				+ "`avgHorseTimeTotalDistance`, `avgHorseTimeDistanceLast5`, `avgHorseTimeDistanceLast10`, `avgHorseTimeDistanceLast15`, "
+				+ "`avgHorsePosTotal`, `avgHorsePosLast5`, `avgHorsePosLast10`, `avgHorsePosLast15`, "
+				+ "`avgHorsePosDistanceTotal`, `avgHorsePosDistanceLast5`, `avgHorsePosDistanceLast10`, `avgHorsePosDistanceLast15`, "
+				+ "`avgDriverTimeTotal`, `avgDriverTimeLast5`, `avgDriverTimeLast10`, `avgDriverTimeLast15`, "
+				+ "`avgDriverTimeDistanceTotal`, `avgDriverTimeDistanceLast5`, `avgDriverTimeDistanceLast10`, `avgDriverTimeDistanceLast15`, "
+				+ "`avgDriverPosTotal`, `avgDriverPosLast5`, `avgDriverPosLast10`, `avgDriverPosLast15`, "
+				+ "`avgDriverPosDistanceTotal`, `avgDriverPosDistanceLast5`, `avgDriverPosDistanceLast10`, `avgDriverPosDistanceLast15`, "
+				+ "`avgCombinedTimeTotal`, `avgCombinedTimeLast5`, `avgCombinedTimeLast10`, `avgCombinedTimeLast15`, "
+				+ "`avgCombinedTimeDistanceTotal`, `avgCombinedTimeDistanceLast5`, `avgCombinedTimeDistanceLast10`, `avgCombinedTimeDistanceLast15`, "
+				+ "`avgCombinedPosTotal`, `avgCombinedPosLast5`, `avgCombinedPosLast10`, `avgCombinedPosLast15`, "
+				+ "`avgCombinedPosDistanceTotal`, `avgCombinedPosDistanceLast5`, `avgCombinedPosDistanceLast10`, `avgCombinedPosDistanceLast15`) "
+				+ "VALUES " + "(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
+		try (PreparedStatement stat = conn.prepareStatement(sql)) {
+			stat.setInt(1, race.getDriverId());
+			stat.setInt(2, race.getHorseId());
+			stat.setInt(3, race.getId());
+
+			// Horse
+			stat.setFloat(4, race.getAvgTimeHorseAll());
+			stat.setFloat(5, race.getAvgTimeHorseLast5());
+			stat.setFloat(6, race.getAvgTimeHorseLast10());
+			stat.setFloat(7, race.getAvgTimeHorseLast15());
+			stat.setFloat(8, race.getAvgTimeHorseDistanceAll());
+			stat.setFloat(9, race.getAvgTimeHorseDistanceLast5());
+			stat.setFloat(10, race.getAvgTimeHorseDistanceLast10());
+			stat.setFloat(11, race.getAvgTimeHorseDistanceLast15());
+
+			stat.setFloat(12, race.getAvgPositionHorseAll());
+			stat.setFloat(13, race.getAvgPositionHorseLast5());
+			stat.setFloat(14, race.getAvgPositionHorseLast10());
+			stat.setFloat(15, race.getAvgPositionHorseLast15());
+			stat.setFloat(16, race.getAvgPositionHorseDistanceAll());
+			stat.setFloat(17, race.getAvgPositionHorseDistanceLast5());
+			stat.setFloat(18, race.getAvgPositionHorseDistanceLast10());
+			stat.setFloat(19, race.getAvgPositionHorseDistanceLast15());
+
+			// Driver
+			stat.setFloat(20, race.getAvgTimeDriverAll());
+			stat.setFloat(21, race.getAvgTimeDriverLast5());
+			stat.setFloat(22, race.getAvgTimeDriverLast10());
+			stat.setFloat(23, race.getAvgTimeDriverLast15());
+			stat.setFloat(24, race.getAvgTimeDriverDistanceAll());
+			stat.setFloat(25, race.getAvgTimeDriverDistanceLast5());
+			stat.setFloat(26, race.getAvgTimeDriverDistanceLast10());
+			stat.setFloat(27, race.getAvgTimeDriverDistanceLast15());
+
+			stat.setFloat(28, race.getAvgPositionDriverAll());
+			stat.setFloat(29, race.getAvgPositionDriverLast5());
+			stat.setFloat(30, race.getAvgPositionDriverLast10());
+			stat.setFloat(31, race.getAvgPositionDriverLast15());
+			stat.setFloat(32, race.getAvgPositionDriverDistanceAll());
+			stat.setFloat(33, race.getAvgPositionDriverDistanceLast5());
+			stat.setFloat(34, race.getAvgPositionDriverDistanceLast10());
+			stat.setFloat(35, race.getAvgPositionDriverDistanceLast15());
+
+			// Combined
+			stat.setFloat(36, race.getAvgTimeCombinedAll());
+			stat.setFloat(37, race.getAvgTimeCombinedLast5());
+			stat.setFloat(38, race.getAvgTimeCombinedLast10());
+			stat.setFloat(39, race.getAvgTimeCombinedLast15());
+			stat.setFloat(40, race.getAvgTimeCombinedDistanceAll());
+			stat.setFloat(41, race.getAvgTimeCombinedDistanceLast5());
+			stat.setFloat(42, race.getAvgTimeCombinedDistanceLast10());
+			stat.setFloat(43, race.getAvgTimeCombinedDistanceLast15());
+
+			stat.setFloat(44, race.getAvgPositionCombinedAll());
+			stat.setFloat(45, race.getAvgPositionCombinedLast5());
+			stat.setFloat(46, race.getAvgPositionCombinedLast10());
+			stat.setFloat(47, race.getAvgPositionCombinedLast15());
+			stat.setFloat(48, race.getAvgPositionCombinedDistanceAll());
+			stat.setFloat(49, race.getAvgPositionCombinedDistanceLast5());
+			stat.setFloat(50, race.getAvgPositionCombinedDistanceLast10());
+			stat.setFloat(51, race.getAvgPositionCombinedDistanceLast15());
+
+			stat.execute();
+
+		} catch (SQLException e) {
+			e.printStackTrace();
+		}
+	}
 
 }

+ 704 - 68
ATG/src/controllers/TestingTabController.java

@@ -4,6 +4,10 @@ import java.io.BufferedReader;
 import java.io.FileReader;
 import java.io.IOException;
 import java.net.URL;
+import java.sql.Connection;
+import java.sql.PreparedStatement;
+import java.sql.ResultSet;
+import java.sql.SQLException;
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.Comparator;
@@ -21,6 +25,7 @@ import com.google.common.base.Strings;
 import com.google.common.collect.Lists;
 import com.google.common.collect.Maps;
 
+import javafx.event.ActionEvent;
 import javafx.fxml.FXML;
 import javafx.fxml.Initializable;
 import javafx.scene.control.Button;
@@ -28,6 +33,7 @@ import javafx.scene.control.Label;
 import javafx.scene.control.TextField;
 import javafx.scene.paint.Color;
 import objects.LaneWinObject;
+import objects.Result;
 import test.Test.CombinedSorter;
 import test.Test.customSorter;
 import test.TestDataRow;
@@ -61,13 +67,13 @@ public class TestingTabController implements Initializable {
 
 	@FXML Label horseDriverSameOrderValue;
 	@FXML Label horseDriverDistanceSameOrderValue;
-	@FXML Label AllFourBasicSameOrderValue;
-	@FXML Label AllSameOrderValue;
+	@FXML Label allFourBasicSameOrderValue;
+	@FXML Label allSameOrderValue;
 
 	@FXML TextField combineHorseWeight;
 	@FXML TextField combineDriverWeight;
 
-	//	String filename = this.getClass().getResource("../test/Atg-Results.csv").getFile();
+	// String filename =
 	String filename = this.getClass().getResource("../test/testFiles_done.csv").getFile();
 	String testDataSetFile = this.getClass().getResource("../test/dataset.csv").getFile();
 	private CSVParser parser;
@@ -81,8 +87,7 @@ public class TestingTabController implements Initializable {
 	private int correctSameHorseDriverByDistanceTotalRaces;
 	private int correctSameHorseDriver;
 
-	@Override
-	public void initialize(URL arg0, ResourceBundle arg1) {
+	@Override public void initialize(URL arg0, ResourceBundle arg1) {
 		LoadData();
 		setBestSettingFromDB();
 	}
@@ -90,39 +95,39 @@ public class TestingTabController implements Initializable {
 	private void setBestSettingFromDB() {
 		final DatabaseController database = DatabaseController.getInstance();
 		String dbValue = database.getSetting(divisorValueHorse.getId());
-		divisorValueHorse.setText(Strings.isNullOrEmpty(dbValue)?"1":dbValue);
+		divisorValueHorse.setText(Strings.isNullOrEmpty(dbValue) ? "1" : dbValue);
 		dbValue = database.getSetting(divisorValueHorse.getId() + "Value");
-		horseAvgTimePercentValue.setText(Strings.isNullOrEmpty(dbValue)?"0%":dbValue + "%");
+		horseAvgTimePercentValue.setText(Strings.isNullOrEmpty(dbValue) ? "0%" : dbValue + "%");
 
 		dbValue = database.getSetting(divisorValueHorseDistance.getId());
-		divisorValueHorseDistance.setText(Strings.isNullOrEmpty(dbValue)?"1":dbValue);
+		divisorValueHorseDistance.setText(Strings.isNullOrEmpty(dbValue) ? "1" : dbValue);
 		dbValue = database.getSetting(divisorValueHorseDistance.getId() + "Value");
-		horseAvgTimeByDistancePercentValue.setText(Strings.isNullOrEmpty(dbValue)?"0%":dbValue + "%");
+		horseAvgTimeByDistancePercentValue.setText(Strings.isNullOrEmpty(dbValue) ? "0%" : dbValue + "%");
 
 		dbValue = database.getSetting(divisorValueDriver.getId());
-		divisorValueDriver.setText(Strings.isNullOrEmpty(dbValue)?"1":dbValue);
+		divisorValueDriver.setText(Strings.isNullOrEmpty(dbValue) ? "1" : dbValue);
 		dbValue = database.getSetting(divisorValueDriver.getId() + "Value");
-		driverAvgTimePercentValue.setText(Strings.isNullOrEmpty(dbValue)?"0%":dbValue + "%");
+		driverAvgTimePercentValue.setText(Strings.isNullOrEmpty(dbValue) ? "0%" : dbValue + "%");
 
 		dbValue = database.getSetting(divisorValueDriverDistance.getId());
-		divisorValueDriverDistance.setText(Strings.isNullOrEmpty(dbValue)?"1":dbValue);
+		divisorValueDriverDistance.setText(Strings.isNullOrEmpty(dbValue) ? "1" : dbValue);
 		dbValue = database.getSetting(divisorValueDriverDistance.getId() + "Value");
-		driverAvgTimeByDistancePercentValue.setText(Strings.isNullOrEmpty(dbValue)?"0%": dbValue + "%");
+		driverAvgTimeByDistancePercentValue.setText(Strings.isNullOrEmpty(dbValue) ? "0%" : dbValue + "%");
 
 		dbValue = database.getSetting(divisorValueCustom.getId());
-		divisorValueCustom.setText(Strings.isNullOrEmpty(dbValue)?"1":dbValue);
+		divisorValueCustom.setText(Strings.isNullOrEmpty(dbValue) ? "1" : dbValue);
 		dbValue = database.getSetting(divisorValueCustom.getId() + "Value");
-		customPercentageValue.setText(Strings.isNullOrEmpty(dbValue)?"0%":dbValue + "%");
+		customPercentageValue.setText(Strings.isNullOrEmpty(dbValue) ? "0%" : dbValue + "%");
 
 		dbValue = database.getSetting(divisorValueCombined.getId());
-		divisorValueCombined.setText(Strings.isNullOrEmpty(dbValue)?"1":dbValue);
+		divisorValueCombined.setText(Strings.isNullOrEmpty(dbValue) ? "1" : dbValue);
 		dbValue = database.getSetting(divisorValueCombined.getId() + "Value");
-		combinedPercentageValue.setText(Strings.isNullOrEmpty(dbValue)?"0%":dbValue + "%");
+		combinedPercentageValue.setText(Strings.isNullOrEmpty(dbValue) ? "0%" : dbValue + "%");
 
 		dbValue = database.getSetting(combineHorseWeight.getId());
-		combineHorseWeight.setText(Strings.isNullOrEmpty(dbValue)?"1":dbValue);
+		combineHorseWeight.setText(Strings.isNullOrEmpty(dbValue) ? "1" : dbValue);
 		dbValue = database.getSetting(combineDriverWeight.getId());
-		combineDriverWeight.setText(Strings.isNullOrEmpty(dbValue)?"1":dbValue);
+		combineDriverWeight.setText(Strings.isNullOrEmpty(dbValue) ? "1" : dbValue);
 
 	}
 
@@ -142,8 +147,7 @@ public class TestingTabController implements Initializable {
 		}
 	}
 
-	@FXML
-	public void CalculateAction() {
+	@FXML public void CalculateAction() {
 		ReadTestData();
 		getPercentagesOrderedBy(Integer.valueOf(topCountTextField.getText()));
 	}
@@ -176,7 +180,8 @@ public class TestingTabController implements Initializable {
 		try {
 			if (autostart) {
 				if (autostartWinPercentages.containsKey(distances)) {
-					final Optional<LaneWinObject> entry = autostartWinPercentages.get(distances).stream().filter(p -> p.getLane() == lane && p.getDistance() == distance).findFirst();
+					final Optional<LaneWinObject> entry = autostartWinPercentages.get(distances).stream()
+							.filter(p -> p.getLane() == lane && p.getDistance() == distance).findFirst();
 
 					if (entry.isPresent()) {
 						returnValue = entry.get().getPercent();
@@ -185,10 +190,10 @@ public class TestingTabController implements Initializable {
 					}
 				} else {
 
-
 					final List<LaneWinObject> autostartWinPercents = DatabaseController.getInstance().getAutostartWinPercents(distances);
 					autostartWinPercentages.put(distances, autostartWinPercents);
-					final Optional<LaneWinObject> lw = autostartWinPercentages.get(distances).stream().filter(p -> p.getLane() == lane && p.getDistance() == distance).findFirst();
+					final Optional<LaneWinObject> lw = autostartWinPercentages.get(distances).stream()
+							.filter(p -> p.getLane() == lane && p.getDistance() == distance).findFirst();
 					if (lw.isPresent()) {
 						returnValue = lw.get().getPercent();
 					} else {
@@ -198,7 +203,8 @@ public class TestingTabController implements Initializable {
 				}
 			} else {
 				if (voltstartWinPercentages.containsKey(distances)) {
-					final Optional<LaneWinObject> entry = voltstartWinPercentages.get(distances).stream().filter(p -> p.getDistance() == distance && p.getLane() == lane).findFirst();
+					final Optional<LaneWinObject> entry = voltstartWinPercentages.get(distances).stream()
+							.filter(p -> p.getDistance() == distance && p.getLane() == lane).findFirst();
 					if (entry.isPresent()) {
 						returnValue = entry.get().getPercent();
 					} else {
@@ -209,7 +215,8 @@ public class TestingTabController implements Initializable {
 					final List<LaneWinObject> percentages = DatabaseController.getInstance().getVoltstartWinPercents(distances);
 					voltstartWinPercentages.put(distances, percentages);
 
-					final Optional<LaneWinObject> lw = voltstartWinPercentages.get(distances).stream().filter(p -> p.getDistance() == distance && p.getLane() == lane).findFirst();
+					final Optional<LaneWinObject> lw = voltstartWinPercentages.get(distances).stream()
+							.filter(p -> p.getDistance() == distance && p.getLane() == lane).findFirst();
 					if (lw.isPresent()) {
 						returnValue = lw.get().getPercent();
 					} else {
@@ -227,12 +234,11 @@ public class TestingTabController implements Initializable {
 
 	public void getPercentagesOrderedBy(int topCount) {
 		// sort by RaceDate, TrackId, RaceNumber
-		Collections.sort(dbDumpTestData, new TestDataRow.RaceDateSorter()
-				.thenComparing(new TestDataRow.TrackIdSorter())
-				.thenComparing(new TestDataRow.RaceNumberSorter()));
+		Collections.sort(dbDumpTestData,
+				new TestDataRow.RaceDateSorter().thenComparing(new TestDataRow.TrackIdSorter()).thenComparing(new TestDataRow.RaceNumberSorter()));
 
 		int correctHorseByDistance = 0;
-		int correctHorse= 0;
+		int correctHorse = 0;
 		int correctDriver = 0;
 		int correctDriverByDistance = 0;
 		int correctCustom = 0;
@@ -249,12 +255,10 @@ public class TestingTabController implements Initializable {
 		final int correctSameAllFourTotalRaces = 0;
 		final int correctSameAllTotalRaces = 0;
 
-
 		for (int i = 0; i < dbDumpTestData.size(); i++) {
 			final TestDataRow firstRow = dbDumpTestData.get(i);
-			final List<TestDataRow> currentRaces = dbDumpTestData.stream().filter(d -> firstRow.getRaceDate().equals(d.getRaceDate()) &&
-					firstRow.getTrackId() == d.getTrackId() &&
-					firstRow.getRaceNumber() == d.getRaceNumber()).collect(Collectors.toList());
+			final List<TestDataRow> currentRaces = dbDumpTestData.stream().filter(d -> firstRow.getRaceDate().equals(d.getRaceDate())
+					&& firstRow.getTrackId() == d.getTrackId() && firstRow.getRaceNumber() == d.getRaceNumber()).collect(Collectors.toList());
 
 			if (currentRaces.size() < 7) { // Not enough info
 				continue;
@@ -264,7 +268,7 @@ public class TestingTabController implements Initializable {
 
 			currentRaces.forEach(cr -> {
 				final String distance = String.valueOf(cr.getDistance());
-				if(!distances.contains(distance)) {
+				if (!distances.contains(distance)) {
 					distances.add(distance);
 				}
 			});
@@ -292,20 +296,21 @@ public class TestingTabController implements Initializable {
 				combinedRaces.add(cr);
 			}
 
-
 			racesCount++;
 
 			horseRaces.forEach(cr -> cr.setLaneWinDivisor(Float.valueOf(divisorValueHorse.getText())));
 			correctHorse = checkIfCorrect(topCount, correctHorse, horseRaces, new TestDataRow.horseAvgTimeSorter());
 
 			horseDistanceRaces.forEach(cr -> cr.setLaneWinDivisor(Float.valueOf(divisorValueHorseDistance.getText())));
-			correctHorseByDistance = checkIfCorrect(topCount, correctHorseByDistance, horseDistanceRaces, new TestDataRow.horseAvgTimeByDistanceSorter());
+			correctHorseByDistance = checkIfCorrect(topCount, correctHorseByDistance, horseDistanceRaces,
+					new TestDataRow.horseAvgTimeByDistanceSorter());
 
 			driverRaces.forEach(cr -> cr.setLaneWinDivisor(Float.valueOf(divisorValueDriver.getText())));
 			correctDriver = checkIfCorrect(topCount, correctDriver, driverRaces, new TestDataRow.driverAvgTimeSorter());
 
 			driverDistanceRaces.forEach(cr -> cr.setLaneWinDivisor(Float.valueOf(divisorValueDriverDistance.getText())));
-			correctDriverByDistance = checkIfCorrect(topCount, correctDriverByDistance, driverDistanceRaces, new TestDataRow.driverAvgTimeByDistanceSorter());
+			correctDriverByDistance = checkIfCorrect(topCount, correctDriverByDistance, driverDistanceRaces,
+					new TestDataRow.driverAvgTimeByDistanceSorter());
 
 			customRaces.forEach(cr -> cr.setLaneWinDivisor(Float.valueOf(divisorValueCustom.getText())));
 			correctCustom = checkIfCorrect(topCount, correctCustom, customRaces, new customSorter());
@@ -321,54 +326,52 @@ public class TestingTabController implements Initializable {
 			i = i + currentRaces.size();
 		}
 
-		System.out.println("TESTING hr dr combined bet on " + correctSameHorseDriverTotalRaces + " of " +
-				racesCount + " correct " + correctSameHorseDriver +  " " + correctSameHorseDriver / (correctSameHorseDriverTotalRaces * 1f));
+		System.out.println("TESTING hr dr combined bet on " + correctSameHorseDriverTotalRaces + " of " + racesCount + " correct "
+				+ correctSameHorseDriver + " " + correctSameHorseDriver / (correctSameHorseDriverTotalRaces * 1f));
 		updateTextColor(correctHorse, racesCount, horseAvgTimePercentValue);
 		if (horseAvgTimePercentValue.getTextFill().equals(Color.GREEN)) {
-			updateTextFieldSetting(divisorValueHorse, correctHorse/(racesCount * 1f) * 100);
+			updateTextFieldSetting(divisorValueHorse, correctHorse / (racesCount * 1f) * 100);
 		}
-		//		updateTextColor(correctHorse, racesCount, horseAvgTimePercentText);
+		// updateTextColor(correctHorse, racesCount, horseAvgTimePercentText);
 
 		updateTextColor(correctHorseByDistance, racesCount, horseAvgTimeByDistancePercentValue);
 		if (horseAvgTimeByDistancePercentValue.getTextFill().equals(Color.GREEN)) {
-			updateTextFieldSetting(divisorValueHorseDistance, correctHorseByDistance/(racesCount * 1f) * 100);
+			updateTextFieldSetting(divisorValueHorseDistance, correctHorseByDistance / (racesCount * 1f) * 100);
 		}
-		//		updateTextColor(correctHorse, racesCount, horseAvgTimePercentText);
+		// updateTextColor(correctHorse, racesCount, horseAvgTimePercentText);
 
 		updateTextColor(correctDriver, racesCount, driverAvgTimePercentValue);
 		if (driverAvgTimePercentValue.getTextFill().equals(Color.GREEN)) {
-			updateTextFieldSetting(divisorValueDriver, correctDriver/(racesCount * 1f) * 100);
+			updateTextFieldSetting(divisorValueDriver, correctDriver / (racesCount * 1f) * 100);
 		}
-		//		updateTextColor(correctHorse, racesCount, horseAvgTimePercentText);
+		// updateTextColor(correctHorse, racesCount, horseAvgTimePercentText);
 
 		updateTextColor(correctDriverByDistance, racesCount, driverAvgTimeByDistancePercentValue);
 		if (driverAvgTimeByDistancePercentValue.getTextFill().equals(Color.GREEN)) {
-			updateTextFieldSetting(divisorValueDriverDistance, correctDriverByDistance/(racesCount * 1f) * 100);
+			updateTextFieldSetting(divisorValueDriverDistance, correctDriverByDistance / (racesCount * 1f) * 100);
 		}
-		//		updateTextColor(correctHorse, racesCount, horseAvgTimePercentText);
+		// updateTextColor(correctHorse, racesCount, horseAvgTimePercentText);
 
 		updateTextColor(correctCustom, racesCount, customPercentageValue);
 		if (customPercentageValue.getTextFill().equals(Color.GREEN)) {
-			updateTextFieldSetting(divisorValueCustom, correctCustom/(racesCount * 1f) * 100);
+			updateTextFieldSetting(divisorValueCustom, correctCustom / (racesCount * 1f) * 100);
 		}
-		//		updateTextColor(correctHorse, racesCount, horseAvgTimePercentText);
+		// updateTextColor(correctHorse, racesCount, horseAvgTimePercentText);
 
 		updateTextColor(correctCombined, racesCount, combinedPercentageValue);
-		final float combinedResultValue = correctCombined/(racesCount * 1f) * 100;
+		final float combinedResultValue = correctCombined / (racesCount * 1f) * 100;
 		if (combinedPercentageValue.getTextFill().equals(Color.GREEN)) {
 			updateTextFieldSetting(divisorValueCombined, combinedResultValue);
 			updateTextFieldSetting(combineHorseWeight, combinedResultValue);
 			updateTextFieldSetting(combineDriverWeight, combinedResultValue);
 		}
-		//		updateTextColor(correctHorse, racesCount, horseAvgTimePercentText);
-
+		// updateTextColor(correctHorse, racesCount, horseAvgTimePercentText);
 
-
-		horseAvgTimePercentValue.setText(String.valueOf(correctHorse/(racesCount * 1f) * 100) + "%");
-		horseAvgTimeByDistancePercentValue.setText(String.valueOf(correctHorseByDistance/(racesCount * 1f) * 100) + "%");
-		driverAvgTimePercentValue.setText(String.valueOf(correctDriver/(racesCount * 1f) * 100) + "%");
-		driverAvgTimeByDistancePercentValue.setText(String.valueOf(correctDriverByDistance/(racesCount * 1f) * 100) + "%");
-		customPercentageValue.setText(String.valueOf(correctCustom/(racesCount * 1f) * 100) + "%");
+		horseAvgTimePercentValue.setText(String.valueOf(correctHorse / (racesCount * 1f) * 100) + "%");
+		horseAvgTimeByDistancePercentValue.setText(String.valueOf(correctHorseByDistance / (racesCount * 1f) * 100) + "%");
+		driverAvgTimePercentValue.setText(String.valueOf(correctDriver / (racesCount * 1f) * 100) + "%");
+		driverAvgTimeByDistancePercentValue.setText(String.valueOf(correctDriverByDistance / (racesCount * 1f) * 100) + "%");
+		customPercentageValue.setText(String.valueOf(correctCustom / (racesCount * 1f) * 100) + "%");
 		combinedPercentageValue.setText(String.valueOf(combinedResultValue) + "%");
 
 	}
@@ -379,19 +382,19 @@ public class TestingTabController implements Initializable {
 		currentRaces.sort(new TestDataRow.horseAvgTimeSorter());
 		List<TestDataRow> horseSorted = Lists.newArrayList(currentRaces);
 
-
-
 		currentRaces.forEach(hr -> hr.setLaneWinDivisor(Float.valueOf(divisorValueDriver.getText())));
 		currentRaces.sort(new TestDataRow.driverAvgTimeSorter());
 		final List<TestDataRow> driverSorted = Lists.newArrayList(currentRaces);
 
-		final int maxSelect = horseSorted.size() - 1 >= Integer.parseInt(topCountTextField.getText())?Integer.parseInt(topCountTextField.getText()):horseSorted.size() - 1;
+		final int maxSelect = horseSorted.size() - 1 >= Integer.parseInt(topCountTextField.getText()) ? Integer.parseInt(topCountTextField.getText())
+				: horseSorted.size() - 1;
 		horseSorted = horseSorted.subList(0, maxSelect);
 		final List<TestDataRow> driverSortedFiltered = driverSorted.subList(0, maxSelect);
 
 		// disjoint Returns true if no matches
 		if (!Collections.disjoint(horseSorted, driverSorted)) {
-			//			final List<TestDataRow> same = horseSorted.stream().filter(hs -> driverSortedFiltered.contains(hs)).collect(Collectors.toList());
+			// final List<TestDataRow> same = horseSorted.stream().filter(hs ->
+			// driverSortedFiltered.contains(hs)).collect(Collectors.toList());
 			final List<TestDataRow> same = Lists.newArrayList();
 			final Integer topCount = maxSelect;
 			for (int i = 0; i < topCount; i++) {
@@ -399,14 +402,14 @@ public class TestingTabController implements Initializable {
 					same.add(horseSorted.get(i));
 				}
 			}
-			//			if (same.size() == topCount) {
+			// if (same.size() == topCount) {
 			for (final TestDataRow testDataRow : same) {
 				if (testDataRow.getResult() == 1) {
 					correctSameHorseDriver++;
 				}
 				correctSameHorseDriverTotalRaces++;
 			}
-			//			}
+			// }
 		} else {
 			System.out.println("No bet, horse and driver lists not the same");
 
@@ -429,7 +432,7 @@ public class TestingTabController implements Initializable {
 	private void updateTextColor(int correct, int totalRaces, Label textLabel) {
 
 		final float prevValue = Float.valueOf(textLabel.getText().substring(0, textLabel.getText().length() - 1));
-		final float newValue = correct/(totalRaces * 1f) * 100;
+		final float newValue = correct / (totalRaces * 1f) * 100;
 
 		if (prevValue < newValue) {
 			textLabel.setTextFill(Color.GREEN);
@@ -452,8 +455,641 @@ public class TestingTabController implements Initializable {
 		return correct;
 	}
 
-	@FXML
-	public void resetSettingsAction() {
+	@FXML public void resetSettingsAction() {
 		setBestSettingFromDB();
 	}
+
+	@SuppressWarnings("squid:S106")
+	@FXML public void testBestValue(ActionEvent event) {
+		int numberOfPositionsToConsider = 2;
+
+		String sql = "SELECT * FROM Results r INNER JOIN testTable tt ON r.id = tt.resultId";
+		List<Result> results = new ArrayList<>();
+		try (PreparedStatement stat = DatabaseController.getInstance().getConnection().prepareStatement(sql)) {
+			ResultSet rs = stat.executeQuery();
+
+			while (rs.next()) {
+				Result res = new Result(rs.getInt("id"), rs.getInt("TrackId"), rs.getString("RaceDate"), rs.getString("RaceType"),
+						rs.getInt("RaceNumber"), rs.getInt("Lane"), rs.getInt("Distance"), rs.getInt("Result"), rs.getFloat("Time"),
+						rs.getString("TimeModifier"), rs.getInt("Shoes"), rs.getInt("Sulky"), rs.getInt("DriverId"), rs.getInt("TrainerId"),
+						rs.getInt("HorseId"), rs.getInt("raceId"));
+
+				res.setAvreges(rs.getFloat("avgDriverTimeTotal"), rs.getFloat("avgDriverTimeLast5"), rs.getFloat("avgDriverTimeLast10"),
+						rs.getFloat("avgDriverTimeLast15"), rs.getFloat("avgDriverTimeDistanceTotal"), rs.getFloat("avgDriverTimeDistanceLast5"),
+						rs.getFloat("avgDriverTimeDistanceLast10"), rs.getFloat("avgDriverTimeDistanceLast15"), rs.getFloat("avgHorseTimeTotal"),
+						rs.getFloat("avgHorseTimeLast5"), rs.getFloat("avgHorseTimeLast10"), rs.getFloat("avgHorseTimeLast15"),
+						rs.getFloat("avgHorseTimeTotalDistance"), rs.getFloat("avgHorseTimeDistanceLast5"), rs.getFloat("avgHorseTimeDistanceLast10"),
+						rs.getFloat("avgHorseTimeDistanceLast15"), rs.getFloat("avgCombinedTimeTotal"), rs.getFloat("avgCombinedTimeLast5"),
+						rs.getFloat("avgCombinedTimeLast10"), rs.getFloat("avgCombinedTimeLast15"), rs.getFloat("avgCombinedTimeDistanceTotal"),
+						rs.getFloat("avgCombinedTimeDistanceLast5"), rs.getFloat("avgCombinedTimeDistanceLast10"),
+						rs.getFloat("avgCombinedTimeDistanceLast15"), rs.getFloat("avgDriverPosTotal"), rs.getFloat("avgDriverPosLast5"),
+						rs.getFloat("avgDriverPosLast10"), rs.getFloat("avgDriverPosLast15"), rs.getFloat("avgDriverPosDistanceTotal"),
+						rs.getFloat("avgDriverPosDistanceLast5"), rs.getFloat("avgDriverPosDistanceLast10"),
+						rs.getFloat("avgDriverPosDistanceLast15"), rs.getFloat("avgHorsePosTotal"), rs.getFloat("avgHorsePosLast5"),
+						rs.getFloat("avgHorsePosLast10"), rs.getFloat("avgHorsePosLast15"), rs.getFloat("avgHorsePosDistanceTotal"),
+						rs.getFloat("avgHorsePosDistanceLast5"), rs.getFloat("avgHorsePosDistanceLast10"), rs.getFloat("avgHorsePosDistanceLast15"),
+						rs.getFloat("avgCombinedPosTotal"), rs.getFloat("avgCombinedPosLast5"), rs.getFloat("avgCombinedPosLast10"),
+						rs.getFloat("avgCombinedPosLast15"), rs.getFloat("avgCombinedPosDistanceTotal"), rs.getFloat("avgCombinedPosDistanceLast5"),
+						rs.getFloat("avgCombinedPosDistanceLast10"), rs.getFloat("avgCombinedPosDistanceLast15"));
+				results.add(res);
+			}
+		} catch (SQLException e) {
+			e.printStackTrace();
+		}
+
+		HashMap<String, Integer> totals = new HashMap<>();
+		for (int i = 0; i < results.size(); i++) {
+			final int pos = i;
+			List<Result> thisRace = results
+					.stream().filter(p -> p.getRaceDate().equals(results.get(pos).getRaceDate())
+							&& p.getRaceNumber() == results.get(pos).getRaceNumber() && p.getTrackId() == results.get(pos).getTrackId())
+					.collect(Collectors.toList());
+
+			if (thisRace.size() > 6) {
+				List<Result> avgTimeHorseAllSorted = thisRace.stream()
+						.sorted((r1, r2) -> Float.compare(r1.getAvgTimeHorseAll(), r2.getAvgTimeHorseAll())).collect(Collectors.toList());
+				List<Result> avgTimeHorseLast5Sorted = thisRace.stream()
+						.sorted((r1, r2) -> Float.compare(r1.getAvgTimeHorseLast5(), r2.getAvgTimeHorseLast5())).collect(Collectors.toList());
+				List<Result> avgTimeHorseLast10Sorted = thisRace.stream()
+						.sorted((r1, r2) -> Float.compare(r1.getAvgTimeHorseLast10(), r2.getAvgTimeHorseLast10())).collect(Collectors.toList());
+				List<Result> avgTimeHorseLast15Sorted = thisRace.stream()
+						.sorted((r1, r2) -> Float.compare(r1.getAvgTimeHorseLast15(), r2.getAvgTimeHorseLast15())).collect(Collectors.toList());
+				List<Result> avgTimeHorseDistanceAllSorted = thisRace.stream()
+						.sorted((r1, r2) -> Float.compare(r1.getAvgTimeHorseDistanceAll(), r2.getAvgTimeHorseDistanceAll()))
+						.collect(Collectors.toList());
+				List<Result> avgTimeHorseDistanceLast5Sorted = thisRace.stream()
+						.sorted((r1, r2) -> Float.compare(r1.getAvgTimeHorseDistanceLast5(), r2.getAvgTimeHorseDistanceLast5()))
+						.collect(Collectors.toList());
+				List<Result> avgTimeHorseDistanceLast10Sorted = thisRace.stream()
+						.sorted((r1, r2) -> Float.compare(r1.getAvgTimeHorseDistanceLast10(), r2.getAvgTimeHorseDistanceLast10()))
+						.collect(Collectors.toList());
+				List<Result> avgTimeHorseDistanceLast15Sorted = thisRace.stream()
+						.sorted((r1, r2) -> Float.compare(r1.getAvgTimeHorseDistanceLast15(), r2.getAvgTimeHorseDistanceLast15()))
+						.collect(Collectors.toList());
+				List<Result> avgTimeDriverAllSorted = thisRace.stream()
+						.sorted((r1, r2) -> Float.compare(r1.getAvgTimeDriverAll(), r2.getAvgTimeDriverAll())).collect(Collectors.toList());
+				List<Result> avgTimeDriverLast5Sorted = thisRace.stream()
+						.sorted((r1, r2) -> Float.compare(r1.getAvgTimeDriverLast5(), r2.getAvgTimeDriverLast5())).collect(Collectors.toList());
+				List<Result> avgTimeDriverLast10Sorted = thisRace.stream()
+						.sorted((r1, r2) -> Float.compare(r1.getAvgTimeDriverLast10(), r2.getAvgTimeDriverLast10())).collect(Collectors.toList());
+				List<Result> avgTimeDriverLast15Sorted = thisRace.stream()
+						.sorted((r1, r2) -> Float.compare(r1.getAvgTimeDriverLast15(), r2.getAvgTimeDriverLast15())).collect(Collectors.toList());
+				List<Result> avgTimeDriverDistanceAllSorted = thisRace.stream()
+						.sorted((r1, r2) -> Float.compare(r1.getAvgTimeDriverDistanceAll(), r2.getAvgTimeDriverDistanceAll()))
+						.collect(Collectors.toList());
+				List<Result> avgTimeDriverDistanceLast5Sorted = thisRace.stream()
+						.sorted((r1, r2) -> Float.compare(r1.getAvgTimeDriverDistanceLast5(), r2.getAvgTimeDriverDistanceLast5()))
+						.collect(Collectors.toList());
+				List<Result> avgTimeDriverDistanceLast10Sorted = thisRace.stream()
+						.sorted((r1, r2) -> Float.compare(r1.getAvgTimeDriverDistanceLast10(), r2.getAvgTimeDriverDistanceLast10()))
+						.collect(Collectors.toList());
+				List<Result> avgTimeDriverDistanceLast15Sorted = thisRace.stream()
+						.sorted((r1, r2) -> Float.compare(r1.getAvgTimeDriverDistanceLast15(), r2.getAvgTimeDriverDistanceLast15()))
+						.collect(Collectors.toList());
+				List<Result> avgTimeCombinedAllSorted = thisRace.stream()
+						.sorted((r1, r2) -> Float.compare(r1.getAvgTimeCombinedAll(), r2.getAvgTimeCombinedAll())).collect(Collectors.toList());
+				List<Result> avgTimeCombinedLast5Sorted = thisRace.stream()
+						.sorted((r1, r2) -> Float.compare(r1.getAvgTimeCombinedLast5(), r2.getAvgTimeCombinedLast5())).collect(Collectors.toList());
+				List<Result> avgTimeCombinedLast10Sorted = thisRace.stream()
+						.sorted((r1, r2) -> Float.compare(r1.getAvgTimeCombinedLast10(), r2.getAvgTimeCombinedLast10())).collect(Collectors.toList());
+				List<Result> avgTimeCombinedLast15Sorted = thisRace.stream()
+						.sorted((r1, r2) -> Float.compare(r1.getAvgTimeCombinedLast15(), r2.getAvgTimeCombinedLast15())).collect(Collectors.toList());
+				List<Result> avgTimeCombinedDistanceAllSorted = thisRace.stream()
+						.sorted((r1, r2) -> Float.compare(r1.getAvgTimeCombinedDistanceAll(), r2.getAvgTimeCombinedDistanceAll()))
+						.collect(Collectors.toList());
+				List<Result> avgTimeCombinedDistanceLast5Sorted = thisRace.stream()
+						.sorted((r1, r2) -> Float.compare(r1.getAvgTimeCombinedDistanceLast5(), r2.getAvgTimeCombinedDistanceLast5()))
+						.collect(Collectors.toList());
+				List<Result> avgTimeCombinedDistanceLast10Sorted = thisRace.stream()
+						.sorted((r1, r2) -> Float.compare(r1.getAvgTimeCombinedDistanceLast10(), r2.getAvgTimeCombinedDistanceLast10()))
+						.collect(Collectors.toList());
+				List<Result> avgTimeCombinedDistanceLast15Sorted = thisRace.stream()
+						.sorted((r1, r2) -> Float.compare(r1.getAvgTimeCombinedDistanceLast15(), r2.getAvgTimeCombinedDistanceLast15()))
+						.collect(Collectors.toList());
+				List<Result> avgPositionHorseAllSorted = thisRace.stream()
+						.sorted((r1, r2) -> Float.compare(r1.getAvgPositionHorseAll(), r2.getAvgPositionHorseAll())).collect(Collectors.toList());
+				List<Result> avgPositionHorseLast5Sorted = thisRace.stream()
+						.sorted((r1, r2) -> Float.compare(r1.getAvgPositionHorseLast5(), r2.getAvgPositionHorseLast5())).collect(Collectors.toList());
+				List<Result> avgPositionHorseLast10Sorted = thisRace.stream()
+						.sorted((r1, r2) -> Float.compare(r1.getAvgPositionHorseLast10(), r2.getAvgPositionHorseLast10()))
+						.collect(Collectors.toList());
+				List<Result> avgPositionHorseLast15Sorted = thisRace.stream()
+						.sorted((r1, r2) -> Float.compare(r1.getAvgPositionHorseLast15(), r2.getAvgPositionHorseLast15()))
+						.collect(Collectors.toList());
+				List<Result> avgPositionHorseDistanceAllSorted = thisRace.stream()
+						.sorted((r1, r2) -> Float.compare(r1.getAvgPositionHorseDistanceAll(), r2.getAvgPositionHorseDistanceAll()))
+						.collect(Collectors.toList());
+				List<Result> avgPostioinHorseDistanceLast5Sorted = thisRace.stream()
+						.sorted((r1, r2) -> Float.compare(r1.getAvgPositionHorseDistanceLast5(), r2.getAvgPositionHorseDistanceLast5()))
+						.collect(Collectors.toList());
+				List<Result> avgPositionHorseDistanceLast10Sorted = thisRace.stream()
+						.sorted((r1, r2) -> Float.compare(r1.getAvgPositionHorseDistanceLast10(), r2.getAvgPositionHorseDistanceLast10()))
+						.collect(Collectors.toList());
+				List<Result> avgPositionHorseDistanceLast15Sorted = thisRace.stream()
+						.sorted((r1, r2) -> Float.compare(r1.getAvgPositionHorseDistanceLast15(), r2.getAvgPositionHorseDistanceLast15()))
+						.collect(Collectors.toList());
+				List<Result> avgPositionDriverAllSorted = thisRace.stream()
+						.sorted((r1, r2) -> Float.compare(r1.getAvgPositionDriverAll(), r2.getAvgPositionDriverAll())).collect(Collectors.toList());
+				List<Result> avgPositionDriverLast5Sorted = thisRace.stream()
+						.sorted((r1, r2) -> Float.compare(r1.getAvgPositionDriverLast5(), r2.getAvgPositionDriverLast5()))
+						.collect(Collectors.toList());
+				List<Result> avgPositionDriverLast10Sorted = thisRace.stream()
+						.sorted((r1, r2) -> Float.compare(r1.getAvgPositionDriverLast10(), r2.getAvgPositionDriverLast10()))
+						.collect(Collectors.toList());
+				List<Result> avgPositionDriverLast15Sorted = thisRace.stream()
+						.sorted((r1, r2) -> Float.compare(r1.getAvgPositionDriverLast15(), r2.getAvgPositionDriverLast15()))
+						.collect(Collectors.toList());
+				List<Result> avgPositionDriverDistanceAllSorted = thisRace.stream()
+						.sorted((r1, r2) -> Float.compare(r1.getAvgPositionDriverDistanceAll(), r2.getAvgPositionDriverDistanceAll()))
+						.collect(Collectors.toList());
+				List<Result> avgPositionDriverDistanceLast5Sorted = thisRace.stream()
+						.sorted((r1, r2) -> Float.compare(r1.getAvgPositionDriverDistanceLast5(), r2.getAvgPositionDriverDistanceLast5()))
+						.collect(Collectors.toList());
+				List<Result> avgPositionDriverDistanceLast10Sorted = thisRace.stream()
+						.sorted((r1, r2) -> Float.compare(r1.getAvgPositionDriverDistanceLast10(), r2.getAvgPositionDriverDistanceLast10()))
+						.collect(Collectors.toList());
+				List<Result> avgPositionDriverDistanceLast15Sorted = thisRace.stream()
+						.sorted((r1, r2) -> Float.compare(r1.getAvgPositionDriverDistanceLast15(), r2.getAvgPositionDriverDistanceLast15()))
+						.collect(Collectors.toList());
+				List<Result> avgPositionCombinedAllSorted = thisRace.stream()
+						.sorted((r1, r2) -> Float.compare(r1.getAvgPositionCombinedAll(), r2.getAvgPositionCombinedAll()))
+						.collect(Collectors.toList());
+				List<Result> avgPositionCombinedLast5Sorted = thisRace.stream()
+						.sorted((r1, r2) -> Float.compare(r1.getAvgPositionCombinedLast5(), r2.getAvgPositionCombinedLast5()))
+						.collect(Collectors.toList());
+				List<Result> avgPositionCombinedLast10Sorted = thisRace.stream()
+						.sorted((r1, r2) -> Float.compare(r1.getAvgPositionCombinedLast10(), r2.getAvgPositionCombinedLast10()))
+						.collect(Collectors.toList());
+				List<Result> avgPositionCombinedLast15Sorted = thisRace.stream()
+						.sorted((r1, r2) -> Float.compare(r1.getAvgPositionCombinedLast15(), r2.getAvgPositionCombinedLast15()))
+						.collect(Collectors.toList());
+				List<Result> avgPositionCombinedDistanceAllSorted = thisRace.stream()
+						.sorted((r1, r2) -> Float.compare(r1.getAvgPositionCombinedDistanceAll(), r2.getAvgPositionCombinedDistanceAll()))
+						.collect(Collectors.toList());
+				List<Result> avgPositionCombinedDistanceLast5Sorted = thisRace.stream()
+						.sorted((r1, r2) -> Float.compare(r1.getAvgPositionCombinedDistanceLast5(), r2.getAvgPositionCombinedDistanceLast5()))
+						.collect(Collectors.toList());
+				List<Result> avgPositionCombinedDistanceLast10Sorted = thisRace.stream()
+						.sorted((r1, r2) -> Float.compare(r1.getAvgPositionCombinedDistanceLast10(), r2.getAvgPositionCombinedDistanceLast10()))
+						.collect(Collectors.toList());
+				List<Result> avtPositionCombinedDistanceLast15Sorted = thisRace.stream()
+						.sorted((r1, r2) -> Float.compare(r1.getAvgPositionCombinedDistanceLast15(), r2.getAvgPositionCombinedDistanceLast15()))
+						.collect(Collectors.toList());
+
+				checkIfWinner(totals, avgTimeHorseAllSorted, numberOfPositionsToConsider, "AvgTimeHorseAll");
+				checkIfWinner(totals, avgTimeHorseLast5Sorted, numberOfPositionsToConsider, "AvgTimeHorseLast5");
+				checkIfWinner(totals, avgTimeHorseLast10Sorted, numberOfPositionsToConsider, "AvgTimeHorseLast10");
+				checkIfWinner(totals, avgTimeHorseLast15Sorted, numberOfPositionsToConsider, "AvgTimeHorseLast15");
+				checkIfWinner(totals, avgTimeHorseDistanceAllSorted, numberOfPositionsToConsider, "AvgTimeHorseDistanceAll");
+				checkIfWinner(totals, avgTimeHorseDistanceLast5Sorted, numberOfPositionsToConsider, "AvgTimeHorseDistanceLast5");
+				checkIfWinner(totals, avgTimeHorseDistanceLast10Sorted, numberOfPositionsToConsider, "AvgTimeHorseDistanceLast10");
+				checkIfWinner(totals, avgTimeHorseDistanceLast15Sorted, numberOfPositionsToConsider, "AvgTimeHorseDistanceLast15");
+				checkIfWinner(totals, avgTimeDriverAllSorted, numberOfPositionsToConsider, "AvgTimeDriverAll");
+				checkIfWinner(totals, avgTimeDriverLast5Sorted, numberOfPositionsToConsider, "AvgTimeDriverLast5");
+				checkIfWinner(totals, avgTimeDriverLast10Sorted, numberOfPositionsToConsider, "AvgTimeDriverLast10");
+				checkIfWinner(totals, avgTimeDriverLast15Sorted, numberOfPositionsToConsider, "AvgTimeDriverLast15");
+				checkIfWinner(totals, avgTimeDriverDistanceAllSorted, numberOfPositionsToConsider, "AvgTimeDriverDistanceAll");
+				checkIfWinner(totals, avgTimeDriverDistanceLast5Sorted, numberOfPositionsToConsider, "AvgTimeDriverDistanceLast5");
+				checkIfWinner(totals, avgTimeDriverDistanceLast10Sorted, numberOfPositionsToConsider, "AvgTimeDriverDistanceLast10");
+				checkIfWinner(totals, avgTimeDriverDistanceLast15Sorted, numberOfPositionsToConsider, "AvgTimeDriverDistanceLast15");
+				checkIfWinner(totals, avgTimeCombinedAllSorted, numberOfPositionsToConsider, "AvgTimeCombinedAll");
+				checkIfWinner(totals, avgTimeCombinedLast5Sorted, numberOfPositionsToConsider, "AvgTimeCombinedLast5");
+				checkIfWinner(totals, avgTimeCombinedLast10Sorted, numberOfPositionsToConsider, "AvgTimeCombinedLast10");
+				checkIfWinner(totals, avgTimeCombinedLast15Sorted, numberOfPositionsToConsider, "AvgTimeCombinedLast15");
+				checkIfWinner(totals, avgTimeCombinedDistanceAllSorted, numberOfPositionsToConsider, "AvgTimeCombinedDistanceAll");
+				checkIfWinner(totals, avgTimeCombinedDistanceLast5Sorted, numberOfPositionsToConsider, "AvgTimeCombinedDistanceLast5");
+				checkIfWinner(totals, avgTimeCombinedDistanceLast10Sorted, numberOfPositionsToConsider, "AvgTimeCombinedDistanceLast10");
+				checkIfWinner(totals, avgTimeCombinedDistanceLast15Sorted, numberOfPositionsToConsider, "AvgTimeCombinedDistanceLast15");
+				checkIfWinner(totals, avgPositionHorseAllSorted, numberOfPositionsToConsider, "AvgPositionHorseAll");
+				checkIfWinner(totals, avgPositionHorseLast5Sorted, numberOfPositionsToConsider, "AvgPositionHorseLast5");
+				checkIfWinner(totals, avgPositionHorseLast10Sorted, numberOfPositionsToConsider, "AvgPositionHorseLast10");
+				checkIfWinner(totals, avgPositionHorseLast15Sorted, numberOfPositionsToConsider, "AvgPositionHorseLast15");
+				checkIfWinner(totals, avgPositionHorseDistanceAllSorted, numberOfPositionsToConsider, "AvgPositionHorseDistanceAll");
+				checkIfWinner(totals, avgPostioinHorseDistanceLast5Sorted, numberOfPositionsToConsider, "AvgPositionHorseDistanceLast5");
+				checkIfWinner(totals, avgPositionHorseDistanceLast10Sorted, numberOfPositionsToConsider, "AvgPositionHorseDistanceLast10");
+				checkIfWinner(totals, avgPositionHorseDistanceLast15Sorted, numberOfPositionsToConsider, "AvgPositionHorseDistanceLast15");
+				checkIfWinner(totals, avgPositionDriverAllSorted, numberOfPositionsToConsider, "AvgPositionDriverAll");
+				checkIfWinner(totals, avgPositionDriverLast5Sorted, numberOfPositionsToConsider, "AvgPositionDriverLast5");
+				checkIfWinner(totals, avgPositionDriverLast10Sorted, numberOfPositionsToConsider, "AvgPositionDriverLast10");
+				checkIfWinner(totals, avgPositionDriverLast15Sorted, numberOfPositionsToConsider, "AvgPositionDriverLast15");
+				checkIfWinner(totals, avgPositionDriverDistanceAllSorted, numberOfPositionsToConsider, "AvgPositionDriverDistanceAll");
+				checkIfWinner(totals, avgPositionDriverDistanceLast5Sorted, numberOfPositionsToConsider, "AvgPositionDriverDistanceLast5");
+				checkIfWinner(totals, avgPositionDriverDistanceLast10Sorted, numberOfPositionsToConsider, "AvgPositionDriverDistanceLast10");
+				checkIfWinner(totals, avgPositionDriverDistanceLast15Sorted, numberOfPositionsToConsider, "AvgPositionDriverDistanceLast15");
+				checkIfWinner(totals, avgPositionCombinedAllSorted, numberOfPositionsToConsider, "AvgPositionCombinedAll");
+				checkIfWinner(totals, avgPositionCombinedLast5Sorted, numberOfPositionsToConsider, "AvgPositionCombinedLast5");
+				checkIfWinner(totals, avgPositionCombinedLast10Sorted, numberOfPositionsToConsider, "AvgPositionCombinedLast10");
+				checkIfWinner(totals, avgPositionCombinedLast15Sorted, numberOfPositionsToConsider, "AvgPositionCombinedLast15");
+				checkIfWinner(totals, avgPositionCombinedDistanceAllSorted, numberOfPositionsToConsider, "AvgPositionCombinedDistanceAll");
+				checkIfWinner(totals, avgPositionCombinedDistanceLast5Sorted, numberOfPositionsToConsider, "AvgPositionCombinedDistanceLast5");
+				checkIfWinner(totals, avgPositionCombinedDistanceLast10Sorted, numberOfPositionsToConsider, "AvgPositionCombinedDistanceLast10");
+				checkIfWinner(totals, avtPositionCombinedDistanceLast15Sorted, numberOfPositionsToConsider, "AvgPositionCombinedDistanceLast15");
+
+				compareLists("AllHorseTimeSame", numberOfPositionsToConsider, totals, avgTimeHorseAllSorted, avgTimeHorseLast5Sorted,
+						avgTimeHorseLast10Sorted, avgTimeHorseLast15Sorted);
+				compareLists("AllHorseSame", numberOfPositionsToConsider, totals, avgTimeHorseAllSorted, avgTimeHorseLast5Sorted,
+						avgTimeHorseLast10Sorted, avgTimeHorseLast15Sorted, avgTimeHorseDistanceAllSorted, avgTimeHorseDistanceLast5Sorted,
+						avgTimeHorseDistanceLast10Sorted, avgTimeHorseDistanceLast15Sorted);
+				compareLists("AllHorseDistanceSame", numberOfPositionsToConsider, totals, avgTimeHorseDistanceAllSorted,
+						avgTimeHorseDistanceLast5Sorted, avgTimeHorseDistanceLast10Sorted, avgTimeHorseDistanceLast15Sorted);
+
+				compareLists("HorseTimeLast5+DriverTimeLast15+DriverPosAll", numberOfPositionsToConsider, totals, avgTimeHorseLast5Sorted,
+						avgTimeDriverLast5Sorted, avgPositionDriverAllSorted);
+				compareLists("HorseTimeLast5+DriverPosAll", numberOfPositionsToConsider, totals, avgTimeHorseLast5Sorted, avgPositionDriverAllSorted);
+
+				totals.merge("TotalRaces", 1, Integer::sum);
+			}
+			i += thisRace.size();
+		}
+
+		if (totals.get("HorseTimeLast5+DriverTimeLast15+DriverPosAllPlayed") != null
+				&& totals.get("HorseTimeLast5+DriverTimeLast15+DriverPosAll") != null) {
+			System.out
+					.println("HorseTimeLast5+DriverTimeLast15+DriverPosAllPlayed: " + totals.get("HorseTimeLast5+DriverTimeLast15+DriverPosAllPlayed")
+							+ " " + (totals.get("HorseTimeLast5+DriverTimeLast15+DriverPosAll")
+									/ (float) totals.get("HorseTimeLast5+DriverTimeLast15+DriverPosAllPlayed") * 100.0f + " %"));
+			System.out.println("HorseTimeLast5+DriverTimeLast15+DriverPosAll: " + totals.get("HorseTimeLast5+DriverTimeLast15+DriverPosAll") + " "
+					+ (totals.get("HorseTimeLast5+DriverTimeLast15+DriverPosAll") / (float) totals.get("TotalRaces") * 100.0f + " %"));
+		}
+
+		if (totals.get("HorseTimeLast5+DriverPosAllPlayed") != null && totals.get("HorseTimeLast5+DriverPosAll") != null) {
+			System.out.println("HorseTimeLast5+DriverPosAllPlayed: " + totals.get("HorseTimeLast5+DriverPosAllPlayed") + " "
+					+ (totals.get("HorseTimeLast5+DriverPosAll") / (float) totals.get("HorseTimeLast5+DriverPosAllPlayed") * 100.0f + " %"));
+			System.out.println("HorseTimeLast5+DriverPosAll: " + totals.get("HorseTimeLast5+DriverPosAll") + " "
+					+ (totals.get("HorseTimeLast5+DriverPosAll") / (float) totals.get("TotalRaces") * 100.0f + " %"));
+		}
+
+		System.out.println("AvgTimeHorseAll: " + totals.get("AvgTimeHorseAll") + " "
+				+ (totals.get("AvgTimeHorseAll") / (float) totals.get("TotalRaces") * 100.0f + " %"));
+		System.out.println("AvgTimeHorseLast5: " + totals.get("AvgTimeHorseLast5") + " "
+				+ (totals.get("AvgTimeHorseLast5") / (float) totals.get("TotalRaces") * 100.0f + " %"));
+		System.out.println("AvgTimeHorseLast10: " + totals.get("AvgTimeHorseLast10") + " "
+				+ (totals.get("AvgTimeHorseLast10") / (float) totals.get("TotalRaces") * 100.0f + " %"));
+		System.out.println("AvgTimeHorseLast15: " + totals.get("AvgTimeHorseLast15") + " "
+				+ (totals.get("AvgTimeHorseLast15") / (float) totals.get("TotalRaces") * 100.0f + " %"));
+		System.out.println("AvgTimeHorseDistanceAll: " + totals.get("AvgTimeHorseDistanceAll") + " "
+				+ (totals.get("AvgTimeHorseDistanceAll") / (float) totals.get("TotalRaces") * 100.0f + " %"));
+		System.out.println("AvgTimeHorseDistanceLast5: " + totals.get("AvgTimeHorseDistanceLast5") + " "
+				+ (totals.get("AvgTimeHorseDistanceLast5") / (float) totals.get("TotalRaces") * 100.0f + " %"));
+		System.out.println("AvgTimeHorseDistanceLast10: " + totals.get("AvgTimeHorseDistanceLast10") + " "
+				+ (totals.get("AvgTimeHorseDistanceLast10") / (float) totals.get("TotalRaces") * 100.0f + " %"));
+		System.out.println("AvgTimeHorseDistanceLast15: " + totals.get("AvgTimeHorseDistanceLast15") + " "
+				+ (totals.get("AvgTimeHorseDistanceLast15") / (float) totals.get("TotalRaces") * 100.0f + " %"));
+
+		System.out.println("AvgTimeDriverAll: " + totals.get("AvgTimeDriverAll") + " "
+				+ (totals.get("AvgTimeDriverAll") / (float) totals.get("TotalRaces") * 100.0f + " %"));
+		System.out.println("AvgTimeDriverLast5: " + totals.get("AvgTimeDriverLast5") + " "
+				+ (totals.get("AvgTimeDriverLast5") / (float) totals.get("TotalRaces") * 100.0f + " %"));
+		System.out.println("AvgTimeDriverLast10: " + totals.get("AvgTimeDriverLast10") + " "
+				+ (totals.get("AvgTimeDriverLast10") / (float) totals.get("TotalRaces") * 100.0f + " %"));
+		System.out.println("AvgTimeDriverLast15: " + totals.get("AvgTimeDriverLast15") + " "
+				+ (totals.get("AvgTimeDriverLast15") / (float) totals.get("TotalRaces") * 100.0f + " %"));
+		System.out.println("AvgTimeDriverDistanceAll: " + totals.get("AvgTimeDriverDistanceAll") + " "
+				+ (totals.get("AvgTimeDriverDistanceAll") / (float) totals.get("TotalRaces") * 100.0f + " %"));
+		System.out.println("AvgTimeDriverDistanceLast5: " + totals.get("AvgTimeDriverDistanceLast5") + " "
+				+ (totals.get("AvgTimeDriverDistanceLast5") / (float) totals.get("TotalRaces") * 100.0f + " %"));
+		System.out.println("AvgTimeDriverDistanceLast10: " + totals.get("AvgTimeDriverDistanceLast10") + " "
+				+ (totals.get("AvgTimeDriverDistanceLast10") / (float) totals.get("TotalRaces") * 100.0f + " %"));
+		System.out.println("AvgTimeDriverDistanceLast15: " + totals.get("AvgTimeDriverDistanceLast15") + " "
+				+ (totals.get("AvgTimeDriverDistanceLast15") / (float) totals.get("TotalRaces") * 100.0f + " %"));
+
+		System.out.println("AvgTimeCombinedAll: " + totals.get("AvgTimeCombinedAll") + " "
+				+ (totals.get("AvgTimeCombinedAll") / (float) totals.get("TotalRaces") * 100.0f + " %"));
+		System.out.println("AvgTimeCombinedLast5: " + totals.get("AvgTimeCombinedLast5") + " "
+				+ (totals.get("AvgTimeCombinedLast5") / (float) totals.get("TotalRaces") * 100.0f + " %"));
+		System.out.println("AvgTimeCombinedLast10: " + totals.get("AvgTimeCombinedLast10") + " "
+				+ (totals.get("AvgTimeCombinedLast10") / (float) totals.get("TotalRaces") * 100.0f + " %"));
+		System.out.println("AvgTimeCombinedLast15: " + totals.get("AvgTimeCombinedLast15") + " "
+				+ (totals.get("AvgTimeCombinedLast15") / (float) totals.get("TotalRaces") * 100.0f + " %"));
+		System.out.println("AvgTimeCombinedDistanceAll: " + totals.get("AvgTimeCombinedDistanceAll") + " "
+				+ (totals.get("AvgTimeCombinedDistanceAll") / (float) totals.get("TotalRaces") * 100.0f + " %"));
+		System.out.println("AvgTimeCombinedDistanceLast5: " + totals.get("AvgTimeCombinedDistanceLast5") + " "
+				+ (totals.get("AvgTimeCombinedDistanceLast5") / (float) totals.get("TotalRaces") * 100.0f + " %"));
+		System.out.println("AvgTimeCombinedDistanceLast10: " + totals.get("AvgTimeCombinedDistanceLast10") + " "
+				+ (totals.get("AvgTimeCombinedDistanceLast10") / (float) totals.get("TotalRaces") * 100.0f + " %"));
+		System.out.println("AvgTimeCombinedDistanceLast15: " + totals.get("AvgTimeCombinedDistanceLast15") + " "
+				+ (totals.get("AvgTimeCombinedDistanceLast15") / (float) totals.get("TotalRaces") * 100.0f + " %"));
+
+		System.out.println();
+
+		System.out.println("AvgPositionHorseAll: " + totals.get("AvgPositionHorseAll") + " "
+				+ (totals.get("AvgPositionHorseAll") / (float) totals.get("TotalRaces") * 100.0f + " %"));
+		System.out.println("AvgPositionHorseLast5: " + totals.get("AvgPositionHorseLast5") + " "
+				+ (totals.get("AvgPositionHorseLast5") / (float) totals.get("TotalRaces") * 100.0f + " %"));
+		System.out.println("AvgPositionHorseLast10: " + totals.get("AvgPositionHorseLast10") + " "
+				+ (totals.get("AvgPositionHorseLast10") / (float) totals.get("TotalRaces") * 100.0f + " %"));
+		System.out.println("AvgPositionHorseLast15: " + totals.get("AvgPositionHorseLast15") + " "
+				+ (totals.get("AvgPositionHorseLast15") / (float) totals.get("TotalRaces") * 100.0f + " %"));
+		System.out.println("AvgPositionHorseDistanceAll: " + totals.get("AvgPositionHorseDistanceAll") + " "
+				+ (totals.get("AvgPositionHorseDistanceAll") / (float) totals.get("TotalRaces") * 100.0f + " %"));
+		System.out.println("AvgPositionHorseDistanceLast5: " + totals.get("AvgPositionHorseDistanceLast5") + " "
+				+ (totals.get("AvgPositionHorseDistanceLast5") / (float) totals.get("TotalRaces") * 100.0f + " %"));
+		System.out.println("AvgPositionHorseDistanceLast10: " + totals.get("AvgPositionHorseDistanceLast10") + " "
+				+ (totals.get("AvgPositionHorseDistanceLast10") / (float) totals.get("TotalRaces") * 100.0f + " %"));
+		System.out.println("AvgPositionHorseDistanceLast15: " + totals.get("AvgPositionHorseDistanceLast15") + " "
+				+ (totals.get("AvgPositionHorseDistanceLast15") / (float) totals.get("TotalRaces") * 100.0f + " %"));
+
+		System.out.println("AvgPositionDriverAll: " + totals.get("AvgPositionDriverAll") + " "
+				+ (totals.get("AvgPositionDriverAll") / (float) totals.get("TotalRaces") * 100.0f + " %"));
+		System.out.println("AvgPositionDriverLast5: " + totals.get("AvgPositionDriverLast5") + " "
+				+ (totals.get("AvgPositionDriverLast5") / (float) totals.get("TotalRaces") * 100.0f + " %"));
+		System.out.println("AvgPositionDriverLast10: " + totals.get("AvgPositionDriverLast10") + " "
+				+ (totals.get("AvgPositionDriverLast10") / (float) totals.get("TotalRaces") * 100.0f + " %"));
+		System.out.println("AvgPositionDriverLast15: " + totals.get("AvgPositionDriverLast15") + " "
+				+ (totals.get("AvgPositionDriverLast15") / (float) totals.get("TotalRaces") * 100.0f + " %"));
+		System.out.println("AvgPositionDriverDistanceAll: " + totals.get("AvgPositionDriverDistanceAll") + " "
+				+ (totals.get("AvgPositionDriverDistanceAll") / (float) totals.get("TotalRaces") * 100.0f + " %"));
+		System.out.println("AvgPositionDriverDistanceLast5: " + totals.get("AvgPositionDriverDistanceLast5") + " "
+				+ (totals.get("AvgPositionDriverDistanceLast5") / (float) totals.get("TotalRaces") * 100.0f + " %"));
+		System.out.println("AvgPositionDriverDistanceLast10: " + totals.get("AvgPositionDriverDistanceLast10") + " "
+				+ (totals.get("AvgPositionDriverDistanceLast10") / (float) totals.get("TotalRaces") * 100.0f + " %"));
+		System.out.println("AvgPositionDriverDistanceLast15: " + totals.get("AvgPositionDriverDistanceLast15") + " "
+				+ (totals.get("AvgPositionDriverDistanceLast15") / (float) totals.get("TotalRaces") * 100.0f + " %"));
+
+		System.out.println("AvgPositionCombinedAll: " + totals.get("AvgPositionCombinedAll") + " "
+				+ (totals.get("AvgPositionCombinedAll") / (float) totals.get("TotalRaces") * 100.0f + " %"));
+		System.out.println("AvgPositionCombinedLast5: " + totals.get("AvgPositionCombinedLast5") + " "
+				+ (totals.get("AvgPositionCombinedLast5") / (float) totals.get("TotalRaces") * 100.0f + " %"));
+		System.out.println("AvgPositionCombinedLast10: " + totals.get("AvgPositionCombinedLast10") + " "
+				+ (totals.get("AvgPositionCombinedLast10") / (float) totals.get("TotalRaces") * 100.0f + " %"));
+		System.out.println("AvgPositionCombinedLast15: " + totals.get("AvgPositionCombinedLast15") + " "
+				+ (totals.get("AvgPositionCombinedLast15") / (float) totals.get("TotalRaces") * 100.0f + " %"));
+		System.out.println("AvgPositionCombinedDistanceAll: " + totals.get("AvgPositionCombinedDistanceAll") + " "
+				+ (totals.get("AvgPositionCombinedDistanceAll") / (float) totals.get("TotalRaces") * 100.0f + " %"));
+		System.out.println("AvgPositionCombinedDistanceLast5: " + totals.get("AvgPositionCombinedDistanceLast5") + " "
+				+ (totals.get("AvgPositionCombinedDistanceLast5") / (float) totals.get("TotalRaces") * 100.0f + " %"));
+		System.out.println("AvgPositionCombinedDistanceLast10: " + totals.get("AvgPositionCombinedDistanceLast10") + " "
+				+ (totals.get("AvgPositionCombinedDistanceLast10") / (float) totals.get("TotalRaces") * 100.0f + " %"));
+		System.out.println("AvgPositionCombinedDistanceLast15: " + totals.get("AvgPositionCombinedDistanceLast15") + " "
+				+ (totals.get("AvgPositionCombinedDistanceLast15") / (float) totals.get("TotalRaces") * 100.0f + " %"));
+
+		if (totals.get("AllHorseTimeSamePlayed") != null && totals.get("AllHorseTimeSame") != null) {
+			System.out.println("AllHorseTimeSamePlayed: " + totals.get("AllHorseTimeSamePlayed") + " "
+					+ (totals.get("AllHorseTimeSame") / (float) totals.get("AllHorseTimeSamePlayed") * 100.0f + " %"));
+			System.out.println("AllHorseTimeSame: " + totals.get("AllHorseTimeSame") + " "
+					+ (totals.get("AllHorseTimeSame") / (float) totals.get("TotalRaces") * 100.0f + " %"));
+		}
+
+		if (totals.get("AllHorseDistanceSamePlayed") != null && totals.get("AllHorseDistanceSame") != null) {
+			System.out.println("AllHorseDistanceSamePlayed: " + totals.get("AllHorseDistanceSamePlayed") + " "
+					+ (totals.get("AllHorseDistanceSame") / (float) totals.get("AllHorseDistanceSamePlayed") * 100.0f + " %"));
+			System.out.println("AllHorseDistanceSame: " + totals.get("AllHorseDistanceSame") + " "
+					+ (totals.get("AllHorseDistanceSame") / (float) totals.get("TotalRaces") * 100.0f + " %"));
+		}
+
+		if (totals.get("AllHorseSamePlayed") != null && totals.get("AllHorseTimeSame") != null) {
+			System.out.println("AllHorseSamePlayed: " + totals.get("AllHorseSamePlayed") + " "
+					+ (totals.get("AllHorseTimeSame") / (float) totals.get("AllHorseSamePlayed") * 100.0f + " %"));
+			System.out.println("AllHorseSame: " + totals.get("AllHorseSame") + " "
+					+ (totals.get("AllHorseSame") / (float) totals.get("TotalRaces") * 100.0f + " %"));
+		}
+
+		System.out.println("TotalRaces: " + totals.get("TotalRaces"));
+
+	}
+
+	private void compareLists(String saveName, int topXResults, HashMap<String, Integer> totals, List<Result>... lists) {
+		List<Result> firstList = lists[0].subList(0, topXResults);
+
+		for (int i = 1; i < lists.length; i++) {
+			if (lists[i].subList(0, topXResults).stream().filter(p -> firstList.contains(p)).count() <= 0) {
+				return;
+			}
+		}
+
+		List<Result> res = firstList.stream().collect(Collectors.toList());
+		totals.merge(saveName + "Played", 1, Integer::sum);
+
+		for (int i = 1; i < lists.length; i++) {
+			res.addAll(lists[i].subList(0, topXResults).stream().filter(p -> res.contains(p)).distinct().collect(Collectors.toList()));
+		}
+		if (res.stream().filter(p -> p.getResult() == 1).count() > 0) {
+			totals.merge(saveName, 1, Integer::sum);
+		}
+	}
+
+	private void checkIfWinner(HashMap<String, Integer> totals, List<Result> racesSortedByCondition, int numberOfPositionsToConsider,
+			String variableName) {
+		for (int i = 0; i < numberOfPositionsToConsider; i++) {
+			if (racesSortedByCondition.get(i).getResult() == 1) {
+				totals.merge(variableName, 1, Integer::sum);
+			}
+		}
+	}
+
+	@FXML public void calculateMostRelevantValue(ActionEvent event) {
+		String createSql = "CREATE TEMPORARY TABLE test (id INT, c int, RaceNumber INT, RaceDate VARCHAR(64), lane INT);";
+		String insertSql = "INSERT INTO test SELECT id, count(*) as c, RaceNumber, RaceDate, lane FROM `Results` WHERE DATE(RaceDate) < DATE(NOW()) GROUP BY RaceDate, RaceNumber HAVING c > 6;";
+		String selectSql = "SELECT * FROM Results r INNER JOIN test t ON r.RaceDate = t.RaceDate AND r.RaceNumber = t.RaceNumber AND r.id NOT IN (SELECT resultId FROM testTable) ORDER BY r.RaceDate DESC, r.RaceNumber ASC;";
+
+		List<Result> results = new ArrayList<>();
+		try (Connection conn = DatabaseController.getInstance().getConnection();
+				PreparedStatement createStat = conn.prepareStatement(createSql);
+				PreparedStatement insertStat = conn.prepareStatement(insertSql);
+				PreparedStatement selectStat = conn.prepareStatement(selectSql);) {
+
+			createStat.execute();
+			insertStat.execute();
+			selectStat.executeQuery();
+
+			ResultSet rs = selectStat.executeQuery();
+			while (rs.next()) {
+				results.add(new Result(rs.getInt("id"), rs.getInt("TrackId"), rs.getString("RaceDate"), rs.getString("RaceType"),
+						rs.getInt("RaceNumber"), rs.getInt("Lane"), rs.getInt("Distance"), rs.getInt("Result"), rs.getFloat("Time"),
+						rs.getString("TimeModifier"), rs.getInt("Shoes"), rs.getInt("Sulky"), rs.getInt("DriverId"), rs.getInt("TrainerId"),
+						rs.getInt("HorseId"), rs.getInt("raceId")));
+			}
+
+			results.sort((r1, r2) -> r2.getRaceDate().compareTo(r1.getRaceDate())); // Sorterat på nyast till äldst
+
+			for (int i = 0; i < results.size(); i++) {
+				final int pos = i;
+				List<Result> thisRace = results
+						.stream().filter(p -> p.getRaceDate().equals(results.get(pos).getRaceDate())
+								&& p.getRaceNumber() == results.get(pos).getRaceNumber() && p.getTrackId() == results.get(pos).getTrackId())
+						.collect(Collectors.toList());
+				calculateTimes(thisRace, results);
+				i += thisRace.size();
+			}
+
+		} catch (SQLException e) {
+			e.printStackTrace();
+		}
+	}
+
+	private void calculateTimes(List<Result> thisRace, List<Result> races) {
+		for (Result race : thisRace) {
+
+			List<Result> horseRaces = races.stream()
+					.filter(p -> p.getHorseId() == race.getHorseId() && p.getRaceDate().compareTo(race.getRaceDate()) < 0)
+					.collect(Collectors.toList());
+			List<Result> driverRaces = races.stream()
+					.filter(p -> p.getDriverId() == race.getDriverId() && p.getRaceDate().compareTo(race.getRaceDate()) < 0)
+					.collect(Collectors.toList());
+			List<Result> combinedRaces = races.stream().filter(p -> p.getHorseId() == race.getHorseId() && p.getDriverId() == race.getDriverId()
+					&& p.getRaceDate().compareTo(race.getRaceDate()) < 0).collect(Collectors.toList());
+
+			setTimeAverages(races, race, horseRaces, driverRaces, combinedRaces);
+			setPositionAverages(races, race, horseRaces, driverRaces, combinedRaces);
+
+			DatabaseController.getInstance().setTestRaceData(race);
+
+		}
+// TODO Continue calculating, not done at all!
+	}
+
+	private void setPositionAverages(List<Result> races, Result race, List<Result> horseRaces, List<Result> driverRaces, List<Result> combinedRaces) {
+		double totalHorseSum = horseRaces.stream().mapToInt(Result::getResult).map(this::getResult).average().orElse(-1d);
+		double horse5 = horseRaces.stream().mapToInt(Result::getResult).map(this::getResult).limit(5).average().orElse(-1d);
+		double horse10 = horseRaces.stream().mapToInt(Result::getResult).map(this::getResult).limit(10).average().orElse(-1d);
+		double horse15 = horseRaces.stream().mapToInt(Result::getResult).map(this::getResult).limit(15).average().orElse(-1d);
+		double driver5 = driverRaces.stream().mapToInt(Result::getResult).map(this::getResult).limit(5).average().orElse(-1d);
+		double driver10 = driverRaces.stream().mapToInt(Result::getResult).map(this::getResult).limit(10).average().orElse(-1d);
+		double driver15 = driverRaces.stream().mapToInt(Result::getResult).map(this::getResult).limit(15).average().orElse(-1d);
+		double combined5 = combinedRaces.stream().mapToInt(Result::getResult).map(this::getResult).limit(5).average().orElse(-1d);
+		double combined10 = combinedRaces.stream().mapToInt(Result::getResult).map(this::getResult).limit(10).average().orElse(-1d);
+		double combined15 = combinedRaces.stream().mapToInt(Result::getResult).map(this::getResult).limit(15).average().orElse(-1d);
+		double totalDriverSum = driverRaces.stream().mapToInt(Result::getResult).map(this::getResult).average().orElse(-1d);
+		double totalCombinedSum = combinedRaces.stream().mapToInt(Result::getResult).map(this::getResult).average().orElse(-1d);
+
+		double totalHorseDistanceSum = horseRaces.stream().filter(p -> p.getDistance() == race.getDistance()).mapToInt(Result::getResult)
+				.map(this::getResult).average().orElse(-1d);
+		double horseDistance5 = horseRaces.stream().filter(p -> p.getDistance() == race.getDistance()).mapToInt(Result::getResult)
+				.map(this::getResult).limit(5).average().orElse(-1d);
+		double horseDistance10 = horseRaces.stream().filter(p -> p.getDistance() == race.getDistance()).mapToInt(Result::getResult)
+				.map(this::getResult).limit(10).average().orElse(-1d);
+		double horseDistance15 = horseRaces.stream().filter(p -> p.getDistance() == race.getDistance()).mapToInt(Result::getResult)
+				.map(this::getResult).limit(15).average().orElse(-1d);
+		double driverDistance5 = driverRaces.stream().filter(p -> p.getDistance() == race.getDistance()).mapToInt(Result::getResult)
+				.map(this::getResult).limit(5).average().orElse(-1d);
+		double driverDistance10 = driverRaces.stream().filter(p -> p.getDistance() == race.getDistance()).mapToInt(Result::getResult)
+				.map(this::getResult).limit(10).average().orElse(-1d);
+		double driverDistance15 = driverRaces.stream().filter(p -> p.getDistance() == race.getDistance()).mapToInt(Result::getResult)
+				.map(this::getResult).limit(15).average().orElse(-1d);
+		double combinedDistance5 = combinedRaces.stream().filter(p -> p.getDistance() == race.getDistance()).mapToInt(Result::getResult)
+				.map(this::getResult).limit(5).average().orElse(-1d);
+		double combinedDistance10 = combinedRaces.stream().filter(p -> p.getDistance() == race.getDistance()).mapToInt(Result::getResult)
+				.map(this::getResult).limit(10).average().orElse(-1d);
+		double combinedDistance15 = combinedRaces.stream().filter(p -> p.getDistance() == race.getDistance()).mapToInt(Result::getResult)
+				.map(this::getResult).limit(15).average().orElse(-1d);
+		double totalDriverDistanceSum = driverRaces.stream().filter(p -> p.getDistance() == race.getDistance()).mapToInt(Result::getResult)
+				.map(this::getResult).average().orElse(-1d);
+		double totalCombinedDistanceSum = combinedRaces.stream().filter(p -> p.getDistance() == race.getDistance()).mapToInt(Result::getResult)
+				.map(this::getResult).average().orElse(-1d);
+
+		Optional<Result> result = races.stream().filter(r -> r.equals(race)).findAny();
+
+		if (result.isPresent()) {
+			Result actualResult = result.get();
+			actualResult.setAvgPositionHorseAll((float) totalHorseSum);
+			actualResult.setAvgPositionHorseLast5((float) horse5);
+			actualResult.setAvgPositionHorseLast10((float) horse10);
+			actualResult.setAvgPositionHorseLast15((float) horse15);
+			actualResult.setAvgPositionDriverAll((float) totalDriverSum);
+			actualResult.setAvgPositionDriverLast5((float) driver5);
+			actualResult.setAvgPositionDriverLast10((float) driver10);
+			actualResult.setAvgPositionDriverLast15((float) driver15);
+			actualResult.setAvgPositionCombinedAll((float) totalCombinedSum);
+			actualResult.setAvgPositionCombinedLast5((float) combined5);
+			actualResult.setAvgPositionCombinedLast10((float) combined10);
+			actualResult.setAvgPositionCombinedLast15((float) combined15);
+
+			actualResult.setAvgPositionHorseDistanceAll((float) totalHorseDistanceSum);
+			actualResult.setAvgPositionHorseDistanceLast5((float) horseDistance5);
+			actualResult.setAvgPositionHorseDistanceLast10((float) horseDistance10);
+			actualResult.setAvgPositionHorseDistanceLast15((float) horseDistance15);
+			actualResult.setAvgPositionDriverDistanceAll((float) totalDriverDistanceSum);
+			actualResult.setAvgPositionDriverDistanceLast5((float) driverDistance5);
+			actualResult.setAvgPositionDriverDistanceLast10((float) driverDistance10);
+			actualResult.setAvgPositionDriverDistanceLast15((float) driverDistance15);
+			actualResult.setAvgPositionCombinedDistanceAll((float) totalCombinedDistanceSum);
+			actualResult.setAvgPositionCombinedDistanceLast5((float) combinedDistance5);
+			actualResult.setAvgPositionCombinedDistanceLast10((float) combinedDistance10);
+			actualResult.setAvgPositionCombinedDistanceLast15((float) combinedDistance15);
+		}
+	}
+
+	private int getResult(int r) {
+		int result = r;
+		if (r == 0) {
+			result = 8;
+		} else if (r == -1) {
+			result = 9;
+		} else if (r == -2) {
+			result = 10;
+		}
+		return result;
+	}
+
+	private void setTimeAverages(List<Result> races, Result race, List<Result> horseRaces, List<Result> driverRaces, List<Result> combinedRaces) {
+
+		double totalHorseSum = horseRaces.stream().mapToDouble(Result::getTime).filter(d -> d > 0d).average().orElse(0d);
+		double horse5 = horseRaces.stream().mapToDouble(Result::getTime).filter(d -> d > 0d).limit(5).average().orElse(0d);
+		double horse10 = horseRaces.stream().mapToDouble(Result::getTime).filter(d -> d > 0d).limit(10).average().orElse(0d);
+		double horse15 = horseRaces.stream().mapToDouble(Result::getTime).filter(d -> d > 0d).limit(15).average().orElse(0d);
+		double driver5 = driverRaces.stream().mapToDouble(Result::getTime).filter(d -> d > 0d).limit(5).average().orElse(0d);
+		double driver10 = driverRaces.stream().mapToDouble(Result::getTime).filter(d -> d > 0d).limit(10).average().orElse(0d);
+		double driver15 = driverRaces.stream().mapToDouble(Result::getTime).filter(d -> d > 0d).limit(15).average().orElse(0d);
+		double combined5 = combinedRaces.stream().mapToDouble(Result::getTime).filter(d -> d > 0d).limit(5).average().orElse(0d);
+		double combined10 = combinedRaces.stream().mapToDouble(Result::getTime).filter(d -> d > 0d).limit(10).average().orElse(0d);
+		double combined15 = combinedRaces.stream().mapToDouble(Result::getTime).filter(d -> d > 0d).limit(15).average().orElse(0d);
+		double totalDriverSum = driverRaces.stream().mapToDouble(Result::getTime).filter(d -> d > 0d).average().orElse(0d);
+		double totalCombinedSum = combinedRaces.stream().mapToDouble(Result::getTime).filter(d -> d > 0d).average().orElse(0d);
+
+		double totalHorseDistanceSum = horseRaces.stream().filter(p -> p.getDistance() == race.getDistance()).mapToDouble(Result::getTime)
+				.filter(d -> d > 0d).average().orElse(0d);
+		double horseDistance5 = horseRaces.stream().filter(p -> p.getDistance() == race.getDistance()).mapToDouble(Result::getTime)
+				.filter(d -> d > 0d).limit(5).average().orElse(0d);
+		double horseDistance10 = horseRaces.stream().filter(p -> p.getDistance() == race.getDistance()).mapToDouble(Result::getTime)
+				.filter(d -> d > 0d).limit(10).average().orElse(0d);
+		double horseDistance15 = horseRaces.stream().filter(p -> p.getDistance() == race.getDistance()).mapToDouble(Result::getTime)
+				.filter(d -> d > 0d).limit(15).average().orElse(0d);
+		double driverDistance5 = driverRaces.stream().filter(p -> p.getDistance() == race.getDistance()).mapToDouble(Result::getTime)
+				.filter(d -> d > 0d).limit(5).average().orElse(0d);
+		double driverDistance10 = driverRaces.stream().filter(p -> p.getDistance() == race.getDistance()).mapToDouble(Result::getTime)
+				.filter(d -> d > 0d).limit(10).average().orElse(0d);
+		double driverDistance15 = driverRaces.stream().filter(p -> p.getDistance() == race.getDistance()).mapToDouble(Result::getTime)
+				.filter(d -> d > 0d).limit(15).average().orElse(0d);
+		double combinedDistance5 = combinedRaces.stream().filter(p -> p.getDistance() == race.getDistance()).mapToDouble(Result::getTime)
+				.filter(d -> d > 0d).limit(5).average().orElse(0d);
+		double combinedDistance10 = combinedRaces.stream().filter(p -> p.getDistance() == race.getDistance()).mapToDouble(Result::getTime)
+				.filter(d -> d > 0d).limit(10).average().orElse(0d);
+		double combinedDistance15 = combinedRaces.stream().filter(p -> p.getDistance() == race.getDistance()).mapToDouble(Result::getTime)
+				.filter(d -> d > 0d).limit(15).average().orElse(0d);
+		double totalDriverDistanceSum = driverRaces.stream().filter(p -> p.getDistance() == race.getDistance()).mapToDouble(Result::getTime)
+				.filter(d -> d > 0d).average().orElse(0d);
+		double totalCombinedDistanceSum = combinedRaces.stream().filter(p -> p.getDistance() == race.getDistance()).mapToDouble(Result::getTime)
+				.filter(d -> d > 0d).average().orElse(0d);
+
+		Optional<Result> result = races.stream().filter(r -> r.equals(race)).findAny();
+
+		if (result.isPresent()) {
+			Result actualResult = result.get();
+			actualResult.setAvgTimeHorseAll((float) totalHorseSum);
+			actualResult.setAvgTimeHorseLast5((float) horse5);
+			actualResult.setAvgTimeHorseLast10((float) horse10);
+			actualResult.setAvgTimeHorseLast15((float) horse15);
+			actualResult.setAvgTimeDriverAll((float) totalDriverSum);
+			actualResult.setAvgTimeDriverLast5((float) driver5);
+			actualResult.setAvgTimeDriverLast10((float) driver10);
+			actualResult.setAvgTimeDriverLast15((float) driver15);
+			actualResult.setAvgTimeCombinedAll((float) totalCombinedSum);
+			actualResult.setAvgTimeCombinedLast5((float) combined5);
+			actualResult.setAvgTimeCombinedLast10((float) combined10);
+			actualResult.setAvgTimeCombinedLast15((float) combined15);
+
+			actualResult.setAvgTimeHorseDistanceAll((float) totalHorseDistanceSum);
+			actualResult.setAvgTimeHorseDistanceLast5((float) horseDistance5);
+			actualResult.setAvgTimeHorseDistanceLast10((float) horseDistance10);
+			actualResult.setAvgTimeHorseDistanceLast15((float) horseDistance15);
+			actualResult.setAvgTimeDriverDistanceAll((float) totalDriverDistanceSum);
+			actualResult.setAvgTimeDriverDistanceLast5((float) driverDistance5);
+			actualResult.setAvgTimeDriverDistanceLast10((float) driverDistance10);
+			actualResult.setAvgTimeDriverDistanceLast15((float) driverDistance15);
+			actualResult.setAvgTimeCombinedDistanceAll((float) totalCombinedDistanceSum);
+			actualResult.setAvgTimeCombinedDistanceLast5((float) combinedDistance5);
+			actualResult.setAvgTimeCombinedDistanceLast10((float) combinedDistance10);
+			actualResult.setAvgTimeCombinedDistanceLast15((float) combinedDistance15);
+		}
+	}
 }

+ 175 - 175
ATG/src/database/Database.java

@@ -11,179 +11,179 @@ import com.google.common.collect.Maps;
 
 public class Database {
 
-    private static Database instance = new Database();
-    private Connection conn;
-
-    private static final String username = "atg";
-    private static final String password = "CvWKY34DqtlVgjt_9";
-    private static final String database = "atg";
-    private static final String url = "jdbc:mysql://nordh.xyz:3306/";
-    private static final String timezoneFix = "?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";
-
-    private  float avgTime = 0;
-    private final Map<Integer, Float> avgTimeDistance = Maps.newHashMap();
-
-    private final Map<Integer, Float> avgTimeDistanceLimit5 = Maps.newHashMap();
-    private final Map<Integer, Float> avgTimeDistanceLimit10 = Maps.newHashMap();
-    private final Map<Integer, Float> avgTimeDistanceLimit15 = Maps.newHashMap();
-
-    private Float avgTimeLimit5 = 0f;
-    private Float avgTimeLimit10 = 0f;
-    private Float avgTimeLimit15 = 0f;
-
-    protected Database() {}
-
-    public static Database getDatabase() {
-        return instance;
-    }
-
-    protected Connection getConnection() {
-        if (conn == null) {
-            try {
-                conn = DriverManager.getConnection(url + database + timezoneFix, username, password);
-            } catch (final SQLException e) {
-                throw new RuntimeException(e.getMessage(), e);
-            }
-        }
-        return conn;
-    }
-
-    public float getAvgTime() {
-        if (avgTime <= 0) {
-            avgTime = getAvgTimeByDistanceLimit(0, 0);
-        }
-
-        return avgTime;
-    }
-
-    public float getAvgTimeByDistance(int distance) {
-        if (avgTimeDistance.get(distance) == null) {
-            avgTimeDistance.put(distance, getAvgTimeByDistanceLimit(distance, 0));
-        }
-
-        return avgTimeDistance.get(distance);
-    }
-
-    public float getAvgTimeWithLimit(int raceLimit) {
-        final float returnValue;
-        switch (raceLimit) {
-        case 5:
-            if (avgTimeLimit5 <= 0) {
-                avgTimeLimit5 = getAvgTimeByDistanceLimit(0, raceLimit);
-            }
-            returnValue = avgTimeLimit5;
-            break;
-        case 10:
-            if (avgTimeLimit10 <= 0) {
-                avgTimeLimit10 = getAvgTimeByDistanceLimit(0, raceLimit);
-            }
-            returnValue = avgTimeLimit10;
-            break;
-        case 15:
-            if (avgTimeLimit15 <= 0) {
-                avgTimeLimit15 = getAvgTimeByDistanceLimit(0, raceLimit);
-            }
-            returnValue = avgTimeLimit15;
-            break;
-
-        default:
-            returnValue = getAvgTimeByDistanceLimit(0, raceLimit);
-            break;
-        }
-        return returnValue;
-    }
-
-    public float getAvgTimeByDistanceLimit(int distance, int raceLimit) {
-        final float returnValue;
-        if (distance > 0 && raceLimit > 0) {
-            switch (raceLimit) {
-            case 5:
-                if (avgTimeDistanceLimit5.get(distance) == null) {
-                    avgTimeDistanceLimit5.put(distance, getNewAvgTimeByDistanceLimit(0, raceLimit));
-                }
-                returnValue = avgTimeDistanceLimit5.get(distance);
-                break;
-            case 10:
-                if (avgTimeDistanceLimit10.get(distance) == null) {
-                    avgTimeDistanceLimit10.put(distance, getNewAvgTimeByDistanceLimit(0, raceLimit));
-                }
-                returnValue = avgTimeDistanceLimit10.get(distance);
-                break;
-            case 15:
-                if (avgTimeDistanceLimit15.get(distance) == null) {
-                    avgTimeDistanceLimit15.put(distance, getNewAvgTimeByDistanceLimit(0, raceLimit));
-                }
-                returnValue = avgTimeDistanceLimit15.get(distance);
-                break;
-
-            default:
-                returnValue = getNewAvgTimeByDistanceLimit(0, raceLimit);
-                break;
-            }
-        } else {
-            returnValue = getNewAvgTimeByDistanceLimit(distance, raceLimit);
-        }
-        return returnValue;
-    }
-
-    public float getNewAvgTimeByDistanceLimit(int distance, int raceLimit) {
-        float returnValue = -1f;
-
-        final String sql = "SELECT ROUND(AVG(t.Time), 2) as avgTime FROM (SELECT AVG(Time) as Time FROM Results WHERE Time > 0 AND Lane > 0 AND RaceDate < NOW()";
-        final String distanceSql = " AND distance BETWEEN ? AND ?";
-        final String groupBySql = " GROUP BY RaceDate";
-        final String orderBySql = " ORDER BY RaceDate";
-        final String limitSql = " DESC LIMIT ?";
-
-        final StringBuilder sb = new StringBuilder();
-        sb.append(sql);
-        boolean orderAppended = false;
-        if (distance > 0) {
-            sb.append(distanceSql);
-            sb.append(groupBySql);
-            sb.append(orderBySql);
-            orderAppended = true;
-        }
-        if (raceLimit > 0) {
-            if (!orderAppended) {
-                sb.append(groupBySql);
-                sb.append(orderBySql);
-            }
-            orderAppended = true;
-            sb.append(limitSql);
-        }
-
-        if (!orderAppended) {
-            sb.append(groupBySql);
-            sb.append(orderBySql);
-        }
-
-        sb.append(") t");
-
-        try {
-            final PreparedStatement stat = getConnection().prepareStatement(sb.toString());
-
-            if (distance > 0) {
-                stat.setInt(1, distance - 50);
-                stat.setInt(2, distance + 50);
-            }
-            if (distance > 0 && raceLimit > 0) {
-                stat.setInt(3, raceLimit);
-            } else if (distance <= 0 && raceLimit > 0) {
-                stat.setInt(1, raceLimit);
-            }
-
-            final ResultSet rs = stat.executeQuery();
-
-            while (rs.next()) {
-                returnValue = rs.getFloat("avgTime");
-            }
-        } catch (final SQLException e) {
-            System.out.println(sb.toString());
-            System.out.println(e.getMessage());
-            // TODO Auto-generated catch block
-            e.printStackTrace();
-        }
-        return returnValue;
-    }
+	private static Database instance = new Database();
+	private Connection conn;
+
+	private static final String username = "atg";
+	private static final String password = "CvWKY34DqtlVgjt_9";
+	private static final String database = "atg";
+	private static final String url = "jdbc:mysql://nordh.xyz:3306/";
+	private static final String timezoneFix = "?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";
+
+	private float avgTime = 0;
+	private final Map<Integer, Float> avgTimeDistance = Maps.newHashMap();
+
+	private final Map<Integer, Float> avgTimeDistanceLimit5 = Maps.newHashMap();
+	private final Map<Integer, Float> avgTimeDistanceLimit10 = Maps.newHashMap();
+	private final Map<Integer, Float> avgTimeDistanceLimit15 = Maps.newHashMap();
+
+	private Float avgTimeLimit5 = 0f;
+	private Float avgTimeLimit10 = 0f;
+	private Float avgTimeLimit15 = 0f;
+
+	protected Database() {
+	}
+
+	public static Database getDatabase() {
+		return instance;
+	}
+
+	protected Connection getConnection() {
+		if (conn == null) {
+			try {
+				conn = DriverManager.getConnection(url + database + timezoneFix, username, password);
+			} catch (final SQLException e) {
+				throw new RuntimeException(e.getMessage(), e);
+			}
+		}
+		return conn;
+	}
+
+	public float getAvgTime() {
+		if (avgTime <= 0) {
+			avgTime = getAvgTimeByDistanceLimit(0, 0);
+		}
+
+		return avgTime;
+	}
+
+	public float getAvgTimeByDistance(int distance) {
+		if (avgTimeDistance.get(distance) == null) {
+			avgTimeDistance.put(distance, getAvgTimeByDistanceLimit(distance, 0));
+		}
+
+		return avgTimeDistance.get(distance);
+	}
+
+	public float getAvgTimeWithLimit(int raceLimit) {
+		final float returnValue;
+		switch (raceLimit) {
+		case 5:
+			if (avgTimeLimit5 <= 0) {
+				avgTimeLimit5 = getAvgTimeByDistanceLimit(0, raceLimit);
+			}
+			returnValue = avgTimeLimit5;
+			break;
+		case 10:
+			if (avgTimeLimit10 <= 0) {
+				avgTimeLimit10 = getAvgTimeByDistanceLimit(0, raceLimit);
+			}
+			returnValue = avgTimeLimit10;
+			break;
+		case 15:
+			if (avgTimeLimit15 <= 0) {
+				avgTimeLimit15 = getAvgTimeByDistanceLimit(0, raceLimit);
+			}
+			returnValue = avgTimeLimit15;
+			break;
+
+		default:
+			returnValue = getAvgTimeByDistanceLimit(0, raceLimit);
+			break;
+		}
+		return returnValue;
+	}
+
+	public float getAvgTimeByDistanceLimit(int distance, int raceLimit) {
+		final float returnValue;
+		if (distance > 0 && raceLimit > 0) {
+			switch (raceLimit) {
+			case 5:
+				if (avgTimeDistanceLimit5.get(distance) == null) {
+					avgTimeDistanceLimit5.put(distance, getNewAvgTimeByDistanceLimit(0, raceLimit));
+				}
+				returnValue = avgTimeDistanceLimit5.get(distance);
+				break;
+			case 10:
+				if (avgTimeDistanceLimit10.get(distance) == null) {
+					avgTimeDistanceLimit10.put(distance, getNewAvgTimeByDistanceLimit(0, raceLimit));
+				}
+				returnValue = avgTimeDistanceLimit10.get(distance);
+				break;
+			case 15:
+				if (avgTimeDistanceLimit15.get(distance) == null) {
+					avgTimeDistanceLimit15.put(distance, getNewAvgTimeByDistanceLimit(0, raceLimit));
+				}
+				returnValue = avgTimeDistanceLimit15.get(distance);
+				break;
+
+			default:
+				returnValue = getNewAvgTimeByDistanceLimit(0, raceLimit);
+				break;
+			}
+		} else {
+			returnValue = getNewAvgTimeByDistanceLimit(distance, raceLimit);
+		}
+		return returnValue;
+	}
+
+	public float getNewAvgTimeByDistanceLimit(int distance, int raceLimit) {
+		float returnValue = -1f;
+
+		final String sql = "SELECT ROUND(AVG(t.Time), 2) as avgTime FROM (SELECT AVG(Time) as Time FROM Results WHERE Time > 0 AND Lane > 0 AND RaceDate < NOW()";
+		final String distanceSql = " AND distance BETWEEN ? AND ?";
+		final String groupBySql = " GROUP BY RaceDate";
+		final String orderBySql = " ORDER BY RaceDate";
+		final String limitSql = " DESC LIMIT ?";
+
+		final StringBuilder sb = new StringBuilder();
+		sb.append(sql);
+		boolean orderAppended = false;
+		if (distance > 0) {
+			sb.append(distanceSql);
+			sb.append(groupBySql);
+			sb.append(orderBySql);
+			orderAppended = true;
+		}
+		if (raceLimit > 0) {
+			if (!orderAppended) {
+				sb.append(groupBySql);
+				sb.append(orderBySql);
+			}
+			orderAppended = true;
+			sb.append(limitSql);
+		}
+
+		if (!orderAppended) {
+			sb.append(groupBySql);
+			sb.append(orderBySql);
+		}
+
+		sb.append(") t");
+
+		try {
+			final PreparedStatement stat = getConnection().prepareStatement(sb.toString());
+
+			if (distance > 0) {
+				stat.setInt(1, distance - 50);
+				stat.setInt(2, distance + 50);
+			}
+			if (distance > 0 && raceLimit > 0) {
+				stat.setInt(3, raceLimit);
+			} else if (distance <= 0 && raceLimit > 0) {
+				stat.setInt(1, raceLimit);
+			}
+
+			final ResultSet rs = stat.executeQuery();
+
+			while (rs.next()) {
+				returnValue = rs.getFloat("avgTime");
+			}
+		} catch (final SQLException e) {
+			System.out.println(sb.toString());
+			System.out.println(e.getMessage());
+			e.printStackTrace();
+		}
+		return returnValue;
+	}
 }

+ 209 - 184
ATG/src/database/DriverDB.java

@@ -4,192 +4,217 @@ import java.sql.PreparedStatement;
 import java.sql.ResultSet;
 import java.sql.SQLException;
 
+import com.google.common.base.Strings;
+
 import objects.ResultsDTO;
 
 public class DriverDB extends Database {
 
-    private static DriverDB instance = new DriverDB();
-
-    private DriverDB() {
-    }
-
-    public static DriverDB getInstance() {
-        return instance;
-    }
-
-    /**
-     *
-     * Hämta ut kuskens id från namn
-     *
-     * @param name - Sträng med formatet "LastName firstName"
-     * @return
-     */
-    public int getDriverIdByName(String name) {
-        int returnValue = -1;
-        final String sql = "SELECT id FROM Driver WHERE name = ?";
-
-        try {
-            final PreparedStatement stat = getConnection().prepareStatement(sql);
-            stat.setString(1, name);
-
-            final ResultSet rs = stat.executeQuery();
-
-            while (rs.next()) {
-                returnValue = rs.getInt("id");
-            }
-        } catch (final SQLException e) {
-            e.printStackTrace();
-        }
-
-        return returnValue;
-    }
-
-    public int getDriverTravsportId(int driverId) {
-        int returnValue = -1;
-        final String sql = "SELECT travsportId FROM Driver WHERE id = ?";
-
-        try {
-            final PreparedStatement stat = getConnection().prepareStatement(sql);
-            stat.setInt(1, driverId);
-
-            final ResultSet rs = stat.executeQuery();
-
-            while (rs.next()) {
-                returnValue = rs.getInt("id");
-            }
-        } catch (final SQLException e) {
-            e.printStackTrace();
-        }
-
-        return returnValue;
-    }
-
-    public ResultsDTO avarageTime(int driverId, String date) {
-        return avarageTimeByDistance(driverId, 0, 0, date);
-    }
-
-    public ResultsDTO avarageTimeByDistance(int driverId, int distance, String date) {
-        return avarageTimeByDistance(driverId, distance, 0, date);
-    }
-
-    public ResultsDTO avarageTimeWithLimit(int driverId, int raceLimit, String date) {
-        return avarageTimeByDistance(driverId, 0, raceLimit, date);
-    }
-
-    public ResultsDTO avarageTimeByDistance(int driverId, int distance, int raceLimit, String date) {
-        final ResultsDTO returnValue = new ResultsDTO();
-        final String sql
-                = "SELECT ROUND(AVG(avgRes.Time), 2) as avgTime, count(*) as num FROM (SELECT Time FROM Results WHERE Time > 0 AND Lane > 0 AND RaceDate < NOW() AND DriverId = ?";
-        final String distanceSql = " AND distance BETWEEN ? AND ?";
-        final String limitSql = " LIMIT ?";
-        final String endingSql = ") avgRes";
-        final String orderSql = " ORDER BY RaceDate DESC";
-
-        final StringBuilder sb = new StringBuilder();
-        sb.append(sql);
-
-        boolean orderAppended = false;
-        if (distance > 0) {
-            sb.append(distanceSql);
-            sb.append(orderSql);
-            orderAppended = true;
-        }
-        if (raceLimit > 0) {
-            if (!orderAppended) {
-                sb.append(orderSql);
-                orderAppended = true;
-            }
-            sb.append(limitSql);
-        }
-
-        if (!orderAppended) {
-            sb.append(orderSql);
-        }
-        sb.append(endingSql);
-
-        try {
-            final PreparedStatement stat = getConnection().prepareStatement(sb.toString());
-            stat.setInt(1, driverId);
-            if (distance > 0) {
-                stat.setInt(2, distance - 50);
-                stat.setInt(3, distance + 50);
-            }
-            if (distance > 0 && raceLimit > 0) {
-                stat.setInt(4, raceLimit);
-            } else if (distance <= 0 && raceLimit > 0) {
-                stat.setInt(2, raceLimit);
-            }
-
-            final ResultSet rs = stat.executeQuery();
-
-            while (rs.next()) {
-                returnValue.setRes(rs.getFloat("avgTime"));
-                returnValue.setCount(rs.getInt("num"));
-            }
-        } catch (final SQLException e) {
-            e.printStackTrace();
-            throw new RuntimeException(e);
-        }
-
-        return returnValue;
-    }
-
-    public ResultsDTO avaragePlacement(int driverId, String date) {
-        return avaragePlacementByDistance(driverId, 0, 0, date);
-    }
-
-    public ResultsDTO avaragePlacementByDistance(int driverId, int distance, String date) {
-        return avaragePlacementByDistance(driverId, distance, 0, date);
-    }
-
-    public ResultsDTO avaragePlacementWithLimit(int driverId, int raceLimit, String date) {
-        return avaragePlacementByDistance(driverId, 0, raceLimit, date);
-    }
-
-    public ResultsDTO avaragePlacementByDistance(int driverId, int distance, int raceLimit, String date) {
-        final ResultsDTO returnValue = new ResultsDTO();
-
-        final StringBuilder sb = new StringBuilder();
-        final String sql = "SELECT ROUND(avg(" + "CASE " + "WHEN Result = -1 THEN 9 " + "WHEN Result = -2 THEN 10 "
-                + "WHEN Result = 0 THEN 8 " + "ELSE Result " + "END "
-                + "), 2) as avgResult, count(*) as num FROM (SELECT Result FROM Results WHERE DriverId = ?";
-        final String distSql = " AND distance BETWEEN ? AND ?";
-        final String limitSql = " limit ?";
-
-        sb.append(sql);
-        if (distance > 0) {
-            sb.append(distSql);
-        }
-        if (raceLimit > 0) {
-            sb.append(limitSql);
-        }
-
-        sb.append(") t");
-
-        try {
-            final PreparedStatement stat = getConnection().prepareStatement(sb.toString());
-            stat.setInt(1, driverId);
-            if (distance > 0) {
-                stat.setInt(2, distance - 50);
-                stat.setInt(3, distance + 50);
-            }
-            if (distance > 0 && raceLimit > 0) {
-                stat.setInt(4, raceLimit);
-            } else if (distance <= 0 && raceLimit > 0) {
-                stat.setInt(2, raceLimit);
-            }
-
-            final ResultSet rs = stat.executeQuery();
-
-            while (rs.next()) {
-                returnValue.setRes(rs.getFloat("avgResult"));
-                returnValue.setCount(rs.getInt("num"));
-            }
-        } catch (final SQLException e) {
-            // TODO Auto-generated catch block
-            e.printStackTrace();
-        }
-
-        return returnValue;
-    }
+	private static DriverDB instance = new DriverDB();
+
+	private DriverDB() {
+	}
+
+	public static DriverDB getInstance() {
+		return instance;
+	}
+
+	/**
+	 *
+	 * H�mta ut kuskens id fr�n namn
+	 *
+	 * @param name - Str�ng med formatet "LastName firstName"
+	 * @return
+	 */
+	public int getDriverIdByName(String name) {
+		int returnValue = -1;
+		final String sql = "SELECT id FROM Driver WHERE name = ?";
+
+		try {
+			final PreparedStatement stat = getConnection().prepareStatement(sql);
+			stat.setString(1, name);
+
+			final ResultSet rs = stat.executeQuery();
+
+			while (rs.next()) {
+				returnValue = rs.getInt("id");
+			}
+		} catch (final SQLException e) {
+			e.printStackTrace();
+		}
+
+		return returnValue;
+	}
+
+	public int getDriverTravsportId(int driverId) {
+		int returnValue = -1;
+		final String sql = "SELECT travsportId FROM Driver WHERE id = ?";
+
+		try {
+			final PreparedStatement stat = getConnection().prepareStatement(sql);
+			stat.setInt(1, driverId);
+
+			final ResultSet rs = stat.executeQuery();
+
+			while (rs.next()) {
+				returnValue = rs.getInt("id");
+			}
+		} catch (final SQLException e) {
+			e.printStackTrace();
+		}
+
+		return returnValue;
+	}
+
+	public ResultsDTO avarageTime(int driverId, String date) {
+		return avarageTimeByDistance(driverId, 0, 0, date);
+	}
+
+	public ResultsDTO avarageTimeByDistance(int driverId, int distance, String date) {
+		return avarageTimeByDistance(driverId, distance, 0, date);
+	}
+
+	public ResultsDTO avarageTimeWithLimit(int driverId, int raceLimit, String date) {
+		return avarageTimeByDistance(driverId, 0, raceLimit, date);
+	}
+
+	public ResultsDTO avarageTimeByDistance(int driverId, int distance, int raceLimit, String date) {
+		final ResultsDTO returnValue = new ResultsDTO();
+
+		String dateLimit;
+		if (Strings.isNullOrEmpty(date)) {
+			dateLimit = " AND DATE(RaceDate) < DATE(NOW())";
+		} else {
+			dateLimit = " AND DATE(RaceDate) < DATE('" + date + "')";
+		}
+		final String sql = "SELECT ROUND(AVG(avgRes.Time), 2) as avgTime, count(*) as num FROM (SELECT Time FROM Results WHERE Time > 0 AND Lane > 0"
+				+ dateLimit + " AND DriverId = ?";
+		final String distanceSql = " AND distance BETWEEN ? AND ?";
+		final String limitSql = " LIMIT ?";
+		final String endingSql = ") avgRes";
+		final String orderSql = " ORDER BY RaceDate DESC";
+
+		final StringBuilder sb = new StringBuilder();
+		sb.append(sql);
+
+		boolean orderAppended = false;
+		if (distance > 0) {
+			sb.append(distanceSql);
+			sb.append(orderSql);
+			orderAppended = true;
+		}
+		if (raceLimit > 0) {
+			if (!orderAppended) {
+				sb.append(orderSql);
+				orderAppended = true;
+			}
+			sb.append(limitSql);
+		}
+
+		if (!orderAppended) {
+			sb.append(orderSql);
+		}
+		sb.append(endingSql);
+
+		try {
+			final PreparedStatement stat = getConnection().prepareStatement(sb.toString());
+			stat.setInt(1, driverId);
+			if (distance > 0) {
+				stat.setInt(2, distance - 50);
+				stat.setInt(3, distance + 50);
+			}
+			if (distance > 0 && raceLimit > 0) {
+				stat.setInt(4, raceLimit);
+			} else if (distance <= 0 && raceLimit > 0) {
+				stat.setInt(2, raceLimit);
+			}
+
+			final ResultSet rs = stat.executeQuery();
+
+			while (rs.next()) {
+				returnValue.setRes(rs.getFloat("avgTime"));
+				returnValue.setCount(rs.getInt("num"));
+			}
+		} catch (final SQLException e) {
+			e.printStackTrace();
+			throw new RuntimeException(e);
+		}
+
+		return returnValue;
+	}
+
+	public ResultsDTO avaragePlacement(int driverId, String date) {
+		return avaragePlacementByDistance(driverId, 0, 0, date);
+	}
+
+	public ResultsDTO avaragePlacementByDistance(int driverId, int distance, String date) {
+		return avaragePlacementByDistance(driverId, distance, 0, date);
+	}
+
+	public ResultsDTO avaragePlacementWithLimit(int driverId, int raceLimit, String date) {
+		return avaragePlacementByDistance(driverId, 0, raceLimit, date);
+	}
+
+	public ResultsDTO avaragePlacementByDistance(int driverId, int distance, int raceLimit, String date) {
+		final ResultsDTO returnValue = new ResultsDTO();
+
+		final StringBuilder sb = new StringBuilder();
+		final String sql = "SELECT ROUND(avg(" + "CASE " + "WHEN Result = -1 THEN 9 " + "WHEN Result = -2 THEN 10 " + "WHEN Result = 0 THEN 8 "
+				+ "ELSE Result " + "END " + "), 2) as avgResult, count(*) as num FROM (SELECT Result FROM Results WHERE DriverId = ?";
+		final String distSql = " AND distance BETWEEN ? AND ?";
+		final String limitSql = " limit ?";
+
+		sb.append(sql);
+		if (distance > 0) {
+			sb.append(distSql);
+		}
+		if (raceLimit > 0) {
+			sb.append(limitSql);
+		}
+
+		sb.append(") t");
+
+		try {
+			final PreparedStatement stat = getConnection().prepareStatement(sb.toString());
+			stat.setInt(1, driverId);
+			if (distance > 0) {
+				stat.setInt(2, distance - 50);
+				stat.setInt(3, distance + 50);
+			}
+			if (distance > 0 && raceLimit > 0) {
+				stat.setInt(4, raceLimit);
+			} else if (distance <= 0 && raceLimit > 0) {
+				stat.setInt(2, raceLimit);
+			}
+
+			final ResultSet rs = stat.executeQuery();
+
+			while (rs.next()) {
+				returnValue.setRes(rs.getFloat("avgResult"));
+				returnValue.setCount(rs.getInt("num"));
+			}
+		} catch (final SQLException e) {
+			e.printStackTrace();
+		}
+
+		return returnValue;
+	}
+
+	public String getNameFromId(int driverId) {
+		String result = "";
+		String sql = "SELECT name FROM Driver WHERE id = ?";
+
+		try (PreparedStatement stat = getConnection().prepareStatement(sql)) {
+			stat.setInt(1, driverId);
+			ResultSet rs = stat.executeQuery();
+
+			while (rs.next()) {
+				result = rs.getString("name");
+			}
+
+		} catch (SQLException e) {
+			e.printStackTrace();
+		}
+		return result;
+	}
 }

+ 131 - 132
ATG/src/database/Ekipage.java

@@ -10,136 +10,135 @@ import objects.ResultsDTO;
 
 public class Ekipage extends Database {
 
-    private static Ekipage instance = new Ekipage();
-
-    private Ekipage() {
-    }
-
-    public static Ekipage getInstance() {
-        return instance;
-    }
-
-    public ResultsDTO avarageTime(int driverId, int horseId, String date) {
-        return avarageTimeByDistance(driverId, horseId, 0, 0, date);
-    }
-
-    public ResultsDTO avarageTimeByDistance(int driverId, int horseId, int distance, String date) {
-        return avarageTimeByDistance(driverId, horseId, distance, 0, date);
-    }
-
-    public ResultsDTO avarageTimeWithLimit(int driverId, int horseId, int raceLimit, String date) {
-        return avarageTimeByDistance(driverId, horseId, 0, raceLimit, date);
-    }
-
-    public ResultsDTO avarageTimeByDistance(int driverId, int horseId, int distance, int raceLimit, String date) {
-        final ResultsDTO returnValue = new ResultsDTO();
-        final String d = Strings.isNullOrEmpty(date) ? "NOW()" : date;
-        final String sql = "SELECT ROUND(AVG(avgRes.Time), 2) as avgTime, count(*) as num FROM (SELECT Time FROM Results "
-                + "WHERE Time > 0 AND Lane > 0 AND RaceDate < ? AND DriverId = ? AND horseId = ?";
-        final String distanceSql = " AND distance BETWEEN ? AND ?";
-        final String limitSql = " LIMIT ?";
-        final String endingSql = ") avgRes";
-
-        final StringBuilder sb = new StringBuilder();
-        sb.append(sql);
-
-        if (distance > 0) {
-            sb.append(distanceSql);
-        }
-        if (raceLimit > 0) {
-            sb.append(limitSql);
-        }
-
-        sb.append(endingSql);
-
-        try {
-            final PreparedStatement stat = getConnection().prepareStatement(sb.toString());
-            stat.setString(1, d);
-            stat.setInt(2, driverId);
-            stat.setInt(3, horseId);
-            if (distance > 0) {
-                stat.setInt(4, distance - 50);
-                stat.setInt(5, distance + 50);
-            }
-            if (distance > 0 && raceLimit > 0) {
-                stat.setInt(6, raceLimit);
-            } else if (distance <= 0 && raceLimit > 0) {
-                stat.setInt(4, raceLimit);
-            }
-
-            final ResultSet rs = stat.executeQuery();
-
-            while (rs.next()) {
-                returnValue.setRes(rs.getFloat("avgTime"));
-                returnValue.setCount(rs.getInt("num"));
-            }
-        } catch (final SQLException e) {
-            e.printStackTrace();
-            throw new RuntimeException(e);
-        }
-
-        return returnValue;
-    }
-
-    public ResultsDTO avaragePlacement(int driverId, int horseId, String date) {
-        return avaragePlacementByDistance(driverId, horseId, 0, 0, date);
-    }
-
-    public ResultsDTO avaragePlacementByDistance(int driverId, int horseId, int distance, String date) {
-        return avaragePlacementByDistance(driverId, horseId, distance, 0, date);
-    }
-
-    public ResultsDTO avaragePlacementWithLimit(int driverId, int horseId, int raceLimit, String date) {
-        return avaragePlacementByDistance(driverId, horseId, 0, raceLimit, date);
-    }
-
-    public ResultsDTO avaragePlacementByDistance(int driverId, int horseId, int distance, int raceLimit, String date) {
-        final ResultsDTO returnValue = new ResultsDTO();
-
-        final String d = Strings.isNullOrEmpty(date) ? "NOW()" : date;
-        final StringBuilder sb = new StringBuilder();
-        final String sql = "SELECT ROUND(avg(" + "CASE " + "WHEN Result = -1 THEN 9 WHEN Result = -2 THEN 10"
-                + " WHEN Result = 0 THEN 8" + " ELSE Result " + "END"
-                + " ), 2) as avgResult, count(*) as num FROM (SELECT Result FROM Results WHERE RaceDate < ? AND DriverId = ? AND horseId = ?";
-        final String distSql = " AND distance BETWEEN ? AND ?";
-        final String limitSql = " limit ?";
-
-        sb.append(sql);
-        if (distance > 0) {
-            sb.append(distSql);
-        }
-        if (raceLimit > 0) {
-            sb.append(limitSql);
-        }
-
-        sb.append(") as t");
-
-        try {
-            final PreparedStatement stat = getConnection().prepareStatement(sb.toString());
-            stat.setString(1, d);
-            stat.setInt(2, driverId);
-            stat.setInt(3, horseId);
-            if (distance > 0) {
-                stat.setInt(4, distance - 50);
-                stat.setInt(5, distance + 50);
-            }
-            if (distance > 0 && raceLimit > 0) {
-                stat.setInt(6, raceLimit);
-            } else if (distance <= 0 && raceLimit > 0) {
-                stat.setInt(4, raceLimit);
-            }
-
-            final ResultSet rs = stat.executeQuery();
-
-            while (rs.next()) {
-                returnValue.setRes(rs.getFloat("avgResult"));
-                returnValue.setCount(rs.getInt("num"));
-            }
-        } catch (final SQLException e) {
-            // TODO Auto-generated catch block
-            e.printStackTrace();
-        }
-
-        return returnValue;
-    }
+	private static Ekipage instance = new Ekipage();
+
+	private Ekipage() {
+	}
+
+	public static Ekipage getInstance() {
+		return instance;
+	}
+
+	public ResultsDTO avarageTime(int driverId, int horseId, String date) {
+		return avarageTimeByDistance(driverId, horseId, 0, 0, date);
+	}
+
+	public ResultsDTO avarageTimeByDistance(int driverId, int horseId, int distance, String date) {
+		return avarageTimeByDistance(driverId, horseId, distance, 0, date);
+	}
+
+	public ResultsDTO avarageTimeWithLimit(int driverId, int horseId, int raceLimit, String date) {
+		return avarageTimeByDistance(driverId, horseId, 0, raceLimit, date);
+	}
+
+	public ResultsDTO avarageTimeByDistance(int driverId, int horseId, int distance, int raceLimit, String date) {
+		final ResultsDTO returnValue = new ResultsDTO();
+		final String d = Strings.isNullOrEmpty(date) ? "NOW()" : date;
+		final String sql = "SELECT ROUND(AVG(avgRes.Time), 2) as avgTime, count(*) as num FROM (SELECT Time FROM Results "
+				+ "WHERE Time > 0 AND Lane > 0 AND RaceDate < ? AND DriverId = ? AND horseId = ?";
+		final String distanceSql = " AND distance BETWEEN ? AND ?";
+		final String limitSql = " LIMIT ?";
+		final String endingSql = ") avgRes";
+
+		final StringBuilder sb = new StringBuilder();
+		sb.append(sql);
+
+		if (distance > 0) {
+			sb.append(distanceSql);
+		}
+		if (raceLimit > 0) {
+			sb.append(limitSql);
+		}
+
+		sb.append(endingSql);
+
+		try {
+			final PreparedStatement stat = getConnection().prepareStatement(sb.toString());
+			stat.setString(1, d);
+			stat.setInt(2, driverId);
+			stat.setInt(3, horseId);
+			if (distance > 0) {
+				stat.setInt(4, distance - 50);
+				stat.setInt(5, distance + 50);
+			}
+			if (distance > 0 && raceLimit > 0) {
+				stat.setInt(6, raceLimit);
+			} else if (distance <= 0 && raceLimit > 0) {
+				stat.setInt(4, raceLimit);
+			}
+
+			final ResultSet rs = stat.executeQuery();
+
+			while (rs.next()) {
+				returnValue.setRes(rs.getFloat("avgTime"));
+				returnValue.setCount(rs.getInt("num"));
+			}
+		} catch (final SQLException e) {
+			e.printStackTrace();
+			throw new RuntimeException(e);
+		}
+
+		return returnValue;
+	}
+
+	public ResultsDTO avaragePlacement(int driverId, int horseId, String date) {
+		return avaragePlacementByDistance(driverId, horseId, 0, 0, date);
+	}
+
+	public ResultsDTO avaragePlacementByDistance(int driverId, int horseId, int distance, String date) {
+		return avaragePlacementByDistance(driverId, horseId, distance, 0, date);
+	}
+
+	public ResultsDTO avaragePlacementWithLimit(int driverId, int horseId, int raceLimit, String date) {
+		return avaragePlacementByDistance(driverId, horseId, 0, raceLimit, date);
+	}
+
+	public ResultsDTO avaragePlacementByDistance(int driverId, int horseId, int distance, int raceLimit, String date) {
+		final ResultsDTO returnValue = new ResultsDTO();
+
+		final String d = Strings.isNullOrEmpty(date) ? "NOW()" : date;
+		final StringBuilder sb = new StringBuilder();
+		final String sql = "SELECT ROUND(avg(" + "CASE " + "WHEN Result = -1 THEN 9 WHEN Result = -2 THEN 10" + " WHEN Result = 0 THEN 8"
+				+ " ELSE Result " + "END"
+				+ " ), 2) as avgResult, count(*) as num FROM (SELECT Result FROM Results WHERE RaceDate < ? AND DriverId = ? AND horseId = ?";
+		final String distSql = " AND distance BETWEEN ? AND ?";
+		final String limitSql = " limit ?";
+
+		sb.append(sql);
+		if (distance > 0) {
+			sb.append(distSql);
+		}
+		if (raceLimit > 0) {
+			sb.append(limitSql);
+		}
+
+		sb.append(") as t");
+
+		try {
+			final PreparedStatement stat = getConnection().prepareStatement(sb.toString());
+			stat.setString(1, d);
+			stat.setInt(2, driverId);
+			stat.setInt(3, horseId);
+			if (distance > 0) {
+				stat.setInt(4, distance - 50);
+				stat.setInt(5, distance + 50);
+			}
+			if (distance > 0 && raceLimit > 0) {
+				stat.setInt(6, raceLimit);
+			} else if (distance <= 0 && raceLimit > 0) {
+				stat.setInt(4, raceLimit);
+			}
+
+			final ResultSet rs = stat.executeQuery();
+
+			while (rs.next()) {
+				returnValue.setRes(rs.getFloat("avgResult"));
+				returnValue.setCount(rs.getInt("num"));
+			}
+		} catch (final SQLException e) {
+			e.printStackTrace();
+		}
+
+		return returnValue;
+	}
 }

+ 221 - 203
ATG/src/database/Horse.java

@@ -10,207 +10,225 @@ import objects.ResultsDTO;
 
 public class Horse extends Database {
 
-    private static Horse instance = new Horse();
-
-    private Horse() {
-    }
-
-    public static Horse getInstance() {
-        return instance;
-    }
-
-    /**
-     *
-     * Hämta ut kuskens id från namn
-     *
-     * @param name - Sträng med formatet "LastName firstName"
-     * @return
-     */
-    public int getHorseIdByName(String name) {
-        int returnValue = -1;
-        final String sql = "SELECT id FROM Horse WHERE name = ?";
-
-        try {
-            final PreparedStatement stat = getConnection().prepareStatement(sql);
-            stat.setString(1, name);
-
-            final ResultSet rs = stat.executeQuery();
-
-            while (rs.next()) {
-                returnValue = rs.getInt("id");
-            }
-        } catch (final SQLException e) {
-            e.printStackTrace();
-        }
-
-        return returnValue;
-    }
-
-    public int getHorseTravsportId(int horseId) {
-        int returnValue = -1;
-        final String sql = "SELECT travsportId FROM Horse WHERE id = ?";
-
-        try {
-            final PreparedStatement stat = getConnection().prepareStatement(sql);
-            stat.setInt(1, horseId);
-
-            final ResultSet rs = stat.executeQuery();
-
-            while (rs.next()) {
-                returnValue = rs.getInt("id");
-            }
-        } catch (final SQLException e) {
-            e.printStackTrace();
-        }
-
-        return returnValue;
-    }
-
-    public ResultsDTO avarageTime(int horseId, String date) {
-        return avarageTimeByDistance(horseId, 0, 0, date);
-    }
-
-    public ResultsDTO avarageTimeByDistance(int horseId, int distance, String date) {
-        return avarageTimeByDistance(horseId, distance, 0, date);
-    }
-
-    public ResultsDTO avarageTimeWithLimit(int horseId, int raceLimit, String date) {
-        return avarageTimeByDistance(horseId, 0, raceLimit, date);
-    }
-
-    public ResultsDTO avarageTimeByDistance(int horseId, int distance, int raceLimit, String date) {
-        final ResultsDTO returnValue = new ResultsDTO();
-
-        final String d = Strings.isNullOrEmpty(date) ? "NOW()" : date;
-
-        final String sql = "SELECT ROUND(AVG(avgRes.Time), 2) as avgTime, count(*) as num FROM "
-                + "(SELECT Time as Time FROM Results WHERE Time > 0 AND Lane > 0 AND RaceDate < ? AND HorseId = ?";
-        final String distanceSql = " AND distance BETWEEN ? AND ?";
-        final String limitSql = " LIMIT ?";
-        final String endingSql = ") avgRes";
-        final String orderSql = " ORDER BY RaceDate DESC";
-
-        final StringBuilder sb = new StringBuilder();
-        sb.append(sql);
-
-        boolean orderAppended = false;
-        if (distance > 0) {
-            sb.append(distanceSql);
-            sb.append(orderSql);
-            orderAppended = true;
-        }
-        if (raceLimit > 0) {
-            if (!orderAppended) {
-                sb.append(orderSql);
-                orderAppended = true;
-            }
-            sb.append(limitSql);
-        }
-
-        if (!orderAppended) {
-            sb.append(orderSql);
-        }
-        sb.append(endingSql);
-
-        try {
-            final PreparedStatement stat = getConnection().prepareStatement(sb.toString());
-            stat.setString(1, d);
-            stat.setInt(2, horseId);
-            if (distance > 0) {
-                stat.setInt(3, distance - 50);
-                stat.setInt(4, distance + 50);
-            }
-            if (distance > 0 && raceLimit > 0) {
-                stat.setInt(5, raceLimit);
-            } else if (distance <= 0 && raceLimit > 0) {
-                stat.setInt(3, raceLimit);
-            }
-
-            final ResultSet rs = stat.executeQuery();
-
-            while (rs.next()) {
-                returnValue.setRes(rs.getFloat("avgTime"));
-                returnValue.setCount(rs.getInt("num"));
-            }
-        } catch (final SQLException e) {
-            e.printStackTrace();
-            throw new RuntimeException(e);
-        }
-
-        return returnValue;
-    }
-
-    public ResultsDTO avaragePlacement(int horseId, String date) {
-        return avaragePlacementByDistance(horseId, 0, 0, date);
-    }
-
-    public ResultsDTO avaragePlacementByDistance(int horseId, int distance, String date) {
-        return avaragePlacementByDistance(horseId, distance, 0, date);
-    }
-
-    public ResultsDTO avaragePlacementWithLimit(int horseId, int raceLimit, String date) {
-        return avaragePlacementByDistance(horseId, 0, raceLimit, date);
-    }
-
-    public ResultsDTO avaragePlacementByDistance(int horseId, int distance, int raceLimit, String date) {
-        final ResultsDTO returnValue = new ResultsDTO();
-
-        final String d = Strings.isNullOrEmpty(date) ? "NOW()" : date;
-
-        final StringBuilder sb = new StringBuilder();
-        final String sql = "SELECT ROUND(avg(" + "CASE " + "WHEN Result = -1 THEN 9 WHEN Result = -2 THEN 10 "
-                + "WHEN Result = 0 THEN 8 ELSE Result END"
-                + "), 2) as avgResult, count(*) as num FROM (SELECT Result FROM Results WHERE RaceDate < DATE(?) AND HorseId = ?";
-        final String distSql = " AND distance BETWEEN ? AND ?";
-        final String limitSql = " limit ?";
-        final String orderBySql = " ORDER BY RaceDate DESC";
-
-        sb.append(sql);
-        boolean orderAppended = false;
-        if (distance > 0) {
-            sb.append(distSql);
-            sb.append(orderBySql);
-            orderAppended = true;
-        }
-        if (raceLimit > 0) {
-            if (!orderAppended) {
-                sb.append(orderBySql);
-                orderAppended = true;
-            }
-            sb.append(limitSql);
-        }
-
-        if (!orderAppended) {
-            sb.append(orderBySql);
-        }
-
-        sb.append(") avgRes");
-
-        try {
-            final PreparedStatement stat = getConnection().prepareStatement(sb.toString());
-            stat.setString(1, d);
-            stat.setInt(2, horseId);
-            if (distance > 0) {
-                stat.setInt(3, distance - 50);
-                stat.setInt(4, distance + 50);
-            }
-            if (distance > 0 && raceLimit > 0) {
-                stat.setInt(5, raceLimit);
-            } else if (distance <= 0 && raceLimit > 0) {
-                stat.setInt(3, raceLimit);
-            }
-
-            final ResultSet rs = stat.executeQuery();
-
-            while (rs.next()) {
-                returnValue.setRes(rs.getFloat("avgResult"));
-                returnValue.setCount(rs.getInt("num"));
-            }
-        } catch (final SQLException e) {
-            e.printStackTrace();
-            System.out.println(sb.toString());
-        }
-
-        return returnValue;
-    }
+	private static Horse instance = new Horse();
+
+	private Horse() {
+	}
+
+	public static Horse getInstance() {
+		return instance;
+	}
+
+	/**
+	 *
+	 * H�mta ut kuskens id fr�n namn
+	 *
+	 * @param name - Str�ng med formatet "LastName firstName"
+	 * @return
+	 */
+	public int getHorseIdByName(String name) {
+		int returnValue = -1;
+		final String sql = "SELECT id FROM Horse WHERE name = ?";
+
+		try {
+			final PreparedStatement stat = getConnection().prepareStatement(sql);
+			stat.setString(1, name);
+
+			final ResultSet rs = stat.executeQuery();
+
+			while (rs.next()) {
+				returnValue = rs.getInt("id");
+			}
+		} catch (final SQLException e) {
+			e.printStackTrace();
+		}
+
+		return returnValue;
+	}
+
+	public int getHorseTravsportId(int horseId) {
+		int returnValue = -1;
+		final String sql = "SELECT travsportId FROM Horse WHERE id = ?";
+
+		try {
+			final PreparedStatement stat = getConnection().prepareStatement(sql);
+			stat.setInt(1, horseId);
+
+			final ResultSet rs = stat.executeQuery();
+
+			while (rs.next()) {
+				returnValue = rs.getInt("id");
+			}
+		} catch (final SQLException e) {
+			e.printStackTrace();
+		}
+
+		return returnValue;
+	}
+
+	public ResultsDTO avarageTime(int horseId, String date) {
+		return avarageTimeByDistance(horseId, 0, 0, date);
+	}
+
+	public ResultsDTO avarageTimeByDistance(int horseId, int distance, String date) {
+		return avarageTimeByDistance(horseId, distance, 0, date);
+	}
+
+	public ResultsDTO avarageTimeWithLimit(int horseId, int raceLimit, String date) {
+		return avarageTimeByDistance(horseId, 0, raceLimit, date);
+	}
+
+	public ResultsDTO avarageTimeByDistance(int horseId, int distance, int raceLimit, String date) {
+		final ResultsDTO returnValue = new ResultsDTO();
+
+		final String d = Strings.isNullOrEmpty(date) ? "NOW()" : date;
+
+		final String sql = "SELECT ROUND(AVG(avgRes.Time), 2) as avgTime, count(*) as num FROM "
+				+ "(SELECT Time as Time FROM Results WHERE Time > 0 AND Lane > 0 AND RaceDate < ? AND HorseId = ?";
+		final String distanceSql = " AND distance BETWEEN ? AND ?";
+		final String limitSql = " LIMIT ?";
+		final String endingSql = ") avgRes";
+		final String orderSql = " ORDER BY RaceDate DESC";
+
+		final StringBuilder sb = new StringBuilder();
+		sb.append(sql);
+
+		boolean orderAppended = false;
+		if (distance > 0) {
+			sb.append(distanceSql);
+			sb.append(orderSql);
+			orderAppended = true;
+		}
+		if (raceLimit > 0) {
+			if (!orderAppended) {
+				sb.append(orderSql);
+				orderAppended = true;
+			}
+			sb.append(limitSql);
+		}
+
+		if (!orderAppended) {
+			sb.append(orderSql);
+		}
+		sb.append(endingSql);
+
+		try {
+			final PreparedStatement stat = getConnection().prepareStatement(sb.toString());
+			stat.setString(1, d);
+			stat.setInt(2, horseId);
+			if (distance > 0) {
+				stat.setInt(3, distance - 50);
+				stat.setInt(4, distance + 50);
+			}
+			if (distance > 0 && raceLimit > 0) {
+				stat.setInt(5, raceLimit);
+			} else if (distance <= 0 && raceLimit > 0) {
+				stat.setInt(3, raceLimit);
+			}
+
+			final ResultSet rs = stat.executeQuery();
+
+			while (rs.next()) {
+				returnValue.setRes(rs.getFloat("avgTime"));
+				returnValue.setCount(rs.getInt("num"));
+			}
+		} catch (final SQLException e) {
+			e.printStackTrace();
+			throw new RuntimeException(e);
+		}
+
+		return returnValue;
+	}
+
+	public ResultsDTO avaragePlacement(int horseId, String date) {
+		return avaragePlacementByDistance(horseId, 0, 0, date);
+	}
+
+	public ResultsDTO avaragePlacementByDistance(int horseId, int distance, String date) {
+		return avaragePlacementByDistance(horseId, distance, 0, date);
+	}
+
+	public ResultsDTO avaragePlacementWithLimit(int horseId, int raceLimit, String date) {
+		return avaragePlacementByDistance(horseId, 0, raceLimit, date);
+	}
+
+	public ResultsDTO avaragePlacementByDistance(int horseId, int distance, int raceLimit, String date) {
+		final ResultsDTO returnValue = new ResultsDTO();
+
+		final String d = Strings.isNullOrEmpty(date) ? "NOW()" : date;
+
+		final StringBuilder sb = new StringBuilder();
+		final String sql = "SELECT ROUND(avg(" + "CASE " + "WHEN Result = -1 THEN 9 WHEN Result = -2 THEN 10 "
+				+ "WHEN Result = 0 THEN 8 ELSE Result END"
+				+ "), 2) as avgResult, count(*) as num FROM (SELECT Result FROM Results WHERE RaceDate < DATE(?) AND HorseId = ?";
+		final String distSql = " AND distance BETWEEN ? AND ?";
+		final String limitSql = " limit ?";
+		final String orderBySql = " ORDER BY RaceDate DESC";
+
+		sb.append(sql);
+		boolean orderAppended = false;
+		if (distance > 0) {
+			sb.append(distSql);
+			sb.append(orderBySql);
+			orderAppended = true;
+		}
+		if (raceLimit > 0) {
+			if (!orderAppended) {
+				sb.append(orderBySql);
+				orderAppended = true;
+			}
+			sb.append(limitSql);
+		}
+
+		if (!orderAppended) {
+			sb.append(orderBySql);
+		}
+
+		sb.append(") avgRes");
+
+		try {
+			final PreparedStatement stat = getConnection().prepareStatement(sb.toString());
+			stat.setString(1, d);
+			stat.setInt(2, horseId);
+			if (distance > 0) {
+				stat.setInt(3, distance - 50);
+				stat.setInt(4, distance + 50);
+			}
+			if (distance > 0 && raceLimit > 0) {
+				stat.setInt(5, raceLimit);
+			} else if (distance <= 0 && raceLimit > 0) {
+				stat.setInt(3, raceLimit);
+			}
+
+			final ResultSet rs = stat.executeQuery();
+
+			while (rs.next()) {
+				returnValue.setRes(rs.getFloat("avgResult"));
+				returnValue.setCount(rs.getInt("num"));
+			}
+		} catch (final SQLException e) {
+			e.printStackTrace();
+			System.out.println(sb.toString());
+		}
+
+		return returnValue;
+	}
+
+	public String getNameFromId(int horseId) {
+		String result = "";
+		String sql = "SELECT name FROM Horse WHERE id = ?";
+
+		try (PreparedStatement stat = getConnection().prepareStatement(sql)) {
+			stat.setInt(1, horseId);
+			ResultSet rs = stat.executeQuery();
+
+			while (rs.next()) {
+				result = rs.getString("name");
+			}
+
+		} catch (SQLException e) {
+			e.printStackTrace();
+		}
+		return result;
+	}
 }

+ 5 - 0
ATG/src/fxml/AtgMain.fxml

@@ -72,6 +72,11 @@
             		<fx:include fx:id="NewTab" source="NewTab/NewTab.fxml" />
             	</content>
             </Tab>
+            <Tab text="AutoPicker">
+            	<content>
+            		<fx:include fx:id="NewTab" source="AutoPicker/AutoPicker.fxml" />
+            	</content>
+            </Tab>
          </tabs>
       </TabPane>
    </children>

+ 31 - 0
ATG/src/fxml/AutoPicker/AutoPicker.fxml

@@ -0,0 +1,31 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<?import javafx.scene.control.Button?>
+<?import javafx.scene.control.DatePicker?>
+<?import javafx.scene.control.TabPane?>
+<?import javafx.scene.layout.AnchorPane?>
+<?import javafx.scene.layout.BorderPane?>
+<?import javafx.scene.layout.FlowPane?>
+<?import javafx.scene.layout.Pane?>
+
+<AnchorPane prefHeight="1000.0" prefWidth="1600.0" xmlns="http://javafx.com/javafx/18" xmlns:fx="http://javafx.com/fxml/1" fx:controller="controllers.AutoPickerController">
+   <children>
+      <BorderPane prefHeight="1000.0" prefWidth="1600.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
+         <top>
+            <FlowPane nodeOrientation="LEFT_TO_RIGHT" orientation="VERTICAL" prefHeight="30.0" BorderPane.alignment="CENTER">
+               <children>
+                  <DatePicker fx:id="datePicker" />
+                  <Button fx:id="submitButton" disable="true" mnemonicParsing="false" onAction="#submitAction" text="Submit" />
+                  <Button fx:id="autoPickButton" disable="true" mnemonicParsing="false" text="AutoPick" onAction="#autoPickAction" />
+               </children>
+            </FlowPane>
+         </top>
+         <left>
+            <TabPane fx:id="locationTabs" minWidth="100.0" prefWidth="200.0" tabClosingPolicy="UNAVAILABLE" BorderPane.alignment="CENTER" />
+         </left>
+         <center>
+            <Pane fx:id="mainContentPane" BorderPane.alignment="CENTER" />
+         </center>
+      </BorderPane>
+   </children>
+</AnchorPane>

+ 3 - 1
ATG/src/fxml/TestingTab.fxml

@@ -11,7 +11,7 @@
 <?import javafx.scene.layout.RowConstraints?>
 <?import javafx.scene.text.Font?>
 
-<AnchorPane prefHeight="800.0" prefWidth="800.0" xmlns="http://javafx.com/javafx/15.0.1" xmlns:fx="http://javafx.com/fxml/1" fx:controller="controllers.TestingTabController">
+<AnchorPane prefHeight="800.0" prefWidth="800.0" xmlns="http://javafx.com/javafx/18" xmlns:fx="http://javafx.com/fxml/1" fx:controller="controllers.TestingTabController">
    <children>
       <BorderPane layoutX="-4.0" prefHeight="800.0" prefWidth="800.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
          <center>
@@ -90,6 +90,8 @@
                      <children>
                         <Button fx:id="resetSettings" mnemonicParsing="false" onAction="#resetSettingsAction" text="Reset Settings" />
                         <Button fx:id="calculateButton" mnemonicParsing="false" onAction="#CalculateAction" text="Calculate" />
+                        <Button mnemonicParsing="false" onAction="#calculateMostRelevantValue" text="CalcMostRelevant" />
+                        <Button mnemonicParsing="false" onAction="#testBestValue" text="Calculate best value" />
                      </children>
                   </FlowPane>
                </bottom>

+ 33 - 33
ATG/src/objects/RaceTableView.java

@@ -42,7 +42,7 @@ public class RaceTableView extends Tab {
 
 	private TableColumn<ComparingResultsData, String> lastRacesColumnCombined;
 
-	public RaceTableView(SimpleEntry<String,List<HorseRaceData>> trackRaces) {
+	public RaceTableView(SimpleEntry<String, List<HorseRaceData>> trackRaces) {
 
 		setText(trackRaces.getKey());
 		this.trackRaces = trackRaces.getValue();
@@ -52,8 +52,8 @@ public class RaceTableView extends Tab {
 		this.setContent(racesTabs);
 
 		for (final Integer rn : raceNumbers) {
-			addRaceNumberTab(rn, ComparingResultsData.convertHorseRaceDataList(
-					this.trackRaces.stream().filter(p -> p.getRaceNumber() == rn).collect(Collectors.toList())));
+			addRaceNumberTab(rn, ComparingResultsData
+					.convertHorseRaceDataList(this.trackRaces.stream().filter(p -> p.getRaceNumber() == rn).collect(Collectors.toList())));
 		}
 	}
 
@@ -69,7 +69,8 @@ public class RaceTableView extends Tab {
 		}
 
 		for (final ComparingResultsData data : races) {
-			final Optional<LaneWinObject> laneWin = laneWinPercents.stream().filter(p -> p.getDistance() == data.getDistance() && p.getLane() == data.getLane()).findFirst();
+			final Optional<LaneWinObject> laneWin = laneWinPercents.stream()
+					.filter(p -> p.getDistance() == data.getDistance() && p.getLane() == data.getLane()).findFirst();
 			if (laneWin.isPresent()) {
 				data.setLaneWin(laneWin.get().getPercent());
 			} else {
@@ -124,29 +125,25 @@ public class RaceTableView extends Tab {
 		}
 
 		ratingLastResultList.sort(new Comparator<SimpleEntry<Integer, Float>>() {
-			@Override
-			public int compare(SimpleEntry<Integer, Float> o1, SimpleEntry<Integer, Float> o2) {
+			@Override public int compare(SimpleEntry<Integer, Float> o1, SimpleEntry<Integer, Float> o2) {
 				return o1.getValue().compareTo(o2.getValue());
 			}
 		});
 
 		ratingSumHorseList.sort(new Comparator<SimpleEntry<Integer, Float>>() {
-			@Override
-			public int compare(SimpleEntry<Integer, Float> o1, SimpleEntry<Integer, Float> o2) {
+			@Override public int compare(SimpleEntry<Integer, Float> o1, SimpleEntry<Integer, Float> o2) {
 				return o1.getValue().compareTo(o2.getValue());
 			}
 		});
 
 		ratingSumDriverList.sort(new Comparator<SimpleEntry<Integer, Float>>() {
-			@Override
-			public int compare(SimpleEntry<Integer, Float> o1, SimpleEntry<Integer, Float> o2) {
+			@Override public int compare(SimpleEntry<Integer, Float> o1, SimpleEntry<Integer, Float> o2) {
 				return o1.getValue().compareTo(o2.getValue());
 			}
 		});
 
 		sumRating.sort(new Comparator<SimpleEntry<Integer, Float>>() {
-			@Override
-			public int compare(SimpleEntry<Integer, Float> o1, SimpleEntry<Integer, Float> o2) {
+			@Override public int compare(SimpleEntry<Integer, Float> o1, SimpleEntry<Integer, Float> o2) {
 				return o1.getValue().compareTo(o2.getValue());
 			}
 		});
@@ -170,9 +167,9 @@ public class RaceTableView extends Tab {
 		for (final SimpleEntry<Integer, Float> r : sumRating) {
 			races.get(r.getKey()).setSumRatings(i++);
 		}
-		//		for (final ComparingResultsData crd : races) {
-		//			crd.setRatingLastResultsTotal(ratingLastResultList.get(i++).getKey());
-		//		}
+		// for (final ComparingResultsData crd : races) {
+		// crd.setRatingLastResultsTotal(ratingLastResultList.get(i++).getKey());
+		// }
 
 		table.getColumns().add(ratingLastResult);
 		table.getColumns().add(ratingSumHorse);
@@ -197,7 +194,8 @@ public class RaceTableView extends Tab {
 		for (final ComparingResultsData crd : races) {
 			final String lastRacesDriver = db.getLastResults(crd.getDriverId(), 0, crd.getRaceDate(), crd.getRaceNumber(), count, "Driver");
 			final String lastRacesHorse = db.getLastResults(crd.getHorseId(), 0, crd.getRaceDate(), crd.getRaceNumber(), count, "Horse");
-			final String lastRacesBoth = db.getLastResults(crd.getDriverId(), crd.getHorseId(), crd.getRaceDate(), crd.getRaceNumber(), count, "Both");
+			final String lastRacesBoth = db.getLastResults(crd.getDriverId(), crd.getHorseId(), crd.getRaceDate(), crd.getRaceNumber(), count,
+					"Both");
 
 			crd.setLastRacesDriver(lastRacesDriver);
 			crd.setLastRacesHorse(lastRacesHorse);
@@ -253,13 +251,16 @@ public class RaceTableView extends Tab {
 				totalAvaragesDriver = db.getTrackAvarages("", distances, crd.getRaceDate(), -1, true);
 
 			}
-			// byt till track avg Horse, behöver inte vara lane specifikt Gäller hela funktionen... eller skapa en ny
+			// byt till track avg Horse, beh�ver inte vara lane specifikt G�ller hela
+			// funktionen... eller skapa en ny
 			final Float valueHorse2 = db.getTrackAvarage(trackName, distances, crd.getRaceDate(), crd.getHorseId(), false) - trackAvarageHorse;
-			//			final Float valueHorse = getAvgValueHorse(db, distances, trackAvaragesHorse, crd);
+			// final Float valueHorse = getAvgValueHorse(db, distances, trackAvaragesHorse,
+			// crd);
 			crd.setAvgTimeHorseChange(valueHorse2);
 
 			final Float valueDriver2 = db.getTrackAvarage(trackName, distances, crd.getRaceDate(), crd.getDriverId(), true) - trackAvarageDriver;
-			//			final Float valueDriver = getAvgValueDriver(db, distances, trackAvaragesDriver, crd);
+			// final Float valueDriver = getAvgValueDriver(db, distances,
+			// trackAvaragesDriver, crd);
 			crd.setAvgTimeDriverChange(valueDriver2);
 
 			final Float trackAvarageDriverValue = db.getTrackAvarage(trackName, distances, crd.getRaceDate(), crd.getDriverId(), true);
@@ -271,7 +272,6 @@ public class RaceTableView extends Tab {
 			crd.setSumAvgTimeDriver(trackAvarageDriverValue + valueDriver2);
 		}
 
-
 		table.getColumns().add(avgTimeColumnHorse);
 		table.getColumns().add(avgTimeColumnHorseChange);
 		table.getColumns().add(sumAvgTimeColumnHorse);
@@ -296,26 +296,27 @@ public class RaceTableView extends Tab {
 			}
 		}
 
-		final List<SimpleEntry<Integer, Float>> horseAvges = db.getTrackAvarages(crd.getTrackName(), distances, crd.getRaceDate(), crd.getHorseId(), false);
+		final List<SimpleEntry<Integer, Float>> horseAvges = db.getTrackAvarages(crd.getTrackName(), distances, crd.getRaceDate(), crd.getHorseId(),
+				false);
 		final Optional<SimpleEntry<Integer, Float>> horseAvg = horseAvges.stream().filter(p -> p.getKey() == crd.getLane()).findFirst();
 
 		if (horseAvg.isPresent() && horseAvg.get().getValue() > 0f) {
-			// Om hästens snitt tid för spåret
+			// Om hästens snitt tid för spåret
 			laneAvg = horseAvg.get().getValue() - laneAvg;
 		} else {
-			// FIXME Här hämtas hästens allmäna tid ut, markera detta??
 			final List<SimpleEntry<Integer, Float>> horseAvges2 = db.getTrackAvarages("", distances, crd.getRaceDate(), crd.getHorseId(), false);
 			final Optional<SimpleEntry<Integer, Float>> horseAvg2 = horseAvges.stream().filter(p -> p.getKey() == crd.getLane()).findFirst();
 			if (horseAvg2.isPresent() && horseAvg2.get().getValue() > 0f) {
 				laneAvg = horseAvg2.get().getValue() - laneAvg;
 			} else {
-				// Hästen helt oprövad på distances, markeras hur?
+				// H�sten helt opr�vad p� distances, markeras hur?
 				final float newVal;
-				final double sum = horseAvges2.stream().mapToDouble(m -> m.getValue() > 0?m.getValue():30f).sum();
+				final double sum = horseAvges2.stream().mapToDouble(m -> m.getValue() > 0 ? m.getValue() : 30f).sum();
 				if (sum > 0) {
 					newVal = (float) (sum / horseAvges2.size());
 				} else {
-					//						newVal = (float)totalAvarages.stream().mapToDouble(m -> m.getValue()).max().orElse(30f);
+					// newVal = (float)totalAvarages.stream().mapToDouble(m ->
+					// m.getValue()).max().orElse(30f);
 					newVal = 30f;
 				}
 				laneAvg = newVal - laneAvg;
@@ -324,8 +325,6 @@ public class RaceTableView extends Tab {
 		return laneAvg;
 	}
 
-
-
 	private Float getAvgValueDriver(final DatabaseController db, final ArrayList<Integer> distances,
 			final List<SimpleEntry<Integer, Float>> trackAvarages, final ComparingResultsData crd) {
 
@@ -338,25 +337,26 @@ public class RaceTableView extends Tab {
 			value = l.get(l.size() - 1);
 		}
 
-		final List<SimpleEntry<Integer, Float>> driverAvges = db.getTrackAvarages(crd.getTrackName(), distances, crd.getRaceDate(), crd.getDriverId(), true);
+		final List<SimpleEntry<Integer, Float>> driverAvges = db.getTrackAvarages(crd.getTrackName(), distances, crd.getRaceDate(), crd.getDriverId(),
+				true);
 		final Optional<SimpleEntry<Integer, Float>> driverAvg = driverAvges.stream().filter(p -> p.getKey() == crd.getLane()).findFirst();
 
 		if (driverAvg.isPresent() && driverAvg.get().getValue() > 0f) {
 			value = driverAvg.get().getValue() - value;
 		} else {
-			// FIXME Här hämtas hästens allmäna tid ut, markera detta??
 			final List<SimpleEntry<Integer, Float>> driverAvges2 = db.getTrackAvarages("", distances, crd.getRaceDate(), crd.getDriverId(), true);
 			final Optional<SimpleEntry<Integer, Float>> driverAvg2 = driverAvges.stream().filter(p -> p.getKey() == crd.getLane()).findFirst();
 			if (driverAvg2.isPresent() && driverAvg2.get().getValue() > 0f) {
 				value = driverAvg2.get().getValue() - value;
 			} else {
-				// Hästen helt oprövad på distances, markeras hur?
+				// H�sten helt opr�vad p� distances, markeras hur?
 				final float newVal;
-				final double sum = driverAvges2.stream().mapToDouble(m -> m.getValue() > 0?m.getValue():30f).sum();
+				final double sum = driverAvges2.stream().mapToDouble(m -> m.getValue() > 0 ? m.getValue() : 30f).sum();
 				if (sum > 0) {
 					newVal = (float) (sum / driverAvges2.size());
 				} else {
-					//						newVal = (float)totalAvarages.stream().mapToDouble(m -> m.getValue()).max().orElse(30f);
+					// newVal = (float)totalAvarages.stream().mapToDouble(m ->
+					// m.getValue()).max().orElse(30f);
 					newVal = 30f;
 				}
 				value = newVal - value;

+ 560 - 10
ATG/src/objects/Result.java

@@ -1,5 +1,8 @@
 package objects;
 
+import java.util.ArrayList;
+import java.util.List;
+
 public class Result {
 	int id;
 	int trackId;
@@ -18,9 +21,63 @@ public class Result {
 	int horseId;
 	int raceId;
 
-	public Result(int id, int trackId, String raceDate, String raceType, int raceNumber, int lane, int distance,
-			int result, float time, String timeModifier, int shoes, int sulky, int driverId, int trainerId, int horseId,
-			int raceId) {
+	float avgTimeDriverAll;
+	float avgTimeDriverLast5;
+	float avgTimeDriverLast10;
+	float avgTimeDriverLast15;
+	float avgTimeDriverDistanceAll;
+	float avgTimeDriverDistanceLast5;
+	float avgTimeDriverDistanceLast10;
+	float avgTimeDriverDistanceLast15;
+
+	float avgTimeHorseAll;
+	float avgTimeHorseLast5;
+	float avgTimeHorseLast10;
+	float avgTimeHorseLast15;
+	float avgTimeHorseDistanceAll;
+	float avgTimeHorseDistanceLast5;
+	float avgTimeHorseDistanceLast10;
+	float avgTimeHorseDistanceLast15;
+
+	float avgTimeCombinedAll;
+	float avgTimeCombinedLast5;
+	float avgTimeCombinedLast10;
+	float avgTimeCombinedLast15;
+	float avgTimeCombinedDistanceAll;
+	float avgTimeCombinedDistanceLast5;
+	float avgTimeCombinedDistanceLast10;
+	float avgTimeCombinedDistanceLast15;
+
+	float avgPositionDriverAll;
+	float avgPositionDriverLast5;
+	float avgPositionDriverLast10;
+	float avgPositionDriverLast15;
+	float avgPositionDriverDistanceAll;
+	float avgPositionDriverDistanceLast5;
+	float avgPositionDriverDistanceLast10;
+	float avgPositionDriverDistanceLast15;
+
+	float avgPositionHorseAll;
+	float avgPositionHorseLast5;
+	float avgPositionHorseLast10;
+	float avgPositionHorseLast15;
+	float avgPositionHorseDistanceAll;
+	float avgPositionHorseDistanceLast5;
+	float avgPositionHorseDistanceLast10;
+	float avgPositionHorseDistanceLast15;
+
+	float avgPositionCombinedAll;
+	float avgPositionCombinedLast5;
+	float avgPositionCombinedLast10;
+	float avgPositionCombinedLast15;
+	float avgPositionCombinedDistanceAll;
+	float avgPositionCombinedDistanceLast5;
+	float avgPositionCombinedDistanceLast10;
+	float avgPositionCombinedDistanceLast15;
+	private String trackName;
+
+	public Result(int id, int trackId, String raceDate, String raceType, int raceNumber, int lane, int distance, int result, float time,
+			String timeModifier, int shoes, int sulky, int driverId, int trainerId, int horseId, int raceId) {
 		super();
 		this.id = id;
 		this.trackId = trackId;
@@ -40,6 +97,31 @@ public class Result {
 		this.raceId = raceId;
 	}
 
+	public Result(HorseRaceData data) {
+		raceDate = data.getRaceDate();
+		RaceNumber = data.getRaceNumber();
+		lane = data.getLane();
+		distance = data.getDistance();
+		result = data.getResult();
+		time = data.getTime();
+		timeModifier = data.getTimeModifier();
+		shoes = data.getShoes();
+		sulky = data.getSulky();
+		driverId = data.getDriverId();
+		horseId = data.getHorseId();
+		trackName = data.getTrackName();
+	}
+
+	public static ArrayList<Result> convertHorseRaceDataList(List<HorseRaceData> races) {
+		final ArrayList<Result> returnArray = new ArrayList<>();
+
+		for (final HorseRaceData data : races) {
+			returnArray.add(new Result(data));
+		}
+
+		return returnArray;
+	}
+
 	public int getId() {
 		return id;
 	}
@@ -169,17 +251,485 @@ public class Result {
 	}
 
 	public String resultToFileString() {
-		return id + ";" + trackId + ";" + raceDate + ";" + RaceType + ";" + RaceNumber + ";" + lane + ";" + distance
-				+ ";" + result + ";" + time + ";" + timeModifier + ";" + shoes + ";" + sulky + ";" + driverId + ";"
-				+ trainerId + ";" + horseId + ";" + raceId;
+		return id + ";" + trackId + ";" + raceDate + ";" + RaceType + ";" + RaceNumber + ";" + lane + ";" + distance + ";" + result + ";" + time + ";"
+				+ timeModifier + ";" + shoes + ";" + sulky + ";" + driverId + ";" + trainerId + ";" + horseId + ";" + raceId;
+	}
+
+	public float getAvgTimeDriverAll() {
+		return avgTimeDriverAll;
+	}
+
+	public void setAvgTimeDriverAll(float avgTimeDriverAll) {
+		this.avgTimeDriverAll = avgTimeDriverAll;
+	}
+
+	public float getAvgTimeDriverLast5() {
+		return avgTimeDriverLast5;
+	}
+
+	public void setAvgTimeDriverLast5(float avgTimeDriverLast5) {
+		this.avgTimeDriverLast5 = avgTimeDriverLast5;
+	}
+
+	public float getAvgTimeDriverLast10() {
+		return avgTimeDriverLast10;
+	}
+
+	public void setAvgTimeDriverLast10(float avgTimeDriverLast10) {
+		this.avgTimeDriverLast10 = avgTimeDriverLast10;
+	}
+
+	public float getAvgTimeDriverLast15() {
+		return avgTimeDriverLast15;
+	}
+
+	public void setAvgTimeDriverLast15(float avgTimeDriverLast15) {
+		this.avgTimeDriverLast15 = avgTimeDriverLast15;
+	}
+
+	public float getAvgTimeDriverDistanceAll() {
+		return avgTimeDriverDistanceAll;
+	}
+
+	public void setAvgTimeDriverDistanceAll(float avgTimeDriverDistanceAll) {
+		this.avgTimeDriverDistanceAll = avgTimeDriverDistanceAll;
+	}
+
+	public float getAvgTimeDriverDistanceLast5() {
+		return avgTimeDriverDistanceLast5;
+	}
+
+	public void setAvgTimeDriverDistanceLast5(float avgTimeDriverDistanceLast5) {
+		this.avgTimeDriverDistanceLast5 = avgTimeDriverDistanceLast5;
+	}
+
+	public float getAvgTimeDriverDistanceLast10() {
+		return avgTimeDriverDistanceLast10;
+	}
+
+	public void setAvgTimeDriverDistanceLast10(float avgTimeDriverDistanceLast10) {
+		this.avgTimeDriverDistanceLast10 = avgTimeDriverDistanceLast10;
+	}
+
+	public float getAvgTimeDriverDistanceLast15() {
+		return avgTimeDriverDistanceLast15;
+	}
+
+	public void setAvgTimeDriverDistanceLast15(float avgTimeDriverDistanceLast15) {
+		this.avgTimeDriverDistanceLast15 = avgTimeDriverDistanceLast15;
+	}
+
+	public float getAvgTimeHorseAll() {
+		return avgTimeHorseAll;
+	}
+
+	public void setAvgTimeHorseAll(float avgTimeHorseAll) {
+		this.avgTimeHorseAll = avgTimeHorseAll;
+	}
+
+	public float getAvgTimeHorseLast5() {
+		return avgTimeHorseLast5;
+	}
+
+	public void setAvgTimeHorseLast5(float avgTimeHorseLast5) {
+		this.avgTimeHorseLast5 = avgTimeHorseLast5;
+	}
+
+	public float getAvgTimeHorseLast10() {
+		return avgTimeHorseLast10;
+	}
+
+	public void setAvgTimeHorseLast10(float avgTimeHorseLast10) {
+		this.avgTimeHorseLast10 = avgTimeHorseLast10;
+	}
+
+	public float getAvgTimeHorseLast15() {
+		return avgTimeHorseLast15;
+	}
+
+	public void setAvgTimeHorseLast15(float avgTimeHorseLast15) {
+		this.avgTimeHorseLast15 = avgTimeHorseLast15;
+	}
+
+	public float getAvgTimeHorseDistanceAll() {
+		return avgTimeHorseDistanceAll;
+	}
+
+	public void setAvgTimeHorseDistanceAll(float avgTimeHorseDistanceAll) {
+		this.avgTimeHorseDistanceAll = avgTimeHorseDistanceAll;
+	}
+
+	public float getAvgTimeHorseDistanceLast5() {
+		return avgTimeHorseDistanceLast5;
+	}
+
+	public void setAvgTimeHorseDistanceLast5(float avgTimeHorseDistanceLast5) {
+		this.avgTimeHorseDistanceLast5 = avgTimeHorseDistanceLast5;
+	}
+
+	public float getAvgTimeHorseDistanceLast10() {
+		return avgTimeHorseDistanceLast10;
+	}
+
+	public void setAvgTimeHorseDistanceLast10(float avgTimeHorseDistanceLast10) {
+		this.avgTimeHorseDistanceLast10 = avgTimeHorseDistanceLast10;
+	}
+
+	public float getAvgTimeHorseDistanceLast15() {
+		return avgTimeHorseDistanceLast15;
+	}
+
+	public void setAvgTimeHorseDistanceLast15(float avgTimeHorseDistanceLast15) {
+		this.avgTimeHorseDistanceLast15 = avgTimeHorseDistanceLast15;
+	}
+
+	public float getAvgTimeCombinedAll() {
+		return avgTimeCombinedAll;
+	}
+
+	public void setAvgTimeCombinedAll(float avgTimeCombinedAll) {
+		this.avgTimeCombinedAll = avgTimeCombinedAll;
+	}
+
+	public float getAvgTimeCombinedLast5() {
+		return avgTimeCombinedLast5;
+	}
+
+	public void setAvgTimeCombinedLast5(float avgTimeCombinedLast5) {
+		this.avgTimeCombinedLast5 = avgTimeCombinedLast5;
+	}
+
+	public float getAvgTimeCombinedLast10() {
+		return avgTimeCombinedLast10;
+	}
+
+	public void setAvgTimeCombinedLast10(float avgTimeCombinedLast10) {
+		this.avgTimeCombinedLast10 = avgTimeCombinedLast10;
+	}
+
+	public float getAvgTimeCombinedLast15() {
+		return avgTimeCombinedLast15;
+	}
+
+	public void setAvgTimeCombinedLast15(float avgTimeCombinedLast15) {
+		this.avgTimeCombinedLast15 = avgTimeCombinedLast15;
+	}
+
+	public float getAvgTimeCombinedDistanceAll() {
+		return avgTimeCombinedDistanceAll;
+	}
+
+	public void setAvgTimeCombinedDistanceAll(float avgTimeCombinedDistanceAll) {
+		this.avgTimeCombinedDistanceAll = avgTimeCombinedDistanceAll;
+	}
+
+	public float getAvgTimeCombinedDistanceLast5() {
+		return avgTimeCombinedDistanceLast5;
+	}
+
+	public void setAvgTimeCombinedDistanceLast5(float avgTimeCombinedDistanceLast5) {
+		this.avgTimeCombinedDistanceLast5 = avgTimeCombinedDistanceLast5;
+	}
+
+	public float getAvgTimeCombinedDistanceLast10() {
+		return avgTimeCombinedDistanceLast10;
+	}
+
+	public void setAvgTimeCombinedDistanceLast10(float avgTimeCombinedDistanceLast10) {
+		this.avgTimeCombinedDistanceLast10 = avgTimeCombinedDistanceLast10;
+	}
+
+	public float getAvgTimeCombinedDistanceLast15() {
+		return avgTimeCombinedDistanceLast15;
+	}
+
+	public void setAvgTimeCombinedDistanceLast15(float avgTimeCombinedDistanceLast15) {
+		this.avgTimeCombinedDistanceLast15 = avgTimeCombinedDistanceLast15;
+	}
+
+	public float getAvgPositionDriverAll() {
+		return avgPositionDriverAll;
+	}
+
+	public void setAvgPositionDriverAll(float avgPositionDriverAll) {
+		this.avgPositionDriverAll = avgPositionDriverAll;
+	}
+
+	public float getAvgPositionDriverLast5() {
+		return avgPositionDriverLast5;
+	}
+
+	public void setAvgPositionDriverLast5(float avgPositionDriverLast5) {
+		this.avgPositionDriverLast5 = avgPositionDriverLast5;
+	}
+
+	public float getAvgPositionDriverLast10() {
+		return avgPositionDriverLast10;
+	}
+
+	public void setAvgPositionDriverLast10(float avgPositionDriverLast10) {
+		this.avgPositionDriverLast10 = avgPositionDriverLast10;
+	}
+
+	public float getAvgPositionDriverLast15() {
+		return avgPositionDriverLast15;
+	}
+
+	public void setAvgPositionDriverLast15(float avgPositionDriverLast15) {
+		this.avgPositionDriverLast15 = avgPositionDriverLast15;
+	}
+
+	public float getAvgPositionDriverDistanceAll() {
+		return avgPositionDriverDistanceAll;
+	}
+
+	public void setAvgPositionDriverDistanceAll(float avgPositionDriverDistanceAll) {
+		this.avgPositionDriverDistanceAll = avgPositionDriverDistanceAll;
+	}
+
+	public float getAvgPositionDriverDistanceLast5() {
+		return avgPositionDriverDistanceLast5;
+	}
+
+	public void setAvgPositionDriverDistanceLast5(float avgPositionDriverDistanceLast5) {
+		this.avgPositionDriverDistanceLast5 = avgPositionDriverDistanceLast5;
+	}
+
+	public float getAvgPositionDriverDistanceLast10() {
+		return avgPositionDriverDistanceLast10;
+	}
+
+	public void setAvgPositionDriverDistanceLast10(float avgPositionDriverDistanceLast10) {
+		this.avgPositionDriverDistanceLast10 = avgPositionDriverDistanceLast10;
+	}
+
+	public float getAvgPositionDriverDistanceLast15() {
+		return avgPositionDriverDistanceLast15;
+	}
+
+	public void setAvgPositionDriverDistanceLast15(float avgPositionDriverDistanceLast15) {
+		this.avgPositionDriverDistanceLast15 = avgPositionDriverDistanceLast15;
+	}
+
+	public float getAvgPositionHorseAll() {
+		return avgPositionHorseAll;
+	}
+
+	public void setAvgPositionHorseAll(float avgPositionHorseAll) {
+		this.avgPositionHorseAll = avgPositionHorseAll;
+	}
+
+	public float getAvgPositionHorseLast5() {
+		return avgPositionHorseLast5;
+	}
+
+	public void setAvgPositionHorseLast5(float avgPositionHorseLast5) {
+		this.avgPositionHorseLast5 = avgPositionHorseLast5;
+	}
+
+	public float getAvgPositionHorseLast10() {
+		return avgPositionHorseLast10;
+	}
+
+	public void setAvgPositionHorseLast10(float avgPositionHorseLast10) {
+		this.avgPositionHorseLast10 = avgPositionHorseLast10;
+	}
+
+	public float getAvgPositionHorseLast15() {
+		return avgPositionHorseLast15;
+	}
+
+	public void setAvgPositionHorseLast15(float avgPositionHorseLast15) {
+		this.avgPositionHorseLast15 = avgPositionHorseLast15;
+	}
+
+	public float getAvgPositionHorseDistanceAll() {
+		return avgPositionHorseDistanceAll;
 	}
 
-	@Override
-	public String toString() {
+	public void setAvgPositionHorseDistanceAll(float avgPositionHorseDistanceAll) {
+		this.avgPositionHorseDistanceAll = avgPositionHorseDistanceAll;
+	}
+
+	public float getAvgPositionHorseDistanceLast5() {
+		return avgPositionHorseDistanceLast5;
+	}
+
+	public void setAvgPositionHorseDistanceLast5(float avgPositionHorseDistanceLast5) {
+		this.avgPositionHorseDistanceLast5 = avgPositionHorseDistanceLast5;
+	}
+
+	public float getAvgPositionHorseDistanceLast10() {
+		return avgPositionHorseDistanceLast10;
+	}
+
+	public void setAvgPositionHorseDistanceLast10(float avgPositionHorseDistanceLast10) {
+		this.avgPositionHorseDistanceLast10 = avgPositionHorseDistanceLast10;
+	}
+
+	public float getAvgPositionHorseDistanceLast15() {
+		return avgPositionHorseDistanceLast15;
+	}
+
+	public void setAvgPositionHorseDistanceLast15(float avgPositionHorseDistanceLast15) {
+		this.avgPositionHorseDistanceLast15 = avgPositionHorseDistanceLast15;
+	}
+
+	public float getAvgPositionCombinedAll() {
+		return avgPositionCombinedAll;
+	}
+
+	public void setAvgPositionCombinedAll(float avgPositionCombinedAll) {
+		this.avgPositionCombinedAll = avgPositionCombinedAll;
+	}
+
+	public float getAvgPositionCombinedLast5() {
+		return avgPositionCombinedLast5;
+	}
+
+	public void setAvgPositionCombinedLast5(float avgPositionCombinedLast5) {
+		this.avgPositionCombinedLast5 = avgPositionCombinedLast5;
+	}
+
+	public float getAvgPositionCombinedLast10() {
+		return avgPositionCombinedLast10;
+	}
+
+	public void setAvgPositionCombinedLast10(float avgPositionCombinedLast10) {
+		this.avgPositionCombinedLast10 = avgPositionCombinedLast10;
+	}
+
+	public float getAvgPositionCombinedLast15() {
+		return avgPositionCombinedLast15;
+	}
+
+	public void setAvgPositionCombinedLast15(float avgPositionCombinedLast15) {
+		this.avgPositionCombinedLast15 = avgPositionCombinedLast15;
+	}
+
+	public float getAvgPositionCombinedDistanceAll() {
+		return avgPositionCombinedDistanceAll;
+	}
+
+	public void setAvgPositionCombinedDistanceAll(float avgPositionCombinedDistanceAll) {
+		this.avgPositionCombinedDistanceAll = avgPositionCombinedDistanceAll;
+	}
+
+	public float getAvgPositionCombinedDistanceLast5() {
+		return avgPositionCombinedDistanceLast5;
+	}
+
+	public void setAvgPositionCombinedDistanceLast5(float avgPositionCombinedDistanceLast5) {
+		this.avgPositionCombinedDistanceLast5 = avgPositionCombinedDistanceLast5;
+	}
+
+	public float getAvgPositionCombinedDistanceLast10() {
+		return avgPositionCombinedDistanceLast10;
+	}
+
+	public void setAvgPositionCombinedDistanceLast10(float avgPositionCombinedDistanceLast10) {
+		this.avgPositionCombinedDistanceLast10 = avgPositionCombinedDistanceLast10;
+	}
+
+	public float getAvgPositionCombinedDistanceLast15() {
+		return avgPositionCombinedDistanceLast15;
+	}
+
+	public void setAvgPositionCombinedDistanceLast15(float avgPositionCombinedDistanceLast15) {
+		this.avgPositionCombinedDistanceLast15 = avgPositionCombinedDistanceLast15;
+	}
+
+	public String getTrackName() {
+		return trackName;
+	}
+
+	public void setTrackName(String trackName) {
+		this.trackName = trackName;
+	}
+
+	@Override public String toString() {
 		return String.format(
 				"id %s, trackId %s, raceDate %s, raceType %s, raceNumber %s, lane %s, distance %s, result %s, time %s, timeModifier %s, "
 						+ " shoes %s, sulky %s, driverId %s, trainerId %s, horseId %s, raceId %s",
-						id, trackId, raceDate, RaceType, RaceNumber, lane, distance, result, time, timeModifier, shoes, sulky,
-						driverId, trainerId, horseId, raceId);
+				id, trackId, raceDate, RaceType, RaceNumber, lane, distance, result, time, timeModifier, shoes, sulky, driverId, trainerId, horseId,
+				raceId);
+	}
+
+	public void PrintAvges() {
+		System.out.println(String.format(
+				"Horse Time (all, 5, 10, 15) (%s, %s, %s, %s)\n" + "Driver Time (all, 5, 10, 15) (%s, %s, %s, %s)\n"
+						+ "Combined Time (all, 5, 10, 15) (%s, %s, %s, %s)\n",
+				avgTimeHorseAll, avgTimeHorseLast5, avgTimeHorseLast10, avgTimeHorseLast15, avgTimeDriverAll, avgTimeDriverLast5, avgTimeDriverLast10,
+				avgTimeDriverLast15, avgTimeCombinedAll, avgTimeCombinedLast5, avgTimeCombinedLast10, avgTimeCombinedLast15));
+		System.out.println(String.format(
+				"Horse Position (all, 5, 10, 15) (%s, %s, %s, %s)\n" + "Driver Position (all, 5, 10, 15) (%s, %s, %s, %s)\n"
+						+ "Combined Position (all, 5, 10, 15) (%s, %s, %s, %s)\n",
+				avgPositionHorseAll, avgPositionHorseLast5, avgPositionHorseLast10, avgPositionHorseLast15, avgPositionDriverAll,
+				avgPositionDriverLast5, avgPositionDriverLast10, avgPositionDriverLast15, avgPositionCombinedAll, avgPositionCombinedLast5,
+				avgPositionCombinedLast10, avgPositionCombinedLast15));
+	}
+
+	public void setAvreges(float avgTimeDriverAll, float avgTimeDriverLast5, float avgTimeDriverLast10, float avgTimeDriverLast15,
+			float avgTimeDriverDistanceAll, float avgTimeDriverDistanceLast5, float avgTimeDriverDistanceLast10, float avgTimeDriverDistanceLast15,
+			float avgTimeHorseAll, float avgTimeHorseLast5, float avgTimeHorseLast10, float avgTimeHorseLast15, float avgTimeHorseDistanceAll,
+			float avgTimeHorseDistanceLast5, float avgTimeHorseDistanceLast10, float avgTimeHorseDistanceLast15, float avgTimeCombinedAll,
+			float avgTimeCombinedLast5, float avgTimeCombinedLast10, float avgTimeCombinedLast15, float avgTimeCombinedDistanceAll,
+			float avgTimeCombinedDistanceLast5, float avgTimeCombinedDistanceLast10, float avgTimeCombinedDistanceLast15, float avgPositionDriverAll,
+			float avgPositionDriverLast5, float avgPositionDriverLast10, float avgPositionDriverLast15, float avgPositionDriverDistanceAll,
+			float avgPositionDriverDistanceLast5, float avgPositionDriverDistanceLast10, float avgPositionDriverDistanceLast15,
+			float avgPositionHorseAll, float avgPositionHorseLast5, float avgPositionHorseLast10, float avgPositionHorseLast15,
+			float avgPositionHorseDistanceAll, float avgPositionHorseDistanceLast5, float avgPositionHorseDistanceLast10,
+			float avgPositionHorseDistanceLast15, float avgPositionCombinedAll, float avgPositionCombinedLast5, float avgPositionCombinedLast10,
+			float avgPositionCombinedLast15, float avgPositionCombinedDistanceAll, float avgPositionCombinedDistanceLast5,
+			float avgPositionCombinedDistanceLast10, float avgPositionCombinedDistanceLast15) {
+		this.avgTimeDriverAll = avgTimeDriverAll;
+		this.avgTimeDriverLast5 = avgTimeDriverLast5;
+		this.avgTimeDriverLast10 = avgTimeDriverLast10;
+		this.avgTimeDriverLast15 = avgTimeDriverLast15;
+		this.avgTimeDriverDistanceAll = avgTimeDriverDistanceAll;
+		this.avgTimeDriverDistanceLast5 = avgTimeDriverDistanceLast5;
+		this.avgTimeDriverDistanceLast10 = avgTimeDriverDistanceLast10;
+		this.avgTimeDriverDistanceLast15 = avgTimeDriverDistanceLast15;
+		this.avgTimeHorseAll = avgTimeHorseAll;
+		this.avgTimeHorseLast5 = avgTimeHorseLast5;
+		this.avgTimeHorseLast10 = avgTimeHorseLast10;
+		this.avgTimeHorseLast15 = avgTimeHorseLast15;
+		this.avgTimeHorseDistanceAll = avgTimeHorseDistanceAll;
+		this.avgTimeHorseDistanceLast5 = avgTimeHorseDistanceLast5;
+		this.avgTimeHorseDistanceLast10 = avgTimeHorseDistanceLast10;
+		this.avgTimeHorseDistanceLast15 = avgTimeHorseDistanceLast15;
+		this.avgTimeCombinedAll = avgTimeCombinedAll;
+		this.avgTimeCombinedLast5 = avgTimeCombinedLast5;
+		this.avgTimeCombinedLast10 = avgTimeCombinedLast10;
+		this.avgTimeCombinedLast15 = avgTimeCombinedLast15;
+		this.avgTimeCombinedDistanceAll = avgTimeCombinedDistanceAll;
+		this.avgTimeCombinedDistanceLast5 = avgTimeCombinedDistanceLast5;
+		this.avgTimeCombinedDistanceLast10 = avgTimeCombinedDistanceLast10;
+		this.avgTimeCombinedDistanceLast15 = avgTimeCombinedDistanceLast15;
+		this.avgPositionDriverAll = avgPositionDriverAll;
+		this.avgPositionDriverLast5 = avgPositionDriverLast5;
+		this.avgPositionDriverLast10 = avgPositionDriverLast10;
+		this.avgPositionDriverLast15 = avgPositionDriverLast15;
+		this.avgPositionDriverDistanceAll = avgPositionDriverDistanceAll;
+		this.avgPositionDriverDistanceLast5 = avgPositionDriverDistanceLast5;
+		this.avgPositionDriverDistanceLast10 = avgPositionDriverDistanceLast10;
+		this.avgPositionDriverDistanceLast15 = avgPositionDriverDistanceLast15;
+		this.avgPositionHorseAll = avgPositionHorseAll;
+		this.avgPositionHorseLast5 = avgPositionHorseLast5;
+		this.avgPositionHorseLast10 = avgPositionHorseLast10;
+		this.avgPositionHorseLast15 = avgPositionHorseLast15;
+		this.avgPositionHorseDistanceAll = avgPositionHorseDistanceAll;
+		this.avgPositionHorseDistanceLast5 = avgPositionHorseDistanceLast5;
+		this.avgPositionHorseDistanceLast10 = avgPositionHorseDistanceLast10;
+		this.avgPositionHorseDistanceLast15 = avgPositionHorseDistanceLast15;
+		this.avgPositionCombinedAll = avgPositionCombinedAll;
+		this.avgPositionCombinedLast5 = avgPositionCombinedLast5;
+		this.avgPositionCombinedLast10 = avgPositionCombinedLast10;
+		this.avgPositionCombinedLast15 = avgPositionCombinedLast15;
+		this.avgPositionCombinedDistanceAll = avgPositionCombinedDistanceAll;
+		this.avgPositionCombinedDistanceLast5 = avgPositionCombinedDistanceLast5;
+		this.avgPositionCombinedDistanceLast10 = avgPositionCombinedDistanceLast10;
+		this.avgPositionCombinedDistanceLast15 = avgPositionCombinedDistanceLast15;
 	}
+
 }

+ 61 - 48
ATG/src/test/Test.java

@@ -24,14 +24,11 @@ import objects.LaneWinObject;
 public class Test {
 
 	/**
-	 * Tests needed
-	 * Form (last eg. 5), results and time
-	 * Days since last race (Horse)
-	 * Days since last race (Driver)
-	 * Races with current driver
+	 * Tests needed Form (last eg. 5), results and time Days since last race (Horse)
+	 * Days since last race (Driver) Races with current driver
 	 *
-	 * Vad ska man göra med gallopp
-	 * Temperature (needs alot og work, dont have temp data)
+	 * Vad ska man göra med gallopp Temperature (needs a lot of work, dont have temp
+	 * data)
 	 *
 	 */
 
@@ -60,19 +57,17 @@ public class Test {
 
 	public float getPercentagesOrderedBy(int topCount, String sortVariable) {
 
-		if(data.isEmpty()) {
+		if (data.isEmpty()) {
 			readFile();
 		}
 
-
 		// sort by RaceDate, TrackId, RaceNumber
 
-		Collections.sort(data, new TestDataRow.RaceDateSorter()
-				.thenComparing(new TestDataRow.TrackIdSorter())
+		Collections.sort(data, new TestDataRow.RaceDateSorter().thenComparing(new TestDataRow.TrackIdSorter())
 				.thenComparing(new TestDataRow.RaceNumberSorter()));
 
 		int correctHorseByDistance = 0;
-		int correctHorse= 0;
+		int correctHorse = 0;
 		int correctDriver = 0;
 		int correctDriverByDistance = 0;
 		int correctCustom = 0;
@@ -80,9 +75,10 @@ public class Test {
 		int racesCount = 0;
 		for (int i = 0; i < data.size(); i++) {
 			final TestDataRow firstRow = data.get(i);
-			final List<TestDataRow> currentRaces = data.stream().filter(d -> firstRow.getRaceDate().equals(d.getRaceDate()) &&
-					firstRow.getTrackId() == d.getTrackId() &&
-					firstRow.getRaceNumber() == d.getRaceNumber()).collect(Collectors.toList());
+			final List<TestDataRow> currentRaces = data.stream()
+					.filter(d -> firstRow.getRaceDate().equals(d.getRaceDate())
+							&& firstRow.getTrackId() == d.getTrackId() && firstRow.getRaceNumber() == d.getRaceNumber())
+					.collect(Collectors.toList());
 
 			if (currentRaces.size() < 7) { // Not enough info
 				continue;
@@ -92,7 +88,7 @@ public class Test {
 
 			currentRaces.forEach(cr -> {
 				final String distance = String.valueOf(cr.getDistance());
-				if(!distances.contains(distance)) {
+				if (!distances.contains(distance)) {
 					distances.add(distance);
 				}
 			});
@@ -104,35 +100,49 @@ public class Test {
 
 			racesCount++;
 			final boolean autostart = firstRow.getTimeModifier().contains("a");
-			currentRaces.forEach(cr -> cr.setLaneWinPercent(getWinPercentage(distances, cr.getLane(), cr.getDistance(), autostart)));
-
-			correctHorseByDistance = checkHorseByDistanceCorrect(topCount, correctHorseByDistance, currentRaces, new TestDataRow.horseAvgTimeByDistanceSorter());
-			correctHorse = checkHorseByDistanceCorrect(topCount, correctHorse, currentRaces, new TestDataRow.horseAvgTimeSorter());
-			correctDriver = checkHorseByDistanceCorrect(topCount, correctDriver, currentRaces, new TestDataRow.driverAvgTimeSorter());
-			correctDriverByDistance = checkHorseByDistanceCorrect(topCount, correctDriverByDistance, currentRaces, new TestDataRow.driverAvgTimeByDistanceSorter());
+			currentRaces.forEach(
+					cr -> cr.setLaneWinPercent(getWinPercentage(distances, cr.getLane(), cr.getDistance(), autostart)));
+
+			correctHorseByDistance = checkHorseByDistanceCorrect(topCount, correctHorseByDistance, currentRaces,
+					new TestDataRow.horseAvgTimeByDistanceSorter());
+			correctHorse = checkHorseByDistanceCorrect(topCount, correctHorse, currentRaces,
+					new TestDataRow.horseAvgTimeSorter());
+			correctDriver = checkHorseByDistanceCorrect(topCount, correctDriver, currentRaces,
+					new TestDataRow.driverAvgTimeSorter());
+			correctDriverByDistance = checkHorseByDistanceCorrect(topCount, correctDriverByDistance, currentRaces,
+					new TestDataRow.driverAvgTimeByDistanceSorter());
 
 			correctCustom = checkHorseByDistanceCorrect(topCount, correctCustom, currentRaces, new customSorter());
-			correctCombined = checkHorseByDistanceCorrect(topCount, correctCombined, currentRaces, new CombinedSorter(1f,1f, 1f, 1f));
+			correctCombined = checkHorseByDistanceCorrect(topCount, correctCombined, currentRaces,
+					new CombinedSorter(1f, 1f, 1f, 1f));
 			i = i + currentRaces.size();
 		}
 
-		System.out.println("total races count " + racesCount + " correctHorse " + correctHorse + " percentage " + correctHorse/(racesCount * 1f));
-		System.out.println("total races count " + racesCount + " correctHorseByDistance " + correctHorseByDistance + " percentage " + correctHorseByDistance/(racesCount * 1f));
-		System.out.println("total races count " + racesCount + " correctDriver " + correctDriver + " percentage " + correctDriver /(racesCount * 1f));
-		System.out.println("total races count " + racesCount + " correctDriverByDistance " + correctDriverByDistance + " percentage " + correctDriverByDistance/(racesCount * 1f));
+		System.out.println("total races count " + racesCount + " correctHorse " + correctHorse + " percentage "
+				+ correctHorse / (racesCount * 1f));
+		System.out.println("total races count " + racesCount + " correctHorseByDistance " + correctHorseByDistance
+				+ " percentage " + correctHorseByDistance / (racesCount * 1f));
+		System.out.println("total races count " + racesCount + " correctDriver " + correctDriver + " percentage "
+				+ correctDriver / (racesCount * 1f));
+		System.out.println("total races count " + racesCount + " correctDriverByDistance " + correctDriverByDistance
+				+ " percentage " + correctDriverByDistance / (racesCount * 1f));
 
-		System.out.println("total races count " + racesCount + " CustomSorter " + correctCustom + " percentage " + correctCustom/(racesCount * 1f));
+		System.out.println("total races count " + racesCount + " CustomSorter " + correctCustom + " percentage "
+				+ correctCustom / (racesCount * 1f));
 
-		System.out.println("total races count " + racesCount + " CombinedSorter " + correctCombined + " percentage " + correctCombined/(racesCount * 1f));
+		System.out.println("total races count " + racesCount + " CombinedSorter " + correctCombined + " percentage "
+				+ correctCombined / (racesCount * 1f));
 		// horseAvgTime approx 24,6%
 		// driverAvgTime approc 25,6%
 		// horseAvgTimeByDistance 27,3%
 		// driverAvgTimeByDistance 22,1%
-		// ((horseTime + horseTimeByDistance) / x) + ((driverTime + driverTimeByDistance) / y) 27.1
-		return correctHorseByDistance/(racesCount * 1f);
+		// ((horseTime + horseTimeByDistance) / x) + ((driverTime +
+		// driverTimeByDistance) / y) 27.1
+		return correctHorseByDistance / (racesCount * 1f);
 	}
 
-	private int checkHorseByDistanceCorrect(int topCount, int correct, final List<TestDataRow> currentRaces, Comparator<TestDataRow> sorter) {
+	private int checkHorseByDistanceCorrect(int topCount, int correct, final List<TestDataRow> currentRaces,
+			Comparator<TestDataRow> sorter) {
 		currentRaces.sort(sorter);
 
 		for (int p = 0; p < topCount; p++) {
@@ -144,15 +154,16 @@ public class Test {
 		return correct;
 	}
 
-
 	private float getWinPercentage(ArrayList<String> distances, int lane, int distance, boolean autostart) {
 		float winPercentage;
 		try {
 			if (autostart) {
 				if (!autostartWinPercentages.containsKey(distances)) {
-					autostartWinPercentages.put(distances, DatabaseController.getInstance().getAutostartWinPercents(distances));
+					autostartWinPercentages.put(distances,
+							DatabaseController.getInstance().getAutostartWinPercents(distances));
 				}
-				final Optional<LaneWinObject> lw = autostartWinPercentages.get(distances).stream().filter(p -> p.getDistance() == distance && p.getLane() == lane).findFirst();
+				final Optional<LaneWinObject> lw = autostartWinPercentages.get(distances).stream()
+						.filter(p -> p.getDistance() == distance && p.getLane() == lane).findFirst();
 				if (lw.isPresent()) {
 					winPercentage = lw.get().getPercent();
 				} else {
@@ -161,9 +172,11 @@ public class Test {
 				}
 			} else {
 				if (!voltstartWinPercentages.containsKey(distances)) {
-					voltstartWinPercentages.put(distances, DatabaseController.getInstance().getVoltstartWinPercents(distances));
+					voltstartWinPercentages.put(distances,
+							DatabaseController.getInstance().getVoltstartWinPercents(distances));
 				}
-				final Optional<LaneWinObject> lw = voltstartWinPercentages.get(distances).stream().filter(p -> p.getDistance() == distance && p.getLane() == lane).findFirst();
+				final Optional<LaneWinObject> lw = voltstartWinPercentages.get(distances).stream()
+						.filter(p -> p.getDistance() == distance && p.getLane() == lane).findFirst();
 				if (lw.isPresent()) {
 					winPercentage = lw.get().getPercent();
 				} else {
@@ -177,7 +190,6 @@ public class Test {
 		return winPercentage;
 	}
 
-
 	public static class CombinedSorter implements Comparator<TestDataRow> {
 
 		float horseWeight = 1f;
@@ -192,17 +204,18 @@ public class Test {
 			this.horseLaneWin = horseLaneWin;
 			this.driverLaneWin = driverLaneWin;
 		}
-		@Override
-		public int compare(TestDataRow o1, TestDataRow o2) {
-			final float o1Time = (o1.getHorseAvgTime() * horseLaneWin * horseWeight) + (o1.getDriverAvgTime() * driverLaneWin * driverWeight) - o1.getLaneWinPercent();
-			final float o2Time = (o2.getHorseAvgTime() * horseLaneWin * horseWeight) + (o2.getDriverAvgTime() * driverLaneWin * driverWeight) - o2.getLaneWinPercent();
+
+		@Override public int compare(TestDataRow o1, TestDataRow o2) {
+			final float o1Time = (o1.getHorseAvgTime() * horseLaneWin * horseWeight)
+					+ (o1.getDriverAvgTime() * driverLaneWin * driverWeight) - o1.getLaneWinPercent();
+			final float o2Time = (o2.getHorseAvgTime() * horseLaneWin * horseWeight)
+					+ (o2.getDriverAvgTime() * driverLaneWin * driverWeight) - o2.getLaneWinPercent();
 			return Float.compare(o1Time, o2Time);
 		}
 	}
 
 	public static class customSorter implements Comparator<TestDataRow> {
-		@Override
-		public int compare(TestDataRow d1, TestDataRow d2) {
+		@Override public int compare(TestDataRow d1, TestDataRow d2) {
 			float horseTimed1 = 0f;
 			int d1DivideHorse = 0;
 			if (d1.getHorseAvgTime() > 0) {
@@ -233,7 +246,6 @@ public class Test {
 				horseTimed2 += 5;
 			}
 
-
 			float driverTimed1 = 0f;
 			int d1DivideDriver = 0;
 			if (d1.getDriverAvgTime() > 0) {
@@ -264,11 +276,12 @@ public class Test {
 				driverTimed2 += 2;
 			}
 
-			final float d1Time = ((horseTimed1 - d1.getLaneWinPercent()) / d1DivideHorse) + ((driverTimed1 - d1.getLaneWinPercent()) / d1DivideDriver * 2);
-			final float d2Time = ((horseTimed2 - d2.getLaneWinPercent()) / d2DivideHorse) + ((driverTimed2 - d2.getLaneWinPercent()) / d2DivideDriver * 2);
+			final float d1Time = ((horseTimed1 - d1.getLaneWinPercent()) / d1DivideHorse)
+					+ ((driverTimed1 - d1.getLaneWinPercent()) / d1DivideDriver * 2);
+			final float d2Time = ((horseTimed2 - d2.getLaneWinPercent()) / d2DivideHorse)
+					+ ((driverTimed2 - d2.getLaneWinPercent()) / d2DivideDriver * 2);
 
 			return Float.compare(d1Time, d2Time);
 		}
 	}
 }
-