prog define getfrmt4trad , rclass
*!	version 3.00  4Aug2023  UNDER CONSTRUCTION
*	This subroutine parses the -frmttable- option so that the user can
*	override most of the options selected by -diffplot-.
*	Then it returns the -frmttable command line to subroutine -tradtable-,
*	which executes -frmttable- producing the output.
	version 14

	syntax  , [frmtstatmat(name) pvalues(name) pstars(numlist) stats(string) ///  -diffplot- options
		beforelbl(string) afterlbl(string) treatedlbl(string) controllbl(string)  ///  -diffplot- options
		statmat(passthru) substat(passthru)  ///  -frmttable- options expropriated by -diffplot-
		hlines(passthru) vlines(passthru) replace  ///  -frmttable- options used by -diffplot-, but user can override
		annotate(passthru) asymbol(string) basefont(passthru)   ///
		ctitles(passthru) rtitles(passthru) note(passthru)  ///
		colsforn(numlist) colsforse(numlist) sdec(passthru) *]

	//  * = -frmttable- options not used by -diffplot- and passed through to -frmttable-
	if "`verbose'"~="" {
		di as err `"In subroutine -getfrmt4trad-, the options catured by -*- are:"'  ///
			_n  `"`options'"'
	}

	foreach opt in statmat substat {
	    if "``opt''"~="" {
		    di as err "The {help frmttable} option, -`opt'-, is used by diffplot and cannot be overridden by the -diffplot- user."
			exit 198
		}
	}

	if "`basefont'"=="" {
		local basefont basefont(arial fs11)
	}

	//  The labels Before After Control & Treatment are always the top label,
	//  optionally supplemented with the user supplied label
	foreach dfltlbl in before after control treated  {
		local prfx = cond("`dfltlbl'"=="treated","trt",substr("`dfltlbl'",1,3))
		// If assigned label = default label, no need for second label
		if "``dfltlbl'lbl'" == proper("`dfltlbl'") {
			local `prfx'alt = 	"``dfltlbl'lbl'"
		}
		// Else default label is top label, user-assigned label is second or -alt- label
		else {
			local `prfx'alt = 	proper("`dfltlbl'")
		}
	}

	//  Default is only the coefficients, no statistics
	local nstats = wordcount("`stats'")

	//  The additional horizontal and vertical grid lines
	//  specified by the hlines and vlines options only appear
	//  in the MS Word or Tex file, not in Stata results output
	if "`hlines'"=="" {
		local hlines =   ///
			cond(`nstats'==0,"hlines(10;1011)",  ///
			cond(`nstats'==1,"hlines(10;1010101)",  ///
			cond(`nstats'==2,"hlines(10;1001001001)",  ///
			cond(`nstats'==3,"hlines(10;1000100010001)",  ///
			cond(`nstats'==4,"hlines(10;1000010000100001)","")))))
	}
	if "`hlstyle'"=="" {
		local hlstyle =   ///
			cond(`nstats'==0,"hlstyle(s;sos)",  ///
			cond(`nstats'==1,"hlstyle(s;ssos)",  ///
			cond(`nstats'==2,"hlstyle(s;sssos)",  ///
			cond(`nstats'==3,"hlstyle(s;ssssos)",  ///
			cond(`nstats'==4,"hlstyle(s;sssssos)","")))))
	}
	if "`vlines'"=="" {
	    local vlines vlines(01010)
	}

	if "`annotate'"=="" {
	    tempname pmatrix
		mat define `pmatrix'= `pvalues'

		tempname stars

		// Stars matrix has same dimensions as matrix -`frmtstatmat'-
		local nrows = rowsof(`frmtstatmat')
		local ncols = colsof(`frmtstatmat')
		matrix `stars' = J(`nrows',`ncols',0)

		// Only put stars on the coefficients in the last column and last row
		//   -stars- column location of coefficients on right margin of tradtable:
		local rtmargcol = cond(`nstats'==0,3,cond(`nstats'==1,5,cond(`nstats'==2,7,cond(`nstats'==3,9,cond(`nstats'==4,11,-1)))))
			if `rtmargcol' < 0 {
			    di as err "Invalid -nstats-"
				exit 198
			}
		//   -stars- column location of coefficient in bottom row, middle column of tradtable:
		local secondcol = cond(`nstats'==0,2,cond(`nstats'==1,3,cond(`nstats'==2,4,cond(`nstats'==3,5,cond(`nstats'==4,6,-1)))))

		if "`pstars'"==""  {
			local pstars 0.1 , 0.05 , 0.01
		}
		tokenize `"`pstars'"', parse(`"," "')
		local i = 1
		while "`1'"~="" {
			if `i' > 3 {
				di as err "The option -pstars(numlist)-, if specified, must contain exactly 3 numbers, such as .1 .05 .01, the default."
				exit 198
			}
			if "`1'"~="," & "`1'"~=`"""' {
				// To sort properly, numbers must be expressed in same format
				local p`i'txt : di %9.4f ``i''
				local pstarsfmt `pstarsfmt' `p`i'txt'
			}
			macro shift
		}
		local pstarsfmt : list sort pstarsfmt
		tokenize `pstarsfmt'
		local pcrit3 = word("`pstarsfmt'",1)
		local pcrit2 = word("`pstarsfmt'",2)
		local pcrit1 = word("`pstarsfmt'",3)

		// Return the `stars' matrix in r(). Then let -tradtable- deliver it to -frmttable-
		matrix `stars'[1,`rtmargcol'] =  ///
			((`pmatrix'[1,3]<`pcrit1') +  (`pmatrix'[1,3]<`pcrit2') + (`pmatrix'[1,3]<`pcrit3'))
		matrix `stars'[2,`rtmargcol'] =  ///
			((`pmatrix'[2,3]<`pcrit1') +  (`pmatrix'[2,3]<`pcrit2') + (`pmatrix'[2,3]<`pcrit3'))
		matrix `stars'[3,`rtmargcol'] =  ///
			((`pmatrix'[3,3]<`pcrit1') +  (`pmatrix'[3,3]<`pcrit2') + (`pmatrix'[3,3]<`pcrit3'))
		matrix `stars'[3,1] =  ///
			((`pmatrix'[3,1]<`pcrit1') +  (`pmatrix'[3,1]<`pcrit2') + (`pmatrix'[3,1]<`pcrit3'))
		matrix `stars'[3,`secondcol'] =  ///
			((`pmatrix'[3,2]<`pcrit1') +  (`pmatrix'[3,2]<`pcrit2') + (`pmatrix'[3,2]<`pcrit3'))
	}

	if `"`asymbol'"'=="" {
	    local asymbol "*","**","***"
	}
	tokenize `"`asymbol'"', parse(`"," "')
	local i = 1
	while "`1'"~="" {
		if `i' > 3 {
			di as err "The option -asymbol- may contain only three symbols."
			exit 198
		}
		if "`1'"~="," & "`1'"~=`"""' {
			local s`i' `1'
			local i = `i' + 1
		}
		macro shift
	}
	local asymbol asymbol(`s1',`s2',`s3')

	if "`ctitles'"=="" {
	    if "`afterlbl'"=="`aftalt'" & "`beforelbl'"=="`befalt'" {
			local ctitles ctitles(  ///
				  "  "    "`aftalt'"         "`befalt'"       "Difference" )
		}
		else {
			local ctitles ctitles(  ///
				  "  "    "`aftalt'"         "`befalt'"       "  "   ///
				\ "  "  `"`afterlbl'"'  `"`beforelbl'"'  "Difference" )
		}
	}

	if "`rtitles'"=="" {
		local blankrows =  ///
			cond(`nstats'==0,`""',  ///
			cond(`nstats'==1,`" \   `"  "'  "',  ///
			cond(`nstats'==2,`" \   `"  "'  \  "  " "',  ///
			cond(`nstats'==3,`" \   `"  "'  \  "  " \  "  " "',  ///
			cond(`nstats'==4,`" \   `"  "'  \  "  " \  "  " \  "  " "',"ERROR")))))

	    if "`treatedlbl'"=="`trtalt'" & "`controllbl'"=="`conalt'" {
			local rtitles rtitles(  ///
				  "`trtalt'"     `blankrows'     ///
				\ "`conalt'"     `blankrows'     ///
				\ "Difference"   `blankrows' )
		}
		else {
			local treatedrows =  ///
				cond(`nstats'==0,`" `"`treatedlbl'"'  "',  ///
				cond(`nstats'==1,`" "`trtalt'"   \  `"  `treatedlbl'"' "',  ///
				cond(`nstats'==2,`" "`trtalt'"   \  `"  `treatedlbl'"'  \  "  "  "',  ///
				cond(`nstats'==3,`" "`trtalt'"   \  `"  `treatedlbl'"'  \  "  "  \  "  "  "',  ///
				cond(`nstats'==4,`" "`trtalt'"   \  `"  `treatedlbl'"'  \  "  "  \  "  "  \  "  "  "',"ERROR")))))
			local controlrows =  ///
				cond(`nstats'==0,`" `"`controllbl'"'  "',  ///
				cond(`nstats'==1,`" "`conalt'"   \  `"  `controllbl'"' "',  ///
				cond(`nstats'==2,`" "`conalt'"   \  `"  `controllbl'"'  \  "  "   "', ///
				cond(`nstats'==3,`" "`conalt'"   \  `"  `controllbl'"'  \  "  "  \  "  "  "',  ///
				cond(`nstats'==4,`" "`conalt'"   \  `"  `controllbl'"'  \  "  "  \  "  "  \  "  "  "',"ERROR")))))
			local rtitles rtitles(  ///
				  `treatedrows'   ///
				\ `controlrows'   ///
				\ "Difference"  `blankrows' )
		}
	}

	// Don't display (i.e. change to missing) the statistics in interior of the `frmtstatmat' table
	// Exception: Include interior cells for the numbers of observations (N) and the standard errors (se)
	local intcols = cond(`ncols'==3,"-1",cond(`ncols'==6,"2 4",cond(`ncols'==9,"2 3 5 6",cond(`ncols'==12,"2 3 4 6 7 8",cond(`ncols'==15,"2 3 4 5 7 8 9 10","")))))
	if "`intcols'"~="-1" & "`intcols'"~="" {
		foreach r of numlist 1/3 {
			foreach c of numlist 1/`ncols' {
				foreach cc of numlist `intcols' {
					local isNcol no
					foreach cforn in `colsforn' {
						if `cc'==`cforn' {
							local isNcol yes
						}
					}
					local isSEcol no
					foreach cforse in `colsforse' {
						if `cc'==`cforse' {
							local isSEcol yes
						}
					}
					if `r'<3 & (`c' == `cc') & ("`isNcol'"=="no")  & ("`isSEcol'"=="no")  {
						mat def `frmtstatmat'[`r',`c'] = .
					}
				}
			}
		}
	}

	// Add footnotes to the table
	if "`tblnote'"=="" {
		local di_p1 = real("`pcrit1'")
		local di_p2 = real("`pcrit2'")
		local di_p3 = real("`pcrit3'")
		local note1 `s1' p < `di_p1';  `s2' p < `di_p2';  `s3' p < `di_p3'
		if "`stats'"~="" {
			foreach stat in `stats' {
				local ptxt `ptxt' `slsh' `stat'
				local slsh  /
			}
			local note2 `ptxt' displayed below estimated differences
		}
		local note note("`note1'" \ "`note2'")
	}

	// If one of the statistics is N, set the number of decimals for it to 0
	// and Center justify the entire table
	if "`colsforn'"~="" & `"`sdec'"'~=""  {
		tokenize "`sdec'", parse("()")
		//  Third token of -sdec(passthru)- is the default number of decimals.
		local ndec = `3'
		//  First digit of numlist -`colsforn'- is the first column of the results matrix in which N appears
		local firstc4n = word("`colsforn'",1)
		local sdecmat `ndec'  // Coefficient estimate gets `ndec' decimals
		local nrows = `nstats'+1
		foreach i of numlist 2/`nrows' {
			if `i' == `firstc4n' {
				local sdecmat  `sdecmat' \ 0
			}
			else {
				local sdecmat  `sdecmat' \  `ndec'
			}
		}
		local sdec sdec( `sdecmat' )
		local coljust coljust(l;.)
	}

	local frmtcmdline statmat(`frmtstatmat') substat(`nstats')  `basefont' `colwidth' ///
		`hlines' `hlstyle' `vlines' `sdec' `coljust' `asymbol' `ctitles' `rtitles' `note' `options'

	return local  frmtcmdline `frmtcmdline'
	return matrix stars       `stars'

end  /* End of program -getfrmt4trad-  */

*	version 3.00 4Aug2023  Fix bug in forcing 0 decimals for the N statistic. Line 240