First working version of optimised version. Minor fixes to come. Increases speed significantly.