%macro MMSStyle;
proc template;
  define Style Styles.MMS; 
      parent = styles.printer;
      style GraphColors                                                       
         "Abstract colors used in graph styles" /                             
         'gablock' = cxF1F0F6                                                 
         'gblock' = cxD7DFEF                                                  
         'gcclipping' = cxDC531F                                              
         'gclipping' = cxE7774F                                               
         'gcstars' = cx000000                                                 
         'gstars' = cxB9CFE7                                                  
         'gcruntest' = cxBF4D4D                                               
         'gruntest' = cxCAE3FF                                                
         'gccontrollim' = cxBFC7D9                                            
         'gcontrollim' = cxE6F2FF                                             
         'gcerror' = cx000000                                                 
         'gerror' = cxB9CFE7                                                  
         'gcpredictlim' = cx003178                                            
         'gpredictlim' = cxB9CFE7                                             
         'gcpredict' = cx003178                                               
         'gpredict' = cx003178                                                
         'gcconfidence2' = cx003178                                           
         'gcconfidence' = cx003178                                            
         'gconfidence2' = cxB9CFE7                                            
         'gconfidence' = cxB9CFE7                                             
         'gcfit2' = cx003178                                                  
         'gcfit' = cx003178                                                   
         'gfit2' = cx003178                                                   
         'gfit' = cx003178                                                    
         'gcoutlier' = cx000000                                               
         'goutlier' = cxB9CFE7                                                
         'gcdata' = cx000000                                                  
         'gdata' = cx0000df                  /* cxB9CFE7 */                                                  
         'ginsetheader' = colors('docbg')                                     
         'ginset' = cxFFFFFF                                                  
         'greferencelines' = cx808080                                         
         'gheader' = colors('docbg')                                          
         'gconramp3cend' = cxFF0000                                           
         'gconramp3cneutral' = cxFF00FF                                       
         'gconramp3cstart' = cx0000FF                                         
         'gramp3cend' = cxDD6060                                              
         'gramp3cneutral' = cxFFFFFF                                          
         'gramp3cstart' = cx6497EB                                            
         'gconramp2cend' = cx6497EB                                           
         'gconramp2cstart' = cxFFFFFF                                         
         'gramp2cend' = cx5E528B                                              
         'gramp2cstart' = cxF1F0F6                                            
         'gtext' = cx000000                                                   
         'glabel' = cx000000                                                  
         'gborderlines' = cx000000                                            
         'goutlines' = cx000000                                               
         'ggrid' = cxECECEC                                                   
         'gaxis' = cx000000                                                   
         'gshadow' = cx000000                                                 
         'glegend' = cxFFFFFF                                                 
         'gfloor' = cxFFFFFF                                                  
         'gwalls' = _undef_                                                   
         'gcdata12' = cxF9DA04                                                
         'gcdata11' = cxB38EF3                                                
         'gcdata10' = cx47A82A                                                
         'gcdata9' = cxD17800                                                 
         'gcdata8' = cxB26084                                                 
         'gcdata6' = cx7F8E1F                                                 
         'gcdata7' = cx2597FA                                                 
         'gcdata4' = cx543005                                                 
         'gcdata5' = cx9D3CDB                                                 
         'gcdata3' = cx01665E                                                 
         'gcdata2' = cxB2182B                                                 
         'gcdata1' = cx2A25D9                                                 
         'gdata12' = cxDDD17E                                                 
         'gdata11' = cxB7AEF1                                                 
         'gdata10' = cx87C873                                                 
         'gdata9' = cxCF974B                                                  
         'gdata8' = cxCD7BA1                                                  
         'gdata6' = cxBABC5C                                                  
         'gdata7' = cx94BDE1                                                  
         'gdata4' = cxA9865B                                                  
         'gdata5' = cxB689CD                                                  
         'gdata3' = cxaf0000             /* cx66A5A0 */                                                  
         'gdata2' = cxcfaf00             /* cxDE7E6F */                                                 
         'gdata1' = cx00af00;            /* cx7C95CA */      
  end;  
run;
%mend; 

