Generalized code and added TERM signal handling