Fixed a few minor bugs. Cleaned up the code and added error logging.