Found shorter way to write this code.
Optimized some code.

Used several tricks to replace loops with more-or-less functional statements, which I find clearer to read. Also, avoid imperative style ("write…") for methods that don't have side-effects.