#!/bin/bash
# Some Defaults:
function ceil () {
 echo "define ceil (x) {if (x<0) {return x/1} \
        else {if (scale(x)==0) {return x} \
        else {return x/1 + 1 }}} ; ceil($1)" | bc;
}

MAX_ZOOM=20
TILE_WIDTH=256
TILE_HEIGHT=${TILE_WIDTH}
CONVERT="/usr/bin/convert"
IDENTIFY="/usr/bin/identify"

# User Input
SOURCE=$1

# Start
# Get Source image dimensions
SOURCE_DIMENSIONS=`${IDENTIFY} -format "%wx%h" ${SOURCE}`
SOURCE_WIDTH=(${SOURCE_DIMENSIONS//x/ })
SOURCE_HEIGHT=${SOURCE_WIDTH[1]}
SOURCE_WIDTH=${SOURCE_WIDTH[0]}
SOURCE_EXTENSION="${SOURCE##*.}"

# Convert to a workable image:
# http://build-failed.blogspot.nl/2012/11/zoomable-image-with-leaflet.html
# Need an image of size TILE_WIDTH x TILE_HEIGHT to the power of 2 (square)
LONGEST_SIDE=$(( ${SOURCE_WIDTH} > ${SOURCE_HEIGHT} ? ${SOURCE_WIDTH} : ${SOURCE_HEIGHT} ))
POWER=$(echo "l($LONGEST_SIDE) / l(2)" | bc -l)
POWER=$(ceil ${POWER})
NEW_SIZE=$(echo "2^${POWER}" | bc)
MAP_IMAGE_BASE="Procees_image"
ZOOM_FACTOR=$(printf "%.0f" $(echo "l($((NEW_SIZE / TILE_WIDTH))) / l(2)" | bc -l))
# Done base image calculations

MAP_IMAGE="${NEW_SIZE}_${MAP_IMAGE_BASE}.${SOURCE_EXTENSION}"
echo "Source image dimensions: ${SOURCE_WIDTH} x ${SOURCE_HEIGHT}, Longest side: ${LONGEST_SIDE}. Scale up with to the power ${POWER} to ${NEW_SIZE} x ${NEW_SIZE} with max zoom factor ${ZOOM_FACTOR}"

${CONVERT} ${SOURCE} -resize ${NEW_SIZE}x${NEW_SIZE} -gravity center -background black -extent ${NEW_SIZE}x${NEW_SIZE} ${MAP_IMAGE}

rm tiles_*.${SOURCE_EXTENSION}

SOURCE_IMAGE=${MAP_IMAGE}
DEST_SIZE=${NEW_SIZE}
for (( ZOOM=0; ZOOM<=${ZOOM_FACTOR}; ZOOM++ ))
do
  if [ "${ZOOM}" -gt "0" ]
  then
    # resize source image to smaller temp image
    DEST_SIZE=$((DEST_SIZE / 2))
    NEW_IMAGE="${DEST_SIZE}_${MAP_IMAGE_BASE}.${SOURCE_EXTENSION}"
    convert ${SOURCE_IMAGE} -resize 50% ${NEW_IMAGE}
    SOURCE_IMAGE=${NEW_IMAGE}
  fi


  echo "Image: ${SOURCE_IMAGE} ${DEST_SIZE} x ${DEST_SIZE}"
  NEW_ZOOM=$((ZOOM_FACTOR - ZOOM))
  convert -crop ${TILE_WIDTH}x${TILE_HEIGHT} +repage ${SOURCE_IMAGE} tiles_${NEW_ZOOM}_%03d.${SOURCE_EXTENSION}

  TILES_PER_COLUMN=$((DEST_SIZE / TILE_WIDTH))
  TOTAL_ROWS=$((DEST_SIZE / TILE_HEIGHT))

  ROW=0
  COLUMN=0
  for f in tiles_${NEW_ZOOM}_*.${SOURCE_EXTENSION}
  do
    TILE_NAME="tiles_${NEW_ZOOM}_${COLUMN}_${ROW}.${SOURCE_EXTENSION}"
    echo "Rename file ${f} to tile: ${TILE_NAME}"
    mv ${f} ${TILE_NAME}
    COLUMN=$((COLUMN + 1))
    if [ "${COLUMN}" -ge "${TILES_PER_COLUMN}" ]
    then
      COLUMN=0
      ROW=$((ROW + 1))
    fi
  done
done


