solving issue #1
All these nasty ifs could be replaced by two nested for loops.