added recursion. need to check why it generates incorrect output