extracted pattern-matching from patterns, added more comments