Refactored tail code into common.js and added a bit more error handling