#include <vga.h>
#include <vgagl.h>
#include <math.h>
#include <stdlib.h>
#define GMODE G320x200x256

/* It's a good idea to keep these global */
GraphicsContext *virtualscreen;
GraphicsContext *physicalscreen;

int main(void)
{
  int c, d; /* counting */
  int x, y; /* box location */
  int *box; /* our box */
  int *cut; /* cookie cut */
  vga_init(); /* start svgalib */
  gl_enableclipping();
  vga_setmode(GMODE); /* set mode */
  gl_setcontextvga(GMODE);
  physicalscreen = gl_allocatecontext();
  gl_getcontext(physicalscreen);
  gl_setcontextvgavirtual(GMODE);
  virtualscreen = gl_allocatecontext();
  gl_getcontext(virtualscreen);

  /* now let's fix the palette up
   *  real pretty like!
   */

  for (d=0; d<256; d++)
    gl_setpalettecolor(d, 32*sin(6.3*d/256.0)+31,
		       32*sin(6.3*(d-67)/256.0)+31,
		       32*sin(6.3*(d-133)/256.0)+31);

  /* generate our square, with a
   * transparent hole in the middle */

  box = malloc(16*16*BYTESPERPIXEL);
  cut = malloc(16*16*BYTESPERPIXEL);
  for (d=0; d<7; d++) /* loop to draw box */
    gl_fillbox(d,d,16-2*d,16-2*d, (d-6)*60);
  gl_getbox(0,0,16,16,box); /* get the box */

  /* draw the background stripes */

  for (d=0; d<HEIGHT; d++)
    gl_hline(0, d, WIDTH-1, d+1);

  /* the main loop. For fun, try adding a few
   * more boxes following the leader
   */

  for (c=d=0; d==0; d=vga_getkey()) {
    c++;
    x = 152*sin(c/37.0)+152;
    y = 92*sin(c/61.0)+93;
    gl_getbox(x,y,16,16,cut);
    gl_putboxmask(x,y,16,16,box);
    gl_copyscreen(physicalscreen);
    vga_waitretrace();
    gl_putbox(x,y,16,16,cut);
  }
  return 0;
}
