Refactored code

Do not merge! Not done testing.

The code has been split into smaller parts to make it easier to build upon later.