Fully working code, lots more info in the comments