Refactored functions a bit to take parameters (follow the flow of data a bit better) and rename globals to follow convention.