program define loopplot
*! version 1.0.0 NJC 5 November 1997
    version 4.0
    local varlist "req ex min(2)"
    local if "opt"
    local in "opt"
    local options "BY(str) SOrt *"   /* sort will be ignored */
    local weight "fweight aweight iweight"
    parse "`*'"
    parse "`varlist'", parse(" ")
    local nvars : word count `varlist'
    tempvar touse order first last miss
    mark `touse' `if' `in'
    markout `touse' ``nvars''
    gen long `order' = _n
    gen byte `first' = 0
    gen byte `last' = 0
    gen byte `miss' = 0

    nobreak {
        local i = 1
        qui while `i' < `nvars' {
            replace `miss' = ``i'' == .
            sort `touse' `last' `miss' `by' `order'
            #delimit ;
            by `touse' `last' `miss' `by' :
             replace `first' =
              _n == 1 & `last' == 0 & `miss' == 0 & `touse' ;
            #delimit cr
            count if `first'
            if _result(1) > 0 { /* avoid replace if nothing to copy */
                local Np1 = _N + 1
                expand 1 + (`first' == 1)
                replace `last' = 1 in `Np1'/l
            }
            local i = `i' + 1
        }

        if "`by'" != "" {
            local byby "by(`by')"
            sort `by' `last' `order'
        }

        gra `varlist' [`weight' `exp'] if `touse', `byby' `options'

        qui drop if `last'
        sort `order'
    } /* end nobreak */
end