************taxcost*********************

capture program drop taxcost
program define taxcost
	syntax [anything(name = grid id = "grid for wages and tax schedule")] [, replace_ext replace_int]

	display "begin taxcost: it will, by utilizing TAXSIM, find the utility loss of not reoptimizing with respect to changes in the tax system"
	display " "

	***************************
	*MANUALLY WRITING CPI-DATA: source: ftp://ftp.bls.gov/pub/special.requests/cpi/cpiai.txt
	***************************

	*Specify first and last year of data (to double check that all years in between are covered too)
	local cpistart = 1960
	local cpistop  = 2008

	*Give the cpi for eeach year in each decade
	local cpi60s "29.6 29.9 30.2 30.6 31 31.5 32.4 33.4 34.8 36.7"
	local cpi70s "38.8 40.5 41.8 44.4 49.3 53.8 56.9 60.6 65.2 72.6"
	local cpi80s "82.4 90.9 96.5 99.6 103.9 107.6 109.6 113.6 118.3 124"
	local cpi90s "130.7 136.2 140.3 144.5 148.2 152.4 156.9 160.5 163 166.6"
	local cpi00s "172.2 177.1 179.9 184 188.9 195.3 201.6 207.342 215.303"
	local cpi "`cpi60s' `cpi70s' `cpi80s' `cpi90s' `cpi00s'"

	*Assign macroes with the cpidata for each year
	local cpicnt=0
	foreach c of local cpi{
		local cpiyear = `cpistart'+`cpicnt'
		local cpi`cpiyear' = `c'
		local cpicnt=`cpicnt'+1
	}

	*Checking that the number of cpi's in the input matches the start and stop years.
	if `cpiyear'~=`cpistop'{
		disp "CPI-input in program is not complete, see contact info for help"
		disp "Program terminated"
		exit, clear
	}

	***************************
	*NECESSARY MANIPULATION OF INPUT BEFORE WE START
	***************************

	*Checking if there's given a grid, if not the default is 100
	local checkgrid = `grid'+1
	if `checkgrid'>1{
		display "Input grid: `grid'"
	}
	else{
		local grid = 100
		display "No grid specified, grid set to default ($100)"
	}

	local grid2 = `grid'/2
	display "Note that the wages used in the code will be rounded off to match the grid."
	display "One implication of this is that wages lower than $`grid2' will be dropped form the data."
	display "For more accurate results, specify a lower grid. The cost is that the program will take longer."

	*To check if any observations are rounded off to zero:
	local Nbefore=_N
	quietly drop if round(pwages,`grid')==0
	local Nchange=`Nbefore' - _N
	if `Nchange'~=0 display "`Nchange' observations were rounded off to zero and dropped from the data"

	*Checking what you want merge
	if "`replace_ext'"=="replace_ext" disp "Key variables for the extensive margin will be merged to your dataset"
	if "`replace_int'"=="replace_int" disp "Key variables for the intensive margin will be merged to your dataset"

	*Specify which margins you want to consider: names must match the code at the end.
	local margin ="int ext"

	*Saving the start data, taxcostid will be used to identify the observations in the end
	capture drop taxcostid
	gen taxcostid=_n
	sort taxcostid
	quietly save startdata, replace

	*Must-have variables
	local mustvars "postyear pwages"

	*"May-have"
	local mayvars "e mstat year state depx agex swages dividends otherprop pensions gssi transfers"
	local mayvars "`mayvars' rentpaid proptax otheritem ui depchild childcare"
	local mayvars "`mayvars' mortgage stcg ltcg"

	*Checking if the input data has all the vars specified in "mayvars"
	quietly describe, varlist
	*the local r(varlist) contains all the variable names in the dataset
	local inset "`r(varlist)'"

	*See if the variable is contained in the dataset
	confirm variable `mustvars'

	* Local of missing mayhaves:
	foreach may of local mayvars {
	capture confirm variable `may'
	if _rc {
			if "`may'"=="year"{
				gen `may'=postyear-3
				display "Variable `may' not given, `may' set to be 3 years before the postyear"
			}
			if "`may'"=="e"{
				gen `may'=1
				display "Variable `may' not given, `may' = 1 generated (the elasticity)"
			}
			if "`may'"=="mstat"{
				gen `may'=1
				display "Variable `may' not given, `may' = 1 generated (= single person)"
			}
			if "`may'"~="e" & "`may'"~="mstat" & "`may'"~="year"{
				gen `may'=0
				display "Variable `may' not given, `may' = 0 generated"
			}
		}
	}

	*Create the group-variable: every group will have identical TAXSIM-vars (except for pwages)
	local groupchar "year postyear state mstat depx agex swages dividends otherprop pensions gssi transfers"
	local groupchar "`groupchar' rentpaid proptax otheritem ui depchild childcare"
	local groupchar "`groupchar' mortgage stcg ltcg"

	egen group=group(`groupchar')

	*Find the number of groups
	egen numgroups=max(group)
	local numgroups = numgroups

	display " "
	display "Dataset consists of `numgroups' different groups."
	display "From here: consider one group at the time.."
	display " "

	quietly save inputdata, replace

	*********************************
	*CONSIDER ONE GROUP AT THE TIME:*
	*********************************

	forvalues num = 1/`numgroups' {

		*************************
		*INPUT: Preparing the data we'll use
		*********************

		display "-Group `num': call on taxsim9"

		use inputdata, clear
		quietly keep if group == `num'

		*Prepare variables that we need to use TAXSIM
		local preyear = year
		local postyear = postyear
		local characts = "state mstat depx agex swages dividends otherprop pensions gssi transfers"
		local characts = "`characts' rentpaid proptax otheritem ui depchild childcare mortgage stcg ltcg"
		foreach char of local characts{
			local `char' = `char'
		}

		*Get the inflation-rate
		*In case the years used are outside what's covered:
		if `postyear'>`cpistop'{
			*Assume inflation of 2%
			local inflation=0.02
			local startextra = `cpistop'+1
			local previous = `cpi`cpistop''
			forvalues i = `startextra'/`postyear'{
				local cpi`i' = `previous'*(1+`inflation')
				local previous = `cpi`i''
			}
			disp " "
			disp "CPI-data lacks for `startextra'-`postyear': an annual inflation rate of `inflation' is assumed for this period."
			disp "CPI-data needs update: see help for contact info."
		}

		*If preyear is zero
		if `preyear'==0 local cpi0 = `cpi`postyear''

		*Find accumulated gross inflation
		local cpi = `cpi`postyear''/`cpi`preyear''

		*Other variables we'll need
		local years = "`preyear' `postyear'"'

		*If preyear is set to zero, we'll perform the "zero-calculations"
		if `preyear'==0	local years = "`postyear'"

		*Need to round off pwages to match the tax schedule wages.
		quietly replace pwages = round(pwages,`grid')

		*Variable to limit the maximum wage considered in the tax schedule
		egen maxpwages = max(pwages)
		local maxobs=2*maxpwages

		*Resulting size of taxschedule:
		local sizeschedule = `maxobs'/`grid'

		*Creating preinput; a file with the wages and their corresponding elasticities
		*This will identify the input wages in the tax schedule + import the elasticities we want to use and the id
		keep pwages e taxcostid
		sort pwages
		quietly save preinput, replace

*---------------------------------------
*3) TAX SCHEDULE: Creating the tax schedule for both pre- and postyear.
*----------------------------------------

		*The schedules will have the size of `maxobs'/`grid'

		*Create the input to send through TAXSIM for each year in "years": i.e., just the postyear if preyear==0
		*Notice that we only use TAXSIM once, this is to maximize efficiency
		foreach ye of local years{
			clear
			quietly set obs `sizeschedule'
			*Put in pre or postyear
			gen year=`ye'
			*and put inn the taxpayer characteristics
			foreach char of local characts{
				gen `char' = ``char''
			}
			*The stepsize in the tax schedule is what you gave as grid
			gen pwages=_n*`grid'
			quietly save preschedule-`ye', replace
		}

		capture append using preschedule-`preyear'

		gen taxsimid = _n

		*Use TAXSIM9
		capture noisily taxsim9, replace
		if _rc continue

		drop taxsimid

		* Put tax rates in decimal form
		quietly replace ficar = ficar/100
		quietly replace frate = frate/100
		quietly replace srate = srate/100

		*Find the post-tax earnings:
		gen earnings = pwages - fica - fiitax - siitax

		*Save year-specific tax schedules: again; only one will be saved if preyear==0
		foreach ye of local years {
			preserve
			quietly keep if year == `ye'
			sort pwages
			quietly save taxschedule-`ye', replace
			restore
		}

		*--------------------------
		*KINKPOINTS AND MTR's
		*--------------------------

		*Locate all the tax brackets and their corresponding kinkpoints
		foreach ye of local years {
			use taxschedule-`ye', clear
			gen MTR = ficar + frate + srate
			*Create groups for all the different MTRs
			egen sameMTR = group(MTR)
			sort pwages
			quietly gen kink=abs(sameMTR-sameMTR[_n+1])
			*Only keep the last wage within each bracket
			quietly keep if kink>0
			local Nmtr`ye' = _N
			*Since we the last wage isn't a kink but just the limit
			quietly replace pwages=0 in `Nmtr`ye''
			quietly replace earnings=0 in `Nmtr`ye''
			*Create locals to use for later
			forvalues i=1/`Nmtr`ye''{
				local MTR`ye'`i' = MTR[`i']
				local kink`ye'`i' = pwages[`i']
				local kinkearn`ye'`i' = earnings[`i']
			}
		}

		*-----------------------
		*ADD ZERO-LINE
		*-------------------------

		foreach ye of local years{
			use taxschedule-`ye', clear
			local makezero = _N + 1
			quietly set obs `makezero'
			quietly replace year=`ye' in `makezero'
			quietly replace pwages=0 in `makezero'
			quietly replace fiitax=0 in `makezero'
			quietly replace siitax=0 in `makezero'
			quietly replace fica=0 in `makezero'
			quietly replace ficar=0 in `makezero'
			quietly replace frate=0 in  `makezero'
			quietly replace srate=0 in  `makezero'
			foreach char of local characts{
				quietly replace `char' = ``char'' in  `makezero'
			}
			quietly replace earnings=0 in `makezero'

			sort pwages
			quietly save taxschedule-`ye', replace
		}