/* Suppliment the Data for Graphing Purposes*/
%macro setup_data(libref,where);
   ods noresults; 

   data ae;  
     set &libref..ae&where. end=eof; 
     by usubjid;
     keep studyid usubjid aeseq aeterm aesev aeout aestdtc aeendtc aestdate aeendate aestdy aeendy aedecod aeacn severity milddy moderatedy severedy;
     format aestdate aeendate YYMMDD10.;

     len = length(strip(AESTDTC));
     if ( len eq 4 ) then
        aestdate = input(cats(AESTDTC,"-01-01"), ANYDTDTE.);
     else if ( len lt 10 ) then
        aestdate = input(AESTDTC, ANYDTDTE.);
     else 
        aestdate = input(AESTDTC, ANYDTDTE10.);

     len = length(strip(AEENDTC)); 
     if ( len eq 4 ) then
        aeendate = input(cats(AEENDTC, "01-01"), ANYDTDTE.);
     else if ( len lt 10 ) then
        aeendate = input(AEENDTC, ANYDTDTE.);
     else
        aeendate = input(AEENDTC, ANYDTDTE10.);

     if AESEV= 'SEVERE' then do; 
        severedy=AESTDY;
        severity = 3;
     end;
     else if AESEV = 'MODERATE' then do; 
        moderatedy=AESTDY;
        severity = 2;
     end;
     else if AESEV = 'MILD' then do; 
        milddy=AESTDY;
        severity = 1;
     end; 
     else 
        severity = 4;
   ;run;

   ods output summary=ae_stats;
   proc means data=ae; 
   var aestdate aeendate aestdy aeendy;
   by usubjid;
   run;

   data aegraph; 
     set ae end=eof; 
     by usubjid;
     keep studyid usubjid aeseq aeterm aesev aeout aestdtc aeendtc aestdate aeendate aestdy aeendy aedecod aeacn severity milddy moderatedy severedy y xc aegraphht aeminday aemaxday aemindate aemaxdate endy;
     retain aeminday aemaxday aemindate aemaxdate maxday frequency aegraphht y xc label_day_offset; 
     format aemindate aemaxdate YYMMDD10.;
     length rfstdtc $ 10. rfendtc $ 10. aegraphht $ 6.;

     endy = aeendy;
     if ( _n_ eq 1 ) then do; 
	    declare hash ae(dataset: "ae_stats", 
                        multidata: 'Y');
        ae.defineKey("USUBJID");
        ae.defineData("aestdy_n", "aestdy_min", "aeendy_max", 'aestdate_min', 'aeendate_max');
        ae.defineDone();

        declare hash dmhash(dataset: "&libref..dm&where.");
        dmhash.defineKey("USUBJID");
        dmhash.defineData("rfstdtc", "rfendtc");
        dmhash.defineDone();
     end; 

     if first.usubjid eq 1 then do; 
        aestdy_n=.; aestdy_min=.; aeendy_max=.; aestdate_min=.; aeendate_max=.; rfstdtc=""; rfendtc="";
        aeminday=.; aemaxday=.; aemindate=.; aemaxdate=.; frequency=.; maxday=.; y=.; xc=.; aegraphht="";

        if ae.find() eq 0 then do;
           frequency = aestdy_n; 
     
           if ( dmhash.find() eq 0 ) then do; 
              len = length(strip(RFSTDTC)); 
              if ( len eq 4 ) then
                 mindate = input(cats(RFSTDTC,"-01-01"), ANYDTDTE.);
              else if ( len lt 10 ) then
                 mindate = input(RFSTDTC, ANYDTDTE.);
              else 
                 mindate = input(RFSTDTC, ANYDTDTE10.);
	          call symput('RFMINDATE', mindate);

              len = length(strip(RFENDTC));
              if ( len eq 4 ) then
                 maxdate = input(cats(RFENDTC, "01-01"), ANYDTDTE.);
              else if ( len lt 10 ) then
                 maxdate = input(RFENDTC, ANYDTDTE.);
              else if ( len ne 0 ) then 
                 maxdate = input(RFENDTC, ANYDTDTE10.);
              call symput('RFMAXDATE', maxdate);

   	  	      if ( aestdate_min ne . ) then 
		         aemindate = MIN(aestdate_min, mindate);
              else 
		         aemindate = mindate; 

		      if ( aeendate_max ne . ) then 
                 aemaxdate = MAX(aeendate_max, maxdate);
		      else 
		         aemaxdate = maxdate; 
            
              label_day_offset = round((aemaxdate-aemindate)/8*1.87);    /* 1.25 inch in # of days */

              aeminday  = AESTDY_MIN-label_day_offset;
              aemindate = aemindate-label_day_offset; 
  
		      maxday   = MAX( AEENDY_MAX, aemaxdate-aemindate-label_day_offset);
			  aemaxday = maxday + round(label_day_offset*.1);

              aegraphht=put(10*frequency+150, 4.) || "px";
       end;
     end; 
   end; 
 
   if ( endy eq . ) then 
      endy = maxday; 

   if frequency > 0 then 
      y=5*aeseq/frequency;

   xc = aestdy-round(label_day_offset*(length(strip(aedecod))/22)/2);

   output;

   if ( eof eq 1 ) then do; 
      ae.delete();
	  dmhash.delete();
   end;
   ;run;

   /*-----------------------------------------------------*/
   /*--Extract MEDS data for one patient, reduce columns--*/
   /*-----------------------------------------------------*/
   data work.cm;
   set &libref..cm&where.;
     format cmstdate cmendate YYMMDD10.;
	 length cmmed $ 24.;
     
	 cmdosu_short = upcase(strip(CMDOSU));
	 if ( cmdosu_short eq "MILLIGRAM" ) then 
	    CMDOSU = "Mg";
	 else if ( cmdosu_short eq "TABLESPOON" ) then 
	    CMDOSU = "Tbls";

     CMMED = strip(CMTRT) || " " || strip(CMDOSE) || " "  || strip(CMDOSU);
 
     label CMMED="Prescribed Drugs";

     len = length(strip(CMSTDTC));
     if ( len = 4 ) then 
        cmstdate = input(cats(strip(CMSTDTC),"-01-01"), ANYDTDTE10.);
     else if ( len < 10 ) and ( len > 4)  then
        cmstdate = input(strip(CMSTDTC), ANYDTDTE.);
     else if (len = 10 ) then
        cmstdate = input(strip(CMSTDTC), ANYDTDTE10.);

     len = length(strip(CMENDTC));
     if ( len = 4 ) then
        cmendate = input(cats(strip(CMENDTC), "01-01"), ANYDTDTE10.);
     else if ( len > 10 ) and ( len < 4 ) then
        cmendate = input(strip(CMENDTC), ANYDTDTE.);
     else if ( len = 10 ) then
        cmendate = input(strip(CMENDTC), ANYDTDTE10.);
   ;run;

   proc sort data=work.cm;
   by usubjid CMMED;run;

   ods output summary=cm_stats;
   proc means data=cm; 
   var cmstdate cmendate cmstdy cmendy;
   by usubjid;
   run;

   data cmgraph; 
     set cm end=eof; 
     by usubjid cmmed;
	 length cmgraphht $ 6.;
     retain cmminday cmmaxday cmmindate cmmaxdate  maxday frequency y xc cmgraphht seq label_day_offset; 
     format mindate maxdate cmenddate_max YYMMDD10.;

     endy = cmendy; 
 
	 if ( _n_ eq 1 ) then do; 
        declare hash cm(dataset: "cm_stats", 
                       multidata: 'Y');
        cm.defineKey("USUBJID");
        cm.defineData("cmstdy_n", "cmstdy_min", "cmendy_max", 'cmstdate_min', 'cmendate_max');
        cm.defineDone();
     end; 

     if first.usubjid eq 1 then do; 
        cmstdy_n=.; cmstdy_min=.; cmendy_max=.; cmstdate_min=.; cmendate_max=.; seq=1;
		cmminday=.; cmmaxday=.; cmmindate=.; cmmaxdate=.; frequency=.; y=.; xc=.; cmgraphht=""; seq=1; 

        if cm.find() eq 0 then do;
          frequency = cmstdy_n; 

          mindate = symget('RFMINDATE'); 
  		  maxdate = symget('RFMAXDATE');  
 
          if ( cmstdate_min ne . ) and ( cmstdate_min-mindate > -15 ) then 
	         cmmindate = MIN(cmstdate_min, mindate-15);
          else 
	         cmmindate = mindate-15; 

	      if ( cmendate_max ne . ) then 
             cmmaxdate = MAX(cmendate_max, maxdate);
	      else 
	         cmmaxdate = maxdate; 
 
          label_day_offset = round((cmmaxdate-cmmindate)/8*1.25);    /* 1.25 inch in # of days */

          if ( CMSTDY_MIN < minday-label_day_offset ) then do; 
             cmminday = -minday-label_day_offset;
	         cmmindate = mindate -label_day_offset;
		  end; 
		  else do;
		     cmminday  = CMSTDY_MIN-label_day_offset;
		  end; 

          cmmaxday = MAX( CMENDY_MAX, round(cmmaxdate-cmmindate-(label_day_offset*.9)));  
		  maxday   = MAX( CMENDY_MAX, cmmaxdate-cmmindate-(label_day_offset));

          cmgraphht=put(10*frequency+150, 4.) || "px";
       end;
     end; 

     if ( endy eq . ) then 
        endy = maxday; 

     if first.cmmed then do;  
        y=.; xc=.;
	    if cmstdy ne . then do;
           if frequency > 0 then do; 
              y=5*seq/frequency;
	   	     seq = seq+1;
           end; 

           xc = cmstdy-round(label_day_offset*(length(strip(cmmed))/20)/2);
        end; 
     end; 

     output;

	 if ( eof eq 1 ) then
	    cm.delete();
  ;run;

   /* Vitals */
   proc sort data=&libref..vs&where. out=vs; 
   by usubjid vstestcd vstpt;run;

   ods output summary=vs_stats;
   proc means data=vs; 
   var vsstresn;
   by usubjid vstestcd;
   run;

   data ae_vs_band(keep=usubjid vstestcd vsstresn_min vsstresn_max x mild_lower mild_upper 
                        moderate_lower moderate_upper severe_lower severe_upper aesev_group mild_ref moderate_ref severe_ref);
   set aegraph; 
   by usubjid; 
   retain usubjid aesev_group mild_lower mild_upper moderate_lower moderate_upper severe_lower severe_upper;
   length vstestcd $ 6. aesev_group $ 8.;

   if _n_ eq 1 then do; 
      array mild [-32767:32767] _temporary_;
      array moderate [-32767:32767] _temporary_;
      array severe [-32767:32767] _temporary_;
      array mildref [-32767:32767] _temporary_;
      array moderateref [-32767:32767] _temporary_;
      array severeref [-32767:32767] _temporary_;  
   end;

   if first.usubjid then do;
      do x = aeminday to aemaxday;
         mild[x] =0;
         moderate[x]=0;
         severe[x]=0;
         mildref[x] =0;
         moderateref[x]=0;
         severeref[x]=0;
     end;
   end; 

   do x = aestdy to endy;
      if severity eq 1 then
         mild[x] = 1;
      else if severity eq 2 then
         moderate[x] = 1;
      else if severity eq 3 then
         severe[x] = 1;

	  
      if ( aestdy eq aeendy ) then do; 
         if ( severity eq 1 ) then 
            mildref[x] = 1; 
         else if (severity eq 2 ) then 
            moderateref[x] = 1;
         else if ( severity eq 3 ) then 
            severeref[x]=1;
      end; 
   end;
   
   if last.usubjid then do;  
      mild_lower=.; mild_upper=.; moderate_lower=.; moderate_upper=.; severe_lower=.; severe_upper=.;
      aesev_group = aesev;
      dcl hash vs(dataset: "vs_stats(where=('" || usubjid || "'))",
                  multidata: 'Y' );
      vs.defineKey("usubjid");
      vs.defineData("vstestcd", "vsstresn_min", "vsstresn_max");
      vs.defineDone();
      if ( vs.find() eq 0 )then do;
         next = 0;
         do while ( next = 0);
           ae_started=0;
           do x = aeminday to aemaxday;
			   mild_ref=.; moderate_ref=.; severe_ref=.;

               mild_lower = vsstresn_min; 
               if mild[x] eq 1 then
                  mild_upper = vsstresn_max;
               else 
                  mild_upper = mild_lower; 
 
               moderate_lower = vsstresn_min; 
               if moderate[x] eq 1 then
                  moderate_upper = vsstresn_max;
               else 
                  moderate_upper = moderate_lower; 

               severe_lower = vsstresn_min; 
               if severe[x] eq 1 then do;
                  severe_upper = vsstresn_max;
               end;
               else 
                  severe_upper = severe_lower;

               if mildref[x] eq 1 then 
                  mild_ref = x;
               if moderateref[x] eq 1 then
                  moderate_ref = x;
               if severeref[x] eq 1 then 
                  severe_ref = x; 
               
               if ((( ae_started eq 0 ) and ( x > aeminday ) and ( x < aemaxday)) and 
                    (( mild[x] ne mild[x-1] ) or 
                     ( moderate[x] ne moderate[x-1] ) or 
                     ( severe[x] ne severe[x-1] ))) then do; 
                  output;
                  output;
				  ae_started = 1; 
			   end;
			   else if ((( ae_started eq 1 ) and ( x < aemaxday )) and 
                         (( mild[x] ne mild[x+1]) or 
                          ( moderate[x] ne moderate[x+1]) or 
                          ( severe[x] ne severe[x+1])))    then do;   
                  output;
                  output;
				  ae_started=0; 
			   end; 
			   else if ( ae_started eq 1 ) then do; 
                  output; 
				  if ( x eq aemaxday ) then 
				     output;
			   end; 

            end;
            next = vs.find_next();
         end;  
      end;
      vs.delete();
   end; 
   ;run;

   data vs; 
   set vs ae_vs_band;
   by usubjid vstestcd;
   ;run;
  
   /*  Labs */ 
   proc sort data=&libref..lb&where. out=lb; 
   by usubjid lbtestcd lbcat;run;

   ods output summary=lb_stats;
   proc means data=lb; 
   var lbstresn lbstnrhi lbstnrlo;
   by usubjid lbtestcd lbcat;
   run;

   data ae_lb_band(keep=usubjid lbtestcd lbcat lbstresn_min lbstresn_max x mild_lower mild_upper 
                        moderate_lower moderate_upper severe_lower severe_upper aesev_group mild_ref moderate_ref severe_ref);
   set aegraph; 
   by usubjid; 
   retain usubjid aesev_group;
   length lbtestcd $ 6. aesev_group $ 8. lbcat $ 10.;
   lbstnrhi_max=.; lbstnrlo_min=.; lbstresn_min=.; lbstresn_max=.;

   if _n_ eq 1 then do; 
      array mild [-32767:32767] _temporary_;
      array moderate [-32767:32767] _temporary_;
      array severe [-32767:32767] _temporary_;
      array mildref [-32767:32767] _temporary_;
      array moderateref [-32767:32767] _temporary_;
      array severeref [-32767:32767] _temporary_;
   end;

   if first.usubjid then do;
      do x = aeminday to aemaxday;
         mild[x] =0;
         moderate[x]=0;
         severe[x]=0;
         mildref[x] =0;
         moderateref[x]=0;
         severeref[x]=0;
      end;
   end;

   do x = aestdy to endy;
       if severity eq 1 then
          mild[x] = 1;
       else if severity eq 2 then
          moderate[x] = 1;
       else if severity eq 3 then
          severe[x] = 1;

       if ( aestdy eq aeendy ) then do;
          if ( severity eq 1 ) then 
             mildref[x] = 1; 
          else if (severity eq 2 ) then 
             moderateref[x] = 1;
          else if ( severity eq 3 ) then 
             severeref[x]=1;
     end; 
   end;

   if last.usubjid then do; 
      aesev_group = aesev;
      dcl hash lb(dataset: "lb_stats(where=('" || usubjid || "'))",
                  multidata: 'Y' );
      lb.defineKey("usubjid");
      lb.defineData("lbtestcd", "lbcat", "lbstresn_min", "lbstresn_max", "lbstnrlo_min", "lbstnrhi_max");
      lb.defineDone();
      if ( lb.find() eq 0 )then do;
         next = 0;
         do while ( next = 0);
		    ae_started=0; 
            do x = aeminday to aemaxday;
               mild_ref=.; moderate_ref=.; severe_ref=.; 

               mild_lower = MIN(lbstresn_min, lbstnrlo_min); 
               if mild[x] eq 1 then
                  mild_upper = MAX(lbstresn_max, lbstnrhi_max);
               else 
                  mild_upper = mild_lower; 

               moderate_lower = MIN(lbstresn_min, lbstnrlo_min); 
               if moderate[x] eq 1 then
                  moderate_upper = MAX(lbstresn_max, lbstnrhi_max);
               else 
                  moderate_upper = moderate_lower; 

               severe_lower = MIN(lbstresn_min, lbstnrlo_min); 
               if severe[x] eq 1 then
                  severe_upper = MAX(lbstresn_max, lbstnrhi_max);
               else 
                  severe_upper = severe_lower;

               if mildref[x] eq 1 then 
                  mild_ref =x;
               if moderateref[x] eq 1 then
                  moderate_ref = x;
               if severeref[x] eq 1 then 
                  severe_ref = x; 

               if ((( ae_started eq 0 ) and ( x > aeminday ) and ( x < aemaxday)) and 
                    (( mild[x] ne mild[x-1] ) or 
                     ( moderate[x] ne moderate[x-1] ) or 
                     ( severe[x] ne severe[x-1] ))) then do; 
                  output;
				  output; 
				  ae_started = 1; 
			   end;
			   else if ((( ae_started eq 1 ) and ( x < aemaxday )) and 
                         (( mild[x] ne mild[x+1]) or 
                          ( moderate[x] ne moderate[x+1]) or 
                          ( severe[x] ne severe[x+1])))    then do;   
                  output;
				  output;
				  ae_started=0; 
			   end; 
			   else if ( ae_started eq 1 ) then do; 
                  output; 
				  if ( x eq aemaxday ) then 
				     output;
			   end; 

                

	    end;
            next = lb.find_next();
         end;  
      end;
      lb.delete();
   end; 
   ;run;

   data lb; 
   set lb ae_lb_band; 
   by usubjid lbtestcd lbcat;
   ;run;
 
   proc freq data=cmgraph(keep=usubjid cmmed) noprint;
     by usubjid;
     tables cmmed / out=cmmed;
     run;
 
   proc sort data=cmgraph(keep=usubjid cmmed cmstdate cmendate) out=cmnodup nodup; 
    by usubjid cmmed; 
	run;

   /*--Merge frequency data with dates--*/ 
   data cmfreq;
   set cmnodup cmmed;
   by usubjid;
   x=1;
   ;run;
