

if("`c(os)'"=="Windows"){
	local tableSaveDir = "Tables\"
	local plotSaveDir = "Plots\NeighborAnalysis\"
	local pythonSaveDir = "PythonScripts\"
}
else{
	local tableSaveDir = "Tables/"
	local plotSaveDir = "Plots/NeighborAnalysis/"
	local pythonSaveDir = "PythonScripts/"
}


//Execute python script to find the appropriate changes in treated neighbor states and add variable "delNeighborNoSafety"
python script "`pythonSaveDir'addNeighboringStateVariables.py"

//Establish Control Variable Sets
local Spec1Controls = "ib51.stateGroup ib1995.year c.normYear#i.stateGroup asinhMetroPop asinhNonMetroPop asinhMetroInc asinhNonMetroInc logrealmeangasprice logemployment loglicenseddrivers logrealstategdp logroadmileage"
local Spec2Controls = "`Spec1Controls'"
local Spec3Controls = "`Spec2Controls' i.vmtDummyExtSpec3"
local Spec4Controls = "`Spec2Controls' i.vmtDummyExtSpec4"

//Establish Cluster Variable
local clusterVar = "stateGroup"

//Absorb Vars are always time and state fixed effects
local absorbVars = "ib51.stateGroup ib1995.year"

//Event Study Table format
local fmtEventStudy = `"cells(b(fmt(3) star) se(par fmt(3))) keep(*neighborDummy*  *shiftedBoundRelYear*) nocon label compress longtable mtitles("\makecell{No \\ DSCs}" "\makecell{Documented \\ DSCs}" "\makecell{Suspected \\ DSCs}" "\makecell{Potential \\ DSCs}") starlevels(* 0.1 ** 0.05 *** 0.01) addnotes("* p \textless 0.1, ** p \textless 0.05, *** p \textless 0.01" "Note: All models include state and year fixed effects as well as state-level time trends." "All models cluster standard errors  by state.")"'



//Add Dummy Variables for Spec2 state Event Study
//Define +- bounds for event study
local bound = 6
//Define Bounds
local lowerBound = -`bound'
local upperBound = `bound'

//Define the relative time period that we will use
local relYear = -1

//Determine the dummy index of the relative year
local relIndex = 1-`lowerBound'+`relYear'

//Generate New Variable
gen boundRelYear = yearrelativeend
//Enforce Bounds
replace boundRelYear = `lowerBound' if boundRelYear<=`lowerBound'
replace boundRelYear = `upperBound' if boundRelYear>=`upperBound'
replace boundRelYear = . if yearrelativeend==.

//Create shifted Bounds for the other events (neighboring states changing their policy)
gen shiftedBoundRelYear = boundRelYear - `lowerBound'+1
replace shiftedBoundRelYear = `relIndex' if boundRelYear==.

qui levelsof delNeighborNoSafety
foreach numNeighborState in `r(levels)'{
	if(`numNeighborState'>0){
		qui gen shiftedBoundRelYear`numNeighborState' = `relYear'
		qui levelsof statecode if delNeighborNoSafety==`numNeighborState'
		di "`numNeighborState'"
		foreach tempSC in `r(levels)'{
			qui sum year if statecode=="`tempSC'" & delNeighborNoSafety==`numNeighborState'
			qui replace shiftedBoundRelYear`numNeighborState' = year-`r(min)' if statecode=="`tempSC'"
			qui replace shiftedBoundRelYear`numNeighborState' = `lowerBound' if shiftedBoundRelYear`numNeighborState'<`lowerBound' & statecode=="`tempSC'"
			qui replace shiftedBoundRelYear`numNeighborState' = `upperBound' if shiftedBoundRelYear`numNeighborState'>`upperBound' & statecode=="`tempSC'" 
			qui replace shiftedBoundRelYear`numNeighborState' = shiftedBoundRelYear`numNeighborState' +`bound'+1 if statecode=="`tempSC'"
		}
		qui replace shiftedBoundRelYear`numNeighborState' = `relIndex' if shiftedBoundRelYear`numNeighborState'==`relYear'
	}
}

xtset stateGroup year
gen diffDelNeighborNoSafety = d.delNeighborNoSafety

levelsof statecode if diffDelNeighborNoSafety==2

foreach tempSC in `r(levels)'{
	sum delNeighborNoSafety if statecode=="`tempSC'" & diffDelNeighborNoSafety==2
	local indFromCopy = `r(mean)'
	local indToCopy = `indFromCopy'-1
	replace shiftedBoundRelYear`indToCopy' = shiftedBoundRelYear`indFromCopy' if statecode=="`tempSC'"
}


