Restructured to make it easier to daemonise