#include <stdio.h>
#include <dos.h>
#include <math.h>
#include <string.h>
#include <malloc.h>
#include <time.h>
#include <stdlib.h>
#include <io.h>
#include <fcntl.h>
#include "3dproj.h"
#include "3ddefs.h"
#include "3dprep.h"
#include "3dvarse.h"

void  initialise_data(void)
{
  FILE *stream;
  char s1[80];
  time_t t;
  VtkObj object,light,camera;
  printf("\n\nLoading...\n");
  stream=fopen("3DDETAIL.CFG","r");
  fscanf(stream , "%s %d\n" , &s1,&videomode);
  fscanf(stream , "%s %d\n" , &s1,&rendermethod);
  fscanf(stream , "%s %d\n" , &s1,&cockpitrendermethod);
  fscanf(stream , "%s %d\n" , &s1,&smalldetails);
  fscanf(stream , "%s %f\n" , &s1,&renderdist);
  fscanf(stream , "%s %f\n" , &s1,&effectsrenderdist);
  fscanf(stream , "%s %d\n" , &s1,&lightsourcing);
  fscanf(stream , "%s %d\n" , &s1,&flames);
  fscanf(stream , "%s %d\n" , &s1,&sparks);
  fscanf(stream , "%s %d\n" , &s1,&complexity);
  fscanf(stream , "%s %d\n" , &s1,&starfield);
  fscanf(stream , "%s %d\n" , &s1,&planets);
  fscanf(stream , "%s %d\n" , &s1,&longlaser);
  fscanf(stream , "%s %d\n" , &s1,&debrisremoval);
  fscanf(stream , "%s %d\n" , &s1,&debris);
  fscanf(stream , "%s %d\n" , &s1,&drawcockpit);
  fscanf(stream , "%s %d\n" , &s1,&attachedobjects);
  fclose(stream);
  stream=fopen("3DSTICK.CFG","r");
  fscanf(stream,"%d\n",&jcenterx);
  fscanf(stream,"%d\n",&jcentery);
  fscanf(stream,"%d\n",&jmaxx);
  fscanf(stream,"%d\n",&jmaxy);
  fclose(stream);
  stream=fopen("3DOPTION.CFG","r");
  fscanf(stream,"%s %d\n",&s1,&control);
  fscanf(stream,"%s %d\n",&s1,&jsens);
  fscanf(stream,"%s %d\n",&s1,&msens);
  fscanf(stream,"%s %d\n",&s1,&fx);
  fscanf(stream,"%s %d\n",&s1,&music);
  fscanf(stream,"%s %d\n",&s1,&sampling);
  fscanf(stream,"%s %d\n",&s1,&volume);
  fscanf(stream,"%s %d\n",&s1,&difficulty);
  fscanf(stream,"%s %d\n",&s1,&triciacomputer);
  fclose(stream);
  if(music==1 || fx==1) soundblaster=1;
  srand((unsigned) time(&t));
  printf("Initialising 3dw_wat...\n");
  apiinstall();
  jjjtargt_open("TEXTURE.GUN");
  jjjtargt_permextract("BELTF.TM");
  jjjtargt_close();
  if(jjjtargt_open("OBJECTS.GUN")!=0) crashout("GUN: You do not have a big gun.");
  object=dddLoad(jjjtargt_tempextract("FITE5.3DW"));
  jjjtargt_close();

  dddMoveTo(object,0,0,240);
  dddRotateTo(object,-5000,30000,4000);
  dddSetShapeFlags(object,1);
  dddSetRenderMethod(object,RENDERED|ZBUFFERED|GOURAUD_SHADE);
  light=dddCreateLight(VECTOR_LIGHT,255,0);
  camera=dddCreateCamera(32000,100,100);
  dddCls();
  dddZBCls();
  dddClearObjects();
  dddInsertObject(object);
  dddInsertObject(light);
  dddSelectCamera(camera);
  dddDrawObjects();
  apiniceprint3(1,36,100,95,"S   E   C   E   S   S   I   O   N");
  dddScreenCopy();
  loadshapes(); // Load the shapes
  createstarfield(); // Load the starfield
  initsound();
}

void  deinitialise_data(void)
{
  deinitsound();
  apirestore();
}

void  allocate_memory_for_everything(void)
{
  int f;
  char s1[80];
  shapedata = ( struct SHAPEDATA * ) malloc ( (dddshapes+1) * sizeof ( struct SHAPEDATA ) );
  if (shapedata == NULL) crashout("STARTUP: Not enough shapedata memory");
  star = ( struct STAR * ) malloc ( (maxstars+1) * sizeof ( struct STAR ) );
  if (star==NULL) crashout("STARTUP: Not enough starfield memory");
  o = ( struct OBJECT * ) malloc ( (ships+2) * sizeof ( struct OBJECT ) );
  if (o == NULL) crashout("STARTUP: Not enough object memory");
  p = ( struct PROJECTILE * ) malloc ( (shapes+1) * sizeof ( struct PROJECTILE ) );
  if (p == NULL) crashout("STARTUP: Not enough projectile memory");
  c = ( struct COMMUNICATION * ) malloc ( (comms+1)  * sizeof ( struct COMMUNICATION ) );
  if (c == NULL) crashout("STARTUP: Not enough comms memory");
  matter = ( int * ) malloc ( (ships+1) * sizeof (int) );
  if (matter == NULL) crashout("STARTUP: Not enough mission memory");
  w = ( struct WAYPOINT * ) malloc ( (nowaypoints+1) * sizeof (struct WAYPOINT) );
  if (w==NULL) crashout("STARTUP: Not enough waypoint memory");
  co = ( struct CREATEOBJECT * ) malloc ( (ships+1)  * sizeof ( struct CREATEOBJECT ) );
  if (co == NULL) crashout("STARTUP: Not enough create object memory");
  oe = ( struct OBJECTEVENT * ) malloc ( (ships+1)  * sizeof ( struct OBJECTEVENT ) );
  if (oe == NULL) crashout("STARTUP: Not enough object event memory");
  ce = ( struct COMMUNICATIONEVENT * ) malloc ( (shapes+1)  * sizeof ( struct COMMUNICATIONEVENT ) );
  if (ce == NULL) crashout("STARTUP: Not enough comms events memory");
  gui = (struct GUIOBJECT * ) malloc ((numguiobjects+1) *sizeof(struct GUIOBJECT));
  if (gui == NULL) crashout("STARTUP: Not enough gui object memory");
  d = ( struct DEBRIS * ) malloc ( (101)  * sizeof ( struct DEBRIS ) );
  if (d == NULL) crashout("STARTUP: Not enough debris memory");
  gr = ( struct GROUND * ) malloc ( (26)  * sizeof ( struct GROUND ) );
  if (gr == NULL) crashout("STARTUP: Not enough ground memory");
  for (f=0; f<ships+2; f++)
  {
    o[f].type=-1;
    o[f].guns=0;
    o[f].turrets=0;
    o[f].crashzones=0;
    o[f].hangerzones=0;
  }
  if(jjjtargt_open("SOUND.GUN")!=0) crashout("GUN: You do not have a big gun for sound.");
  sound1[1]=LoadWave(jjjtargt_tempextract("plasma02.wav"),&length1[1]);
  sound1[2]=LoadWave(jjjtargt_tempextract("mghit02.wav"),&length1[2]);
  sound1[3]=LoadWave(jjjtargt_tempextract("zap3.wav"),&length1[3]);
  sound1[4]=LoadWave(jjjtargt_tempextract("bomb.wav"),&length1[4]);
  sound1[5]=LoadWave(jjjtargt_tempextract("beam.wav"),&length1[5]);
  sound1[6]=LoadWave(jjjtargt_tempextract("alien1.wav"),&length1[6]);
  sound1[7]=LoadWave(jjjtargt_tempextract("rocket02.wav"),&length1[7]);
  sound1[8]=LoadWave(jjjtargt_tempextract("plasma03.wav"),&length1[8]);
  sound1[9]=LoadWave(jjjtargt_tempextract("boom3.wav"),&length1[9]);
  sound1[10]=LoadWave(jjjtargt_tempextract("engine2.wav"),&length1[10]);
  sound1[11]=LoadWave(jjjtargt_tempextract("elect02.wav"),&length1[11]);
  sound1[12]=NULL; //LoadWave("flyby.wav",&length1[12]);
  sound1[13]=LoadWave(jjjtargt_tempextract("incoming.wav"),&length1[13]);
  sound1[14]=LoadWave(jjjtargt_tempextract("warning.wav"),&length1[14]);
// put in the triciasound1 stuff here
  triciasound1[1]=LoadWave(jjjtargt_tempextract("1.wav"),&tricialength1[1]);
  triciasound1[2]=LoadWave(jjjtargt_tempextract("2.wav"),&tricialength1[2]);
  triciasound1[3]=LoadWave(jjjtargt_tempextract("3.wav"),&tricialength1[3]);
  triciasound1[4]=LoadWave(jjjtargt_tempextract("4.wav"),&tricialength1[4]);
  triciasound1[5]=LoadWave(jjjtargt_tempextract("5.wav"),&tricialength1[5]);
  triciasound1[6]=LoadWave(jjjtargt_tempextract("6.wav"),&tricialength1[6]);
  triciasound1[7]=LoadWave(jjjtargt_tempextract("7.wav"),&tricialength1[7]);
  triciasound1[8]=LoadWave(jjjtargt_tempextract("8.wav"),&tricialength1[8]);
  triciasound1[9]=LoadWave(jjjtargt_tempextract("9.wav"),&tricialength1[9]);
  triciasound1[10]=LoadWave(jjjtargt_tempextract("10.wav"),&tricialength1[10]);
  triciasound1[11]=NULL;//LoadWave("11.wav",&tricialength1[11]);
  triciasound1[12]=NULL;//LoadWave("12.wav",&tricialength1[12]);
  triciasound1[13]=LoadWave(jjjtargt_tempextract("13.wav"),&tricialength1[13]);
  triciasound1[14]=LoadWave(jjjtargt_tempextract("14.wav"),&tricialength1[14]);
  triciasound1[15]=LoadWave(jjjtargt_tempextract("15.wav"),&tricialength1[15]);
  triciasound1[16]=LoadWave(jjjtargt_tempextract("16.wav"),&tricialength1[16]);
  triciasound1[17]=LoadWave(jjjtargt_tempextract("17.wav"),&tricialength1[17]);
  triciasound1[18]=LoadWave(jjjtargt_tempextract("18.wav"),&tricialength1[18]);
  triciasound1[19]=LoadWave(jjjtargt_tempextract("19.wav"),&tricialength1[19]);
  modsong[0] = LoadMod(jjjtargt_tempextract("jcb1.mod"),(char *)s1);
  modsong[1] = LoadMod(jjjtargt_tempextract("jcb1.mod"),(char *)s1);
  modsong[2] = LoadMod(jjjtargt_tempextract("jcb2.mod"),(char *)s1);
  modsong[3] = LoadMod(jjjtargt_tempextract("jcb3.mod"),(char *)s1);
  jjjtargt_close();
}

void  free_memory_for_everything(void)
{
  if (star!=NULL) free (star);
  if (shapedata!=NULL) free (shapedata);
  if (o!=NULL) free (o);
  if (p!=NULL) free (p);
  if (c!=NULL) free (c);
  if (w!=NULL) free (w);
  if (co!=NULL) free (co);
  if (oe!=NULL) free (oe);
  if (ce!=NULL) free (ce);
  if (gui!=NULL) free (gui);
  if (matter!=NULL) free (matter);
  if (d!=NULL) free (d);
  if (gr!=NULL) free (gr);
  if(sound1[0]!=NULL) free(sound1[0]);
  if(sound1[1]!=NULL) free(sound1[1]);
  if(sound1[2]!=NULL) free(sound1[2]);
  if(sound1[3]!=NULL) free(sound1[3]);
  if(sound1[4]!=NULL) free(sound1[4]);
  if(sound1[5]!=NULL) free(sound1[5]);
  if(sound1[6]!=NULL) free(sound1[6]);
  if(sound1[7]!=NULL) free(sound1[7]);
  if(sound1[8]!=NULL) free(sound1[8]);
  if(sound1[9]!=NULL) free(sound1[9]);
  if(sound1[10]!=NULL) free(sound1[10]);
  if(sound1[11]!=NULL) free(sound1[11]);
  if(sound1[12]!=NULL) free(sound1[12]);
  if(sound1[13]!=NULL) free(sound1[13]);
  if(sound1[14]!=NULL) free(sound1[14]);
  if(sound1[15]!=NULL) free(sound1[15]);
  if(sound1[16]!=NULL) free(sound1[16]);
  if(sound1[17]!=NULL) free(sound1[17]);
  if(sound1[18]!=NULL) free(sound1[18]);
  if(sound1[19]!=NULL) free(sound1[19]);
// put in the triciasound1 stuff here
  if(triciasound1[1]!=NULL) free(triciasound1[1]);
  if(triciasound1[2]!=NULL) free(triciasound1[2]);
  if(triciasound1[3]!=NULL) free(triciasound1[3]);
  if(triciasound1[4]!=NULL) free(triciasound1[4]);
  if(triciasound1[5]!=NULL) free(triciasound1[5]);
  if(triciasound1[6]!=NULL) free(triciasound1[6]);
  if(triciasound1[7]!=NULL) free(triciasound1[7]);
  if(triciasound1[8]!=NULL) free(triciasound1[8]);
  if(triciasound1[9]!=NULL) free(triciasound1[9]);
  if(triciasound1[10]!=NULL) free(triciasound1[10]);
  if(triciasound1[11]!=NULL) free(triciasound1[11]);
  if(triciasound1[12]!=NULL) free(triciasound1[12]);
  if(triciasound1[13]!=NULL) free(triciasound1[13]);
  if(triciasound1[14]!=NULL) free(triciasound1[14]);
  if(triciasound1[15]!=NULL) free(triciasound1[15]);
  if(triciasound1[16]!=NULL) free(triciasound1[16]);
  if(triciasound1[17]!=NULL) free(triciasound1[17]);
  if(triciasound1[18]!=NULL) free(triciasound1[18]);
  if(triciasound1[19]!=NULL) free(triciasound1[19]);

  if(modsong[0]!=NULL) FreeMod(modsong[0]);
  if(modsong[1]!=NULL) FreeMod(modsong[1]);
  if(modsong[2]!=NULL) FreeMod(modsong[2]);
  if(modsong[3]!=NULL) FreeMod(modsong[3]);
}

