# Build crosswalk from 1970 county groups to counties, by race
# Combines IPUMS USA's 1970 county-group composition table with NHGIS 1970 county-level race counts
# to produce race-specific population weights for splitting county groups across counties

dir.create('intermediate_data/1970_crosswalk/')

# IPUMS USA 1970 county-group composition (downloaded separately from IPUMS USA)
cg = read_csv('raw_data/1970_crosswalk/ipums_usa_1970_county_group_composition.csv')
cg$cg = str_pad(cg$`County Group (CNTYGP70)`, 5, pad = '0')

# 1970 county-level race population from NHGIS
pop = read_csv(paste0('raw_data/1970_crosswalk/',nhgis_1970pop_name,'_csv/',nhgis_1970pop_name,'_ds94_1970_county.csv'))
pop = mutate(pop, popo = CBW003 + CBW004 + CBW005)

dta = full_join(cg %>% select(cg, st = `State FIPS Code (STATEFIP)`, cnty = `County FIPS Code* (COUNTYFIP)`),
                pop %>% select(st = STATEA, cnty = COUNTYA, popt = CBC001, popw = CBW001, popb = CBW002, popo),
                by = c('st','cnty'))

# Adams County WI and Dillingham Census Area AK are missing from the NHGIS county file
# Fill in total population from Wikipedia and assign entirely to white given the small Black share in their county groups
# Adams County, WI: 9234 (https://en.wikipedia.org/wiki/Adams_County,_Wisconsin); county group 07705 is ~0.2% Black
# Dillingham Census Area, AK: 3485 (https://en.wikipedia.org/wiki/Dillingham_Census_Area,_Alaska); county group 14801 is ~0.3% Black
dta[dta$st == '55' & dta$cnty == '001','popt'] = 9234
dta[dta$st == '02' & dta$cnty == '070','popt'] = 3485
dta[dta$st == '55' & dta$cnty == '001','popw'] = 9234
dta[dta$st == '02' & dta$cnty == '070','popw'] = 3485
dta[dta$st == '55' & dta$cnty == '001','popb'] = 0
dta[dta$st == '02' & dta$cnty == '070','popb'] = 0
dta[dta$st == '55' & dta$cnty == '001','popo'] = 0
dta[dta$st == '02' & dta$cnty == '070','popo'] = 0

dta = filter(dta, !is.na(cg))

# Pivot to long format with one row per county-group x county x race
dta = dta %>% pivot_longer(cols = c(popw,popb,popo), values_to = 'pop')
dta$race = str_remove(dta$name,'pop')

# Compute race-specific and all-race population weights for splitting each county group across its constituent counties
dta = dta %>% group_by(cg, race) %>% mutate(pop_cg = sum(pop))
dta = dta %>% group_by(cg) %>% mutate(popt_cg = sum(pop))

dta$cwt = dta$pop / dta$pop_cg
dta$cwt_allraces = dta$popt / dta$popt_cg

write_csv(dta, 'intermediate_data/1970_crosswalk/xwalk_1970_cg_cnty_byrace.csv')
