Applied @ramsey patch with some fixes