clean_all:

	make clean dir=input
	make clean dir=output



clean:

	rm -rf ${dir};
	mkdir ${dir};



download:
	curl 'http://mapserv.wxinfoicebox.com/cgi-bin/mapserv?map=/data/mapserver/mapfiles/eventimage.map&SRS=EPSG%3A4326&SERVICE=WMS&REQUEST=GetMap&VERSION=1.1.1&LAYERS=snow&STYLES=&FORMAT=image%2Ftiff&TRANSPARENT=true&HEIGHT=2000&WIDTH=2000&PERIOD=24&BBOX=-85.5,31.0,-67.0,47.5' > input/snow.tif;
	curl 'http://www.weather.gov//source/erh/hydromet/stormTotalv3_24.point.snow.kml' > input/snow.kml;
	curl 'http://digital.weather.gov/wms.php?LAYERS=ndfd.conus.totalsnowamt&FORMAT=image%2Ftiff&TRANSPARENT=TRUE&VERSION=1.3.0&VT=2017-02-10T06%3A00&EXCEPTIONS=INIMAGE&SERVICE=WMS&REQUEST=GetMap&STYLES=&CRS=EPSG%3A3857&BBOX=-9517816.46282,3632749.14338,-7458405.88315,6024072.11937&WIDTH=2000&HEIGHT=2000' > input/forecast.tif;



georeference:

	gdal_translate -of GTiff -a_ullr -9517816.46282 6024072.11937 -7458405.88315 3632749.14338 -a_srs EPSG:3857 input/forecast.tif output/forecast_3857.tif;
	gdalwarp -t_srs "EPSG:4326" output/forecast_3857.tif output/forecast_4326.tif;



preprocess:
	cd input; \
		gdal_calc.py -A snow.tif -B snow.tif -C snow.tif --A_band=1 --B_band=2 --C_band=3 --outfile=../output/integered.tif --calc="A+B+C"



polygonize:
	gdal_polygonize.py output/integered.tif -f "ESRI Shapefile" output/snowtotals.shp;
	gdal_polygonize.py output/forecast_4326.tif -f "ESRI Shapefile" output/forecast.shp;



presimplify:
	shp2json output/snowtotals.shp | \
	ndjson-split 'd.features' | \
	ndjson-map -r d3 'd.properties.DN = d3.scaleOrdinal().domain([0,64,229,167,11,142,208,247,192,148,169,216]).range([0,0.1,1,2,4,6,8,10,15,20,25,30])(d.properties.DN), d' | \
	ndjson-reduce 'p.features.push(d), p' '{type: "FeatureCollection", name: "allSnowtotals", features: []}' \
	> output/allSnowtotals.geojson;
	cd output; \
		ogr2ogr -f "GeoJSON" snowtotals-valid.geojson allSnowtotals.geojson \
		-dialect sqlite -sql "select ST_MakeValid(geometry) as geometry, * from OGRGeoJSON where DN > 0"
	cd output; \
		mapshaper snowtotals-valid.geojson snap -dissolve DN -o snowtotals.geojson;



reports:
	npm run reports
	cd output; \
		cat reports.json | \
		in2csv -f json | \
		csvjson --lat lat --lon lon > reports.geojson;



topojsonize:
	geo2topo output/reports.geojson output/snowtotals.geojson | \
		toposimplify -s 0.00000001 -f | \
		topoquantize 10000 \
		> output/snowtotals.topojson;



deploy:
	cp output/snowtotals.topojson src/assets/snowtotals.topojson



input: clean_all download



output:
	make clean dir=output
	make georeference
	make preprocess
	make polygonize
	make presimplify
	make reports
	make topojsonize
	make deploy



all: input output