void  free_memory_for_ship(int f)
{
  int g,h;
  o[f].type=-1; // Vanish the ship
  if (o[f].guns>0)
  {
    free( o[f].g );
    o[f].guns=0;
  }
  if (o[f].turrets>0)
  {
    free( o[f].t );
    o[f].turrets=0;
  }
  if (o[f].crashzones>0)
  {
    free( o[f].c );
    o[f].crashzones=0;
  }
  if (o[f].hangerzones>0)
  {
    free( o[f].h );
    o[f].hangerzones=0;
  }
  if (o[0].target==f)
  {
    o[0].target=-1;
    targetinfoupdown=10;
    if (view==8 || view==9) view=0;
  }
  for (g=0; g<shapes; g++) // Make sure that there are no homing projectiles attacking this guy.
    if (p[g].target==oe[f].no && p[g].type==MISSILE || p[g].type==TORP || p[g].type==NUKE || p[g].type==BOMB) p[g].target=-1;
  for (g=1; g<ships; g++) // Make sure that there are no ships targetting this man
  {
    if (o[g].target==oe[f].no) o[g].target=-1;
    for (h=0; h<o[g].turrets; h++) // Make no turrets target this man.
      if (o[g].t[h].target==oe[f].no) o[g].t[h].target=-1;
  }
}

void  turretallocate(int f)
{
  int g;
  char s1[80];
  if (o[f].turrets<=0) return;
  sprintf(s1,"Allocating memory for %d turrets for object %d",o[f].turrets,f);
  o[f].t = (struct TURRET *) malloc ( (o[f].turrets) * sizeof (struct TURRET) );
  if (o[f].t == NULL ) crashout(s1);
  else for (g=0; g<o[f].turrets; g++)
  {
    o[f].t[g].object=dddLoad("turret1.3dw");
    o[f].t[g].gun=dddLoad("gun1.3dw");
    o[f].t[g].shape=54;
    o[f].t[g].cx=0;      o[f].t[g].cy=0;      o[f].t[g].cz=0;
    o[f].t[g].rx=o[f].t[g].ry=o[f].t[g].rz=0;
    o[f].t[g].srx=o[f].t[g].sry=o[f].t[g].srz=0;
    o[f].t[g].dx[0]=0.1; o[f].t[g].dy[0]=0.1; o[f].t[g].dz[0]=100;
    o[f].t[g].dx[1]=0.1; o[f].t[g].dy[1]=100; o[f].t[g].dz[1]=0.1;
    o[f].t[g].dx[2]=100; o[f].t[g].dy[2]=0.1; o[f].t[g].dz[2]=0.1;
    o[f].t[g].sx=0.1;    o[f].t[g].sy=-100 ;  o[f].t[g].sz=0.1;
    o[f].t[g].sx2=-100;    o[f].t[g].sy2=0.1 ;  o[f].t[g].sz2=0.1;
    o[f].t[g].target=-1;
    o[f].t[g].fireframe=0;
    o[f].t[g].hits=0;
    o[f].t[g].damage=0;
    o[f].t[g].deadframe=0;
    o[f].t[g].type=LASER;
  }
}
void  gunallocate(int f)
{
  int g;
  char s1[80];
  if (o[f].guns<=0) return;
  sprintf(s1,"Allocating memory for %d guns for object %d",o[f].guns,f);
  o[f].g = (struct GUN *) malloc ( (o[f].guns) * sizeof (struct GUN) );
  if (o[f].g == NULL ) crashout(s1);
  else for (g=0; g<o[f].guns; g++)
  {
    o[f].g[g].selected=1;
    o[f].g[g].type=LASER;
    o[f].g[g].fireframe=0;
    o[f].g[g].fireflag=1;
    o[f].g[g].gun=0.1;
    o[f].g[g].gunz=-0.1;
    o[f].g[g].guny=0;
    o[f].g[g].left=1;
  }
}
void  crashzoneallocate(int f)
{
  int g;
  char s1[80];
  if (o[f].crashzones<=0) return;
  sprintf(s1,"Allocating memory for %d crashzones for object %d",o[f].crashzones,f);
  o[f].c = (struct CRASHZONE *) malloc ( (o[f].crashzones) * sizeof (struct CRASHZONE) );
  if (o[f].c == NULL ) crashout(s1);
  else for (g=0; g<o[f].crashzones; g++)
  {
    o[f].c[g].size=100;
    o[f].c[g].x=100;
    o[f].c[g].y=100;
    o[f].c[g].z=100;
  }
}
void  hangerzoneallocate(int f)
{
  int g;
  char s1[80];
  if (o[f].hangerzones<=0) return;
  sprintf(s1,"Allocating memory for %d hangers for object %d",o[f].hangerzones,f);
  o[f].h = (struct HANGERZONE *) malloc ( (o[f].hangerzones) * sizeof (struct HANGERZONE) );
  if (o[f].t == NULL ) crashout(s1);
  else for (g=0; g<o[f].hangerzones; g++)
  {
    o[f].h[g].object=dddLoad("hanger1.3dw");
    o[f].h[g].type=1; // Normal hanger
    o[f].h[g].cx=10;      o[f].h[g].cy=10;      o[f].h[g].cz=10;
    o[f].h[g].dx[0]=0.1; o[f].h[g].dy[0]=0.1; o[f].h[g].dz[0]=100;
    o[f].h[g].dx[1]=0.1; o[f].h[g].dy[1]=100; o[f].h[g].dz[1]=0.1;
    o[f].h[g].dx[2]=100; o[f].h[g].dy[2]=0.1; o[f].h[g].dz[2]=0.1;
    o[f].h[g].rx=1000;      o[f].h[g].ry=1000;      o[f].h[g].rz=1000;
  }
}

void  crashout(char reason[80])
{
  int f;
  if (star!=NULL) free (star);
  if (shapedata!=NULL) free (shapedata);
  if (o!=NULL)
  {
    for (f=0; f<ships; f++)
    {
      if (o[f].guns>0) free( o[f].g );
      if (o[f].turrets>0) free( o[f].t );
      if (o[f].crashzones>0) free( o[f].c );
    }
    free (o);
  }
  if (p!=NULL) free (p);
  if (c!=NULL) free (c);
  if (w!=NULL) free (w);
  if (co!=NULL) free (co);
  if (oe!=NULL) free (oe);
  if (ce!=NULL) free (ce);
  if (gui!=NULL) free (ce);
  if (matter!=NULL) free (matter);
  apirestore();
  printf("%s\n",reason);
  /*
  for (f=0; f<ships+1; f++)
  {
    if (o[f].type>-1)
    {
      printf("Starship %i exists\n",f );
      if (o[f].guns>0) printf("Starship %i has %i guns \n",f,o[f].guns );
      if (o[f].turrets>0) printf("Starship %i has %i turrets \n",f,o[f].turrets );
      if (o[f].crashzones>0) printf("Starship %i has %i crashzones \n",f,o[f].crashzones );
      if (o[f].hangerzones>0) printf("Starship %i has %i hangerzones \n",f,o[f].hangerzones );
    }
  }
  */
  exit(0);
}

