Refactoring

The code has been reworked in an attempt to make it easier to read and maintain. Apart from the last commit that changed the default paths the behavior should be the same as before. I have been running this on a server for a couple of days now and it appear to be working just fine.

Please let me know if there is anything I can do help with the merge.