#! /bin/csh -f 
# Last edited on 2008-02-04 18:26:48 by stolfi

set usage = "$0 [-gray] [-test] [-show] DIRECTORY SIZE..." 

# Converts a PPM image (or a pair of PPm images) to GIF format, color or grayscale,
# gamma-encoded, scaled to the specified sizes.
#
# Each size must be of the form WxH, where W and H are integers:
# e.g. 140x392, 025x035, etc..
#
# This script expects to find the files
#
#   DIRECTORY/p.comments       short description of image.
#
#   DIRECTORY/p.ppm            (for opaque images).
#   DIRECTORY/p-0.ppm          black background (for transparent images).
#   DIRECTORY/p-1.ppm          white background (for transparent images).
#
# The following file(s) may be present in place of (or in addition to)
# the files DIRECTORY/p.ppm, DIRECTORY/p-0.ppm, DIRECTORY/p-1.ppm:
#
#   DIRECTORY/p-raw.ppm        raw scanned image (for opaque images).
#   DIRECTORY/p-0-raw.ppm      ditto, black background (for transparent images).
#   DIRECTORY/p-1-raw.ppm      ditto, white background (for transparent images).
#
#   DIRECTORY/p-raw.jpg        same as above, in JPEG format.
#   DIRECTORY/p-0-raw.jpg      same as above, in JPEG format.
#   DIRECTORY/p-1-raw.jpg      same as above, in JPEG format.
#
# In that case there must also exist the file
#
#   DIRECTORY/p.parms          the color correction parameters.
#
# The script will then automatically (re)create p.ppm from p-raw.ppm
# by applying the color correction described in p.parms, 
# if p.ppm is either missing or obsolete. The same applies
# for the p-0 and p-1 files, if present.
#
# In any case, the ".ppm" files may be compressed with "compress" or "gzip".
#   
# For each given SIZE, the script will also (re)create, if necessary, the files
#
#   DIRECTORY/p-SIZE.gif       scaled color version of image.
#   
#   DIRECTORY/p-SIZE-gray.gif  scaled grayscale version of image.
# 
# The grayscale versions will be created only if the 
# "-gray" switch is given.  The script creates also:
# 
#   DIRECTORY/p.gif            a symbolic link to p-LASTSZ.gif
#   DIRECTORY/p-icon.gif       a symbolic link to "p-FIRSTSZ.gif"
#
#   DIRECTORY/p.html-inc       an html fragment, that inlines
#                              p-icon.gif and links to p.gif,
#                              for use by make-image-index
#   
# where FIRSTSZ and LASTSZ are the first and last of the given SIZEs.
#
# The "-show" switch displays the input and output files, using "xv".  
# The "-test" option generates a single GIF of intermediate size.

# Set program paths:

echo "script = ${0}"

set imgbin = "${STOLFIHOME}/EXPORT/images/tools/bin"
set choosesize = "${imgbin}/choose-test-size"
set mkcorrppm = "${imgbin}/make-corrected-ppm"

set pubbin = "${STOLFIHOME}/bin"
set mkcgif  = "${pubbin}/linear-ppm-to-gif"
set mkggif  = "${pubbin}/linear-ppm-to-gray-gif"
set mktgif  = "${pubbin}/linear-ppm-pair-to-gif"
set mkhtml  = "${pubbin}/make-image-index-entry"
set chkdep  = "${pubbin}/check-dependencies"

set showimg = "display"

# Option parsing:

unset show
unset dograys
unset transparent
unset testsize

set mkgif = "${mkcgif}"

