Refactor code & improve error messages