Implementation of fold and cut algorithm