Added comments, refactored a little, and used codeblocks AStyle reformatter