Lots of changes and refactoring