Refactor and add some comments