updating C++ version of joshs algo.