%mend;

/*--Create AE Graph--*/
%macro adverse_events;
%let usubjid=%sysfunc(dequote(&usubjid.));
%let height=%sysfunc(dequote(&height.));

   ods graphics / reset  noborder width=8in height=&height imagename="Adverse_Events_&usubjid."  noscale;
   ods noresults; 

   proc sgplot data=aegraph(where=(usubjid="&usubjid")) noautolegend nocycleattrs tmplout="aeplot.sas";
     refline 0 / axis=x lineattrs=(thickness=2);
     *vector x=eval(coln(-110,-110,-110)) y=eval(coln(-110,-110,-110)) / xorigin=-110 yorigin=-110 group=eval(coln(1,2,3)) lineattrs=(thickness=5px pattern=solid) name='sev';
     vector x=endy y=y / xorigin=aestdy yorigin=y noarrowheads lineattrs=(thickness=3px pattern=solid) group=severity; /* Draw the vectors for duration of AE */
     scatter x=aestdy y=y / markerattrs=(size=7px symbol=trianglefilled) group=aesev;  /* Start of Adverse Event */
     scatter x=aestdy y=y / markerattrs=graphdatadefault(size=8px symbol=triangle color=black);  /* Start of Adverse Event marker Outline*/
     scatter x=aeendy y=y / markerattrs=(size=7px symbol=trianglefilled) group=aesev;  /* End of Adverse Event */
     scatter x=aeendy y=y / markerattrs=graphdatadefault(size=8px symbol=triangle color=black);  /* End of Adverse Event marker Outline */
     scatter x=xc y=y / markerchar=aedecod markercharattrs=(size=7pt); /* Put out the labels */
     scatter x=aestdate y=y /  markerattrs=(size=0) x2axis; /* Attach some data for the xaxis2 */
	 refline &rfmindate / axis=x2; 
	 refline &rfmaxdate / axis=x2; 
     yaxis display=(nolabel noticks novalues) min=0;
     xaxis grid label='Study Days' offsetmin=0.02 offsetmax=0.02 values=(&minday to &maxday by 2);
     x2axis notimesplit display=(nolabel) tickvalueformat=date7. offsetmin=0.02 offsetmax=0.02 values=(&mindate to &maxdate); 
     *keylegend 'sev'/ title='Severity :';
     run;

   title;
   footnote;
