Rewrite algorithm from scratch (part 1).