Combined algorithms 3 and 4 into one algorithm with a flag argument to specify which to use.