Code cleanup and error checking