Added comments, reorganized code