Reordered functions to follow the flow of the program better. Added comments and docstrings.