Seems to be a fairly correct implementation now