Overhaul; replaced Jev's code.