Updated for readability / correctness.

Added comments.
Moved closest into loop.
Now using ternary operator and clearer variable names.
(I'm not sure if the previous logic was actually wrong or not, but this
is more readable, as I hope you will agree.)