void  loadshapes(void)
{
  int f,i;
  for (f=0; f<dddshapes; f++)
  {
    shapedata[f].scale=5;
    sprintf(shapedata[f].name,"SHAPE %d",f);
    sprintf(shapedata[f].type,"TYPE %d",f);
  }

  sprintf(shapedata[1].filename,"laser1.3dw");
  sprintf(shapedata[2].filename,"laser2.3dw");
  sprintf(shapedata[3].filename,"line1.3dw");
  sprintf(shapedata[4].filename,"line2.3dw");
  sprintf(shapedata[5].filename,"beam1.3dw");
  sprintf(shapedata[6].filename,"beam2.3dw");
  sprintf(shapedata[7].filename,"ion1.3dw");
  sprintf(shapedata[8].filename,"hit1.3dw");
  sprintf(shapedata[9].filename,"smoke1.3dw");
  sprintf(shapedata[10].filename,"fite1.3dw");
  sprintf(shapedata[11].filename,"fite2.3dw");
  sprintf(shapedata[12].filename,"fite3.3dw");
  sprintf(shapedata[13].filename,"fite4.3dw");
  sprintf(shapedata[14].filename,"fite5.3dw");
  sprintf(shapedata[15].filename,"fite6.3dw");
  sprintf(shapedata[16].filename,"fite7.3dw");
  sprintf(shapedata[17].filename,"fite8.3dw");
  sprintf(shapedata[18].filename,"fite9.3dw");
  sprintf(shapedata[19].filename,"corv1.3dw");
  sprintf(shapedata[20].filename,"corv2.3dw");
  sprintf(shapedata[21].filename,"frig3.3dw");
  sprintf(shapedata[22].filename,"frig2.3dw");
  sprintf(shapedata[23].filename,"dest1.3dw");
  sprintf(shapedata[24].filename,"dest2.3dw");
  sprintf(shapedata[25].filename,"batt3.3dw");
  sprintf(shapedata[26].filename,"batt2.3dw");
  sprintf(shapedata[27].filename,"carr1.3dw");
  sprintf(shapedata[28].filename,"carr2.3dw");
  sprintf(shapedata[29].filename,"moon.3dw");
  sprintf(shapedata[30].filename,"mars.3dw");
  sprintf(shapedata[31].filename,"jupiter.3dw");
  sprintf(shapedata[32].filename,"saturn.3dw");
  sprintf(shapedata[33].filename,"titan.3dw");
  sprintf(shapedata[34].filename,"uranus.3dw");
  sprintf(shapedata[35].filename,"neptune.3dw");
  sprintf(shapedata[36].filename,"asteroi1.3dw");
  sprintf(shapedata[37].filename,"asteroi2.3dw");
  sprintf(shapedata[38].filename,"asteroi3.3dw");
  sprintf(shapedata[39].filename,"laser3.3dw");
  sprintf(shapedata[40].filename,"line3.3dw");
  sprintf(shapedata[41].filename,"spark1.3dw");
  sprintf(shapedata[42].filename,"spark2.3dw");
  sprintf(shapedata[43].filename,"wreck1.3dw");
  sprintf(shapedata[44].filename,"wreck2.3dw");
  sprintf(shapedata[45].filename,"wreck3.3dw");
  sprintf(shapedata[46].filename,"wreck4.3dw");
  sprintf(shapedata[47].filename,"wreck5.3dw");
  sprintf(shapedata[48].filename,"wreck6.3dw");
  sprintf(shapedata[49].filename,"hanger2.3dw");
  sprintf(shapedata[50].filename,"star1.3dw");
  sprintf(shapedata[51].filename,"star2.3dw");
  sprintf(shapedata[52].filename,"star3.3dw");
  sprintf(shapedata[53].filename,"star4.3dw");
  sprintf(shapedata[54].filename,"turret1.3dw");
  sprintf(shapedata[55].filename,"gun1.3dw");
  sprintf(shapedata[56].filename,"missile2.3dw");
  sprintf(shapedata[57].filename,"torp1.3dw");
  sprintf(shapedata[58].filename,"bomb1.3dw");
  sprintf(shapedata[59].filename,"bomb2.3dw");
  sprintf(shapedata[60].filename,"sun.3dw");
  sprintf(shapedata[61].filename,"fakefite.3dw");
  sprintf(shapedata[62].filename,"boom.3dw");
  sprintf(shapedata[63].filename,"boom2.3dw");
  sprintf(shapedata[64].filename,"boom3.3dw");
  sprintf(shapedata[65].filename,"gun2.3dw");
  sprintf(shapedata[66].filename,"gun3.3dw");
  sprintf(shapedata[67].filename,"main1.3dw");
  sprintf(shapedata[68].filename,"main2.3dw");
  sprintf(shapedata[69].filename,"main3.3dw");
  sprintf(shapedata[70].filename,"main4.3dw");
  sprintf(shapedata[71].filename,"alien2.3dw");
  sprintf(shapedata[72].filename,"torp2.3dw");
  sprintf(shapedata[73].filename,"beam3.3dw");
  sprintf(shapedata[74].filename,"hanger1.3dw");
  sprintf(shapedata[75].filename,"gun4.3dw");
  sprintf(shapedata[76].filename,"alien1.3dw");
  sprintf(shapedata[77].filename,"sport1.3dw");
  sprintf(shapedata[78].filename,"boom4.3dw");
  sprintf(shapedata[79].filename,"board1.3dw"); //Crashes mission editor
  sprintf(shapedata[80].filename,"boom5.3dw");
  sprintf(shapedata[81].filename,"earth.3dw");
  sprintf(shapedata[82].filename,"luna.3dw");
  sprintf(shapedata[83].filename,"galaxy.3dw");
  sprintf(shapedata[84].filename,"cfite1.3dw");
  sprintf(shapedata[85].filename,"cattack1.3dw");
  sprintf(shapedata[86].filename,"claunch.3dw");
  sprintf(shapedata[87].filename,"rfite1.3dw");
  sprintf(shapedata[88].filename,"rfite2.3dw");
  sprintf(shapedata[89].filename,"rcruiser.3dw");
  sprintf(shapedata[90].filename,"grbase1.3dw");
  sprintf(shapedata[91].filename,"grbase1.3dw");
  sprintf(shapedata[92].filename,"grbase5.3dw");
  sprintf(shapedata[93].filename,"grbase6.3dw");
  sprintf(shapedata[94].filename,"ground1.3dw");
  sprintf(shapedata[95].filename,"ground2.3dw");
  sprintf(shapedata[96].filename,"ground3.3dw");
  sprintf(shapedata[97].filename,"sky.3dw");
  sprintf(shapedata[98].filename,"grbase3.3dw");
  sprintf(shapedata[99].filename,"mount2.3dw");
  sprintf(shapedata[100].filename,"mount3.3dw");
  sprintf(shapedata[101].filename,"neb1.3dw");
  sprintf(shapedata[102].filename,"neb2.3dw");
  sprintf(shapedata[103].filename,"neb3.3dw");
  sprintf(shapedata[104].filename,"SPARK3.3DW");
  sprintf(shapedata[105].filename,"RED.3DW");
  sprintf(shapedata[106].filename,"COCK6.3DW");
  sprintf(shapedata[107].filename,"EX2.3DW");
  sprintf(shapedata[108].filename,"EX1.3DW");
  sprintf(shapedata[109].filename,"COMM6.3DW");
  sprintf(shapedata[110].filename,"GRBASE7.3DW");
  sprintf(shapedata[111].filename,"COCK.3DW");
  sprintf(shapedata[112].filename,"TARGET.3DW");
  sprintf(shapedata[113].filename,"BOOM6.3DW");
  sprintf(shapedata[114].filename,"COMM2.3DW");
  sprintf(shapedata[115].filename,"GROUND4.3DW");
  sprintf(shapedata[116].filename,"COCK1.3DW");
  sprintf(shapedata[117].filename,"COCK2.3DW");
  sprintf(shapedata[118].filename,"COCK3.3DW");
  sprintf(shapedata[119].filename,"COCK5.3DW");
  sprintf(shapedata[120].filename,"COCK4.3DW");
  sprintf(shapedata[121].filename,"COMM3.3DW");
  sprintf(shapedata[122].filename,"COMM4.3DW");
  sprintf(shapedata[123].filename,"COMM1.3DW");
  sprintf(shapedata[124].filename,"EX3.3DW");
  sprintf(shapedata[125].filename,"EX4.3DW");
  sprintf(shapedata[126].filename,"GRBASE2.3DW");
  sprintf(shapedata[127].filename,"GRBASE4.3DW");
  sprintf(shapedata[128].filename,"COMM5.3DW");
  sprintf(shapedata[129].filename,"LOADING.3DW");
  // Belt fighters
  shapedata[10].scale=0.5; strcpy(shapedata[10].name,"JUNO-II"); strcpy(shapedata[10].type,"FIGHTER");
  shapedata[13].scale=0.5; strcpy(shapedata[13].name,"PALLAS-X"); strcpy(shapedata[13].type,"MEDIUM FIGHTER");
  shapedata[14].scale=0.75;strcpy(shapedata[14].name,"CERES-V"); strcpy(shapedata[14].type,"HEAVY FIGHTER");
  shapedata[15].scale=0.5; strcpy(shapedata[15].name,"NEMESIS"); strcpy(shapedata[15].type,"BOMBER");
  // UEA fighters
  shapedata[11].scale=0.4; strcpy(shapedata[11].name,"F400 STING"); strcpy(shapedata[11].type,"LIGHT FIGHTER");
  shapedata[16].scale=0.75; strcpy(shapedata[16].name,"F499 THORN"); strcpy(shapedata[16].type,"MEDIUM FIGHTER");
  shapedata[12].scale=0.65; strcpy(shapedata[12].name,"CONQUORER"); strcpy(shapedata[12].type,"HEAVY FIGHTER");
  shapedata[17].scale=0.85; strcpy(shapedata[17].name,"PREDATOR"); strcpy(shapedata[17].type,"ASSAULT FIGHTER");
  shapedata[18].scale=0.6; strcpy(shapedata[18].name,"B-666 VENGER"); strcpy(shapedata[18].type,"BOMBER");
  // Belt capital ships
  shapedata[19].scale=5; strcpy(shapedata[19].name,"PLANETARY"); strcpy(shapedata[19].type,"CORVETTE");
  shapedata[21].scale=8; strcpy(shapedata[21].name,"STELLAR"); strcpy(shapedata[21].type,"ESCORT FRIGATE");
  shapedata[23].scale=8; strcpy(shapedata[23].name,"NOVA"); strcpy(shapedata[23].type,"DESTROYER");
  shapedata[25].scale=14; strcpy(shapedata[25].name,"LEVIATHAN"); strcpy(shapedata[25].type,"BATTLESHIP");
  shapedata[28].scale=10; strcpy(shapedata[28].name,"AVENGER"); strcpy(shapedata[28].type,"CARRIER");
  // UEA capital ships
  shapedata[20].scale=5; strcpy(shapedata[20].name,"MILITARY"); strcpy(shapedata[20].type,"PICKET");
  shapedata[22].scale=8; strcpy(shapedata[22].name,"NEWCASTLE"); strcpy(shapedata[22].type,"FRIGATE");
  shapedata[24].scale=10;strcpy(shapedata[24].name,"FEDERAL"); strcpy(shapedata[24].type,"DESTROYER");
  shapedata[26].scale=19;strcpy(shapedata[26].name,"IMPERIAL"); strcpy(shapedata[26].type,"BATTLESHIP");
  shapedata[27].scale=10;strcpy(shapedata[27].name,"LEXINGTON"); strcpy(shapedata[27].type,"CARRIER");
  //Other shit
  shapedata[29].scale=1;
  shapedata[30].scale=1;
  shapedata[31].scale=10;
  shapedata[32].scale=10;
  shapedata[33].scale=1;
  shapedata[34].scale=10;
  shapedata[35].scale=10;
  // Large stones
  shapedata[36].scale=4; strcpy(shapedata[36].name,"LARGE"); strcpy(shapedata[36].type,"ASTEROID");
  shapedata[37].scale=3; strcpy(shapedata[37].name,"MEDIUM"); strcpy(shapedata[37].type,"ASTEROID");
  shapedata[38].scale=2; strcpy(shapedata[38].name,"SMALL"); strcpy(shapedata[38].type,"ASTEROID");
  // More shit
  shapedata[60].scale=1;
  shapedata[71].scale=5;    strcpy(shapedata[71].name,"UNKNOWN");       strcpy(shapedata[71].type,"ALIEN CRAFT");
  shapedata[76].scale=1.5;  strcpy(shapedata[76].name,"UNKNOWN");       strcpy(shapedata[76].type,"ALIEN CRAFT");
  shapedata[77].scale=3.5;  strcpy(shapedata[77].name,"BULK");          strcpy(shapedata[77].type,"TRANSPORT");
  shapedata[79].scale=1.5; strcpy(shapedata[79].name,"RAPE");           strcpy(shapedata[79].type,"BOARDER");
  // non belt/uea beasties
  shapedata[84].scale=0.9; strcpy(shapedata[84].name,"FIGHTER"); strcpy(shapedata[84].type,"UCORP SHIP");
  shapedata[85].scale=10; strcpy(shapedata[85].name,"ATTACK SHIP"); strcpy(shapedata[85].type,"UCORP SHIP");
  shapedata[86].scale=18; strcpy(shapedata[86].name,"BESERKER"); strcpy(shapedata[86].type,"UCORP SHIP");
  shapedata[87].scale=0.9; strcpy(shapedata[87].name,"HURRICANE"); strcpy(shapedata[87].type,"FIGHTER");
  shapedata[88].scale=0.9; strcpy(shapedata[88].name,"VORTEX"); strcpy(shapedata[88].type,"HEAVY FIGHTER");
  shapedata[89].scale=10; strcpy(shapedata[89].name,"ROYAL"); strcpy(shapedata[89].type,"CRUISER");
  shapedata[90].scale=15; strcpy(shapedata[90].name,"MILITARY"); strcpy(shapedata[90].type,"INSTALLATION");
  shapedata[91].scale=15; strcpy(shapedata[91].name,"METROPOLIS"); strcpy(shapedata[91].type,"CITY");
  shapedata[92].scale=15; strcpy(shapedata[92].name,"NEVADA"); strcpy(shapedata[92].type,"MILITARY BASE");
  shapedata[93].scale=15; strcpy(shapedata[93].name,"LIGHT"); strcpy(shapedata[93].type,"BUILDINGS");
  shapedata[98].scale=3; strcpy(shapedata[98].name,"OMNI D"); strcpy(shapedata[98].type,"LIGHT TURRET");
  shapedata[99].scale=3; strcpy(shapedata[99].name,"MOUNT2"); strcpy(shapedata[99].type,"MOUNTAIN");
  shapedata[100].scale=3; strcpy(shapedata[100].name,"MOUNT3"); strcpy(shapedata[100].type,"MOUNTAIN");
  apiniceprint3(21,36,280,190,"LOADING...");
  apiscreenswap();
  jjjtargt_open("TEXTURE.GUN");
  jjjtargt_permextract("FIRE2.TM");
  jjjtargt_permextract("UEA.TM");
  jjjtargt_permextract("BELT.TM");
  jjjtargt_permextract("LUNA.TM");
  jjjtargt_permextract("HANGER.TM");
  jjjtargt_permextract("INTERIOR.TM");
  jjjtargt_permextract("ROCK.TM");
  jjjtargt_permextract("JUPITER.TM");
  jjjtargt_permextract("BLUE.TM");
  jjjtargt_permextract("EARTH.TM");
  jjjtargt_permextract("BELTF.TM");
  jjjtargt_permextract("UEAF.TM");
  jjjtargt_permextract("ALIEN.TM");
  jjjtargt_permextract("COCK.TM");
  jjjtargt_permextract("GALAXY.TM");
  jjjtargt_permextract("MOON.TM");
  jjjtargt_permextract("CORP.TM");
  jjjtargt_permextract("ROYAL.TM");
  jjjtargt_permextract("EX.TM");
  jjjtargt_permextract("MARS.TM");
  jjjtargt_permextract("ICE.TM");
  jjjtargt_permextract("SKY.TM");
  jjjtargt_permextract("NEB1.TM");
  jjjtargt_permextract("NEB2.TM");
  jjjtargt_permextract("NEB3.TM");
  jjjtargt_permextract("LOADING.TM");
  jjjtargt_close();
//  while(!key[_ESC]);
  jjjtargt_open("OBJECTS.GUN");
  for(i=1;i<=129;i++)
  {
    ShapeHandle[i] = dddLoad(jjjtargt_tempextract(shapedata[i].filename));
    if(i%10==0)
    {
      apiniceprint3((i%20?1:21),(i%20?130:36),280,190,"LOADING...");
      for(f=0;f<i;f+=1)
      {
        apiline(128,((float)(f)/(float)(dddshapes))*280,192,
                    ((float)(f)/(float)(dddshapes))*280,194);
        apiline(112,((float)(f)/(float)(dddshapes))*280,193,
                    ((float)(f)/(float)(dddshapes))*280,193);
      }
    }
    apiscreenswap();
  }
  jjjtargt_close();
  remove("FIRE2.TM");
  remove("UEA.TM");
  remove("BELT.TM");
  remove("LUNA.TM");
  remove("HANGER.TM");
  remove("INTERIOR.TM");
  remove("ROCK.TM");
  remove("JUPITER.TM");
  remove("BLUE.TM");
  remove("EARTH.TM");
  remove("BELTF.TM");
  remove("UEAF.TM");
  remove("ALIEN.TM");
  remove("COCK.TM");
  remove("GALAXY.TM");
  remove("MOON.TM");
  remove("CORP.TM");
  remove("ROYAL.TM");
  remove("EX.TM");
  remove("MARS.TM");
  remove("ICE.TM");
  remove("SKY.TM");
  remove("NEB1.TM");
  remove("NEB2.TM");
  remove("NEB3.TM");
  remove("LOADING.TM");
}

