email alert feature and tidy up code