improved daemon code as pointed by Matt