modified logic to be simpler.