*! VERSION 1.1.0 6/6/92, for STATA version 3.0
*! Slightly cleaned up version 9/8/98.
*! WARNING!  This program is in testing only, and does not incorporate full
*! data protection features
/* Written by:
     D.H. Judson
     Nevada State Demographer's Office/024
     University of Nevada, Reno
     Reno, NV 89557-0100
     (702) 784-6352
     (702) 784-6353 Fax
     internet: djudson@unr.edu
   Program code enhancements and suggestions are welcome at the above address.
   This program calls ado files:
      None.
*/
cap prog drop centroid
prog def centroid
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 red "ERROR: You must specify a grouping variable"
      exit 198
}

noi di "NOTE: Using Minkowski distance measure (p=`dist')."
qui cap drop DIST*
qui tab `group'
mac def k=_result(2)
local it=1
local it2=1
while `it'<=$k {
     local it2=1
     local test=1
     while `test'~=0 {
               qui summ `$_it2' if `group'==`it'
          local CENT`it'`it2'=_result(3)
          local it2=`it2'+1
          qui count if "`$_it2'"~=""
          local test=_result(1)
     }
local it=`it'+1
}
local it=1
local it2=1
while `it'<=$k {
     qui gen DIST`it'=0
     local it2=1
     local test=1
     while `test'~=0 {
          qui replace DIST`it'=DIST`it'+abs((`$_it2'-`CENT`it'`it2''))^`dist'
          local it2=`it2'+1
          qui count if "`$_it2'"~=""
          local test=_result(1)
     }
     qui replace DIST`it'=(DIST`it')^(1/`dist')
     lab var DIST`it' "DISTANCE FROM CENTROID `it'"
     local it=`it'+1
}
end