* PROGRAM NAME: BUILD_FFF_FORMAT.SAS;

LIBNAME FORM "&FORMDIR";

%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;
      SET FORM.PLAN_FORMULARY;
      LENGTH CONTPLN $8;      
      CONTPLN = CONTRACT_ID || PLAN_ID;
    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 _NULL_;
CALL SYMPUT('NUM',TRIM(LEFT(PUT(NUMOBS,4.))));
STOP;
SET FREEFILL NOBS=NUMOBS;
STOP;
RUN;
%MACRO FFFFMT;
  %IF &NUM > 0 %THEN %DO;
    DATA FMT FMTLAST;
      SET FREEFILL END=LAST;
      LENGTH START $16 LABEL $3 FMTNAME $8 HLO $1;
      START=CONTRACT_ID || PLAN_ID || LEFT(PUT(RXCUI,8.));
      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;