#!/bin/csh -f
#
#   Name: ncgm2gif
#
#   Description: Converts an NCGM file to a GIF file (single or multi frame)
#
#   This script should be invoked with:
#
#       ncgm2gif [options] ncgm_filename
#      
#   If the file "ncgm_filename" is of the form "xxx.ncgm", then the
#   resultant GIF file will be called "xxx.gif".  Otherwise, the GIF
#   file will be called "ncgm_filename.gif"
#
#   The basic conversion steps taken are:
#
#     NCGM -> individual NCGMs (if needed) -> raster file -> GIF
#
#   Several pieces of software are required to run this script:
#
#       1. NCAR Graphics (ctrans and ncgmstat)
#
#       2. imconv (part of Image Tools)
#          file://ftp.sdsc.edu/pub/sdsc/graphics/imtools/
#   OR
#          convert (part of ImageMagick)
#          http://www.imagemagick.org/script/index.php
#
#       3. gifmerge - only needed if you are planning to create multi-frame
#                     GIF files (written by Rene K. Muller and based on
#                    "txtmerge" written by Mark Podlipec)
#
#          http://the-labs.com/GIFMerge/
#
#          OR
#
#          gifsicle - written by Eddie Kohler and available at: 
#
#          http://www.lcdf.org/~eddietwo/gifsicle/
#
#   Options:
#       -i             prompt user whenever a file might be overwritten.
#                      The default is to overwrite files.
#
#       -res {w}x{h}   specifies output resolution in pixels where
#                      {w} and {h} are integers specifying width and height
#                      in pixels. Default is 500x500.
#
#       -loop N        For a multi-framed NCGM, indicates how many times
#                      you want the GIF animation to be run beyond the 
#                      initial run. N=0 indicates infinite looping, N=1
#                      indicates the animation will be run twice, etc.
#                      The default is no looping.
#                      
#       -delay N       If looping is turned on (see '-loop' above), indicates
#                      the delay between frames in units of 1/100th of a
#                      second. The default is N=50 (0.5 seconds between
#                      frames).
#
#      -nomerge        Do not merge into one animation GIF file. Leave as
#                      separate GIF files. 
#
#      -useconvert     If doing a single GIF, the default is to 
#                      use imconv.  If imconv is not available, and
#                      convert is, then use this option to indicate you
#                      want to use convert instead.
#
#      -usegifsicle    If doing an animation GIF, the default is to 
#                      use gifmerge.  If gifmerge is not available, and
#                      gifsicle is, then use this option to indicate you
#                      want to use gifsicle instead.
#
#   Other options to add later:
#      1. Changing raster output used
#      2. "-clean" option
#      3. Allow to select which frames you want
#         (like Tom's ncgmgrab script)
#      4. Allow to change output file name
#
#   Example usages:
#
#     1. To convert a single-frame NCGM called "gmeta" to a GIF file:
#
#          ncgm2gif gmeta
#
#     2. To convert a multi-frame NCGM called "example.ncgm" to a multi-
#        framed GIF file that is 200x200 pixels:
#
#          ncgm2gif -res 200x200 example.ncgm
#
#     3. To convert a multi-frame NCGM called "example.ncgm" to a multi-
#        framed GIF file, and have the animation run 4 times with a delay
#        of 20/100 seconds between each frame:
#
#          ncgm2gif -loop 3 -delay 20 example.ncgm
#
#

