*! 1.1.0 07Jun97  Jeroen Weesie/ICS

program define _gslope
   version 5.0

   local type "`1'"                      /* type of result */
   mac shift
   local g "`1'"                         /* name of result */
   mac shift 2                           /* discard = sign */

   local varlist "req ex min(1)"
   local in "opt"
   local if "opt"
   local options "Coo Min(int 2)"
   parse "`*'"

 * check #variables

   if "`cons'" == "" {
      local npar 2
   }
   else local npar 1

   local nvar : word count `varlist'
   local k = mod(`nvar',2)
   local npair = int(`nvar'/2)
   if `k' ~= 0 {
      di in re "slope() expects an even number of variables"
      exit 498
   }
   if `npair' < `npar' {
      di in re "slope() expects at least `npar' (y,x) pairs"
      exit 198
   }
   if `min' < `npar' | `min' > `npair' {
      di in re "minimum number of valid (x,y) pairs should be between `npar' and `npair'"
      exit 498
   }

   quietly {

      tempvar n mx my cyx vx tmx touse u

      mark `touse' `if' `in'
      if "`coo'" != "" {
          markout `touse' `varlist'
      }

    * compute cov(y,x) and var(x) using the method of provisional means
    * See: Dixon et al (1990), Vol 1: p 538.

      gen int    `n'   = 0
      gen double `mx'  = 0
      gen double `my'  = 0
      gen double `cyx' = 0
      gen double `vx'  = 0

      parse "`varlist'", parse(" ")
      local i 1
      while `i' <= `nvar' {
         local y "``i''"
         local i = `i'+1
         local x "``i''"
         local i = `i'+1

         gen     `tmx' = `mx'
         gen     `u'   = `touse' & (`x'~=.) & (`y'~=.)
         replace `n'   = `n'+1                           if `u'
         replace `mx'  = `mx' + (`x'-`mx')/`n'           if `u'
         replace `my'  = `my' + (`y'-`my')/`n'           if `u'
         replace `vx'  = `vx' + (`x'-`mx')*(`x'-`tmx')   if `u'
         replace `cyx' = `cyx' + (`y'-`my')*(`x'-`tmx')  if `u'

         drop `tmx' `u'
      }

    * slope = cov(x,y)/var(x)

      gen `type' `g' = `cyx' / `vx' if `touse' & `n' >= `min'

      if "`obs'" ~= "" {
         gen `obs' = `n' if `touse' & `n' >= `min'
      }

   } /* end quietly */
end