Final solution - same code as previous commit, explanatory comments added.