if ($#argv < 1) goto usage

#************#
#            #
# Initialize #
#            #
#************#
set wresltn = 500
set hresltn = 500
set rasfmt = sun
set clobberfiles
set merge
set loopstr = ""
set delay = 50
set gif_files

#************************************************#
#                                                #
# For individual GIFs, user must choose whether  #
# using convert or imconv.  imconv is the        #
# default.                                       #
#                                                #
# Only one of these can be set!                  #
#                                                #
#************************************************#
set useimconv
unset useconvert

#************************************************#
#                                                #
# For animated GIFs, user must choose whether    #
# using gifmerge or gifsicle.  gifmerge is the   #
# default.                                       #
#                                                #
# Only one of these can be set!                  #
#                                                #
#************************************************#
set usegifmerge
unset usegifsicle

while ($#argv > 0)
  switch ($1)
    case "-i":
      shift
      unset clobberfiles
    breaksw

    case "-loop":
      shift
      set loops = $1
      if ($loops < 0) then
        echo ""
        echo "  ncgm2gif: The loop value must be an integer >= 0."
        echo ""
        exit 1
      endif
      set loopstr = ($loopstr "-l$loops")
      shift
    breaksw

    case "-delay":
      shift
      set delay = $1
      if ($delay <= 0) then
        echo ""
        echo "  ncgm2gif: The delay must be an integer greater than 0."
        echo ""
        exit 1
      endif
      if ($?usegifmerge) then
        set loopstr = ($loopstr "-$delay")
      else
        set loopstr = ($loopstr "-d$delay")
      endif
      shift
    breaksw

    case "-res":
      shift
      set wresltn = `expr $1 : '\(.*\)x.*'`
      set hresltn = `expr $1 : '.*x\(.*\)'`
      shift
    breaksw

    case "-nomerge":
      unset merge
      shift
    breaksw

    case "-useconvert":
      unset useimconv
      set useconvert
      shift
    breaksw

    case "-usegifsicle":
      unset usegifmerge
      set usegifsicle
      shift
    breaksw

    case "-*":
      echo "$0 : Unknown option <$1>"
      exit 1
      breaksw

    default:
    set ncgmfile = $1
    shift
    breaksw
  endsw
end

#
# Make sure we have one of the necessary convert 
# tools.
#

if ($?useconvert) then
  set converttool  = "convert"
  set converttool2 = "imcomv"
else
  set converttool  = "imconv"
  set converttool2 = "convert"
endif

which $converttool >&! /dev/null
if ($status != 0) then
  echo ""
  echo "    '$converttool' not found. Will try '$converttool2'..."
  which $converttool2 >&! /dev/null
  if ($status != 0) then
    echo "    Cannot find either '$converttool' or '$converttool2'"
    echo "    One of these tools is necessary to create the GIF file."
    echo ""
    exit 1
  else
    echo "    '$converttool2' found! Will use this."
    set converttool = $converttool2
  endif
endif

if ($?usegifsicle) then
  set mergetool = "gifsicle"
else
  set mergetool = "gifmerge"
endif

if (! -f $ncgmfile) then
  echo ""
  echo "  ncgm2gif: $ncgmfile doesn't exist"
  echo ""
  exit 1
endif

if ($ncgmfile:e == "ncgm") then
  set rootname = $ncgmfile:r
else
  set rootname = $ncgmfile
endif


#**********************#
#                      #
# Initialize some more #
#                      #
#**********************#
set rasfile = $rootname.$rasfmt
set giffile = $rootname.gif

#****************************************#
#                                        #
# Make sure we have all the apps we need #
#                                        #
#****************************************#
#set apps = (ctrans ncgmstat imconv gifmerge gifsicle)
#
#echo ""
#echo "    Checking to be sure we have all the necessary applications..."
#
#foreach app($apps)
#  echo -n "        $app..."
#  which $app >& /dev/null
#  if ($status != 0) then
#    echo "not found"
#    echo ""
#    exit 1
#  endif
#  echo "okay"
#end
#

#***************************#
#                           #
# Count frames in NCGM file #
#                           #
#***************************#
set nframes = `ncgmstat -c $ncgmfile`

if ($nframes <= 0) then 
  echo ""
  echo "  ncgm2gif:   Not measuring any frames in '$ncgmfile'."
  echo "              Are you sure it's a valid NCGM?"
  echo ""
  exit 1
endif

if (! $?clobberfiles) then
#***************************#
#                           #
# Check to be sure we don't #
# overwrite existing files. #
#                           #
#***************************#
  if (-f $rasfile) then
    echo ""
    echo "    '$rasfile' already exists."
    echo -n "    Overwrite? (y/n) (n) "
    set answer = $<
    if ("$answer" != "y" && "$answer" != "Y") then
      exit 1
    endif
  endif

  if (-f $giffile) then
    echo ""
    echo "    '$giffile' already exists."
    echo -n "    Overwrite? (y/n) (n) "
    set answer = $<
    if ("$answer" != "y" && "$answer" != "Y") then
      exit 1
    endif
  endif
endif

if ($nframes > 1) then
#*********************************************#
#                                             #
# Split NCGM file into individual ncgm files. #
#                                             #
# Files will be called 'med001.ncgm',         #
# 'med002.ncgm', etc.                         #
#                                             #
#*********************************************#
  echo ""
  echo "    Splitting your $nframes-frame NCGM into individual NCGMs..."
  med -e "1,$ split $nframes $rootname" $ncgmfile
else
  /bin/cp $ncgmfile {$rootname}001.ncgm
endif

#************************************#
#                                    #
# Convert NCGM(s) to raster file(s). #
#                                    #
#************************************#
echo ""
echo "    Converting your NCGM(s) to GIF..."
@ num = 1
while ( $num <= $nframes )
  set newnum = `echo $num | awk '{printf("%03d\n",$1)}'`
  ctrans -d $rasfmt -res ${wresltn}x${hresltn} $rootname{$newnum}.ncgm >! $rasfile
  if ($status != 0) then
    echo ""
    echo "  ncgm2gif:  The 'ctrans' command failed. Please check your NCGM"
    echo "             to be sure it is valid."
    echo ""
    exit 1
  endif

#*****************************#
#                             #
# Convert raster file to GIF. #
#                             #
#*****************************#
#  imscale -infile $rasfile  -xsize $wresltn -ysize $hresltn -outfile 2.$rasfile
#  /bin/mv 2.$rasfile $rasfile
  if ($converttool == "convert") then
    convert $rasfile $rootname{$newnum}.gif
  else
    imconv -infile $rasfile -outfile $rootname{$newnum}.gif
  endif
  if ($status != 0) then
    echo ""
    echo "  ncgm2gif: The $converttool command failed."
    echo ""
    exit 1
  endif
  /bin/rm $rasfile $rootname{$newnum}.ncgm
  set gif_files = ($gif_files $rootname{$newnum}.gif)
  @ num+=1
end

if ($nframes == 1) then
  /bin/mv {$rootname}001.gif $giffile
else
  if ($?merge) then
    $mergetool $loopstr $gif_files >! $giffile
    /bin/rm $gif_files
  endif
endif

echo ""
echo "    'ncgm2gif' completed successfully."
echo "     GIF file is named '$giffile'."
echo ""

exit 0

#***************************#
#                           #
# ncgm2gif usage statement #
#                           #
#***************************#
usage:
echo ""
echo "    usage: ncgm2gif [options] ncgm_filename"
echo ""
echo "    Options:"
echo ""
echo "    -i"
echo "    -loop N"
echo "    -delay N"
echo "    -res {w}x{h}"
echo ""
exit 1


