copied algorithm 1 to modify for 3