Refactored code segments into functions, and added PHPdoc