void  load(char filename[20])
{
  char file[30],encrypt[30];
  char s1[80];
  int f,g,handle,inte;
  inte=16000;
  apiniceprint3(1,130,280,185,"LOADING...");
  if(debug==1) apiniceprint3(1,130,10,175,"LOADING" );
  apiscreenswap();
  sprintf(file,"%s.MSN",filename);
  handle=open(file,O_RDONLY|O_BINARY);
  sprintf(s1,"failed to open mission file %s",file);
  if(handle==-1) crashout(s1);

  read(handle,&encrypt,sizeof(encrypt));
  for(f=0;f<strlen(encrypt);f++)
  {
    encrypt[f]=encrypt[f]-f;
  }
  if(strcmp(strupr(encrypt),strupr(file))!=0)
  {
    crashout("DISK: Bad mission file");
  }

  read(handle,&norand,sizeof(norand));
  read(handle,&finishtime,sizeof(finishtime));
  read(handle,&startflag,sizeof(startflag));
  read(handle,&ground,sizeof(ground));
  for (f=0; f<nowaypoints; f++) read(handle,&w[f],sizeof(w[f]));
  for (f=0; f<ships; f++) read(handle,&matter[f],sizeof(matter[f]));
  for (f=0; f<ships; f++) read(handle,&oe[f],sizeof(oe[f]));
  for (f=0; f<ships; f++) read(handle,&co[f],sizeof(co[f]));
  for (f=0; f<shapes; f++) read(handle,&ce[f],sizeof(ce[f]));
  for (f=shapes-10; f<shapes; f++) read(handle,&p[f],sizeof(p[f]));
  for (f=0; f<9; f++) read(handle,&gr[f],sizeof(gr[f]));
  for (f=0; f<ships; f++)
  {
    read(handle,&o[f].shape,sizeof(o[f].shape));
    read(handle,&o[f].type,sizeof(o[f].type));
    read(handle,&o[f].frame1,sizeof(o[f].frame1));
    read(handle,&o[f].frame2,sizeof(o[f].frame2));
    read(handle,&o[f].frame3,sizeof(o[f].frame3));
    read(handle,&o[f].doing,sizeof(o[f].doing));
    read(handle,&o[f].smoking,sizeof(o[f].smoking));
    read(handle,&o[f].sparking,sizeof(o[f].sparking));
    read(handle,&o[f].side,sizeof(o[f].side));
    read(handle,&o[f].target,sizeof(o[f].target));
    read(handle,&o[f].speed,sizeof(o[f].speed));
    read(handle,&o[f].topspeed,sizeof(o[f].topspeed));
    read(handle,&o[f].toprevs,sizeof(o[f].toprevs));
    read(handle,&o[f].currentrevs,sizeof(o[f].currentrevs));
    read(handle,&o[f].shields,sizeof(o[f].shields));
    read(handle,&o[f].maxshields,sizeof(o[f].maxshields));
    read(handle,&o[f].armour,sizeof(o[f].armour));
    read(handle,&o[f].maxarmour,sizeof(o[f].maxarmour));
    read(handle,&o[f].sparkx,sizeof(o[f].sparkx));
    read(handle,&o[f].sparky,sizeof(o[f].sparky));
    read(handle,&o[f].sparkz,sizeof(o[f].sparkz));
    read(handle,&o[f].cx,sizeof(o[f].cx));
    read(handle,&o[f].cy,sizeof(o[f].cy));
    read(handle,&o[f].cz,sizeof(o[f].cz));
    read(handle,&o[f].sx,sizeof(o[f].sx));
    read(handle,&o[f].sy,sizeof(o[f].sy));
    read(handle,&o[f].sz,sizeof(o[f].sz));
    read(handle,&o[f].dx[0],sizeof(o[f].dx[0]));
    read(handle,&o[f].dy[0],sizeof(o[f].dy[0]));
    read(handle,&o[f].dz[0],sizeof(o[f].dz[0]));
    read(handle,&o[f].dx[1],sizeof(o[f].dx[1]));
    read(handle,&o[f].dy[1],sizeof(o[f].dy[1]));
    read(handle,&o[f].dz[1],sizeof(o[f].dz[1]));
    read(handle,&o[f].dx[2],sizeof(o[f].dx[2]));
    read(handle,&o[f].dy[2],sizeof(o[f].dy[2]));
    read(handle,&o[f].dz[2],sizeof(o[f].dz[2]));
    read(handle,&o[f].rx,sizeof(o[f].rx));
    read(handle,&o[f].ry,sizeof(o[f].ry));
    read(handle,&o[f].rz,sizeof(o[f].rz));
    read(handle,&o[f].rsx,sizeof(o[f].rsx));
    read(handle,&o[f].rsy,sizeof(o[f].rsy));
    read(handle,&o[f].rsz,sizeof(o[f].rsz));
    read(handle,&o[f].turrets,sizeof(o[f].turrets));
    read(handle,&o[f].guns,sizeof(o[f].guns));
    read(handle,&o[f].crashzones,sizeof(o[f].crashzones));
    read(handle,&o[f].hangerzones,sizeof(o[f].hangerzones));
    read(handle,&o[f].stubborn,sizeof(o[f].stubborn));
    read(handle,&o[f].wingleader,sizeof(o[f].wingleader));
    read(handle,&o[f].wingtype,sizeof(o[f].wingtype));
    read(handle,&o[f].wingx,sizeof(o[f].wingx));
    read(handle,&o[f].wingy,sizeof(o[f].wingy));
    read(handle,&o[f].wingz,sizeof(o[f].wingz));
    read(handle,&o[f].destination,sizeof(o[f].destination));
    read(handle,&o[f].name,sizeof(o[f].name));
    read(handle,&o[f].rank,sizeof(o[f].rank));
    read(handle,&o[f].mother,sizeof(o[f].mother));
    read(handle,&o[f].motherhangerzone,sizeof(o[f].motherhangerzone));
    if (o[f].type>-1)
    {
      if (o[f].turrets>0)
      {
        turretallocate(f);
        for (g=0; g<o[f].turrets; g++)
        {
          read(handle,&o[f].t[g].shape,sizeof(o[f].t[g].shape));
          read(handle,&o[f].t[g].type,sizeof(o[f].t[g].type));
          read(handle,&o[f].t[g].fireframe,sizeof(o[f].t[g].fireframe));
          read(handle,&o[f].t[g].target,sizeof(o[f].t[g].target));
          read(handle,&o[f].t[g].cx,sizeof(o[f].t[g].cx));
          read(handle,&o[f].t[g].cy,sizeof(o[f].t[g].cy));
          read(handle,&o[f].t[g].cz,sizeof(o[f].t[g].cz));
          read(handle,&o[f].t[g].dx[0],sizeof(o[f].t[g].dx[0]));
          read(handle,&o[f].t[g].dy[0],sizeof(o[f].t[g].dy[0]));
          read(handle,&o[f].t[g].dz[0],sizeof(o[f].t[g].dz[0]));
          read(handle,&o[f].t[g].dx[1],sizeof(o[f].t[g].dx[1]));
          read(handle,&o[f].t[g].dy[1],sizeof(o[f].t[g].dy[1]));
          read(handle,&o[f].t[g].dz[1],sizeof(o[f].t[g].dz[1]));
          read(handle,&o[f].t[g].dx[2],sizeof(o[f].t[g].dx[2]));
          read(handle,&o[f].t[g].dy[2],sizeof(o[f].t[g].dy[2]));
          read(handle,&o[f].t[g].dz[2],sizeof(o[f].t[g].dz[2]));
          read(handle,&o[f].t[g].rx,sizeof(o[f].t[g].rx));
          read(handle,&o[f].t[g].ry,sizeof(o[f].t[g].ry));
          read(handle,&o[f].t[g].rz,sizeof(o[f].t[g].rz));
          read(handle,&o[f].t[g].sx,sizeof(o[f].t[g].sx));
          read(handle,&o[f].t[g].sy,sizeof(o[f].t[g].sy));
          read(handle,&o[f].t[g].sz,sizeof(o[f].t[g].sz));
          read(handle,&o[f].t[g].sx2,sizeof(o[f].t[g].sx2));
          read(handle,&o[f].t[g].sy2,sizeof(o[f].t[g].sy2));
          read(handle,&o[f].t[g].sz2,sizeof(o[f].t[g].sz2));
          read(handle,&o[f].t[g].srx,sizeof(o[f].t[g].srx));
          read(handle,&o[f].t[g].sry,sizeof(o[f].t[g].sry));
          read(handle,&o[f].t[g].srz,sizeof(o[f].t[g].srz));
          read(handle,&o[f].t[g].hits,sizeof(o[f].t[g].hits));
          read(handle,&o[f].t[g].damage,sizeof(o[f].t[g].damage));
          read(handle,&o[f].t[g].deadframe,sizeof(o[f].t[g].deadframe));
        }
      }
      if (o[f].guns>0)
      {
        gunallocate(f);
        for (g=0; g<o[f].guns; g++)
        {
          read(handle,&o[f].g[g].type,      sizeof(o[f].g[g].type)    );
          read(handle,&o[f].g[g].selected,  sizeof(o[f].g[g].selected));
          read(handle,&o[f].g[g].fireframe, sizeof(o[f].g[g].fireframe));
          read(handle,&o[f].g[g].fireflag,  sizeof(o[f].g[g].fireflag));
          read(handle,&o[f].g[g].left,      sizeof(o[f].g[g].left)    );
          read(handle,&o[f].g[g].gun,       sizeof(o[f].g[g].gun)     );
          read(handle,&o[f].g[g].gunz,      sizeof(o[f].g[g].gunz)    );
          read(handle,&o[f].g[g].guny,      sizeof(o[f].g[g].guny)    );
        }
      }
      if (o[f].crashzones>0)
      {
        crashzoneallocate(f);
        for (g=0; g<o[f].crashzones; g++)
        {
          read(handle,&o[f].c[g].x,    sizeof(o[f].c[g].x)  );
          read(handle,&o[f].c[g].y,    sizeof(o[f].c[g].y)  );
          read(handle,&o[f].c[g].z,    sizeof(o[f].c[g].z)  );
          read(handle,&o[f].c[g].size, sizeof(o[f].c[g].size));
        }
      }
      if (o[f].hangerzones>0)
      {
        hangerzoneallocate(f);
        for (g=0; g<o[f].hangerzones; g++)
        {
          read(handle,&o[f].h[g].type,sizeof(o[f].h[g].type));
          read(handle,&o[f].h[g].frame1,sizeof(o[f].h[g].frame1));
          read(handle,&o[f].h[g].cx,sizeof(o[f].h[g].cx));
          read(handle,&o[f].h[g].cy,sizeof(o[f].h[g].cy));
          read(handle,&o[f].h[g].cz,sizeof(o[f].h[g].cz));
          read(handle,&o[f].h[g].dx[0],sizeof(o[f].h[g].dx[0]));
          read(handle,&o[f].h[g].dy[0],sizeof(o[f].h[g].dy[0]));
          read(handle,&o[f].h[g].dz[0],sizeof(o[f].h[g].dz[0]));
          read(handle,&o[f].h[g].dx[1],sizeof(o[f].h[g].dx[1]));
          read(handle,&o[f].h[g].dy[1],sizeof(o[f].h[g].dy[1]));
          read(handle,&o[f].h[g].dz[1],sizeof(o[f].h[g].dz[1]));
          read(handle,&o[f].h[g].dx[2],sizeof(o[f].h[g].dx[2]));
          read(handle,&o[f].h[g].dy[2],sizeof(o[f].h[g].dy[2]));
          read(handle,&o[f].h[g].dz[2],sizeof(o[f].h[g].dz[2]));
          read(handle,&o[f].h[g].rx,sizeof(o[f].h[g].rx));
          read(handle,&o[f].h[g].ry,sizeof(o[f].h[g].ry));
          read(handle,&o[f].h[g].rz,sizeof(o[f].h[g].rz));
        }
      }
    }
  }
  close(handle);
  if(debug==1){apigameprint3(1,10,185,"LOADED" );apiscreenswap();}

  //Initialise your ship properly.
  for (g=0; g<o[0].guns; g++)
  {
    if ((o[0].g[g].type==1)||(o[0].g[g].type==2)||
    (o[0].g[g].type==3)||(o[0].g[g].type==7)||
    (o[0].g[g].type==8) || o[0].g[g].type==11) o[0].g[g].selected=1;
    else o[0].g[g].selected=0;
  }
  if(norand==0)
  {
    o[0].rsx=o[0].rsy=o[0].rsz=0;
    o[0].speed=o[0].topspeed;             // Maximum speed
    o[0].cx=o[0].cz=0;
    o[0].cy=20;
    o[0].doing=ATTACKING;
  }
  else if(norand==1)
  {
    o[0].type=-1;
    free_memory_for_ship(0);
    o[0].speed=o[0].sz;
    srand(1);
  }
  //Do all the dddshape loads
  for(f=0;f<ships;f++) if(o[f].type>-1)
  {
    o[f].object=dddLoad(shapedata[o[f].shape].filename);
    if(attachedobjects==ON)
    {
      attach(f);
    }
    if(o[f].shape==90) attach90(f);
    else if(o[f].shape==91) attach91(f);
    else if(o[f].shape==92) attach92(f);
    else if(o[f].shape==93) attach93(f);
    o[f].farobject=dddLoad(shapedata[61].filename);
    o[f].spark=dddLoad(shapedata[8].filename);
    for(g=0;g<o[f].turrets;g++)
    {
      o[f].t[g].object=dddLoad(shapedata[54].filename);
      o[f].t[g].gun=dddLoad(shapedata[55].filename);
    }
    for(g=0;g<o[f].hangerzones;g++) if(o[f].h[g].type==1) o[f].h[g].object=dddLoad(shapedata[74].filename);
    if(o[f].dpt==1 && dpt[f]==0) free_memory_for_ship(f);
  }
  for(f=shapes-10;f<shapes;f++)
  {
    p[f].object=dddLoad(shapedata[p[f].shape].filename);
    p[f].farobject=dddLoad(shapedata[p[f].shape].filename);
  }
  if(ground>0)
  {
    for(f=0;f<9;f++) gr[f].object=dddLoad(shapedata[gr[f].shape].filename);
    dddAttach(gr[0].object,gr[4].object,"0",-inte,0,-inte,0,0,0);
    dddAttach(gr[1].object,gr[4].object,"1",0,0,-inte,0,0,0);
    dddAttach(gr[2].object,gr[4].object,"2",inte,0,-inte,0,0,0);
    dddAttach(gr[3].object,gr[4].object,"3",-inte,0,0,0,0,0);
    dddAttach(gr[5].object,gr[4].object,"5",inte,0,0,0,0,0);
    dddAttach(gr[6].object,gr[4].object,"6",-inte,0,inte,0,0,0);
    dddAttach(gr[7].object,gr[4].object,"7",0,0,inte,0,0,0);
    dddAttach(gr[8].object,gr[4].object,"8",inte,0,inte,0,0,0);
    sortgroundout();
  }
  for(f=0;f<ships;f++) co[f].object=dddLoad(shapedata[co[f].shape].filename);
  if (o[0].shape==10) cockpit=dddLoad("cock1.3dw"); // Juno
  else if (o[0].shape==11 || o[0].shape==16) cockpit=dddLoad("cock2.3dw"); // Sting and Thorn
  else if (o[0].shape==12 || o[0].shape==17) cockpit=dddLoad("cock4.3dw"); // Pallas and Ceres
  else if (o[0].shape==13 || o[0].shape==14) cockpit=dddLoad("cock3.3dw"); // Predator and Conquorer
  else if (o[0].shape==18 || o[0].shape==15) cockpit=dddLoad("cock5.3dw"); // Nemesis and Avenger
  else cockpit=dddLoad("cock6.3dw"); // Bridge
  if(debug==1){apigameprint3(1,10,195,"SHAPES LOADED" );apiscreenswap();}
  red=dddLoad("red.3dw");
  for (f=0; f<complines; f++)
  {
    compside[f]=o[0].side;
  }
  p[shapes-8].cx=0;
  p[shapes-8].cy=0;
  p[shapes-8].cz=0;
}

