#!/usr/bin/env dvo

macro go 
  if ($0 != 5)
    echo "USAGE: go (RA) (DEC) (RADIUS) (output)"
    break
  end

  # sleep 10
  catdir /data/ipp004.0/ipp/ippRefs/catdir.synth.grizyJHK
  
  $rmin = $1 - $3*dcos($2)
  $rmax = $1 + $3*dcos($2)
  $dmin = $2 - $3
  $dmax = $2 + $3
  if ($3 + $2 >= 90) 
    $rmin = 0.0
    $rmax = 360.0
    $dmax = 90.0
  end
  if ($3 + $2 <= -90.0) 
    $rmin = 0.0
    $rmax = 360.0
    $dmin = -90.0
  end

  if ($rmin < 0.0) 
    skyregion 0.0 $rmax $dmin $dmax
    avextract ra dec g_SYNTH r_SYNTH i_SYNTH z_SYNTH y_SYNTH J H K
    write $4 ra dec g_SYNTH r_SYNTH i_SYNTH z_SYNTH y_SYNTH J H K
  
    skyregion {$rmin + 360.0} 360.0 $dmin $dmax
    avextract ra dec g_SYNTH r_SYNTH i_SYNTH z_SYNTH y_SYNTH J H K
    write -append $4 ra dec g_SYNTH r_SYNTH i_SYNTH z_SYNTH y_SYNTH J H K
    return
  end

  if ($rmax > 360.0) 
    echo skyregion 0.0 {$rmax - 360.0} $dmin $dmax
    skyregion 0.0 {$rmax - 360.0} $dmin $dmax
    avextract ra dec g_SYNTH r_SYNTH i_SYNTH z_SYNTH y_SYNTH J H K
    write $4 ra dec g_SYNTH r_SYNTH i_SYNTH z_SYNTH y_SYNTH J H K
  
    echo skyregion $rmin 360.0 $dmin $dmax
    skyregion $rmin 360.0 $dmin $dmax
    avextract ra dec g_SYNTH r_SYNTH i_SYNTH z_SYNTH y_SYNTH J H K
    write -append $4 ra dec g_SYNTH r_SYNTH i_SYNTH z_SYNTH y_SYNTH J H K
    return
  end

  skyregion $rmin $rmax $dmin $dmax
  avextract ra dec g_SYNTH r_SYNTH i_SYNTH z_SYNTH y_SYNTH J H K
  write $4 ra dec g_SYNTH r_SYNTH i_SYNTH z_SYNTH y_SYNTH J H K
end

if ($SCRIPT) 
  if ($argv:n != 4)
    echo "USAGE: dvo2mass (RA) (DEC) (RADIUS) (output)"
    exit 2
  end

  go $argv:0 $argv:1 $argv:2 $argv:3
  exit 0
end
