/*

extract.c - program for making video data file from 1bpp bitmaps

*/

/*...sincludes:0:*/
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stddef.h>
#include <stdlib.h>
#include <stdarg.h>
#if defined(AIX) || defined(LINUX) || defined(SUN) || defined(MACOSX) || defined(IPHONE)
#include <unistd.h>
#else
#include <io.h>
#endif
#include <fcntl.h>
#ifdef MAC
#include <types.h>
#include <stat.h>
#else
#include <sys/types.h>
#include <sys/stat.h>
#endif
#ifndef O_BINARY
#define	O_BINARY	0
#endif
#include "gbm.h"

/*...vgbm\46\h:0:*/
/*...e*/

static char progname[] = "extract";

/*...sfatal:0:*/
static void fatal(const char *fmt, ...)
	{
	va_list	vars;
	char s[256+1];

	va_start(vars, fmt);
	vsprintf(s, fmt, vars);
	va_end(vars);
	fprintf(stderr, "%s: %s\n", progname, s);
	exit(1);
	}
/*...e*/
/*...susage:0:*/
static void usage(void)
	{
	fprintf(stderr, "usage: %s n1 n2 n3 fn.ext{,opt} outfile.bin\n", progname);
	exit(1);
	}
/*...e*/
/*...sconvert:0:*/
static void convert(const gbm_u8 *src, gbm_u8 *dest)
	{
	int y, x, b;
	for ( y = 0; y < 16; y++ )
		for ( x = 0; x < 20; x++ )
			for ( b = 0; b < 8; b++ )
				*dest++ = ~src[(128-1-(y*8+b))*20+x];
	}
/*...e*/
/*...smain:0:*/
static gbm_u8 data[2560];
static gbm_u8 data2[2560];

int main(int argc, char *argv[])
	{
	char	fn[500+1], *opt;
	int	fd, fd_out, ft, n1, n2, n3, frame;
	GBM_ERR	rc;
	GBMFT	gbmft;
	GBM	gbm;
	GBMRGB	gbmrgb[0x100];

	if ( argc < 6 )
		usage();

	sscanf(argv[1], "%i", &n1);
	sscanf(argv[2], "%i", &n2);
	sscanf(argv[3], "%i", &n3);

	strcpy(fn, argv[4]);
	if ( (opt = strchr(fn, ',')) != NULL )
		*opt++ = '\0';
	else
		opt = "";

	if ( (fd_out = open(argv[5], O_CREAT|O_TRUNC|O_WRONLY|O_BINARY, S_IREAD|S_IWRITE)) == -1 ) 
		fatal("can't create output file: %s", argv[5]);

	gbm_init();

	for ( frame = n1; frame != n2; frame += n3 )
		{
		char fn_frame[500+1];
		sprintf(fn_frame, fn, frame);

		if ( gbm_guess_filetype(fn_frame, &ft) != GBM_ERR_OK )
			fatal("can't guess bitmap file format for %s", fn_frame);

		if ( (fd = gbm_io_open(fn_frame, O_RDONLY|O_BINARY)) == -1 )
			fatal("can't open %s", fn_frame);

		if ( (rc = gbm_read_header(fn_frame, fd, ft, &gbm, opt)) != GBM_ERR_OK )
			{
			gbm_io_close(fd);
			fatal("can't read header of %s: %s", fn_frame, gbm_err(rc));
			}

		if ( (rc = gbm_read_data(fd, ft, &gbm, data)) != GBM_ERR_OK )
			{
			gbm_io_close(fd);
			fatal("can't read bitmap data of %s: %s", fn_frame, gbm_err(rc));
			}

		gbm_io_close(fd);

		convert(data, data2);

		write(fd_out, data2, 2560);
		}

	gbm_deinit();

	close(fd_out);

	return 0;
	}
/*...e*/