void attach(int f)
{
  int g;
  if(o[f].type>-1)
  {
    for(g=0;g<20;g++) o[f].thingytype[g]=0;
    if(o[f].shape==10) attach10(f);
    else if(o[f].shape==11) attach11(f);
    else if(o[f].shape==12) attach12(f);
    else if(o[f].shape==13) attach13(f);
    else if(o[f].shape==14) attach14(f);
    else if(o[f].shape==15) attach15(f);
    else if(o[f].shape==16) attach16(f);
    else if(o[f].shape==17) attach17(f);
    else if(o[f].shape==18) attach18(f);
    else if(o[f].shape==19) attach19(f);
    else if(o[f].shape==20) attach20(f);
    else if(o[f].shape==21) attach21(f);
    else if(o[f].shape==22) attach22(f);
    else if(o[f].shape==23) attach23(f);
    else if(o[f].shape==24) attach24(f);
    else if(o[f].shape==25) attach25(f);
    else if(o[f].shape==26) attach26(f);
    else if(o[f].shape==27) attach27(f);
    else if(o[f].shape==28) attach28(f);
    else if(o[f].shape==77) attach77(f);
    else if(o[f].shape==87) attach87(f);
    else if(o[f].shape==88) attach88(f);
  }
}

void detach(int f)
{
  int g;
  if(o[f].type>-1)
  {
    dddDetachChildren(o[f].object);
    for(g=0;g<o[g].thingys;g++)
    {
//      dddDetach(o[f].thingy[g]);
//      dddDestroy(o[f].thingy[g]);
      o[f].thingytype[g]=0;
    }
    o[f].thingys=0;
  }
}

void  reset(void)
{
  int f,g;
  w[0].x=0;             w[0].y=0;               w[0].z=327670L;
  w[1].x=0;             w[1].y=0;               w[1].z=-327670L;
  w[2].x=327670L;       w[2].y=0;               w[2].z=0;
  w[3].x=-327670L;      w[3].y=0;               w[3].z=0;
  w[4].x=0;             w[4].y=327670L;         w[4].z=0;
  w[5].x=0;             w[5].y=-327670L;        w[5].z=0;
  w[6].x=0;             w[6].y=0;               w[6].z=1000;
  w[7].x=0;             w[7].y=0;               w[7].z=9000;
  w[8].x=0;             w[8].y=9000;            w[8].z=0;
  w[9].x=9000;          w[9].y=0;               w[9].z=0;
  for (f=0; f<ships+1; f++)
  {
    if (o[f].guns>0) free(o[f].g);
    if (o[f].turrets>0) free(o[f].t);
    if (o[f].crashzones>0) free(o[f].c);
    if (o[f].hangerzones>0) free(o[f].h);
    o[f].shape=10;
    o[f].type=-1;
    o[f].frame1=o[f].frame2=o[f].frame3=0;
    o[f].doing=o[f].smoking=o[f].sparking=0;
    o[f].side=1;
    o[f].target=-1;
    o[f].speed=o[f].topspeed=o[f].toprevs=o[f].currentrevs=1;
    o[f].shields=o[f].maxshields=o[f].armour=o[f].maxarmour=10;
    o[f].sparkx=o[f].sparky=o[f].sparkz=0;
    o[f].cx=0;      o[f].cy=0;      o[f].cz=1000;
    o[f].sx=0;      o[f].sy=0;      o[f].sz=0;
    o[f].rx=0;      o[f].ry=0;      o[f].rz=0;
    o[f].rsx=0;     o[f].rsy=0;     o[f].rsz=0;
    o[f].dx[0]=1;   o[f].dy[0]=1;   o[f].dz[0]=100;
    o[f].dx[1]=1;   o[f].dy[1]=100; o[f].dz[1]=1;
    o[f].dx[2]=100; o[f].dy[2]=1;   o[f].dz[2]=1;
    o[f].turrets=o[f].guns=o[f].crashzones=o[f].hangerzones=0;
    o[f].stubborn=0;
    o[f].wingleader=-1; o[f].wingtype=1;
    o[f].wingx=o[f].wingy=o[f].wingz=500;
    o[f].destination=0;
    strcpy (o[f].name,"UNKNOWN");
    o[f].rank=0;
    o[f].mother=-1; o[f].motherhangerzone=0;
    o[f].thingys=0;
    for (g=0; g<20; g++) o[f].thingytype[g]=0;
  }
  for (f=0; f<shapes; f++)
  {
    p[f].shape=33;
    p[f].type=-1;
    p[f].frame1=p[f].frame2=p[f].frame3=0;
    p[f].side=0;
    p[f].target=-1;
    p[f].speed=p[f].topspeed=p[f].toprevs=p[f].currentrevs=1;
    p[f].cx=0;      p[f].cy=0;      p[f].cz=5000;
    p[f].sx=0;      p[f].sy=0;      p[f].sz=0;
    p[f].rx=0;      p[f].ry=0;      p[f].rz=0;
    p[f].rsx=0;     p[f].rsy=0;     p[f].rsz=0;
    p[f].dx[0]=1;   p[f].dy[0]=1;   p[f].dz[0]=100;
    p[f].dx[1]=1;   p[f].dy[1]=100; p[f].dz[1]=1;
    p[f].dx[2]=100; p[f].dy[2]=1;   p[f].dz[2]=1;
  }
  for (f=0; f<numguiobjects; f++)
  {
    gui[f].shape=33;
    gui[f].type=-1;
    gui[f].speed=gui[f].topspeed=gui[f].toprevs=gui[f].currentrevs=1;
    gui[f].cx=0;      gui[f].cy=0;      gui[f].cz=5000;
    gui[f].sx=0;      gui[f].sy=0;      gui[f].sz=0;
    gui[f].rx=0;      gui[f].ry=0;      gui[f].rz=0;
    gui[f].rsx=0;     gui[f].rsy=0;     gui[f].rsz=0;
    gui[f].dx[0]=1;   gui[f].dy[0]=1;   gui[f].dz[0]=100;
    gui[f].dx[1]=1;   gui[f].dy[1]=100; gui[f].dz[1]=1;
    gui[f].dx[2]=100; gui[f].dy[2]=1;   gui[f].dz[2]=1;
  }
  for (f=0; f<ships; f++)
  {
    co[f].time=-1;
    co[f].no=f;
    co[f].shape=10;
    co[f].type=1;
    co[f].side=1;
    co[f].target=-1;
    co[f].cx=0;         co[f].cy=0;       co[f].cz=1000;
    co[f].sx=0;         co[f].sy=0;       co[f].sz=0;
    co[f].dx[0]=1;      co[f].dy[0]=1;    co[f].dz[0]=100;
    co[f].dx[1]=1;      co[f].dy[1]=100;  co[f].dz[1]=1;
    co[f].dx[2]=100;    co[f].dy[2]=1;    co[f].dz[2]=1;
    co[f].rx=0;         co[f].ry=0;       co[f].rz=0;
    co[f].rsx=0;        co[f].rsy=0;      co[f].rsz=0;
    co[f].stubborn=0;
    co[f].wingleader=-1;
    co[f].wingtype=0;
    co[f].wingx=co[f].wingy=co[f].wingz=100;
    co[f].destination=0;
    strcpy (co[f].name,"UNKNOWN");
    co[f].rank=0;
    co[f].mother=-1; co[f].motherhangerzone=0;
    co[f].createtype=0;
  }
  for (f=0; f<ships; f++)
  {
    oe[f].time=-1;
    oe[f].no=-1;
    oe[f].type=-1;
    oe[f].doing=-1;
    oe[f].side=-1;
    oe[f].target=-1;
    oe[f].topspeed=oe[f].toprevs=-1;
    oe[f].shields=oe[f].maxshields=oe[f].armour=oe[f].maxarmour=-1;
    oe[f].stubborn=-1;
    oe[f].wingleader=-1;
    oe[f].wingtype=-1;
    oe[f].wingx=oe[f].wingy=oe[f].wingz=-1;
    oe[f].destination=0;
    oe[f].rank=-1;
  }
  for (f=0; f<shapes; f++)            // Initialise the communications
  {
    ce[f].time=-1;
    ce[f].from=-1;
    ce[f].side=-1;
    strcpy(ce[f].msg,"STATIC");
  }
  for (f=0; f<ships; f++) matter[f]=0;
  for (f=0; f<complines; f++) strcpy(comp[f]," ");
  for (f=0; f<comms; f++)
  {
    c[f].from=-1;
    c[f].type=0;
    c[f].side=-1;
    strcpy(c[f].msg,"STATIC");
    c[f].newcomm=0;
  }
  strcpy(c[0].msg,"MISSION STARTS");
  strcpy(comp[0],"TRANSFERING");
  strcpy(comp[1],"FLIGHT CONTROL.");
  strcpy(comp[2],"FIRING COMBAT");
  strcpy(comp[3],"ENGINES.");
  frame1=frame2=frame3=0;
  missiontime=0;
  currentcomm=0;
  commtimer=0;
  currentprintcomm=0;
  incoming=0;
  complatest=0;
  complatesttimer=0;
  view=0;
  viewx=0; viewy=0; viewz=0;
  viewrx=0; viewry=0; viewrz=0;
  missioncompleted=0;
  startflag=TAKEOFF;
  notcompleted=0;  // mission complete or Not.
  completedcount=0;
  critical=0;
  frame1=frame2=frame3=0;
  targetinfo=10;
  targetinfoupdown=10;
  ccpp=0;

  p[shapes-9].cx=0;
  p[shapes-9].cy=0;
  p[shapes-9].cz=-300;
  light=dddCreateLight(VECTOR_LIGHT,255,1000);
  p[shapes-9].type=1;
  p[shapes-9].object=dddLoad("sun.3dw");
  p[shapes-9].shape=60;
  spinprojectile(shapes-9, 0,0,0, 10,0,0,0); // Stick the sun up in the sky.
  p[shapes-8].cx=0;
  p[shapes-8].cy=0;
  p[shapes-8].cz=0;
  p[shapes-8].type=1;
  p[shapes-8].object=dddLoad("galaxy.3dw");
  p[shapes-8].shape=83;
  spinprojectile(shapes-8, 0,0,0, 5,0,9,0); // Make it a nice milky way
  p[shapes-7].cx=0;
  p[shapes-7].cy=0;
  p[shapes-7].cz=500;
  p[shapes-7].type=1;
  p[shapes-7].object=dddLoad("neb1.3dw");
  p[shapes-7].shape=101;
  spinprojectile(shapes-7, 0,0,0, -15,0,4,0); // Make it a nice SPLUT
  p[shapes-6].cx=0;
  p[shapes-6].cy=0;
  p[shapes-6].cz=500;
  p[shapes-6].type=1;
  p[shapes-6].object=dddLoad("neb2.3dw");
  p[shapes-6].shape=102;
  spinprojectile(shapes-6, 0,0,0, 30,5,0,0); // Make it a nice THINGY
  p[shapes-5].cx=0;
  p[shapes-5].cy=0;
  p[shapes-5].cz=400;
  p[shapes-5].type=1;
  p[shapes-5].object=dddLoad("neb3.3dw");
  p[shapes-5].shape=103;
  spinprojectile(shapes-5, 0,0,0, 20,20,5,0); // Make it a nice THINGY

  pilot.inmisfriendlyhits=0;
  judx=0;
  judy=0;
  ground=OFF;
  missiontime=0;
  view=0;
  terminateflag=0;
  tricia=0;
  for(f=0;f<40;f++)
  {
    triciaplaying[f]=0;
  }
}

