Better error checking, some minor fixes