*! mklist v1.0.2 JNighohossian 25jul2013
* This will take a list of values and concatenate them
* v1.0.1 26jul2013 - added noquote option for strings
* v1.0.2 26jul2013 - altered it to only pick up distinct values

program mklist, sortpreserve
version 12.1
	syntax varname [if] [in][ , Delimiter(string) NOQuote]

	tempvar touse index
	tempname output i quote

	mark `touse' `if' `in'
	preserve
	keep if `touse'
	gen `index'=_n
	bysort `varlist': keep if _n==1
	sort `index'

qui {
	if "`delimiter'"=="" {
		local delimiter=","
	}

	local `output' "0"
	local `quote' `"""'

	local `i'=1
	gsort -`touse'
	if substr("`:type `varlist''",1,3)=="str" {
		if "`noquote'"!="noquote" {
			local delimiter "`=char(34)'`delimiter'`=char(34)'"
		}
		while `touse'[``i'']==1 {
			local `output'=`"``output''"'+`"`delimiter'"'+`varlist'[``i'']
			local `i'=``i''+1
		}
		if "`noquote'"=="noquote" {
			n display as text substr(`"``output''"',3,.)
		}
		else {
			n display as text substr(`"``output''"',4,.) `"`=char(34)'"'
		}
	}
	else {
		while `touse'[``i'']==1 {
			local `output'="``output''"+"`delimiter'"+string(`varlist'[``i''])
			local `i'=``i''+1
		}
		n display as text substr("``output''",3,.)
	}

}

restore

end