Code clean up and error checking