refactored and added a few more comments