%mend;

/*--Create CM Graph--*/
%macro Concomitant_Meds;
%let usubjid=%sysfunc(dequote(&usubjid.));
%let height=%sysfunc(dequote(&height.));

   ods graphics / reset  noborder width=8in height=&height imagename="Concomitant_Meds_&usubjid"  noscale;
   ods noresults; 
   proc sgplot data=cmgraph(where=(usubjid="&usubjid")) noautolegend nocycleattrs tmplout="cmplot.sas";
     refline 0 / axis=x lineattrs=(thickness=2);
     vector x=endy y=y / xorigin=cmstdy yorigin=y noarrowheads lineattrs=(thickness=3px pattern=solid);  
     scatter x=cmstdy y=y / markerattrs=(size=7px symbol=trianglefilled);   
     scatter x=cmstdy y=y / markerattrs=graphdatadefault(size=8px symbol=triangle color=blue);   
     scatter x=cmendy y=y / markerattrs=(size=7px symbol=trianglefilled);   
     scatter x=cmendy y=y / markerattrs=graphdatadefault(size=8px symbol=triangle color=blue);   
     scatter x=xc y=y / group=cmmed markerchar=cmmed markercharattrs=(size=7pt color=black);  
     scatter x=cmstdate y=y /  markerattrs=(size=0) x2axis;  
*	 refline &rfmindate / axis=x2; 
*	 refline &rfmaxdate / axis=x2; 
     yaxis display=(nolabel noticks novalues) min=0;
     xaxis grid label='Study Days' offsetmin=0.02 offsetmax=0.02 values=(&minday to &maxday by 2);
*     x2axis notimesplit display=(nolabel) tickvalueformat=date7. offsetmin=0.02 offsetmax=0.02 values=(&mindate to &maxdate); 
     run;

   title;
   footnote;
%mend;

/*--Create Vital Sign Graph--*/
%macro Vital_signs;
%let usubjid=%sysfunc(dequote(&usubjid.));
%put %str(Min = &rfmindate);
%put %str(Max = &rfmaxdate); 

   ods graphics / height=5in width=8in imagename="Vital_Signs_&usubjid"; 
   ods noresults; 

   proc sgpanel data=vs(where=(usubjid="&usubjid" and vstestcd ne "HEIGHT")) noautolegend cycleattrs;
      panelby vstestcd / uniscale=column spacing=5 rows=5 layout=rowlattice rowheaderpos=left novarname;
        band x=x lower=mild_lower upper=mild_upper / transparency=.9 fillattrs=(color=lightgreen) name="Mild" legendlabel="Mild";
        band x=x lower=moderate_lower upper=moderate_upper / transparency=.9 fillattrs=(color=yellow) name="Moderate" legendlabel="Moderate";
        band x=x lower=severe_lower upper=severe_upper / transparency=.9 fillattrs=(color=lightred) name="Severe" legendlabel="Severe";
        refline mild_ref / axis=x transparency=.9 lineattrs=(color=lightgreen);
        refline moderate_ref / axis=x transparency=.9 lineattrs=(color=yellow);
        refline severe_ref / axis=x transparency=.9 lineattrs=(color=lightred);
        series x=visitdy y=vsstresn / Group=vstpt markers markerattrs=( symbol=squarefilled size=8px) lineattrs=(pattern=solid) name="Series";
        scatter x=visitdy y=vsstresn / Group=vstpt markerattrs=( symbol=square size=10px color=black);
*	 refline &rfmindate / axis=x2; 
*	 refline &rfmaxdate / axis=x2; 
*     x2axis notimesplit display=(nolabel) tickvalueformat=date7. offsetmin=0.02 offsetmax=0.02 values=(&mindate to &maxdate); 
       rowaxis display=(nolabel);
       keylegend "Mild" "Moderate" "Severe";
	   keylegend "Series";
   run;

   title;
   footnote;
%mend;

/*--Create Vital Sign Graph--*/
%macro LabsUR;
%let usubjid=%sysfunc(dequote(&usubjid.));

   ods graphics / height=5in width=8in imagename="LabsUR_&usubjid"  noscale;
   ods noresults; 

   proc sgpanel data=lb(where=(usubjid="&usubjid" and lbcat="URINALYSIS" and lbtestcd ne "COLOR  ")) noautolegend cycleattrs;
     panelby lbtestcd / uniscale=column spacing=5 rows=5 layout=rowlattice rowheaderpos=left novarname;
       band x=lbdy lower=lbstnrlo upper=lbstnrhi / transparency=.8  fillattrs=(color=lightgray) name="Limits" LegendLabel="Reference Range"; 
       band x=x lower=mild_lower upper=mild_upper / transparency=.9 fillattrs=(color=lightgreen) name="Mild" legendlabel="Mild";
       band x=x lower=moderate_lower upper=moderate_upper / transparency=.9 fillattrs=(color=yellow) name="Moderate" legendlabel="Moderate";
       band x=x lower=severe_lower upper=severe_upper / transparency=.9 fillattrs=(color=lightred) name="Severe" legendlabel="Severe";
       refline mild_ref / axis=x transparency=.9 lineattrs=(color=lightgreen);
       refline moderate_ref / axis=x transparency=.9 lineattrs=(color=yellow);
       refline severe_ref / axis=x transparency=.9 lineattrs=(color=lightred);
       series x=lbdy y=lbstresn / markers markerattrs=( symbol=squarefilled size=8px) lineattrs=(pattern=solid) name="Series";
       scatter x=lbdy y=lbstresn / markerattrs=( symbol=square size=10px color=black);
       rowaxis display=(nolabel);
       keylegend "Mild" "Moderate" "Severe";
       keylegend "Limits" "Series";
   run;

   title;
   footnote;
