Refactored and added a few comments