* PROGRAM: BUILD_GAPDRUGS_FORMAT.SAS;

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 GAPCOV();
  %IF &INPUT^=INPUTCMS %THEN %DO;
    PROC SORT DATA=FORM.GAP_DRUGS OUT=GAPDRUGS;
    BY RXCUI;
    RUN;
  %END;
  %ELSE %IF &INPUT=INPUTCMS %THEN %DO;
    PROC SORT DATA=FORM.PLAN_GAP_COVERED_RXCUI OUT=GAPDRUGS (KEEP=CONTRACT_ID PLAN_ID RXCUI);
    WHERE PARTIAL_TIER_FLAG='Yes' & COVERED='Yes';
    BY RXCUI;
    RUN;
  %END;
%MEND;

%GAPCOV();

data gapdrugs_drugname;
merge gapdrugs (in=a) druglist_rollup (in=b);
by rxcui;
if a & b;
run;

data gapdrugs_drugname_flip;
set gapdrugs_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=gapdrugs_drugname_flip;
by drugname;
run;

data merge_script;
merge gapdrugs_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 GAPFMT;
%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='$gapf';
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='$gapf';
start='other';
label='no';
hlo='O';
output fmt;
output fmtlast;
keep start label fmtname hlo;
RUN;
%END;
%MEND;

%GAPFMT;
RUN;

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

proc format cntlin=fmt library=library;
run;
