*! 1.1.2 NJC 4 September1998
* 1.1.1 NJC 31 August 1998
* 1.1.0 NJC 16 July 1998
* 1.0.0 NJC 30 March 1998
program define genfreq
    version 5.0
    local varlist "req ex max(1)"
    local if "opt"
    local in "opt"
    local weight "aweight fweight iweight"
    local options "Width(real 0) Fgenerate(str) Bgenerate(str) BY(str)"
    local options "`options' Ulinc"
    parse "`*'"

    if "`fgenera'" == "" {
        di in r "fgenerate( ) option required"
        exit 198
    }
    else { confirm new variable `fgenera' }

    if "`bgenera'" == "" {
        if `width' > 0 {
            di in r "bgenerate( ) option required"
            exit 198
        }
    }
    else { confirm new variable `bgenera' }

    if "`by'" != "" {
        unabbrev `by'
        local by $S_1
    }

    tempvar data touse wt tag

    mark `touse' `if' `in'
    markout `touse' `varlist'

    qui {
        if `width' > 0 {
            if "`ulinc'" == "" {
                gen `data' = 0.5 * `width' /*
                 */ + round(`varlist'- 0.5 * `width',`width') if `touse'
            }
            else {
                gen `data' =  /*
                 */ round(`varlist',`width') - 0.5 * `width' if `touse'
            }
            local binw ", width `width'"
        }
        else gen `data' = `varlist' if `touse'

        if "`exp'" == "" { local exp "= 1" }
        gen `wt' `exp'
        sort `touse' `by' `data'
        by `touse' `by' `data' : gen `fgenera' = sum(`wt') if `touse'
        by `touse' `by' `data' : replace `fgenera' = `fgenera'[_N]
        by `touse' `by' `data' : gen byte `tag' = _n == 1 & `touse'
        label var `fgenera' "`varlist' freq`binw'"
        su `fgenera' if `tag', meanonly
        global S_1 = _result(18)

        if "`bgenera'" != "" {
            gen `bgenera' = `data'
            if `width' > 0 {
                label var `bgenera' "`varlist' bins`binw'"
            }
            else {
                label var `bgenera' "`varlist'"
            }
        }
    }
end