refactored code for error checking and maintenance