*! 1.2.0 NJC 27 April 1999
* 1.1.2 NJC 4 September 1998
program define genfreq
    version 6.0
    syntax varname [if] [in] [aweight fweight iweight] /*
    */ , Fgenerate(str) [ Width(real 0) Bgenerate(str) BY(varlist) Ulinc ]

    confirm new variable `fgenera'

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

    tempvar data wt tag
    marksample touse

    qui {
        if `width' > 0 {
            if "`ulinc'" == "" {
                gen double `data' = 0.5 * `width' /*
                 */ + round(`varlist'- 0.5 * `width',`width') if `touse'
            }
            else {
                gen double `data' =  /*
                 */ round(`varlist',`width') - 0.5 * `width' if `touse'
            }
            local binw ", width `width'"
        }
        else gen double `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 = r(sum)

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