fixed algorithm 1 and 3, added recursion