Full solution, working version of the task.