improved error handling, cleaned some stuff up, added comments