implementation of scan and fold