if mrx_first_fill='1' & put(cpdn,$fffmt.)='yes' & rx_script_order=1 then do;
  remaining_avg_cost=0;
end;
else do;
  if deductible < plan_deductible then do;
    remaining_deductible = sum(plan_deductible,-deductible);
    deductible + min(remaining_deductible,avg_price);
    total_covered_oopc + min(remaining_deductible,avg_price);
    remaining_avg_cost = max(0,sum(avg_price,-remaining_deductible));
  end;
  else remaining_avg_cost = avg_price;
end;

if remaining_avg_cost > 0 and icl < plan_icl then do;
  remaining_icl = sum(plan_icl,-icl);
  coins_oopc + min(remaining_avg_cost,avg_price * 0.25);
  total_covered_oopc + min(remaining_avg_cost,avg_price * 0.25);
  remaining_avg_cost = 0;
end;

if remaining_avg_cost > 0 and threshold < plan_threshold then do;
  if drug_type='G' then discount_avg_price=avg_price*(1-&GENERIC_GAP_DISCOUNT.);
  else if drug_type='B' then discount_avg_price=avg_price*(1-&BRAND_GAP_DISCOUNT.-&BRAND_GAP_LIABDISC.);
  total_covered_oopc + min(discount_avg_price,sum(plan_threshold,-threshold));
  remaining_avg_cost = max(0,sum(discount_avg_price,-sum(plan_threshold,-threshold)));
end;

if remaining_avg_cost > 0 and threshold >= plan_threshold then do;
  if drug_type = 'G' then do;
    if (remaining_avg_cost < plan_copay_cat_gen) and (remaining_avg_cost <
          (avg_price * 0.05)) then do;
      copay_oopc + remaining_avg_cost;
      total_covered_oopc + remaining_avg_cost;
    end;
    else if plan_copay_cat_gen >= (avg_price * 0.05) then do;
      copay_oopc + plan_copay_cat_gen;
      total_covered_oopc + plan_copay_cat_gen;
    end;
    else do;
      coins_oopc + (avg_price * 0.05);
      total_covered_oopc + (avg_price * 0.05);
    end;
  end;
  else if drug_type = 'B' then do;
    if (remaining_avg_cost < plan_copay_cat_brand) and (remaining_avg_cost <
          (avg_price * 0.05)) then do;
      copay_oopc + remaining_avg_cost;
      total_covered_oopc + remaining_avg_cost;
    end;
    else if plan_copay_cat_brand >= (avg_price * 0.05) then do;
      copay_oopc + plan_copay_cat_brand;
      total_covered_oopc + plan_copay_cat_brand;
    end;
    else do;
      coins_oopc + (avg_price * 0.05);
      total_covered_oopc + (avg_price * 0.05);
    end;
  end;
end;

if icl < plan_icl then icl + avg_price;
threshold + avg_price;
