#! /bin/csh -f
#
#    send miriad (and fits) data to ds9
#
#  TODO:
#    some grepping now done wrong on solaris, output of imhead issue
#
#  You will need to have ds9 and the XPA tools in your searchpath.
#  Example URLs for Linux and Max from http://hea-www.harvard.edu/RD/ds9/
#  for ds9 version 4.12 and  xpa version 2.1.7b2 (as in april 2007)
# http://hea-www.harvard.edu/saord/download/ds9/linux/ds9.linux.4.12.tar.gz
# http://hea-www.harvard.edu/saord/download/ds9/linux64/ds9.linux64.4.12.tar.gz
# http://hea-www.harvard.edu/saord/download/ds9/macosxppc/ds9.macosxppc.4.12.tar.gz
# http://hea-www.harvard.edu/saord/download/ds9/macosxintel/ds9.macosxintel.4.12.tar.gz
# and
# http://hea-www.harvard.edu/saord/download/ds9/linux/xpa.linux.2.1.7b2.tar.gz  
# http://hea-www.harvard.edu/saord/download/ds9/linux64/xpa.linux64.2.1.7b2.tar.gz  
# http://hea-www.harvard.edu/saord/download/ds9/darwinppc/xpa.darwinppc.2.1.7b2.tar.gz  
# http://hea-www.harvard.edu/saord/download/ds9/darwinintel/xpa.darwinintel.2.1.7b2.tar.gz  
# 
# 
#
#  $Id$
#
set version="3.7 - 21-dec-2015 PJT"

