* PROGRAM: BUILD_FFF_FORMAT.SAS;

LIBNAME FORM "&FORMDIR";

proc sort data=IN1.druglist_rxcui out=druglist_rxcui (keep=drugname rxcui) nodupkey;
by rxcui drugname;
run;

data druglist_rollup;
set druglist_rxcui;
by rxcui drugname;
array dn(500) $60 dn1-dn500;
retain dn1-dn500 dncnt;
if first.rxcui then do;
  dncnt=0;
  do i=1 to 500;
    dn(i)=' ';
  end;
end;
dncnt+1;
dn(dncnt)=drugname;
if last.rxcui then output;
keep rxcui dn1-dn500 dncnt;
run;

%MACRO FFFX();

  %IF &INPUT^=INPUTCMS %THEN %DO;
  
    proc sort data=form.free_first_fill out=freefill (keep=contract_id plan_id rxcui);
    by rxcui;
    run;
    
  %END;
  %ELSE %IF &INPUT=INPUTCMS %THEN %DO;
    
    data plan_form_fff;
      length contpln $8;
      set form.plan_formulary;
      contpln = contract_id!!plan_id;
      if put(contpln,$contplnf.) ne 'NO';
    run;
    
    proc sort data=plan_form_fff out=planform_fff (keep=contract_id plan_id formulary_id);
      by formulary_id;
    run;
    
    proc sql;
      create table freefill as
        select f.formulary_id, f.rxcui, p.contract_id, p.plan_id 
        from form.fff f, plan_form_fff p
        where f.formulary_id = p.formulary_id
      order by f.rxcui;
    run;
    quit;
    
  %END;
%MEND;

%FFFX();

data freefill_drugname;
merge freefill (in=a) druglist_rollup (in=b);
by rxcui;
if a & b;
run;

data freefill_drugname_flip;
set freefill_drugname;
array dn(500) $ dn1-dn500;
length drugname $60;
do i=1 to dncnt;
  drugname=dn(i);
  output;
end;
keep contract_id plan_id rxcui drugname;
run;

proc sort data=IN1.bene_script out=script_temp (keep=drugname drugname_code) nodupkey;
by drugname drugname_code;
run;

proc sort data=freefill_drugname_flip;
by drugname;
run;

data merge_script;
merge freefill_drugname_flip (in=a) script_temp (in=b);
by drugname;
if a;
run;

DATA _NULL_;
CALL SYMPUT('NUM',TRIM(LEFT(PUT(NUMOBS,4.))));
STOP;
SET merge_script NOBS=NUMOBS;
STOP;
RUN;

%MACRO FFFFMT;
%IF &NUM > 0 %THEN %DO;
data fmt fmtlast;
set merge_script end=last;
length start $13 label $3 fmtname $8 hlo $1;
start=contract_id || plan_id || drugname_code;
label='yes';
fmtname='$fffmt';
hlo=' ';
output fmt;
if last then do;
  output fmtlast;
  start='other';
  label='no';
  hlo='O';
  output fmt;
  output fmtlast;
end;
keep start label fmtname hlo;
run;
%END;
%ELSE %DO;
DATA fmt fmtlast;
fmtname='$fffmt';
start='other';
label='no';
hlo='O';
output fmt;
output fmtlast;
keep start label fmtname hlo;
RUN;
%END;
%MEND;

%FFFFMT;
RUN;

proc sort data=fmt nodupkey;
by start;
run;

proc format cntlin=fmt library=library;
run;
