Bug fix for recursive function