***********************************************
*PREYEAR CALCULATIONS
***********************************************

		local year=`preyear'

*----------------------------
*4) FIND PRODUCTIVITY PARAMETERS
*----------------------------

		*preinput contains the inputwages and the elasticities you want to use
		use preinput, clear

		*Get the tax rates
		*Either from the tax schedule:
		if `year'>0{
			sort pwages
			quietly merge pwages using taxschedule-`year'
			quietly drop if taxcostid==.
			drop _merge
		}
		*or the necessary variables as from the tax schedule, but all taxes set to zero:
		if `year'==0{
			gen ficar=0
			gen frate=0
			gen srate=0
		}

		* Find appropriate productivity parameter, noting that with this utility function
		* pre-tax earnings = m * (1-MTR)^(1/k)
		gen m = pwages/(1-ficar-frate-srate)^e

		*Keep the variables we'll need for the non-convex fix
		keep pwages m e taxcostid
		ren pwages inwage
		sort taxcostid
		quietly save fixinput, replace

*----------------------------------
*5) THE NON-CONVEX FIX
*----------------------------------

		use fixinput, clear

		gen maxwage = 0
		gen maxutility = 0
		gen kink = 0

		*Loop over all different kinkpoints and all different MTR's (each value of i will give a pair of values):
		*Note than some of the pwages will exceed the limit of the tax schedule and thus get a "missing value"
		*as its utility. This doesn't matter because it's just for very low MTR's, which aren't relevant.
		if `year'>0{
			forvalues i=1/`Nmtr`year''{
				*Get the MTR and kinkpoint for bracket i
				gen mtr = `MTR`year'`i''
				gen kinkwage = `kink`year'`i''
				*Find the tangent wage
				gen pwages = round(m*(1-mtr)^e,`grid')
				sort pwages
				*Load the implied tax rate for the tangent wage
				quietly merge pwages using taxschedule-`year'
				quietly drop if taxcostid==.
				drop _merge
				*Need a seperate MTR-variable to make the if-code work..
				quietly gen MTR = frate+srate+ficar
				*Find utility with the tangent wage and with the kink wage
				quietly gen utility = earnings -m*((pwages/m)^(1+(1/e)))/(1+(1/e))
				quietly gen kinkutility = `kinkearn`year'`i'' -m*((kinkwage/m)^(1+(1/e)))/(1+(1/e))

				*First; choose the kinkutility if it's larger than previous max;
				quietly replace maxwage=kinkwage if kinkutility>maxutility
				quietly replace kink=1 if kinkutility>maxutility
				quietly replace maxutility = kinkutility if kinkutility>maxutility

				*Or choose the tangent solution, provided that the MTR used to find the tangent actually equals the MTR corresponding
				*to the tangent wage.
				quietly replace maxwage=pwages if utility>=maxutility & MTR==mtr
				quietly replace kink=0 if utility>=maxutility & MTR==mtr
				quietly replace maxutility = utility if utility>=maxutility & MTR==mtr

				keep maxutility maxwage kink m e inwage taxcostid
			}
		}

		*No need for non-convex fix if we assume the tax rates are zero:
		if `year'==0{
			quietly replace maxwage=inwage
		}

*--------------------
*6) OUTPUT FOR PREYEAR: prepare variables we'll need for later
*--------------------

		ren maxwage pwages
		drop maxutility

		*inputchange will give you the difference between the input wage and the wage used (after non-convex fix)
		gen inputchange = (pwages - inwage)
		drop inwage

		*Get the tax rates from the right tax schedule
		if `year'>0{
			sort pwages
			quietly merge pwages using taxschedule-`year'
			quietly drop if taxcostid==.
			drop _merge
		}
		*or just create a zero tax schedule
		if `year'==0{
			gen year=0
			foreach char of local characts{
			gen `char' = ``char''
			}
			gen fiitax=0
			gen siitax=0
			gen fica=0
			gen ficar=0
			gen frate=0
			gen srate=0
			gen earnings=pwages
		}

		*Generate the variables we'll need for the postperiod calculations
		*Note that pwages_noopt is rounded off to match the tax schedule. m_post is found from the rounded off pwages_noopt since,
		*if the taxes are unchanged, the optimal wage we locate in the tax schedule should equal to pwages_noopt. If we'd just used
		*m*cpi we would risk not getting this because of round-off.
		gen pwages_noopt = round(pwages*`cpi',`grid')
		gen m_post = pwages_noopt/(1-frate-srate-ficar)^e

		*Calculate utility = fixed cost of joining the labor market (relevant for extensive margin)
		*this is the cost making the worker indifferent between working and staying out of the labor force in
		*the post reform year, given no tax changes.
		gen fixedcost = earnings*`cpi' - m_post*((pwages*`cpi'/m_post)^(1+(1/e)))/(1+(1/e))

		* Label variables
		lab var year "Pre-Tax Change Year"
		lab var m "Productivity parameter: Pre-Year"
		lab var pwages "Income: Pre-Year"
		lab var earnings "After-tax earnings: Pre-Year"
		lab var kink "Wage located at a kink: Pre-Year"
		lab var siitax "State Income Tax: Pre-Year"
		lab var srate "State Income Tax Marginal Rate: Pre-Year"
		lab var fiitax  "Federal Income Tax: Pre-Year"
		lab var fica "OASDI and HI Payroll Tax: Pre-Year"
		lab var frate "Federal income marginal rate: Pre-Year"
		lab var ficar "SS marginal rate: Pre-Year"

		sort taxcostid
		quietly save predata, replace

		*Create the dataset with only pwages_noopt (ROUNDED OFF), m and e.
		keep pwages_noopt m_post e fixedcost taxcostid
		ren pwages_noopt pwages
		ren m_post m
		sort taxcostid
		quietly save postinput, replace

