Refactor

@theneikos please review this. I think you should be able to rebase your work onto this...