/******************************************************************************
 * Programme : Maîtriser les Formats SAS : Comment générer un Dataset de Contrôle (CNTLOUT) Robuste
 * Reference : GENERABC61
 * Source    : https://www.wearecas.eu/en/sampleCode/GENERABC61
 ******************************************************************************/

/* --- BLOC 1 --- */
%macro mp_cntlout(
  iftrue=(1=1)
  ,libcat=
  ,cntlout=work.fmtextract
  ,fmtlist=0
)/*/STORE SOURCE*/;
%local ddlds cntlds i;

%if not(%eval(%unquote(&iftrue))) %then %return;

%let ddlds=%mf_getuniquename();
%let cntlds=%mf_getuniquename();

/* --- BLOC 2 --- */
%mddl_sas_cntlout(libds=&ddlds)

%if %index(&libcat,-)>0 and %scan(&libcat,2,-)=FC %then %do;
  %let libcat=%scan(&libcat,1,-);
%end;

proc format lib=&libcat cntlout=&cntlds;
%if "&fmtlist" ne "0" and "&fmtlist" ne "" %then %do;
  select
  %do i=1 %to %sysfunc(countw(&fmtlist,%str( ));
    %scan(&fmtlist,&i,%str( ))
  %end;
  ;
%end;
run;

/* --- BLOC 3 --- */
data &cntlout/nonote2err;
  if 0 then set &ddlds;
  set &cntlds;
  by type fmtname notsorted;

  /* align the numeric values to avoid overlapping ranges */
  if type in ("I","N") then do;
    %mp_aligndecimal(start,width=16)
    %mp_aligndecimal(end,width=16)
  end;

  /* create row marker. Data cannot be sorted without it! */
  if first.fmtname then fmtrow=1;
  else fmtrow+1;

run;

/* --- BLOC 4 --- */
proc sort;
  by type fmtname fmtrow;
run;

/* --- BLOC 5 --- */
proc sql;
drop table &ddlds,&cntlds;
quit;

/* --- BLOC 6 --- */
%mend mp_cntlout;

