optimization, bug fixes and error handling