Greatly simplified solution 1