added error checking and additional code comments