#!/usr/local/bin/kermit +
#
# IN UNIX CHANGE TOP LINE TO INDICATE ACTUAL PATH OF C-KERMIT
# and give this file execute permission.
#
# Usage: photoalbum.ksc [ keyword=value [ keyword=value [ ... ] ] ]
#
# Make web site of pictures, which must be jpg's.
# To use, put the desired jpg's in an empty directory,
# cd to the directory, and run this script with the desired arguments:
#
# Makes an index page with thumbnails (or picture filenames if there are
# no thumbnails) and then a page for each picture with forward, back, and
# index links, with the ability to click on each picture to see the original.
# Page can be in Spanish or English.
#
# Options (keywords):
#   title="This will be the title" (enclose in quotes if multiple words)
#   color=xxx      (foreground text color, default dargmagenta)
#   background=yyy (background color, default #fff0f0)
#   language=zzz   (english or spanish, default english)
#   height=nnn     (height for thumbnails in pixels, default 120)
#   noscale=n      (0 to scale photos, 1 not to scale, default 0)
#   resize=n       (resize originals, n = max width or height, pixels)
#   arrows         (put Unicode triangles for navigation instead of words)
#   shorttitle="short title for photos" (default is full title)
#
# NOTE: For the present, keywords must be spelled out in full.
#
# The shorttitle is used in the alt= and title= clause of each photo.
# If no shorttitle is given, the regular title is used.
#
# Overwrites any previous versions of the .html pages each time you run it.
#
# If ImageMagick is available, it is used to generate thumbnails for the
# index page.  Otherwise the index page just contains a list of links to
# the individual HTML pages.  ImageMagick can be found here:
#
#   http://www.imagemagick.org/
#
# Alternatively if you can make thumbnails some other way, they will be used
# if they are already there.  For each file xxx.jpg, the corresponding
# thumbnail must be called xxx-t.jpg; all thumbnails should be the same height.
#
# Frank da Cruz, Columbia University, 9 July 2006
#
# Updates:
# 10 Jul 2006: Fixed some typos and fixed the test for Windows.
# 11 Jul 2006: Added RESIZE option (RESIZE=n, pixels, default=760).
# 11 Jul 2006: Reduced disk size of thumbnails by factor of 10.
# 12 Jul 2006: Don't give HTML HEIGHT or WIDTH directives for resized images.
# 12 Jul 2006: Keep and link to original when resizing rather than replacing.
# 15 Sep 2006: Fix NOSCALE result; add "arrows" option for navigation links.
# 16 Nov 2006: Colors for links; fix help text; allow "-help".
# 12 Dec 2009: Nicer default colors; give usage message if no arguments.
# 07 Aug 2010: Put alts and better titles on images; new default colors

.myname := \fbasename(\%0)              # Filename of this script