*********************************
*POSTPERIOD CALCULATIONS
*********************************

		local year=`postyear'

*----------------------------
*7) IF YOU DON'T REOPTIMIZE
*----------------------------

		use postinput, clear

		*Get the tax rates
		sort pwages
		quietly merge pwages using taxschedule-`year'
		quietly drop if taxcostid==.
		drop _merge

		*Find utility
		gen utility = earnings - m*((pwages/m)^(1+(1/e)))/(1+(1/e))

		*Rename variables to make sure they don't overlap when merging with postyear calcs;
		local renvars = "utility pwages earnings fiitax siitax fica frate srate ficar"
		foreach ren of local renvars{
			ren `ren' `ren'_noopt
		}

		* Label variables
		lab var pwages_noopt "Post-tax income when not optimizing"
		lab var earnings_noopt "Post-tax earnings when not optimizing"
		lab var utility_noopt "Utility when not optimizing"
		lab var siitax_noopt "State Income Tax: Post-Year for Non-Optimizers"
		lab var srate_noopt "State Income Tax Marginal Rate: Post-Year for Non-Optimizers"
		lab var fiitax_noopt  "Federal Income Tax: Post-Year for Non-Optimizers"
		lab var fica_noopt "OASDI and HI Payroll Tax: Post-Year for Non-Optimizers"
		lab var frate_noopt "Federal income marginal rate: Post-Year for Non-Optimizers"
		lab var ficar_noopt "SS marginal rate: Post-Year for Non-Optimizers"

		sort taxcostid
		quietly save noopt, replace

