*!version 1.0.1 10sep1996
program define rocauc
 version 4.0
 local varlist "req ex max(1)"
 local options "BY(string) pause"
 parse "`*'"
 if "`by'"==""{
     di in red "You must specify the Grouping Variable"
     exit 198
 }
 confirm var `by'
 preserve
 tempvar i S X Y
 quietly{
   keep `varlist' `by'
   keep if `varlist'~=. & `by'~=.
   sort `by'
   if `by'[_N]~=2{
        recode `by' 0=2
        sort `by'
   }
   if `by'[_N]~=2{
        noisily di in red "2 Groups required coded as 1,2 or 0,1"
        exit 198
           }
   sort `varlist'
   gen `X'=`varlist' if `by'==1
   gen `Y'=`varlist' if `by'==2
   gen `S'=.
   local i=1
   while `i'<_N+1{
     tempvar score
        scalar k=`Y'[`i']
        if k~=.{
          gen `score'=0 if `X'<k
          replace `score'=0.5 if `X'==k
          replace `score'=1 if `X'>k
          replace `score'=. if `X'==.
          replace `score'=sum(`score')
          scalar score=`score'[_N]
          replace `S'=scalar(score) if _n==`i'
          drop `score'
      }
     local i=`i'+1
   }
   tempvar sumS numpos numneg
   gen `sumS'=sum(`S')
   gen `numpos'=1 if `by'==1
   replace `numpos'=sum(`numpos')
   gen `numneg'=1 if `by'==2
   replace `numneg'=sum(`numneg')
   noi di _newline in gr "Grouping variable: "  in yellow "`by'"
   #delimit ;
   noisily di in gr "Positives " in ye `numpos'[_N] in gr
     "  negatives " in ye `numneg'[_N];
   #delimit cr
   tempname AUC
   scalar `AUC'=(1/(`numneg'[_N]*`numpos'[_N]))*`sumS'[_N]
   local shauc: display %9.2f `AUC'
   local shauc = trim("`shauc'")
   noisily di in gr "The AUC of the empirical ROC curve " _continue
   noi di in green "for" " ${Sroc_v$counter}" " =" in ye `shauc'
   global Sroc$counter = `AUC'
   drop `sumS' `numpos' `numneg' `S' `X' `Y'
   }
end