Implementation of the rest of the algorithm