Completed the problem in one go - comments explain the different components of the solution