prog define difftable , rclass
*!	difftable 1.10 11Aug2023 called by -diffplot- by Mead Over 	version 3.00  4Aug2023
*	Approximately reproduce the table in -diff.ado-, but for publication
*	An edited version of code from Juan Villa's -diff.ado-
*	Output of this -difftable- subroutine does not change with -resultsfrom-
	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 verbose debug
		cfact sdec(real 3) ]
		;
	#delimit cr

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

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

	local depvar `varlist'

	//  Get the -frmttable- command line for -difftable-
	getfrmt4diff, pvalues(`tradtable_p')   ///
		beforelbl(`beforelbl') afterlbl(`afterlbl') treatedlbl(`treatedlbl') controllbl(`controllbl')   ///
		`trtlbl' `conlbl' `beflbl' `aftlbl' `frmtopts'
	local asymbol `r(asymbol)'
	local tblnote `r(note)'

	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)

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

*	Add a row to the table for the counterfactual estimate and stats
if "`cfact'"=="" {
	// Row g reports the DID estimate and test statistics
	local row4didstar = 9
	local rownm4did   g
	local hlineopts    hlines(101{0001}1) hlstyle(sss{o}ss)
	local tblnote note("Estimated Diff-in-Diff in row g is defined as row f minus row c" \ "`tblnote'")
}
else {
	// Row g reports the counterfactual estimate, but does not
	// report t-stat & p, there is no reason to test Cfact ==0
	local difftbl_cfact_woN   \ `outmat'[1,8] , `outmat'[2,8] , . , .
	local difftbl_cfact_wN    \ `outmat'[1,8] , `outmat'[2,8] , . , . , .
	local rtitle_cfact    \ "g.  Counterfactual"
	local rname_cfact    "Counterfactual"
	local row4didstar = 10
	local rownm4did   h
	local hlineopts  hlines(1010001000011) hlstyle(sss{o}ss)
	local tblnote note("Estimated counterfactual in row g is defined as the sum of rows d and c"  ///
		"Estimated Diff-in-Diff in row h is defined as either row f minus row c or as row e minus row g" "`tblnote'")
}