%mend;/*--Create Vital Sign Graph--*/

%macro LabsHE;
%let usubjid=%sysfunc(dequote(&usubjid.));

   ods graphics / height=10in width=8in imagename="LabsHE_&usubjid"  noscale;
   ods noresults; 

   proc sgpanel data=lb(where=(usubjid="&usubjid" and lbcat="HEMATOLOGY")) noautolegend cycleattrs;
     panelby lbtestcd / uniscale=column spacing=5 rows=12 layout=rowlattice rowheaderpos=left novarname;
       band x=lbdy lower=lbstnrlo upper=lbstnrhi / transparency=.8  fillattrs=(color=lightgray) name="Limits" LegendLabel="Reference Range"; 
       band x=x lower=mild_lower upper=mild_upper / transparency=.9 fillattrs=(color=lightgreen) name="Mild" legendlabel="Mild";
       band x=x lower=moderate_lower upper=moderate_upper / transparency=.9 fillattrs=(color=yellow) name="Moderate" legendlabel="Moderate";
       band x=x lower=severe_lower upper=severe_upper / transparency=.9 fillattrs=(color=lightred) name="Severe" legendlabel="Severe";
       refline mild_ref / axis=x transparency=.9 lineattrs=(color=lightgreen);
       refline moderate_ref / axis=x transparency=.9 lineattrs=(color=yellow);
       refline severe_ref / axis=x transparency=.9 lineattrs=(color=lightred);
       series x=lbdy y=lbstresn / markers markerattrs=( symbol=squarefilled size=8px) lineattrs=(pattern=solid) name="Series";
       scatter x=lbdy y=lbstresn / markerattrs=( symbol=square size=10px color=black);
       rowaxis display=(nolabel);
       keylegend "Mild" "Moderate" "Severe";
       keylegend "Limits" "Series";
   run;

   title;
   footnote;
%mend;/*--Create Vital Sign Graph--*/

%macro LabsCH;
%let usubjid=%sysfunc(dequote(&usubjid.));

   ods graphics / height=10in width=8in imagename="LabsCH_&usubjid"  noscale;
   ods noresults; 

   proc sgpanel data=lb(where=(usubjid="&usubjid" and lbcat="CHEMISTRY ")) noautolegend cycleattrs;
     panelby lbtestcd / uniscale=column spacing=5 rows=9 layout=rowlattice rowheaderpos=left novarname;
       band x=lbdy lower=lbstnrlo upper=lbstnrhi / transparency=.8  fillattrs=(color=lightgray) name="Limits" LegendLabel="Reference Range"; 
       band x=x lower=mild_lower upper=mild_upper / transparency=.9 fillattrs=(color=lightgreen) name="Mild" legendlabel="Mild";
       band x=x lower=moderate_lower upper=moderate_upper / transparency=.9 fillattrs=(color=yellow) name="Moderate" legendlabel="Moderate";
       band x=x lower=severe_lower upper=severe_upper / transparency=.9 fillattrs=(color=lightred) name="Severe" legendlabel="Severe";
       refline mild_ref / axis=x transparency=.9 lineattrs=(color=lightgreen);
       refline moderate_ref / axis=x transparency=.9 lineattrs=(color=yellow);
       refline severe_ref / axis=x transparency=.9 lineattrs=(color=lightred);
       series x=lbdy y=lbstresn / markers markerattrs=( symbol=squarefilled size=8px) lineattrs=(pattern=solid) name="Series";
       scatter x=lbdy y=lbstresn / markerattrs=( symbol=square size=10px color=black);
       rowaxis display=(nolabel);
       keylegend "Mild" "Moderate" "Severe";
       keylegend "Limits" "Series";
   run;

   title;
   footnote;
%mend;
%macro LabsOther;
%let usubjid=%sysfunc(dequote(&usubjid.));

   ods graphics / height=10in width=8in imagename="LabsCH_&usubjid"  noscale;
   ods noresults; 

   proc sgpanel data=lb(where=(usubjid="&usubjid" and lbcat="OTHER     ")) noautolegend cycleattrs;
     panelby lbtestcd / uniscale=column spacing=5 rows=12 layout=rowlattice rowheaderpos=left novarname;
       band x=lbdy lower=lbstnrlo upper=lbstnrhi / transparency=.8  fillattrs=(color=lightgray) name="Limits" LegendLabel="Reference Range"; 
       band x=x lower=mild_lower upper=mild_upper / transparency=.9 fillattrs=(color=lightgreen) name="Mild" legendlabel="Mild";
       band x=x lower=moderate_lower upper=moderate_upper / transparency=.9 fillattrs=(color=yellow) name="Moderate" legendlabel="Moderate";
       band x=x lower=severe_lower upper=severe_upper / transparency=.9 fillattrs=(color=lightred) name="Severe" legendlabel="Severe";
       refline mild_ref / axis=x transparency=.9 lineattrs=(color=lightgreen);
       refline moderate_ref / axis=x transparency=.9 lineattrs=(color=yellow);
       refline severe_ref / axis=x transparency=.9 lineattrs=(color=lightred);
       series x=lbdy y=lbstresn / markers markerattrs=( symbol=squarefilled size=8px) lineattrs=(pattern=solid) name="Series";
       scatter x=lbdy y=lbstresn / markerattrs=( symbol=square size=10px color=black);
       rowaxis display=(nolabel);
       keylegend "Mild" "Moderate" "Severe";
       keylegend "Limits" "Series";
   run;

   title;
   footnote;
%mend;

%macro Labs;
%let usubjid=%sysfunc(dequote(&usubjid.));

   ods graphics / height=10in width=8in imagename="Labs_&usubjid"  noscale;
   ods noresults; 

   proc sgpanel data=lb(where=(usubjid="&usubjid")) noautolegend cycleattrs;
     panelby lbtestcd / uniscale=column spacing=5 rows=12 layout=rowlattice rowheaderpos=left novarname;
       band x=lbdy lower=lbstnrlo upper=lbstnrhi / transparency=.8  fillattrs=(color=lightgray) name="Limits" LegendLabel="Reference Range"; 
       band x=x lower=mild_lower upper=mild_upper / transparency=.9 fillattrs=(color=lightgreen) name="Mild" legendlabel="Mild";
       band x=x lower=moderate_lower upper=moderate_upper / transparency=.9 fillattrs=(color=yellow) name="Moderate" legendlabel="Moderate";
       band x=x lower=severe_lower upper=severe_upper / transparency=.9 fillattrs=(color=lightred) name="Severe" legendlabel="Severe";
       refline mild_ref / axis=x transparency=.9 lineattrs=(color=lightgreen);
       refline moderate_ref / axis=x transparency=.9 lineattrs=(color=yellow);
       refline severe_ref / axis=x transparency=.9 lineattrs=(color=lightred);
       series x=lbdy y=lbstresn / markers markerattrs=( symbol=squarefilled size=8px) lineattrs=(pattern=solid) name="Series";
       scatter x=lbdy y=lbstresn / markerattrs=( symbol=square size=10px color=black);
       rowaxis display=(nolabel);
       keylegend "Mild" "Moderate" "Severe";
       keylegend "Limits" "Series";
   run;

   title;
   footnote;
