refactored some codes and added comments