Restructuring code, and adding comments