rewritten to use better folding