Bug-fixes and optimisation

Fixed a lot of code