first part of algorithm 2