*! version 1.0.1 October 22, 1999 @ 08:10:04
*! gathers sample statistics about file into another file
program define sampstat
version 5.0
	/* 1.0.1 - put quotes around tempfile name for folks with spaces in */
	/*         default path names. Arrrrgh */
	/*         put in the forgotten replace option */
	quietly describe
	if _result(7) {
		display in red "data in memory would be lost"
		exit 4
		}
	local varlist "req ex"
	local if "opt pre"
	local in "opt pre"
	local options "MEan STDdev saving(str) seed(int 0) SAMples(int 100) SIZE(int 0) REPLACE"
	parse "`*'"

	if "`mean'`stddev'"=="" {
		display in red "at least one summary statistic is needed..."
		exit 198
		}

	if "`saving'"!="" {
		if "`replace'"=="" {
			/* not really good for the file name, but beats using some of */
			/* the new utilities.... */
			confirm new file "`saving'.dta"
			}
		}

	if `size'<=0 {
		display in red "The sample size must be larger than 0!"
		exit 198
		}

	tempvar ifin
	mark `ifin' `if' `in'
	quietly count if `ifin'
	local selsize = _result(1)

	if `size'>=`selsize' {
		display in red "The sample size must be less than the number of selected"
		display in red "  observations: " in yellow "`selsize'" in red "!"
		exit 198
		}

	parse "`varlist'", parse(" ")
	local cnt 1
	while "``cnt''"!="" {
		/* will have trouble if the first 7 letters of two variables */
		/*  are the same */
		local stub = substr("``cnt''",1,7)
		if "`mean'"!="" {
			local pvar "`pvar' m`stub'"
			}
		if "`stddev'"!="" {
			local pvar "`pvar' s`stub'"
			}
		local cnt = `cnt' + 1
		}

	tempname pname
	tempfile pfile
	postfile `pname' `pvar' using "`pfile'", double

	if `seed' {
		set seed `seed'
		}

	tempvar keeper sorter
	local scnt 1
	while `scnt' <= `samples' {
		capture drop `keeper'
		capture drop `sorter'
		quietly gen double `sorter' = uniform() if `ifin'
		sort `sorter'							 /* missing to the end */
		local post

		/* tokens are the varlist right now... */
		local cnt 1
		while "``cnt''"!="" {
			quietly sum ``cnt'' in 1 / `size'
			if "`mean'"!="" {
				local res = _result(3)
				local post "`post' `res'"
				}
			if "`stddev'"!="" {
				local res = sqrt(_result(4))
				local post "`post' `res'"
				}
			local cnt = `cnt' + 1
			}
		post `pname' `post'
		local scnt = `scnt' + 1
		}
	postclose `pname'

	use "`pfile'"
	/* tokens still have the variable names */
	local cnt 1
	while "``cnt''"!="" {
		local stub = substr("``cnt''",1,7)
		if "`mean'"!="" {
			label var m`stub' "Sample Means of ``cnt''"
			}
		if "`stddev'"!="" {
			label var s`stub' "Sample Standard Deviations of ``cnt''"
			}
		local cnt = `cnt' + 1
		}
	if "`saving'"!="" {
		save `"`saving'"', `replace'
		}
	else {
		global S_FN
		}

end