Added comments for clarification of the logic. This is almost done but not properly tested.