A slightly tidied up functioning solution
A more tidied up varsion