*! Make a categorical variable by cutting at break points
*! Addition to egen in stata 6.0
*! Version 1.2, David Clayton and Michael Hills 8 July 1999

program def _gcut
    version 6.0
    syntax newvarname(gen) =/exp [if] [in] /*
    */ [, AT(string) Group(real 0) ICodes Label ]
    if "`at'"=="" & `group'==0 {
      di in red "needs at or group option"
        exit
    }
    tempvar touse pctile x
    qui gen `x' = `exp'
    marksample touse, novarlist
    markout `touse' `x'
    if "`at'"=="" & `group'!=0 & "`icodes'"==""{
        local icodes  "icodes"
    }
    if "`label'"!="" & "`icodes'"=="" {
        local icodes  "icodes"
    }
    cap label drop `varlist'

    if "`at'"=="" {
        local count = 1
      qui summ `x', meanonly
        local extra = string(r(min))
      local at  "`extra'"
      qui pctile `pctile' = `x' if `touse', nq(`group')
        while `count' < `group' {
          local extra = string(`pctile'[`count'])
        local at  "`at',`extra'"
        local count = `count' + 1
        }
        qui summ `x' if `touse', meanonly
        local extra = string(r(max)+1)
      local at  "`at',`extra'"
    }

    numlist "`at'" , asc
    tokenize "`r(numlist)'"
    local n: word count `r(numlist)'

    local i=0
    while "`1'"!="" {
      local cutp `1'
        if "`icodes'"=="" {
        qui replace `varlist' = `cutp' if `x' >= float(`cutp') & `touse'
      }
        else {
          qui replace `varlist' = `i' if `x'>=float(`cutp') & `touse'
        }
        if `i'>0 & "`label'"!="" & "`icodes'" != "" {
        local code = `i' - 1
        la def `varlist' `code' "`lastcut'-", a
        }
        if `i'>0 & "`label'"!="" & "`icodes'" == "" {
        la def `varlist' `lastcut' "`lastcut'-", a
        }
      local lastcut "`cutp'"
      local i=`i'+1
      mac shift
    }
    if "`label'"!="" {
       la val `varlist' `varlist'
    }

end