add folding, rearrange code