added some error handling and cleaned up a bit