Fixed infinite loop and close