#!/bin/sh

# Run the real pix2wcs script using the gaia_swish binary.

# The gaia_swish binary runs the gaiaMain.tcl script as soon as it
# starts, so the only way we can stop GAIA from running up is by
# replacing the commands that gaiaMain invokes.

# Need a directory to put all the files we need. Use /tmp.
script_dir="${TMPDIR:-/tmp}/pix2wcs${USER}$$"
if test -f ${script_dir}; then
    \rm -r -f ${script_dir}
fi
mkdir -p ${script_dir}

# Local directory is GAIA_LIBRARY so that we can pick up Tcl code.
GAIA_LIBRARY=${script_dir}
export GAIA_LIBRARY

# Make sure we remove this all on exit.
trap 'rm -r -f ${script_dir};exit' 0 1 2 3 9 15

# Add the intermediary files we need.
# 

# - tclIndex
cat > ${script_dir}/tclIndex <<EOF
# Tcl autoload index file, version 2.0
# This file is generated by the "auto_mkindex" command
# and sourced to set up indexing information for one or
# more commands.  Typically each line is a command that
# sets an element in the auto_index array, where the
# element name is the name of a command and the value is
# a script that loads the command.

set auto_index(::gaia::Gaia) [list source [file join \$dir start_script.tcl]]
set auto_index(::gaia::Gaia::startGaia) [list source [file join \$dir start_script.tcl]]
set auto_index(::gaia::GaiaImageName) [list source [file join \$dir GaiaImageName.tcl]]
set auto_index(::gaia::GaiaProperties) [list source [file join \$dir GaiaProperties.tcl]]
set auto_index(::gaia::GaiaProperties::instance) [list source [file join \$dir GaiaProperties.tcl]]
EOF

# - GaiaImageName.tcl
cat > ${script_dir}/GaiaImageName.tcl <<EOF
itcl::class gaia::GaiaImageName {
   constructor {args} {
      eval configure \$args
   }
   destructor  {
   }
   public method fullname { {fitsext 1} } {
      return \$imagename
   }
   public method diskfile {} {
      return \$imagename
   }
   public method slice {} {
      return \$slice_
   }
   public method fitsext {} {
      return \$fitsext_
   }
   public method fitshdunum {} {
      return 0
   }
   public method path {} {
      return \$path_
   }
   public method type {} {
      return \$type_
   }
   public method ndfname {} {
      return \$imagename
   }
   public method exists {} {
      return 1
   }
   public method absolute {} {
   }
   public method protect {} {
   }
   public variable imagename {} {
   }
   protected variable fullname_ {}
   protected variable diskfile_ {}
   protected variable slice_ {}
   protected variable fitsext_ {}
   protected variable fitshdu_ 0
   protected variable path_ {}
   protected variable type_ {.sdf}
}
EOF

cat > ${script_dir}/GaiaProperties.tcl <<EOF
itcl::class gaia::GaiaProperties {

   #  Singleton entry point:
   #  ----------------------
   proc instance {} {
      return [GaiaProperties ::\#auto]
   }

   constructor {args} {
   }

   destructor {
   }
   public method restore_properties {} {
   }
   protected method read_file_ {filename} {
   }
   public method save_properties {} {
   }
   public method set_property {key value} {
   }
   public method set_named_property {name key value} {
   }
   public method get_property {key} {
      return {}
   }
   public method get_named_property {name key} {
      return {}
   }
   public method unset_property {key} {
   }
   public method unset_named_property {name key} {
   }
   public method get_named_keys {name} {
      return {}
   }
   public method get_unnamed_key {name fullkey} {
      return {}
   }
   public method apply_named_properties {object name} {
   }
   private common instance_ {}
}
EOF

# - pix2wcs.real
cat > ${script_dir}/pix2wcs.real <<EOF
#   Name:
#      pix2wcs
#
#   Purpose:
#      Convert a file of pixel coordinate to world coordinates.
#
#   Usage:
#      pix2wcs image pixel_coordinates_file world_coordinates file
#
#   Description:
#      This command transforms a list of pixel coordinate stored in a
#      file into world coordinates. The format of the pixel file
#      should be:
#
#        x y
#        x y
#
#      The output file is proper tab-table which can be displayed
#      in GAIA.
#
#   Authors:
#      Peter W. Draper (PDRAPER):
#
#   History:
#      28-APR-1999 (PDRAPER):
#         Original version.
#-
#.

global argc
global argv

#  There may be confusion over arguments. 
#  Remove "-file", "-file_types {*}" and "-hdu {*}"
set n [lsearch -exact \$argv "-file"]
if { \$n != -1 } {
   lvarpop argv \$n
}
set n [lsearch -exact \$argv "-file_types"]
if { \$n != -1 } {
   lvarpop argv [expr \$n+1]
   lvarpop argv \$n
}
set n [lsearch -exact \$argv "-hdu"]
if { \$n != -1 } {
   lvarpop argv [expr \$n+1]
   lvarpop argv \$n
}
set argc [llength \$argv]

#  Get the image, if not given.
if { \$argc == 0 } {
   puts -nonewline "Image: "
   flush stdout
   gets stdin image
} else {
   set image [lindex \$argv 0]
}

#  Get names of files.
if { \$argc <= 1  } {
   puts -nonewline "XY coordinate file: "
   flush stdout
   gets stdin infile
} else {
   set infile [lindex \$argv 1]
}
if { ! [file exists \$infile] } {
   puts stderr "Sorry file: \$infile, does not exist"
   exit 1
}

if { \$argc <= 2 } {
   puts -nonewline "Output file: "
   flush stdout
   gets stdin outfile
} else {
   set outfile [lindex \$argv 2]
}

#  Open the XY positions file and the output file.
if { [catch "open \$infile r" infile] } {
   puts stderr "Failed to open input file: \$infile (\$infile)"
   exit 1
}
if { [catch "open \$outfile w" outfile] } {
   puts stderr "Failed to open output file: \$infile (\$outfile)"
   exit 1
}

#  Open the image.
set rtdimage [image create rtdimage -file \$image]
if { ! [info exists rtdimage] } {
   puts stderr "Failed to open image: \$image"
   exit 1
}

#  Add the initialising commands.
puts \$outfile "QueryResult"
puts \$outfile "ra_col: 1"
puts \$outfile "dec_col: 2"
puts \$outfile "symbol: INDEX {circle {} {} {} {\\\$INDEX} {}} {4.0 {}}"

puts \$outfile "INDEX\t RA\t DEC\t XPOS\t YPOS"
puts \$outfile "-----\t --\t ---\t ----\t ----"

#  Loop over the input file reading all the elements and writing them
#  back out with RA/Dec and TAB separated fields.
set id 0
while { [gets \$infile line] > -1 } {
   set nitems [llength \$line]
   if { \$nitems > 0 } {
      foreach {x y} \$line {
         incr id
         \$rtdimage convert coords \$x \$y image ra dec wcs
         puts \$outfile "\$id\t \$ra\t \$dec\t \$x\t \$y"
      }
   }
}
close \$infile
close \$outfile
exit
EOF

#- start_script
echo >  ${script_dir}/start_script.tcl 'itcl::class gaia::Gaia {'
echo >> ${script_dir}/start_script.tcl '   public proc startGaia {} {'
echo >> ${script_dir}/start_script.tcl "      source ${script_dir}/pix2wcs.real"
echo >> ${script_dir}/start_script.tcl '   }'
echo >> ${script_dir}/start_script.tcl '}'

#  Now run up script.
$GAIA_DIR/gaia_swish $*

exit