*! version 1.0 - Aug2013
*! Marcelo Coca Perraillon

program stdif, eclass
   version 12
   syntax [varlist] [if] [in], BY(varname) [CATegorical UNEqual]

   marksample touse

	tempvar group
	sort `touse' `by'
	quietly {
	   by `touse' `by': gen `group'=1 if _n==1 & `touse'
	   replace `group'=sum(`group') if `touse'
		local gval = `by'[_n==1]
   }

   if `group'[_N]!=2 {
	   di as error "`by' must take on two values"
	   exit 198
   }

   if "`unequal'"=="unequal" & "`categorical'"=="categorical" {
      di as error "Option unequal not valid with categorical variables"
		exit 198
   }


	di as text "{hline 68}"
   di as text "Variable " _column(17) "Group2" _column(29) "Group1"  _column(40) "Diff." ///
	      _column(48) "p-value" _column(59) "Std. Diff."
   di as text "{hline 68}"


	if "`categorical'"==""{
      foreach i of local varlist {
	      qui summ `i' if `group'==2 & `touse'
	      local mean2 =r(mean)
	      local var2 = r(Var)
  	      qui summ `i' if `group'==1 & `touse'
	      local mean1 =r(mean)
	      local var1 = r(Var)

	      local dif =   (`mean2'-`mean1')
			local var = sqrt((`var1'+`var2')/2)
         local stdif = (`mean2'-`mean1')/`var'

			if "`unequal'"=="" {
            qui ttest `i' if `touse', by(`group')
   		   local pval = r(p)
			}
			else {
			   qui ttest `i' if `touse', by(`group') `unequal'
   		   local pval = r(p)
			}

		  	ereturn local stdif `stdif'
			ereturn local dif `dif'
			ereturn local p `pval'
			ereturn local var `var'

	      di as text "`i'" as result _column(14) %9.0g `mean2' _column(26) %9.0g `mean1' ///
	          _column(37) %9.0g `dif' _column(45) %9.0g `pval' _column(59) %9.0g `stdif'
         }
		    di as text "{hline 68}"
	      di "Group1: `by'=" "`gval'"
	  }
	  else {
	     foreach i of local varlist {

  	        qui summ `i' if `group'==2 & `touse'
	        local p2 =r(mean)
  	        qui summ `i' if `group'==1 & `touse'
	        local p1 =r(mean)

	        local dif =  (`p2'-`p1')
			  local var = sqrt((`p2'*(1-`p2')+`p1'*(1-`p1'))/2)
           local stdif = `dif'/`var'

           qui tab `i' `group' if `touse', chi2
   		  local pval = r(p)

	        ereturn local stdif `stdif'
  			  ereturn local dif `dif'
			  ereturn local p `pval'
   		  ereturn local var `var'

    	     di as text "`i'" as result _column(14) %9.0g `p2' _column(26) %9.0g `p1' ///
	           _column(37) %9.0g `dif' _column(45) %9.0g `pval' _column(59) %9.0g `stdif'
	     }
		  di as text "{hline 68}"
	     di "Group1: `by'=" "`gval'"
	  }
end