local finIndex = `upperBound'-`lowerBound'+1
forvalues ind = 1(1)`finIndex'{
	di "`ind'"
	gen neighborDummy`ind' = 0
	
	
	qui sum delNeighborNoSafety
	local numInd = `r(max)'
	
	qui levelsof statecode
	foreach tempSC in `r(levels)'{
		forvalues nInd = 1(1)`numInd'{
			qui sum delNeighborNoSafety if statecode=="`tempSC'"
			if(`nInd'<=`r(max)'){
				qui replace neighborDummy`ind'=neighborDummy`ind'+1 if shiftedBoundRelYear`nInd'==`ind' & statecode=="`tempSC'"
			}
		}
	}
	local trueT = `ind'-`bound'-1
	
	if(`trueT'==`upperBound'){
		label var neighborDummy`ind' "Neighbor Event: t $\geq$ `trueT'"
	}
	else if(`trueT'==`lowerBound'){
		label var neighborDummy`ind' "Neighbor Event: t $\leq$ `trueT'"
	}
	else{
		label var neighborDummy`ind' "Neighbor Event: t = `trueT'"
	}
	
	
}
//Define main event labels
label define shiftedBoundRelYear 1 "Main Event: t $\leq$ -6" 2 "Main Event: t=-5" 3 "Main Event: t=-4" 4 "Main Event: t=-3" 5 "Main Event: t=-2" 6 "Main Event: t=-1" 7 "Main Event: t=0" 8 "Main Event: t=1" 9 "Main Event: t=2" 10 "Main Event: t=3" 11 "Main Event: t=4" 12 "Main Event: t=5" 13 "Main Event: t $\geq$ 6"
label values shiftedBoundRelYear shiftedBoundRelYear

// drop neighborDummy`relIndex' to enforce baseline
replace neighborDummy`relIndex' = 1

// //Label values


// //Plot formats
local plotFormat = `"vertical yline(0) keep(*neighborDummy*) omitted baselevels xlabel(1 "≤-6" 2 "-5" 3 "-4" 4 "-3" 5 "-2" 6 "-1" 7 "0" 8 "1" 9 "2" 10 "3" 11 "4" 12 "5" 13 "≥6", angle(0)) xtitle("Years Relative to Neighbor Removal")"'

local plotFormat = `"vertical yline(0) keep(*neighborDummy*) drop(neighborDummy1 neighborDummy`finIndex') omitted baselevels xlabel(1 "-5" 2 "-4" 3 "-3" 4 "-2" 5 "-1" 6 "0" 7 "1" 8 "2" 9 "3" 10 "4" 11 "5", angle(0)) xtitle("Years Relative to Neighbor Removal") ytitle("Proportional Change in VMT")"'


//Run regressions and output results

local title = "VMT Spillover Analysis Event Study Results \label{atab:VMTSpillover`upperBound'}"


