Added extra safety check on inputs for clearer error messages on malformed input.