void  waypoints(void)
{
  int f;
  for (f=0; f<9; f++)
  {
    rotatesummat(&w[f].x,&w[f].y,&w[f].z,o[0].rsx,o[0].rsy,-o[0].rsz);
    w[f].z-=(o[0].speed*velconst);
  }
}

void  pause(void)
{
  apiniceprint3(21,36,140,89,"P A U S E D");
  apiscreenswap();
  apiniceprint3(21,36,140,89,"P A U S E D");
  apiscreenswap();
  while (key[_P] ) {}
  while (!key[_P] ) {}
  while (key[_P] ) {}
  targetframe=1;
}

void options(void)
{
  char s1[80];
  int flag,oldcontrol,oldsampling;
  float rx,ry,rz;
  VtkObj object,light1,camera;
  FILE *stream;
  int cursor=1,select=0;
  rx=o[0].rsx;
  ry=o[0].rsy;
  rz=o[0].rsz;
  apiclearcliparea();
  apiscreenswap();
  object=dddLoad("jupiter.3dw");
  oldcontrol=control;
  oldsampling=sampling;
  flag=0;
  dddMoveTo(object,0,0,3000);
  dddRotateTo(object,-16000,0,0);
  camera=dddCreateCamera(32000,100,100);
  light1=dddCreateLight(VECTOR_LIGHT,122,0);
  dddRotateTo(light1,6000,2000,0);

//  deinitsound();

  o[0].rsx=0;o[0].rsy=0;o[0].rsz=0;
  flag=0;
  while (flag==0)
  {
    apiclearcliparea();
    apigetmousepos();
    apiclearobjects();
    drawstarfield(o[0].rsx,o[0].rsy,o[0].rsz);

    if (rendermethod==NONE) dddSetRenderMethod(object,RENDERED|ZBUFFERED);
    else if (rendermethod==FLAT) dddSetRenderMethod(object,RENDERED|ZBUFFERED|FLAT_SHADE);
    else if (rendermethod==PHONG) dddSetRenderMethod(object,RENDERED|ZBUFFERED|GOURAUD_SHADE);
    else if (rendermethod==FULL) dddSetRenderMethod(object,RENDERED|ZBUFFERED|GOURAUD_SHADE);
    dddSetShapeFlags(object,1);
    dddInsertObject(object);
    dddInsertObject(light1);
    dddSelectCamera(camera);
    apidrawobjects();
    dddRotateBy(object,0,112,0);

    apicoolprint3(1,10,150,10,"GAME OPTIONS");
    switch(control)
    {
      case 0: sprintf(s1,"KEYBOARD"); break;
      case 1: sprintf(s1,"JOYSTICK"); break;
      case 2: sprintf(s1,"MOUSE"); break;
    }
    apicoolprint3(1,10,90,30,"CONTROL METHOD             :");
    apicoolprint3(1,10,210,30,s1);
    sprintf(s1,"%d PERCENT",(25-(jsens-5))*4 );
    apicoolprint3(1,10,90,40,"JOYSTICK SENSITIVITY       :");
    apicoolprint3(1,10,210,40,s1);
    if(control==1 && oldcontrol!=1) sprintf(s1,"SELECT");
    else sprintf(s1,"NOT NECESSARY");
    apicoolprint3(1,10,90,50,"CALIBRATE JOYSTICK         :");
    apicoolprint3(1,10,210,50,s1);
    sprintf(s1,"%d PERCENT",(25-(msens-5))*4 );
    apicoolprint3(1,10,90,60,"MOUSE SENSITIVITY          :");
    apicoolprint3(1,10,210,60,s1);
    if(fx==ON) sprintf(s1,"ON"); else sprintf(s1,"OFF");
    apicoolprint3(32,10,90,70,"SOUND EFFECTS              :");
    apicoolprint3(32,10,210,70,s1);
    if(music==ON) sprintf(s1,"ON"); else sprintf(s1,"OFF");
    apicoolprint3(32,10,90,80,"MUSICAL SCORE              :");
    apicoolprint3(32,10,210,80,s1);
    switch(sampling)
    {
      case 0: sprintf(s1,"11000 HZ"); break;
      case 1: sprintf(s1,"22000 HZ"); break;
      case 2: sprintf(s1,"8000 HZ"); break;
    }
    apicoolprint3(32,10,90,90,"SAMPLING SPEED             :");
    apicoolprint3(32,10,210,90,s1);
    sprintf(s1,"%d0 PERCENT",11-volume);
    apicoolprint3(1,10,90,100,"VOLUME                     :");
    apicoolprint3(1,10,210,100,s1);

    if(difficulty==0) sprintf(s1,"NORMAL");
    else if(difficulty==1) sprintf(s1,"BETTER WEAPONS");
    else if(difficulty==2) sprintf(s1,"INEPT ENEMIES");
    else sprintf(s1,"CHILDSPLAY");
    apicoolprint3(1,10,90,110,"DIFFICULTY LEVEL           :");
    apicoolprint3(1,10,210,110,s1);
    if(triciacomputer==ON) sprintf(s1,"ON"); else sprintf(s1,"OFF");
    apicoolprint3(1,10,90,120,"COMPUTER VOICE             :");
    apicoolprint3(1,10,210,120,s1);

    if (!key[_C_DOWN] && !key[_C_UP] && !key[_SPACEBAR] &&
        !key[_EQUALS] && !key[_MINUS] && !key[_RETURN]) select=0;
    if (select>0)
    {
      select++; if(select>5000) select=0;
    }
    else
    {
      if(key[_C_DOWN])
      {
        cursor++; if(cursor>10) cursor=1;
      }
      if(key[_C_UP])
      {
        cursor--; if(cursor<1) cursor=10;
      }
      if(key[_SPACEBAR] || key[_EQUALS] || key[_C_RIGHT])
      {
        switch(cursor)
        {
          case 1:
            control++;
            if(control>1) control=0;
          break;
          case 2:
            if (jsens>5) jsens--;
          break;
          case 3: calibrate(); break;
          case 4:
            if (msens>5) msens--;
          break;
          case 5:
//            if(fx==1) fx=0; else fx=1;
          break;
          case 6:
//            if (music==1) music=0; else music=1;
          break;
          case 7:
//            sampling++; if(sampling>2) sampling=0;
          break;
          case 8:
            if (volume>1) volume--;
          break;
          case 9:
            difficulty--;
            if (difficulty<0) difficulty=3;
          break;
          case 10:
            triciacomputer--;
            if (triciacomputer<0) triciacomputer=1;
          break;
        }
      }
      if(key[_RETURN] || key[_MINUS] || key[_C_LEFT])
      {
        switch(cursor)
        {
          case 1:
            control--;
            if(control<0) control=1;
          break;
          case 2:
            if (jsens<30) jsens++;
          break;
          case 3: calibrate(); break;
          case 4:
            if (msens<30) msens++;
          break;
          case 5:
//            if (fx==1) fx=0; else fx=1;
          break;
          case 6:
//            if (music==1) music=0; else music=1;
          break;
          case 7:
//            sampling--; if(sampling<0) sampling=2;
          break;
          case 8:
            if (volume<10) volume++;
          break;
          case 9:
            difficulty++;
            if (difficulty>3) difficulty=0;
          break;
          case 10:
            triciacomputer++;
            if (triciacomputer>1) triciacomputer=0;
          break;
        }
      }
    }
    delay(50);
    apiline(2,70,(22+cursor*10),85,(22+cursor*10));
    apiline(2,81,(18+cursor*10),85,(22+cursor*10));
    apiline(2,81,(26+cursor*10),85,(22+cursor*10));

    apibox(42,13,177,37,187);
    apibox(37,15,178,35,186);

    apicoolprint3(1,10, 20,180,"OK" );

    if ((apimouse_y/5.3>177 && apimouse_y/5.3<188 && apimouse_x/3.3>15 && apimouse_x/3.3<35 && apilbutton==1) || key[_ESC]) flag=1;

    if (apimouse_x>=0 && apimouse_x/3.3<319 && apimouse_y>=0 && apimouse_y/5.3<199)
    {
      apiline(1,1+(apimouse_x/3.3)-1,(apimouse_y/5.3),1+(apimouse_x/3.3)+1,(apimouse_y/5.3));
      apiline(1,1+(apimouse_x/3.3),(apimouse_y/5.3)-1,1+(apimouse_x/3.3),(apimouse_y/5.3)+1);
    }
    apiscreenswap();
  }
  while(key[_ESC]) {}

  o[0].rsx=rx;
  o[0].rsy=ry;
  o[0].rsz=rz;
  stream=fopen("3DOPTION.CFG","w");
  fprintf(stream,"CONTROL: %d\n",control);
  fprintf(stream,"JOYSTICKSENSITIVITY: %d\n",jsens);
  fprintf(stream,"MOUSESENSITIVITY: %d\n",msens);
  fprintf(stream,"SOUNDEFFECTS: %d\n",fx);
  fprintf(stream,"MUSICALSCORE: %d\n",music);
  fprintf(stream,"SAMPLINGSPEED: %d\n",sampling);
  fprintf(stream,"VOLUME: %d\n",volume);
  fprintf(stream,"DIFFICULTY: %d\n",difficulty);
  fprintf(stream,"TRICIA: %d\n",triciacomputer);
  fclose(stream);
//  if(music==1 || fx==1) soundblaster=1;
//  initsound();
}

