Fixed warning for unintialized variable
Refactored code segments into functions and added PHPdoc