*!  Version 1.1 31Jan2019 by Mead Over, Center for Global Devleopment
*!	Companion program to be executed by the help file: cleancmmdline.sthlp
program define cleancmdline_example
	version 11.1
    preserve
		set more off
		capture prog drop cleancmmdline

		set more off
		`0'

		capture prog drop flexmake
		capture prog drop sureg
	restore
end

program define Msg
	di as txt
	di as txt "-> " as inp `"`0'"'
end

program define Xeq
	di as txt
	di as txt `"-> "' as inp _asis `"`0'"'  as res " "
	`0'
end

program define NewFile
	args fn
	capture confirm new file `fn'
	if _rc {
		di as err "{p 0 2 2}"
		di "Example cannot be run because you already have a"
		di "file named {res:`fn'}"
		di "{p_end}"
		error 602
	}
end

program define NewName
	args fn
	capture graph rename `fn' `fn'
	if _rc==0 {
		di as err "{p 0 2 2}"
		di "Example cannot be run because you already have a"
		di "graph in memory named {res:`fn'}."
		di "Either drop this graph or simply click {stata graph drop _all}."
		di "{p_end}"
		di as err _n "graph `fn' already exists"
		exit 110
	}
end

program define Meq  //  Version of Xeq which displays macros
	syntax,   ///
		cmd(string) [ ///
		part1(string) global1(string) ///
		local1(string) ///
		part2(string) local2(string) global2(string) ///
		part3(string) local3(string) global3(string) ///
		part4(string) local4(string) global4(string) ///
		part5(string) local5(string) global5(string) ///
		part6(string) local6(string) global6(string) ///
		part7(string) local7(string) global7(string) ///
		part8(string) local8(string) global8(string) ///
		part9(string) local9(string) global9(string) ]
	di as txt
	di as txt `"-> "'  _c
	foreach i of numlist 1/9 {
		if `"`part`i''"'~="" {
			di as res _asis "`part`i''"  _c
		}
		if `"`global`i''"'~="" {
			di as res _asis _char(36) "`global`i''" _c
		}
		if `"`local`i''"'~="" {
			di as res _asis _char(96) "`local`i''" _char(39) _c
		}
		if `"`part`i''"'=="" & `"`local`i''"'=="" & `"`global`i''"'=="" {
			di
			continue, break
		}
	}
	`cmd'
end

prog define run_flexmake
	Msg *  This example uses a copy of data on Stata's web site,
	Msg *  which comes originally from Greene (1997, section 15.6).
	Msg *  The data is available at http://www.stata-press.com/data/r14/mfgcost -

	Msg *  User's data has been preserved before running this example
	Xeq sysuse flex_mfgcost, clear

	Msg *  flexmake prefers the input names, here k, l, e and m,
	Msg *  to always be preceded by the underscore character
	Xeq rename pk p_k
	Xeq rename pl p_l
	Xeq rename pe p_e
	Xeq rename pm p_m

	Xeq describe
	Xeq summarize

	Msg *  Executing -flexmake- on this data generates the transformed variables
	Msg *  and the terms of the quadratic function selected by the user.
	Msg *  Here we use the -ln- option to construct the data and syntax for the translog function.

	Xeq flexmake cost, ln prices(p_*) shares(s_*) globals half
	Msg *  Because the -globals option is specified, the following
	Msg *  -flexmake- results are available as global macros:
	Xeq return list

	Msg *  Flexmake complements the provided data by computing
	Msg *  the implied expenditure totals and input quantities:
	Xeq describe
	Xeq summarize

	qui snapshot erase _all  //  Assures the snapshot will be #1
	qui snapshot save, label("flexmake example data from Stata's mfgcost.dta and transformation")
end

program define run_regress
	capture snapshot restore 1
		if _rc~=0  {
			di _n as err "Must {stata cleancmmdline_example run_flexmake:click to set up data} before running any cleancmmdline example from this help file."
			exit 111
		}
	Msg * Since the -globals- option was specified, we can save effort by using
	Msg * the global macros for the lists of transformed price variables

*	By using -Meq- instead of -Xeq-, we properly display the macros.
	Meq , cmd(`"di "$ownprices""') part1("di ") global1("ownprices")

	Msg *	Estimate a Cobb-Douglas cost function

	Meq , cmd(`"regress cost $ownprices"')  ///
		part1(`"regress cost "') global1(`"ownprices"')

	Msg *	After {help regress}, Stata returns the command line in the local macro {cmd:e(cmdline)}.

	Xeq di e(cmdline)

	qui snapshot save, label("#2 cleancmmdline mfgcost data plus e(sample) from sureg without cost function")
