Rewrite the code

Add a check, use better names and fix error to pass the tests.