if eq "\v(system)" "unix" {             # Check prerequisites
    local msg
    .msg = C-Kermit 8.0.212 Dev.20 or later required.
    if llt \v(version) 800212 exit 1 \m(msg)
    if < \v(buildid) 20060707 exit 1 \m(msg)
}
if eq "\v(system)" "windows" {
    if <= \v(xversion) 2103 {
        echo
        echo WARNING:
        echo Certain functions in this script won't work in Windows but a fully
        echo functional website should still result. Ignore any error messages.
        echo This script will operate correctly in the next release of K95.
        echo
    }
}
def USAGE {
    echo
    echo { Usage: \m(myname) keyword=value [ keyword=value [ ... ] ]}
    echo
    echo { Makes a website in a directory containing .jpg images.}
    echo { Index page shows thumbnails of the images.}
    echo
    echo { Options (keywords):}
    echo {   title="This will be the title"}
    echo {   color=xxx      (foreground text color, default darkmagenta)}
    echo {   background=yyy (background color, default \#fff0f0)}
    echo {   language=zzz   (english or spanish, default english)}
    echo {   height=nnn     (height for thumbnails in pixels, default 72)}
    echo {   noscale=n      (0 to scale photos, 1 not to scale, default 0)}
    echo {   resize=n       (nonzero n means resize pictures to n pixels)}
    echo {   arrows         (use arrows instead "next" and "previous")}
    echo {   help           (print this message)}
    echo {   shorttitle="short title for photos" (default is full title)}
    echo
    exit 0
}
if < \v(argc) 2 usage

.kerbang = 0                            # How we exit depends on how invoked
if kerbang incr kerbang                 # (This only works at top level)
define FATAL {                          # Fatal error macro
    fclose all                          # Close all open files
    echo                                # and exit or stop with given message
    if \m(kerbang) exit 1 FATAL - \%*
    else stop 1 FATAL - \%*
}
def STYLE {				# Write <style>..</style> stanza
    fwrite /line \%1 <style type="text/css">
    if \m(arrows) {
	fwrite /line \%1 "  a { text-decoration:none }"
    }
    fwrite /line \%1 "  a:link { color:\m(color) }"
    fwrite /line \%1 "  a:visited { color:\m(color) }"
    fwrite /line \%1 "  a:hover { color:\m(hover) }"
    fwrite /line \%1 "  a:active { color:\m(hover) }"
    fwrite /line \%1 "  img { border:2px solid \m(color) }"
    fwrite /line \%1 </style>
}
# Command-line processing - title and options

.height = 120				# Default thumbnail height
.language = English			# Default text language
.color = darkmagenta   	                # Default text language
.background = \#fff0f0			# Default background color

.lp = (					# Left paren
.rp = )					# Right paren

for \%i 1 \v(argc)-1 1 {                # Parse each keyword option
    void \fkeywordvalue(\&_[\%i])	# This function does it
    if eq "\v(lastkwval)" "help" usage	# If keyword was "help" give help
    if eq "\v(lastkwval)" "-help" usage	# If keyword was "-help" give help
    if eq "\v(lastkwval)" "-h" usage	# If keyword was "-h" give help
    if eq "\v(lastkwval)" "resize" {	# If "resize" given without argument
        if not def resize .resize = 720 # supply default.
    }
    if eq "\v(lastkwval)" "noscale" {	# If "noscale" given without argument
        if not def noscale .noscale = 1 # supply default.
    }
    if eq "\v(lastkwval)" "arrows" {	# If "arrows" given without argument
        if not def arrows .arrows = 1   # supply default.
    }
}
stop

if not def resize .resize = 0
if not def noscale .noscale = 0
if not def arrows .arrows = 0
if not numeric \m(height) exit 1 Fatal - Height not numeric: \m(height)
if not numeric \m(noscale) exit 1 Fatal - Noscale not numeric: \m(noscale)

if match english \m(language)* .language = English
else if match spanish \m(language)* .language = Spanish
else exit 1 Fatal - Language "\m(language)" not supported

.hover := \m(color)
switch \m(color) {
  :darkmagenta, .hover = fuchsia, break
  :deeppink,    .hover = pink, break
  :gold,  .hover = yellow, break
  :black, .hover = lightgrey, break
  :blue,  .hover = lightblue, break
  :red,   .hover = pink
}
show macro title color background hover language height noscale resize arrows

undef \%h \%w				# Height and width clauses for HTML
if not \m(noscale) {
    .\%h = { height="90%"}		# Portrait
    .\%w = { width="100%"}		# Landscape
}
pwd

# Use Image Magick 'convert' (if available) to create resize originals
# and/or create thumbnails.

dir /array:&t /except:*-[tr].jpg *.jpg  # Get list of original images
if not \fdimension(&t) fatal No original JPGs found - nothing to do.

if eq \v(system) unix chmod 664 *.jpg

.need_thumbnails = 0                    # Assume we don't need thumbnails
if def height .need_thumbnails = 1      # If height given maybe we do
if not \m(need_thumbnails) {            # Or...
    .\%t := \ffiles(*-t.jpg)            # if we don't have a thumbnail for
    if > \&t[0] \%t .need_thumbnails = 1 # every non-thumbnail
}
.have_convert = 0                       # Assume we don't have 'convert'
if \m(need_thumbnails) {                # Need thumbnails.
    !convert -version > /dev/null       # Do we have Image Magick convert?
    if fail {
	echo Image Magick 'convert' not found - can't make thumbnails...
        .need_thumbnails = 0            # No - can't make thumbnails
    } else {
        .have_convert = 1
    }
}
if ( \m(resize) && \m(have_convert) ) { # Resizing originals
    echo Resizing...
    for i 1 \&t[0] 1 {                  # Go through non-thumbnail jpgs...
        .t := \fstripx(\fbasename(\&t[i]),.)-r.jpg # Name for resized version
        if not exist \m(t) {            # If it doesn't exist
            copy \&t[i] \m(t)           # copy original
        }
        .\%9 := \fpictureinfo(\m(t),&d) # Get current size
        if == \m(resize) \&d[\%9] {     # If it's already the desired size
            echo \m(t) SKIPPED          # don't resize it.
            continue
        }
        xecho \m(t): \fsize(\m(t))...   # Resize the copy
        !convert \m(t) -resize \m(resize)x\m(resize) \m(t)
        if fail echo PROBLEM RESIZING \&t[i] - Continuing...
        echo \fsize(\m(t))
        chmod 644 \m(t)
    }
    echo                                # Done with thumbnails
}
if \m(need_thumbnails) {                # Need to and can make thumbnails...
    echo Checking thumbnails...
    for i 1 \&t[0] 1 {                  # Go through non-thumbnail jpgs...
        .t := \fstripx(\fbasename(\&t[i]),.)
        .tt := \m(t)-t.jpg              # Make name for thumbnail
        if exist \m(tt) {               # Already exists?
            if \fpictureinfo(\m(tt),&d) { # get its height
                if ( == \m(height) \&d[2] ) { # Same as requested height?
                    continue                  # Nothing to do
                }
            }
            del /quiet \m(tt)           # Delete existing thumbnail
        }
        xecho " \&t[i]"                 # Create new thumbnail
        !convert \&t[i] -thumbnail x\m(height) \m(tt)
        if fail echo PROBLEM MAKING THUMBNAIL FROM \&t[i] - Continuing...
        chmod 644 \m(tt)
    }
    echo                                # Done with thumbnails
}
.\%t := \ffiles(*-t.jpg)                # Now see how many thumbnails exist

# Localization (Spanish or English)...

.charset = iso-8859-1                   # Character set is ISO 8859-1
undef langtag                           # No HMTL language tag yet

switch \m(language) {                   # Text messages for selected language
  :spanish
    .langtag = { lang="es"}             # HTML language tag
    if not def title .title = Fotos     # Default title
    .photo = Foto                       # Individual page title
    .next  = Adelante                   # Forward
    .prev  = Atrás                      # Back
    .index = Indice                     # Index
    .up    = Arriba
    .msg1  = Haz clic en cualquier nombre para ver fotos # Legend for index
    if \%t .msg1 = Haz clic en cualquier foto para entrar
    .msg2  = (Haz clic para ver en tamaño completo)
    break
  :english
    .langtag = { lang="en"}             # HTML language tag
    if not def title .title = Photos    # Default title
    .photo = Photo                      # Individual page title
    .next  = Next                       # Forward
    .prev  = Prev                       # Back
    .index = Index                      # Index
    .up    = Up
    .msg1  = Click on any name to see photos # Legend for index
    if \%t .msg1 = Click on any photo to enter
    .msg2  = (Click to enlarge)
    break
  :default
    fatal "No language!"
}
if not def shorttitle .shorttitle := \m(title)

if \m(noscale) undef msg2

if \m(arrows) {
    undef lp rp
    .index = <span style="font-size:40px;padding-top:16">&#9650;</span>
    .up := \m(index)
    .next = <span style="font-size:36px;padding-top:16">&#9654;</span>
    .prev = <span style="font-size:36px;padding-top:16">&#9664;</span>
}

echo Creating Web pages...

fopen /write \%o index.html             # Create the index page
if fail fatal FOPEN index failed

# Write HTML prologue...

fwrite /line \%o <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
fwrite /line \%o <html\m(langtag)>
fwrite /line \%o <head>
fwrite /line \%o <title>\m(title)</title>
fwrite /line \%o -
  <META http-equiv="Content-Type" content="text/html; charset=\m(charset)">
do style \%o
fwrite /line \%o </head>
fwrite /line \%o -
 <body style="background:\m(background);color:\m(color);font-size:13pt">
fwrite /line \%o <h1>\m(title)</h1>
fwrite /line \%o {\m(lp) <a href="..">\m(up)</a> \m(rp) &nbsp;}
fwrite /line \%o <i>(\m(msg1))</i><br>

.\%n := \&t[0]                          # How many non-thumbnail JPGs
set flag off
.\%r := \ffiles(*-r.jpg)
if == \%r \%n set flag on               # We have resized images

for \%i 1 \%n 1 {                       # Loop through all non-thumbnails
    xecho "FILENAME \&t[\%i] => "       # Start to say what we're going
    .\%b := \fstripx(\&t[\%i])          # Filename without ".jpg"
    .\%f := \%b.html                    # Filename with ".html"
    .\%a := \&t[\%i]                    # Filename of image file
    if flag .\%a := \%b-r.jpg           # Change to this for resized image
    .orientation := \fpictureinfo(\%a)  # Get picture orientation

    undef \%q                           # Scaling command for HTML
    switch \m(orientation) {
      :1, .\%p = "Landscape", .\%q := \%w, break
      :2, .\%p = "Portrait",  .\%q := \%h, break
      :default, .\%p = "Unknown"
    }
    if \m(resize) undef \%q             # No HTML scale if resizing ourselves
    echo \%f (\%p)                      # Finish saying what we're doing
    fopen /write \%c \%f                # Create page for this picture
    if fail exit 1 OPEN failed
    fwrite /line \%c -                  # Write HTML prologue
      <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
    fwrite /line \%c <html\m(langtag)>
    fwrite /line \%c <head>
    fwrite /line \%c <title>\m(photo) \#\%i - \m(title)</title>
    fwrite /line \%c -
      <META http-equiv="Content-Type" content="text/html; charset=\m(charset)">
    do style \%c
    fwrite /line \%c </head>
    fwrite /line \%c -
      <body style="background:\m(background);color:\m(color);font-size:13pt">
    fwrite /line \%c <h2>\m(title) - \m(photo) \#\%i</h2>
    fwrite /line \%c
    fwrite /line \%c <div>

    if == \%i \%n {                     # If last picture there is no next.
        .\%x := index.html
        fwrite /line \%c \m(lp) <a href="index.html">\m(index)</a> \m(rp)
    } else {                            # Not last picture
	.\%x := \fstripx(\&t[\%i+1]).html # So make link to next.
        fwrite /line \%c \m(lp) <a href="\%x">\m(next)</a> \m(rp)
    }
    .xnext := \%x			# Remember this for later
    if != \%i 1 {                       # Not first picture?
      .\%x := \fstripx(\&t[\%i-1]).html # Not first so link to previous
      fwrite /line \%c {&nbsp; \m(lp) <a href='\%x'>\m(prev)</a> \m(rp) &nbsp;}
    }
    if != \%i \%n {                     # Not last picture?
      # Link to index
      fwrite /line \%c \m(lp) <a href='index.html'>\m(index)</a> \m(rp)
    }
    if def msg2 fwrite /line \%c <small><i>&nbsp; \m(msg2)</i></small><br>
    .\%x := \%b
    .\%z = \fcontents(\%b)
    if exist \%x.jpg .\%z = \fcontents(\%x)

    fwrite /line \%c </div>

    if \m(noscale) {
        fwrite /line \%c <a href='\m(xnext)'><img -
title="\m(shorttitle) \m(photo) \#\%i" -
alt="\m(shorttitle) \m(photo) \#\%i" -
src="\%a"\%q></a>
    } else {
        fwrite /line \%c <a href='\%z.jpg'><img -
title="\m(shorttitle) \m(photo) \#\%i" -
alt="\m(shorttitle) \m(photo) \#\%i" -
src="\%a"\%q></a>
    }
    fwrite /line \%c <p>
    fwrite /line \%c <hr color="\m(color)"> # End of page
    fwrite /line \%c </body>
    fwrite /line \%c </html>
    fclose \%c
    if eq \v(system) unix chmod 664 \%f
    .\%x := \fstripx(\%f)-t             # Make entry in index page.
    if exist \%x.jpg {
        fwrite /line \%o {<a href='\%f'><img -
title="\m(shorttitle) \m(photo) \#\%i" -
alt="\m(shorttitle) \m(photo) \#\%i" -
src="\%x.jpg"></a>}
    } else {
        fwrite /line \%o [&nbsp;<a href='\%f'>\%f</a>&nbsp;]
    }
}
# Finish and close Index page

fwrite /line \%o <hr color="\m(color)"> # End of page
fwrite /line \%o Created \v(date) by -
 <a href="http://www.columbia.edu/kermit/photoalbum.html">photoalbum</a>
fwrite /line \%o </body>
fwrite /line \%o </html>
fclose \%o
if eq \v(system) unix {
    chmod 664 index.html
    exit
}
