Improve reference solution with function comments and some code consolidation.