prog define tradtable, rclass
*!	tradtable 1.01 called by -diffplot- by Mead Over 	version 3.00  4Aug2023
*	Produce the traditional 2 x 2 diff-in-diff table
	version 14

	#delimit ;
	syntax varname [using/]  // Name of dependent variable [output file]
		[if] [in],   // Define the sample
		resultsfrom(string)
		period(varname fv)
		treated(varname fv)
		[beforelbl(string) afterlbl(string) controllbl(string) treatedlbl(string)
		outmat(name) pstars(passthru) title(passthru)
		stats(string) frmtopts(string) replace frmtaddtable verbose debug
		sdec(real 3)]  //  Changing this to -sdec(passthru)- breaks -tradtable- option
		;
	#delimit cr

	if "`debug'"~= "" {
		di as err `"In routine -tradtable- at line 905, option frmtopts is: `frmtopts' and option -sdec- is: `sdec'"'
	}

	local shhh = cond("`verbose'"=="", "quietly", "")

	if "`frmtaddtable'"~=""  {
	    local replace addtable
		local pretext pretext(" " \  " ")
	}

	// Define sample as observations within [if] [in]
	// for which -varname- is not missing
	marksample samp

	foreach lcl in before after control treated  {
		if `"``lcl'lbl'"'==""  {
		    local lcl'lbl' = strproper(`lcl')
		}
		else {
			local lcl'lbl' = abbrev(`"`lcl'lbl''"',8)
		}
	}

*	Columns of matrix -outmat- are:
*	cnt_b4    cnt_aft    cnt_dif     trt_b4    trt_aft    trt_dif        did  trt_cfact     b4_dif    aft_dif

	//  Rearrange outputs from -outmat- into four 3x3 matrices with traditional DID layout
	foreach sfx in b se t p N {
		local tradrnm = cond("`sfx'"=="b","estimate",cond("`sfx'"=="se","std_err",cond("`sfx'"=="t","t-stat",cond("`sfx'"=="p","p-value",cond("`sfx'"=="N","Nobs","ERROR")))))
		tempname tradtable_`sfx'
		mat define `tradtable_`sfx'' = (  ///
			  `outmat'["`tradrnm'","trt_aft"]  , `outmat'["`tradrnm'","trt_b4"] , `outmat'["`tradrnm'","trt_dif"]   ///
			\ `outmat'["`tradrnm'","cnt_aft"]  , `outmat'["`tradrnm'","cnt_b4"] , `outmat'["`tradrnm'","cnt_dif"]    ///
			\ `outmat'["`tradrnm'","aft_dif"]  , `outmat'["`tradrnm'","b4_dif"] , `outmat'["`tradrnm'","did"] 	)
			mat colnames `tradtable_`sfx'' =  `"`afterlbl'"'  `"`beforelbl'"'  "Difference"
			mat rownames `tradtable_`sfx'' = `"`treatedlbl'"' `"`controllbl'"' "Difference"

		if "`debug'"~=""  matlist `tradtable_`sfx'', title("tradtable_`sfx'")
	}

	//	Default (when stats() is blank) is to omit all statistics
	local nstats = wordcount("`stats'")  // Argument for frmttable's option substat(`nstats')

	// Formatting the tradtable output:
	//   Minimum with no substat is one column for _b x three columns of final display table = 3
	//   For a column for _b and one for _p or two columns x three columns of final display table = 6
	//   Maximum with all three -stats- is four rows x three columns of final display table = 12
	//   Adding a possible row for Nobs = 15
	//   Perhaps later add a possible row for a confidence interval.???
	local ncolstradtable = cond(`nstats'==0,3,cond(`nstats'==1,6,cond(`nstats'==2,9,cond(`nstats'==3,12,cond(`nstats'==4,15,-1)))))
		if `ncolstradtable' < 0 {
		    di as err "Error in the options for -difftable-"  ///
				_n "More than four statistics requested in the option -stats()-"
			exit 198
		}

	// Assemble the matrix which -frmttable- wants in its option -statmat()-
	tempname frmtstatmat
	mat def `frmtstatmat' = J(3,`ncolstradtable',.)  //  Change according to which stats are selected

	foreach r of numlist 1/3 { // Over the rows
	    local cc =  1
		foreach c of numlist 1/3  {  //  Over the columns of `frmtstatmat'[3,`ncolstradtable']
			local cnm_base = cond(`c'==1,"`afterlbl'",cond(`c'==2,"`beforelbl'","Difference"))
			foreach sfx in b `stats' {
				mat def `frmtstatmat'[`r',`cc'] =  `tradtable_`sfx''[`r',`c']
				if `r' == 3  local colnms `colnms' `"`cnm_base'_`sfx'"'
				if "`sfx'"=="N"  local colsforN `colsforN' `cc'
				if "`sfx'"=="se"  local colsforSE `colsforSE' `cc'
				local cc = `cc' + 1
			}
		}
	}
	mat rownames `frmtstatmat' = `"`treatedlbl'"' `"`controllbl'"' "Difference"
	mat colnames `frmtstatmat' = `colnms'
	if "`colsforN'"~="" {
		local colsforN : list uniq colsforN
		local colsforn colsforn(`colsforN')
	}
	if "`colsforSE'"~="" {
		local colsforSE : list uniq colsforSE
		local colsforse colsforse(`colsforSE')
	}
	tempname rtrnfstmt
	mat def `rtrnfstmt' = `frmtstatmat'

	if "`debug'"~=""  matlist `frmtstatmat', title("Diffplot results matrix as fed to {help frmttable}")

	//  Get the -frmttable- command line for -tradtable-
	getfrmt4trad , frmtstatmat(`frmtstatmat') pvalues(`tradtable_p') stats(`stats')   ///
		beforelbl(`beforelbl') afterlbl(`afterlbl') treatedlbl(`treatedlbl') controllbl(`controllbl')   ///
		`trtlbl' `conlbl' `beflbl' `aftlbl' `colsforn' `colsforse' `frmtopts' sdec(`sdec')

	if "`r(stars)'"~="" {
		tempname stars
		mat define `stars' = r(stars)
		local annotate annotate(`stars')

		if "`debug'"~=""   matlist `stars', title("matrix stars on return from -getfrmt4trad-")
	}

	local frmtcmdline `r(frmtcmdline)'

	if "`using'"~="" {
		local savefile using `"`using'"'
	}

	//  Create the traditional DID table
	di _n as txt "Producing the two-by-two traditional DID table using the program {help frmttable}" _continue
	if "`verbose'"=="verbose"  {
		di as txt " with command: "  ///
		 _n as inp `"frmttable `savefile', `frmtcmdline' `annotate' `replace' `title' `pretext'"'
	}
	frmttable `savefile', `frmtcmdline' `annotate' `replace' `title' `pretext'

	return matrix tradtable = `rtrnfstmt'

end  /* End of program -tradtable-  */