* PROGRAM NAME: BUILD_GAPDRUGS_FORMAT.SAS;

%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();

%MACRO GAPFMT;
  %IF &NUM > 0 %THEN %DO;
    DATA FMT FMTLAST;
      SET GAPDRUGS END=LAST;
      LENGTH START $16 LABEL $3 FMTNAME $8 HLO $1;
      START=CONTRACT_ID || PLAN_ID || LEFT(PUT(RXCUI,8.));
      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;
