Code refactored and remove LOOP BUG in the algorithm.