added error handling and fixed some bugs