Inserting code from gist

Ironically gist deleted some stuff as I copied things across