added some debug code and cleaned up some error checking