*! mencode v2.0.1 Jeremy Nighohossian 2014jun12
*! This command provides a sometimes useful application of encode
*!   where the values and labels are contained in the dataset already

*! v1.0.1 - altered file so that commas in labels would not crash command
*! v1.0.2 - force option used for variables that have labels assigned instead
*!          of when the label name already exists
*! v2.0.0 - exactly the same to user, but uses the observations directly instead
*!			of using levelsof and tokenize
*! v2.0.1 - added an error catch in case labels and values aren't 1:1

program mencode, sortpreserve
syntax varname, labels(varname) [labelname(string) force drop]

*Error Checking

*Check for presence of labelname
	if "`labelname'"=="" local labelname `varlist'
//	label values `varlist'
	capture label define `labelname' 1 "test"
	if _rc==110 & "`force'"!="force" {
		display as error "Label `labelname' already defined. Choose different", ///
		"name or drop existing label."
		exit
	}
	label drop `labelname'

*Define Temporaries
tempvar vallabel index //touse
tempname labelsmac positions

//mark `touse' `if' `in'

preserve
qui {
	keep `varlist' `labels'
	g `index'=_n
	duplicates drop `varlist' `labels', force
	capture isid `varlist'
	local unique1=_rc==0
	capture isid `labels'
	local unique2=_rc==0
	if `unique1'*`unique2'==0 {
		display as error "Value labels and values do not match 1 to 1"
		exit
	}
	sort `varlist'
	mkmat `index', matrix(`positions')
	local cnt=rowsof(`positions')
	restore
	forv i=1/`cnt' {
		local cell=`positions'[`i',1]
		local temp=string(`varlist'[`cell'])+`" ""'+`labels'[`cell']+`"""'
		local cmd="label define `labelname' "+`"`temp'"'+", add"
		display `"`cmd'"'
		`cmd'
	}
	label values `varlist' `labelname'
	if "`drop'"=="drop" {
		drop `labels'
	}
}

end