void  detailsettings(void)
{
  char s1[80];
  int flag;
  int oldmode;
  float rx,ry,rz;
  VtkObj object,camera,light1,light2,planet;
  VtkObj gun1,gun2;
  FILE *stream;
  int cursor=1,select=0,oldattached,f;
  rx=o[0].rsx;
  ry=o[0].rsy;
  rz=o[0].rsz;
  oldmode=videomode;
  apiclearcliparea();
  apiscreenswap();
  object=dddLoad("fite3.3dw");
  planet=dddLoad("neptune.3dw");
  gun1=dddLoad("gun2.3dw");
  gun2=dddLoad("gun2.3dw");
  flag=0;
  dddMoveTo(object,0,0,200);
  dddMoveTo(gun1,40,40,100);
  dddMoveTo(gun2,-40,40,100);
  camera=dddCreateCamera(32000,100,100);
  light1=dddCreateLight(VECTOR_LIGHT,255,0);
  dddRotateTo(light1,16000,0,0);
  light2=dddCreateLight(OMNI_LIGHT,255,0);
  dddMoveTo(light2,0,1000,2000);
  o[0].rsx=0;o[0].rsy=0;o[0].rsz=0;
  flag=0;
  oldattached=attachedobjects;
  while (flag==0)
  {
    apiclearcliparea();
    apigetmousepos();
    apiclearobjects();
    drawstarfield(o[0].rsx,o[0].rsy,o[0].rsz);
    if(planets!=OFF) apiplanet(planet,32,0,0,5000,0,22767,10000);
    apiline(153,0,1,160-(160/(effectsrenderdist/9600)),101-(100/(effectsrenderdist/9600)));
    apiline(153,319,1,160+(160/(effectsrenderdist/9600)),101-(100/(effectsrenderdist/9600)));
    apiline(153,0,198,160-(160/(effectsrenderdist/9600)),99+(100/(effectsrenderdist/9600)));
    apiline(153,319,198,160+(160/(effectsrenderdist/9600)),99+(100/(effectsrenderdist/9600)));
    apirect(153,160-(160/(effectsrenderdist/9600)),101-(100/(effectsrenderdist/9600))
               ,160+(160/(effectsrenderdist/9600)),99+(100/(effectsrenderdist/9600)));
    apiline(157,0,0,160-(160/(renderdist/9600)),100-(100/(renderdist/9600)));
    apiline(157,319,0,160+(160/(renderdist/9600)),100-(100/(renderdist/9600)));
    apiline(157,0,199,160-(160/(renderdist/9600)),100+(100/(renderdist/9600)));
    apiline(157,319,199,160+(160/(renderdist/9600)),100+(100/(renderdist/9600)));
    apirect(157,160-(160/(renderdist/9600)),100-(100/(renderdist/9600))
               ,160+(160/(renderdist/9600)),100+(100/(renderdist/9600)));
    if (rendermethod==FULL) dddSetShapeFlags(object,1); else dddSetShapeFlags(object,0);
    if (rendermethod==NONE) dddSetRenderMethod(object,RENDERED|ZBUFFERED);
    else if (rendermethod==FLAT) dddSetRenderMethod(object,RENDERED|ZBUFFERED|FLAT_SHADE);
    else if (rendermethod==PHONG) dddSetRenderMethod(object,RENDERED|ZBUFFERED|GOURAUD_SHADE);
    else if (rendermethod==FULL) dddSetRenderMethod(object,RENDERED|ZBUFFERED|GOURAUD_SHADE);
    dddInsertObject(object);
    if (cockpitrendermethod==NONE) { dddSetRenderMethod(gun1,RENDERED|ZBUFFERED);dddSetRenderMethod(gun2,RENDERED|ZBUFFERED);}
    else if (cockpitrendermethod==FLAT) { dddSetRenderMethod(gun1,RENDERED|ZBUFFERED|FLAT_SHADE);dddSetRenderMethod(gun2,RENDERED|ZBUFFERED|FLAT_SHADE);}
    else if (cockpitrendermethod==PHONG) { dddSetRenderMethod(gun1,RENDERED|ZBUFFERED|GOURAUD_SHADE);dddSetRenderMethod(gun2,RENDERED|ZBUFFERED|GOURAUD_SHADE);}
    else if (cockpitrendermethod==FULL) { dddSetRenderMethod(gun1,RENDERED|ZBUFFERED|GOURAUD_SHADE);dddSetRenderMethod(gun2,RENDERED|ZBUFFERED|GOURAUD_SHADE);}
    dddInsertObject(gun1);
    dddInsertObject(gun2);

    dddInsertObject(light1);
    if(lightsourcing==ON) dddInsertObject(light2);
    dddSelectCamera(camera);
    apidrawobjects();
    dddRotateBy(object,256,512,0);

    apicoolprint3(1,10,120,10,"SCREEN DETAIL SETTINGS");
    switch(videomode)
    {
      case 0: sprintf(s1,"VGA 320x200"); break;
      case 1: sprintf(s1,"VGA 320x400"); break;
      case 2: sprintf(s1,"SVGA 640x480"); break;
    }
    apicoolprint3(1,10,50,30,"RESOLUTION        :");
    apicoolprint3(1,10,130,30,s1);
    switch(rendermethod)
    {
      case NONE: sprintf(s1,"NONE"); break;
      case FLAT: sprintf(s1,"LIGHT SOURCED, FLAT"); break;
      case PHONG: sprintf(s1,"LIGHT SOURCED, GOURAD, PHONG"); break;
      case FULL: sprintf(s1,"LIGHT SOURCED, GOURAD, PHONG, TEXTURE"); break;
    }
    apicoolprint3(1,10,50,37,"MAIN RENDERING    :");
    apicoolprint3(1,10,130,37,s1);
    switch(smalldetails)
    {
      case NONE: sprintf(s1,"NOT DRAWN"); break;
      case FLAT: sprintf(s1,"LIGHT SOURCED, FLAT"); break;
      case PHONG: sprintf(s1,"LIGHT SOURCED, GOURAD, PHONG"); break;
      case FULL: sprintf(s1,"LIGHT SOURCED, GOURAD, PHONG, TEXTURE"); break;
      case BASIC: sprintf(s1,"NONE"); break;
    }
    apicoolprint3(1,10,50,44,"DETAILS RENDERING :");
    apicoolprint3(1,10,130,44,s1);
    switch(cockpitrendermethod)
    {
      case NONE: sprintf(s1,"NONE"); break;
      case FLAT: sprintf(s1,"LIGHT SOURCED, FLAT"); break;
      case PHONG: sprintf(s1,"LIGHT SOURCED, GOURAD, PHONG"); break;
      case FULL: sprintf(s1,"LIGHT SOURCED, GOURAD, PHONG, TEXTURE"); break;
    }
    apicoolprint3(1,10,50,51,"COCKPIT RENDERING :");
    apicoolprint3(1,10,130,51,s1);
    gcvt( renderdist/1000 ,8,s1); strcat(s1," KM");
    apicoolprint3(1,10,50,58,"RENDER DISTANCE   :");
    apicoolprint3(1,10,130,58,s1);
    gcvt( effectsrenderdist/1000 ,8,s1); strcat(s1," KM");
    apicoolprint3(1,10,50,65,"EFFECTS DISTANCE  :");
    apicoolprint3(1,10,130,65,s1);
    if(lightsourcing==ON) sprintf(s1,"ON"); else sprintf(s1,"OFF");
    apicoolprint3(1,10,50,72,"MULTIPLE SOURCING :");
    apicoolprint3(1,10,130,72,s1);
    if(flames==ON) sprintf(s1,"ON"); else sprintf(s1,"OFF");
    apicoolprint3(1,10,50,79,"PYROTECHNICS      :");
    apicoolprint3(1,10,130,79,s1);
    if(sparks==ON) sprintf(s1,"ON"); else sprintf(s1,"OFF");
    apicoolprint3(1,10,50,86,"EXPLOSION FX      :");
    apicoolprint3(1,10,130,86,s1);
    sprintf(s1,"%d",complexity);
    apicoolprint3(1,10,50,93,"FX COMPLEXITY     :");
    apicoolprint3(1,10,130,93,s1);
    sprintf(s1,"%d",starfield*2);
    apicoolprint3(1,10,50,100,"STARS             :");
    apicoolprint3(1,10,130,100,s1);
    if(planets==0) sprintf(s1,"OFF");
    else if(planets==1) sprintf(s1,"SIMPLE");
    else if(planets==2) sprintf(s1,"TEXTURED");
    apicoolprint3(1,10,50,107,"PLANETS           :");
    apicoolprint3(1,10,130,107,s1);
    if(longlaser==ON) sprintf(s1,"ON"); else sprintf(s1,"OFF");
    apicoolprint3(1,10,50,114,"LONG PLASMA BEAMS :");
    apicoolprint3(1,10,130,114,s1);
    if(debrisremoval==ON) sprintf(s1,"ON"); else sprintf(s1,"OFF");
    apicoolprint3(1,10,50,121,"DEBRIS REMOVAL    :");
    apicoolprint3(1,10,130,121,s1);
    sprintf(s1,"%d",debris);
    apicoolprint3(1,10,50,128,"DEBRIS FIELD SIZE :");
    apicoolprint3(1,10,130,128,s1);
    if(drawcockpit==ON) sprintf(s1,"ON"); else sprintf(s1,"OFF");
    apicoolprint3(1,10,50,135,"DRAW COCKPIT :");
    apicoolprint3(1,10,130,135,s1);
    if(attachedobjects==ON) sprintf(s1,"ON"); else sprintf(s1,"OFF");
    apicoolprint3(1,10,50,141,"ATTACHED OBJECTS :");
    apicoolprint3(1,10,130,141,s1);
    if (!key[_C_DOWN] && !key[_C_UP] && !key[_SPACEBAR] &&
        !key[_EQUALS] && !key[_MINUS] && !key[_RETURN]) select=0;
    if (select>0)
    {
      select++; if(select>5000) select=0;
    }
    else
    {
      if(key[_C_DOWN])
      {
        cursor++; if(cursor>17) cursor=1;
      }
      if(key[_C_UP])
      {
        cursor--; if(cursor<1) cursor=17;
      }
      if(key[_SPACEBAR] || key[_EQUALS] || key[_C_RIGHT])
      {
        switch(cursor)
        {
          case 1:
            videomode++;
            if(videomode>1) videomode=0;
            apisetvideo();
          break;
          case 2:
            rendermethod++;
            if(rendermethod>FULL) rendermethod=NONE;
          break;
          case 3:
            smalldetails++;
            if(smalldetails>BASIC) smalldetails=NONE;
          break;
          case 4:
            cockpitrendermethod++;
            if(cockpitrendermethod>FULL) cockpitrendermethod=NONE;
          break;
          case 5:
            if (renderdist<32000) renderdist+=1000;
          break;
          case 6:
            if (effectsrenderdist<32000) effectsrenderdist+=1000;
          break;
          case 7:
            if(lightsourcing==ON) lightsourcing=OFF; else lightsourcing=ON;
          break;
          case 8:
            if(flames==ON) flames=OFF; else flames=ON;
          break;
          case 9:
            if(sparks==ON) sparks=OFF; else sparks=ON;
          break;
          case 10:                                           
            if (complexity<15) complexity++;
          break;
          case 11:
            if (starfield<2000) starfield+=10;
          break;
          case 12:
            planets++; if(planets>2) planets=0;
          break;
          case 13:
            if(longlaser==ON) longlaser=OFF; else longlaser=ON;
          break;
          case 14:
            if(debrisremoval==ON) debrisremoval=OFF; else debrisremoval=ON;
          break;
          case 15:
            if (debris<100) debris+=10;
          break;
          case 16:
            if(drawcockpit==ON) drawcockpit=OFF; else drawcockpit=ON;
          break;
          case 17:
            if(attachedobjects==ON) attachedobjects=OFF; else attachedobjects=ON;
          break;
        }
      }
      if(key[_RETURN] || key[_MINUS] || key[_C_LEFT])
      {
        switch(cursor)
        {
          case 1:
            videomode--;
            if(videomode<0) videomode=1;
            apisetvideo();
          break;
          case 2:
            rendermethod--;
            if(rendermethod<NONE) rendermethod=FULL;
          break;
          case 3:
            smalldetails--;
            if(smalldetails<NONE) smalldetails=BASIC;
          break;
          case 4:
            cockpitrendermethod--;
            if(cockpitrendermethod<NONE) cockpitrendermethod=FULL;
          break;
          case 5:
            if (renderdist>4000) renderdist-=1000;
          break;
          case 6:
            if (effectsrenderdist>4000) effectsrenderdist-=1000;
          break;
          case 7:
            if(lightsourcing==ON) lightsourcing=OFF; else lightsourcing=ON;
          break;
          case 8:
            if(flames==ON) flames=OFF; else flames=ON;
          break;
          case 9:
            if(sparks==ON) sparks=OFF; else sparks=ON;
          break;
          case 10:
            if (complexity>1) complexity--;
          break;
          case 11:
            if (starfield>10) starfield-=10;
          break;
          case 12:
            planets--; if(planets<0) planets=2;
          break;
          case 13:
            if(longlaser==ON) longlaser=OFF; else longlaser=ON;
          break;
          case 14:
            if(debrisremoval==ON) debrisremoval=OFF; else debrisremoval=ON;
          break;
          case 15:
            if (debris>0) debris-=10;
          break;
          case 16:
            if(drawcockpit==ON) drawcockpit=OFF; else drawcockpit=ON;
          break;
          case 17:
            if(attachedobjects==ON) attachedobjects=OFF; else attachedobjects=ON;
          break;
        }
      }
    }
    delay(50);
    apiline(2,30,(25+cursor*7),45,(25+cursor*7));
    apiline(2,41,(21+cursor*7),45,(25+cursor*7));
    apiline(2,41,(29+cursor*7),45,(25+cursor*7));

    apibox(42,13,177,37,187);
    apibox(37,15,178,35,186);

    apicoolprint3(1,10, 20,180,"OK" );

    if ((apimouse_y/5.3>177 && apimouse_y/5.3<188 && apimouse_x/3.3>15 && apimouse_x/3.3<35 && apilbutton==1) || key[_ESC]) flag=1;

    if (apimouse_x>=0 && apimouse_x/3.3<319 && apimouse_y>=0 && apimouse_y/5.3<199)
    {
      apiline(1,1+(apimouse_x/3.3)-1,(apimouse_y/5.3),1+(apimouse_x/3.3)+1,(apimouse_y/5.3));
      apiline(1,1+(apimouse_x/3.3),(apimouse_y/5.3)-1,1+(apimouse_x/3.3),(apimouse_y/5.3)+1);
    }
    apiscreenswap();
  }
  while(key[_ESC]) {}
  o[0].rsx=rx;
  o[0].rsy=ry;
  o[0].rsz=rz;
  if(oldattached!=attachedobjects)
  {
    for(f=0;f<ships;f++)
    {
      if(attachedobjects==ON)
      {
        attach(f);
      }
      if(attachedobjects==OFF)
      {
        detach(f);
      }
    }
  }
  sortgroundout();
  stream=fopen("3DDETAIL.CFG","w");
  fprintf(stream,"VIDEOMODE: %d\n",videomode);
  fprintf(stream,"RENDERMETHOD: %d\n",rendermethod);
  fprintf(stream,"COCKPITRENDERMETHOD: %d\n",cockpitrendermethod);
  fprintf(stream,"EFFECTSRENDERMETHOD: %d\n",smalldetails);
  fprintf(stream,"RENDERDISTANCE: %f\n",renderdist);
  fprintf(stream,"EFFECTSRENDERDISTANCE: %f\n",effectsrenderdist);
  fprintf(stream,"LIGHTSOURCING: %d\n",lightsourcing);
  fprintf(stream,"PYROTECHNICS: %d\n",flames);
  fprintf(stream,"EXPLOSIONEFFECTS: %d\n",sparks);
  fprintf(stream,"EFFECTSCOMPLEXITY: %d\n",complexity);
  fprintf(stream,"STARFIELDSIZE: %d\n",starfield);
  fprintf(stream,"PLANETS: %d\n",planets);
  fprintf(stream,"LONGPLASMABEAMS: %d\n",longlaser);
  fprintf(stream,"DEBRISREVOBAL: %d\n",debrisremoval);
  fprintf(stream,"DEBRISFIELD: %d\n",debris);
  fprintf(stream,"DRAWCOCKPIT: %d\n",drawcockpit);
  fprintf(stream,"ATTACHEDOBJECTS: %d\n",attachedobjects);
  fclose(stream);
}

