added error checking and cleaned up code