Added comments and rearranged code