Added timeout support and some error handling to avoid infinite loop issue