Fairly drastic reworking of fold.py