Full solution, with minor modification of comments