Simplify the code, add better error messages