add some sanity checks, maybe this will improve stability on invalid input