Merged Generalized Loop Correction code kindly provided by Siamak Ravanbakhsh