better error handling and minor cleanup