clean up error handling
bug fix and code clean up