Added the excellent directory handling code by David Tribble.