First part of algorithm