Optimisations, error handling and fixes. Tests not passing.

@ismailsunni please review and merge. Note the tests are not passing so you will need to look at those before merging.