So I finally got around to optimising the bloody thing.