Modified logic to avoid duplicate records