#!/bin/sh

#############################################################################
#
# jpg2frame.sh
#
# Usage:
#   jpg2frame.sh <infile> <outfile> [quality]
#
# Description:
#   Convert jpeg files for direct download to the Philips 7FF1AW picture
#   frame. The resulting picture is marked as beeing part of the diaporama.
#
# Copyright 2006 Vincent Stehlé
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
#
#############################################################################

#############################################################################
#
# DEFAULT_QUALITY
#
#############################################################################
DEFAULT_QUALITY=85

# Arguments.
in="$1"
out="$2"
quality=$DEFAULT_QUALITY

if [ x"$3" != x ]; then
    quality=$3
fi

# Find-out jpeg tools.
DJPEG=djpeg-mmx
[ `which $DJPEG` ] || DJPEG=djpeg

CJPEG=cjpeg-mmx
[ `which $CJPEG` ] || CJPEG=cjpeg

# Compute resize.
infos=`jpeginfo "$in"`
width=`echo $infos |sed 's/.* \([0-9]\+\) x [0-9]\+.*/\1/'`
height=`echo $infos |sed 's/.* [0-9]\+ x \([0-9]\+\).*/\1/'`

# If we resize width to 720,
# is resulting height too small?
if [ $[720 * $height / $width] -ge 480 ]; then
    # Ok to scale width.
    scale="-width 720"
    cut="-height 480 -top $[((720 * $height / $width) - 480) / 2]"

else
    # Rather scale height.
    scale="-height 480"
    cut="-width 720 -left $[((480 * $width / $height) - 720) / 2]"
fi

# Prepare header in destination.
cat header.bin > "$out"

# Transform.
$DJPEG -pnm "$in"                       \
    |pnmscale $scale                    \
    |pnmcut $cut                        \
    |$CJPEG -optimize -quality $quality \
    >> "$out"

