Cleaned up code, added error checking