slight code simplification and comments added