while ( ( $#argv > 0 ) && ( "/$1" =~ /-* ) )
  if ( ( $#argv >= 1 ) && ( "/$1" == "/-show" ) ) then
    set show 
    shift
  else if ( ( $#argv >= 1 ) && ( "/$1" == "/-gray" ) ) then
    set dograys
    shift
  else if ( ( $#argv >= 1 ) && ( "/$1" == "/-test" ) ) then
    set testsize
    shift
  else
    echo "usage: ${usage}" ; exit 1
  endif
end

if ( $#argv < 2 ) then
  echo "usage: ${usage}" ; exit 1
endif

set dir = "$1"; shift;
set sizes = ( `echo $* | sed -e 's/x/./g'` )
if ( $?testsize ) then
  set fullsize = `${choosesize} ${sizes}`
  set iconsize = ${fullsize}
  set sizes = ( ${fullsize} )
else
  set fullsize = "${sizes[$#sizes]}"
  set iconsize = "${sizes[1]}"
endif

# Ensure comment file is present

set comments = "${dir}/p.comments"
if ( ! ( -r ${comments} ) ) then
  echo "$0"': '" ${comments} not found" ; exit 1
endif

# Remove symbolic links p.gif and p-icon.gif to default sizes: 

/bin/rm -f ${dir}/p.gif ${dir}/p.gif~ ${dir}/p-icon.gif ${dir}/p-icon.gif~

# Apply color corrections if needed:

foreach img ( p p-0 p-1 )
  set f = "${dir}/${img}-raw"
  if ( ( -r $f.ppm ) || ( -r $f.ppm.Z ) || ( -r $f.ppm.gz ) || ( -r $f.jpg ) ) then
    ${mkcorrppm} ${dir} ${img} p
    if ( $status != 0 ) exit 1
  endif
end

# Decide whether the image is opaque or has transparent background:

set bppm = "${dir}/p-0.ppm"
set wppm = "${dir}/p-1.ppm"
set sppm = "${dir}/p.ppm"

if ( ( -r "${bppm}" ) || ( -r "${bppm}.Z" ) || ( -r "${bppm}.gz" ) ) set bexists
if ( ( -r "${wppm}" ) || ( -r "${wppm}.Z" ) || ( -r "${wppm}.gz" ) ) set wexists
if ( ( -r "${sppm}" ) || ( -r "${sppm}.Z" ) || ( -r "${sppm}.gz" ) ) set sexists

if ( $?bexists && $?wexists && $?sexists ) then 
  echo "ambiguous --- ${sppm}, ${bppm}, and ${wppm} all exist"; exit 1
else if ( $?bexists && $?wexists ) then
  set transparent = 1
else if ( $?bexists ) then
  echo "${wppm} is missing"; exit 1
else if ( $?wexists ) then
  echo "${bppm} is missing"; exit 1
else if ( $?sexists ) then
  set transparent = 0
else
  echo "${sppm}, ${bppm}, and ${wppm} are all missing"; exit 1
endif

# Now recreate the scaled GIFs if necessary:

if ( $transparent ) then

  # Check (and uncompress if necessary) the input PPM files

  set baseppms = ( "${dir}/p-0.ppm" "${dir}/p-1.ppm" )
  foreach f ( ${baseppms} )
    if ( -r ${f} ) then
      # OK
    else if ( -r ${f}.Z ) then
      uncompress ${f}.Z
    else if ( -r ${f}.gz ) then
      gunzip ${f}.gz
    else 
      echo "$0"': '" ${f} not found" ; exit 1
    endif
  end

  # Generate scaled transparent versions:

  foreach sz ( ${sizes} )
    set nx = ${sz:r}; set ny = ${sz:e}

    set cgif = "${dir}/p-${nx}x${ny}.gif"
    if ( "`${chkdep} ${cgif} ${baseppms} ${mktgif}`" == 1 ) then
      echo "=== generating transparent ${cgif} from ${baseppms} ==="
      if ( "$sz" == "${fullsize}" ) then
        if ( -r ${cgif}~ ) /bin/mv ${cgif}~ ${cgif}~~
        if ( -r ${cgif} ) /bin/mv ${cgif} ${cgif}~
      endif
      nice ${mktgif} \
          -xsize ${nx} -ysize ${ny} \
          -gamma 1.9 \
        ${baseppms} \
        > ${cgif}
    endif
  end
  
  foreach f ( ${baseppms} )
    compress ${f}
  end

else

  # Check (and uncompress if necessary) the input PPM files

  set baseppm = "${dir}/p.ppm"
  set basecat = "cat"
  if ( ! ( -r ${baseppm} ) ) then
    if ( -r ${baseppm}.Z ) then
      set baseppm = "${baseppm}.Z"
      set basecat = "zcat"
    else if ( -r ${baseppm}.gz ) then
      set baseppm = "${baseppm}.gz"
      set basecat = "zcat"
    endif
  endif

  if ( ! ( -r ${baseppm} ) ) then
    echo "$0"': '"${baseppm} not found" ; exit 1
  endif

  # Generate scaled versions:

  foreach sz ( ${sizes} )
    set nx = ${sz:r}; set ny = ${sz:e}

    set cgif = "${dir}/p-${nx}x${ny}.gif"
    if ( `${chkdep} ${cgif} ${baseppm} ${mkcgif}` == 1 ) then
      echo "=== generating ${cgif} ==="
      if ( "$sz" == "${fullsize}" ) then
        if ( -r ${cgif}~ ) /bin/mv ${cgif}~ ${cgif}~~
        if ( -r ${cgif} ) /bin/mv ${cgif} ${cgif}~
      endif
      ${basecat} ${baseppm} \
        | nice ${mkcgif} \
          -xsize ${nx} -ysize ${ny} \
          -gamma 1.9 \
        > ${cgif}
    endif

    set ggif = "${dir}/p-${nx}x${ny}-gray.gif"
    if ( $?dograys && ("`${chkdep} ${ggif} ${baseppm} ${mkggif}`" == 1)) then
      echo "=== generating ${ggif} ==="
      if ( "$sz" == "${showsize}" ) then
        if ( -r ${ggif}~ ) /bin/mv ${ggif}~ ${ggif}~~
        if ( -r ${ggif} ) /bin/mv ${ggif} ${ggif}~
      endif
      ${basecat} ${baseppm} \
        | nice ${mkggif} \
          -xsize ${nx} -ysize ${ny} \
          -gamma 1.9 \
        > ${ggif}
    endif

  end

endif

pushd ${dir}

  # Create symbolic links p.gif and p-icon.gif to the default sizes:

  /bin/ln -s p-${fullsize:r}x${fullsize:e}.gif p.gif
  if ( -r p-${fullsize:r}x${fullsize:e}.gif~ ) then
    /bin/ln -s p-${fullsize:r}x${fullsize:e}.gif~ p.gif~
  endif
  
  if ( -r p-${iconsize:r}x${iconsize:e}.gif~ ) then
    /bin/ln -s p-${iconsize:r}x${iconsize:e}.gif~ p-icon.gif~
  endif
  /bin/ln -s p-${iconsize:r}x${iconsize:e}.gif p-icon.gif
  ${mkhtml} p.gif > p.html-inc

  # Display images if so requested:
  
  if ( $?show ) then
    set nonomatch
    ${showimg} -title "${dir:t}/%f" \
      p.gif p.gif~ p-raw.ppm* p.ppm* \
      p-icon.gif p-icon.gif~ p.parms &
    unset nonomatch
  endif
popd