Eliminated infinite loops and added a proper timeout setup to prevent hanging.