*! version 1.0.0 16mar2000 updated 26mar2002
program define aucdist, rclass
version 6.0

	syntax varlist(numeric min=3 max=3) [if] [in] /*
		*/ [, Trapezoid fit(string) Generate(string) stat(string) /*
                */ nodots GRaph * ]

	qui {

	tokenize `varlist'
	tempvar id conc time
	gen double `id' = `1'
	gen double `time' = `2'
	gen double `conc' = `3'
	compress `id' `time' `conc'

	sort `id' `time'
	marksample touse


	if ("`stat'" != "") & (("`stat'" != "tmax") & ("`stat'" != "inf") & ("`stat'" != "cmax" )) {
		noi di in red "stat() must be either: tmax, inf or cmax -- auc is the default"
		exit 198
	}

	if "`generate'" != "" {
		capture confirm new v `generate'
		if _rc {
			noi di in red "variable `generate' already exists"
			exit 198
		}
	}

	if "`stat'" == "" {
		local stat = "auc"
	}

	tempname nid
	egen `nid' = group(`id') if `touse'

	su `nid',meanonly
	tempname max
	tempvar measure
	sort `nid' `time'
	gen `measure' = .
	scalar `max' = r(max)
	local index = 1
	while `index' < `max' + 1 {

		if "`nodots'" == "" {
			noi di in ye "." _c
		}

		auccalc `time' `conc' if `nid' == `index' & `touse', `trapezoid' fit(`fit')

		if "`stat'" == "auc" {
			replace `measure' = r(auc) if `id' == `index' & `time' == r(tmax)
		}
		else if "`stat'" == "inf" {
			replace `measure' = r(ln_auc) if `id' == `index' & `time' == r(tmax)
		}
		else if "`stat'" == "cmax" {
			replace `measure' = r(cmax) if `id' == `index' & `time' == r(tmax)
		}
		else if "`stat'" == "tmax" {
			replace `measure' = r(tomc) if `id' == `index' & `time' == r(tmax)
		}

		local index = `index' + 1
	}


	su `measure', detail

	} /* end qui loop */

	di in gr _n
	di in gr _col(5) "              Summary statistics for the distribution of " in ye "`stat'"
	di in gr _col(10) _dup(67) "-"
	di in gr _col(5) "        N  |    Mean   |   Median   | Variance |  Skewness  |  Kurtosis  "
	di in gr _col(5) "     ------+-----------+------------+----------+------------+-----------"
	di in ye _col(5) %9.0f r(N) in gr "  |" in ye %9.2f r(mean) in gr "  |" in ye %9.2f r(p50) in gr "   |" in ye %9.2f r(Var) in gr " |" in ye %9.2f r(skewness) in gr "   |" in ye %9.2f r(kurtosis)
	di in gr _col(10) _dup(67) "-"
	qui sktest `measure'
	di in gr _col(10) "Pr(Dist. is Normal) : " in ye %9.2f `r(P_chi2)'

	sort `id' `time'

	local clab: variable label `conc'
	if "`clab'" == "" {
		if "`stat'" == "auc" {
			local clab = "Area Under Curve (AUC)"
		}
		else if "`stat'" == "inf" {
			local clab = "Log Concentration AUC"
		}
		else if "`stat'" == "cmax" {
			local clab = "C max"
		}
		else if "`stat'" == "tmax" {
			local clab = "T max"
		}
	}
	label var `measure' "`clab'"

	if "`graph'" != "" {
		graph `measure', `options'
	}

	if "`generate'" != "" {
		nobreak {
			gen `generate' = `measure'
		}
	}

end