Revised with some debugging after consulting a couple of references.