improved patch incorporating kbk's comments.