end

program define run_sureg
	capture snapshot restore 1
		if _rc~=0  {
			di _n as err "Must {stata cleancmmdline_example run_flexmake:click to set up data} before running any cleancmmdline example from this help file."
			exit 111
		}
	Msg * First, specify the cross-equation constraints consistent with cost minimization.
	Xeq constraint 1 _b[s_k:c.ln_p_l]  =  _b[s_l:c.ln_p_k]
	Xeq constraint 2 _b[s_k:c.ln_p_e]  =  _b[s_e:c.ln_p_k]
	Xeq constraint 3 _b[s_l:c.ln_p_e]  =  _b[s_e:c.ln_p_l]
	Xeq constraint 4 _b[s_k:c.ln_p_k] + _b[s_k:c.ln_p_l] + _b[s_k:c.ln_p_e] + _b[s_k:c.ln_p_m] = 0
	Xeq constraint 5 _b[s_l:c.ln_p_k] + _b[s_l:c.ln_p_l] + _b[s_l:c.ln_p_e] + _b[s_l:c.ln_p_m] = 0
	Xeq constraint 6 _b[s_e:c.ln_p_k] + _b[s_e:c.ln_p_l] + _b[s_e:c.ln_p_e] + _b[s_e:c.ln_p_m] = 0

	Msg * Since {help flexmake}'s  -globals- option was specified, we can save effort by using
	Msg * the global macros for the lists of transformed price variables

