;=================================================
; creates a netcdf file with a mask that is 1 within a certain distance off the coast and missing elsewhere
;=================================================
load "$NCARG_ROOT/lib/ncarg/nclscripts/csm/gsn_code.ncl"
load "$NCARG_ROOT/lib/ncarg/nclscripts/csm/gsn_csm.ncl"
load "$NCARG_ROOT/lib/ncarg/nclscripts/csm/contributed.ncl"
;=================================================
begin
;=================================================
; open file and read in data
;=================================================
; input needs to be land sea mask with land=1 and ocean=0
; global file will take long to process, choose subregion if you don't need a global mask
  ifile 		= addfile("/work/bm0764/m300265/test/TP04_lsm_SETA.nc","r")
	coast  	= ifile->var1
	lat		= ifile->lat
	lon		= ifile->lon

printVarSummary(coast)

; choose output directory
outdir = "/scratch/m/$USER/"

ofile = addfile(outdir + "mask_box_TP04_1deg.nc" ,"c")  ; open output netCDF file
;=================================================
; calculations
;=================================================

newcoast = coast
newcoast(:,:,:) = newcoast@_FillValue

; select distance off coast (every ocean cell closer to coast than this value will be marked)
range = 1

dim=dimsizes(coast)
imax = dim(1)-1
jmax = dim(2)-1

do i=0,imax
	do j=0,jmax
	if(coast(0,i,j).eq.0) then
		clat=lat(i,j)
		clon=lon(i,j)
		distmat = new((/dim(1),dim(2)/),"float")

			do ii=0,imax
				do jj=0,jmax
					if(coast(0,ii,jj).eq.1) then
						distmat(ii,jj)=gc_latlon(clat,clon,lat(ii,jj),lon(ii,jj),2,2)
					end if
				end do
			end do
			mindist=min(distmat)
			if(mindist.le.range) then
				newcoast(0,i,j)=1
			end if
	end if
	end do
end do


ofile->coast 	= newcoast
ofile->lon		= lon
ofile->lat		= lat