Code ported from rndblnch, yet behaves weirdly: still has a bug somewhere