program define labsort
*! RAO 1.0.0 1 August 2001

   version 6

   syntax varlist(min=2 max=2) [, Stat(string) Gen(string) Label(string) ]

   tokenize `varlist'
   local grp  "`1'"
   local y    "`2'"

   if "`stat'"=="" { local stat mean }
   if "`gen'"=="" { local gen _newvar }
   if "`label'"=="" { local label _newlbl }

   confirm new variable `gen'

   local vallbl : value label `grp'
   if "`vallbl'"=="" {
      di in r "`grp' has no value label"
      exit
   }
   capture label list `vallbl'
   if _rc {
      di in r "`vallbl' not a value label"
      exit
   }

   tempvar ystat rnk
   egen `ystat' = `stat'(`y') , by(`grp')
   sort `ystat' `grp'
   * In case there are ties in `ystat',
   egen `rnk' = group(`ystat' `grp')

   * Find the new order
   preserve
   collapse (mean) `rnk' , by(`grp')
   sort `grp'
   local i 0
   local to ""
   while `i'<_N {
      local i = `i'+1
      local j = `rnk'[`i']
      local to `"`to' `j'"'
   }
   local nlab = _N
   restore

   local i 0
   while `i' < `nlab' {
      local i = `i' + 1
      local lab : label `vallbl' `i'
      local t : word `i' of `to'
      local args `"`args' `t' `"`lab'"'"'
   }
   label def `label' `args'
   gen `gen' = `rnk'
   lab val `gen' `label'
   local varlab : variable label `grp'
   lab var `gen' "`varlab'"

   noi di _n in gr "New variable " in ye "`gen' = `grp'" in gr " sorted by " in ye "`stat'(`y')" in gr " created with value labels " in ye "`label'"
   di _n `"label def `label' `args' "'

end