*! VERSION 1.0.0 4/24/92, for STATA version 3.0
*! Slightly cleaned up version, 10/8/98
*! Warning! Does not incorporate full data protection features!
/* Written by:
   D.H. Judson
   Nevada State Demographer's Office/024
   University of Nevada, Reno
   Reno, NV 89507
   Phone: 702-784-6352
   Fax: 702-784-6353
   E-mail: djudson@unr.edu
   Program code enhancements and suggestions are welcome at the above address.
   This program calls ado files:
      None.
*/
prog def medoid
version 3.0
local options "GRoup(string) Dist(real 2) *"
local varlist "req ex"
local in "opt"
local if "opt"
local weight "opt fweight aweight noprefix"
parse "`*'"
parse "`varlist'", parse(" ")

if "`group'"=="" {
      di in bl "You must specify a grouping variable"
      exit 198
}

noi di "NOTE: Using Minkowski distance measure (p=`dist'),"
noi di "      calculated around medoids (multivariate medians)."

qui cap drop DIST*

qui tab `group'
mac def k=_result(2)
local it=1
local it2=1

while `it'<=$k {
      local it2=1
      mac def test=1    
      while $test~=0 {
        	qui summ `$_it2' if `group'==`it', detail
        	local MED`it'`it2'=_result(10)
        	local it2=`it2'+1
        	qui count if "`$_it2'"~=""      
        	mac def test=_result(1)
	}
	local it=`it'+1
}

local it=1
local it2=1
while `it'<=$k {
      qui gen DIST`it'=0
      local it2=1
      mac def test=1
      while $test~=0 {
            qui replace DIST`it'=DIST`it'+abs((`$_it2'-`MED`it'`it2''))^`dist'
            local it2=`it2'+1
            qui count if "`$_it2'"~=""
            mac def test=_result(1)
      }
	qui replace DIST`it'=(DIST`it')^(1/`dist')
	lab var DIST`it' "DISTANCE FROM MEDOID `it'"
	local it=`it'+1
}
end