# convert-jp2-tiff Copyright 2012 DMM; GPL 3+ 
#

# For each file in a directory which is either a .tiff or a .jp2,
# convert it to png (uncomment lines for jpg)

# requires package: openjpeg (Arch Linux) or 
#                   openjpeg_tools (Ubuntu) for j2k_to_image

shopt -s extglob 

FILES=`ls`

for f in $FILES; do

   # cut the shorted possible (%) string off the end which matches 
   # exactly one (@) of .jp2 or .tiff
   # In other words, strip the .jp2 or .tiff suffix
   BASE=${f%@(.jp2|.tiff)} 
   # Now get the suffix by stripping the BASE off the filename
   SUFFIX=${f#$BASE} 
   
   if [ "$SUFFIX" == ".jp2" ]; then
      echo $f
      j2k_to_image -i $f -o $BASE.pnm > /dev/null
      nice -n 19 convert $BASE.pnm $BASE.png
#      convert $BASE.pnm $BASE.jpg
      rm $BASE.pnm
   elif [ "$SUFFIX" == ".tiff" ]; then
      echo $f
      nice -n 19 convert $f $BASE.png
#      convert $f $BASE.jpg
   else
      echo $f IS UNKNOWN, skipping
   fi

done
