Major code refactoring. Lots more to do