Fixed infinite loop in recursive function