*-----------------------
*8) IF YOU REOPTIMIZE
*-----------------------

		use postinput, clear

		drop pwages
		gen maxwage = 0
		gen maxutility = 0
		gen kink = 0

		forvalues i=1/`Nmtr`year''{
			*Get the necessary "kink-variables"
			gen mtr = `MTR`year'`i''
			gen kinkwage = `kink`year'`i''
			*Find the tangent wage
			gen pwages = round(m*(1-mtr)^e,`grid')
			sort pwages
			*Load the implied tax rates for the tanget wages
			quietly merge pwages using taxschedule-`year'
			quietly drop if m==.
			drop _merge
			*NOTE: some wages might exceed the max of the tax schedule, but this is only for very low MTR's and doesn't matter; the
			*wage-MTR combination is not feasible anyways.
			*Need a seperate MTR-variable to make the if-code work..
			quietly gen MTR = frate+srate+ficar
			*Find utility with the tangent wage and with the kink wage
			quietly gen utility = earnings -m*((pwages/m)^(1+(1/e)))/(1+(1/e))
			quietly gen kinkutility = `kinkearn`year'`i'' -m*((kinkwage/m)^(1+(1/e)))/(1+(1/e))

			*FINDING MAX FOR INTENSIVE MARGIN
			*First; choose the kinkutility if it's larger than previous max;
			quietly replace maxwage=kinkwage if kinkutility>maxutility
			quietly replace kink=1 if kinkutility>maxutility
			quietly replace maxutility = kinkutility if kinkutility>maxutility

			*Or choose the tangent solution, provided that the MTR used to find max == the resulting rate after max.
			quietly replace maxwage=pwages if utility>=maxutility & MTR==mtr
			quietly replace kink=0 if utility>=maxutility & MTR==mtr
			quietly replace maxutility = utility if utility>=maxutility & MTR==mtr

			keep maxutility maxwage kink m e taxcostid fixedcost
		}

		ren maxwage pwages
		ren maxutility utility
		quietly save postdata-int, replace

		*FINDING MAX FOR EXTENSIVE MARGIN
		quietly replace utility=utility-fixedcost
		quietly replace pwages = 0 if utility<0
		quietly replace kink = 0 if utility<0
		quietly replace utility= 0 if utility<0

		quietly save postdata-ext, replace

*------------------
*ADDING THE NO-OPT RESTULTS
*------------------

		foreach ma of local margin{
			use postdata-`ma', clear

			*Get the tax rates
			sort pwages
			quietly merge pwages using taxschedule-`year'
			quietly drop if taxcostid==.
			drop _merge

			*And import the results from no optimization
			sort taxcostid
			quietly merge taxcostid using noopt
			drop _merge

			*Subtract fixedcost from utility at the extensive margin
			quietly if "`ma'"=="ext" replace utility_noopt = utility_noopt - fixedcost*(pwages_noopt>0)

			quietly save postdata-`ma', replace
		}

*--------------------------------
*10) CLEAN-UP/CREATING THE FINAL OUTPUT
*--------------------------------

		foreach ma of local margin{
			use postdata-`ma', clear

			*Reload variables to keep in the output
			ren year postyear
			ren m m_post
			ren kink kink_reopt
			gen cpi=`cpi'

			*Rename variables to make sure they don't overlap when merging with postyear calcs;
			local renvars = "utility pwages earnings fiitax siitax fica frate srate ficar"
			foreach ren of local renvars{
				ren `ren' `ren'_reopt
			}

			*Load the results for the preyear
			sort taxcostid
			quietly merge taxcostid using predata
			drop _merge

			* Label variables
			lab var postyear "Post Tax-Change Year"
			lab var m_post "Productivity parameter: Post-Year"
			lab var state "State (SOI codes)"
			lab var mstat "Marital Status (1. single 2. joint 3. head of household 8. Dependent taxpayer)"
			lab var depx "Number of Dependent Exemptions (including childern of all ages)"
			lab var agex "Number of taxpayers over 65 years of age"
			lab var swages "Wage and salary income of Spouse (include self-employment)"
			lab var dividends "Dividend income (corporate dividends only for 2003 on"
			lab var otherprop "Other property income"
			lab var pensions "Taxable pensions"
			lab var gssi "Gross Social Security Income"
			lab var transfers "Other non-taxable transfer Income"
			lab var rentpaid "Rent Paid"
			lab var proptax "Property and other taxes paid (except state income or post-2003 formula)"
			lab var otheritem "Itemized deductions other than mortage, state income tax and local prop tax"
			lab var childcare "Child care expences"
			lab var ui "Unemployment compensation recieved"
			lab var depchild "Number of Dependent Children under age 17 (for child credit, not more than depx"
			lab var mortgage "Mortgage Interest and other decuctions not a preference for the AMT"
			lab var stcg "Short Term Capital Gains or losses"
			lab var ltcg "Long Term Capital Gains or losses"
			lab var pwages_reopt "Post-Year Pre-Tax Income if Reoptimizing"
			lab var cpi "Inflation Rate between Pre- and Post-Years"
			quietly lab var fixedcost "Fixed Cost of Working"
			lab var e "Elasticity of labor supply"
			lab var kink_reopt "Reoptimized wage located at a kink"
			lab var inputchange "%-points change made to the (rounded off) inputwage given by the user"

			*Generate the MTR's
			gen MTR_pre = frate+srate+ficar
			gen MTR_post_noopt = frate_noopt+srate_noopt+ficar_noopt
			gen MTR_post_reopt = frate_reopt+srate_reopt+ficar_reopt
			lab var MTR_pre  "MTR in `preyear'"
			lab var MTR_post_noopt "MTR in `postyear' if not reoptimizing"
			lab var MTR_post_reopt "MTR in `postyear' after reoptimizing"

			* Create variables on average tax rates
			quietly gen ATR_pre = (fiitax + fica+siitax)/pwages
			quietly replace ATR_pre=0 if ATR_pre==.
			quietly gen ATR_post_noopt = (fiitax_noopt + fica_noopt + siitax_noopt)/pwages_noopt
			quietly replace ATR_post_noopt=0 if ATR_post_noopt==.
			quietly gen ATR_post_reopt = (fiitax_reopt + fica_reopt + siitax_reopt)/pwages_reopt
			quietly replace ATR_post_reopt=0 if ATR_post_reopt==.
			lab var ATR_pre "Average Tax Rate in Pre-year"
			lab var ATR_post_noopt "Average Tax Rate in Post-year for Non-Optimizers"

			*For the extensive margin: set utility_noopt=0 if the ATR fell, but not if ATR increased
			*This is the same as assuming that you werent working before if your ATR fell, but that you were working if it increases
			quietly if "`ma'"=="ext"{
				replace utility_noopt = 0 if ATR_pre>=ATR_post_noopt
			}

			*Define denominator for percentage calculations
			if `preyear'>0{
                gen denominator = pwages_reopt*(1-ATR_post_reopt)
			}
			*Change the denominator for zero-calcs
			if `preyear'==0{
				quietly gen denominator = earnings_noopt
			}

			*Rename pwages for the preperiod to avoid confusion with those not rounded off.
			ren pwages pwages_round

			* Find dollar gain
			gen dollargain_`ma' = utility_reopt - utility_noopt
			lab var dollargain_`ma' "Cost of Not Reoptimizing ($)"

			* If dollargain is negative, it is because of round-off
			quietly if dollargain_`ma'<0 replace dollargain_`ma'=0

			* Create variable for percentage of income gained by reoptimizing
			quietly gen percentgain_`ma' = round(dollargain_`ma'/denominator*100,.01)
			lab var percentgain_`ma' "Cost of Not Reoptimizing/Post-Year Post-Tax Earnings"

			*Find difference in wages and earnings
			gen delta_TI_`ma' = pwages_reopt - pwages_noopt
			quietly if "`ma'"=="ext" & ATR_pre > ATR_post_noopt replace delta_TI_`ma' = pwages_reopt
			lab var delta_TI "Change in TI required to reoptimize"

			*Drop variables we don't need
			drop earnings earnings_noopt earnings_reopt utility_reopt utility_noopt fixedcost denominator

			*Order the variables
			#delimit;
			order year postyear taxcostid `characts' cpi e m m_post
			pwages_round inputchange kink fiitax siitax fica frate srate ficar
			pwages_noopt fiitax_noopt siitax_noopt fica_noopt frate_noopt srate_noopt ficar_noopt
			pwages_reopt kink_reopt fiitax_reopt siitax_reopt fica_reopt frate_reopt srate_reopt ficar_reopt
			MTR_pre MTR_post_noopt MTR_post_reopt
			ATR_pre ATR_post_noopt ATR_post_reopt
			dollargain percentgain delta_TI;
			#delimit cr

			sort taxcostid
			* For first go-through for both extensive and intensive margins, must create a new dataset; otherwise, append
			if `num'==1{
				quietly saveold taxcost_out_`ma', replace
			}
			if `num'>1{
				append using taxcost_out_`ma'
				sort taxcostid
				quietly saveold taxcost_out_`ma', replace
			}
		}
		foreach ye of local years{
			capture erase preschedule-`ye'.dta
			capture erase taxschedule-`ye'.dta
		}
	}

	*Erase all the temporary dta-files
	capture erase inputdata.dta
	capture erase preinput.dta
	capture erase taxsim_out.dta
	capture erase fixinput.dta
	capture erase predata.dta
	capture erase postinput.dta
	capture erase noopt.dta
	foreach ma of local margin{
		capture erase postdata-`ma'.dta
	}

	display "Final output is saved as taxcost_out_ext.dta and taxcost_out_int.dta"
	display " "

	use startdata, clear

	local extmerge = 0
	local intmerge = 0

	*Merging the desired output to the users dataset
	if "`replace_ext'"=="replace_ext"{
		sort taxcostid
		quietly merge taxcostid using taxcost_out_ext, keep(ATR_pre ATR_post_noopt dollargain_ext percentgain_ext delta_TI_ext)
		quietly drop _merge
		disp "Key variables for the extensive margin have been merged to your dataset"
		local extmerge = 1
	}
	if "`replace_int'"=="replace_int"{
		sort taxcostid
		quietly merge taxcostid using taxcost_out_int, keep(MTR_pre MTR_post_noopt dollargain_int percentgain_int delta_TI_int)
		quietly drop _merge
		disp "Key variables for the intensive margin have been merged to your dataset"
		local intmerge = 1
	}

	if `extmerge'==1 | `intmerge'==1{
		sort taxcostid
		drop taxcostid
		disp " "
		disp "To merge more variables from the output files, type the following:"
		disp "generate taxcostid = _n"
		disp "sort taxcostid"
		disp "merge taxcostid using taxcost_out_XX"
		disp " "
		disp "where XX equals either int or ext, depending on which margin you want the results for."
		disp "Don't merge both at the same time, that will cause some variables to overlap."
	}

	if `extmerge'==0 & `intmerge'==0{
		sort taxcostid
		drop taxcostid
		disp "To merge the taxcost results to the current dataset, run the commands below.
		disp " "
		disp "generate taxcostid = _n"
		disp "sort taxcostid"
		disp "merge taxcostid using taxcost_out_XX"
		disp " "
		disp "where XX equals either int or ext, depending on which margin you want the results for."
		disp " "
		disp "Use the options replace_int and replace_ext to avoid merging by hand."
		disp "These can be used either by themselves or at the same time."
	}
	capture erase startdata.dta

end

*END OF PROGRAM