*	By using -Meq- instead of -Xeq-, we properly display the macros.
	Meq , cmd(`"di "$ownprices""') part1("di ") global1("ownprices")

	Msg *	Now we estimate the same share equations shown in the Stata manual

*	It would be simpler to use the following command to execute -sureg-
*	Xeq sureg (s_k $ownprices ) (s_l $ownprices ) (s_e $ownprices ), constraints(1-6) isure

*	But by using -Meq- instead of -Xeq-, we properly display the macros.
	Meq , cmd(`"sureg (s_k $ownprices ) (s_l $ownprices ) (s_e $ownprices ), constraints(1-6) isure"')  ///
		part1(`"sureg (s_k "') global1(`"ownprices"')  ///
		part2(`") (s_l "')  global2(`"ownprices"')  ///
		part3(`") (s_e "')  global3(`"ownprices"')  ///
		part4(`"), constraints(1-6) isure"')

	Msg *	After {help sureg}, Stata returns the command line in the local macro ///
	cmd:e(return)}, but note that it retains the specifications of all the ///
	estimated equations and, potentially, also the {help if} and {help in} ///
	qualifiers.

	Xeq di e(cmdline)

	qui snapshot save, label("#2 cleancmmdline mfgcost data plus e(sample) from sureg without cost function")
end


program define run_ivregress
	capture snapshot restore 1
		if _rc~=0  {
			di _n as err "Must {stata cleancmmdline_example run_flexmake:click to set up data} before running any cleancmmdline example from this help file."
			exit 111
		}
	Msg * Stata's standard syntax for instrumental variable regression is to
	Msg * enclose endogenous right-hand-side variables and the excluded exogenous
	Msg * variables in parentheses separated by an equals sign.

	Msg *	Estimate a Cobb-Douglas cost function by Two-staged Least Squares using {help ivregress}
	Msg *	Assume the price of labor is endogenous and can be instrumented by lagged prices

	Xeq tsset year

	Xeq ivregress 2sls cost c.ln_p_k c.ln_p_e c.ln_p_m c.ln_p_e c.ln_p_m (c.ln_p_l  = L.c.ln_p_k L.c.ln_p_e L.c.ln_p_m)

	Msg *	After {help ivregress}, Stata returns the full command line in the local macro {cmd:e(cmdline)}.

	Xeq di e(cmdline)

	qui snapshot save, label("#2 cleancmmdline mfgcost data plus e(sample) from ivregress")
end


program define xeq_ccl
	capture snapshot restore 1
		if _rc~=0  {
			di _n as err "Must {stata cleancmmdline_example run_flexmake:click to set up data} before running any cleancmmdline example from this help file."
			exit 111
		}
	Msg * Execute {cmd:cleancmdline} in order to extract the syntax for the first equation.

	Meq, cmd(`"cleancmdline , cmdline("`e(cmdline)'")"')  ///
		part1(`"cleancmdline , cmdline("')  local1(e(cmdline))  part2(`")"')

	Msg * The program {cmd:cleancmdline} returns the following cleaned version of the first equation

	Xeq di r(cmdline)

	Msg * The full set of macros returned by {cmd:cleancmdline} is listed below:
	Xeq return list

end

/*
program define run_with_cost
	capture snapshot restore 1
		if _rc~=0  {
			di _n as err "Must {stata cleancmmdline_example run_flexmake:click to set up data} before running any cleancmmdline example from this help file."
			exit 111
		}

	Xeq constraint 1 _b[s_k:c.ln_p_l]  =  _b[s_l:c.ln_p_k]
	Xeq constraint 2 _b[s_k:c.ln_p_e]  =  _b[s_e:c.ln_p_k]
	Xeq constraint 3 _b[s_l:c.ln_p_e]  =  _b[s_e:c.ln_p_l]
	Xeq constraint 4 _b[s_k:c.ln_p_k] + _b[s_k:c.ln_p_l] + _b[s_k:c.ln_p_e] + _b[s_k:c.ln_p_m] = 0
	Xeq constraint 5 _b[s_l:c.ln_p_k] + _b[s_l:c.ln_p_l] + _b[s_l:c.ln_p_e] + _b[s_l:c.ln_p_m] = 0
	Xeq constraint 6 _b[s_e:c.ln_p_k] + _b[s_e:c.ln_p_l] + _b[s_e:c.ln_p_e] + _b[s_e:c.ln_p_m] = 0
	Xeq constraint 7 _b[ln_cost:c.ln_p_k]  =  _b[s_k:_cons]
	Xeq constraint 8 _b[ln_cost:c.ln_p_l]  =  _b[s_l:_cons]
	Xeq constraint 9 _b[ln_cost:c.ln_p_e]  =  _b[s_e:_cons]
	Xeq constraint 10 _b[ln_cost:c.ln_p_k] + _b[ln_cost:c.ln_p_l] + _b[ln_cost:c.ln_p_e] + _b[ln_cost:c.ln_p_m]  =  1.0
	Xeq constraint 11 _b[ln_cost:c.ln_p_k#c.ln_p_k#c.__half]  =  _b[s_k:c.ln_p_k]
	Xeq constraint 12 _b[ln_cost:c.ln_p_l#c.ln_p_l#c.__half]  =  _b[s_l:c.ln_p_l]
	Xeq constraint 13 _b[ln_cost:c.ln_p_e#c.ln_p_e#c.__half]  =  _b[s_e:c.ln_p_e]
	Xeq constraint 14 _b[ln_cost:c.ln_p_k#c.ln_p_l]  =  _b[s_k:c.ln_p_l]
	Xeq constraint 15 _b[ln_cost:c.ln_p_k#c.ln_p_e]  =  _b[s_k:c.ln_p_e]
	Xeq constraint 16 _b[ln_cost:c.ln_p_k#c.ln_p_m]  =  _b[s_k:c.ln_p_m]
	Xeq constraint 17 _b[ln_cost:c.ln_p_l#c.ln_p_e]  =  _b[s_l:c.ln_p_e]
	Xeq constraint 18 _b[ln_cost:c.ln_p_l#c.ln_p_m]  =  _b[s_l:c.ln_p_m]
    Xeq constraint 19 _b[ln_cost:c.ln_p_e#c.ln_p_m]  =  _b[s_e:c.ln_p_m]

*	It would be simpler to use the following command to execute -sureg-
*	Xeq sureg (ln_cost $ownprices $ownprices2 $crossprices) (s_k $ownprices ) (s_l $ownprices ) (s_e $ownprices ), constraints(1-18) isure

*	But by using -Meq- instead of -Xeq-, we properly display the macros.
	Meq , cmd(`"sureg (ln_cost $ownprices $ownprices2 $crossprices) (s_k $ownprices ) (s_l $ownprices ) (s_e $ownprices ), constraints(1-18) isure"')  ///
		part1(`"sureg (ln_cost "') global1(`"ownprices"') part2(`"  "') global2(`"ownprices2"')  part3(`"  "') global3(`"crossprices"')    ///
		part4(`") (s_k "') global4(`"ownprices"')  ///
		part5(`") (s_l "')  global5(`"ownprices"')  ///
		part6(`") (s_e "')  global6(`"ownprices"')  ///
		part7(`"), constraints(1-19) isure"')


	Xeq est store withcost

	qui snapshot save, label("#3 flexmake mfgcost data plus e(sample) from sureg WITH cost function")
end

program define make_esttable
	capture est table wocost withcost
	if _rc~=0 {
		Msg est table wocost withcost, t stat(N ll)
		di as err "Run both of the above examples to store their estimates "
		di as err "before running this example to display and compare them"
		exit
	}

	Xeq est table wocost withcost, t stat(N ll)

end

program define show_margins_atmeans
	capture snapshot restore 2
		if _rc~=0  {
			di _n as err "Must {stata cleancmmdline_example run_flexmake:click to set up data}"  ///
				_n "and then {stata cleancmmdline_example run_sureg:click to run Example 1} "  ///
				_n "before running any cleancmmdline example from this help file."
			exit 111
		}

	capture est table wocost withcost
	if _rc~=0 {
		Msg est table wocost withcost, t stat(N ll)
		di as err "Run both of the above examples to store their estimates "
		di as err "before running this example to display and compare them"
		exit
	}

	Msg *	Estimated  Allan-Uzawa own price Allan-Uzawa elasticity of substitution for capital
	Xeq est restore wocost
	Xeq summ s_k
*	Don't need -Meq- for following commands, because the `'$ characters not required.
	Xeq scalar kmean=r(mean)
	Xeq margins , expression((_b[s_k:ln_p_k] + kmean * (kmean-1))/kmean) atmeans
	Msg *	The above computation matches that in the manual.
end

program define show_margins_atmeans_est
	capture snapshot restore 3
		if _rc~=0  {
			di _n as err "Must {stata flexmake_example run_cleancmmdline:click to set up data}"  ///
				_n "and then {stata cleancmmdline_example run_sureg:click to run Example 1} "  ///
				_n "and then {stata cleancmmdline_example run_with_cost:click to run Example 2} "  ///
				_n "before running any cleancmmdline example from this help file."
			exit 111
		}

	Msg *	Estimated Allan-Uzawa own price Allan-Uzawa elasticity of substitution for capital
	Msg *	using predicted mean of the capital share rather than its actual mean.
	Msg *	First estimate the elasticity from the estimates obtained *without* the cost function.
	Xeq est restore wocost
	Xeq margins , expression((_b[s_k:ln_p_k] + predict(xb equation(s_k)) * (predict(xb equation(s_k))-1))/predict(xb equation(s_k))) atmeans
	Msg *	Thus in this case assuming the sample mean of the capital share
	Msg *	is constant has little effect.
	Msg *	Now estimate the elasticity using the estimates that include the cost function.
	Xeq est restore withcost
	Xeq margins , expression((_b[s_k:ln_p_k] + predict(xb equation(s_k)) * (predict(xb equation(s_k))-1))/predict(xb equation(s_k))) atmeans
	Msg *	Clearly including the cost function along with the share equations greatly changes the estimated elasticity.
end

program define demo_flexelast
	capture snapshot restore 3
		if _rc~=0  {
			di _n as err "Must {stata cleancmmdline_example run_cleancmmdline:click to set up data}"  ///
				_n "and then {stata cleancmmdline_example run_sureg:click to run Example 1} "  ///
				_n "and then {stata cleancmmdline_example run_with_cost:click to run Example 2} "  ///
				_n "before running any cleancmmdline example from this help file."
			exit 111
		}

	capture flexelasticity
	if _rc==199 {
		di as err "You must install {help flexelasticity} to run this example."
		exit
	}
	Msg *	When the system of equations includes a cost function,
	Msg *   simplify the estimation of elasticities by using the program -flexelasticity-.
	Msg *	For example, compute the own-price elasticity of demand for capital.
	Meq , cmd(`"flexelasticity ln_p_k ln_p_k, cmdline(`e(cmdline)') shares(s_k s_k) chain(ln) "')  ///
		part1(`"flexelasticity ln_p_k ln_p_k, cmdline("') local1("e(cmdline)")  ///
		part2(`") shares(s_k s_k) chain(ln) "')

	Msg *	Compare this estimate with the one computed by the margins command.
	Msg *	Also compute the cross-price elasticity using flexelasticity
	Meq , cmd(`"flexelasticity ln_p_k ln_p_l, cmdline(`e(cmdline)') shares(s_k s_l) chain(ln) "')  ///
		part1(`"flexelasticity ln_p_k ln_p_l, cmdline("') local1("e(cmdline)")  ///
		part2(`") shares(s_k s_l) chain(ln) "')
end

*/


*	Version 1.0 15Aug2016 by Mead Over, Center for Global Devleopment
*		Based on Version 1.5 25Jul2017 of flexxmake_example.ado
*	Ver 1.1 31Jan 2019 Add the routine -run_ivregress-