*	Define a 9x4 (or 10x4) Stata matrix formatted like the -diff- results table.
*		This version excludes the numbers of observations
	tempname difftbl_woN
	mat define `difftbl_woN' =  ///
		(         .      ,          .     ,        .       ,       .          ///  "Before"
		\ `outmat'[1,1]  , `outmat'[2,1]  ,        .       ,       .          ///  "  Control"
		\ `outmat'[1,4]  , `outmat'[2,4]  ,        .       ,       .          ///  "  Treated"
		\ `outmat'[1,9]  , `outmat'[2,9]  , `outmat'[3,9]  , `outmat'[4,9]    ///  "  Diff (T-C)"
		\        .       ,          .     ,        .       ,       .          ///  "After"
		\ `outmat'[1,2]  , `outmat'[2,2]  ,        .       ,       .          ///  "  Control"
		\ `outmat'[1,5]  , `outmat'[2,5]  ,        .       ,       .          ///  "  Treated "
		\ `outmat'[1,10] , `outmat'[2,10] , `outmat'[3,10] , `outmat'[4,10]   ///  "  Diff (T-C)"
		`difftbl_cfact_woN'                                                       ///  "  Counterfactual"
		\ `outmat'[1,7]  , `outmat'[2,7] , `outmat'[3,7] , `outmat'[4,7]   )  //   "Diff-in-Diff"


	mat colnames  `difftbl_woN' = Estimate StdErr t-stat p-value
	mat rownames  `difftbl_woN' =   ///
		"Before" "Control(t=0)" "Treated(t=0)" "Diff(t=0)"  ///
		"After"  "Control(t=1)" "Treated(t=1)" "Diff(t=1)" `rname_cfact' "DID"

	if "`debug'"~=""  matlist `difftbl_woN', title(Matrix for -frmttable- without N as last column)

*		This version includes an extra column for the numbers of observations
	tempname difftbl_wN
	mat define `difftbl_wN' =  ///
		(         .      ,          .     ,        .       ,       .        ,     .            ///  "Before"
		\ `outmat'[1,1]  , `outmat'[2,1]  ,        .       ,       .        ,  `outmat'[5,1]   ///  "  Control"
		\ `outmat'[1,4]  , `outmat'[2,4]  ,        .       ,       .        ,  `outmat'[5,4]   ///  "  Treated"
		\ `outmat'[1,9]  , `outmat'[2,9]  , `outmat'[3,9]  , `outmat'[4,9]  ,  `outmat'[5,9]   ///  "  Diff (T-C)"
		\        .       ,          .     ,        .       ,       .        ,     .            ///  "After"
		\ `outmat'[1,2]  , `outmat'[2,2]  ,        .       ,       .        ,  `outmat'[5,2]   ///  "  Control"
		\ `outmat'[1,5]  , `outmat'[2,5]  ,        .       ,       .        ,  `outmat'[5,5]   ///  "  Treated "
		\ `outmat'[1,10] , `outmat'[2,10] , `outmat'[3,10] , `outmat'[4,10] ,  `outmat'[5,10]  ///  "  Diff (T-C)"
		`difftbl_cfact_wN'                                                                        ///  "  Counterfactual"
		\ `outmat'[1,7]  , `outmat'[2,7] , `outmat'[3,7] , `outmat'[4,7]    ,  `outmat'[5,7])  //   "Diff-in-Diff"


	mat colnames  `difftbl_wN' = Estimate StdErr t-stat p-value N
	mat rownames  `difftbl_wN' =   ///
		"Before" "Control(t=0)" "Treated(t=0)" "Diff(t=0)"  ///
		"After"  "Control(t=1)" "Treated(t=1)" "Diff(t=1)" `rname_cfact' "DID"

	if "`debug'"~=""  matlist `difftbl_wN', title(Matrix for -frmttable- with N as last column)

	local p0 = `outmat'[4,9]
	local p1 = `outmat'[4,10]
	local p11 = `outmat'[4,7]

	tempname stars
	mat define `stars'  =  J(`row4didstar',4,0)

	mat def `stars'[4,4] =  ///
			((`p0'<`pcrit1') +  (`p0'<`pcrit2') + (`p0'<`pcrit3'))
	mat def `stars'[8,4] =  ///
			((`p1'<`pcrit1') +  (`p1'<`pcrit2') + (`p1'<`pcrit3'))
	mat def `stars'[`row4didstar',4] =  ///
			((`p11'<`pcrit1') +  (`p11'<`pcrit2') + (`p11'<`pcrit3'))

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

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

	local annotate annotate(`stars')

	tempname dtbl dtblrtrn

	if strpos("`stats'","N")==0  {
		local ctitles ctitles( "Outcome Variable:"  , ""         , "Standard" , "t"         , "p"      ///
					         \ "  `depvar'"         , "Estimate" , "Error"    , "Statistic" , "Value")
		mat def `dtbl'     = `difftbl_woN'
		mat def `dtblrtrn' = `difftbl_woN'

		local sdec sdec(`sdec')
	}
	else {
		local ctitles ctitles( "Outcome Variable:"  , ""         , "Standard" , "t"         , "p"     , ""    ///
					         \ "  `depvar'"         , "Estimate" , "Error"    , "Statistic" , "Value" , "N" )
		mat def `dtbl'     = `difftbl_wN'
		mat def `dtblrtrn' = `difftbl_wN'

		local coljust coljust(l;....r)
		local sdec sdec(`sdec',`sdec',`sdec',`sdec',0)

	}

	local frmtcmdline statmat(`dtbl') `sdec' `hlineopts' ///
		`asymbol' `basefont' `tblnote' `ctitles'  `coljust' ///
		rtitle(  ///
			  "`beforelbl'" ///
			\ "a.  `controllbl'"  ///
			\ "b.  `treatedlbl'"  ///
			\ "c.  Diff (b-a)"  ///
			\ "`afterlbl'"  ///
			\ "d.  `controllbl'"  ///
			\ "e.  `treatedlbl'"  ///
			\ "f.  Diff (e-d)"  ///
			`rtitle_cfact'  ///
			\ "`rownm4did'.  Diff-in-Diff")

	//  Create a results table that resembles that of Villa's -diff- program
	di _n as txt "Producing the single-column version of the 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'


	/*

	frmttable `savefile' , statmat(`difftbl_woN') `sdec' `hlineopts' ///
		annotate(`stars') `asymbol' `replace' `basefont'  ///
		`title' `tblnote'  ///
		ctitles( "Outcome Variable:" , ""         , "Standard" , "t"         , "p"   ///
		       \ "  `depvar'"         , "Estimate" , "Error"    , "Statistic" , "Value")  ///
		rtitle(  ///
			  "`beforelbl'" ///
			\ "a.  `controllbl'"  ///
			\ "b.  `treatedlbl'"  ///
			\ "c.  Diff (b-a)"  ///
			\ "`afterlbl'"  ///
			\ "d.  `controllbl'"  ///
			\ "e.  `treatedlbl'"  ///
			\ "f.  Diff (e-d)"  ///
			`rtitle_cfact'  ///
			\ "`rownm4did'.  Diff-in-Diff")

	*/

/*
This alternative version of the -rtitle- option makes two columns:
		rtitle(  ///
			  "Before"       , ""  ///
			\ ""          , "Control"  ///
			\ ""          , "Treated"  ///
			\ ""          , "Diff (T-C)"  ///
			\ "After"     , "" ///
			\ ""          , "Control"  ///
			\ ""          , "Treated"  ///
			\ ""          , "Diff (T-C)"  ///
			\ "Diff-in-Diff" , "" )

*/

	return matrix difftable = `dtblrtrn'

end  /* End of program -difftable-  */