#!/bin/sh
#
# script to convert pcbm header file to an sgi .rgb file by creating a
# C program which includes the header pcbm file, which is compiled, and
# then spits out the .rgb file.

create_cfile () {
cat << EOF
/* temp file for frompcbm $1 */

#include <pcbm/pcbm.h>
#include <gl/image.h>
#define BLACK			0
#define RED			1
#define GREEN			2
#define YELLOW			3
#define BLUE			4
#define MAGENTA			5
#define CYAN			6
#define WHITE			7
#define BLACK2			8
#define RED2			9
#define GREEN2			10
#define YELLOW2			11
#define BLUE2			12
#define MAGENTA2		13
#define CYAN2			14
#define WHITE2			15
#define TP_IDX			16
#define VeryDarkGray		17
#define VeryLightGray		18
#define MediumGray		19
#define MACHCLR0		20
#define MACHCLR1		21
#define MACHCLR2		22
#define MACHCLR3		23
#define MACHCLR4		24
#include "$1.h"

int rgb[26] = {
	0x000000,	0xff0000,	0x00ff00,	0xffff00,
	0x0000ff,	0xff00ff,	0x00ffff,	0xffffff,
	0x555555,	0xc67171,	0x71c671,	0x8e8e38,
	0x7171c6,	0x8e388e,	0x388383,	0xaaaaaa,
	0x606070,	0x2a2a2a,	0xd5d5d5,	0x808080,
#ifdef MACHCLR0_CLR
	MACHCLR0_CLR,
#endif
#ifdef MACHCLR1_CLR
	MACHCLR1_CLR,
#endif
#ifdef MACHCLR2_CLR
	MACHCLR2_CLR,
#endif
#ifdef MACHCLR3_CLR
	MACHCLR3_CLR,
#endif
#ifdef MACHCLR4_CLR
	MACHCLR4_CLR,
#endif
	0
};

short rdata[256][256];
short gdata[256][256];
short bdata[256][256];

main(int argc, char ** argv)
{
	struct pcbm_node *p;
	IMAGE *img;
	int x,y;

	for (y=0; y < 256; y++)
	     for (x = 0; x < 256; x++) {
		     rdata[y][x] = 210;
		     gdata[y][x] = 180;
		     bdata[y][x] = 140;
	     }

	for (p=$2.bitlist; p->bits; p++) {
		int r,g,b,c,spr,bx,by,i;

		c = rgb[p->color];
		r = (0xff0000 & c) >> 16;
		g = (0x00ff00 & c) >> 8;
		b = (0xff & c);

		x = p->dx;
		y = p->dy;

		spr = (p->w-1)/16 + 1;

		for (by=0; by < p->h; by++)
			for (bx=0; bx < p->w; bx+=16)
				for (i=0; i<16 && (bx+i) < p->w; i++)
					if (p->bits[(by*spr)+(bx/16)] &
					    (1<<(15-i))) {
						rdata[y+by][x+bx+i] = r;
						gdata[y+by][x+bx+i] = g;
						bdata[y+by][x+bx+i] = b;
					}
	}

	img = iopen(argv[1],"w",RLE(1),3,$2.w,$2.h,3);

	for (y=0; y < $2.h; y++) {
		putrow(img,rdata[y],y,0);
		putrow(img,gdata[y],y,1);
		putrow(img,bdata[y],y,2);
	}

	iclose(img);
}
EOF
}

if [ -z "$1" ]
then
	echo "usage: frompcbm filename [iconname]"
	exit 1
fi

PCBMFILE=$1
BASENAME=`echo $1 | sed 's%\.h$%%'`
ICONNAME=${2:-$BASENAME}
RGBFILE=${BASENAME}.rgb
CONVBIN=frompcbm$$
CONVCFILE=${CONVBIN}.c

create_cfile $BASENAME $ICONNAME > $CONVCFILE

cc -I ${ROOT}/stand/arcs/include $CONVCFILE -limage -o $CONVBIN

if [ -x $CONVBIN ]
then
	$CONVBIN $RGBFILE
fi

rm -f $CONVCFILE $CONVBIN

exit 0
