Refactor validation code and resolve some bugs