void  calibrate(void)
{
  FILE *stream;
  int maxx,maxy,minx,miny,cenx,ceny;
  int dx1,dx2;

  apibox(141, 49,94,271, 107 );
  apibox(207, 50,95,270, 106 );
  apicoolprint3(1,10,90,99,"MOVE STICK TO TOP LEFT AND PRESS RETURN");
  apiscreenswap();
  while (!key[_RETURN])
  {
    apireadjoystick();
  }
  while (key[_RETURN])  {}
  minx=apijoystick_x_position;
  miny=apijoystick_y_position;
  apijoystick_right_button=255;
  //delay(100);
  apiscreenswap();
  apibox(141, 49,94,271, 107 );
  apibox(207, 50,95,270, 106 );
  apicoolprint3(1,10,80,99,"MOVE STICK TO BOTTOM RIGHT AND PRESS RETURN");
  apiscreenswap();
  while (!key[_RETURN])
  {
    apireadjoystick();
  }
  while (key[_RETURN])  {}
  maxx=apijoystick_x_position;
  maxy=apijoystick_y_position;
  apijoystick_right_button=255;
  //delay(100);
  apiscreenswap();
  apibox(141, 49,94,271, 107 );
  apibox(207, 50,95,270, 106 );
  apicoolprint3(1,10,90,99,"MOVE STICK TO THE CENTER AND PRESS RETURN");
  apiscreenswap();
  while (!key[_RETURN])
  {
    apireadjoystick();
  }
  while (key[_RETURN])  {}
  apijoystick_right_button=255;
  cenx=apijoystick_x_position;
  ceny=apijoystick_y_position;
  dx1 = cenx - minx;
  dx2 = maxx - cenx;
  if (dx1>dx2) jmaxx=dx2;
  else jmaxx=dx1;
  dx1 = ceny - miny;
  dx2 = maxy - ceny;
  if (dx1>dx2) jmaxy=dx2;
  else jmaxy=dx1;
  jcenterx=cenx;
  jcentery=ceny;
  stream = fopen("3DSTICK.CFG","w");
  fprintf(stream,"%d\n",jcenterx);
  fprintf(stream,"%d\n",jcentery);
  fprintf(stream,"%d\n",jmaxx);
  fprintf(stream,"%d\n",jmaxy);
  fclose (stream);
  apiscreenswap();

  targetframe=1;
}

void  playsoundeffect(int f, float dist)
{
  if(dist>0) dist+=1500;
  if(soundblaster==1 && fx==1 && sound1[f]!=NULL && playing[f]==0 && dist<6000 )
  {
    id1 = PlaySound(sound1[f],length1[f],v_fancy);
    if(sampling==1) AlterSoundEffect(id1,v_setrate,120); // This bit is done if sample speed = 22000
    if(sampling==2) AlterSoundEffect(id1,v_setrate,180); // This bit is done if sample speed = 8000
    if (dist<1500) AlterSoundEffect(id1 ,v_setvolume,(15-(dist/150))/(volume)  );
    else AlterSoundEffect(id1 ,v_setvolume,(8-(dist/750))/(volume)  );
    playing[f]=1;
  }
}

void  playtricia(int f)
{
  if(soundblaster==1 && fx==1 && triciasound1[f]!=NULL && tricia==0 && triciacomputer==1 && triciaplaying[f]==0 && norand==0 && o[0].doing!=DIEING)
  {
    id1 = PlaySound(triciasound1[f],tricialength1[f],v_fancy);
    if(sampling==1) AlterSoundEffect(id1,v_setrate,120);
    if(sampling==2) AlterSoundEffect(id1,v_setrate,180);
    tricia=1;
    triciaplaying[f]=1;
  }
}

int newpilot(void)
{
  VtkObj object,light1,camera;
  char str[80];
  int doing,oldkey,f;
  object=dddLoad("moon.3dw");
  dddSetRenderMethod(object,RENDERED|ZBUFFERED|GOURAUD_SHADE);
  dddSetShapeFlags(object,1);
  dddMoveTo(object,0,0,1500);
  camera=dddCreateCamera(32000,100,100);
  light1=dddCreateLight(VECTOR_LIGHT,122,0);
  dddRotateTo(light1,6000,2000,0);
  pilot.campaign=0;
  pilot.side=0;
  pilot.mission=0;
  pilot.missions=0;
  pilot.kills=0;
  pilot.rank=0;
  strcpy(pilot.sirname,"");
  strcpy(pilot.firstname,"");
  pilot.deaths=0;
  pilot.restarts=0;
  pilot.score=0;
  pilot.campaignstatus=0;
  pilot.friendlyhits=pilot.enemyhits=pilot.inmisfriendlyhits=pilot.spare5=pilot.spare6=0;

  sprintf(str,"");
  doing=0;
  oldkey=0;
  while (!(key[_RETURN] && doing==2))
  {
    apisetviewangles(0,0,0);
    apisetviewpos(0,0,0);
    apiclearcliparea();
    apiclearobjects();
    apigetmousepos();
    drawstarfield(0,0.1,0);
    dddInsertObject(object);
    dddInsertObject(light1);
    dddSelectCamera(camera);
    apidrawobjects();
    dddRotateBy(object,100,-112,150);
    apiniceprint3(1,130,95,30,"C  R  E  A  T  E    P  I  L  O  T");
    apiniceprint3(21,36,85,80,"ENTER FIRST NAME :");
    apiniceprint3(21,36,160,80,pilot.firstname);
    if (doing==0)
    {
      sprintf(pilot.firstname,"%s",str);
    }
    if (doing==1)
    {
      sprintf(pilot.sirname,"%s",str);
      apiniceprint3(21,36,85,100,"ENTER LAST NAME  :");
      apiniceprint3(21,36,160,100,pilot.sirname);
    }
    if (key[_RETURN])
    {
      doing++;
      sprintf(str,"");
      if(doing==1) while(key[_RETURN]) {}
    }
    if(key[_ESC]) return(1);
    if (key[_A]){if (oldkey==0) strcat (str ,"A" ); oldkey=1;}
    else if (key[_B])   {      if (oldkey==0) strcat (str ,"B" );oldkey=1;    }
    else if (key[_C])    {      if (oldkey==0) strcat (str ,"C" );oldkey=1;    }
    else if (key[_D])    {      if (oldkey==0) strcat (str ,"D" );oldkey=1;    }
    else if (key[_E])    {      if (oldkey==0) strcat (str ,"E" );oldkey=1;    }
    else if (key[_F])    {      if (oldkey==0) strcat (str ,"F" );oldkey=1;    }
    else if (key[_G])    {      if (oldkey==0) strcat (str ,"G" );oldkey=1;    }
    else if (key[_H])    {      if (oldkey==0) strcat (str ,"H" );oldkey=1;    }
    else if (key[_I])    {      if (oldkey==0) strcat (str ,"I" );oldkey=1;    }
    else if (key[_J])    {      if (oldkey==0) strcat (str ,"J" );oldkey=1;    }
    else if (key[_K])    {      if (oldkey==0) strcat (str ,"K" );oldkey=1;    }
    else if (key[_L])    {      if (oldkey==0) strcat (str ,"L" );oldkey=1;    }
    else if (key[_M])    {      if (oldkey==0) strcat (str ,"M" );oldkey=1;    }
    else if (key[_N])    {      if (oldkey==0) strcat (str ,"N" );oldkey=1;    }
    else if (key[_O])    {      if (oldkey==0) strcat (str ,"O" );oldkey=1;    }
    else if (key[_P])    {      if (oldkey==0) strcat (str ,"P" );oldkey=1;    }
    else if (key[_Q])    {      if (oldkey==0) strcat (str ,"Q" );oldkey=1;    }
    else if (key[_R])    {      if (oldkey==0) strcat (str ,"R" );oldkey=1;    }
    else if (key[_S])    {      if (oldkey==0) strcat (str ,"S" );oldkey=1;    }
    else if (key[_T])    {      if (oldkey==0) strcat (str ,"T" );oldkey=1;    }
    else if (key[_U])    {      if (oldkey==0) strcat (str ,"U" );oldkey=1;    }
    else if (key[_V])    {      if (oldkey==0) strcat (str ,"V" );oldkey=1;    }
    else if (key[_W])    {      if (oldkey==0) strcat (str ,"W" );oldkey=1;    }
    else if (key[_X])    {      if (oldkey==0) strcat (str ,"X" );oldkey=1;    }
    else if (key[_Y])    {      if (oldkey==0) strcat (str ,"Y" );oldkey=1;    }
    else if (key[_Z])    {      if (oldkey==0) strcat (str ,"Z" );oldkey=1;    }
    else if (key[_1])    {      if (oldkey==0) strcat (str ,"1" );oldkey=1;    }
    else if (key[_2])    {      if (oldkey==0) strcat (str ,"2" );oldkey=1;    }
    else if (key[_3])    {      if (oldkey==0) strcat (str ,"3" );oldkey=1;    }
    else if (key[_4])    {      if (oldkey==0) strcat (str ,"4" );oldkey=1;    }
    else if (key[_5])    {      if (oldkey==0) strcat (str ,"5" );oldkey=1;    }
    else if (key[_6])    {      if (oldkey==0) strcat (str ,"6" );oldkey=1;    }
    else if (key[_7])    {      if (oldkey==0) strcat (str ,"7" );oldkey=1;    }
    else if (key[_8])    {      if (oldkey==0) strcat (str ,"8" );oldkey=1;    }
    else if (key[_9])    {      if (oldkey==0) strcat (str ,"9" );oldkey=1;    }
    else if (key[_0])    {      if (oldkey==0) strcat (str ,"0" );oldkey=1;    }
    else if (key[_BACKSPACE])    {      if (oldkey==0)      {        f=strlen(str)-1;        str[f]='\0';        oldkey=1;     }    }
    else oldkey=0;
    if (oldkey>0)
    {
      oldkey++;
      if (oldkey>10) oldkey=0;
    }
    apiniceprint3(21,36, 290 , 194 ,  "RETURN"  );
//    this_time = apireadtimer();
//    old_time=this_time-first_time;
//    while (this_time-first_time < maxspeed) this_time = apireadtimer();
    apiscreenswap();
    delay(10);
  }
  for(f=0;f<49;f++) dpt[f]=1;
  if(key[_RETURN]) while(key[_RETURN]) {}
  if(key[_ESC]) while(key[_ESC]) {}
  return(0);
}

void prepareyourguns(void)
{
  int f;
  if(o[0].type>-1)
  {
    for (f=0; f<o[0].guns; f++)
    {
      switch(o[0].g[f].type)
      {
        case LASER:
          lgun[f]=dddLoad("gun2.3dw");
          rgun[f]=dddLoad("gun2.3dw");
        break;
        case ION:
          lgun[f]=dddLoad("gun3.3dw");
          rgun[f]=dddLoad("gun3.3dw");
        break;
        case TURBOLASER:
          lgun[f]=dddLoad("gun2.3dw");
          rgun[f]=dddLoad("gun2.3dw");
        break;
        case CHAINGUN:
          lgun[f]=dddLoad("gun4.3dw");
          rgun[f]=dddLoad("gun4.3dw");
        break;
      }
    }
    //Prepare cockpit shapes
    cock=dddLoad("cock.3dw");
    targetbox=dddLoad("target.3dw");
  }
}

void palette_set(int percent)
{
  int i;
  FILE *temp;

  temp=fopen("PALETTE","w");
  fprintf(temp,"%d\n",percent);
  for(i=0;i<256;i++)
  {
    fprintf(temp,"%ld,%ld,%ld  ",MyPal->Color[i].r,MyPal->Color[i].g,MyPal->Color[i].b);
    fprintf(temp,"%ld,%ld,%ld  ",FullPal->Color[i].r,FullPal->Color[i].g,FullPal->Color[i].b);
    MyPal->Color[i].r=FullPal->Color[i].r*percent/100;
    MyPal->Color[i].g=FullPal->Color[i].g*percent/100;
    MyPal->Color[i].b=FullPal->Color[i].b*percent/100;

    fprintf(temp,"%ld,%ld,%ld\n",MyPal->Color[i].r,MyPal->Color[i].g,MyPal->Color[i].b);
  }
  dddSetPalette(MyPal);
  fclose(temp);
}

void initsound(void)
{
//  char s1[80];
  if(thereisnosound==1)
  {
    soundblaster=0;
    music=0;
    fx=0;
    return;
  }
  if(music==1 || fx==1)
  {
    if(!SBSetUp()) { soundblaster=0; music=0; fx=0; return; }
//    if(sampling==0) SetSampleRate(11000);
    if(sampling==1) SetSampleRate(22000);
    else if(sampling==2) SetSampleRate(8000);
    GoVarmint();
  }
}

void deinitsound(void)
{
  if(thereisnosound==1) return;
  if(soundblaster==1 || music==1 || fx==1)
  {
    DropDeadVarmint();
    SBCleanUp();
  }
}

void savepilot(void)
{
  FILE *stream;
  char s1[80];
  int f;
  f=0;
  if (strlen(pilot.sirname)>7) for (f=0; f<8; f++)
  {
    s1[f]=pilot.sirname[f];
  }
  else for (f=0; f<strlen(pilot.sirname)+1; f++)
  {
    s1[f]=pilot.sirname[f];
  }
  strcat(s1,".PLT");
  stream=fopen(s1,"w");
  fprintf(stream,"%d\n",pilot.campaign);
  fprintf(stream,"%d\n",pilot.side);
  fprintf(stream,"%d\n",pilot.mission);
  fprintf(stream,"%d\n",pilot.missions);
  fprintf(stream,"%d\n",pilot.kills);
  fprintf(stream,"%d\n",pilot.rank);
  fprintf(stream,"%s\n",pilot.sirname);
  fprintf(stream,"%s\n",pilot.firstname);
  fprintf(stream,"%d\n",pilot.deaths);
  fprintf(stream,"%d\n",pilot.restarts);
  fprintf(stream,"%d\n",pilot.score);
  fprintf(stream,"%d\n",pilot.campaignstatus);
  fprintf(stream,"%d\n",pilot.friendlyhits);
  fprintf(stream,"%d\n",pilot.enemyhits);
  for(f=0; f<49; f++) fprintf(stream,"%d\n",dpt[f]);
  fclose(stream);
}