'reinit'

nc_file = 'ucomp.1981-2000.climatology.nc'
nx = 144 ; dlon = 2.5
ny = 90 ; dlat = 2.0
zz = 10
var = ucomp

'sdfopen 'nc_file
'set x 1 'nx
'set y 1 'ny
'set z 'zz
'set t 1'
'define varmask = const('var',-1,-a)'

'q ctlinfo'
undef_rec = sublin(result,3) ; undef_value = subwrd(undef_rec,2)
say
say result
say 'undef_value = 'undef_value
say

pause()

* ref: http://grads.iges.org/grads/gadoc/gradcomdsetdefval.html

  ylat = -45
while ( ylat <= 10 )
  xlon = 300
while ( xlon <= 360 )
  'set lon 'xlon
  'set lat 'ylat
  'q dims'
  xrec = sublin(result,2) ; xx = subwrd(xrec,9)
  yrec = sublin(result,3) ; yy = subwrd(yrec,9)
  if( xx > 0 & xx <= nx )
  if( yy > 0 & yy <= ny )
    'set x 'xx
    'set y 'yy
    'd 'var
    say 'xx = 'xx
    say 'yy = 'yy
    var_value = subwrd(result,4)
    say 'var_value = 'var_value
    if( var_value != undef_value )
      'set defval varmask 'xx' 'yy' 1'
    endif
  endif
  endif
  xlon=xlon+dlon
endwhile
  xlon = 0
while ( xlon <= 20 )
  'set lon 'xlon
  'set lat 'ylat
  'q dims'
  xrec = sublin(result,2) ; xx = subwrd(xrec,9)
  yrec = sublin(result,3) ; yy = subwrd(yrec,9)
  if( xx > 0 & xx <= nx )
  if( yy > 0 & yy <= ny )
    'set x 'xx
    'set y 'yy
    'd 'var
    say 'xx = 'xx
    say 'yy = 'yy
    var_value = subwrd(result,4)
    say 'var_value = 'var_value
    if( var_value != undef_value )
      'set defval varmask 'xx' 'yy' 1'
    endif
  endif
  endif
  xlon=xlon+dlon
endwhile
  ylat=ylat+dlat
endwhile

'c'
'set x 1 'nx
'set y 1 'ny
'set z 'zz
'set t 1'
'set gxout shaded'
'set clevs -10 -5 0 5 10 15 20 25 30 35'
'd maskout('var',varmask)'
'run cbar 0.7'

pause()

'c'
'set x 1 'nx
'set y 1 'ny
'set z 'zz
'set t 1'
'set gxout shaded'
'd maskout('var',varmask)-'var
'run cbar 0.7'

************************************************************************
*
function pause()
*
* Pauses till ENTER key is pressed 
*
 say
 say '*********************************'
 say 'Press "ENTER" key to continue...'
 say '*********************************'
 pull answer
*
return
*
************************************************************************