Restructuring algorithm code and adding option for inverting the direction per level