made it tail-recursive