#!/bin/sh
#
# $Id: ppm2nokia,v 1.2 2005/04/20 20:25:31 pkot Exp $
#
# G N O K I I
#
# A Linux/Unix toolset and driver for the mobile phones.
#
# This file is part of gnokii.
#
# Gnokii 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.
#
# Gnokii 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 gnokii; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
# Copyright (c) 2002 by Vidar Madsen
#
# ppm2nokia v1.0 - Convert PPM/PGM files to Nokia's NOL or NGG format.
#
# Usage: ppm2nokia [-i] < logo.ppm > logo.nol
#
# Only raw PPM and PGM files are supported.
#
# Output format will be selected automatically based on the geometry
# of the input image. Currently, 78x21 means NOL, and 72x14 means NGG.
#
# Verify the output file with;  gnokii --viewlogo logo.nol
# Send it to your phone with;   gnokii --setlogo op logo.nol
#
# Have fun. :)
# -- Vidar

black=1
white=0

while [ "$1" != "" ]; do
  arg="$1"
  shift
  if [ "$arg" = "-i" ]; then black=0; white=1; continue; fi
  echo "ppm2nokia: Unknown argument \"$arg\"" >&2
  exit
done

function readline {
  while true; do
    read line
    if [ "${line:0:1}" != "#" ]; then break; fi
  done
}

readline
if [ "$line" == "P6" ]; then
  ppm=true
elif [ "$line" == "P5" ]; then
  ppm=false
else
  echo "ppm2nokia: PPM/PGM marker not found ($line)." >&2
  exit
fi

readline
set -f -- $line
size="${1}x${2}"
pad=$[((($1*$2)+7)/8)*8 - ($1*$2)]
if [ "$size" == "78x21" ]; then
  hdr='NOL\x00\x01\x00\xF2\x00\x01\x00\x4E\x00\x15\x00\x01\x00\x01\x00\x00\x00'
elif [ "$size" == "72x14" ]; then
  hdr='NGG\x00\x01\x00\x48\x00\x0E\x00\x01\x00\x01\x00\x00\x00'
else
  echo "ppm2nokia: Invalid size (${size}). Only 78x21 and 72x14 is supported." >&2
  exit
fi

readline
if [ "$line" != "255" ]; then
  echo "ppm2nokia: Invalid depth ($line)." >&2
  exit
fi

echo -ne $hdr

cat | tr '\000-\177\200-\377' "[$black*128][$white*128]" | \
	if $ppm; then sed 's/\(.\)../\1/g'; else cat; fi

# Pad file to multiple of 8 bytes
printf "%0${pad}d" 0
