restructure error checking