Refactored some codes and added comments