//Neighbor Analysis
//Spec1 specification
reghdfe logvmt ib`relIndex'.shiftedBoundRelYear neighborDummy1-neighborDummy`finIndex' `Spec1Controls', vce (cluster `clusterVar')  absorb(`absorbVars')
coefplot, `plotFormat' title("Neighbor Event Coefficients") name("Spec1SpilloverVMT`upperBound'") graphregion(color(white)) plotregion(color(white))
graph export "`plotSaveDir'NeighborStateSpec1VMT`upperBound'.png", replace name("Spec1SpilloverVMT`upperBound'")
eststo Spec1
// //Spec2 specification
reghdfe logvmt ib`relIndex'.shiftedBoundRelYear neighborDummy1-neighborDummy`finIndex' `Spec2Controls', vce (cluster `clusterVar')  absorb(`absorbVars')
coefplot, `plotFormat' title("Neighbor Event Coefficients") name("Spec2SpilloverVMT`upperBound'") graphregion(color(white)) plotregion(color(white))
graph export "`plotSaveDir'NeighborStateSpec2VMT`upperBound'.png", replace name("Spec2SpilloverVMT`upperBound'")
eststo Spec2 
// //Spec2 specification
reghdfe logvmt ib`relIndex'.shiftedBoundRelYear neighborDummy1-neighborDummy`finIndex' `Spec3Controls', vce (cluster `clusterVar')  absorb(`absorbVars')
coefplot, `plotFormat' title("Neighbor Event Coefficients") name("Spec3SpilloverVMT`upperBound'") graphregion(color(white)) plotregion(color(white))
graph export "`plotSaveDir'NeighborStateSpec3VMT`upperBound'.png", replace name("Spec3SpilloverVMT`upperBound'")
eststo Spec3
// //Spec2 specification
reghdfe logvmt ib`relIndex'.shiftedBoundRelYear neighborDummy1-neighborDummy`finIndex' `Spec4Controls', vce (cluster `clusterVar')  absorb(`absorbVars')
coefplot, `plotFormat' title("Neighbor Event Coefficients") name("Spec4SpilloverVMT`upperBound'") graphregion(color(white)) plotregion(color(white))
graph export "`plotSaveDir'NeighborStateSpec4VMT`upperBound'.png", replace name("Spec4SpilloverVMT`upperBound'")
eststo Spec4


local plotFormat = `"vertical yline(0) keep(*shiftedBoundRelYear*) omitted baselevels xlabel(1 "≤-6" 2 "-5" 3 "-4" 4 "-3" 5 "-2" 6 "-1" 7 "0" 8 "1" 9 "2" 10 "3" 11 "4" 12 "5" 13 "≥6", angle(0)) xtitle("Years Relative to Treatment Year") ytitle("Proportional Change in Total VMT")"'

local plotFormat = `"vertical yline(0) keep(*shiftedBoundRelYear*) drop(1.shiftedBoundRelYear 13.shiftedBoundRelYear) omitted baselevels xlabel(1 "-5" 2 "-4" 3 "-3" 4 "-2" 5 "-1" 6 "0" 7 "1" 8 "2" 9 "3" 10 "4" 11 "5", angle(0)) xtitle("Years Relative to Inspection Removal") ytitle("Proportional Change in Total VMT")"'

//Main Analysis Comparison
//Spec1 specification
reghdfe logvmt ib`relIndex'.shiftedBoundRelYear `Spec1Controls', vce (cluster `clusterVar')  absorb(`absorbVars')
eststo Spec1Main
coefplot Spec1 Spec1Main, `plotFormat' title("Main Event Coefficients") name("Spec1ComparisonVMT`upperBound'") p1(label("With Neighbor Coefficients")) p2(label("Without Neighbor Coefficients")) graphregion(color(white)) plotregion(color(white)) legend(rows(2) ring(0) pos(7) size(*.8))
graph export "`plotSaveDir'NeighborStateMainComparisonSpec1VMT`upperBound'.png", replace name("Spec1ComparisonVMT`upperBound'")
// //Spec2 specification
reghdfe logvmt ib`relIndex'.shiftedBoundRelYear  `Spec2Controls', vce (cluster `clusterVar')  absorb(`absorbVars')
eststo Spec2Main
coefplot Spec2 Spec2Main, `plotFormat' title("Main Event Coefficients") name("Spec2ComparisonVMT`upperBound'") p1(label("With Neighbor Coefficients")) p2(label("Without Neighbor Coefficients")) graphregion(color(white)) plotregion(color(white)) legend(rows(2) ring(0) pos(7) size(*.8))
graph export "`plotSaveDir'NeighborStateMainComparisonSpec2VMT`upperBound'.png", replace name("Spec2ComparisonVMT`upperBound'")

// //Spec2 specification
reghdfe logvmt ib`relIndex'.shiftedBoundRelYear  `Spec3Controls', vce (cluster `clusterVar')  absorb(`absorbVars')
eststo Spec3Main
coefplot Spec3 Spec3Main, `plotFormat' title("Main Event Coefficients") name("Spec3ComparisonVMT`upperBound'") p1(label("With Neighbor Coefficients")) p2(label("Without Neighbor Coefficients")) graphregion(color(white)) plotregion(color(white)) legend(rows(2) ring(0) pos(7) size(*.8))
graph export "`plotSaveDir'NeighborStateMainComparisonSpec3VMT`upperBound'.png", replace name("Spec3ComparisonVMT`upperBound'")

// //Spec2 specification
reghdfe logvmt ib`relIndex'.shiftedBoundRelYear  `Spec4Controls', vce (cluster `clusterVar')  absorb(`absorbVars')
eststo Spec4Main
coefplot Spec4 Spec4Main, `plotFormat' title("Main Event Coefficients") name("Spec4ComparisonVMT`upperBound'") p1(label("With Neighbor Coefficients")) p2(label("Without Neighbor Coefficients")) graphregion(color(white)) plotregion(color(white)) legend(rows(2) ring(0) pos(7) size(*.8))
graph export "`plotSaveDir'NeighborStateMainComparisonSpec4VMT`upperBound'.png", replace name("Spec4ComparisonVMT`upperBound'")


graph combine Spec1ComparisonVMT`upperBound' Spec1SpilloverVMT`upperBound', ycommon commonscheme graphregion(color(white)) plotregion(color(white)) // title("No DSCs Spec.")
graph export "`plotSaveDir'NeighborStateJointSpec1VMT`upperBound'.png", replace
graph combine Spec2ComparisonVMT`upperBound' Spec2SpilloverVMT`upperBound', ycommon commonscheme graphregion(color(white)) plotregion(color(white)) // title("Documented DSCs Spec.")
graph export "`plotSaveDir'NeighborStateJointSpec2VMT`upperBound'.png", replace
graph combine Spec3ComparisonVMT`upperBound' Spec3SpilloverVMT`upperBound', ycommon commonscheme graphregion(color(white)) plotregion(color(white)) // title("Suspected DSCs Spec.")
graph export "`plotSaveDir'NeighborStateJointSpec3VMT`upperBound'.png", replace
graph combine Spec4ComparisonVMT`upperBound' Spec4SpilloverVMT`upperBound', ycommon commonscheme graphregion(color(white)) plotregion(color(white)) // title("Potential DSCs Spec.")
graph export "`plotSaveDir'NeighborStateJointSpec4VMT`upperBound'.png", replace

if("`c(os)'"=="Windows"){
	local tableSaveDir = "Tables\Spillover\"
	local plotSaveDir = "Plots\NeighborAnalysis\"
	local pythonSaveDir = "PythonScripts\"
}
else{
	local tableSaveDir = "Tables/Spillover/"
	local plotSaveDir = "Plots/NeighborAnalysis/"
	local pythonSaveDir = "PythonScripts/"
}

//Output table
local saveFile = "`tableSaveDir'"+"NeighborAnalysisVMT`upperBound'.tex"

esttab Spec1 Spec2 Spec3 Spec4 using "`saveFile'", `fmtEventStudy' title(`title') replace
