rtucker's original code plus some minor fixes.