* CENSORED POISSON REGRESSION : Joseph Hilbe 12Dec1997
* A revision of cnpois, 1994, J. Hilbe and D. Judson
* OPTIONS: tolerance,nolog,,offset, irr
program define cenpois
 version 5.0
 local options "Level(integer $S_level) IRr"
 if "`*'"=="" | substr("`1'",1,1)=="," {
   if "$S_E_cmd"=="cenpois" {
     error 301
   }
   parse "`*'"
   if `level'<10 | `level'> 99 {
     di in red "level() must be between 10 and 99"
     exit 198
   }
 }
 else {
   local varlist "req ex"
   local options "`options' LTolerance(real -1) noLOg ITerate OFfset(string) CENsor(string) *"
   local in "opt"
   local if "opt"
   local weight "fweight aweight"
   parse "`*'"
   parse "`varlist'",parse(" ")
   if "`log'"!="" { local log "quietly" }
   global S_mloff "`offset'"

 tempvar touse mysamp
 tempname b f V
 mark `touse' `if' `in'
 markout `touse' `varlist' `offset'

  if "`weight'" != "" {
        tempvar wvar
        gen double `wvar' `exp'
  }
  else  local wvar   1

  if ("`weight'"=="aweight")  {
        qui sum `wvar'
        qui replace `wvar' = `wvar'/_result(3)
  }

  if "`offset'" != "" {
        local ovar "`offset'"
  }
  else  local ovar   0
  global S_cen "`censor'"
* ESTIMATION OF LL0
 quietly {
   qui poisson `1'
   mat coef=get(_b)
   eq `1': `1'
   ml begin
   ml function cnpoislf
   ml method lf
   ml model `b' = `1', from(coefs)
   ml sample `mysamp' [`weight' `exp'] if `touse'
   `log' ml maximize `f' `V', `options'
   local lf0 = `f'
   drop `mysamp'
 }

* ESTIMATION OF FULL MODEL
   qui poisson `varlist'
   mat coef=get(_b)
   eq `1': `varlist'
   ml begin
   ml function cnpoislf
   ml method lf
   ml model `b' = `1', from(coefs)
   ml sample `mysamp' [`weight' `exp'] if `touse'
   `log' ml maximize `f' `V', `options'
   ml post cnpois, title("Censored Poisson Estimates") lf0(`lf0') pr2
   if "`irr'"!="" {
      local eform "eform(IRR)"
   }
}
ml mlout cnpois, level(`level') `eform'
end