#! /bin/csh -f 
# Last edited on 2009-12-26 15:34:56 by stolfi

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

# Converts a PPM image (or a pair of PPm images) to PNG
# formats, 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 following files:
# 
#   DIRECTORY/p-SIZE.png       scaled color version of image.
#   DIRECTORY/p-SIZE-gray.png  scaled grayscale version of image.
# 
# The grayscale versions will be created only if the 
# "-gray" switch is given.  The script creates also:
# 
#   DIRECTORY/p.png            a symbolic link to "p-LASTSZ.png"
#   DIRECTORY/p-icon.png       a symbolic link to "p-FIRSTSZ.png"
# 
# where FIRSTSZ and LASTSZ are the first and last of the given SIZEs.
# 
# Finally the script creates
# 
#   DIRECTORY/p.html-inc       an HTML fragment, that inlines
#                              p-icon.png and links to p.png,
#                              for use by make-image-index
#   
# The "-show" switch displays the input and output files.  
# The "-test" option generates a single PNG 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}/PUB/bin"
set mkcpng  = "${pubbin}/linear-ppm-to-png"
set mkgpng  = "${pubbin}/linear-ppm-to-gray-png"
set mktpng  = "${pubbin}/linear-ppm-pair-to-png"
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 mkpng = "${mkcpng}"

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

# Apply color corrections if needed:

set pics = ( )

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

# Main image files:

set bppm = "${dir}/p-0.ppm"
set wppm = "${dir}/p-1.ppm"
set sppm = "${dir}/p.ppm"
set spng = "${dir}/p.png"
set fpng = "${dir}/p-${fullsize:r}x${fullsize:e}.png"

# TRUE means create ${spng} from PPM source image(s):
set createpng = 1

# TRUE means create a transparent image out of two PPMs:
set transparent = 0

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

if ( ( -r "${bppm}" ) || ( -r "${bppm}.Z" ) || ( -r "${bppm}.gz" ) ) set bppmex
if ( ( -r "${wppm}" ) || ( -r "${wppm}.Z" ) || ( -r "${wppm}.gz" ) ) set wppmex
if ( ( -r "${sppm}" ) || ( -r "${sppm}.Z" ) || ( -r "${sppm}.gz" ) ) set sppmex
if ( ( -r "${spng}" ) || ( -r "${fpng}" ) ) set pngex

if ( $?bppmex && $?wppmex && $?sppmex ) then 
  echo "ambiguous --- ${sppm}, ${bppm}, and ${wppm} all exist, aborted"; exit 1
else if ( $?bppmex && $?wppmex ) then
  # We have both "p-0.ppm" and "p-1.ppm", but no "p.ppm":
  set createpng = 1
  set transparent = 1
else if ( $?bppmex ) then
  echo "${wppm} is missing, aborted"; exit 1
else if ( $?wppmex ) then
  echo "${bppm} is missing, aborted"; exit 1
else if ( $?sppmex ) then
  # We have "p.ppm", but neither "p-0.ppm" nor "p-1.ppm":
  set createpng = 1
  set transparent = 0
else
  echo "${sppm}, ${bppm}, and ${wppm} are all missing";
  if ( $?pngex ) then
    # We have "p.png" or "p-NNNxNNN.png", but no "p.ppm", "p-0.ppm", "p-1.ppm":
    echo "using ${spng} or ${fpng} as source image"
    set createpng = 0
  else
    echo "${spng} and ${fpng} also missing, aborted";
    exit 1
  endif
endif

if ( ${createpng} ) then 

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

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

  # Now recreate the base PNG if necessary:

  # Dtermine the gamma correction needed.
  # If the 
  set gammadif = 1.9

  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 cpng = "${dir}/p-${nx}x${ny}.png"
      if ( "`${chkdep} ${cpng} ${baseppms} ${mktpng}`" == 1 ) then
        echo "=== generating transparent ${cpng} from ${baseppms} ==="
        if ( "$sz" == "${fullsize}" ) then
          if ( -r ${cpng}~ ) /bin/mv ${cpng}~ ${cpng}~~
          if ( -r ${cpng} ) /bin/mv ${cpng} ${cpng}~
        endif
        nice ${mktpng} \
            -xsize ${nx} -ysize ${ny} \
            -gamma ${gammadif} \
          ${baseppms} \
          > ${cpng}
      endif
    end

    foreach f ( ${baseppms} )
      gzip ${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 cpng = "${dir}/p-${nx}x${ny}.png"
      if ( `${chkdep} ${cpng} ${baseppm} ${mkcpng}` == 1 ) then
        echo "=== generating ${cpng} from ${baseppm} ==="
        if ( "$sz" == "${fullsize}" ) then
          if ( -r ${cpng}~ ) /bin/mv ${cpng}~ ${cpng}~~
          if ( -r ${cpng} ) /bin/mv ${cpng} ${cpng}~
        endif
        ${basecat} ${baseppm} \
          | nice ${mkcpng} \
            -xsize ${nx} -ysize ${ny} \
            -gamma ${gammadif} \
          > ${cpng}
      endif

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

    end

  endif

else

  # Generate scaled versions of PNG image:

  set basepng = "${fpng}"
  if ( ! ( -r ${basepng} ) ) then
    set basepng = "${spng}"
  endif

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

    set upng = "${dir}/p-${nx}x${ny}.png"
    if ( `${chkdep} ${upng} ${basepng}` == 1 ) then
      echo "=== generating ${upng} from ${basepng} ==="
      if ( "$sz" == "${fullsize}" ) then
        if ( -r ${upng}~ ) /bin/mv ${upng}~ ${upng}~~
        if ( -r ${upng} ) /bin/mv ${upng} ${upng}~
      endif
      convert ${basepng} \
          -geometry "${nx}x${ny}" \
        > ${upng}
    endif

    set gpng = "${dir}/p-${nx}x${ny}-gray.png"
    if ( $?dograys && ("`${chkdep} ${gpng} ${basepng}`" == 1)) then
      echo "=== generating ${gpng} from ${basepng} ==="
      if ( "$sz" == "${showsize}" ) then
        if ( -r ${gpng}~ ) /bin/mv ${gpng}~ ${gpng}~~
        if ( -r ${gpng} ) /bin/mv ${gpng} ${gpng}~
      endif
      convert ${basepng} \
          -colorspace GRAY \
          -geometry "${nx}x${ny}" \
        > ${gpng}
    endif

  end

endif

pushd ${dir}

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

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

  # Display images if so requested:
  
  if ( $?show ) then
    set pics = ( p.png )
    if ( -r p.png~ ) set pics = ( ${pics} p.png~ )
    if ( -r p-raw.ppm ) then
      set pics = ( ${pics} p-raw.ppm )
    else if ( -r p-raw.ppm.gz ) then
      set pics = ( ${pics} p-raw.ppm.gz )
    else if ( -r p-raw.ppm.Z ) then
      set pics = ( ${pics} p-raw.ppm.Z )
    endif
    if ( -r p.ppm ) then
      set pics = ( ${pics} p.ppm )
    else if ( -r p.ppm.gz ) then
      set pics = ( ${pics} p.ppm.gz )
    else if ( -r p.ppm.Z ) then
      set pics = ( ${pics} p.ppm.Z )
    endif
    if ( -r p-icon.png ) set pics = ( ${pics} p-icon.png )
    if ( -r p-icon.png~ ) set pics = ( ${pics} p-icon.png~ )
    ${showimg} -title "${dir:t}/%f" ${pics} &
  endif
popd