morning exercise: avoid lots of recomputations in "inner loops" over all positions

(had to move some auxiliary functions to extra module to avoid circular
imports)