Improve code to run as daemon