improved error handling and fixed some bugs