added comment and reorganized to make more understandable.