Shamelessly copying Nathan's code