Refactored code

Added comments, reorganized code layout based on method functionality.