#! /usr/bin/perl
#
# $Id$

use strict;
use warnings;

undef $/;
my $data=<>;
$data=~s/^\s*#.*\n//m;
my($format,$width,$height)=($data=~/^(P[14])\n(\d+) (\d+)\n/);
$data=$';
die "Invalid format" if !$format || !$width || !$height;
die "Picture too big; width=$width < 0xFF && height=$height < 0xFF" if $width>0xFF || $height>0xFF;
if ($format eq "P1") {
	$data=~tr/01//cd;
	}
else {
	$data=unpack("b*",$data);
	my $width8=int(($width+7)/8)*8;
	for my $y (0..$height-1) {
		# cut end-of-line gap
		substr($data,$width*$y+$width,$width8-$width)="";
		}
	}
die "Bad data length ".length($data) if length($data)!=$width*$height;

my @pictureudh=(
		0x05,	# IEI
		0x04,	# IEDL
		0x15,0x8A,	# dest port (ring tones)
		0x15,0x8A);	# src port (unused)

my $multihdr_uniq=int(rand(0x100));
sub multihdr
{
my($num,$total)=@_;

	return (
		0x00,	# IEI
		0x03,	# IEDL
		$multihdr_uniq,	# unique serial ID
		$total,	# total messages
		$num+1);	# message number (# from 1)
}

sub udh
{
my(@bytes)=@_;

	return pack "C*",scalar(@bytes),@bytes;
}


my $picturebyteslen=int(($width*$height+7)/8)+4;	# +4 is for some part of the header
my $picturedata=unpack("b*",pack("C*",
				0x30,	# version string '0'
				0x02,	# item=OTA bitmap
				($picturebyteslen>>8)&0xFF,	# picture size in bytes incl. header; HIGH
				($picturebyteslen>>0)&0xFF,	# picture size in bytes incl. header; LOW
				0x00,	# animation pictures - 0=static picture
				$width,$height,	# picture size in pixels
				0x01,	# picture depth - B/W
				))
		.$data;

my @out=udh(@pictureudh).pack("b*",$picturedata);
if (length($out[0])>140) {
	my $datalen=int((length($picturedata)+7)/8);
	my $hdrlen=length(udh(@pictureudh,multihdr(8,8)));
	my $dataspace=(140-$hdrlen);
	my $total=int(($datalen+$dataspace-1)/$dataspace);
	die "Too big: total=$total <=0xFF !" if $total>0xFF;
	@out=map({
		udh(@pictureudh,multihdr($_,$total)).pack("b*",substr($picturedata,$dataspace*8*$_,$dataspace*8));
		} (0..$total-1));
	}
print map({ uc(unpack("H*",$_))."\n"; } @out);
