#include "\include\gemdefs.h"
#include "\include\osbind.h"
#include "rtd.h"
int debug;

#define GRMODE   0      	/* graphics mode 0 (320x200) */
#define FSIZE  32034    	/* size of DEGAS save-file */
int	vs_handle;		/* virtual screen (workstation) handle */
int *clut_fetch();
int read_pal[16];

/* the first FSIZE bytes of the file is DEGAS */

/* save screen data to disk in DEGAS-like format */

f_write(fn)
char *fn;
{
   char *scrnp;
   int fd, n;
   short gmode[1];

   if (fn == 0)
	return (-1);
   scrnp = (char *)Physbase() ;  /* get pointer to display frame */
   *gmode = GRMODE ;

   if ((fd = creatb(fn, 0755)) < 0) 
	return(-1);

   n = write(fd, gmode, 2);		/* write graphics mode */
   n += write(fd, clut_fetch() /*palet(ind)*/, 32);	/* write palette */
   n += write(fd, scrnp, 32000);	/* write screen data */
   close(fd);

   if (n != FSIZE)
   {  unlink(fn);
      panic("Not enough space on disk to write file\n(need 32K)");
   }
   return(0) ;
}

/* read file (DEGAS format) */
int f_read(fn, buf)
char *fn, *buf;
{
   char *scrnp;
   int fd, n;
   short gmode[1];

   if (fn == 0)
	return (-1);
   if ((fd = openb(fn, 0)) < 0) 
	return(-1);

   n = read(fd, gmode, 2);		/* read graphics mode */
   n += read(fd, &read_pal, 32);	/* read palette */
   n += read(fd, (buf? buf: (char *)Physbase()), 32000);
   close(fd);				/* read screen data */
   
   if (n != FSIZE)
	return(-2);			/* file read error: file too short */
   clut_put(&read_pal);


   return(0);
}

int scramble[16] = {0, 2, 3, 6, 4, 7, 5, 8, 9, 10, 11, 14, 12, 15, 13, 1};

int *clut_fetch()
{	int *p = read_pal, i;
	int rgb[3], red, green, blue;

	for (i=0; i<16; i++)
	{	vq_color(vs_handle, scramble[i], 0, rgb);
		red   = rgb[0] / 125;	
		green = rgb[1] / 125;
		blue  = rgb[2] / 125;
		if (debug)
			printf("cF(%d>%d): %d %d %d ->%d %d %d\n",i,scramble[i],
				rgb[0], rgb[1], rgb[2], red, green, blue);
		*p++ = (red*0x100 + green*0x10 + blue);
	}
	return(read_pal);
}

#define clr(r) 1000*(2*(r)+1)/16;

clut_put(p)
int *p;
{	int i;
	int rgb[3], red, green, blue;
	for (i=0; i<16; i++, p++)
	{	rgb[0] = clr( *p >>8 & 0xf);	/* red */
		rgb[1] = clr( *p >>4 & 0xf);	/* green */
		rgb[2] = clr( *p & 0xf);	/* blue */
		vs_color(vs_handle, scramble[i], rgb);
}	}
