*! regeq ver 1.21 30Mar2012
*! ver 1.2 modify to work on models with long equations
*!          _const now indexed 0
*!          Option for prefix added
*! ver 1.21 modified for cox
*! Postestimation command to -regress-, logit, logistic, st cox
*!
*! Authors: Morten Frydenberg

program regeq
version 9
syntax [, format(string) prefix(string)]

if !inlist(e(cmd),"regress","logit","logistic","cox") {
   display as error "The last estimation should be -regress-,-logit-,-logistic- or cox"
   exit
}

if "`format'" == "" {
   local format = "%12.4f"
}
if "`prefix'" == "" {
   local prefix = "b"
}
macro drop `prefix'*

tempname zzzmat
matrix `zzzmat'=e(b)

mata: cnames=st_matrixcolstripe("e(b)")
local ncol=colsof(`zzzmat')
local zzzp 0

foreach zzzn of numlist 1/`ncol' {
    mata: st_local("coefname",cnames[`zzzn',2])
    local coef=`zzzmat'[1,`zzzn']
    if abs(`coef')>0.00000001 {
	local zzzp=`zzzp'+1
	local c`zzzp'="`coefname'"
    local `prefix'`zzzp'=`coef'
     }
  }

 disp "estimated equation"
 local feq = string(``prefix'`zzzp'',"`format'")+ " +"
 local dum=`zzzp'-1
 **************************************
 if e(cmd)=="cox" local dum=`zzzp'
 if e(cmd)=="cox" local feq =  " "

 **************************************

foreach zzz of numlist 1/`dum' {
 if length("`feq'")>50 {
  disp "`feq'" " /// "
  local feq " "
  }

 local feq= "`feq'" +  string(``prefix'`zzz'',"`format'")+ " * `c`zzz'' "
 if ``prefix'`zzz''>=0 &`zzz'<`dum' local feq= "`feq'" + " +"
}
 if length("`feq'")>0   disp "`feq'"

 disp  _newline(1)  "equation"
 local feq = "  `prefix'0 +"
  **************************************
 if e(cmd)=="cox" local feq =  " "

 **************************************
foreach zzz of numlist 1/`dum' {
 if length("`feq'")>50 {
  disp "`feq'" " /// "
  local feq " "
  }
 local feq= "`feq'" +  " `prefix'`zzz' * `c`zzz'' "
 if `zzz'<`dum' local feq= "`feq'" +  "+"
}
 if length("`feq'")>0   disp "`feq'"
foreach zzz of numlist 1/`dum'  {
 global `prefix'`zzz'=``prefix'`zzz''
}
global `prefix'0=``prefix'`zzzp''
end