****************************************************************************************************
*                                           PROGRAM OVERVIEW
****************************************************************************************************
*
* PROGRAM: ms_episoderec2.sas  
*
* Created (mm/dd/yyyy): 07/31/2014 
* Last modified: 03/19/2015
* Version: 1.1
*
*--------------------------------------------------------------------------------------------------
* PURPOSE:
*   While allowing a maximum gap between two consecutve enrollment periods, this program bridges 
* 	member raw enrollment episodes  into continuous periods.                                      
*   
*  Program inputs:                                                                                   
* 	-SAS data file with enrollment data
* 
*  Program outputs:                                                                                                                                       
* 	-SAS data file (.SAS7BDAT format) containing the bridged enrollment episodes
* 
*  PARAMETERS:                                                                       
*	-INFILE    = SAS dataset containing the raw enrollment data               						   			
*	-OUTFILE   = SAS output dataset containing the conciliated enrollment periods					   
*  	-COVERAGE  = Drug and Medical coverage indicator														       
*  	-CHARTRES  = Chart availability indicator															       		
*  	-ENRSTART  = Name of enrollment episode start date variable in INFILE	    					   
*  	-ENREND    = Name of enrollment episode end date variable in INFILE								   
*  	-ENROLGAP  = Maximum allowable enrollment episode gap											   
*       -REMOVEDUP = Indicates the removal of duplicates from the output file    
* 
*  Programming Notes:                                                                                
*   -Consolidated enrollment episode start and end dates are named EStart EEnd.         
*   -User can use rename after if other names are preferred.                            
*   -In the case where there is the presence of time varying variables,                 
*    this procedure will keep all records of the input file.                                                                                                
*
*
*--------------------------------------------------------------------------------------------------
* CONTACT INFO: 
*  Mini-Sentinel Coordinating Center
*  info@mini-sentinel.org
*
*--------------------------------------------------------------------------------------------------
*  CHANGE LOG: 
*
*   Version   Date       Initials      Comment (reference external documentation when available)
*   -------   --------   --------   ---------------------------------------------------------------
*    1.1      03/19/15	    DM	      Changed the chart comparison value from N to Y to prevent
*                                     discrepancies due to other values in MSDD databases
*	  
*									
*
***************************************************************************************************;


%macro ms_episoderec2(INFILE=, OUTFILE=, COVERAGE=, CHARTRES=, ENRSTART=, ENREND=, ENROLGAP=, REMOVEDUP=); 

%put =====> MACRO CALLED: ms_episoderec2 v1.1;

*Sort in approrpiate order;
    proc sort data=&INFILE. out=&OUTFILE.;
    by Patid &ENRSTART. &ENREND.;
    %IF %UPCASE("&COVERAGE.") eq %STR("MD") %THEN %DO; 
        where upcase(MEDCOV)="Y" and upcase(DRUGCOV)="Y";
    %END;
    %IF %UPCASE("&COVERAGE.") eq %STR("M") %THEN %DO; 
        where upcase(MEDCOV)="Y";
    %END;
    %IF %UPCASE("&COVERAGE.") eq %STR("D") %THEN %DO; 	
        where upcase(DRUGCOV)="Y";
    %END;
    run;


%put &CHARTRES.;

*Managing chart type;
%if %UPCASE("&CHARTRES.")=%str("Y") %then %do;
	Data _NoChart;
	set &OUTFILE.;
	where chart ne 'Y' and (&startfollowup. <= Enr_Start <= &enddate. or
	                        &startfollowup. <= Enr_End <= &enddate.);
	keep Patid;
	run;

	proc sort nodupkey data=_Nochart;
	by PatId;
	run;

	data &OUTFILE.;
	merge &OUTFILE.(in=a)
	      _Nochart(in=b);
	by Patid;
	if a and not b;
	run;
%end;

%macro wrapper();
	data &OUTFILE.;
	   set  &OUTFILE.(where=(Enr_End >= Enr_Start));
	   by PatId;

	   *Change episode if maximum allowable gap is reached or if changes occur in benefit coverage;
		%IF %UPCASE("&COVERAGE.") eq %STR("MD") %THEN %DO; 
			if &ENRSTART.-lag(&ENREND.)-1 > &ENROLGAP. or MedCov ne lag(MedCov) or DrugCov ne lag(DrugCov) then episode=episode+1; 
		%END;
		%IF %UPCASE("&COVERAGE.") eq %STR("M") %THEN %DO; 
			if &ENRSTART.-lag(&ENREND.)-1 > &ENROLGAP. or MedCov ne lag(MedCov) then episode=episode+1;
		%END;
		%IF %UPCASE("&COVERAGE.") eq %STR("D") %THEN %DO; 	
			if &ENRSTART.-lag(&ENREND.)-1 > &ENROLGAP. or DrugCov ne lag(DrugCov) then episode=episode+1;
		%END;
		if first.Patid then episode=1;
	   retain episode;
	run;
%mend wrapper;
%wrapper();

/*Reconciliation of eligible episodes*/
proc means data=&OUTFILE. nway noprint;
   var &ENRSTART. &ENREND.;
   class PatId episode;
*   id Birth_Date sex MinAgeDate MaxAgeDate MedCov DrugCov;
   output out=&OUTFILE.(drop=_:) min(&ENRSTART.)= max(&ENREND.)=;
run;

%macro wrapper();
%IF "&REMOVEDUP." = "Yes" %THEN %DO;
    proc sort nodupkey data=&OUTFILE.;
    by _ALL_;
    run;
%END;
%mend wrapper;
%wrapper();

%put NOTE: ********END OF MACRO: ms_episoderec2 v1.1********;

%mend ms_episoderec2;