working but something funny going on with variable scoping
that leads to the wrong answer