#!/usr/bin/env grass-script
#!/bin/bash -xe
# greenland is (mostly) missing in the mn75 (7.5arcsec) data
# but island and and the south is there
# idea is to use 7.5 data where possible and fall back to 30 arcsec
# data where needed
# => build a mask from 7.5 data
# unfortunately it didn't work out that well

#echo "$@"
P="$1"
r.in.gdal -e input="$P/$3" output=mn75
r.info mn75
r.in.gdal input="$P/$2" output=mn30
r.info mn30
g.region rast=mn30
r.resamp.stats -w input=mn75 output=mn75at30 method=maximum
r.info mn75at30

r.mapcalc mask="if(mn75at30>0,0,null())"
r.buffer input=mask output=mask2 distances=1000

# unfortunately we now have a gap in the south of Greenland
# close that gap by painting a box into the mask with extent:
# -45,60 to -42,60.01

{ cat <<EOF
ORGANIZATION: 
DIGIT DATE:   
DIGIT NAME:   karme
MAP NAME:     
MAP DATE:     Wed Sep 26 14:31:05 2012
MAP SCALE:    1
OTHER INFO:   
ZONE:         0
MAP THRESH:   0.000000
VERTI:
B  5 1
 -45 60
 -42 60
 -42 60.01
 -45 60.01
 -45 60
 1     1         
C  1 1
 -44 60.005
 1     2         
EOF
} | v.in.ascii output=box format=standard
v.info box
v.to.rast input=box output=box use=val
r.info box
r.mapcalc mask='if(isnull(mask2)||(!isnull(box)),0,1)'
r.info mask

r.mapcalc res="if(mask,null(),mn30)"

r.out.gdal input=res output="$P/$4" format=GTiff type=Int16 createopt="TILED=YES,COMPRESS=DEFLATE,ZLEVEL=7,PREDICTOR=2"

