program def sbplot
*! 1.0.0 NJC 8 February 1999
    version 6.0
    #delimit ;
    syntax varlist(min=2 numeric) [if] [in] , [ Width(str) Base(str)
    BY(str) JOIN Symbol(str) Connect(str) * ] ;
    #delimit cr
    tokenize `varlist'
    local nvars : word count `varlist'
    local x ``nvars''        /* x is last-named */
    local `nvars'            /* blank it out */
    local yb `1'             /* bar variable is first-named */
    mac shift                /* line variables are others */

    tempvar touse Width Base id
    mark `touse' `if' `in'
    markout `touse' `x'

    if "`connect'" != "" {
        local bad = index("`connect'","m") + index("`connect'","s")
        local bad = `bad' + index(substr("`connect'",2,.),"L")
        if `bad' {
            di in r "invalid connect() option"
            exit 198
        }
    }
    else {
        local connect : di _dup(`nvars') "."
        local connect "L`connect'"
    }

    if "`symbol'" == "" {
        local symbol = substr("OpSTdOpSTdOpSTdOpSTd",1,`nvars')
        local symbol "i`symbol'"
    }

    if "`width'" != "" {
        capture confirm variable `width'
        if _rc { confirm number `width' }
    }
    else local width 1
    gen `Width' = `width'

    local basevar 0
    if "`base'" != "" {
        capture confirm variable `base'
        if _rc { confirm number `base' }
        else local basevar 1
    }
    else local base 0
    gen `Base' = `base'

    preserve

    qui {
        keep if `touse'
        keep `by' `varlist' `Width' `Base'
        sort `by' `varlist' `Width' `Base'
        by `by' `varlist' `Width' `Base' : keep if _n == 1
        expand 7
        if `basevar' {
            tempvar minx
            egen `minx' = min(`x'), by(`Base')
            replace `minx' = - `minx'
        }
        if "`join'" != "" { sort `by' `minx' `Base' `x' `yb'}
        else gsort `by' `minx' `Base' - `x' `yb'
        gen byte `id' = mod(_n,7)
        replace `yb' = `Base' if (`id' == 1 | `id' >= 4) & `yb' < .
        replace `yb' = . if `id' == 0
        replace `x' = `x' - 0.5 * `Width' /*
         */ if `id' == 1 | `id' == 2 | `id' == 5
        replace `x' = `x' + 0.5 * `Width' /*
         */ if `id' == 3 | `id' == 4 | `id' == 6
        while "`1'" != "" {
            replace `1' = . if `id' != 0
            mac shift
        }
    }

    if "`by'" != "" { local byby "by(`by')" }
    gra `varlist', sy(`symbol') c(`connect') `byby' `options'
end