program define sreg,eclass

*' Need to know if LHS is transformed (ln), fraction or count.

* local mincellsize 11
* * local mincellsize 10 - changed to 11 by Mohan 2023/11/14
* di "mincellsize: `mincellsize'"
*
* di "mincellsize: `mincellsize'"
* if "x`mincellsize'"=="x" {
*    di "Must specify mincellsize in global macro"
*    exit 324
* }


*if "x`mincellsize'"=="x" {
if "x$mincellsize"=="x" {
   di "mincellsize is not specified in global macro.  Setting to default."
   local mincellsize 11
*    exit 324
}
else {
   local mincellsize "$mincellsize"

}

di "mincellsize: `mincellsize'"


* read into matrix lang
matrix eb=e(b)
matrix ev=e(V)
*di "Debug: Print matrix eb"
matrix list eb
*di "Debug: Print matrix ev"
matrix list ev

local depvars : rownames(ev)
scalar _last=colsof(eb)
local _last=_last
*di "Debug: Print _last:`_last'"
forvalues i=1/`_last' {
    di "`i'"
    *   Round coef and se to 3 significant digits
    tempname b
    scalar `b' = eb[1,`i']
    if `b'!=.&`b'!=0 scalar `b'=sign(`b')*round(abs(`b'),10^(floor(log10(abs(`b')))-3))
    matrix eb[1,`i'] = `b'

    scalar `b' = ev[`i',`i']
    if `b'!=.&`b'!=0 scalar `b'=sign(`b')*round(abs(`b'),10^(floor(log10(abs(`b')))-3))
    matrix ev[`i',`i'] = `b'


    local var : word `i' of `depvars'
    di "Checking `var' for cellsize"
    cap des `var'
    di _rc
    if "`var'"!="_cons" & _rc==111 {
        ** Some regressions return additional metrics
        di "`var' not found in original dataset - censor by default"
        matrix eb[1,`i'] = 0
        matrix ev[`i',`i'] = 0
        continue
        }
    * no change to non-dummy variables.
    * how do we define dummy variables - only has two categories
    tempvar tabvar
    quietly {
       gen `tabvar'= `var'
       cap tab `tabvar' if e(sample)
    }
    * tab returns too many values error `134` if too many errors
    * not binary in that case
    if _rc==134 continue

    scalar numcats = r(r)
    if numcats >3 continue
    * no change to dummies with enough of both values.
    capture count if `var'==0 & e(sample)
    tempname numzer
    scalar `numzer' = r(N)
    capture count if `var'!=0 & e(sample)
    tempname numnot
    scalar `numnot' = r(N)
        if `numzer'<`mincellsize' | `numnot'<`mincellsize' {
            di "`i' `var' censored'"
            matrix eb[1,`i'] = 0
            matrix ev[`i',`i'] = 0
        }
}


*Always censor constant.
local _cons=colnumb(eb,"_cons")
* matrix eb[1,`_cons'] = 0
* matrix ev[`_cons',`_cons'] = 0
capture {
  matrix eb[1,`_cons'] = 0
  matrix ev[`_cons',`_cons'] = 0
}
* Use Stata for output
_coef_table ,bmatrix(eb) vmatrix(ev)
di "0 values indicate fewer than `mincellsize' records" ///
   " (or secondary suppression of the constant)."

ereturn repost b=eb V=ev
end