extensive error checking added