Better error checking, fixed valid() bug