error checking and flag checking added