code cleanup
slightly better error handling