GENERATED_FILES = \
	ok-counties.json

all: $(GENERATED_FILES)

.PHONY: clean all

clean:
	rm -rf -- $(GENERATED_FILES) build

build/gz/%.tar.gz:
	mkdir -p $(dir $@)
	curl 'http://dds.cr.usgs.gov/pub/data/nationalatlas/$(notdir $@)' -o $@.download
	mv $@.download $@

build/shp/us/counties-unfiltered.shp: build/gz/countyp010_nt00795.tar.gz

build/shp/us/%.shp:
	rm -rf $(basename $@)
	mkdir -p $(basename $@)
	tar -xzm -C $(basename $@) -f $<
	for file in $(basename $@)/*; do chmod 644 $$file; mv $$file $(basename $@).$${file##*.}; done
	rmdir $(basename $@)

# remove water counties (e.g., Great Lakes)
build/shp/us/counties.shp: build/shp/us/counties-unfiltered.shp
	rm -f $@
	ogr2ogr -f 'ESRI Shapefile' -where "FIPS NOT LIKE '%000'" $@ $<

build/shp/%/counties.shp: build/shp/us/counties.shp
	mkdir -p $(dir $@)
	rm -f $@
	ogr2ogr -f 'ESRI Shapefile' -where "STATE = '`echo $* | tr a-z A-Z`'" $@ $<

ok-counties.json: build/shp/ok/counties.shp
	node_modules/.bin/topojson \
		-o $@ \
		--q0=0 \
		--simplify=1 \
		--projection='d3.geo.mercator().center([-97.5350, 35.4822]).scale(6.5 * 960).translate([960 / 1.55, 500 / 2]).precision(0)' \
		--id-property=+FIPS \
		-- $(filter %.shp,$^)