%mend;

%macro Medical_Events;
   ods noresults; 

   proc report data=aegraph(where=(usubjid=&usubjid))  nowd
   style (report)=[frame=void rules=none cellspacing=0 width=100pct];
   columns AEDECOD AESTDTC AESTDY AEENDY AESEV AEACN;
   define AESTDTC / format=$10.;
   run;
   quit;

   title; 
   footnote;
%mend;

%macro Medications;
%let usubjid=%sysfunc(dequote(&usubjid.));

   ods graphics / reset  noborder width=8in height=3in imagename="Meddical_Freq_&usubjid"  noscale;
   ods noresults; 

   proc template;
     define statgraph meds;
       begingraph;
	  layout lattice / columns=3 columnweights=(.2 .2 .6) rowdatarange=union;
	    rowaxes;
		  rowaxis / display=(line ticks tickvalues);
		endrowaxes;
		layout overlay / xaxisopts=(label='Start Date' display=(line label));
	      scatterplot x=x y=cmmed  / markercharacter=cmstdate;
		endlayout;
		layout overlay / xaxisopts=(label='End Date' display=(line label));
		  scatterplot x=x y=cmmed / markercharacter=cmendate;
		endlayout;
           layout overlay;
		  barchart x=cmmed y=count / orient=horizontal;
	   endlayout;
 	  endlayout;
       endgraph;
     end;
   run;

   proc sgrender data=cmfreq(where=(usubjid="&usubjid")) template=meds;
   run;

   title;
   footnote;
%mend;

%macro Newfile; 
   %if &path ne '' %then  
       %let pathopt= path=&path(url=none);
   %else 
       %let pathopt=;

   %if &gpath ne '' %then 
       %let gpathopt= gpath=&gpath(url=none);
   %else 
       %let gpathopt=;

   %let destination=%sysfunc(dequote(&destination.));
   %let path=%sysfunc(dequote(&path.));
   %let gpath=%sysfunc(dequote(&gpath.));
   %let file=%sysfunc(dequote(&file.)); 
   %let extension=%sysfunc(dequote(&extension));

%put %str(Style = &styleparm);

   %if &styleparm ne '' %then 
      %let styleopt= style=%sysfunc(dequote(&styleparm.)); 
   %else 
      %let styleopt=; 
 
   %if ( &package_created eq 0  ) %then 
      %let packageopt=package;
   %else 
      %let packageopt=; 

   %if ( %upcase(&destination) eq PDF ) %then %do;
       ods &destination &packageopt file="&path.&file..&extension" notoc startpage=no &styleopt;
   %end;
   %else %if (( %upcase(&destination) eq RTF ) or ( %upcase(&destination) eq TAGSETS.RTF )) %then %do;
       ods &destination &packageopt file="&path.&file..&extension" startpage=no &styleopt;
   %end;
   %else %if ( %upcase(&destination) eq HTML ) %then %do;
       ods &destination &packageopt file="&file..&extension" &pathopt &gpathopt &styleopt;
   %end;

%mend; 

%macro NewPage; 
%let destination=%sysfunc(dequote(&destination.));

   %if ( %upcase(&destination) ne HTML ) %then %do;
       ods &destination startpage=now;
	   ods &destination startpage=no; 
   %end;

%mend; 

%macro Results;
%let onoff=%sysfunc(dequote(&onoff.));

    %if ( %upcase(&onoff) eq ON ) %then
        ods results; 
    %else %if ( %upcase(&onoff) eq OFF ) %then 
        ods noresults;

%mend; 

%macro PackageOpen;
%let packagetemplate=%sysfunc(dequote(&packagetemplate.));

    %if ( &packagetemplate eq  ) %then 
        ods package open nopf; 
    %else 
        ods package open template=&packagetemplate nopf;

%mend; 

%macro PackageClose(clear);
%let clear=%sysfunc(dequote(&clear.));

    %if ( &clear eq  ) %then
        ods package close; 
    %else %if ( %upcase(&clear) eq CLEAR ) %then 
        ods package close clear;

%mend; 

%macro PackagePublish(packagename, packagepath ); 

    %if (( "&packagename" ne "" ) and ( "&packagepath" ne '' )) %then 
        ods package publish archive properties(archive_name="&packagename..zip" archive_path="&packagepath");
    %else %if ( "&packagename" ne "" ) %then
	    ods package publish archive properties(archive_name="&packagename..zip");
    %else  
	    ods package publish;

%mend; 

%macro patient_profile (libref=, destination=pdf, path=, gpath=, filename=Patient_Profile, extension=, where="", subjid="", newfile=PATIENT, style=MMS, select=ALL, packagename=, packagetemplate=);

ods noresults; 
proc fcmp outlib=work.fncs.submit;
  function AE_Timeline(usubjid $, minday, maxday, mindate, maxdate, height $, rfmindate, rfmaxdate);
    rc = run_macro('adverse_events', usubjid, minday, maxday, mindate, maxdate, height, rfmindate, rfmaxdate);
    return(rc);
  endsub;
  function MEDS(usubjid $, minday, maxday, mindate, maxdate, height $, rfmindate, rfmaxdate);
    rc = run_macro('Concomitant_Meds', usubjid, minday, maxday, mindate, maxdate, height, rfmindate, rfmaxdate);
    return(rc);
  endsub;
  function Vitals(usubjid $, rfmindate, rfmaxdate);
    rc = run_macro('Vital_signs', usubjid, rfmindate, rfmaxdate);
    return(rc);
  endsub;
  function LabsUR(usubjid $);
    rc = run_macro('LabsUR', usubjid );
    return(rc);
  endsub;
  function LabsCH(usubjid $);
    rc = run_macro('LabsCH', usubjid );
    return(rc);
  endsub;
  function LabsHE(usubjid $);
    rc = run_macro('LabsHE', usubjid );
    return(rc);
  endsub;
  function LabsOther(usubjid $);
    rc = run_macro('LabsOther', usubjid );
    return(rc);
  endsub;
  function Labs(usubjid $);
    rc = run_macro('Labs', usubjid );
    return(rc);
  endsub;
  function Medical_Events(usubjid $);
    rc = run_macro('Medical_Events', usubjid );
    return(rc);
  endsub;
  function Medications(usubjid $);
    rc = run_macro('Medications', usubjid );
    return(rc);
  endsub;
  function Newfile( destination $, path $, gpath $, file $, extension $, styleparm $, package_created);
    rc = run_macro('Newfile', destination, path, gpath, file, extension, styleparm, package_created );
    return(rc);
  endsub;
  function NewPage( destination $ );
    rc = run_macro('NewPage', destination );
    return(rc);
  endsub;
  function Results(onoff $);
    rc = run_macro('Results', onoff);
    return(rc);
  endsub;
  function PackageOpen(packagetemplate $);
    rc = run_macro('PackageOpen', packagetemplate );
    return(rc);
  endsub;
run;
quit;

/* Set the defaults */
%if ( &libref eq "" ) %then %do;
   %let libref=cdisc;
   %if ( &path ne "" ) %then
       libref &libref. &path;
%end;

%let subjid= %sysfunc(dequote(&subjid.));
%if "&subjid" ne "" %then %do;
   %let usubjid_where=(where=(&subjid));  
