Steal a crapton of code from Steve Losh