error handling and general code cleanup