Added some better error handling and possibly fixed a bug