Final code - will open a pull-request after this as I've almost completed the project.