*! isknown v1.0 27jul2014
*! by Sergiy Radyakin

program define isknown

		  version 9.0

		  syntax varlist(min=2 max=2), generate(string) [label(string asis)]
		  // For example: isknown referencevar probevar, generate(resultvar)

		  confirm new variable `generate'

		  local refvar : word 1 of `varlist'
		  local probevar : word 2 of `varlist'

		  capture confirm numeric variable `refvar'
		  if _rc {
			// refvar is string
			capture confirm string variable `probevar'
			if _rc {
			  display in red "Variables must be of the same type, but {result:`refvar'} is a string variable and {result:`probevar'} is numeric."
			  local err=1
			}
		  }
		  else {
			capture confirm numeric variable `probevar'
			if _rc {
			  display in red "Variables must be of the same type, but {result:`refvar'} is a numeric variable and {result:`probevar'} is a string."
			  local err=1
			}
		  }

		  if !missing(`"`err'"') {
			display "{text}    To convert from numeric to string values:"
			display "{result}        generate s=string(x)"
			display "{text}    To convert from string to numeric values:"
			display "{result}        generate x=real(s)"
			display "{text}    or: {result}destring s, generate(x)"
			display "{text}    See reference for {help string:string}, {help real:real}, and {help destring:destring}"
			display ""
			error 106
		  }

		  preserve
			  keep `refvar'
			  sort `refvar'
			  by `refvar': keep if _n==1

			  rename `refvar' `probevar'
			  tempfile known
			  save `known'
		  restore

		  tempvar srtvar
		  generate long `srtvar'=_n

		  sort `probevar'

		  quietly {

		      // New syntax of merge is not used to maintain
			  // compatibility with Stata v9.0
			  merge `probevar' using `known', nokeep ///
			    uniqusing _merge(`generate')
			  recode `generate' (1=0) (3=1)

		  }

		  if !missing(`"`label'"') {
		    local lname `:word 1 of `label''
			local n `:word count `label''
			if (`n'==1) {
				label define `lname'    ///
				           0 "unknown"  ///
						   1 "known"
			}
			else {
				label define `lname'     ///
				           0 `"`:word 2 of `label''"' ///
				           1 `"`:word 3 of `label''"'
			}
			label values `generate' `lname'
		  }

		  sort `srtvar'
end
//end of file