*! hist3 Version 1.0b UK 15 June 2000
program define hist3
version 6.0
syntax varname [if][in][, Values(numlist) XLAbel(string) L1title(string) *]
preserve

* if/in
if "`if'" ~= "" | "`in'" ~= "" {
	keep `if' `in'
}

* Declarations
tempvar XVAR YVAR N H NULL

* Calculations
quietly {
	* Keeping some results
	sum `varlist'
	local min = r(min)
	local max = r(max)
	local n = r(N)

	* Grouping the variable, we want do display
	* No Values supplied
	if "`values'" == "" {
		local ng = min(sqrt(`n'), 10*log10(`n'))
		gen `XVAR' = autocode(`varlist', `ng', `min', `max')
		local values "`min', `max'"
	}
	* Values supplied
	else {
		* Check minimum supplied > min of the data
		local minsupp: word 1 of `values'
		if `minsupp' == `min' {
			di in red "Lowest Value should be ~= min of `varlist'"
			exit
		}

		* Check if maximum supplied < max of the data
		local vlength: word count `values'
		local maxsupp: word `vlength' of `values'
		if `maxsupp' < `max' {
			local values "`values' `max'"
			di in blue "Note: Upper bound set to max of `varlist'"
		}

		* Buidling comma-separated value-list
		tokenize `values'
		local val "`1'"
		mac shift
		while "`1'" ~= "" {
			local val "`val',`1'"
			mac shift
		}

		* Group Variables
		gen `XVAR' = recode(`varlist',`val')
	}

	* Absolut frequencies of the groups
	sort `XVAR'
	by `XVAR': gen `N' = sum(`XVAR' ~= .)
	by `XVAR': drop if _n ~=_N | `XVAR'==.

	* Storing upper bound
	local max = `XVAR'[_N]

	* Calculating the width of the Intervalls
	gen `H' = `XVAR'[_n] - `XVAR'[_n-1]
	replace `H' = `XVAR'[1] - `min' in 1

	* Building some Observations, we need for proper display
	count
	local obs = r(N)+3
	set obs `obs'
	replace `XVAR' = `min' if _n > `obs'-3
	replace `XVAR' = `max' in `obs'
      local label: variable label `varlist'
	if "`label'" == "" {local label "`varlist'"}
      label variable `XVAR' "`label'"

	* Calculating the density
	sort `XVAR' `N'
	gen `YVAR' = `N'/(`H'*`n')
	replace `YVAR' = 0 in 1

	* With connect(J) we need the lags
	replace `YVAR' = `YVAR'[_n+1] if _n > 1

	* With connect(J) we must build the last lines by hand
	replace `YVAR' = `YVAR'[_n-1] if _n == `obs'-1
	replace `YVAR' = 0 in `obs'

	* We like to have Bars
	gen `NULL' = 0
}

* Graph-Defaults
if "`xlabel'" == "" {local xlabel "`min',`values'"}
if "`l1title'" == "" {local l1title "Density"}

graph `YVAR' `YVAR' `NULL' `NULL' `XVAR', c(J||l) s(iiii) xlabel(`xlabel') pen(2222) /*
*/ l1title(`l1title') `options'

end
exit