Variation on http://stackoverflow.com/a/16528383/680454

Haven't managed to test this yet, but something like this will probably do what we want.