better error handling and some bug fixes