Refactoring and Tests

This is still very much a work in progress