added annotated code, refactored condensed version