refactory algorithm