Refactored code to eliminate some duplication. Commented all function definitions and added extended comments for related functions.