Initial refactoring

Lots of refactoring (part 1)