****************************************************************************************************
*                                           PROGRAM OVERVIEW
****************************************************************************************************
*
* PROGRAM: ms_episoderec2.sas  
*
* Created (mm/dd/yyyy): 07/31/2014 
* Last modified: 02/05/2019
* Version: 1.2
*
*--------------------------------------------------------------------------------------------------
* 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: 
*  Sentinel Coordinating Center
*  info@sentinelsystem.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
*	  
*    1.2      02/05/19	    AP	      DEV-3233: Modified Chart restriction to ensure enrollment span
*									  only needs to overlap query period
*
***************************************************************************************************;

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

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

    *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) in ("Y", "A") and upcase(DRUGCOV)="Y";
        %END;
        %IF %UPCASE("&COVERAGE.") eq %STR("M") %THEN %DO; 
            where upcase(MEDCOV) in ("Y", "A");
        %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 %MS_PeriodsOverlap(period1=enr_start enr_end, period2=&startdate. &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;

	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;

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

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

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

%mend ms_episoderec2;