combined code for algorithm 1