*-----------------------------------------------------------------------------
* Custom Regression table for Epidemiologists
* Version 1.3: March 14, 2021: by Attaullah Shah
*-----------------------------------------------------------------------------

program define asdocx_reg1

	if strmatch("`0'", "*:*") |  strmatch("`0'", "* :*") | strmatch("`0'", "*: *") | strmatch("`0'", "* : *") {
		cap _on_colon_parse `0'
		local 0 `"`s(after)'"'
		local prefix `"`s(before)'"'
		if ("`prefix'" != "") loc prefix `prefix' :

	}

	//gettoken command 0 : 0
	syntax anything [if] [in] [fw pw iw aw] , [title(str) notes(str) modifytype(str) ///
		dect(str) dec(str) btp *]


	if ("`dect'" == "") loc dect `dec'

	if ("$modifytype" == "replace") {
	    cap rm $active_flexmat_file
		loc location 1
	}

	else {
		flexmat showmat ,  filename($active_flexmat_file) qui getlocinfo

		if ("$flexmat_current_loc" == "") {
			loc location 1
		}

		else loc location = $flexmat_current_loc + 1
	}

	flexmat addrow, data(Variable, OR [95% CI], P-value) ///
        row(`ThisRow') filename($active_flexmat_file) location(`location') qui

	loc ThisRow = 2

	if ("`weight'" != "") loc wgt "[`weight'`exp']"

	`prefix'  `anything' `if' `in' `wgt' , `options'

	//loc dec 2
	loc depvar `e(depvar)'
	loc N `e(N)'
	matrix table = r(table)
	local varnames : colfullnames table
	loc nvars : word count `varnames'

	loc c = 1

	foreach v of local varnames {

		loc hzratio : dis %9.`dec'f = table[1, `c']
		loc ll : dis %9.`dec'f = table[5,`c']
		loc ul : dis %9.`dec'f = table[6,`c']
		loc pvalue : dis %9.`dect'f = table[4,`c']

		loc hzratio `hzratio' [`ll'\comma `ul']

		forv i = 1 / 6 {
			loc hzratio = subinstr("`hzratio'", "[ ", "[", .)
		}

		if ("`btp'" != "") {
		    loc hzratio = subinstr("`hzratio'", "[", "\openpar", .)
			loc hzratio = subinstr("`hzratio'", "]", "\closepar", .)

		}

		loc v = subinstr("`v'", "`e(depvar)':", "", .)

		if strmatch("`v'", "*b.*") {
			loc hzratio
			loc pvalue
		}
		mata: st_local("varLabel", getlable("`v'"))
		loc varLabel = subinstr("`varLabel'", ",", "\comma", .)
		loc varLabel = subinstr("`varLabel'", "_cons", "Constant", .)

		if ("`varLabel'" == "Constant" & "${drop}" == "constant") continue
		else {

			flexmat addrow, data("`varLabel'", `hzratio', `pvalue' ) qui ///
				row(`ThisRow') filename($active_flexmat_file) location(`location')

			loc `++ThisRow'
			loc `++c'

		}
	}
	flexmat addrow, data(Observations, , `N' ) qui ///
		row(`ThisRow') filename($active_flexmat_file) location(`location')

	if ("`title'" == "") loc title Table: Regression Results - `depvar'
	if ("`notes'" == "") loc notes "Notes:"

	mata {
		flexmat_fmtmat = J(2,2,"")
		flexmat_fmtmat[1,1] = "title"
		flexmat_fmtmat[1,2] = "`title'"
		flexmat_fmtmat[2,1] = "notes"
		flexmat_fmtmat[2,2] = "`notes'"
	}
	flexmat fmtmat, file("$active_flexmat_file") loc(`location')  hide

	glob drop
end