*! version 1.0.4 08sep1996
program define rocplot
  version 4.0
  local varlist "req ex max(1)"
  local options "BY(string) File(string) pause *"
  parse "`*'"
  if "`by'"==""{
    di in red "You must specify the Grouping variable"
    exit 198
  }
  confirm var `by'
  if "`pause'"=="pause"{
    more
    }
    preserve
    tempvar cutoff index i
    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
      }
      gen `cutoff'=`varlist'
      gen Spec=.
      gen Sens=.
      sort `varlist'
      local i=1
      while `i'<_N{
        tempvar k
        egen `k'=min(`cutoff')
        if `k'~=.{
          tempvar Pred trupos truneg tiepos tieneg numpos numneg
          gen `Pred'=1 if `varlist'>`k'
          replace `Pred'=2 if `varlist'<`k'
          replace `Pred'=1.5 if `varlist'==`k'
          gen `trupos'=1 if `Pred'==1 & `by'==1
          gen `truneg'=1 if `Pred'==2 & `by'==2
          gen `tiepos'=1 if `Pred'==1.5 & `by'==1
          gen `tieneg'=1 if `Pred'==1.5 & `by'==2
          replace `trupos'=sum(`trupos')
          replace `truneg'=sum(`truneg')
          replace `tiepos'=sum(`tiepos')
          replace `tieneg'=sum(`tieneg')
          gen `numpos'=1 if `by'==1
          replace `numpos'=sum(`numpos')
          gen `numneg'=1 if `by'==2
          replace `numneg'=sum(`numneg')
          #delimit ;
          replace Spec=
          (`truneg'[_N]+0.5*`tieneg'[_N])/`numneg'[_N] if _n==`i';
          replace Sens=
          (`trupos'[_N]+0.5*`tiepos'[_N])/`numpos'[_N] if _n==`i';
          drop `Pred' `trupos' `truneg' `tiepos' `tieneg'
          `numpos' `numneg';
          #delimit cr
        }
        else{
          local i=_N
        }
        replace `cutoff'=. if `cutoff'<=`k'
        drop `k'
        local i=`i'+1
      }
      local expand = _N + 2
      set obs `expand'
      gen neutral = .
      replace neutral = 1 if _n == _N-1
      replace Spec = 0 if _n == _N-1
      replace neutral = 0 if _n == _N
      replace Spec = 1 if _n == _N


      gen hor=1-Spec
      local xtrim : display  %9.2f ${Sroc$counter}
      local xtrim = trim("`xtrim'")

      #delimit ;
      graph Sens neutral hor,c(ll) sort
      t2("Empirical ROC plot for `varlist':  AUC= `xtrim' (Group variable: `by')")
      symbol(oi)
      xlabel(0,0.25,0.5,0.75,1) ylabel(0,.25,0.5,0.75,1.00)
      xline(.25,.50,.75,1) yline(.25,.50,.75,1) b2(1-Specificity)
      l1(Sensitivity);
      #delimit cr
      keep Spec Sens
      rename Spec spec
      rename Sens `varlist' /* sens${counter} */
      if "`file'" ~="nosave"{
        save `file'$counter,replace

      }
    }
end