Cleaned up code, much optimisation.