if ($#argv == 0) then
    echo "Usage: $0 [-options] miriad_dataset [plane1] [plane2 ...]"
    echo "  Load selected planes, or a cube, from a miriad dataset into ds9"
    echo "  Options:"
    echo "      -minmax data_min data_max"
    echo "                  clipped display values from data_min to data_max"
    echo "      -movie"
    echo "                  start animating selected frames (pretty crude)"
    echo "      -wcs"
    echo "                  do not load WCS, even if it has one"
    echo "      -title <TITLE>"
    echo "                  use a matching ds9 as server (ds9 -title <TITLE>)"
    echo "                  or:   setenv DS9_TITLE foobar"
    echo "      -swap"
    echo "                  force little endian data instead of big"
    echo "      -debug"
    echo "                  add some debug options, keep temp files etc."
    echo ""
    echo "  Version $version"
    echo ""
    echo "  Be sure 'ds9' and the XPA routines are in your environment."
    echo "  You do need to start ds9 manually yourself."
    echo "  For XPA on machines that are not connected to the internet"
    echo "  you may need to use 'setenv XPA_METHOD local'"
    echo 
    echo ""
    exit 0
else
    echo "mirds9 : Version $version"
endif

#   "tail +2" needs this in new Linux distributions
setenv _POSIX2_VERSION 1

set scalelims=0
set movie=0
set wcs=0
set dowcs=1
set debug=0
set arch=bigendian

if ($?TMPDIR == 0) setenv TMPDIR /tmp

if ($?DS9_TITLE) then
  set title=$DS9_TITLE
else
  set title=ds9
endif

foreach dummy ($*)
  if ("$1" == "-minmax") then
    set datamin=$2
    set datamax=$3
    set scalelims=1
    shift argv; shift argv; shift argv;
  else if ("$1" == "-title") then
    set title=$2
    shift argv; shift argv
  else if ("$1" == "-movie") then
    set movie=1
    shift argv
  else if ("$1" == "-wcs") then
    set dowcs=0
    shift argv
  else if ("$1" == "-swap") then
    set arch=littleendian
    shift argv
  else if ("$1" == "-debug") then
    set debug=1
    shift argv
  else
    break
  endif
end

set name=$1
set dir=`pwd`

#   if the first char of the file is not / (absolute), make it absolute
#   since we don't know if ds9 had been started in the current directory
if (`echo $name | cut -c1` != '/') then
  echo Assuming dir=$dir
  set name=$dir/$1
endif

shift argv

set xpasets=(`which xpaset`)

if ($#xpasets > 1) then
  echo 'It does not look like your $path knows about xpaset.'
  echo 'You need the xpatools for this from SAO.'
  exit 0
endif

set wcsmsg=""
if (-d $name) then
    # assume it's a miriad data directory
    if (-e $name/visdata) then
       echo You cannot directly look at visdata, use uvimage to convert to an image
       exit 1
    endif
    if (! -e $name/image) then
       echo Warning: does not look like a MIRIAD data directory, continue at your own risk
    endif
    set ndim=`itemize in=$name/naxis | tail -1 | awk '{print $3}'`
    set n1=`itemize in=$name/naxis1 | tail -1 | awk '{print $3}'`
    set n2=`itemize in=$name/naxis2 | tail -1 | awk '{print $3}'`
    if ($ndim > 2) then
      set n3=`itemize in=$name/naxis3 | tail -1 | awk '{print $3}'`
    else 
      set n3=1
    endif
    set dims=(`itemize in=$name | grep naxis | tail +2 | awk '{print $3}'`)
    echo "Found $ndim-dim cube, ($dims) : maps $n1 x $n2 x $n3"
    if ($dowcs) then
        if ($debug) then
	  set wcs=$TMPDIR/saotng_$USER.wcs
        else
          set wcs=$TMPDIR/saotng_$$.wcs
        endif
        # work around an earlier bug by adding NAXIS=2
        # note this method isn't robust, it doesn't really check the header
        imhead in=$name key=ctype1 | egrep -q '(RA|DEC|LON)'
        if ($status == 0) then
 	   set wcsmsg="Astronomical WCS assumed"
	   set ascl=57.2957795131
        else
 	   set wcsmsg="Linear WCS assumed"
           set ascl=1
        endif
        echo "NAXIS  2" > $wcs
	if ($n3 > 1) echo "NAXIS  3" > $wcs
        echo CDELT1 `imhead in=$name key=cdelt1 | awk '{printf("%.10f\n",$1*'$ascl')}'` >> $wcs
        echo CDELT2 `imhead in=$name key=cdelt2 | awk '{printf("%.10f\n",$1*'$ascl')}'` >> $wcs
        echo CRVAL1 `imhead in=$name key=crval1 | awk '{printf("%.10f\n",$1*'$ascl')}'` >> $wcs
        echo CRVAL2 `imhead in=$name key=crval2 | awk '{printf("%.10f\n",$1*'$ascl')}'` >> $wcs
        echo CRPIX1 `imhead in=$name key=crpix1 | awk '{print $1}'` >> $wcs
        echo CRPIX2 `imhead in=$name key=crpix2 | awk '{print $1}'` >> $wcs
        echo CTYPE1 \'`imhead in=$name key=ctype1`\' >> $wcs
        echo CTYPE2 \'`imhead in=$name key=ctype2`\' >> $wcs
	set object=(`itemize in=$name/object |& tail -1 | awk -F= '{print $2}'`)
	if ($#object > 0) then
	    echo OBJECT \'$name:t_$object\'              >> $wcs
	else
	    echo OBJECT \'$name:t\'                      >> $wcs
	endif
        set llrot=(`itemize in=$name/llrot |& tail -1 | awk -F= '{print $2}'`)
        if ($#llrot > 0) then
	    # make sure it's not "llrota     (nonexistent data, 0 elements)"
	    set crota=`calc "$llrot*180/pi"`
	    echo CROTA: $llrot $crota
	    echo CROTA1 $crota >> $wcs
	    echo CROTA2 $crota >> $wcs
        endif
	if ($n3 > 1) then
	  # TODO: should check per axis if ascl=1 or 57....
	  set ascl=1
          echo CDELT3 `imhead in=$name key=cdelt3 | awk '{printf("%.10f\n",$1*'$ascl')}'` >> $wcs
          echo CRVAL3 `imhead in=$name key=crval3 | awk '{printf("%.10f\n",$1*'$ascl')}'` >> $wcs
          echo CRPIX3 `imhead in=$name key=crpix3 | awk '{print $1}'` >> $wcs
          echo CTYPE3 \'`imhead in=$name key=ctype3`\' >> $wcs
  	endif
    endif
else if (-f $name) then
   set type=`file $name | awk '{print $2}'`
	# work around another new  solaris/umd bug
   if ($name:e == fits) set type=FITS
   if ($name:e == FITS) set type=FITS
   if ($name:e == fts) set type=FITS
   if ($name:e == FTS) set type=FITS
   if ($name:e == fit) set type=FITS
   if ($name:e == FIT) set type=FITS
   echo Found type $type
   if ($type == FITS) then
   	# echo $name | xpaset $title fits $name
	cat $name | xpaset $title fits $name
   else if ($type == gzip) then
	# bit of a risk, not sure if it is really a FITS file ...
   	echo Displaying gz compressed $name FITS file
	zcat $name | xpaset $title fits $name
   else if ($type == compressed) then
	# bit of a risk, not sure if it is really a FITS file ...
   	echo Displaying Z compressed $name FITS file
        zcat $name | xpaset $title fits $name
   else if ($type == Nemo) then
        ccdfits $name - | xpaset $title fits $name
   else
	echo File type $type not understood by mirtng yet
	exit 1
   endif
   if ($scalelims) then
      xpaset -p $title scale limits $datamin $datamax
   endif
   exit 0
else 
   echo No file or directory with name $name found
   exit 1
endif


if ($#argv > 0) then
   set planes=($*)
else
   set planes=(1)
endif

set nplane=$#planes
set iplane=0

set frames=(`xpaget $title frame | awk '{print $1}'`)
if ($#frames > 1) then
   echo Warning: something is fishy here, maybe you have multiple ds9
   echo running.  Frames=$frames
endif
set frame=$frames

foreach p ($planes)
    @ iplane++

    set skip=`echo " $n1 $n2 $p " | awk '{printf("%d",($1*$2*($3-1)*4)+4)}'`
    set n3s=`expr $n3 + 1 - $p`

    echo $name $n1 $n2 $n3s -32 $skip 

    # cat $name/image | $pipe | xpaset $title array  $name/image\[xdim=$n1,ydim=$n2,zdim=$n3,bitpix=-32,skip=$skip\]
    # xpaset -p $title file array  $name/image\[xdim=$n1,ydim=$n2,zdim=$n3,bitpix=-32,skip=$skip,arch=$arch\]
    cat $name/image | xpaset $title array  $name/image\[xdim=$n1,ydim=$n2,zdim=$n3s,bitpix=-32,skip=$skip,arch=$arch\]


#    echo array $name/image $n1 $n2 -32 $skip | $pipe | xpaset $title

    if ($scalelims) then
      xpaset -p $title scale limits $datamin $datamax
    endif
    if ($wcs != 0) then
      # ??? echo autoflip true | xpaset $title   ??? does this work ?
      echo "Adding WCS from $wcs. $wcsmsg"
      cat $wcs | xpaset $title wcs replace
      # echo 'flip y | xpaset $title'
    endif

    #  Don't do a 'new' for the last frame

    if ($nplane > 1 && $iplane < $nplane) then
        @ frame++
        set frames=($frames $frame)
        echo frame $frame | xpaset $title
    endif
end

if ($nplane > 1) then
   echo frame $frames[1] | xpaset $title
endif

if ($movie) then
  echo 'Animate: you should probably toggle the "Blink Frames" in control panel on'
  echo Using frames: $frames
  echo 'tcl set blinkFrames "'$frames'"' | xpaset $title
endif

if ($debug) then
  echo Keeping $wcs
else
  if (! -e $wcs || -z $wcs) then
    echo "WARNING: Your $wcs file appear corrupted.  Full TMPDIR = $TMPDIR perhaps?"
  endif
  rm -f $wcs
endif

