Refactor and add code comments