incorporate changes/fixes made to similar code in james/trunk rev 410089