cleanups, error checking, small bugfix