Move the daemonizing code into a separate function and clean up the code a bit