#!/bin/bash

SRCDIR="testpic2"
DSTDIR="testpic3"

TARGET_MAX_WIDTH=520
TARGET_MAX_HEIGHT=720

TMPFILE=tmppiclist.txt

ls $SRCDIR  >  $TMPFILE

TOTALNUM=`wc -l $TMPFILE | awk '{print $1}'`

NUM=0

echo "$TOTALNUM files"

while [ $NUM -lt $TOTALNUM ] ; do
    let NUM+=1

    FILENAME=`cat $TMPFILE | sed -n ''$NUM','$NUM' p'`
    echo "${FILENAME}"

    FILE_WH=`identify -format "%wx%h" $SRCDIR/"${FILENAME}"`
    X_POS=`expr index $FILE_WH "x"`
    FILE_W=${FILE_WH:0:$X_POS-1}
    FILE_H=${FILE_WH:$X_POS}

    echo "  $FILE_W x $FILE_H"
    SRC_PATH=$SRCDIR/"${FILENAME}"
    DST_PATH=$DSTDIR/"${FILENAME}"

    if  ! [ $FILE_W -gt $TARGET_MAX_WIDTH ] && ! [ $FILE_H -gt $TARGET_MAX_HEIGHT ] ; then
              echo "   small pic, do nothing and copy it"
              cp   "$SRC_PATH"  "$DST_PATH"
    elif   [ $FILE_W -gt $TARGET_MAX_WIDTH ] && ! [ $FILE_H -gt $TARGET_MAX_HEIGHT ] ; then
              convert -resize   $TARGET_MAX_WIDTH   "$SRC_PATH"  "$DST_PATH"
              DST_FILE_WH=`identify -format "%wx%h" "${DST_PATH}"`
              echo "   converted to be $DST_FILE_WH"
    elif  ! [ $FILE_W -gt $TARGET_MAX_WIDTH ] &&  [ $FILE_H -gt $TARGET_MAX_HEIGHT ] ; then
              convert -resize  x$TARGET_MAX_HEIGHT   "$SRC_PATH"  "$DST_PATH"
              DST_FILE_WH=`identify -format "%wx%h" "${DST_PATH}"`
              echo "   converted to be $DST_FILE_WH"
    elif   [ $FILE_W -gt $TARGET_MAX_WIDTH ] &&   [ $FILE_H -gt $TARGET_MAX_HEIGHT ] ; then
              VAL1=`expr $FILE_H \* $TARGET_MAX_WIDTH`
              VAL2=`expr $FILE_W \* $TARGET_MAX_HEIGHT`

	      if ! [ $VAL1 -gt $VAL2 ] ; then
               convert -resize   $TARGET_MAX_WIDTH   "$SRC_PATH"  "$DST_PATH"
               DST_FILE_WH=`identify -format "%wx%h" "${DST_PATH}"`
               echo "   converted to be $DST_FILE_WH"
	      else
               convert -resize x$TARGET_MAX_HEIGHT   "$SRC_PATH"  "$DST_PATH"
               DST_FILE_WH=`identify -format "%wx%h" "${DST_PATH}"`
               echo "   converted to be $DST_FILE_WH"
	      fi

    fi



done
