#define __RAWKS_INIT__
#define DBG 0

#include <sys/time.h>
#include <stdio.h>
#include "gl.h"
#include "gldevice.h"
#include <sys/types.h>
#include <signal.h>
#include "defines.h"
#include "protos.h"
#include "struct.h"
#include "globals.h"

/* I really had a hard time deciding how to do this.  Whether to use the
   overlay planes and have something cool in the background (like a nice
   picture or something).  It turned out that I had to leave out any
   background on account of compatibility with all SGI machines.
   Anyway, if I decided ahead of time, that would have made this much more
   readable.  And of course I'm too lazy to clean it up. 
   - Aaron Michael Hightower */

void clear_normal(void)
{
#ifdef __LINUX__
  gl_clearscreen(0);
#else
  frontbuffer(TRUE);
  C_BLACK;
  clear();
  frontbuffer(FALSE);
#endif
}

void setwinattr(void)
{
  static int last_dbuff=-1;
  static int dbuff=1;
  int temp;

  RGBmode();

  if(last_dbuff!=Opts.nodbuff) {
    if(Opts.nodbuff) singlebuffer();
    else doublebuffer();
    gconfig();
    last_dbuff = Opts.nodbuff; /* Trying to work around GL bug */
  }

  newsize();
  drawmode(NORMALDRAW);

  clear_normal();
  gflush();

  update_overlay(OLAY_TEXT|OLAY_CLEAR);

  cursoff();
}

void newsize(void)
{
  long dx=0,dy=0;
  long x,y;

  getsize(&x,&y);

  Sizex = x;
  Sizey = y;

  if(Opts.noborder) noborder();
  winconstraints();

  viewport(0,x-1,0,y-1);
}

void initwindow(void)
{
  Sizex=getgdesc(GD_XPMAX);
  Sizey=getgdesc(GD_YPMAX);
  if (Opts.fullscreen) {
    prefposition(0,Sizex-1,0,Sizey-1);
  } else {
    prefposition(Opts.xoff,Opts.xoff+Opts.xsize,Opts.yoff,
		     Opts.yoff+Opts.ysize);
  }
#ifdef FOREGROUND
  foreground();
#endif

  Window = winopen("rAWKs");
#ifdef __LINUX__
  Opts.nodbuff = 1; /* linux vers does not support hardware double buffering */
#endif
  qdevice(WINQUIT);
  qdevice(WINSHUT);

  Font = openvecfont(50,30,0.7);
  winconstraints();
/*   keepaspect(Sizex,Sizey); */

  setwinattr();
  update_overlay(OLAY_CLEAR);
}

void closeall(void)
{
#ifndef __LINUX__
  setvaluator(MOUSEX,getgdesc(GD_XPMAX)>>1,0,getgdesc(GD_XPMAX)-1);
  setvaluator(MOUSEY,getgdesc(GD_YPMAX)>>1,0,getgdesc(GD_YPMAX)-1);

  drawmode(PUPDRAW);
  color(0);
  clear();
#endif
  drawmode(NORMALDRAW);
  cpack(0);
  clear();
  my_swapbuffers(NORMALDRAW);

  end_sound();
  if(Window) winclose(Window);
  exit(0);
}

void initvars(void)
{
  int i,j;

  Speed = INIT_SPEED;
  Smallfont = openvecfont(120,75,0.7);
  Mediumfont = openvecfont(80,50,0.7);
  Largefont = openvecfont(40,25,0.7);
  init_score_fonts();
#ifndef NO_SOUND
  Has_snd_hardware = check_for_audio_hw();
#endif
  Num_scores = MAX_PLAYERS;
  for(i=1;i<=Num_scores;i++) P[i].color = ship_color(i);
  for(i=0;i<START_SND_QUEUESIZE;i++) Start_sound[i] = -1;
  End_sound = -1;
  make_math_tables();
  D_time = 1.0;
  set_frame_rate(120000); /* Get rid of ridiculous delays - Gee Chris! */
}
