#include <stdio.h>
#include "rasterfile.h"

#define MAX_COLOUR 255		/* highest RGB value (for white) */

sunrf_open(xres, yres, max_colour, out_fp)
int xres, yres;		/* size of image */
unsigned char max_colour;	/* highest value of pixel data */
FILE *out_fp;		/* output file pointer */
{
	int size = max_colour + 1;	/* number of palette entries used */
	int ras_magic = RAS_MAGIC;
	int bits_per_pixel = 8;
	int length = xres * yres;
	int type   = RT_STANDARD;
	int map_type = RMT_EQUAL_RGB;
	int map_len = size * 3;
	register int i;

	if (max_colour > 255) {
		fprintf(stderr, "Too many output colour (max 255)\n");
		exit(1);
	}

	put_sun_word(ras_magic,out_fp);
	put_sun_word(xres,out_fp);
	put_sun_word(yres,out_fp);
	put_sun_word(bits_per_pixel,out_fp);
	put_sun_word(length,out_fp);
	put_sun_word(type,out_fp);
	put_sun_word(map_type,out_fp);
	put_sun_word(map_len,out_fp);

	/* greyscaled map values, inverse mapping for black marks on white bg */
	/* red */
	for (i = 0; i < size; i++) {
		fputc(MAX_COLOUR - (i * MAX_COLOUR / max_colour), out_fp);
	}
	/* green */
	for (i = 0; i < size; i++) {
		fputc(MAX_COLOUR - (i * MAX_COLOUR / max_colour), out_fp);
	}
	/* blue */
	for (i = 0; i < size; i++) {
		fputc(MAX_COLOUR - (i * MAX_COLOUR / max_colour), out_fp);
	}
}

sunrf_line(colors, xres, out_fp)
unsigned char *colors;	/* pixel data */
int xres;		/* number of pixels */
FILE *out_fp;
{
	int x, y;
	unsigned char *ptr;

	for (x = 0, ptr=colors; x < xres; x++) {
		fputc(*ptr++, out_fp);
	}
}

sunrf_close(out_fp)
FILE *out_fp;
{
	fclose(out_fp);
}

static
put_sun_word(num, fp)
int	num;
FILE	*fp;
{
	fputc((num >> 24) & 0xff, fp);
	fputc((num >> 16) & 0xff, fp);
	fputc((num >> 8 ) & 0xff, fp);
	fputc((num      ) & 0xff, fp);
}
