Fixed bug with last element being skipped. Also lots of optimisation!
Merge branch 'master' into adam