

* PROGRAM: PLAN_LEVEL.SAS;
* DESCRIPTION: CREATES A PLAN LEVEL FILE FROM PLAN_FORMULARY AND FORMULARYDATA FILES;

LIBNAME FORM "&FORMDIR";
LIBNAME PBP "&PBPDIR";

PROC SORT DATA=FORM.PLAN_FORMULARY OUT=PLAN_FORM NODUPKEY;
  BY FORMULARY_ID CONTRACT_ID PLAN_ID;
RUN;

DATA CONTRACT_PLAN;
  LENGTH CONTRACT_PLAN $8;
  SET PLAN_FORM;
  CONTRACT_PLAN = CONTRACT_ID||PLAN_ID;
  IF PUT(CONTRACT_PLAN,$CONTPLNF.) NE 'NO';
RUN;

PROC SORT DATA=FORM.FORMULARY(KEEP=FORMULARY_ID FORMULARY_VERSION) NODUPKEY OUT=FORMDATA;
  BY FORMULARY_ID FORMULARY_VERSION;
RUN;

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

%MACRO FMT;
  %IF &NUM > 0 %THEN %DO;
    DATA FORMULARY_FMT (KEEP=START LABEL HLO FMTNAME);
      SET FORMDATA (RENAME=FORMULARY_ID=START) END=LAST;
      LENGTH FMTNAME $8 LABEL 8 HLO $1;
      FMTNAME='$PFORMF';
      LABEL=FORMULARY_VERSION;
      HLO=' ';
      OUTPUT;
      IF LAST THEN DO;
        START='OTHER';
        LABEL=.;
        HLO='O';
        OUTPUT;
      END;
    RUN;
  %END;
  %ELSE %DO;
    DATA FORMULARY_FMT (KEEP=START LABEL HLO FMTNAME);
      LENGTH FMTNAME $8 LABEL 8 HLO $1;
      FMTNAME='$PFORMF';
      START='OTHER';
      LABEL='NO';
      HLO='O';
      OUTPUT;
    RUN;
  %END;
%MEND;

%FMT;
RUN;

PROC FORMAT LIBRARY=LIBRARY CNTLIN=FORMULARY_FMT;
RUN;

DATA PLAN_LEVEL;
  LENGTH FORMULARY_VERSION 8;
  SET CONTRACT_PLAN;
  FORMULARY_VERSION = PUT(FORMULARY_ID,$PFORMF.);
RUN;

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

%MACRO FMT2;
  %IF &NUM > 0 %THEN %DO;
    DATA CONTRACT_FMT (KEEP=START LABEL HLO FMTNAME);
      SET PLAN_LEVEL (RENAME=CONTRACT_PLAN=START) END=LAST;
      LENGTH FMTNAME $8 LABEL 8 HLO $1;
      FMTNAME='$CONTVER';
      LABEL=FORMULARY_VERSION;
      HLO=' ';
      OUTPUT;
      IF LAST THEN DO;
        START='OTHER';
        LABEL=.;
        HLO='O';
        OUTPUT;
      END;
    RUN;
  %END;
  %ELSE %DO;
    DATA CONTRACT_FMT (KEEP=START LABEL HLO FMTNAME);
      LENGTH FMTNAME $8 LABEL 8 HLO $1;
      FMTNAME='$CONTVER';
      START='OTHER';
      LABEL=.;
      HLO='O';
      OUTPUT;
    RUN;
  %END;
%MEND;

%FMT2;
RUN;

PROC FORMAT CNTLIN=CONTRACT_FMT LIBRARY=LIBRARY;
RUN;
