The whole algorithm