A bit of a mess, but here's the initial code