%end;
%else 
   %let usubjid_where= ; 

%put %str(USUBJID Where = &usubjid_where);

%let where = %sysfunc(dequote(&where.));
%if "&where" ne "" %then %do;
   %if &subjid ne  %then 
       %let where=(where=( &subjid and &where ));
   %else 
       %let where=(where=( &where ));  
%end; 
%else %if "&usubjid_where" ne "" %then 
   %let where=&usubjid_where;

%put %str(Where = &where);

%let select = %upcase(&select); 
%let newfile = %upcase(&newfile); 

ods listing close; 

%if ( "&extension" eq "" ) and ( &destination ne "" ) %then 
   %let extension =&destination; 

/* Call the macro to process the data */ 
%setup_data ( &libref, &usubjid_where ); 

%put %str(Libname =  &libref);
%put %str(Desination = &destination); 
%put %str(Path = &path);
%put %str(GPath = &gpath);
%put %str(Filename = &filename);
%put %str(Style = &style);
%put %str(Where = &where);
%put %str(Extension = &extension);
%put %str(Select = &select);
%put %str(Package Name = &packagename); 
%put %str(Package Template = &packagetemplate); 

options cmplib=work.fncs;
data _null_;
set &libref..DM&where. end=eof;
length vstestcd $ 6. lbtestcd $ 7. cmgraphht $ 6. aegraphht $ 6.;
retain package_created;
by usubjid;
vsstresn_min=.; vsstresn_max=.; lbstresn_min=.; lbstresn_max=.; aestdy=.; aeendy=.; aeminday=.; aemaxday=.; aemaxdate=.; aemindate=.; severity=.;
cmminday=.; cmmaxday=.; cmmaxdate=.; cmmindate=.; cmgraphht=""; aegraphht="";
if ( _n_ eq 1 ) then do;
    visitdy=.;
	package_created=.;
    length studyid $12.;
dcl odsout obj();
dcl hash vs(dataset: "vs_stats",
            multidata: 'Y');
dcl hiter vs_iter('vs');
    vs.defineKey("usubjid");
    vs.defineData("vstestcd", "vsstresn_min", "vsstresn_max");
    vs.defineDone();
dcl hash cm(dataset: "cmgraph");
    cm.defineKey("usubjid");
    cm.defineData("studyid", "cmminday", "cmmaxday", "cmmindate", "cmmaxdate", "cmgraphht");
    cm.defineDone();
dcl hash ae(dataset: "aegraph",
            multidata: 'Y');
    ae.defineKey("usubjid");
    ae.defineData("studyid", "AESTDY", "AEENDY", "aeminday", "aemaxday", "aemindate", "aemaxdate", "aegraphht", "severity");
    ae.defineDone();
dcl hash lb(dataset: "lb_stats",
            multidata: 'Y');
    lb.defineKey("usubjid");
    lb.defineData("lbtestcd", "lbstresn_min", "lbstresn_max");
    lb.defineDone();

if (( symget('packagename') ne '' ) or ( symget('packagetemplate') ne '' )) then do; 
	   package_created = PackageOpen( symget('packagetemplate') ); 
    end; 

    if ( symget('newfile') eq 'NONE' ) then do; 
       rc = Newfile( symget('destination'), symget('path'), symget('gpath'), symget('filename'), symget('extension'), symget('style'), package_created );
    end; 
end;

if ( first.usubjid ) then do;
   put _n_ " Subject = " usubjid;
   
   if ( _n_ ne 1 ) then do;
      if ( symget('destination') eq 'HTML' ) then
         obj.page();
      else  
	     rc =NewPage(symget('destination'));
   end;

   if ( symget('newfile')  eq 'PATIENT' ) then do;
      rc = Newfile( symget('destination'), symget('path'), symget('gpath'), cats(dequote(symget('filename')), "_", usubjid), symget('extension'), symget('style'),  package_created );
   end; 

   obj.table_start(
                   overrides: "just=left cellspacing=0");
   obj.row_start();
   obj.format_cell(data: "Study",
                   overrides: "font_size=16pt just=left width=1.5in background=verylightgray" );
   obj.format_cell(data: STUDYID,
                   overrides: "font_size=16pt font_weight=bold just=left");
   obj.row_end();
   obj.row_start();
   obj.format_cell(data: "Patient ID",
                   overrides: "font_size=16pt just=left width=1.5in background=verylightgray");
   obj.format_cell(data: SUBJID,
                   overrides: "font_size=16pt font_weight=bold just=left");
   obj.row_end();
   obj.table_end();

   rc = Results("ON"); 

   obj.table_start(name: usubjid,
                   label: "Patient Profile for Patient " || usubjid,
                   overrides: "frame=void rules=none width=100pct cellspacing=0 cellpadding=0");
   obj.row_start();
   obj.format_cell(data: "Patient Information",
                   column_span: 4,
                   overrides: "font_size=16pt background=cx8888ff");
   obj.row_end();
end;

obj.row_start();
obj.format_cell(data: "Age",
                overrides: "font_size=12pt just=left width=2.1in");
obj.format_cell(data: strip(AGE) || " " ||strip(AGEU),
                overrides: "font_size=12pt font_weight=bold just=left");
obj.format_cell(data: "DOB:",
                overrides: "font_size=12pt just=left width=1in");
obj.format_cell(data: BRTHDTC,
                overrides: "font_size=12pt font_weight=bold just=left");
obj.row_end();

obj.row_start();
obj.format_cell(data: "Sex",
                overrides: "font_size=12pt just=left width=2.1in");
obj.format_cell(data: SEX,
                overrides: "font_size=12pt font_weight=bold just=left");
obj.format_cell(data: "Country:",
                overrides: "font_size=12pt just=left width=1in");
obj.format_cell(data: COUNTRY,
                overrides: "font_size=12pt font_weight=bold just=left");
obj.row_end();

obj.row_start();
obj.format_cell(data: "Race:",
                overrides: "font_size=12pt just=left width=2.1in");
obj.format_cell(data: RACE,
                overrides: "font_size=12pt font_weight=bold just=left");
obj.format_cell(data: "Start Date:",
                overrides: "font_size=12pt just=left width=1in");
obj.format_cell(data: RFSTDTC,
                overrides: "font_size=12pt font_weight=bold just=left");
obj.row_end();


obj.row_start();
obj.format_cell(data: cats(vlabel(ARM),":"),
                overrides: "font_size=12pt just=left width=2.1in");
obj.format_cell(data: strip(ARM),
                overrides: "font_size=12pt font_weight=bold just=left");
obj.format_cell(data: "End Date:",
                overrides: "font_size=12pt just=left width=1in");
obj.format_cell(data: RFENDTC,
                overrides: "font_size=12pt font_weight=bold just=left");
obj.row_end();

if ( last.usubjid ) then do;
   obj.table_end();

   rc = Results("OFF");
   
  len = length(strip(RFSTDTC));
  if ( len eq 4 ) then
     rfstdate = input(cats(RFSTDTC,"-01-01"), ANYDTDTE.);
  else if ( len lt 10 ) then
     rfstdate = input(RFSTDTC, ANYDTDTE.);
  else 
     rfstdate = input(RFSTDTC, ANYDTDTE10.);

  len = length(strip(RFENDTC)); 
  if ( len eq 4 ) then
     rfendate = input(cats(RFENDTC, "01-01"), ANYDTDTE.);
  else if ( len lt 10 ) then
     rfendate = input(RFENDTC, ANYDTDTE.);
  else
     rfendate = input(RFENDTC, ANYDTDTE10.);
  
  if (( symget('select') eq "ALL" ) or ( index(symget('select'), "AE") > 0 )) then do;   
     if (( ae.find() eq 0 ) and ( rfstdate ne . ) and ( rfendate ne . )) then do; 
         obj.format_text(data: "" );
         obj.format_text(data: "Adverse Event Patient Timeline",
                         overrides: "font_face='Arial' font_size=16pt just=center width=100pct background=cx8888ff");
