Added comments and rearranged some code