#!/bin/bash
#
# This finds a bright area in a RAW file, centres it, and crops around.
# Then it adds some technical and copyright information.
# Written for web casting of the Solar Eclipse 20th March 2015.
# By Thomas Ulich, Sodankylä Geophysical Observatory, www.sgo.fi
# 
for f; do
  # Define file names to be used later
  j=${f/CR2/jpg}
  p=${f/CR2/ppm}
  bw=bw.ppm
  # Extract creation date and time
  t=(`exiftool -CreateDate $f | cut -d: -f 2-`)
  # Change colons into dashes for the date
  t[0]=${t[0]//:/-}
  # Convert from CR2 to ppm
  dcraw $f
  # Generate a two-colour black and white version
  convert $p -threshold 50% $bw
  # Use -fuzz to find the geometry for an auto-crop of the white
  # bits in the two-colour image
  crop=`convert $bw -fuzz 1% -format "%@" info:`
  # Now $crop is something like: 1009x821+2711+1392
  # The following replaces x and + with spaces and converts to an array.
  crop=(${crop//[x+]/ })
  # Compute the centre point of the bright area and then go back by
  # half the final image size, which in our case is 1500x1500 pixels.
  # x0, y0 are the final offsets.
  x0=$((${crop[2]}+${crop[0]}/2-750))
  y0=$((${crop[3]}+${crop[1]}/2-750))
  # if the Sun is at the edge, the crop might not be possible. Then make
  # margins smaller, but keep image at the same size. In any case, the Sun
  # will be fully in the frame.
  if [ $x0 -lt 1 ]; then x0=1; fi
  if [ $y0 -lt 1 ]; then y0=1; fi
  # Generate new geometry string
  crop=1500x1500+${x0}+${y0}
  # Sharpen the image. For some reasons this does not work when part of
  # the next command, leading to this extra step.
  convert $p \
    -crop $crop \
    -sharpen 0x3 \
    aux.tif
  # Add text below the image with time stamp and copyright info.
  convert aux.tif \
    -background Black -fill White \
    -pointsize 36 -font Courier \
    label:"Solar eclipse live web cast:   ${t[0]} ${t[1]}UTC
    (c)2015 by Sodankyl채 Geophysical Observatory.
All rights reserved. Photo: Thomas Ulich.  www.sgo.fi" \
    -gravity center -append \
    -quality 95 \
    $j
  # Copy EXIF data from RAW *CR2 file to JPG file
  exiftool -TagsFromFile $f $j
  # Clean up files
  rm -f *_original *.ppm aux.tif
done