Containts elements of code by Sebastian Akerman <sak@parallelconsulting.com> and made a bit less "naughty" by Steve.