put usubjid= aeminday= aemaxday= aemindate= aemaxdate=; 
         rc = AE_Timeline(usubjid, aeminday, aemaxday, aemindate, aemaxdate, aegraphht, rfstdate, rfendate );
      end;
      else do;
         obj.format_text(data: "Adverse Event Patient Timeline",
                         overrides: "font_face='Arial' font_size=16pt just=center width=100pct background=cx8888ff");
         obj.format_text(data: "(*ESC*){newline 1}No Event data available.");
         obj.format_text(data: " ");
      end;
  end; 

  if (( symget('select') eq "ALL" ) or ( index(symget('select'), "CM") > 0 )) then do;   

     if ( cm.find() eq 0 ) and ( rfstdate ne . ) and ( rfendate ne . ) then do;
        obj.format_text(data: "Concomitant Medications",
                        overrides: "font_face='Arial' font_size=16pt just=center width=100pct background=cx8888ff");
        rc = MEDS(usubjid, cmminday, cmmaxday, cmmindate, cmmaxdate, cmgraphht, rfstdate, rfendate);
     end;
     else do;
        obj.format_text(data: "Concomitant Medications",
                        overrides: "font_face='Arial' font_size=16pt just=center width=100pct background=cx8888ff");
        obj.format_text(data: "(*ESC*){newline 1}No Concomitant data available.");
        obj.format_text(data: " ");
     end;
  end; 

  if (( symget('select') eq "ALL" ) or ( index(symget('select'), "VS") > 0 )) then do;   
     if ( vs.find() eq 0 )then do;
	    if ( symget('destination') eq 'HTML' ) then
           obj.page();
        else  
	       rc =NewPage(symget('destination'));

        obj.format_text(data: "Vital Signs",
                        overrides: "font_face='Arial' font_size=16pt just=center width=100pct background=cx8888ff");
        rc = Vitals(usubjid, rfstdate, rfendate);
     end;
     else do;
        obj.format_text(data: "Vital Signs",
                        overrides: "font_face='Arial' font_size=16pt just=center width=100pct background=cx8888ff");
        obj.format_text(data: "(*ESC*){newline 1}No Vital Sign information available.");
        obj.format_text(data: " ");
     end;
  end; 

  if ( index(symget('select'), "LABS") > 0 ) then do;   
     if ( lb.find() eq 0 )then do;
	    if ( symget('destination') eq 'HTML' ) then
           obj.page();
        else  
	       rc =NewPage(symget('destination'));

        obj.format_text(data: "Labs",
                        overrides: "font_face='Arial' font_size=16pt just=center width=100pct background=cx8888ff");
        rc = Labs(usubjid);
     end;
     else do;
        obj.format_text(data: "Labs",
                        overrides: "font_face='Arial' font_size=16pt just=center width=100pct background=cx8888ff");
        obj.format_text(data: "(*ESC*){newline 1}No Lab information available.");
        obj.format_text(data: " ");
     end;
  end; 
  else do; 
     if (( symget('select') eq "ALL" ) or ( index(symget('select'), "LBUR") > 0 )) then do;   
        if ( lb.find() eq 0 )then do;
	       if ( symget('destination') eq 'HTML' ) then
              obj.page();
           else  
	          rc =NewPage(symget('destination'));

           obj.format_text(data: "Urin Aanalysis Labs",
                           overrides: "font_face='Arial' font_size=16pt just=center width=100pct background=cx8888ff");
           rc = LabsUR(usubjid);
        end;
        else do;
           obj.format_text(data: "Urin Analysis Labs",
                            overrides: "font_face='Arial' font_size=16pt just=center width=100pct background=cx8888ff");
           obj.format_text(data: "(*ESC*){newline 1}No Lab information available.");
           obj.format_text(data: " ");
        end;
     end; 

     if (( symget('select') eq "ALL" ) or ( index(symget('select'), "LBCH") > 0 )) then do;   
        if ( lb.find() eq 0 )then do;
	       if ( symget('destination') eq 'HTML' ) then
              obj.page();
           else  
	          rc =NewPage(symget('destination'));

           obj.format_text(data: "Chemistry Labs",
                           overrides: "font_face='Arial' font_size=16pt just=center width=100pct background=cx8888ff");
           rc = LabsCH(usubjid);
        end;
        else do;
           obj.format_text(data: "Chemistry Labs",
                           overrides: "font_face='Arial' font_size=16pt just=center width=100pct background=cx8888ff");
           obj.format_text(data: "(*ESC*){newline 1}No Lab information available.");
           obj.format_text(data: " ");
        end;
     end; 

     if (( symget('select') eq "ALL" ) or ( index(symget('select'), "LBHE") > 0 )) then do;   
        if ( lb.find() eq 0 )then do;
	       if ( symget('destination') eq 'HTML' ) then
              obj.page();
           else  
              rc =NewPage(symget('destination'));

           obj.format_text(data: "Hematology Labs",
                           overrides: "font_face='Arial' font_size=16pt just=center width=100pct background=cx8888ff");
           rc = LabsHE(usubjid);
        end;
        else do;
           obj.format_text(data: "Hematology Labs",
                           overrides: "font_face='Arial' font_size=16pt just=center width=100pct background=cx8888ff");
           obj.format_text(data: "(*ESC*){newline 1}No Lab information available.");
           obj.format_text(data: " ");
        end;
     end; 
  end; 

  if (( symget('select') eq "ALL" ) or ( index(symget('select'), "AET") > 0 )) then do;   
     if ( ae.find() eq 0 ) or ( cm.find() eq 0 ) then do;
        if ( symget('destination') eq 'HTML' ) then
           obj.page();
         else  
	       rc =NewPage(symget('destination'));
     end; 

  	 if ae.find() eq 0 then do;
        obj.format_text(data: "Medical Events",
                        overrides: "font_face='Arial' font_size=16pt just=center width=100pct background=cx8888ff");
        rc = Medical_Events(usubjid);
     end;
     else do;
        obj.format_text(data: "Medical Events",
                        overrides: "font_face='Arial' font_size=16pt just=center width=100pct background=cx8888ff");
        obj.format_text(data: "(*ESC*){newline 1}No Adverse Events data available.");
        obj.format_text(data: " ");
     end;
  end; 

  if (( symget('select') eq "ALL" ) or ( index(symget('select'), "MD") > 0 )) then do;   
     if ( cm.find() eq 0 ) then do;
        obj.format_text(data: "Medications",
                        overrides: "font_face='Arial' font_size=16pt just=center width=100pct background=cx8888ff");
        rc = Medications(usubjid);
     end;
     else do;
        obj.format_text(data: "Medications",
                        overrides: "font_face='Arial' font_size=16pt just=center width=100pct background=cx8888ff");
        obj.format_text(data: "(*ESC*){newline 1}No Medication data available.");
        obj.format_text(data: " ");
     end;
  end; 

end;

if eof eq 1 then do;

   obj.delete();
   lb.delete();
   cm.delete();
   ae.delete();
   vs.delete();
end;
;run;

ods results;
ods _all_ close;

%if (( "&packagename" ne "" ) or ( "&packagetemplate" ne "" )) %then %do; 
   %PackagePublish( &packagename, &path );
   %PackageClose( "CLEAR" ); 
%end;
 
%mend;

