/*

	Modulo principale di noctis.
	Funzioni di supervisione per il modulo di base.

*/

#include "defs.h"
#include "noctis-d.h"
#include "noctis-0.h"
#include "noctis-2.h"
#include <stdio.h>
#include <dir.h>
#include <conio.h>
//#include "mem.h"
#ifdef WINDOWS
#include "randalg.h"
#include "win.h"
#include "noctis-ng.h"
#endif

Uchar restart=0;
Word opencapdelta = 0;
Word holdtomiddle = 0;
double localTargetMinDist = 0;
double localTargetMaxDist = 0;
double localTargetTick = 0.0;
								
const double deg = M_PI / 180;

extern char helpison = 0;
extern int helppage = 0;
extern char showplanet;
extern char showplanetmode;
extern int showplanetadd;
extern char nightisoff;
//extern char *filetouse; //ACKBUGS
extern char portablegoesbgr;
extern char exitflag;
extern char entryflag;
extern void planetary_main ();
extern float tiredness;
extern char blinkhudlights;
extern char blinkhudlights_stay;
char newmessage;
/*char mooses;
int moosepage;*/
int helpmessageID;


// ############## -- STARDRIFTER FLARE EFFECTS -- #################
#define OMEGAORBON //commenting this out turns off the Omega Drive's Orb visualisation effect.
//#define SPARKSON // commenting this out turns off the 'spark' effects.
#define INTERNALLIGHT //commenting this out removes the internal light.

//#--INTERNAL LIGHT settings--#
#define intlightnewposition //this puts the internal light at the new 'NICE' position (center of Stardrifter). -- Commenting it might have strange effects
//BUGS with commenting (OLD position): Morphing cupola parts when landing on a planet are weird.

//#--OMEGA ORB settings--#
#define omegaorbtype 2
  //Omega Orb types:
  // 1 - Blinking, old stype (on fuel low). Erratic and 'strange'.
  // 2 - Blinking, new style (on fuel low). Nice.

//#--SPARK settings--#
#define numspark 255 //defines the maximum ammount of sparks (not the Omega Drive's Orb flares) available.
#define sparkeffect 1
  //Spark effects:
  // 1 - Corner (dark one, opposite of Main Screen and GOES screens) 'waterfall'. - sparkphys 1
  // 2 - Tiny mid-ship fountain.                                                  - sparkphys 1
 #if sparkeffect == 1
   #define sparkphys 1
 #endif
 #if sparkeffect == 2
   #define sparkphys 2
 #endif
  //Spark physics
  //1 - General standard physics.
  //2 - Kill sparks when they touch walls.
 #if sparkphys == 1
   #define SPARKBOUNCEFLOOR float(8 - random(4))/10
   #define SPARKBOUNCEWALL 0.8
 #endif
 #if sparkphys == 2
   #define SPARKBOUNCEFLOOR 0.1
   #define SPARKBOUNCEWALL 0.1
   #define SPARKKILL
 #endif

#ifdef SPARKSON
int sparkinit = 1;
float sparkx[numspark];
float sparkz[numspark];
float sparky[numspark];
float spark_sx[numspark];
float spark_sz[numspark];
float spark_sy[numspark];
float sparklife[numspark];
float sparkdensity[numspark];
#endif //SPARKSON
#ifdef OMEGAORBON
float orbsize;
int temptimer;
int tempflarecharge;
int tempflaredensity = 1;
int tempflaredensityt = 1;
#endif //OMEGAORBON
// ####### -- END OF STARDRIFTER FLARE EFFECTS -- ######

double cur_eclipse = 0;
/* Roba importata da noctis-0.cpp per alleggerirlo */

char   nsnp 		= 1; // Nearstar-Not-Prepared
char   manual_target	= 0;
char   mt_string_char	= 0;
char   mt_coord		= 0;
char   manual_x_string [15];
char   manual_y_string [15];
char   manual_z_string [15];

/* Carica i parametri di viaggio per il pilota automatico. */

void fix_remote_target ()
{
	double dxx, dyy, dzz;

	status ("TGT FIXED", 105);
	dxx = dzat_x - ap_target_x;
	dyy = dzat_y - ap_target_y;
	dzz = dzat_z - ap_target_z;
	ap_target_initial_d = SQRT (dxx*dxx + dyy*dyy + dzz*dzz);
	requested_vimana_coefficient = 1000 * ap_target_initial_d;
	current_vimana_coefficient = 1000 * ap_target_initial_d;
	vimana_reaction_time = 0.01;
	ap_reached = 0;
	dxx = SQRT (ap_target_x * ap_target_x + ap_target_z * ap_target_z);
	dxx += fabs(ap_target_y * 30);
	if (dxx > 2E9) {
		status ("OUTOFRANGE", 105);
		ap_targetted = 0;
	}
	else
		ap_targetted = 1;
}

void fix_local_target ()
{
	double dxx, dyy, dzz;

	status ("TGT FIXED", 105);
	planet_xyz (ip_targetted);
	dxx = dzat_x - plx;
	dyy = dzat_y - ply;
	dzz = dzat_z - plz;
	ip_target_initial_d = SQRT (dxx*dxx + dyy*dyy + dzz*dzz);
	requested_approach_coefficient = 1000 * ip_target_initial_d;
	current_approach_coefficient = 1000 * ip_target_initial_d;
	reaction_time = 0.01;
	localTargetMinDist = 0;
	localTargetMaxDist = 0;
	localTargetTick = 0.0;
}

/* Lampada alogena (ovvero il laser a diffusione interno alle zattere). */

void alogena ()
{
	float x[3], y[3], z[3];
	float lon, dlon, dlon_2;
	Word pcol;

	dlon = M_PI / 5;

	if (fabs(cam_z)>1500) dlon *= fabs(cam_z) / 1500;

	dlon_2 = dlon / 2;

	pcol = 72 + ilightv;
	if (pcol > 100) pcol = 100;

	x[2] = -10; y[2] = 10; z[2] = -10;
	for (lon = 0; lon < 2*M_PI - dlon_2;) {
		x[0] = 15*sin(lon); y[0] = 15*cos(lon); z[0] = (y[0]-x[0])/2;
		lon += dlon; x[1] = 15*sin(lon); y[1] = 15*cos(lon); z[1] = (y[1]-x[1])/2;
		poly3d (x, y, z, 3, pcol);
		pcol += 2;
	}

        if (ilightv==1 && !elight) {
	/*	//Lens flares, from left to right (GOES SCREEN INPUT, GOES SCREEN OUTPUT, LANDING SCREEN)
		lens_flares_for (cam_x, cam_y, cam_z, 3540, -285, 1540, -5000, 2, 1, 0, 0, 0);
		lens_flares_for (cam_x, cam_y, cam_z, 3540, -810, 1540, -5000, 2, 1, 0, 0, 0);
		lens_flares_for (cam_x, cam_y, cam_z, 3540, -285, 790, -5000, 2, 1, 0, 0, 0);
		lens_flares_for (cam_x, cam_y, cam_z, 3540, -810, 790, -5000, 2, 1, 0, 0, 0);

		lens_flares_for (cam_x, cam_y, cam_z, 3540, -285, 735, -5000, 2, 1, 0, 0, 0);
		lens_flares_for (cam_x, cam_y, cam_z, 3540, -810, 735, -5000, 2, 1, 0, 0, 0);
		lens_flares_for (cam_x, cam_y, cam_z, 3540, -285, -20, -5000, 2, 1, 0, 0, 0);
		lens_flares_for (cam_x, cam_y, cam_z, 3540, -810, -20, -5000, 2, 1, 0, 0, 0);

		lens_flares_for (cam_x, cam_y, cam_z, 3540, -285, -80, -5000, 2, 1, 0, 0, 0);
		lens_flares_for (cam_x, cam_y, cam_z, 3540, -810, -80, -5000, 2, 1, 0, 0, 0);
		lens_flares_for (cam_x, cam_y, cam_z, 3540, -285, -835, -5000, 2, 1, 0, 0, 0);
		lens_flares_for (cam_x, cam_y, cam_z, 3540, -810, -835, -5000, 2, 1, 0, 0, 0); */

                #ifdef INTERNALLIGHT
                  #ifdef intlightnewposition
		   //The original (new), big lens flare.. The one in the center of the SD...
		   lens_flares_for (cam_x, cam_y, cam_z, -10, 10, -10, -50000, 2, 1, 0, 0, 0);
		  #endif
		  #ifndef intlightnewposition
		   //The original (old NIVstyle), big lens flare.. The one in the corner of the SD...
		   lens_flares_for (cam_x, cam_y, cam_z, -10, 10, -10, -50000, 2, 1, 0, 0, 0);
		  #endif
		#endif

                #ifndef intlightnewposition
                 cam_x += 3395; //Correcting the cam_values if the OLD NIV light is being used.
	         cam_y -=  980;
	         cam_z +=  2900;
                #endif

		/*for (int c=100; c>0; c--) { //floor
		    lens_flares_for (cam_x, cam_y, cam_z, RANDOM(7000) - 3500, -10, RANDOM(7000) - 3500, -5000, 2, 0, 0, 0, 0);
		}*/


                #ifdef SPARKSON
                if (sparkinit) {
                  for (int ts=numspark - 1; ts>=0; ts--) {
                    sparklife[ts] = -random(1000);
                    sparkdensity[ts] = 30;
                  }
                  sparkinit = 0;
                }
        
                for (int ts=numspark - 1; ts>=0; ts--) {
                  if (sparklife[ts] < 0) {
                    sparklife[ts] = sparklife[ts] + 1.0;
                  }
                  if (sparklife[ts] >= 0) {
                    // Move spark and make the remaining lifespan of a spark lower.
                    sparkx[ts] = sparkx[ts] + spark_sx[ts];
                    sparkz[ts] = sparkz[ts] + spark_sz[ts];
                    sparky[ts] = sparky[ts] + spark_sy[ts];
                    if (sparklife[ts] > 0) {
                      sparklife[ts] = sparklife[ts] - 1.0;
                    }
        
                    // 'Per-frame' physics.
                    spark_sx[ts] = spark_sx[ts] * 0.998; //Air resistance
                    spark_sz[ts] = spark_sz[ts] * 0.998; //Air resistance
                    spark_sy[ts] = spark_sy[ts] + 0.05;  //Gravity
        
                    // Collision detection
                    // SPARKBOUNCEFLOOR and SPARKBOUNCEWALL are defined above. See 'effects'.
                    // SPARKKILL (boolean. either defined or not) kills sparks as soon as they hit the Stardrifter.
                    #ifndef SPARKKILL
                      if (sparky[ts] > 0) { //floor
                        spark_sy[ts] = 0 - spark_sy[ts] * SPARKBOUNCEFLOOR;
                        sparky[ts] = -1;
                      }
                      if (sparkx[ts] < -3600) {//side X-
                        spark_sx[ts] = 0 - spark_sx[ts] * SPARKBOUNCEWALL;
                        sparkx[ts] = -3599;
                      }
                      if (sparkx[ts] > 3600) {//side X+
                        spark_sx[ts] = 0 - spark_sx[ts] * SPARKBOUNCEWALL;
                        sparkx[ts] = 3599;
                      }
                      if (sparkz[ts] < -3100) {//side Z-
                        spark_sz[ts] = 0 - spark_sz[ts] * SPARKBOUNCEWALL;
                        sparkz[ts] = -3099;
                      }
                      if (sparkz[ts] > 3100) {//side Z+
                        spark_sz[ts] = 0 - spark_sz[ts] * SPARKBOUNCEWALL;
                        sparkz[ts] = 3099;
                      }
                    #endif
                    #ifdef SPARKKILL
                      if (sparky[ts] > 0) {     sparkdensity[ts] = 201;  sparklife[ts] = -1; } //floor
                      if (sparkx[ts] < -3600) { sparkdensity[ts] = 201;  sparklife[ts] = -1; } //side X-
                      if (sparkx[ts] > 3600) {  sparkdensity[ts] = 201;  sparklife[ts] = -1; } //side X+
                      if (sparkz[ts] < -3100) { sparkdensity[ts] = 201;  sparklife[ts] = -1; } //side Z-
                      if (sparkz[ts] > 3100) {  sparkdensity[ts] = 201;  sparklife[ts] = -1; } //side Z+
                    #endif
        
        
                    // Kill sparks
                    if (sparklife[ts] == 0) {
                      sparkdensity[ts] = sparkdensity[ts] + 1.0;
                    }
                    // Generate new sparks when old sparks are 'dead'.
                    if (sparkdensity[ts] > 200) {
                      #if sparkeffect == 1
                        sparkx[ts] = -3599; // Corner waterfall. El-neato.
                        sparkz[ts] = -3099;
                        sparky[ts] = -950 + random(50);
                        spark_sx[ts] = float(random (51) + 20)/10;
                        spark_sz[ts] = float(random (51) + 20)/10;
                        spark_sy[ts] = -1;
                        sparklife[ts] = RANDOM(500);
                        sparkdensity[ts] = 40;
                      #endif
        
                      #if sparkeffect == 2
                        sparkx[ts] = 0; //default center fountain
                        sparkz[ts] = 0;
                        sparky[ts] = -100;
                        spark_sx[ts] = float(random (61) - 30)/10;
                        spark_sz[ts] = float(random (61) - 30)/10;
                        spark_sy[ts] = -6;
                        sparklife[ts] = random(500);
                        sparkdensity[ts] = 30;
                      #endif
                    }
                    lens_flares_for (cam_x, cam_y, cam_z, sparkx[ts], sparky[ts], sparkz[ts], -5000, sparkdensity[ts] / 10, 0, 0, 0, 0);
                  }
                }
                #endif //SPARKSON
        
                #ifdef OMEGAORBON
                if (charge > -1) {
                  orbsize = (float) pwr - 15000; if (orbsize<0) orbsize = 0; //calculate Kilodyams.
                  orbsize = ((charge * 4) + (orbsize / (5000/4))) + 100;
                  tempflarecharge = ((120 - charge) * 55.8333333) - 3000;
                  #if omegaorbtype == 1
                  if (charge <= 4) { //Blink the fuel indicator erratically when fuel is critical-ish! - STYLE 1
                    tempflaredensity = tempflaredensity + 1;
                    if (tempflaredensity > ((6 - charge) * 2) + 2) tempflaredensity = 2;
                  }
                  #endif
                  #if omegaorbtype == 2
                  if (charge <= 10) {
                    tempflaredensityt++;
                    if (tempflaredensityt > (charge + 1) * 8) {
                      tempflaredensityt = 0;
                      tempflaredensity = 8;
                    } else {
                      tempflaredensity--;
                      if (tempflaredensity < 2) tempflaredensity = 2;
                    }
                  }
                  #endif
                   else {
                    tempflaredensity = 2;
                  }
                  temptimer = 180;
                } else {
                  orbsize = 580;
                  temptimer = temptimer + 3;
                  if (temptimer > 360) temptimer = 1;
                  tempflaredensity = 2;
		    tempflarecharge = (sin(temptimer * 0.0174532925) * 3000);
                }

		for (int c=18; c>0; c--) { // orbishness stuff
                  int tempangledeg;
                  float tempanglerad;
                  tempangledeg = c * 20;
                  tempanglerad = tempangledeg * 0.0174532925; // * degree to radian
                  //lens_flares_for (cam_x, cam_y, cam_z, sin(tempanglerad) * 100, -10, cos(tempanglerad) * 100, -5000, 2, 0, 0, 0, 0); //donut :D
                  for (int i=8; i>0; i--) { // introduce Y! //std
                    float tempyangle;
                    tempyangle = i * 20;
                    tempyangle = tempyangle * 0.0174532925; // * degree to radian
                    //lens_flares_for (cam_x, cam_y, cam_z, sin(tempanglerad) * orbsize, cos(tempyangle) * orbsize, cos(tempanglerad) * orbsize, -5000, 2, 0, 0, 0, 0); //Cylinder
                    lens_flares_for (cam_x, cam_y, cam_z, sin(tempanglerad + (temptimer / 3 * 0.0174532925)) * (sin(tempyangle) * orbsize), (cos(tempyangle) * orbsize) - 500, cos(tempanglerad + (temptimer / 3 * 0.0174532925)) * (sin(tempyangle) * orbsize), -5000 + tempflarecharge, tempflaredensity, 0, 0, 0, 0);
                  }
                  /*for (int i=16; i>0; i--) { // introduce Y!  //nuke - just for fun :P
                    float tempyangle;
                    int i2;
                    if (i < 4) i2 = i;
                    if (i >= 4 && i < 10) i2 = 4;
                    if (i >= 10) i2 = i - 7;
                    tempyangle = i * 10;
                    tempyangle = tempyangle * 0.0174532925; // * degree to radian
                    lens_flares_for (cam_x, cam_y, cam_z, sin(tempanglerad) * i2 * 100, (i * 100) - 1000, cos(tempanglerad) * i2 * 100, -5000, 2, 0, 0, 0, 0); //Cylinder
                    status("NUCLEAR LAUNCH DETECTED", 50);
                  }*/
		}
                #endif //OMEGAORBON
        
                /*lens_flares_for (cam_x, cam_y, cam_z, ap_target_x / 10000, ap_target_y / 10000, ap_target_z / 10000, -50000, 2, 1, 0, 0, 0); //Show star position in galaxy
        	navigation_beta = 180;
                lens_flares_for (cam_x, cam_y, cam_z, plx / 100, 0, plz / 100, -50000, 2, 1, 0, 0, 0);  //Galaxy Position light (only works properly if navigation_beta is 180 due to angling of the SD.
                navigation_beta = 180;*/
	}
}

/* Quadranti di selezione del computer di bordo. */

void qsel (float *x, float *y, float *z, Uword n, Uchar c)
{
	setfx (1);

	x[0] -= 10; y[0] -= 10;
	x[1] += 10; y[1] -= 10;
	x[2] += 10; y[2] += 10;
	x[3] -= 10; y[3] += 10;

	poly3d (x, y, z, n, c);

	chgfx (0);

	x[0] += 10; y[0] += 10;
	x[1] -= 10; y[1] += 10;
	x[2] -= 10; y[2] -= 10;
	x[3] += 10; y[3] -= 10;

	poly3d (x, y, z, n, 68);

	resetfx ();
}

/* Tutti i riflessi sulle superfici riflettenti. */

void reflexes ()
{
	float x[4], y[4], z[4];

	setfx (1);

	lbxf++;

/*	if (depolarize) goto norefs;

	if (ilight) {
		x[0] = 3200; y[0] = -425; z[0] = -100;
		x[1] = 1000; y[1] = -415; z[1] = -100;
		x[2] = 3200; y[2] = -400; z[2] = -100;
		poly3d (x, y, z, 3, 1);
		x[0] = 3200; y[0] = -400; z[0] = -100;
		x[1] = 3175; y[1] = -425; z[1] = -100;
		x[2] = 3200; y[2] = +300; z[2] = -100;
		poly3d (x, y, z, 3, 5);
	}

	if (pos_z<-1750||beta<-45||beta>45) {
		x[0] = -1200; y[0] = -525; z[0] = -1800;
		x[1] = +1350; y[1] = -525; z[1] = -1800;
		x[2] = +1300; y[2] = -575; z[2] = -1850;
		poly3d (x, y, z, 3, 1);
		x[0] = +1350; y[0] = -525; z[0] = -1800;
		x[1] = +1350; y[1] = -525; z[1] = -4000;
		poly3d (x, y, z, 3, 1);
		x[0] = -1200; y[0] = +450; z[0] = -1800;
		x[1] = +1350; y[1] = +450; z[1] = -1800;
		x[2] = +1300; y[2] = +500; z[2] = -1850;
		poly3d (x, y, z, 3, 1);
		x[0] = +1350; y[0] = +450; z[0] = -1800;
		x[1] = +1350; y[1] = +450; z[1] = -4000;
		poly3d (x, y, z, 3, 1);
	} */

norefs:	if (ap_targetting||ip_targetting) goto noevid;

	if (ilight)
		setfx (1);
	else
		setfx (0);

	z[0] = 0;
	z[1] = 0;
	z[2] = 0;
	z[3] = 0;

	if (s_control) {
		x[0] = -66*30 - 10; y[0] = 50 * (s_control - 3) - 30;
		x[1] = -46*30;      y[1] = 50 * (s_control - 3) - 30;
		x[2] = -46*30;      y[2] = 50 * (s_control - 2) - 25;
		x[3] = -66*30 - 10; y[3] = 50 * (s_control - 2) - 25;
		qsel (x, y, z, 4, 1);
	}

	if (sys!=4) {
		x[0] = -45.65*30; y[0] = - 125;
		x[1] = -45.45*30; y[1] = - 125;
		x[2] = -45.45*30; y[2] =    75;
		x[3] = -45.65*30; y[3] =    75;
		if (stspeed)
			poly3d (x, y, z, 4, 32);
		else {
			if (ilight)
				poly3d (x, y, z, 4, 8);
			else
				poly3d (x, y, z, 4, 80);
		}
		if (s_command) {
			x[0] = 27*30*s_command - 72*30 + 10; y[0] = -130;
			x[1] = x[0] + 26*30 + 10;    	     y[1] = -130;
			x[2] = x[1]; 			     y[2] =  -75;
			x[3] = x[0]; 			     y[3] =  -75;
			qsel (x, y, z, 4, 1);
		}
	}

noevid:	lbxf--;

	setfx (0);
}

/* Schemi aggiuntivi per lo schermo del computer. */

void frame (float x, float y, float l, float h,
	    float borderwidth, Uchar color)
{ // disegna una cornice rettangolare.
	float vx[4], vy[4], vz[4] = { 0, 0, 0, 0 };

	float x0 = cam_x;
	float y0 = cam_y;

	setfx (4);

	vx[0] = -l-borderwidth; vy[0] = -borderwidth;
	vx[1] = +l+borderwidth;	vy[1] = vy[0];
	vx[2] = +l+borderwidth; vy[2] = +borderwidth;
	vx[3] = -l-borderwidth; vy[3] = vy[2];

	cam_x = x0 - x;
	cam_y = y0 - y - h; poly3d (vx, vy, vz, 4, color);
	cam_y = y0 - y + h; poly3d (vx, vy, vz, 4, color);

	vx[0] = -borderwidth; vy[0] = -h-borderwidth;
	vx[1] = +borderwidth; vy[1] = vy[0];
	vx[2] = +borderwidth; vy[2] = +h+borderwidth;
	vx[3] = -borderwidth; vy[3] = vy[2];

	cam_y = y0 - y;
	cam_x = x0 - x - l; poly3d (vx, vy, vz, 4, color);
	cam_x = x0 - x + l; poly3d (vx, vy, vz, 4, color);

	cam_x = x0;
	cam_y = y0;

	resetfx ();
}

/* Croce di puntamento delle stelle. */

void pointer_cross_for (double xlight, double ylight, double zlight)
{
	double xx, yy, zz, z2, rx, ry, rz;

	xx = xlight - dzat_x;
	yy = ylight - dzat_y;
	zz = zlight - dzat_z;

	rx = xx * opt_pcosbeta + zz * opt_psinbeta;
	z2 = zz * opt_tcosbeta - xx * opt_tsinbeta;
	rz = z2 * opt_tcosalfa + yy * opt_tsinalfa;
	ry = yy * opt_pcosalfa - z2 * opt_psinalfa;

	if (rz>1) {
		rx /= rz; rx += x_centro;
		ry /= rz; ry += y_centro - 2;
		if (rx>10&&ry>10&&rx<310&&ry<190) {
			#ifdef WINDOWS
			int tmp = 320*(int)ry + rx;
			asm {
				push edi
				push esi
				mov esi, tmp
			}
			//_ESI = 320*(int)ry + rx;
			asm {	mov edi, [adapted]
				add edi, esi
				mov al, 126
				mov [edi-320*7-7], al
				mov [edi-320*6-6], al
				mov [edi-320*5-5], al
				mov [edi-320*4-4], al
				mov [edi+320*4+4], al
				mov [edi+320*5+5], al
				mov [edi+320*6+6], al
				mov [edi+320*7+7], al
				mov [edi-320*7+7], al
				mov [edi-320*6+6], al
				mov [edi-320*5+5], al
				mov [edi-320*4+4], al
				mov [edi+320*4-4], al
				mov [edi+320*5-5], al
				mov [edi+320*6-6], al
				mov [edi+320*7-7], al
				pop esi
				pop edi
			}
			#else
			_SI = 320*(int)ry + rx;
			asm {	les di, dword ptr adapted
				add di, si
				mov al, 126
				mov es:[di-320*7-7], al
				mov es:[di-320*6-6], al
				mov es:[di-320*5-5], al
				mov es:[di-320*4-4], al
				mov es:[di+320*4+4], al
				mov es:[di+320*5+5], al
				mov es:[di+320*6+6], al
				mov es:[di+320*7+7], al
				mov es:[di-320*7+7], al
				mov es:[di-320*6+6], al
				mov es:[di-320*5+5], al
				mov es:[di-320*4+4], al
				mov es:[di+320*4-4], al
				mov es:[di+320*5-5], al
				mov es:[di+320*6-6], al
				mov es:[di+320*7-7], al }
			#endif
		}
	}
}

void centerouter_cross ()			//Center / outer ring pointer (Mega)
{
	double xx, yy, zz, z2, rx, ry, rz;

	xx = 0 - dzat_x;
	yy = 0 - dzat_y;
	zz = 0 - dzat_z;

	rx = xx * opt_pcosbeta + zz * opt_psinbeta;
	z2 = zz * opt_tcosbeta - xx * opt_tsinbeta;
	rz = z2 * opt_tcosalfa + yy * opt_tsinalfa;
	ry = yy * opt_pcosalfa - z2 * opt_psinalfa;

	if (rz>1) {
		rx /= rz; rx += x_centro;
		ry /= rz; ry += y_centro - 2;
		if (rx>10&&ry>10&&rx<310&&ry<190) {
			#ifdef WINDOWS
			int tmp = 320*(int)ry + rx;
			asm {
				push edi
				push esi
				mov esi, tmp
			}
			//_ESI = 320*(int)ry + rx;
			asm {	mov edi, [adapted]
				add edi, esi
				mov al, 120
				mov [edi-0], al
				mov [edi-2], al
				mov [edi+2], al
				mov [edi+320*2+1], al
				mov [edi+320*2+0], al
				mov [edi+320*2-1], al
				mov [edi+320*1-2], al
				mov [edi+320*1+2], al
				mov [edi-320*2+1], al
				mov [edi-320*2+0], al
				mov [edi-320*2-1], al
				mov [edi-320*1-2], al
				mov [edi-320*1+2], al
				pop esi
				pop edi
			}
			#else
			_SI = 320*(int)ry + rx;
			asm {	les di, dword ptr adapted
				add di, si
				mov al, 120
				mov es:[di+320*0-0], al
				mov es:[di+320*0-2], al
				mov es:[di+320*0+2], al
				mov es:[di+320*2+1], al
				mov es:[di+320*2+0], al
				mov es:[di+320*2-1], al
				mov es:[di+320*1-2], al
				mov es:[di+320*1+2], al
				mov es:[di-320*2+1], al
				mov es:[di-320*2+0], al
				mov es:[di-320*2-1], al
				mov es:[di-320*1-2], al
				mov es:[di-320*1+2], al
			}
			#endif
		}
	}

	xx = dzat_x*2;
	yy = dzat_y*2;
	zz = dzat_z*2;

	rx = xx * opt_pcosbeta + zz * opt_psinbeta;
	z2 = zz * opt_tcosbeta - xx * opt_tsinbeta;
	rz = z2 * opt_tcosalfa + yy * opt_tsinalfa;
	ry = yy * opt_pcosalfa - z2 * opt_psinalfa;

	if (rz>1) {
		rx /= rz; rx += x_centro;
		ry /= rz; ry += y_centro - 2;
		if (rx>10&&ry>10&&rx<310&&ry<190) {
			#ifdef WINDOWS
			int tmp = 320*(int)ry + rx;
			asm {
				push edi
				push esi
				mov esi, tmp
			}
			//_ESI = 320*(int)ry + rx;
			asm {	mov edi, [adapted]
				add edi, esi
				mov al, 120
				mov [edi-320*1-0], al
				mov [edi+320*1-0], al
				mov [edi+1], al
				mov [edi-1], al
				pop esi
				pop edi
			}
			#else
			_SI = 320*(int)ry + rx;
			asm {	les di, dword ptr adapted
				add di, si
				mov al, 120
				mov es:[di-320*1-0], al
				mov es:[di+320*1-0], al
				mov es:[di+320*0+1], al
				mov es:[di-320*0-1], al
			}
			#endif
		}
	}
}

void z_axis ()						//Z-axis pointer (Mega)
{
	double xx, yy, zz, z2, rx, ry, rz;

	xx = 0;
	yy = 0;
	zz = 500;

	rx = xx * opt_pcosbeta + zz * opt_psinbeta;
	z2 = zz * opt_tcosbeta - xx * opt_tsinbeta;
	rz = z2 * opt_tcosalfa + yy * opt_tsinalfa;
	ry = yy * opt_pcosalfa - z2 * opt_psinalfa;

	if (rz>1) {
		rx /= rz; rx += x_centro;
		ry /= rz; ry += y_centro - 2;
		if (rx>10&&ry>10&&rx<310&&ry<190) {
			#ifdef WINDOWS
			int tmp = 320*(int)ry + rx;
			asm {
				push edi
				push esi
				mov esi, tmp
			}
			//_ESI = 320*(int)ry + rx;
			asm {	mov edi, [adapted]
				add edi, esi
				mov al, 120
				mov [edi], al
				mov [edi+320*1-1], al
				mov [edi+320*2-1], al
				mov [edi+320*2-0], al
				mov [edi+320*2+1], al
				mov [edi+320*2+2], al

				mov [edi-320*1+1], al
				mov [edi-320*2+1], al
				mov [edi-320*2+0], al
				mov [edi-320*2-1], al
				mov [edi-320*2-2], al
				pop esi
				pop edi
			}
			#else
			_SI = 320*(int)ry + rx;
			asm {	les di, dword ptr adapted
				add di, si
				mov al, 120
				mov es:[di+320*0-0], al
				mov es:[di+320*1-1], al
				mov es:[di+320*2-1], al
				mov es:[di+320*2-0], al
				mov es:[di+320*2+1], al
				mov es:[di+320*2+2], al

				mov es:[di-320*1+1], al
				mov es:[di-320*2+1], al
				mov es:[di-320*2+0], al
				mov es:[di-320*2-1], al
				mov es:[di-320*2-2], al
			}
			#endif
		}
	}

	xx = 0;
	yy = 0;
	zz = -500;

	rx = xx * opt_pcosbeta + zz * opt_psinbeta;
	z2 = zz * opt_tcosbeta - xx * opt_tsinbeta;
	rz = z2 * opt_tcosalfa + yy * opt_tsinalfa;
	ry = yy * opt_pcosalfa - z2 * opt_psinalfa;

	if (rz>1) {
		rx /= rz; rx += x_centro;
		ry /= rz; ry += y_centro - 2;
		if (rx>10&&ry>10&&rx<310&&ry<190) {
			#ifdef WINDOWS
			int tmp = 320*(int)ry + rx;
			asm {
				push edi
				push esi
				mov esi, tmp
			}
			//_ESI = 320*(int)ry + rx;
			asm {
				mov edi, [adapted]
				add edi, esi
				mov al, 120
				mov [edi], al
				mov [edi+320*1], al
				mov [edi+320*1+1], al
				mov [edi-320*1], al
				mov [edi-320*1-1], al
				pop esi
				pop edi
			}
			
			#else
			_SI = 320*(int)ry + rx;
			asm {	les di, dword ptr adapted
				add di, si
				mov al, 120
				mov es:[di+320*0-0], al
				mov es:[di+320*1-0], al
				mov es:[di+320*1+1], al
				mov es:[di-320*1-0], al
				mov es:[di-320*1-1], al
			}
			#endif
		}
	}
}

void x_axis ()						//X-axis pointer (Mega)
{
	double xx, yy, zz, z2, rx, ry, rz;

	xx = 500;
	yy = 0;
	zz = 0;

	rx = xx * opt_pcosbeta + zz * opt_psinbeta;
	z2 = zz * opt_tcosbeta - xx * opt_tsinbeta;
	rz = z2 * opt_tcosalfa + yy * opt_tsinalfa;
	ry = yy * opt_pcosalfa - z2 * opt_psinalfa;

	if (rz>1) {
		rx /= rz; rx += x_centro;
		ry /= rz; ry += y_centro - 2;
		if (rx>10&&ry>10&&rx<310&&ry<190) {
			#ifdef WINDOWS
			int tmp = 320*(int)ry + rx;
			asm {
				push edi
				push esi
				mov esi, tmp
			}
			//_ESI = 320*(int)ry + rx;
			asm {
				mov edi, [adapted]
				add edi, esi
				mov al, 120
				mov [edi], al
				mov [edi+320*1-1], al
				mov [edi+320*2-2], al
				mov [edi+320*1+1], al
				mov [edi+320*2+2], al
				mov [edi-320*1-1], al
				mov [edi-320*2-2], al
				mov [edi-320*1+1], al
				mov [edi-320*2+2], al
				pop esi
				pop edi
			}
			#else
			_SI = 320*(int)ry + rx;
			asm {	les di, dword ptr adapted
				add di, si
				mov al, 120
				mov es:[di+320*0-0], al
				mov es:[di+320*1-1], al
				mov es:[di+320*2-2], al
				mov es:[di+320*1+1], al
				mov es:[di+320*2+2], al
				mov es:[di-320*1-1], al
				mov es:[di-320*2-2], al
				mov es:[di-320*1+1], al
				mov es:[di-320*2+2], al
			}
			#endif
		}
	}

	xx = -500;
	yy = 0;
	zz = 0;

	rx = xx * opt_pcosbeta + zz * opt_psinbeta;
	z2 = zz * opt_tcosbeta - xx * opt_tsinbeta;
	rz = z2 * opt_tcosalfa + yy * opt_tsinalfa;
	ry = yy * opt_pcosalfa - z2 * opt_psinalfa;

	if (rz>1) {
		rx /= rz; rx += x_centro;
		ry /= rz; ry += y_centro - 2;
		if (rx>10&&ry>10&&rx<310&&ry<190) {
			#ifdef WINDOWS
			int tmp = 320*(int)ry + rx;
			asm {
				push edi
				push esi
				mov esi, tmp
			}
			//_ESI = 320*(int)ry + rx;
			asm {
				mov edi, [adapted]
				add edi, esi
				mov al, 120
				mov [edi], al
				mov [edi+320*1-1], al
				mov [edi+320*1+1], al
				mov [edi-320*1-1], al
				mov [edi-320*1+1], al
				pop esi
				pop edi
			}
			#else
			_SI = 320*(int)ry + rx;
			asm {	les di, dword ptr adapted
				add di, si
				mov al, 120
				mov es:[di+320*0-0], al
				mov es:[di+320*1-1], al
				mov es:[di+320*1+1], al
				mov es:[di-320*1-1], al
				mov es:[di-320*1+1], al
			}
			#endif
		}
	}
}

void y_axis ()			//Y-axis pointer (Mega)
{
	double xx, yy, zz, z2, rx, ry, rz;

	xx = 0;
	yy = -500;
	zz = 0;

	rx = xx * opt_pcosbeta + zz * opt_psinbeta;
	z2 = zz * opt_tcosbeta - xx * opt_tsinbeta;
	rz = z2 * opt_tcosalfa + yy * opt_tsinalfa;
	ry = yy * opt_pcosalfa - z2 * opt_psinalfa;

	if (rz>1) {
		rx /= rz; rx += x_centro;
		ry /= rz; ry += y_centro - 2;
		if (rx>10&&ry>10&&rx<310&&ry<190) {
			#ifdef WINDOWS
			int tmp = 320*(int)ry + rx;
			asm {
				push edi
				push esi
				mov esi, tmp
			}
			//_ESI = 320*(int)ry + rx;
			asm {
				mov edi, [adapted]
				add edi, esi
				mov al, 120
				mov [edi], al
				mov [edi-320*1-1], al
				mov [edi-320*2-2], al
				mov [edi-320*1+1], al
				mov [edi-320*2+2], al
				mov [edi+320*1], al
				mov [edi+320*2], al
				pop esi
				pop edi
			}
			#else
			_SI = 320*(int)ry + rx;
			asm {	les di, dword ptr adapted
				add di, si
				mov al, 120
				mov es:[di-320*0-0], al
				mov es:[di-320*1-1], al
				mov es:[di-320*2-2], al
				mov es:[di-320*1+1], al
				mov es:[di-320*2+2], al
				mov es:[di+320*1-0], al
				mov es:[di+320*2-0], al
			}
			#endif
		}
	}

	xx = 0;
	yy = 500;
	zz = 0;

	rx = xx * opt_pcosbeta + zz * opt_psinbeta;
	z2 = zz * opt_tcosbeta - xx * opt_tsinbeta;
	rz = z2 * opt_tcosalfa + yy * opt_tsinalfa;
	ry = yy * opt_pcosalfa - z2 * opt_psinalfa;

	if (rz>1) {
		rx /= rz; rx += x_centro;
		ry /= rz; ry += y_centro - 2;
		if (rx>10&&ry>10&&rx<310&&ry<190) {
			#ifdef WINDOWS
			int tmp = 320*(int)ry + rx;
			asm {
				push edi
				push esi
				mov esi, tmp
			}
			//_ESI = 320*(int)ry + rx;
			asm {
				mov edi, [adapted]
				add edi, esi
				mov al, 120
				mov [edi], al
				mov [edi-320*1-1], al
				mov [edi-320*1+1], al
				mov [edi+320*1], al
				pop esi
				pop edi
			}
			#else
			_SI = 320*(int)ry + rx;
			asm {	les di, dword ptr adapted
				add di, si
				mov al, 120
				mov es:[di-320*0-0], al
				mov es:[di-320*1-1], al
				mov es:[di-320*1+1], al
				mov es:[di+320*1-0], al
			}
			#endif
		}
	}
}

/* Scrive sullo schermo del computer di bordo: una linea. */

void cline (Word line, char *text)
{
	#ifdef WINDOWS
	Dword lineDW = line;
	#endif
	asm {
		#ifdef WINDOWS
		push edi
		push esi
		lea edi, ctb
		shl lineDW, 7
		add edi, lineDW
		add edi, 20
		mov esi, [text]
	} byter: asm {
		cmp byte ptr [esi], 0
		je endline
		movsb
		jmp byter
		pop esi
		pop edi
		}
endline:asm {   mov point, edi
		#else
		push ds
		push ds
		pop es
		lea di, ctb
		shl line, 7
		add di, line
		add di, 20
		lds si, dword ptr text }
byter:	asm {	cmp byte ptr [si], 0
		je endline
		movsb
		jmp byter }
endline:asm {   mov point, di
		pop ds
		#endif
	}
}

/* Prosegue la linea suddetta. */

void other (char *text)
{
	asm {
		#ifdef WINDOWS
		push edi
		push esi
		mov edi, point
		mov esi, [text]
		}
byter:	asm {	cmp byte ptr [esi], 0
		je endline
		movsb
		jmp byter }
endline:asm {   mov point, edi
		pop esi
		pop edi
		}
		#else
		push ds
		push ds
		pop es
		mov di, point
		lds si, dword ptr text }
byter:	asm {	cmp byte ptr [si], 0
		je endline
		movsb
		jmp byter }
endline:asm {   mov point, di
		pop ds }
		#endif
}

/* Scrive il titolo di un controllo di sistema (sono 4 in tutto). */

void control (Word line, char *text)
{
	#ifdef WINDOWS
	Dword lineDW = line;
	#endif
	asm {
		#ifdef WINDOWS
		push edi
		push esi
		lea edi, ctb
		dec lineDW
		shl lineDW, 7
		add edi, lineDW
		mov esi, [text]
	}
byter:	asm {	cmp byte ptr [esi], 0
		je endline
		movsb
		jmp byter }
endline:
		asm {
			pop esi;
			pop edi;
		}
		#else
		push ds
		push ds
		pop es
		lea di, ctb
		dec line
		shl line, 7
		add di, line
		lds si, dword ptr text }
byter:	asm {	cmp byte ptr [si], 0
		je endline
		movsb
		jmp byter }
endline:asm 	pop ds
		#endif
}

/* Scrive il titolo di un comando. */

void command (Word nr, char *text)
{
	asm {
		#ifdef WINDOWS
		push edi
		push esi
		lea edi, ctb
		add edi, 20
		dec nr
		movsx eax, nr
		mov dx, 27
		mul dx
		add edi, eax
		mov eax, 27
		mov esi, [text]
		}
byter:	asm {	cmp byte ptr [esi], 0
		je endline
		movsb
		dec eax
		jnz byter }
endline:asm {	test eax, eax
		jz endwork
		mov byte ptr [edi], 32
		inc edi
		dec eax
		jnz endline }
endwork: asm {
		pop esi
		pop edi
		}
		#else
		push ds
		push ds
		pop es
		lea di, ctb
		add di, 20
		dec nr
		mov ax, nr
		mov dx, 27
		mul dx
		add di, ax
		mov ax, 27
		lds si, dword ptr text }
byter:	asm {	cmp byte ptr [si], 0
		je endline
		movsb
		dec ax
		jnz byter }
endline:asm {	test ax, ax
		jz endwork
		mov byte ptr es:[di], 32
		inc di
		dec ax
		jnz endline }
endwork:asm  	pop ds
	#endif
}

/* Cancella tutto lo schermo del computer di bordo. */

void clear_onboard_screen ()
{
	//Was mov cx, 256, changed when I added a row to the display. (SL)
	asm {
	#ifdef WINDOWS
		push edi
		lea edi, ctb
		mov ecx, 320
		xor eax, eax
	#else
		push ds
		pop es
		lea di, ctb
		mov cx, 320
		xor ax, ax
	#endif
		cld
		rep stosw
	#ifdef WINDOWS
		pop edi
	#endif
	}
}

/* Gruppo di gestione del sistema operativo di bordo. */

Uchar reset_signal = 55;		// Segnale di reset (=55).
char force_update = 0;				// Forza il refresh schermi.
char active_screen = 0;				// Schermo attualmente attivo.
Uchar osscreen[2][7*21+1]; 		// Matrici degli schermi GOES.
Word osscreen_cursor_x[2] = { 0, 0 };		// Posizione cursori (x).
Word osscreen_cursor_y[2] = { 0, 0 };		// Posizione cursori (y).
char osscreen_textbuffer[7*21+1] = "";		// Buffer degli schermi.

void mslocate (Word screen_id, Word cursor_x, Word cursor_y)
{ // Rilocazione cursore (multischermo).

	osscreen_cursor_x[screen_id] = cursor_x;
	osscreen_cursor_y[screen_id] = cursor_y;
}

void mswrite (Word screen_id, char *text)
{ // Scrittura caratteri (multischermo).

	Word  i, c = 0;
	char symbol;

	while ((symbol = text[c]) != 0) {
		if (symbol>=32 && symbol<=96) {
			i = 21 * osscreen_cursor_y[screen_id];
			i += osscreen_cursor_x[screen_id];
			osscreen[screen_id][i] = symbol;
			osscreen_cursor_x[screen_id]++;
			if (osscreen_cursor_x[screen_id] >= 21) {
				osscreen_cursor_x[screen_id] = 0;
				osscreen_cursor_y[screen_id]++;
			}
		}
		switch (symbol) {
			case 13:
				osscreen_cursor_x[screen_id] = 0;
				osscreen_cursor_y[screen_id]++;
				break;
			case 9:
				osscreen_cursor_x[screen_id] /= (3*4);
				osscreen_cursor_x[screen_id]++;
				osscreen_cursor_x[screen_id] *= (3*4);
				if (osscreen_cursor_x[screen_id] >= 21) {
					osscreen_cursor_x[screen_id] = 0;
					osscreen_cursor_y[screen_id]++;
				}
				break;
		}
		c++;
	}
}

char gnc_pos = 0;			// Numero carattere in command line.
Dword goesfile_pos = 0;			// Posizione sul file output di GOES.
char goesnet_command[120] = "_";	// Command line di GOES Net.

/* Congela la situazione (all'uscita dal programma o al run di un modulo). */

void freeze ()
{
	/*printf("Opening [%s]\n", situation_file);
	FILE *fh = fopen(situation_file, "wb");
	if (fh==NULL) return;
	fprintf(fh, "This is a test.\n");
	*/
	FILEPTR fh = CREATEFILE(situation_file);
	if (fh==NOFILE) return;
	#ifndef WINDOWS
	WRITEFILE (fh, &sync, old_currentbin_length);
	WRITEFILE (fh, &gnc_pos, 1);
	WRITEFILE (fh, &goesfile_pos, 4);
	WRITEFILE (fh, goesnet_command, 120);
	WRITEFILE (fh, &option_speedup, new_currentbin_length);
	#else
	//Made this regex: [a-zA-Z]+[ \t]+\([a-zA-Z0-9_\[\]0-9]+\)[ \t]*=[ \t]*[\-0-9a-zA-Z\.+-\"]+;
	//To write this: WRITEFILE (fh, &\1, sizeof(\1));
	//To transform the variable declarations into a bunch of WRITEFILE calls.
	WRITEFILE (fh, &sync, sizeof(sync));		// 0
	WRITEFILE (fh, &anti_rad, sizeof(anti_rad));          // 1
	WRITEFILE (fh, &pl_search, sizeof(pl_search));          // 2
	WRITEFILE (fh, &field_amplificator, sizeof(field_amplificator));          // 3
	WRITEFILE (fh, &ilight, sizeof(ilight));         // 4
	WRITEFILE (fh, &ilightv, sizeof(ilightv));          // 5
	WRITEFILE (fh, &charge, sizeof(charge));          // 6
	WRITEFILE (fh, &revcontrols, sizeof(revcontrols));          // 7
	WRITEFILE (fh, &ap_targetting, sizeof(ap_targetting));          // 8
	WRITEFILE (fh, &ap_targetted, sizeof(ap_targetted));          // 9
	WRITEFILE (fh, &ip_targetting, sizeof(ip_targetting));          // 10
	WRITEFILE (fh, &ip_targetted, sizeof(ip_targetted));		// 11
	WRITEFILE (fh, &ip_reaching, sizeof(ip_reaching));          // 12
	WRITEFILE (fh, &ip_reached, sizeof(ip_reached));          // 13
	WRITEFILE (fh, &ap_target_spin, sizeof(ap_target_spin));          // 14
	WRITEFILE (fh, &ap_target_r, sizeof(ap_target_r));          // 15
	WRITEFILE (fh, &ap_target_g, sizeof(ap_target_g));          // 16
	WRITEFILE (fh, &ap_target_b, sizeof(ap_target_b));          // 17
	WRITEFILE (fh, &nearstar_spin, sizeof(nearstar_spin));          // 18
	WRITEFILE (fh, &nearstar_r, sizeof(nearstar_r));          // 19
	WRITEFILE (fh, &nearstar_g, sizeof(nearstar_g));          // 20
	WRITEFILE (fh, &nearstar_b, sizeof(nearstar_b));          // 21
	WRITEFILE (fh, &gburst, sizeof(gburst));          // 22
	WRITEFILE (fh, &menusalwayson, sizeof(menusalwayson));		// 23
	WRITEFILE (fh, &depolarize, sizeof(depolarize));          // 24
	WRITEFILE (fh, &sys, sizeof(sys));		// 25
	WRITEFILE (fh, &pwr, sizeof(pwr));	// 27
	WRITEFILE (fh, &dev_page, sizeof(dev_page));		// 29
	WRITEFILE (fh, &ap_target_class, sizeof(ap_target_class));		// 31
	WRITEFILE (fh, &f_ray_elapsed, sizeof(f_ray_elapsed));		// 33
	WRITEFILE (fh, &nearstar_class, sizeof(nearstar_class));		// 35
	WRITEFILE (fh, &nearstar_nop, sizeof(nearstar_nop));		// 37
	WRITEFILE (fh, &pos_x, sizeof(pos_x));		// 39
	WRITEFILE (fh, &pos_y, sizeof(pos_y));		// 43
	WRITEFILE (fh, &pos_z, sizeof(pos_z));	// 47
	WRITEFILE (fh, &user_alfa, sizeof(user_alfa));		// 51
	WRITEFILE (fh, &user_beta, sizeof(user_beta));		// 55
	WRITEFILE (fh, &navigation_beta, sizeof(navigation_beta));		// 59
	WRITEFILE (fh, &ap_target_ray, sizeof(ap_target_ray));	// 63
	WRITEFILE (fh, &nearstar_ray, sizeof(nearstar_ray));	// 67
	WRITEFILE (fh, &dzat_x, sizeof(dzat_x));	// 71
	WRITEFILE (fh, &dzat_y, sizeof(dzat_y));	// 79
	WRITEFILE (fh, &dzat_z, sizeof(dzat_z));	// 87
	WRITEFILE (fh, &ap_target_x, sizeof(ap_target_x));		// 95
	WRITEFILE (fh, &ap_target_y, sizeof(ap_target_y));	// 103
	WRITEFILE (fh, &ap_target_z, sizeof(ap_target_z));		// 111
	WRITEFILE (fh, &nearstar_x, sizeof(nearstar_x));		// 119
	WRITEFILE (fh, &nearstar_y, sizeof(nearstar_y));	// 127
	WRITEFILE (fh, &nearstar_z, sizeof(nearstar_z));		// 135
	WRITEFILE (fh, &helptime, sizeof(helptime));		// 143
	WRITEFILE (fh, &ip_target_initial_d, sizeof(ip_target_initial_d));	// 151
	WRITEFILE (fh, &requested_approach_coefficient, sizeof(requested_approach_coefficient));// 159
	WRITEFILE (fh, &current_approach_coefficient, sizeof(current_approach_coefficient));// 167
	WRITEFILE (fh, &reaction_time, sizeof(reaction_time));	// 175
	WRITEFILE (fh, &(fcs_status[0]), 11);	// 183
	WRITEFILE (fh, &fcs_status_delay, sizeof(fcs_status_delay));		// 194
	WRITEFILE (fh, &psys, sizeof(psys));		// 196
	WRITEFILE (fh, &ap_target_initial_d, sizeof(ap_target_initial_d));	// 198
	WRITEFILE (fh, &requested_vimana_coefficient, sizeof(requested_vimana_coefficient));// 206
	WRITEFILE (fh, &current_vimana_coefficient, sizeof(current_vimana_coefficient));	// 214
	WRITEFILE (fh, &vimana_reaction_time, sizeof(vimana_reaction_time));	// 222
	WRITEFILE (fh, &lithium_collector, sizeof(lithium_collector));		// 230
	WRITEFILE (fh, &autoscreenoff, sizeof(autoscreenoff));		// 231
	WRITEFILE (fh, &ap_reached, sizeof(ap_reached));		// 232
	WRITEFILE (fh, &lifter, sizeof(lifter));		// 233
	WRITEFILE (fh, &secs, sizeof(secs));		// 235
	WRITEFILE (fh, &data, sizeof(data));		// 243
	WRITEFILE (fh, &surlight, sizeof(surlight));		// 244

	WRITEFILE (fh, &gnc_pos, 1);
	WRITEFILE (fh, &goesfile_pos, 4);
	WRITEFILE (fh, goesnet_command, 120);

	//Same regex as before:
	//This regex: [a-zA-Z]+[ \t]+\([a-zA-Z0-9_\[\]0-9]+\)[ \t]*=[ \t]*[\-0-9a-zA-Z\.+-\"]+;
	//To write this: WRITEFILE (fh, &\1, sizeof(\1));
	//To transform the variable declarations into a bunch of WRITEFILE calls.
	//Additional variables: (SL and Mega)
	WRITEFILE (fh, &option_speedup, sizeof(option_speedup));			// 0
	WRITEFILE (fh, &option_temperature, sizeof(option_temperature));			// 1
	WRITEFILE (fh, &nearstar_mass, sizeof(nearstar_mass));				// 2
	WRITEFILE (fh, &nearstar_surfaceTemperature, sizeof(nearstar_surfaceTemperature));	// 10
	WRITEFILE (fh, &nearstar_temperatureTransmission, sizeof(nearstar_temperatureTransmission));// 18
	WRITEFILE (fh, &option_temperature_units, sizeof(option_temperature_units));			// 26
	WRITEFILE (fh, &option_flying_lander, sizeof(option_flying_lander));				// 27
	WRITEFILE (fh, &option_antialias_in_stardrifter, sizeof(option_antialias_in_stardrifter));		// 28
	WRITEFILE (fh, &option_center_outerring_pointer, sizeof(option_center_outerring_pointer));		// 29
	WRITEFILE (fh, &option_x_axis_pointer, sizeof(option_x_axis_pointer));		// 30
	WRITEFILE (fh, &option_y_axis_pointer, sizeof(option_y_axis_pointer));		// 31
	WRITEFILE (fh, &option_z_axis_pointer, sizeof(option_z_axis_pointer));		// 32
	WRITEFILE (fh, &option_multiplayer, sizeof(option_multiplayer));		// 33
	WRITEFILE (fh, &option_invis_sd, sizeof(option_invis_sd));			// 34
	WRITEFILE (fh, &option_change_over_time, sizeof(option_change_over_time));	//35
	WRITEFILE (fh, &lastSnapshot, sizeof(lastSnapshot));				//36
	WRITEFILE (fh, &option_mouseLook, sizeof(option_mouseLook));			//40
	WRITEFILE (fh, &ap_target_sx, sizeof(ap_target_sx));		//41
	WRITEFILE (fh, &ap_target_sy, sizeof(ap_target_sy));		//45
	WRITEFILE (fh, &ap_target_sz, sizeof(ap_target_sz));		//49
	WRITEFILE (fh, &nearstar_sx, sizeof(nearstar_sx));		//53
	WRITEFILE (fh, &nearstar_sy, sizeof(nearstar_sy));		//57
	WRITEFILE (fh, &nearstar_sz, sizeof(nearstar_sz));		//61
	WRITEFILE (fh, &option_3dbrackets, sizeof(option_3dbrackets));					//65
	WRITEFILE (fh, &option_controlset, sizeof(option_controlset));					//66
	WRITEFILE (fh, &current_galaxy, sizeof(current_galaxy));					//67
	

	#endif
	CLOSEFILE (fh);
}

//Obsolete: Use RunCommand. (SL)
/*
void run_goesnet_module ()
{ // Esecuzione di un modulo eseguibile della GOES Net.

	int ch;
	unsigned bqw = QUADWORDS;
	char isX = (goesnet_command[0]=='x' || goesnet_command[0]=='X') && (goesnet_command[1]==0 || goesnet_command[1]==' ');

	// Salva la situazione perch‚ alcuni moduli ne hanno bisogno.
	freeze ();

	// Libera circa 60 kilobytes per il lancio del modulo eseguibile.
	farfree (adapted);

	// Verifica comandi residenti.
	if (!memcmp (goesnet_command, "CLR", 3)) {
		remove (goesoutputfile);
		goto solong;
	}

	ch = _creat (goesoutputfile, 0);
	if (ch > -1) {
		_write (ch, "(UNKNOWN MODULE)", 16);
		_close (ch);
	}

	// Cancella l'ultimo carattere (che Š il _ cursore) dalla command
	// line, poi aggiunge la redirezione sul file "goesfile.txt"
	goesnet_command[gnc_pos] = 0;
	strcat (goesnet_command, " >");
	strcat (goesnet_command, goesoutputfile);
	system (goesnet_command);

	// Ri-alloca l'area temporaneamente liberata.
solong:	adapted = (Uchar far  *) farmalloc (sc_bytes);

	if (!adapted) {
		_80_25_C ();
		printf ("Sorry, GOES Net crashed.\n");
		printf ("System integrity compromised: any key to quit.\n\n");
		attendi_pressione_tasto();
		exit (0xFF);
	}
	else {
		QUADWORDS = 80 * 10;
		pclear (adaptor, 0);
		QUADWORDS = 16000 - 80 * 12;
		pcopy (adapted + 2*320, adaptor);
		QUADWORDS = bqw;
		// Reagisce alla presenza di dati nel file di comunicazione.
		ReadCommFile(0);
	}

	force_update = 1;
	goesfile_pos = 0;
	
	if (isX) {
		RecordXTime();
	}
}
*/

/* Gruppo di tracciamento dello schermo del computer di bordo. */

void squaredot (float x, float y, float size, Uchar color)
{ // questo Š un quadratino, un "pixel" del computer di bordo.
	float vx[4], vy[4], vz[4] = { 0, 0, 0, 0 };

	vx[0] = x-size;
	vx[1] = x+size;
	vx[2] = x+size;
	vx[3] = x-size;

	vy[0] = y-size;
	vy[1] = y-size;
	vy[2] = y+size;
	vy[3] = y+size;

	poly3d (vx, vy, vz, 4, color);
}

Dword pp[32]= { 0x00000001, 0x00000002, 0x00000004, 0x00000008,
		   0x00000010, 0x00000020, 0x00000040, 0x00000080,
		   0x00000100, 0x00000200, 0x00000400, 0x00000800,
		   0x00001000, 0x00002000, 0x00004000, 0x00008000,
		   0x00010000, 0x00020000, 0x00040000, 0x00080000,
		   0x00100000, 0x00200000, 0x00400000, 0x00800000,
		   0x01000000, 0x02000000, 0x04000000, 0x08000000,
		   0x10000000, 0x20000000, 0x40000000, 0x80000000 };

void digit_at (char digit, float x, float y, float size, Uchar color, char shader)
{ // questo Š un carattere alfanumerico...
	Uchar maybehuge *prev_txtr = txtr;

	float vx[4], vy[4], vz[4] = { 0, 0, 0, 0 };

	float size_x_left = size * -1.5;
	float size_y_left = size * -2.0;
	float size_x_right= size * +4.0;
	float size_y_right= size * +8.0;

	Dword prev_xs = XSIZE;
	Dword prev_ys = YSIZE;

	#ifdef WINDOWS
	Dword n, m, d, i;
	#else
	Word  n, m, d, i;
	#endif
	
	char pixel_color = color % 64;
	char map_base = (color >> 6) << 6;

	if (reset_signal > 100) {
		pixel_color -= (reset_signal - 100);
		if (pixel_color < 0) pixel_color = 0;
	}

	//BUFFERCHECK
	if (digit>32 && digit<=96) {
		txtr = p_surfacemap+16;
		d = (digit - 32) * 36;
		for (n = 0; n < 36; n++) {
			i = 256 * n - 5;
			//BUFFERCHECK
			txtr[i-1] = 0; // evita aliasing a fine scanline.
			//BUFFERCHECK
			for (m = 0; m < 32; m++) {
				//BUFFERCHECK
				if (digimap2[n+d] & pp[m]) {
					//BUFFERCHECK
					txtr[i] = pixel_color;
					//BUFFERCHECK
				} else {
					//BUFFERCHECK
					txtr[i] = 0;
					//BUFFERCHECK
				}
				i++;
			}
		
			if (shader) pixel_color--;
		}
		//BUFFERCHECK
		txtr[256 * 36 - 6] = 0; // evita aliasing a fine matrice.
		//BUFFERCHECK
		vx[3] = x + size_x_left;
		vx[0] = x + size_x_right;
		vx[1] = x + size_x_right;
		vx[2] = x + size_x_left;
		vy[3] = y + size_y_left;
		vy[0] = y + size_y_left;
		vy[1] = y + size_y_right;
		vy[2] = y + size_y_right;
		//BUFFERCHECK
		setfx (2);
		//BUFFERCHECK
		XSIZE = 512; YSIZE = 576;
		//BUFFERCHECK
		polymap (vx, vy, vz, 4, map_base);
		//BUFFERCHECK
		XSIZE = prev_xs; YSIZE = prev_ys;
		//BUFFERCHECK
		txtr = prev_txtr;
		//BUFFERCHECK
		resetfx ();
		//BUFFERCHECK
		
	}
}

void screen ()
{
	float x, y;
	Word   c, p, t = 0;

	#define blinkscolor 127
	#define screencolor 127

	if (ap_targetting) return;

	if (pwr <= 15000 && !charge) {
		fast_srand (secs);
		c = fast_random(3) + 2;
		if (CLOCK() % c) return;
	}

	x = cam_x;
	y = cam_y;

	for (p=-2; p<3; p++)		//Added a row to the display (SL)
		for (c=-64; c<64; c++) {
			cam_x = x - c*30;
			if (c<-44) {
				if (s_control || menusalwayson) {
					cam_x += 50;
					cam_y = y - p*50;
				}
				else {
					t += 19;
					c += 19;
					goto passby;
				}
			}
			if (c==-44) {
				if (s_command || menusalwayson) {
					if (p==-2 || menusalwayson)
						cam_y = y - p*50;
					else {
						t += 108;
						break;
					}
				}
				else {
					if (!infoarea || p==-2) {
						t += 108;
						break;
					}
					else
						cam_y = y - p*46 - 12;
				}
			}
			if (ctb[t]>='A'&&ctb[t]<='Z')
				digit_at (ctb[t], -6, -16, 4, blinkscolor - 12*(CLOCK()%6), 1);
			else {
				if (ctb[t]>='a'&&ctb[t]<='z')
					digit_at (ctb[t] - 32, -6, -16, 4, screencolor, 1);
				else
					digit_at (ctb[t], -6, -16, 4, screencolor, 1);
			}
		passby:	t++;
		}

	cam_x = x;
	cam_y = y;
}

/* Disegna la mappa di superficie al momento in cui si vuole sbarcare. */

void show_planetary_map ()
{
	char 	is_moon;
	Word 	lat, lon, i, j, p;

	if (nearstar_p_owner[ip_targetted] > -1)
		is_moon = 1;
	else
		is_moon = 0;

	lon = landing_pt_lon - 22;
	for (i = 0; i < 48; i++) {
		while (lon > 359) lon -= 360;
		while (lon <   0) lon += 360;
		lat = landing_pt_lat - 14;
		for (j = 0; j < 32; j++) {
			p = ((j + 9) << 8) + i + 14;
			if (lat > 0 && lat < 120) {
				ptr = lat * 360 + lon;
				if (is_moon)
					p_surfacemap[p] = s_background[ptr] + 128;
				else
					p_surfacemap[p] = p_background[ptr] + 192;
			}
			else
				p_surfacemap[p] = 4;
			lat++;
		}
		lon++;
	}
}

/* Disegna l'astrozattera. (Quella che si sta usando, vista dall'interno.)
   Assume anche il compito di decifrare i comandi da tastiera per GOESNet. */

Word goesk_a = -1;
Word goesk_e = -1;

void vehicle (float opencapcount)
{
	Word   n, c, i, j, k;
	FILEPTR screenfile;
	char  short_text[11];
	Uchar chcol;

	float backup_cam_x, backup_cam_z;
	float backup_beta = beta;
	float chry;

	float vx[4], vy[4], vz[4];
	float osscreen_x[4], osscreen_z[4];
	float osscreen_y[4] = { -20*15,  14*15,  14*15, -20*15 };

	//BUFFERCHECK
	if (elight) {
		FMEMSET (osscreen[0], 0, 7*21);
		FMEMSET (osscreen[1], 0, 7*21);
	}
	//BUFFERCHECK
	
	// Tracciamento delle cupole panoramiche.
	// Quando non si stanno chiudendo per formare la capsula.

	if (!opencapcount) {
		cam_z += 3100;
		cam_y -= 550;
		//BUFFERCHECK
		polycupola (0, 0);
		//BUFFERCHECK
		setfx(0); cupola (0, 8); resetfx();
		//BUFFERCHECK
		cam_y += 550;
		if (!ontheroof) {
			//BUFFERCHECK
			polycupola (+1, 0);
			//BUFFERCHECK
			setfx(0); cupola (+1, 8); resetfx();
			//BUFFERCHECK
		}
		cam_z -= 3100;
	}
	//BUFFERCHECK
	
	// Resto dello scafo.
	// Se si Š in terrazza, ci si ferma qui, dopo aver disegnato
	// la cupola superiore, che dev'essere sovraimpressa allo scafo.
	
	if (option_invis_sd) {
		
	} else if (depolarize) {
		//BUFFERCHECK
		setfx (2);
		//BUFFERCHECK
		drawpv (vehicle_handle, 2, 3, 0.0, 0.0, 0.0, 0);
		//BUFFERCHECK
		resetfx ();
		//BUFFERCHECK
	} else {
		//BUFFERCHECK
		drawpv (vehicle_handle, 2, 2, 0.0, 0.0, 0.0, 0);
		//BUFFERCHECK
	}
	if (ontheroof) {
		cam_z += 3100;
		BUFFERCHECK
		polycupola (+1, 0);
		BUFFERCHECK
		setfx(0);
		BUFFERCHECK
		cupola (+1, 8);
		BUFFERCHECK
		resetfx();
		BUFFERCHECK
		cam_z -= 3100;
		return;
	}
	// Intercettazione tasti (prioritaria) per GOESNet.

	if (force_update || (active_screen == 0 && tasto_premuto())) {
		if (!force_update) {
			BUFFERCHECK
			goesk_a = -1;
			c = attendi_pressione_tasto();
			if (!c) {
				c = attendi_pressione_tasto();
				goesk_e = c;
				if (c == 0x47) {	//home: 36/true
					goesnet_command[0] = '_';
					goesnet_command[1] = 0;
					gnc_pos = 0;
					goesk_e = -1;
				}
			}
			else {
				switch (c) {
				       case 27:	goesk_a = c; //escape	// passa la keystroke
						break;
				       case 8:  if (gnc_pos > 0) {	//backspace
							goesnet_command[gnc_pos - 1] = '_';
							goesnet_command[gnc_pos] = 0;
							gnc_pos--;
						}
						break;
				       case 13: RunCommand (NULL);	//enter
						n = 0;
						if (!memcmp (goesnet_command, "CAST", 4)) {
							i = 0;
							while (i < gnc_pos) {
								if (goesnet_command[i] == ':') {
									n = i + 1;
									goto reset_cli;
								}
								i++;
							}
						}
					   reset_cli:
						goesnet_command[n] = '_';
						goesnet_command[n+1] = 0;
						gnc_pos = n;
				}
				// trasformazione virgolette in apici:	//change " to '
				if (c == 34) c = 39;
				// trasformazione minuscole in maiuscole:		//lowercase to uppercase
				if (c >= 'a' && c <= 'z') c -= 32;
				// controllo caratteri non validi:
				if (c == 36) goto non_valido; // dollaro		//$
				if (c == 38) goto non_valido; // e commerciale	//%
				if (c == 60) goto non_valido; // minore			//<
				if (c == 62) goto non_valido; // maggiore		//>
				if (c == 95) goto valido;     // sottolinea		//_
				// inserimento caratteri validi:
				if (c >= 32 && c <= 90 && gnc_pos < 83) {		//!#^'()*+,-./:;=?@ and 0-9 and A-Z are treated as valid.
				    valido:
					goesnet_command[gnc_pos] = c;
					goesnet_command[gnc_pos+1] = '_';
					goesnet_command[gnc_pos+2] = 0;
					gnc_pos++;
				}
			    non_valido:
			    0;		//(FIX): Do nothing, to help DMC compile this.
			}
			BUFFERCHECK
	
		}
		BUFFERCHECK
		FMEMSET (osscreen[0]+3*21, 0, 4*21);
		BUFFERCHECK
		mslocate (0, 0, 3); mswrite (0, goesnet_command);
		BUFFERCHECK
	}

	// Intercettazione tasti (prioritaria) per lo schermo "STARMAP TREE".

	BUFFERCHECK
	if (force_update || (active_screen == 1 && tasto_premuto())) {
		if (!force_update) {
			krep1:
			BUFFERCHECK
			c = attendi_pressione_tasto();
			goesk_a = c;
			if (!c)	{
				goesk_a = -1;
				c = attendi_pressione_tasto();
				goesk_e = c;
				switch (c) {
				     case 0x4F:	//79	//end: 23/true in windows
				     case 0x76:	//118	//ctrl-pgdown
				     case 0x91: screenfile = OPENFILE (goesoutputfile, OPEN_RB);	//145	//Must be keypad *
						if (screenfile ISFILEVALID) {
							FILELENGTH(goesfile_pos, screenfile);
							
							goesfile_pos -= 7*21;
							if (goesfile_pos < 0) goesfile_pos = 0;
							CLOSEFILE (screenfile);
						}
						goesk_e = -1;
						break;
				     case 0x47:	//71	//Home	//24/true in windows
				     case 0x84:	//132	//ctrl-pgup
				     case 0x8D: goesfile_pos = 0;		//141		//not listed in conio.h
						goesk_e = -1;
						break;
				       case 80: goesfile_pos += 21;		//down arrow	//28/true in windows
						goesk_e = -1;
						break;
				       case 72: goesfile_pos -= 21;		//up arrow		//26/true in windows
						if (goesfile_pos < 0) goesfile_pos = 0;
						goesk_e = -1;
						break;
				       case 0x51: goesfile_pos += 21*7;			//pgdown: 34/true in windows
						goesk_e = -1;
						break;
				       case 0x49: goesfile_pos -= 21*7;			//pgup: 33/true in windows
						if (goesfile_pos < 0) goesfile_pos = 0;
						goesk_e = -1;
						break;
				}
			}
			BUFFERCHECK
			if (tasto_premuto()) goto krep1;
		}
		BUFFERCHECK
		FMEMSET (osscreen[1], 0, 21*7);
		BUFFERCHECK
		screenfile = OPENFILE (goesoutputfile, OPEN_RB);
		BUFFERCHECK
		if (screenfile ISFILEVALID) {
			FILESEEK (screenfile, goesfile_pos, SEEK_SET);
			#ifdef WINDOWS
			n = fread(osscreen[1], 1, 7*21, screenfile);
			#else
			n = READFILE (screenfile, osscreen[1], 7*21);
			#endif
			osscreen[1][n] = 0;
			CLOSEFILE(screenfile);
			BUFFERCHECK
		}
	}

	// Intercettazione tasti (prioritaria) per la planetary map.
	BUFFERCHECK
	
	if (active_screen == 2 && tasto_premuto()) {
		krep2:
		c = attendi_pressione_tasto();
		goesk_a = c;
		if (!c)	{
			goesk_a = -1;
			c = attendi_pressione_tasto();
			goesk_e = c;
			if (landing_point) {
				switch (c) {
				       case 77: landing_pt_lon++;			//right arrow	//27/true
						if (landing_pt_lon >= 360) landing_pt_lon -= 360;
						goesk_e = -1;
						break;
				       case 75: landing_pt_lon--;			//left arrow	//25/true
						if (landing_pt_lon < 0) landing_pt_lon += 360;
						goesk_e = -1;
						break;
				       case 80: landing_pt_lat++;			//down arrow
						if (landing_pt_lat > 119) landing_pt_lat = 119;
						goesk_e = -1;
						break;
				       case 72: landing_pt_lat--;			//up arrow
						if (landing_pt_lat < 1) landing_pt_lat = 1;
						goesk_e = -1;
						break;
				     case 0x74: landing_pt_lon += 3;		//ctrl-right
						if (landing_pt_lon >= 360) landing_pt_lon -= 360;
						goesk_e = -1;
						break;
				     case 0x73: landing_pt_lon -= 3;		//ctrl-left
						if (landing_pt_lon < 0) landing_pt_lon += 360;
						goesk_e = -1;
						break;
				     case 0x91: landing_pt_lat += 3;		//145: unknown	//ctrl-down?
						if (landing_pt_lat > 119) landing_pt_lat = 119;
						goesk_e = -1;
						break;
				     case 0x8D: landing_pt_lat -= 3;		//141: unknown	//ctrl-up?
						if (landing_pt_lat < 1) landing_pt_lat = 1;
						goesk_e = -1;
				}
			}
			//if (goesk_e==-1) npcs=-12345; resident_map1=-1; resident_map2=-1;	//TEMPORARY (For testing albedo changes - this forces the recalculation of the albedo etc whenever a key is pressed (if the surface-map is open)) (SL)
		}
		else {
			if (landing_point) {
				if (c == 13) {
					land_now = 1;
					goesk_a = -1;
				}
				if (c == 27) {
					landing_point = 0;
					status ("CANCELLED", 50);
					goesk_a = -1;
				}
				/* Unit… di debugging dell'albedo
				Uchar maybefar *ov=(Uchar maybefar*)objectschart;
				if (c == 'b') {
					ov[(18 + 60*360) / 2] += 4;
					p_background[18 + 60*360] ++;
				}
				if (c == 'd') {
					ov[(18 + 60*360) / 2] -= 4;
					p_background[18 + 60*360] --;
				}*/
			}
		}
		if (tasto_premuto()) goto krep2;
	}
	BUFFERCHECK

	if ((active_screen == 0 || active_screen == 1) && blinkhudlights == 1) {		//turn lights off if you look at the outpud HUD and they're on.
		blinkhudlights = 0;
	}

	// Tracciamento degli schermi di GOESNet.
	// Si tratta dei primi due schermi sulla paratia destra.

	H_MATRIXS = 6; V_MATRIXS = 3;
	BUFFERCHECK
	change_txm_repeating_mode ();
	BUFFERCHECK
	txtr = p_surfacemap + 256 * 8 + 16;

	BUFFERCHECK
	osscreen_z[0] = -104*15;
	osscreen_z[1] = -104*15;
	osscreen_z[2] = -154*15;
	osscreen_z[3] = -154*15;
	osscreen_x[0] = +236*15;
	osscreen_x[1] = +236*15;
	osscreen_x[2] = +236*15;
	osscreen_x[3] = +236*15;
	BUFFERCHECK
	
	vx[0] = 236*15; vx[1] = 236*15; vx[2] = 236*15; vx[3] = 236*15;
	vy[0] = -22*15; vy[1] = -23*15; vy[2] = -23*15; vy[3] = -22*15;
	vz[0] =-104*15; vz[1] =-104*15; vz[2] =-108*15; vz[3] =-108*15;
	BUFFERCHECK
	
	n = 0; while (n < 2) {
		BUFFERCHECK
		poly3d (osscreen_x, osscreen_y, osscreen_z, 4, 68);
		BUFFERCHECK
		beta += 90; if (beta > 359) beta -= 360;
		change_angle_of_view ();
		BUFFERCHECK
		backup_cam_x = cam_x;
		backup_cam_z = cam_z;
		cam_z = backup_cam_x - 236*15;
		chry = -18*15;
		chcol = 152;
		k = 0;
		for (j = 0; j < 7; j++) {
			cam_x = - backup_cam_z - 105*15;
			for (i = 0; i < 21; i++) {
				c = osscreen[n][k + i];
				if (c > 48 && c < 91)
					digit_at (c, 0, chry, 5.5, chcol, 0);
				else {
					if (c == '(') chcol = 191;
					if (c != '$' && c != '[' && c != ']'
					 && c != '*' && c != '&' && c != '_')
						digit_at (c, 0, chry, 5.5, chcol, 0);
					else
						digit_at (c, 0, chry, 6.5, 138, 0);
					if (c == ')') chcol = 152;
				}
				cam_x -= 2.35*15;
			}
			k += 21;
			chry += 4.5*15;
		}
		BUFFERCHECK
		cam_x = backup_cam_x;
		cam_z = backup_cam_z;
		beta = backup_beta;
		change_angle_of_view ();
		BUFFERCHECK
		if (n == active_screen)
			poly3d (vx, vy, vz, 4, 63);
		else
			poly3d (vx, vy, vz, 4, 00);
		BUFFERCHECK
		cam_z += 54 * 15;
		n++;
	}

	// Tracciamento della mappa planetaria.
	// Dopo gli schermi di GOES.

	H_MATRIXS = 3; V_MATRIXS = 2;
	BUFFERCHECK
	change_txm_repeating_mode ();
	BUFFERCHECK
	
	if (landing_point) {
		BUFFERCHECK
		show_planetary_map ();
		BUFFERCHECK
		polymap (osscreen_x, osscreen_y, osscreen_z, 4, 0);
		BUFFERCHECK
		if (nearstar_p_type[ip_targetted]==3 && terrainFilter==1) {
			char 	is_moon;
			if (nearstar_p_owner[ip_targetted] > -1)
				is_moon = 1;
			else
				is_moon = 0;
			char sctype;
			if (is_moon)
				sctype = s_background[landing_pt_lat*360+landing_pt_lon] - 8;
			else
				sctype = p_background[landing_pt_lat*360+landing_pt_lon] - 8;
			char nsctype = OCEAN;
			switch (sctype) {
				case 1:
					nsctype=OCEAN;
					break;
				case 2:
					nsctype=FOREST;
					break;
				case 3:
					nsctype=PLAINS;
					break;
				case 4:
					nsctype=SHRUBLAND;
					break;
				case 5:
					nsctype=DESERT;
					break;
				case 6:
					nsctype=ICY;
					break;
			}
			BUFFERCHECK
			WriteTerrainType(nsctype, True);
			sprintf(outhudbuffer, "z%s LQ %03d:%03d", terrainTypeBuffer, landing_pt_lon, landing_pt_lat);
			status(outhudbuffer, 10);
		} else {
			sprintf (short_text, "T%i LQ %03d:%03d", (int) (nearstar_p_type[ip_targetted]), landing_pt_lon, landing_pt_lat);
			status (short_text, 10);
		}
	} else {
		BUFFERCHECK
		poly3d (osscreen_x, osscreen_y, osscreen_z, 4, 4);
		BUFFERCHECK
	}

	#define surface_crosshair_x_shift	+25
	#define surface_crosshair_y_shift	-10
	#define surface_crosshair_x_spacing	+11
	#define surface_crosshair_y_spacing	+10

	BUFFERCHECK
	setfx (2);
	stick3d (osscreen_x[0], osscreen_y[0], osscreen_z[0] - 27 * 15 - surface_crosshair_x_spacing + surface_crosshair_x_shift,
		 osscreen_x[0], osscreen_y[1], osscreen_z[0] - 27 * 15 - surface_crosshair_x_spacing + surface_crosshair_x_shift);
	stick3d (osscreen_x[0], osscreen_y[0], osscreen_z[0] - 27 * 15 + surface_crosshair_x_spacing + surface_crosshair_x_shift,
		 osscreen_x[0], osscreen_y[1], osscreen_z[0] - 27 * 15 + surface_crosshair_x_spacing + surface_crosshair_x_shift);
	stick3d (osscreen_x[0], osscreen_y[0] + 17 * 15 - surface_crosshair_y_spacing + surface_crosshair_y_shift, osscreen_z[0],
		 osscreen_x[0], osscreen_y[0] + 17 * 15 - surface_crosshair_y_spacing + surface_crosshair_y_shift, osscreen_z[2]);
	stick3d (osscreen_x[0], osscreen_y[0] + 17 * 15 + surface_crosshair_y_spacing + surface_crosshair_y_shift, osscreen_z[0],
		 osscreen_x[0], osscreen_y[0] + 17 * 15 + surface_crosshair_y_spacing + surface_crosshair_y_shift, osscreen_z[2]);
	resetfx();
	BUFFERCHECK
	
	if (active_screen == 2)
		poly3d (vx, vy, vz, 4, 63);
	else
		poly3d (vx, vy, vz, 4, 00);
	BUFFERCHECK
	
	// Fine tracciamento schermi.

	cam_z -= 2 * 54 * 15;
	txtr = p_background;
	if (force_update) force_update = 0;

	// Tracciamento della lampada interna.

        #ifdef intlightnewposition
	 cam_x -= 0;
	 cam_y +=  -500;
	 cam_z +=  3100;
	 alogena ();
	 cam_x += 0;
	 cam_y -=  -500;
	 cam_z -=  3100;
	 BUFFERCHECK
	#endif

	#ifndef intlightnewposition
	 cam_x -= 3395;
	 cam_y +=  480;
	 cam_z +=  200;
	 alogena ();
	 cam_x += 3395;
	 cam_y -=  480;
	 cam_z -=  200;
	#endif
	
	// Tracciamento delle cupole panoramiche.
	// Quando si stanno chiudendo per formare la capsula.

	BUFFERCHECK
	if (opencapcount) {
		chry = cam_y;
		cam_z += 3100;
		cam_y = chry + opencapcount * 9.55 - 550;
		BUFFERCHECK
		polycupola (-opencapcount/85, 0);
		BUFFERCHECK
		setfx(0); cupola (-opencapcount/85, 8); resetfx();
		BUFFERCHECK
		cam_y = chry - opencapcount * 9.55;
		if (!ontheroof) {
			BUFFERCHECK
			polycupola (+1, 0);
			BUFFERCHECK
			setfx(0); cupola (+1, 8); resetfx();
			BUFFERCHECK
		}
		cam_z -= 3100;
		cam_y = chry;
	}
	BUFFERCHECK
	
}

/* Disegna un'astrozattera, vista dall'esterno. */

void other_vehicle_at (double ovhx, double ovhy, double ovhz)
{
	cam_x = - ovhx;
	cam_y = - ovhy;
	cam_z = - ovhz;

	cam_z += 3100;
	setfx (2);
	if (ovhy>-375) cupola (+1, 8);
	if (ovhy<+375) cupola (-1, 8);
	resetfx ();
	cam_z -= 3100;

	cam_x = 0;
	cam_y = 0;
	cam_z = 0;

	drawpv (vehicle_handle, 0, 0, ovhx, ovhy, ovhz, 1);

	cam_x = - ovhx;
	cam_y = - ovhy;
	cam_z = - ovhz;

	cam_z += 3100;
	setfx (2);
	if (ovhy>+375) cupola (+1, 8);
	if (ovhy<-375) cupola (-1, 8);
	resetfx ();
	cam_z -= 3100;

	lens_flares_for (cam_x, cam_y, cam_z, 3225, 0, 0, -5e5, 3, 1, 1, 1, 1);
	lens_flares_for (cam_x, cam_y, cam_z, -3225, 0, 0, -5e5, 3, 1, 1, 1, 1);
	lens_flares_for (cam_x, cam_y, cam_z, 3225, 0, -6150, -5e5, 3, 1, 1, 1, 1);
	lens_flares_for (cam_x, cam_y, cam_z, -3225, 0, -6150, -5e5, 3, 1, 1, 1, 1);
}


/* Fine roba importata da noctis-0.cpp */

/* Variabili globali di uso generico. */

Uchar maybefar * ctrlkeys     = (Uchar maybefar *) 0x00000417;

char   aso_countdown = 100;	// contatore per la funzione "autoscreenoff"
Dword   tgt_label_pos = -1;	// posizione etichetta target selezionato
Word    tgts_in_show = 0;	// targets correntemente visualizzati

/* Dati gestione cartografia. */

char   targets_in_range = 0;
char   lightscale = 0;
char   lightscale2 = 0;
#ifdef OLD_STARMAP
Dword   sm_consolidated  = 0;
#endif

char   target_name[4][24];

char   iptargetstring[11];
char   iptargetchar = 0;
char   iptargetplanet;
char   iptargetmoon;

double ap_target_id = 12345, ap_target_previd = 54321;
double current_planet_id = 12345, prev_planet_id = 54321;
char   labstar = 0, labplanet = 0, labstar_char = 0, labplanet_char = 0;
Dword   star_label_pos = -1, planet_label_pos = -1;

double star_id = 12345;
char   star_label[25] = "UNKNOWN STAR / CLASS ...";
char   star_no_label[25] = "UNKNOWN STAR / CLASS ...";

double planet_id = 12345;
char   planet_label[25] = "NAMELESS PLANET / N. ...";
char   planet_no_label[25] = "NAMELESS PLANET / N. ...";
char   moon_no_label[25] =   "NAMELESS MOON #../../...";
#define sunp_no_label "NAMELESS SUN    / N. ..."
#define sunm_no_label "NAMELESS SUN  #.. /../..."
char   *sr_message = "SYSTEM RESET";

void update_star_label ()
{
	if (ap_targetted == -1)
		strcpy (star_label, "- DIRECT PARSIS TARGET -");
	else {
		ap_target_id = ap_target_x / 100000 * ap_target_y / 100000 * ap_target_z / 100000;
		if (ap_target_id != ap_target_previd) {
			ap_target_previd = ap_target_id;
			#ifdef OLD_STARMAP
			star_label_pos = search_id_code (ap_target_id, 'S');
			if (star_label_pos != -1) {
				smh = OPENFILE (starmap_file, OPEN_RB);
				FILESEEK (smh, star_label_pos, SEEK_SET);
				READFILE (smh, &star_id, 32);
				CLOSEFILE (smh);
			}
			#else
			if (ap_target_sx==0x7FFFFFFF && ap_target_sy==0x7FFFFFFF && ap_target_sz==0x7FFFFFFF) {
				//Sector coords unknown; find them!
				Dword retval = getSectorCoords(ap_target_x, ap_target_y, ap_target_z, &ap_target_sx, &ap_target_sy, &ap_target_sz);				
				if (retval==-1) {
					status ("ACK! CAN'T FIND SYSTEM", 200);
				} else if (retval==-2) {
					enableR9aBugMessage();
				}
			}
			#ifdef WINDOWS
			star_label_pos = system_labelled (ap_target_sx, ap_target_sy, ap_target_sz, current_galaxy);
			#else
			star_label_pos = system_labelled (ap_target_sx, ap_target_sy, ap_target_sz);
			#endif
			if (star_label_pos > 0) {
				star_id = ap_target_id;
				#ifdef WINDOWS
				FILE * tmpFile;
				if (current_galaxy==0) {
					tmpFile = fopen(starmap3_file, "rb");
				} else {
					tmpFile = fopen(starmap3b_file, "rb");
				}
				#else
				FILE * tmpFile = fopen(starmap3_file, "rb");
				#endif
				fseek(tmpFile, star_label_pos+5, SEEK_SET);
				fread(star_label, 20, 1, tmpFile);
				star_label[20]=' ';
				fclose(tmpFile);
			}
			#endif
			else
				memcpy (star_label, star_no_label, 24);
			SRAND (ap_target_id); sprintf (star_label+21, "S%02d", RANDOM (star_classes));
		}
	}
}

void update_planet_label ()
{
	current_planet_id = nearstar_identity + ip_targetted + 1;
	if (current_planet_id != prev_planet_id) {
		prev_planet_id = current_planet_id;
		#ifdef OLD_STARMAP
		planet_label_pos = search_id_code (current_planet_id, 'P');
		if (planet_label_pos != -1) {
			smh = OPENFILE (starmap_file, OPEN_RB);
			FILESEEK (smh, planet_label_pos, SEEK_SET);
			READFILE (smh, &planet_id, 32);
			CLOSEFILE (smh);
		}
		else {
			if (nearstar_p_owner[ip_targetted] == -1)
				if (nearstar_p_type[ip_targetted]==10) {
					memcpy (planet_label, sunp_no_label, 24);
				} else {
					memcpy (planet_label, planet_no_label, 24);
				}
			else {
				if (nearstar_p_type[ip_targetted]==10) {
					memcpy (planet_label, sunm_no_label, 24);
				} else {
					memcpy (planet_label, moon_no_label, 24);
				}
				sprintf (planet_label+15, "%02d", nearstar_p_moonid[ip_targetted] + 1);
				sprintf (planet_label+18, "%02d", nearstar_p_owner[ip_targetted] + 1);
				planet_label[17] = '/';
				planet_label[20] = '&';
			}
		}
		#else
		#ifdef WINDOWS
		Udword tgt_starFP = system_labelled(nearstar_sx, nearstar_sy, nearstar_sz, current_galaxy);
		planet_label_pos = planet_labelled (tgt_starFP, ip_targetted, nearstar_p_owner[ip_targetted], nearstar_p_moonid[ip_targetted], nearstar_p_type[ip_targetted], False, current_galaxy);
		#else
		Udword tgt_starFP = system_labelled(nearstar_sx, nearstar_sy, nearstar_sz);
		planet_label_pos = planet_labelled (tgt_starFP, ip_targetted, nearstar_p_owner[ip_targetted], nearstar_p_moonid[ip_targetted], nearstar_p_type[ip_targetted], False);
		#endif
		if (planet_label_pos > 0) {
			planet_id = current_planet_id;
			#ifdef WINDOWS
			FILE * tmpFile;
			if (current_galaxy==0) {
				tmpFile = fopen(starmap3_file, "rb");
			} else {
				tmpFile = fopen(starmap3b_file, "rb");
			}
			#else
			FILE * tmpFile = fopen(starmap3_file, "rb");
			#endif
			fseek(tmpFile, planet_label_pos+5, SEEK_SET);
			fread(planet_label, 20, 1, tmpFile);
			fclose(tmpFile);
			planet_label[20]=' ';
			/*
			//This makes the names rather short, so it's disabled now.(SL)
			//This puts the moon and orbiting numbers back into the displayed name of named planets. (SL)
			if (nearstar_p_owner[ip_targetted] != -1) {
				sprintf (planet_label+15, "%02d", nearstar_p_moonid[ip_targetted] + 1);
				sprintf (planet_label+18, "%02d", nearstar_p_owner[ip_targetted] + 1);
				planet_label[16] = '#';
				planet_label[17] = '/';
				planet_label[20] = '&';
			}
			*/
		} else {
			if (nearstar_p_owner[ip_targetted] == -1) {
				if (nearstar_p_type[ip_targetted]==10) {
					memcpy (planet_label, sunp_no_label, 24);
				} else {
					memcpy (planet_label, planet_no_label, 24);
				}
			} else {
				if (nearstar_p_type[ip_targetted]==10) {
					memcpy (planet_label, sunm_no_label, 24);
				} else {
					memcpy (planet_label, moon_no_label, 24);
				}
				sprintf (planet_label+15, "%02d", nearstar_p_moonid[ip_targetted] + 1);
				sprintf (planet_label+18, "%02d", nearstar_p_owner[ip_targetted] + 1);
				planet_label[17] = '/';
				planet_label[20] = '&';
			}
		}
		#endif
		sprintf (planet_label+21, "P%02d", ip_targetted + 1);
	}
}

/* Controllo di volo (Flight Control System). */

void fcs ()
{
	Word n;

	if (ip_targetted != -1) {
		cline (1, "local target: ");
		if (nearstar_p_owner[ip_targetted] > -1) {
			other ("moon #");
			other (alphavalue(nearstar_p_moonid[ip_targetted] + 1));
			other (" of ");
			n = nearstar_p_owner[ip_targetted];
		}
		else
			n = ip_targetted;
		other (ord[n + 1]);
		other (" planet. ");
		other (planet_description[nearstar_p_type[ip_targetted]]);
	}

	if (ap_targetted) {
		if (ap_targetted == 1) {
			cline (2, "remote target: class ");
			other (alphavalue(ap_target_class));
			other (" star; ");
			other (star_description[ap_target_class]);
		}
		else
			cline (2, "direct parsis target: non-star type.");
	}
	else
		cline (2, "no remote target selected");

	cline (3, "current range: elapsed ");
	xx = (float) pwr - 15000; if (xx<0) xx = 0;
	other (alphavalue(xx));
	other (" kilodyams, remaining lithium: ");
	if (charge > -1) { 
          other (alphavalue(charge));
          other (" grams.");
        } else { 
          other (" INFINITE (omega drive)");
        }

	
	#ifdef WINDOWS
	if (current_galaxy==0) {
		cline (4, "feltyrion galaxy");
	} else {
		cline (4, "new galaxy");
	}
	#endif
	
	command (1, "set remote target");

	if (stspeed)
		command (2, "stop vimana flight");
	else
		command (2, "start vimana flight");

	if (landing_point)
		command (4, "cancel landing request");
	else
		command (4, "deploy surface capsule");

	if (ip_targetted==-1||ip_reached)
		command (3, "set local target");
	else {
		if (ip_reaching)
			command (3, "stop fine approach");
		else {
			command (3, "start fine approach");
			command (4, "clear local target");
		}
	}
}

/* Comandi dell'FCS. */

void fcs_commands ()
{
	switch (s_command) {
		case 1: if (stspeed || manual_target) {	//set remote target
				status ("CONFLICT", 50);
				break;
			}
			status ("TGT-REMOTE", 50);
			landing_point = 0;	//FIXED the 'I can land on unlandable objects if I start the landing request on a landable one and change target before landing!' bug (SL)
			if (opencapdelta>0) {	//FIXED changing target while landing (SL)
				status ("CANCELLED LANDING", 100);
				opencapdelta=-2;
			}
			ap_targetting = 1;
			ap_targetted = 0;
			break;
		case 2:		//start vimana
			landing_point = 0;	//FIXED the 'I can land on unlandable objects if I start the landing request on a landable one and change target before landing!' bug (SL)
			if (opencapdelta>0) {	//FIXED changing target while landing (SL)
				status ("CANCELLED LANDING", 100);
				opencapdelta=-2;
			}
			if (stspeed) {
				if (ip_vimana>0) {
					if (ip_reaching) {
						status ("IDLE", 50);
						ip_targetted = -1;
						ip_reaching = 0;
						ip_reached = 1;
					}
				} else {
					stspeed = 0;
					status ("IDLE", 50);
				}
			}
			else {
				if (lithium_collector || manual_target) {
					status ("CONFLICT", 50);
					break;
				}
				if (pwr > 15000) {
					if (nearstar_x == ap_target_x && nearstar_y == ap_target_y && nearstar_z == ap_target_z && ip_targetted>=0 && !ip_reached && ip_reaching) {
						ip_vimana=2;
					} else {
						if (ap_targetted) {
							nsnp = 1;
							ap_reached = 0;
							ip_reached = 0;
							ip_targetted = -1;
							ip_reaching = 0;
						}
						stspeed = 1;
					}
				}
			}
			
			break;
		case 3: if (ip_reached||ip_targetted==-1) {	//set local target
				landing_point = 0;	//FIXED the 'I can land on unlandable objects if I start the landing request on a landable one and change target before landing!' bug (SL)
				if (opencapdelta>0) {	//FIXED changing target while landing (SL)
					status ("CANCELLED LANDING", 100);
					opencapdelta=-2;
				}
				if (ap_reached) {
					//FIXED the 'shaking screen when you try to select local target' bug (SL)
					if (nearstar_nop==0) {
						status ("NO PLANETS", 100);
					} else {
						ip_targetted = -1;
						ip_targetting = 1;
						ip_reaching = 0;
						if (ip_vimana) {
							ip_vimana=0;
							stspeed=0;
						}
						ip_reached = 0;
						iptargetchar = 0;
					}
				}
				else
					status ("NEED RECAL", 75);
			}
			else {
				if (ip_reaching) {
					status ("IDLE", 50);
					ip_targetted = -1;
					ip_reaching = 0;
					ip_reached = 1;
				}
				else {
					if (pwr > 15000) {
						ip_reaching = 1;
						status ("CONFIRM", 50);
					}
				}
			}
			break;
		case 4: if (!ip_reaching&&ip_targetted!=-1) {
				if (!ip_reached) {
					ip_targetted = -1;
					status ("TGT REJECT", 50);
				}
				else {
					//get distance
					planet_xyz (ip_targetted);
					double dxx = dzat_x - plx;
					double dyy = dzat_y - ply;
					double dzz = dzat_z - plz;
					double l_dsd = SQRT (dxx*dxx + dyy*dyy + dzz*dzz);
					//status ("DIST", 500);
					//sprintf(fcs_status_extended, "DIST %0.6f", l_dsd);
					if (l_dsd<1) {
						landing_point = 1 - landing_point;
						if (landing_point) {
							#ifdef WINDOWS
							if (nearstar_p_type[ip_targetted]==planet_types+1) {
								status ("ZORT", 50);
								SwitchGalaxy();
								landing_point = 0;
							} else 
							#endif
							if (nearstar_p_type[ip_targetted] == 6
							  //||nearstar_p_type[ip_targetted] == 0
							  ||nearstar_p_type[ip_targetted] >= 9) {
								status ("IMPOSSIBLE", 50);
								landing_point = 0;
							} else {
								status ("SURFACE", 50);
								landing_pt_lon = 0;
								landing_pt_lat = 60;
							}
						}
						else
							status ("IDLE", 50);
					} else {
						status ("GET CLOSER FIRST", 50);
						//sprintf(fcs_status_extended, "TOO FAR %0.6f", l_dsd);
					}
				}
			}
			else
				status ("ERROR", 50);
	}
}

//New commands menu
void extended ()
{
	switch (dev_page) {
		case 0:
			command (1, "Options");
			command (2, "More Options");
			command (3, "Navigational Help");
			command (4, "Visual Options");
			cline (3, "SELECT ARGUMENT");
			break;
		case 1:
			command (1, "Speedup");
			switch (option_speedup) {
				case 0:
					cline (1, "Speedup is disabled");
					break;
				case 1:
					cline(1, "Speedup is enabled on the roof only");
					break;
				case 2:
					cline(1, "Speedup is enabled in the SD and on the roof");
					break;
				
			}
			command (2, "Temperature");
			switch (option_temperature) {
				case 0:
					cline(2, "Old temperature model");
					break;
				case 1:
					cline(2, "New temperature model");
					break;
				case 2:
					cline(2, "Simple temperature model");
					break;
				
			}
			command (3, "Temperature Units");
			switch (option_temperature_units) {
				case 0:
					command(3, "Celsius");
					break;
				case 1:
					command(3, "Kelvin");
					break;
				case 2:
					command(3, "Fahrenheit");
					break;
			}
			command (4, "Flying Lander");
			if (option_flying_lander) {
				command(4, "Flying Lander");
			} else {
				command(4, "Original Lander");
			}
			break;
		case 2:
			command (1, "Moving sun");
			if (option_change_over_time) {
				cline (1, "You can see the sun(s) moving on the planet surface, and can see sunsets and sunrises.");
			} else {
				cline (1, "On planet surfaces, the sun won't move and you won't see sunsets or sunrises.");
			}
			command (2, "Mouselook");
			if (option_mouseLook==1) {
				cline (2, "Mouselook on planet surfaces is on.");
			} else if (option_mouseLook==2) {
				cline (2, "Mouselook on planet surfaces is on, and the Y axis is inverted.");
			} else {
				cline (2, "Mouselook on planet surfaces is off.");
			}
			command (3, "Controlset");
			if (option_controlset==1) {
				cline (3, "controlset is set to NOCTIS IV CE styled 1/2/3/4/5");
			} else {
				cline (3, "controlset is set to NOCTIS IV styled 5/r/d/x/4");
			}
			if (charge > -1) {
                          command (4, "Install OMEGA Drive");
                          cline (4, "OMEGA Drive is not installed");
                        } else {
                          command (4, "Remove OMEGA Drive");
                          cline (4, "OMEGA Drive is installed");
                        }
			/*command (2, "Terrain Types");
			if (option_newTerrainAlgorithms) {
				cline (2, "The new terrain-types and terrain distribution is selected.");
			} else {
				cline (2, "The original terrain-types and terrain distribution is selected.");
			}*/
			//MULTIPLAYER_DISABLED (This comment exists to make it is to find all the code that need to be reenabled to reenable multiplayer) (SL)
			/*
			command (2, "Multiplayer");
			if (option_multiplayer) {
				cline (2, "Multiplayer probably doesn't work yet, but you've enabled it anyways.");
			} else {
				cline (2, "Multiplayer is disabled - It probably doesn't work yet anyways.");
			}*/
			
			break;
		case 3:
			command (1, "Center/Outer ring Pointer");
			command (2, "X-axis Pointer");
			command (3, "Y-axis Pointer");
			command (4, "Z-axis Pointer");
			break;
		case 4:
			command (1, "Antialiasing in SD");
			command (2, "Invis SD");
			command (3, "3D Brackets");
			if (option_invis_sd) {
				cline (2, "The SD is mostly invisible.");
			} else {
				cline (2, "The SD is not invisible.");
			}
			if (option_3dbrackets) {
				cline (3, "Brackets on nearby creatures are 3d.");
			} else {
				cline (3, "Brackets on nearby creatures are not 3d.");
			}
			
			
	}
	
}

void extended_commands()
{
	switch (dev_page) {
		case 0:
			dev_page = s_command;
			switch (s_command) {
				case 1: status ("OPTIONS", 50); break;
			}
			break;
		case 1:
			switch (s_command) {
				case 1: option_speedup++;
					if (option_speedup>2) option_speedup=0;
					switch (option_speedup) {
						case 0:
							status ("DISABLED", 50);
							break;
						case 1:
							status ("ON ROOF", 50);
							break;
						case 2:
							status ("EVERYWHERE", 50);
							break;
					}
					break;
				case 2: option_temperature=1-option_temperature;
					if (option_temperature==1) {
						#if defined(ALL) || defined(TEMPERATURE)
						status ("NEW", 50);
						#else
						status ("NEW", 200);
						//status ("RESTARTING", 50);
						restart=1;
						#endif
					//} else if (option_temperature==2) {
					//	status ("SIMPLE", 50);
					} else {
						#if defined(ALL) || !defined(TEMPERATURE)
						status ("OLD", 50);
						#else
						status ("OLD", 200);
						//status ("RESTARTING", 50);
						restart=1;
						#endif
					}
					nearstar_mass = -1;
					nearstar_surfaceTemperature = -1;
					nearstar_temperatureTransmission =-1;

					break;
				case 3: option_temperature_units++;
					if (option_temperature_units>2) option_temperature_units=0;
					switch (option_temperature_units) {
						case 0:
							status ("CELSIUS", 50);
							break;
						case 1:
							status ("KELVIN", 50);
							break;
						case 2:
							status ("FAHRENHEIT", 50);
							break;
					}
					break;
				case 4: option_flying_lander=1-option_flying_lander;
					if (option_flying_lander) {
						#if defined(ALL) || defined(FLYING_LANDER)
						status ("ENABLED", 50);
						#else
						status ("ENABLED", 200);
						//status ("RESTARTING", 50);
						restart=1;
						#endif
					} else {
						#if defined(ALL) || !defined(FLYING_LANDER)
						status ("DISABLED", 50);
						#else
						status ("DISABLED", 200);
						//status ("RESTARTING", 50);
						restart=1;
						#endif
					}
					break;
			}
			break;
		case 2:
			switch (s_command) {
				case 1:
					option_change_over_time=1-option_change_over_time;
					if (option_change_over_time) {
						status ("ENABLED", 50);
					} else {
						status ("DISABLED", 50);
					}
					break;
				case 2:
					option_mouseLook++;
					if (option_mouseLook>2) option_mouseLook=0;
					if (option_mouseLook==1) {
						status ("NOW NORMALLY ON ON PLANETS", 50);
					} else if (option_mouseLook==2) {
						status ("INVERTED Y AXIS FOR MOUSELOOK", 50);
					} else {
						status ("NOW NORMALLY OFF ON PLANETS", 50);
					}
					break;
				case 3:
					option_controlset=1-option_controlset;
					if (option_controlset) {
						status ("NICE - 1/2/3/4/5", 50);
					} else {
						status ("NIV  - 5/R/D/X/4", 50);
					}
					break;
				case 4:
				        if (charge > -1) {
                                          charge = -2;
                                          status ("INSTALLED OMEGA DRIVE", 50);
                                        } else {
                                          charge = 3;
                                          status ("REMOVED OMEGA DRIVE", 50);
                                        }
				        break;
				/*case 2:
					option_newTerrainAlgorithms=1-option_newTerrainAlgorithms;
					if (option_newTerrainAlgorithms) {
						status ("NEW", 50);
					} else {
						status ("ORIGINAL", 50);
					}
					break;*/
				//MULTIPLAYER_DISABLED (This comment exists to make it is to find all the code that need to be reenabled to reenable multiplayer) (SL)
				/*case 2:
					option_multiplayer=1-option_multiplayer;
					if (option_multiplayer) {
						#if defined(ALL) || defined(MULTIPLAYER)
						status ("ENABLED", 50);
						SendInfo();
						SendRequestInfo();
						RequestServerTime();
						#else
						status ("ENABLED", 200);
						//status ("RESTARTING", 50);
						restart=1;
						#endif
					} else {
						timeAdjustment=0;
						#if defined(ALL) || !defined(MULTIPLAYER)
						status ("DISABLED", 50);
						#else
						status ("DISABLED", 200);
						//status ("RESTARTING", 50);
						restart=1;
						#endif
					}
					break;
				*/
			}
			break;
		case 3:
			switch (s_command) {
				case 1:
					option_center_outerring_pointer=1-option_center_outerring_pointer;
					if (option_center_outerring_pointer){
						status ("ENABLED", 50);
					} else {
						status ("DISABLED", 50);
					}
					break;
				case 2:
					option_x_axis_pointer=1-option_x_axis_pointer;
					if (option_x_axis_pointer){
						status ("ENABLED", 50);
					} else {
						status ("DISABLED", 50);
					}
					break;
				case 3:
					option_y_axis_pointer=1-option_y_axis_pointer;
					if (option_y_axis_pointer){
						status ("ENABLED", 50);
					} else {
						status ("DISABLED", 50);
					}
					break;
				case 4:
					option_z_axis_pointer=1-option_z_axis_pointer;
					if (option_z_axis_pointer){
						status ("ENABLED", 50);
					} else {
						status ("DISABLED", 50);
					}
					break;
			}
			break;
		case 4:
			switch (s_command) {
				case 1:
					option_antialias_in_stardrifter=1-option_antialias_in_stardrifter;
					if (option_antialias_in_stardrifter) {
						status ("ENABLED", 50);
					} else {
						status ("DISABLED", 50);
					}
					break;
				case 2:
					option_invis_sd=1-option_invis_sd;
					if (option_invis_sd) {
						status ("INVISIBLE", 50);
					} else {
						status ("VISIBLE", 50);
					}
					break;
				case 3:
					option_3dbrackets=1-option_3dbrackets;
					if (option_3dbrackets) {
						status("3D BRACKETS ON", 50);
					} else {
						status("3D BRACKETS OFF", 50);
					}
					break;
			}
	}
}

/* Dispositivi di bordo: men— principale e quattro sottomen—. */

void devices ()
{
	double 	parsis_x, parsis_y, parsis_z;
	Word 	n, sp;
	Dword 	lsecs;

	switch (dev_page) {
		case 0: // sub menu
			command (1, "navigation instruments");
			command (2, "miscellaneous");
			command (3, "galactic cartography");
			command (4, "emergency functions");
			cline (3, "SELECT ARGUMENT");
			break;
		case 1: // navigation status
			if (field_amplificator) {
				command (1, "STARFIELD AMPLIFICATOR");
				cline (1, "starfield amplification active, ");
			}
			else {
				command (1, "starfield amplificator");
				cline (1, "starfield amplification disabled, ");
			}
			if (anti_rad) {
				command (4, "FORCE RADIATIONS LIMIT");
				other ("high-radiation fields are avoided.");
			}
			else {
				command (4, "force radiations limit");
				other ("high-radiation fields are ignored.");
			}
			if (sync) {
				if (ip_targetted!=-1 && ip_reached) {
					sp = 0;
					for (n = 0; n < ip_targetted; n++) {
						if (nearstar_p_type[n] != -1)
							sp++;
					}
					cline (2, "tracking status: performing ");
					if (sync==1) {
						other ("fixed-point chase.");
						command (3, "fixed-point chase");
					}
					if (sync==2) {
						other ("far chase.");
						command (3, "far chase");
					}
					if (sync==3) {
						other ("syncrone orbit.");
						command (3, "syncrone orbit");
					}
					if (sync==4) {
						other ("high-speed orbit.");
						command (3, "high-speed orbit");
					}
					if (sync==5) {
						other ("near chase.");
						command (3, "near chase");
					}
					if (sync==6) {
						other ("high-speed near chase.");
						command (3, "high-speed near");
					}
				}
				else {
					cline (2, "tracking status: disconnected.");
					if (sync==1)
						command (3, "fixed-point chase");
					if (sync==2)
						command (3, "far chase");
					if (sync==3)
						command (3, "syncrone orbit");
					if (sync==4)
						command (3, "high-speed orbit");
					if (sync==5)
						command (3, "near chase");
					if (sync==6)
						command (3, "high-speed near");
				}
			}
			else {
				cline (2, "tracking status: inactive.");
				command (3, "drive tracking mode");
			}
			if (pl_search) {
				command (2, "LOCAL PLANETS FINDER");
				xx = nearstar_x - dzat_x;
				yy = nearstar_y - dzat_y;
				zz = nearstar_z - dzat_z;
				xx = SQRT (xx*xx+yy*yy+zz*zz);
				if (xx<20000) {
					if (nearstar_nop) {
						cline (3, "planet finder report: system has ");
						int suns = 0;
						int planets = 0;
						for (int a=0; a<nearstar_nop; a++) {
							if (nearstar_p_type[a]==10) {	//companion star
								suns++;
							} else {
								planets++;
							}
						}
						other (alphavalue(planets));
						other (" ");
						if (nearstar_class==9)
							other ("proto");
						if (nearstar_nop==1)
							other ("planet, and ");
						else
							other ("planets, and ");
						other (alphavalue(nearstar_nob - nearstar_nop));
						other (" minor bodies. ");
						other (alphavalue(nearstar_labeled));
						other (" labeled out of ");
						other (alphavalue(nearstar_nob));
						other (".");
						if (suns>0) {
							cline (4, "system has ");
							other(alphavalue(suns));
							other(" companion stars.");
						}
					}
					else
						cline (3, "planet finder report: there are no major bodies in this system.");
				}
				else
					cline (3, "planet finder report: no stellar systems within remote sensors range.");
			}
			else
				command (2, "local planets finder");
			break;
		case 2: // miscellaneous devices status
			if (ilightv==1)
				command (1, "internal light on");
			else
				command (1, "internal light off");
			command (2, "remote target data");
			command (3, "local target data");
			command (4, "environment data");
			if (data == 1) command (2, "REMOTE TARGET DATA");
			if (data == 2) command (3, "LOCAL TARGET DATA");
			if (data == 3) command (4, "ENVIRONMENT DATA");
			break;
		case 3: // galactic cartography status
			if (labstar)
				command (1, "assign star label");
			else {
				if (star_label_pos > -1)
					command (1, "remove star label");
				else
					command (1, "label star as...");
			}
			if (labplanet)
				command (2, "assign planet label");
			else {
				if (planet_label_pos > -1)
					command (2, "remove planet label");
				else
					command (2, "label planet as...");
			}
			if (targets_in_range)
				command (3, "quit targets in range");
			else
				command (3, "show targets in range");
			if (manual_target)
				command (4, "(enter coordinates)");
			else
				command (4, "set target to parsis");
			cline (1, "epoc ");
			other (alphavalue((Dword)epoc)); other (" triads ");
			lsecs = secs; lsecs -= lsecs % 1000000L; lsecs /= 1000000L;
			other (alphavalue(lsecs)); other (",");
			lsecs = secs; lsecs %= 1000000L; lsecs -= lsecs % 1000; lsecs /= 1000;
			other (alphavalue(lsecs)); other (",");
			lsecs = secs; lsecs %= 1000;
			other (alphavalue(lsecs));
			cline (2, "parsis universal coordinates: ");
			asm {	fld dzat_x
				frndint
				fstp parsis_x
				fld dzat_y
				frndint
				fstp parsis_y
				fld dzat_z
				frndint
				fstp parsis_z }
			other (alphavalue(parsis_x));
			other (";");
			other (alphavalue(-parsis_y));
			other (";");
			other (alphavalue(parsis_z));
			cline (3, "heading pitch: ");
			other (alphavalue((Dword)(sin(deg*navigation_beta)*+100)));
			other (";");
			other (alphavalue((Dword)(cos(deg*navigation_beta)*-100)));
			break;
		case 4: // emergency functions status
			command (1, "reset onboard system");
			command (2, "send help request");
			if (lithium_collector)
				command (3, "stop scoping lithium");
			else
				command (3, "scope for lithium");
			command (4, "clear status");
			if (gburst == -1) {
				cline (1, "NOTE: there are no emergencies at the moment.");
				cline (2, "help request not sent.");
				break;
			}
			break;
	}
}

/* Comandi dei dispositivi di bordo. */

char dummy_identity[8] = "Removed:";
char comp_data[32];

void dev_commands ()
{
	Word n;
	float dist;

	switch (dev_page) {
		case 0:	dev_page = s_command;
			switch (s_command) {
				case 1: status ("NAVIGATION", 50); break;
				case 2: status ("SUPPORTS", 50); break;
				case 3: status ("CARTOGRAFY", 50); break;
				case 4: status ("EMERGENCY", 50);
			}
			break;
		case 1: switch (s_command) {
				case 1: field_amplificator = 1 - field_amplificator;
					if (field_amplificator)
						status ("ACTIVE", 50);
					else
						status ("INACTIVE", 50);
					break;
				case 2: pl_search = 1 - pl_search;
					if (pl_search)
						status ("ACTIVE", 50);
					else
						status ("INACTIVE", 50);
					break;
				case 3: sync++;
					sync %= 7;
					if (!sync) {
						status ("IDLE", 50);
						ip_reaching = 0;
						ip_reached = 1;
					}
					else {
						status ("ACQUIRED", 50);
						if (ip_reached) {
							ip_reaching = 1;
							ip_reached = 0;
						}
					}
					break;
				case 4: anti_rad = 1 - anti_rad;
					if (anti_rad)
						status ("ACTIVE", 50);
					else
						status ("INACTIVE", 50);
			}
			break;
		case 2: switch (s_command) {
				case 1: ilightv = -ilightv;
					if (ilightv > 0)
						status ("ON", 50);
					else
						status ("OFF", 50);
					break;
				case 2: if (data == 1)
						datasheetdelta = -2;
					else {
						data = 1;
						datasheetdelta = +2;
					}
					break;
				case 3: 
					if (data == 2) {
						data = 6;
					} else if (data==6) {
						datasheetdelta = -2;
					} else {
						data = 2;
						datasheetdelta = +2;
					}
					break;
				case 4: if (data == 3)
						datasheetdelta = -2;
					else {
						data = 3;
						datasheetdelta = +2;
					}
					break;
				case 5: if (data == 4)
						datasheetdelta = -2;
					else {
						data = 4;
						datasheetdelta = +2;
					}
					break;
				case 6: if (data == 5)
						datasheetdelta = -2;
					else {
						data = 5;
						datasheetdelta = +2;
					}
					break;
			}
			break;
		case 3: // galactic cartography commands
			switch (s_command) {
				case 1:

					if (ap_targetted==1 && !ap_targetting && !labplanet) {
						status("PROCEEDING", 100);
						if (ap_target_id != nearstar_identity) {
							status ("WE'RE NOT IN THAT SYSTEM", 1001);
							break;
						}
						labstar = 1 - labstar;
						if (labstar) {
							if (star_label_pos > -1) {
								labstar = 0;
								#ifdef OLD_STARMAP
								if (star_label_pos >= sm_consolidated) {
									smh = OPENFILE (starmap_file, OPEN_RPLUS);
									if (smh ISFILEVALID) {
										FILESEEK (smh, star_label_pos, SEEK_SET);
										WRITEFILE (smh, &dummy_identity[0], 8);
										CLOSEFILE (smh);
										ap_target_previd = 12345;
										status ("REMOVED", 50);
										star_label_pos = -1;
										//nearstar_labeled--;
									}
									else
										status ("INT. ERROR", 50);
								}
								else
									status ("DENIED", 50);
								#else
								#ifdef WINDOWS
								FILE * tmpFile;
								if (current_galaxy==0) {
									tmpFile = fopen(starmap3_file, "r+b");
								} else {
									tmpFile = fopen(starmap3b_file, "r+b");
								}
								#else
								FILE * tmpFile = fopen(starmap3_file, "r+b");
								#endif
								if (tmpFile!=NULL) {
									fseek(tmpFile, star_label_pos, SEEK_SET);
									Uchar flags;
									fread(&flags, 1, 1, tmpFile);
									
									flags=flags|0x20;	//deleted
									//DebugPrintf(0, "Fixing things pointing to this entry (%lx).", star_label_pos);
									//Fix anything pointing to this entry.
									fseek(tmpFile, star_label_pos, SEEK_SET);
									fwrite(&flags, 1, 1, tmpFile);
									fseek(tmpFile, star_label_pos+39, SEEK_SET);
									Udword nextAltPos = 0;
									fread(&nextAltPos, 4, 1, tmpFile);
									fclose(tmpFile);
									#ifdef WINDOWS
									Dword altrefpos = something_pointing_alt_to(star_label_pos, current_galaxy);
									#else
									Dword altrefpos = something_pointing_alt_to(star_label_pos);
									#endif
									if (altrefpos>0) {
										#ifdef WINDOWS
										FILE * tmpFile;
										if (current_galaxy==0) {
											tmpFile = fopen(starmap3_file, "r+b");
										} else {
											tmpFile = fopen(starmap3b_file, "r+b");
										}
										#else
										FILE * tmpFile = fopen(starmap3_file, "r+b");
										#endif
										fseek(tmpFile, altrefpos+39, SEEK_SET);
										fwrite(&nextAltPos, 4, 1, tmpFile);
										fclose(tmpFile);
									}
									//DebugPrintf(0, "Fixed alt ref stuff.");
									//Either forward or delete planet entries for this system too:
									#ifdef WINDOWS
									Dword starrefpos = something_pointing_star_to(star_label_pos, current_galaxy);
									#else
									Dword starrefpos = something_pointing_star_to(star_label_pos);
									#endif
									while (starrefpos>0) {
										//DebugPrintf(0, "Starrefpos = %lx.", starrefpos);
										#ifdef WINDOWS
										FILE * tmpFile;
										if (current_galaxy==0) {
											tmpFile = fopen(starmap3_file, "r+b");
										} else {
											tmpFile = fopen(starmap3b_file, "r+b");
										}
										#else
										FILE * tmpFile = fopen(starmap3_file, "r+b");
										#endif
										if (altrefpos<=0) {	//There are no other entries for this star.
											//DebugPrintf(0, "Processing with no altrefpos.");
											fseek(tmpFile, starrefpos, SEEK_SET);
											Uchar pflags;
											fread(&pflags, 1, 1, tmpFile);
											//DebugPrintf(0, "pflags=%x", (int) pflags);
											pflags=pflags|0x20;
											fseek(tmpFile, starrefpos, SEEK_SET);
											fwrite(&pflags, 1, 1, tmpFile);
											fclose(tmpFile);
											#ifdef WINDOWS
											starrefpos = something_pointing_star_to(star_label_pos, current_galaxy);
											#else
											starrefpos = something_pointing_star_to(star_label_pos);
											#endif
										} else {	//There is another entry for this star after this one.
											//DebugPrintf(0, "Processing with altrefpos.");
											fseek(tmpFile, starrefpos+25, SEEK_SET);
											fwrite(&altrefpos, 4, 1, tmpFile);	//Change its 'starFP' to point at the alternate entry.
											fclose(tmpFile);
											#ifdef WINDOWS
											starrefpos = something_pointing_star_to(star_label_pos, current_galaxy);
											#else
											starrefpos = something_pointing_star_to(star_label_pos);
											#endif
										}
									}
									//DebugPrintf(0, "Done fixing stuff.");
									ap_target_previd = 12345;
									status ("REMOVED", 101);
									star_label_pos = -1;
									prev_planet_id = 12345;
									planet_label_pos = -1;
									labstar = 0;
									nearstar_labeled = 0;	//number of labelled bodies in the system
									labplanet = 0;
								} else {
									status ("MISSING STARMAP", 200);
								}
								#endif
							}
							else {
								status ("PROMPT", 101);
								labstar_char = 0;
								star_id = ap_target_id;
								for (n = 0; n < 21; n++)
									star_label[n] = 32;
								
							}
						}
						else {
							#ifdef OLD_STARMAP
							smh = OPENFILE (starmap_file, OPEN_RPLUS);
							if (smh == NOFILE) {
								smh = CREATEFILE (starmap_file);
								sm_consolidated = 4; WRITEFILE (smh, &sm_consolidated, 4);
							}
							if (smh ISFILEVALID) {
								FILESEEK (smh, 4, SEEK_SET);
								while (READFILE (smh, comp_data, 32) ISREADLEN(32))
									if (memcmp (comp_data, dummy_identity, 8)) {
									if (!memicmp (comp_data+8, star_label, 20)) {
										status ("EXTANT", 50);
										ap_target_previd = 12345;
										star_label_pos = -1;
										CLOSEFILE (smh);
										return;
									}}
								FILESEEK (smh, 0, SEEK_END);
								star_label_pos = FILETELL(smh);
								WRITEFILE (smh, &star_id, 32);
								CLOSEFILE (smh);
								status ("ASSIGNED", 50);
								//nearstar_labeled++;
							}
							else
								status ("INT. ERROR", 50);
							#else
							#ifdef WINDOWS
							FILE * tmpFile;
							if (current_galaxy==0) {
								tmpFile = fopen(starmap3_file, "rb");
							} else {
								tmpFile = fopen(starmap3b_file, "rb");
							}
							#else
							FILE * tmpFile = fopen(starmap3_file, "rb");
							#endif
							if (tmpFile==NULL) {
								//No longer will an empty starmap be made if the file is missing. Instead NICE will complain.
								//This is because the starmap comes with NICE, etc, not having it would be a Bad Thing, and you'd need to know. (SL)
								status ("MISSING STARMAP", 200);
							} else {
								fclose(tmpFile);
								#ifdef WINDOWS
								if (something_labelled(star_label, current_galaxy)>-1) {
								#else
								if (something_labelled(star_label)>-1) {
								#endif
									status ("EXTANT", 101);
									ap_target_previd = 12345;
									star_label_pos = -1;
									return;
								}
								status("WRITING", 101);
								//reopen it and write a new entry at the end.
								//write discoverer as 0xFFFFFFFE if we don't know our user ID#.
								Uchar sm_flags = 0x80|0x40|0x8;	//include in outbox (0x80), local only (0x40), and star (0x8). Include in outbox and local only combined have a special meaning: This entry has never been sent in an outbox. The local only flag will be cleared when SyncStarmap is run. (SL)
								Udword sm_discoverer = 0xFFFFFFFE;
								
								if (ap_target_sx==0x7FFFFFFF && ap_target_sy==0x7FFFFFFF && ap_target_sz==0x7FFFFFFF) {
									//Sector coords unknown; find them!
									Dword retval = getSectorCoords(ap_target_x, ap_target_y, ap_target_z, &ap_target_sx, &ap_target_sy, &ap_target_sz);
									if (retval==-1) {
										status ("ACK! CAN'T FIND SYSTEM", 200);
									} else if (retval==-2) {
										enableR9aBugMessage();
									}
								}
								if (ap_target_sx!=0x7FFFFFFF && ap_target_sy!=0x7FFFFFFF && ap_target_sz!=0x7FFFFFFF) {
									#ifdef WINDOWS
									FILE * tmpFile;
									if (current_galaxy==0) {
										tmpFile = fopen(starmap3_file, "ab");
									} else {
										tmpFile = fopen(starmap3b_file, "ab");
									}
									#else
									FILE * tmpFile = fopen(starmap3_file, "ab");
									#endif
									Uword sm_data = (nearstar_class&0xF) | ((nearstar_nop&0x1F)<<4) | (((nearstar_nob - nearstar_nop)&0x1F)<<9);
									Udword zero = 0;
									fwrite(&sm_flags, 1, 1, tmpFile);
									star_label_pos=ftell(tmpFile)-1;
									fwrite(&sm_discoverer, 4, 1, tmpFile);
									fwrite(&star_label, 20, 1, tmpFile);
									fwrite(&ap_target_sx, 4, 1, tmpFile);
									fwrite(&ap_target_sy, 4, 1, tmpFile);
									fwrite(&ap_target_sz, 4, 1, tmpFile);
									fwrite(&sm_data, 2, 1, tmpFile);
									fwrite(&zero, 4, 1, tmpFile);
									fclose(tmpFile);
									status("WROTE IT", 102);
								} else {
									status ("NICE IS CONFUSED, CAN'T FIND SYSTEM STILL.", 199);
									//DebugPrintf(0, "Star coordinates nearstar_x=%f nearstar_y=%f nearstar_z=%f.", nearstar_x, nearstar_y, nearstar_z);
								}
							}
							#endif
						}
					}
					else
						status ("CONFLICT", 50);
					break;
				case 2:
					if (ip_targetted!=-1 && !labstar) {
						status("PROCEEDING", 100);
						labplanet = 1 - labplanet;
						if (labplanet) {
							if (planet_label_pos > -1) {
								labplanet = 0;
								#ifdef OLD_STARMAP
								if (planet_label_pos >= sm_consolidated) {
									smh = OPENFILE (starmap_file, OPEN_RPLUS);
									if (smh ISFILEVALID) {
										FILESEEK (smh, planet_label_pos, SEEK_SET);
										WRITEFILE (smh, &dummy_identity[0], 8);
										CLOSEFILE (smh);
										prev_planet_id = 12345;
										status ("REMOVED", 50);
										planet_label_pos = -1;
										nearstar_labeled--;
									}
									else
										status ("INT. ERROR", 50);
								}
								else
									status ("DENIED", 50);
								#else
								#ifdef WINDOWS
								FILE * tmpFile;
								if (current_galaxy==0) {
									tmpFile = fopen(starmap3_file, "r+b");
								} else {
									tmpFile = fopen(starmap3b_file, "r+b");
								}
								#else
								FILE * tmpFile = fopen(starmap3_file, "r+b");
								#endif
								if (tmpFile!=NULL) {
									//DebugPrintf(0, "planet_label_pos=%lx",  planet_label_pos);
									fseek(tmpFile, planet_label_pos, SEEK_SET);
									Uchar flags;
									fread(&flags, 1, 1, tmpFile);
									flags=flags|0x20;	//deleted
									fseek(tmpFile, planet_label_pos, SEEK_SET);
									fwrite(&flags, 1, 1, tmpFile);
									fseek(tmpFile, planet_label_pos+31, SEEK_SET);
									Udword nextAltPos = 0;
									fread(&nextAltPos, 4, 1, tmpFile);
									fclose(tmpFile);
									#ifdef WINDOWS
									Dword altrefpos = something_pointing_alt_to(planet_label_pos, current_galaxy);
									#else
									Dword altrefpos = something_pointing_alt_to(planet_label_pos);
									#endif
									if (altrefpos!=0) {
										#ifdef WINDOWS
										FILE * tmpFile;
										if (current_galaxy==0) {
											tmpFile = fopen(starmap3_file, "r+b");
										} else {
											tmpFile = fopen(starmap3b_file, "r+b");
										}
										#else
										FILE * tmpFile = fopen(starmap3_file, "r+b");
										#endif
										fseek(tmpFile, altrefpos+31, SEEK_SET);
										fwrite(&nextAltPos, 4, 1, tmpFile);
										fclose(tmpFile);
									}
									labplanet=0;
									prev_planet_id = 12345;
									status ("REMOVED", 50);
									planet_label_pos = -1;
									if (nearstar_labeled>0) {
										nearstar_labeled--;
									}
								} else {
									status ("MISSING STARMAP", 200);
								}
								#endif
							}
							else {
								status ("PROMPT", 50);
								labplanet_char = 0;
								planet_id = nearstar_identity + ip_targetted + 1;
								for (n = 0; n < 21; n++)
									planet_label[n] = 32;
							}
						}
						else {
							#ifdef OLD_STARMAP
							smh = OPENFILE (starmap_file, OPEN_RPLUS);
							if (smh == NOFILE) {
								smh = CREATEFILE (starmap_file);
								sm_consolidated = 4; WRITEFILE (smh, &sm_consolidated, 4);
							}
							if (smh ISFILEVALID) {
								FILESEEK (smh, 4, SEEK_SET);
								while (READFILE (smh, comp_data, 32) ISREADLEN(32))
									if (memcmp (comp_data, dummy_identity, 8)) {
									if (!memicmp (comp_data+8, planet_label, 20)) {
										status ("EXTANT", 50);
										prev_planet_id = 12345;
										planet_label_pos = -1;
										CLOSEFILE (smh);
										return;
									}}
								FILESEEK (smh, 0, SEEK_END);
								planet_label_pos = FILETELL(smh);
								WRITEFILE (smh, &planet_id, 32);
								CLOSEFILE (smh);
								status ("ASSIGNED", 50);
								nearstar_labeled++;
							}
							else
								status ("INT. ERROR", 50);
							#else
							status("CHECKING FOR FILE", 101);
							#ifdef WINDOWS
							FILE * tmpFile;
							if (current_galaxy==0) {
								tmpFile = fopen(starmap3_file, "rb");
							} else {
								tmpFile = fopen(starmap3b_file, "rb");
							}
							#else
							FILE * tmpFile = fopen(starmap3_file, "rb");
							#endif
							if (tmpFile==NULL) {
								//No longer will an empty starmap be made if the file is missing. Instead NICE will complain.
								//This is because the starmap comes with NICE, etc, not having it would be a Bad Thing, and you'd need to know. (SL)
								status ("MISSING STARMAP", 200);
							} else {
								fclose(tmpFile);
								status("PROCEEDING", 102);
								#ifdef WINDOWS
								if (something_labelled(planet_label, current_galaxy)>-1) {
								#else
								if (something_labelled(planet_label)>-1) {
								#endif
									status ("EXTANT", 153);
									prev_planet_id = 12345;
									planet_label_pos = -1;
									labplanet=0;
									return;
								}
								//reopen it and write a new entry at the end.
								if (nearstar_sx==0x7FFFFFFF && nearstar_sy==0x7FFFFFFF && nearstar_sz==0x7FFFFFFF) {
									//Sector coords unknown; find them!
									Dword retval = getSectorCoords(nearstar_x, nearstar_y, nearstar_z, &nearstar_sx, &nearstar_sy, &nearstar_sz);
									if (retval==-1) {
										status ("ACK! CAN'T FIND SYSTEM", 200);
									} else if (retval==-2) {
										enableR9aBugMessage();
									}
								}
								if (nearstar_sx!=0x7FFFFFFF || nearstar_sy!=0x7FFFFFFF || nearstar_sz!=0x7FFFFFFF) {
									status("FINDING STAR", 153);
									//Find the star entry:
									#ifdef WINDOWS
									Dword starFP = system_labelled(nearstar_sx, nearstar_sy, nearstar_sz, current_galaxy);
									#else
									Dword starFP = system_labelled(nearstar_sx, nearstar_sy, nearstar_sz);
									#endif
									if (starFP==-1) {
										status("LABEL STAR FIRST.", 154);
										prev_planet_id = 12345;
										planet_label_pos = -1;
										labplanet=0;
									} else {
										status("WRITING", 154);
										#ifdef WINDOWS
										FILE * tmpFile;
										if (current_galaxy==0) {
											tmpFile = fopen(starmap3_file, "ab");
										} else {
											tmpFile = fopen(starmap3b_file, "ab");
										}
										#else
										FILE * tmpFile = fopen(starmap3_file, "ab");
										#endif
										nearstar_labeled++;
										//write discoverer as 0xFFFFFFFE if we don't know our user ID#.
										Uchar sm_flags = 0x80|0x40;	//include in outbox (0x80) and local only (0x40). Include in outbox and local only combined have a special meaning: This entry has never been sent in an outbox. The local only flag will be cleared when SyncStarmap is run. (SL)
										Udword sm_discoverer = 0xFFFFFFFE;
										Uword sm_data = 0;
										Uword pType = nearstar_p_type[ip_targetted];
										Word pNum=nearstar_p_owner[ip_targetted];
										Uword mNum=nearstar_p_moonid[ip_targetted];
										if (pNum==-1) {
											pNum=ip_targetted;
											mNum=0x1F;
										}
										sm_data = (pType&0xF) | ((pNum&0x1F)<<4) | ((mNum&0x1F)<<9);
										Udword zero = 0;
										fwrite(&sm_flags, 1, 1, tmpFile);
										planet_label_pos = ftell(tmpFile)-1;
										fwrite(&sm_discoverer, 4, 1, tmpFile);
										fwrite(&planet_label, 20, 1, tmpFile);
										fwrite(&starFP, 4, 1, tmpFile);
										fwrite(&sm_data, 2, 1, tmpFile);
										fwrite(&zero, 4, 1, tmpFile);
										
										fclose(tmpFile);
										
									}
								} else {
									status ("NICE IS CONFUSED, CAN'T FIND SYSTEM STILL.", 199);
									//status ("ACK! CAN'T FIND STAR!", 200);
									//DebugPrintf(0, "Star coordinates nearstar_sx=%f nearstar_sy=%f nearstar_sz=%f.", nearstar_sx, nearstar_sy, nearstar_sz);
									prev_planet_id = 12345;
									planet_label_pos = -1;
									labplanet=0;
									
								}
							}
							#endif
						}
					}
					else
						status ("CONFLICT", 50);
					break;
				case 3:	targets_in_range = 1 - targets_in_range;
					if (targets_in_range) {
						targets = 0;
						target_line = 0;
						topmost_target = 0;
						tgt_collect_lastpos = 4;
						collecting_targets = 1;
						memset (&target_name[0], 32, 4 * 24);
						collect_targets ();
						tgts_in_show = 0;
					}
					break;
				case 4: // target parsis
					manual_target = 1 - manual_target;
					if (manual_target) {
						mt_coord = 0;
						mt_string_char = 0;
						manual_x_string[0] = 0;
						status ("TGT MANUAL", 100);
						ap_targetted = 0;
						stspeed = 0;
					}
					else
						status ("TGT REJECT", 100);
					break;
			}
			break;
		case 4: switch (s_command) {
				case 1: // reset onboard system
					reset_signal = 150;
					break;
				case 2: // help request
					if (pwr <= 15000 && !charge) {
						dist = fabs(dzat_x + dzat_y + dzat_z) * 0.0001;
						if (dist > 1800) dist = 1800;
						fast_srand (CLOCK());
						helptime = (flandom() * dist) + secs + 60;
						status ("HELP REQ.", 50);
						gburst = 63;
					}
					else {
						status ("ERROR", 50);
						gburst = -1;
					}
					break;
				case 3: // collect lithium
					if (!lithium_collector) {
						if (ap_reached && ap_targetted == 1) {
							if (nearstar_class == 5 || (nearstar_class == 6 && nearstar_ray > 4))
								lithium_collector = 1;
							else
								status ("UNSUITABLE", 50);
						}
						else
							status ("NEED RECAL", 75);
					}
					else {
						lithium_collector = 0;
						status ("IDLE", 50);
					}
					break;
				case 4: // clear status
					status ("READY", 50);
					gburst = 0;
			}
	}
}

/* Preferenze. */

void prefs ()
{
	if (autoscreenoff)
		command (1, "auto screen sleep on");
	else
		command (1, "auto screen sleep off");

	if (revcontrols)
		command (2, "reverse pitch controls");
	else
		command (2, "normal pitch controls");

	if (menusalwayson)
		command (3, "menus always onscreen");
	else
		command (3, "auto-hidden menus");

	if (depolarize)
		command (4, "polarize");
	else
		command (4, "depolarize");
}

/* Comandi di impostazione delle opzioni preferenziali. */

void toggle_option (char *option_flag)
{
	*option_flag = 1 - *option_flag;
	if (*option_flag)
		status ("ACQUIRED", 50);
	else
		status ("DISABLED", 50);
}

void pfs_commands ()
{
	switch (s_command) {
		case 1: toggle_option (&autoscreenoff); break;
		case 2: toggle_option (&revcontrols);	break;
		case 3: toggle_option (&menusalwayson); break;
		case 4: toggle_option (&depolarize);
	}
}

/* Comandi impartiti al computer di bordo.
   Tutti tranne "disattiva schermo". */

void commands ()
{
	switch (sys) {
		case 1: fcs_commands (); break;
		case 2: dev_commands (); break;
		case 3: pfs_commands (); break;
		case 5: extended_commands (); break;
	}
}

/* Scongela la situazione, riproducendola in tutto e per tutto,
   e facendola evolvere al momento attuale. */

void unfreeze ()
{
	FILEPTR 	fh;
	double	elapsed, dpwr;

	/* Lettura della mappa stellare consolidata. */

	#ifdef OLD_STARMAP
	smh = OPENFILE (starmap_file, OPEN_RPLUS);
	if (smh ISFILEVALID) {
		READFILE (smh, &sm_consolidated, 4);
		if (!sm_consolidated) {
			FILESEEK (smh, 0, SEEK_SET);
			FILELENGTH(sm_consolidated, smh);
			WRITEFILE (smh, &sm_consolidated, 4);
		}
		CLOSEFILE (smh);
	}
	else
		sm_consolidated = 0;
	#endif

	/* Lettura della situazione precedente. */

	fh = OPENFILE (situation_file, OPEN_RB);
	//if (fh==NOFILE) newmessage=1;
	if (fh ISFILEVALID) {
		#ifndef WINDOWS
		READFILE (fh, &sync, old_currentbin_length);
		READFILE (fh, &gnc_pos, 1);
		READFILE (fh, &goesfile_pos, 4);
		READFILE (fh, goesnet_command, 120);
		READFILE (fh, &option_speedup, new_currentbin_length);
		#else
		//Made this regex: [a-zA-Z]+[ \t]+\([a-zA-Z0-9_\[\]0-9]+\)[ \t]*=[ \t]*[\-0-9a-zA-Z\.+-\"]+;
		//To write this: READFILE (fh, &\1, sizeof(\1));
		//To transform the variable declarations into a bunch of READFILE calls.
		READFILE (fh, &sync, sizeof(sync));		// 0
		READFILE (fh, &anti_rad, sizeof(anti_rad));          // 1
		READFILE (fh, &pl_search, sizeof(pl_search));          // 2
		READFILE (fh, &field_amplificator, sizeof(field_amplificator));          // 3
		READFILE (fh, &ilight, sizeof(ilight));         // 4
		READFILE (fh, &ilightv, sizeof(ilightv));          // 5
		READFILE (fh, &charge, sizeof(charge));          // 6
		READFILE (fh, &revcontrols, sizeof(revcontrols));          // 7
		READFILE (fh, &ap_targetting, sizeof(ap_targetting));          // 8
		READFILE (fh, &ap_targetted, sizeof(ap_targetted));          // 9
		READFILE (fh, &ip_targetting, sizeof(ip_targetting));          // 10
		READFILE (fh, &ip_targetted, sizeof(ip_targetted));		// 11
		READFILE (fh, &ip_reaching, sizeof(ip_reaching));          // 12
		READFILE (fh, &ip_reached, sizeof(ip_reached));          // 13
		READFILE (fh, &ap_target_spin, sizeof(ap_target_spin));          // 14
		READFILE (fh, &ap_target_r, sizeof(ap_target_r));          // 15
		READFILE (fh, &ap_target_g, sizeof(ap_target_g));          // 16
		READFILE (fh, &ap_target_b, sizeof(ap_target_b));          // 17
		READFILE (fh, &nearstar_spin, sizeof(nearstar_spin));          // 18
		READFILE (fh, &nearstar_r, sizeof(nearstar_r));          // 19
		READFILE (fh, &nearstar_g, sizeof(nearstar_g));          // 20
		READFILE (fh, &nearstar_b, sizeof(nearstar_b));          // 21
		READFILE (fh, &gburst, sizeof(gburst));          // 22
		READFILE (fh, &menusalwayson, sizeof(menusalwayson));		// 23
		READFILE (fh, &depolarize, sizeof(depolarize));          // 24
		READFILE (fh, &sys, sizeof(sys));		// 25
		READFILE (fh, &pwr, sizeof(pwr));	// 27
		READFILE (fh, &dev_page, sizeof(dev_page));		// 29
		READFILE (fh, &ap_target_class, sizeof(ap_target_class));		// 31
		READFILE (fh, &f_ray_elapsed, sizeof(f_ray_elapsed));		// 33
		READFILE (fh, &nearstar_class, sizeof(nearstar_class));		// 35
		READFILE (fh, &nearstar_nop, sizeof(nearstar_nop));		// 37
		READFILE (fh, &pos_x, sizeof(pos_x));		// 39
		READFILE (fh, &pos_y, sizeof(pos_y));		// 43
		READFILE (fh, &pos_z, sizeof(pos_z));	// 47
		READFILE (fh, &user_alfa, sizeof(user_alfa));		// 51
		READFILE (fh, &user_beta, sizeof(user_beta));		// 55
		READFILE (fh, &navigation_beta, sizeof(navigation_beta));		// 59
		READFILE (fh, &ap_target_ray, sizeof(ap_target_ray));	// 63
		READFILE (fh, &nearstar_ray, sizeof(nearstar_ray));	// 67
		READFILE (fh, &dzat_x, sizeof(dzat_x));	// 71
		READFILE (fh, &dzat_y, sizeof(dzat_y));	// 79
		READFILE (fh, &dzat_z, sizeof(dzat_z));	// 87
		READFILE (fh, &ap_target_x, sizeof(ap_target_x));		// 95
		READFILE (fh, &ap_target_y, sizeof(ap_target_y));	// 103
		READFILE (fh, &ap_target_z, sizeof(ap_target_z));		// 111
		READFILE (fh, &nearstar_x, sizeof(nearstar_x));		// 119
		READFILE (fh, &nearstar_y, sizeof(nearstar_y));	// 127
		READFILE (fh, &nearstar_z, sizeof(nearstar_z));		// 135
		READFILE (fh, &helptime, sizeof(helptime));		// 143
		READFILE (fh, &ip_target_initial_d, sizeof(ip_target_initial_d));	// 151
		READFILE (fh, &requested_approach_coefficient, sizeof(requested_approach_coefficient));// 159
		READFILE (fh, &current_approach_coefficient, sizeof(current_approach_coefficient));// 167
		READFILE (fh, &reaction_time, sizeof(reaction_time));	// 175
		READFILE (fh, &(fcs_status[0]), 11);	// 183
		READFILE (fh, &fcs_status_delay, sizeof(fcs_status_delay));		// 194
		READFILE (fh, &psys, sizeof(psys));		// 196
		READFILE (fh, &ap_target_initial_d, sizeof(ap_target_initial_d));	// 198
		READFILE (fh, &requested_vimana_coefficient, sizeof(requested_vimana_coefficient));// 206
		READFILE (fh, &current_vimana_coefficient, sizeof(current_vimana_coefficient));	// 214
		READFILE (fh, &vimana_reaction_time, sizeof(vimana_reaction_time));	// 222
		READFILE (fh, &lithium_collector, sizeof(lithium_collector));		// 230
		READFILE (fh, &autoscreenoff, sizeof(autoscreenoff));		// 231
		READFILE (fh, &ap_reached, sizeof(ap_reached));		// 232
		READFILE (fh, &lifter, sizeof(lifter));		// 233
		READFILE (fh, &secs, sizeof(secs));		// 235
		READFILE (fh, &data, sizeof(data));		// 243
		READFILE (fh, &surlight, sizeof(surlight));		// 244
		
		//fprintf(stderr, "File pos for GNC: %i.\n", (int)ftell(fh));
		
		READFILE (fh, &gnc_pos, 1);
		READFILE (fh, &goesfile_pos, 4);
		READFILE (fh, goesnet_command, 120);
		//fprintf(stderr, "File pos for new data: %i.\n", (int)ftell(fh));
		
		//Same regex as before:
		//This regex: [a-zA-Z]+[ \t]+\([a-zA-Z0-9_\[\]0-9]+\)[ \t]*=[ \t]*[\-0-9a-zA-Z\.+-\"]+;
		//To write this: READFILE (fh, &\1, sizeof(\1));
		//To transform the variable declarations into a bunch of READFILE calls.
		//Additional variables: (SL and Mega)
		READFILE (fh, &option_speedup, sizeof(option_speedup));			// 0
		READFILE (fh, &option_temperature, sizeof(option_temperature));			// 1
		READFILE (fh, &nearstar_mass, sizeof(nearstar_mass));				// 2
		READFILE (fh, &nearstar_surfaceTemperature, sizeof(nearstar_surfaceTemperature));	// 10
		READFILE (fh, &nearstar_temperatureTransmission, sizeof(nearstar_temperatureTransmission));// 18
		READFILE (fh, &option_temperature_units, sizeof(option_temperature_units));			// 26
		READFILE (fh, &option_flying_lander, sizeof(option_flying_lander));				// 27
		READFILE (fh, &option_antialias_in_stardrifter, sizeof(option_antialias_in_stardrifter));		// 28
		READFILE (fh, &option_center_outerring_pointer, sizeof(option_center_outerring_pointer));		// 29
		READFILE (fh, &option_x_axis_pointer, sizeof(option_x_axis_pointer));		// 30
		READFILE (fh, &option_y_axis_pointer, sizeof(option_y_axis_pointer));		// 31
		READFILE (fh, &option_z_axis_pointer, sizeof(option_z_axis_pointer));		// 32
		READFILE (fh, &option_multiplayer, sizeof(option_multiplayer));		// 33
		READFILE (fh, &option_invis_sd, sizeof(option_invis_sd));			// 34
		READFILE (fh, &option_change_over_time, sizeof(option_change_over_time));	//35
		READFILE (fh, &lastSnapshot, sizeof(lastSnapshot));				//36
		READFILE (fh, &option_mouseLook, sizeof(option_mouseLook));			//40
		READFILE (fh, &ap_target_sx, sizeof(ap_target_sx));		//41
		READFILE (fh, &ap_target_sy, sizeof(ap_target_sy));		//45
		READFILE (fh, &ap_target_sz, sizeof(ap_target_sz));		//49
		READFILE (fh, &nearstar_sx, sizeof(nearstar_sx));		//53
		READFILE (fh, &nearstar_sy, sizeof(nearstar_sy));		//57
		READFILE (fh, &nearstar_sz, sizeof(nearstar_sz));		//61
		READFILE (fh, &option_3dbrackets, sizeof(option_3dbrackets));					//65
		READFILE (fh, &option_controlset, sizeof(option_controlset));					//66
		//fprintf(stderr, "File pos for current galaxy: %i.\n", (int)ftell(fh));
		READFILE (fh, &current_galaxy, sizeof(current_galaxy));					//67

		#endif
		strcpy(fcs_status_extended, fcs_status_extended);
		CLOSEFILE (fh);
	}
	else
		return;

	/* Risincronizzazione della situazione in relazione ai
	   precedenti eventi (evoluzione nascosta della situazione). */

	elapsed = secs;
	getsecs ();
	elapsed = secs - elapsed;

	if (helptime && secs>helptime+20) {
		helptime = 0;
		charge = 4;
		gburst = 0;
	}

	/* Ricostruzione del sistema stellare attuale. */

	npcs = -12345;
	prepare_nearstar (NEARSTAR_ALREADY_SET);

	if (lithium_collector) {
		while (elapsed >= 30 && charge < 120) {
			elapsed -= 30;
			charge++;
		}
		if (charge==120)
			pwr = 20000;
		else {
			SRAND (secs);
			pwr = RANDOM(5000) + 15000;
		}
	}

	/* Aggiornamento consumi supplementari. */

	dpwr = pwr;

	if (ilightv==1) dpwr -= elapsed / 84;
	if (pl_search) dpwr -= elapsed / 155;
	if (field_amplificator) dpwr -= elapsed / 41;

	if (ip_targetted != -1 && ip_reached) {
		if (sync==1) // fixed-point chase
			dpwr -= elapsed / 29;
		if (sync==2) // far chase
			dpwr -= elapsed / 18;
		if (sync==3) // syncrone orbit
			dpwr -= elapsed / 58;
		if (sync==4) // high-speed orbit
			dpwr -= elapsed / 7;
		if (sync==5) // near chase
			dpwr -= elapsed / 33;
		if (sync==6) // high-speed near chase
			dpwr -= elapsed / 7;
	}

	while (dpwr < 15000) {
		if (charge) {
			dpwr += 5000;
			charge--;
		}
		else
			dpwr = 15000;
	}

	pwr = dpwr;
}

/* Gestione errori hardware. */

#ifndef WINDOWS
#pragma warn -par
int caught_somewhere_in_time (int errval, int ax, int bp, int si)
{
	//DebugPrintf(1, "HARDERR errval=%i ax=%i bp=%i si=%i", errval, ax, bp, si);
	hardresume (_HARDERR_FAIL);
	return (2);
}
#pragma warn +par
#endif

/* Programma principale. */

float starmass_correction[star_classes] = {
	   1.886, // classe 0
	#if defined(ALL) || defined(TEMPERATURE)
	0.21,	//class 1 (SL)
	#else
	1.50, // classe 1
	#endif
	 8000.40, // classe 2
	0.05, // classe 3
	#if defined(ALL) || defined(TEMPERATURE)
	1.25,	//class 4 (SL)
	#else
	2.44, // classe 4
	#endif
	3.10, // classe 5
	9.30, // classe 6
	   48.00, // classe 7
	1.00, // classe 8
	1.00, // classe 9
	0.07, // classe 10
	15000.00  // classe 11
};

extern Uword _stklen = 0x1800;

char nohud = 1;
char vimana_shield = 0;
#ifdef WINDOWS
void mainA()
#else
void main ()
#endif
{
	
	//double tsecspassed=0;	//For the TEMPORARY periodic snapshot code (SL)
	
	#if defined(ALL) || defined(MULTIPLAYER)
	//MULTIPLAYER_DISABLED (This comment exists to make it is to find all the code that need to be reenabled to reenable multiplayer) (SL)
	//Uchar initCycles=0;
	#endif
	Word opencapcount = 0;
	float satur, DfCoS;
	 //	float user_drawing_range;
	
	Dword  ir,  ig,  ib,  ire  = 0, ige  = 0, ibe  = 0;
	Dword  ir2, ig2, ib2, ir2e = 0, ig2e = 0, ib2e = 0;
	Dword  ir3, ig3, ib3, ir3e = 0, ig3e = 0, ib3e = 0;

	Word   c, p_mpul = 0;
	char  sky_palette_ok = 0;
	char  select, lrv, right_dblclick = 0;
	float right_dblclick_dir;
	//float dist;

	double dpz, ras, rap, dasp, eclipse;
	double dxx, dyy, dzz, l_dsd, p_dsd, stz, ang;

	char felisian;

	char leftturn, rightturn, arrowcolor, farstar = 0;

	char temp_distance_buffer[16];
	//double outside_pp_temp=0;
	
	char *planetd[] = { "INTERNALLY HOT",
				   "CRATERIZED NO ATMOSPHERE",
				   "THICK ATMOSPHERE",
				   "FELISIAN",
				   "CREASED NO ATMOSPHERE",
				   "THIN ATMOSPHERE",
				   "LARGE NOT CONSISTENT",
				   "ICY",
				   "QUARTZ",
				   "SUBSTELLAR OBJECT",
				   "COMPANION STAR"
#ifdef WINDOWS
					, "GATEWAY"
#endif
		};



	Uword pqw;
	float hold_z;
	char about=0;
	char sptype=0;
	char islabeled[81];
		
	float tmp_float;
	Dword p1, p2, p3, p4;

	#ifndef WINDOWS
	harderr (caught_somewhere_in_time);
	#endif
	for (ir = 0; ir < 200; ir ++) m200[ir] = ir * 200;
	
	if (!test_and_init_mouse()) {
		printf ("\nMouse not present or mouse driver not installed.\n");
		return;
	}
	
	//TestForUTC();	//Disabled to save conventional memory, because the UTC code doesn't work (SL)
	
	n_offsets_map = (Uchar maybefar  *) FARMALLOC (om_bytes, "n_offsets_map");
	n_globes_map  = (char maybefar  *) FARMALLOC ((unsigned)gl_bytes+(unsigned)gl_brest, "n_globes_map");
	s_background  = (Uchar maybefar  *) FARMALLOC (st_bytes, "s_background");
	p_background  = (Uchar maybefar  *) FARMALLOC (pl_bytes, "p_background");
	p_surfacemap  = (Uchar maybehuge *) FARMALLOC (ps_bytes, "p_surfacemap");
	objectschart  = (quadrant maybefar *) FARMALLOC (oc_bytes, "objectschart");
	ruinschart    = (Uchar maybefar  *) objectschart; // oc alias
	pvfile        = (Uchar maybefar  *) FARMALLOC (pv_bytes, "pvfile");
	#ifdef WINDOWS
	adapted = WinGetScreen();
	#else
	adapted       = (Uchar maybefar  *) FARMALLOC (sc_bytes, "adapted");
	#endif
	txtr          = (Uchar maybehuge *) p_background; // txtr alias
	digimap2      = (Udword maybefar *) &n_globes_map[gl_bytes]; // font alias
	//BUFFERCHECK
	/*
	XMS stuff for testing. (SL)
	XmsInit();
	xms_objectschart = AllocMirror((void far*) objectschart, oc_bytes);
	xms_p_background = AllocMirror((void far*) p_background, pl_bytes);
	xms_s_background = AllocMirror((void far*) s_background, st_bytes);
	*/
	reach_your_dir ();
	remove(xbuff_txt);
	remove(x_txt);
	BUFFERCHECK


	FILE *frestart = fopen(restart_txt, "rt");
	if (frestart!=NULL) {
		fclose(frestart);
		frestart = NULL;
		remove (restart_txt);
		status("RESTARTED", 100);
	}

	if (pvfile&&adapted&&n_offsets_map&&n_globes_map
		&&p_background&&s_background&&p_surfacemap
		&&objectschart&&lens_flares_init()) {
		lrv = loadpv (vehicle_handle, vehicle_ncc, 15, 15, 15, 0, 0, 0, 0, 1);
		if (lrv < 1) {
			printf ("\nLoad error.\n");
			return;
		}
		loadpv (mini_vehicle_handle, vehicle_ncc, 15e-6, 15e-6, 15e-6, 0, 0, 3050e-6, 0, 1);
		load_QVRmaps ();
		load_starface ();
		load_digimap2 ();
	}
	else {
		printf ("\nNot enough free conventional memory to run.");
		printf ("\nType MEM and hit ENTER to check it out.");
		printf ("\nA lot of free conventional memory is needed to run Noctis IV CE.\n");
		printf ("\nSee troubleshooting.txt.\n");
		printf ("Press any key to exit.\n");
		getch();
		return;
	}
	BUFFERCHECK
	#ifdef WINDOWS
	NgInit();
	#endif
	
	//tweakedVGA (X320Y200C4YPAL); // INIZIALIZZAZIONE GRAFICA.
	_320_200_256 (); // INIZIALIZZAZIONE GRAFICA.

	initscanlines ();

	init_FP_segments ();

	unfreeze ();

	pclear (adapted, 0);
	QUADWORDS -= 1440;
	pqw = QUADWORDS;

	mouse_input ();
	mpul = 0;

	clock_t right_dblclick_timing = 0;

	dpp  = 210;
	change_camera_lens ();
	BUFFERCHECK

	//   0..64  veicolo, selezioni computer, artefatti. BLU COBALTO, ma dipende dalla luce delle stelle.
	//  64..128 cosmo, sfondo galattico, cieli sereni e "suplucsi effect". dal BLU ELETTRICO al BIANCO.
	// 128..192 stelle (continue sfumature cicliche) o lune (non costanti)
	// 192..256 pianeti (non costanti)
	tavola_colori (range8088, 0, 64, 16, 32, 63);
	tavola_colori (tmppal, 0, 256, 64, 64, 64);
	Word resolve = 64;

	// causa il recupero dell'eventuale contenuto dello schermo
	// di output della GOES command net
	force_update = 1;

	// recupero della situazione di superficie
	double olddzat_x = dzat_x; double olddzat_y = dzat_y; double olddzat_z = dzat_y;
	double distTravelledX, distTravelledY, distTravelledZ, distTravelled;
	/*printf("Foom %x.\n", 64);
	printf("sit=%x\n", situation_file);
	printf("star=%x\n", starmap3_file);
	printf("goes=%x\n", goesoutputfile);
	printf("surface=%x\n", surface_file);*/
	sfh = OPENFILE (surface_file, OPEN_RB);
	if (sfh ISFILEVALID) {
		if (ip_targetted==-1) {	//If things screw up really bad, this can get us back in orbit
			CLOSEFILE(sfh);
			remove(surface_file);
			goto pretendtohavehadsurfacebin;
		}
		// lettura precedenti coordinate di sbarco
		READFILE (sfh, &landing_pt_lon, 2);
		READFILE (sfh, &landing_pt_lat, 2);
		CLOSEFILE (sfh);
		// recupero labels del pianeta e della stella-bersaglio
		update_star_label ();
		update_planet_label ();
		// risincronizzazione istantanea della posizione della navicella
		RecalcPlanetStuff(1);
		// ripresa del ciclo di esplorazione planetaria
		
		entryflag = 1; planetary_main();
		pretendtohavehadsurfacebin:
		// termine esplorazione
		opencapcount = 86;
		opencapdelta = -2;
		holdtomiddle = 1;
		pp_gravity = 1;
		QUADWORDS = 16000;
		pclear (adapted, 0);
		#ifndef WINDOWS
		pclear (adaptor, 0);
		#endif
		QUADWORDS = pqw;
		if (exitflag) goto allstop;
	}
	secspassed=0;

	do {
		BUFFERCHECK
		sync_start ();
		
		//
		// Controllo del flag che indica quando ci si trova
		// sulla "terrazza panoramica", il tetto dello stardrifter.
		//
		pos_y += lifter;
		if (lifter > 0) {
			lifter--;
			if (lifter > 65)
				user_alfa += 0.11 * (40 - user_alfa);
			else
				user_alfa -= 0.25 * user_alfa;
			step = 0.5 * lifter;
		}
		if (lifter < 0) {
			lifter++;
			if (pos_y > -325)
				user_alfa += 0.12 * (user_alfa - 40);
			if (pos_y < -325 && pos_y > -715)
				step = - pos_y;
		}
		if (pos_y > 0) {
			lifter = 0;
			pos_y = 0;
		}
		if (pos_y < -750) {
			lifter = 0;
			pos_y = -750;
		}
		if (pos_y < -500)
			ontheroof = 1;
		else
			ontheroof = 0;
		if (!lifter && ontheroof) {
			DfCoS = pos_z + 3100;
			DfCoS = SQRT(pos_x*pos_x+DfCoS*DfCoS);
			if (DfCoS + step < 1100) {
				lifter = + 75;
			/*	//Disabled for now (SL)
			} else {
				double outsideTemp = GetOrbitingTemperatureAt(dsd);
				if (outsideTemp>50000.0) {
					status ("TOO HOT!", 25);
					//push them inside
					pos_x*=0.9;
					pos_z = ((pos_z+3100)*0.9)-3100;
				}
			*/
			}
		}
		//
		// Risposta al reset del sistema operativo di bordo.
		// La variabile "reset_signal" controlla la procedura
		// di reset, che reimposta tutti i parametri operativi
		// allo stato originario.
		//
		// Impostanto reset_signal a 150 si resetta tutto il sistema.
		// Impostanto reset_signal a 60 si resetta la rete GOES.
		//
		if (reset_signal) {
			switch (reset_signal) {
				   case 150: elight 		= 1;
					 ilight			= 0;
					 ilightv		= 0;
					 status ("----------", 100);
					 break;
				   case 140: ip_targetted 		= -1;
					 ip_reaching		= 0;
					 break;
				   case 130: ap_targetted 		= 0;
					 stspeed 		= 0;
					 break;
				   case 120: gburst			= 0;
					 sync			= 1;
					 anti_rad		= 1;
					 pl_search		= 0;
					 field_amplificator 	= 0;
					 break;
				   case 115: sys			= 4;
					 psys			= 4;
					 break;
				   case 110: lithium_collector	= 0;
					 autoscreenoff		= 0;
					 break;
				   case 101: status ("_^*^-!_$[]", 100);
					 ap_reached		= 0;
					 ip_reached		= 0;
					 landing_point		= 0;
					 break;
				case 75: elight 		= 0;
					 ilightv 		= 1;
					 break;
				case 55: mslocate (0, 0, 0);
					 mswrite (0, "G.O.E.S. COMMAND NET:");
					 break;
				case 35: mslocate (0, 0, 1);
					 mswrite (0, "REVISION ID 6011/0200");
					 break;
				case 25: mslocate (0, 0, 2);
					 mswrite (0, "SESSION ID ");
					 fast_srand (secs * 18);
					 sprintf (temp_distance_buffer, "%05lu%05lu", fast_random (0x7FFF), fast_random (0x7FFF));
					 mswrite (0, temp_distance_buffer);
					 break;
				case 10: status ("STANDBY", 100);
					 break;
			}
			reset_signal--;
		}
		//
		// Controlla il timer di sistema.
		//
		prevsecs = secs;
		getsecs ();
		secspassed += secs-prevsecs;
		if (secspassed<=0) secspassed=0;
		//
		// Accensione luci d'emergenza.
		// Comportamento dell'astrozattera in mancanza di litio.
		//
		if (pwr <= 15000 && !charge) {
			elight = 1;
			sync = 0;
			anti_rad = 0;
			pl_search = 0;
			field_amplificator = 0;
			ip_targetted = -1;
			ap_reached = 0;
			ip_reaching = 0;
			datasheetdelta = -100;
			depolarize=1;
			option_invis_sd=0;
		}
		else {
			if (elight && !reset_signal) {
				elight = 0;
				ilight = 0;
				ilightv = 1;
				reset_signal = 200;
			}
		}
		//
		// Input del mouse per gli spostamenti dell'utente.
		//
		p_mpul = mpul; mpul = 0;
		mouse_input ();
		if (mpul&2) {
			shift += 3*mdltx;
			dlt_alfa -= (float) mdlty / 8;
		}
		else {
			step -= 3*mdlty;
			if (abs(mdlty)>7) dlt_alfa = -user_alfa / 6;
			dlt_beta -= (float) mdltx / 3;
		}
		
		//
		// Input del mouse per il doppio click sinistro e destro.
		//
		BUFFERCHECK
		ReadCommFile(1);
		#if defined(ALL) || defined(MULTIPLAYER)
		//MULTIPLAYER_DISABLED (This comment exists to make it is to find all the code that need to be reenabled to reenable multiplayer) (SL)
		/*if (option_multiplayer && initCycles==4) {
			Multiplayer();
		}*/
		#endif
		
		//Check if there's stuff queued for x and x is ready to handle one, and if so, call X.
		FILE *tmpxbuff = fopen(xbuff_txt, "rt");
		FILE *tmpx = fopen(x_txt, "rt");
		
		
		if (tmpxbuff!=NULL && (tmpx==NULL || (lastXFps>-1 && fps>=lastXFps && secs-timeAdjustment>=lastXSecs+2))) {	//if fps==lastXFps then 1 second has just passed since X was called...
			//DebugPrintf(0, "Buffer processing. tmpxbuff=%li tmpx=%li lastXFps=%i lastXSecs=%f fps=%i secs=%f", tmpxbuff, tmpx, lastXFps, lastXSecs, fps, secs);
			//DebugPrintf(0, "secs is %f", secs);
			fclose(tmpxbuff); tmpxbuff=NULL;
			if (tmpx!=NULL) {	//If tmpx!=NULL and we got here then x.txt hasn't been deleted and has existed for a second or more.
				//DebugPrintf(0, "Command was ignored. ");
				lastXFps=-1; lastXSecs=-1;
				FILE *errors = fopen(errors_txt, "rt");
				if (errors!=NULL) {
					fclose(errors);
					errors = fopen(errors_txt, "at");
				} else {
					errors = fopen(errors_txt, "wt");
				}
				if (errors!=NULL) {
					fprintf(errors, "Invalid X command: ");
					for (char c = fgetc(tmpx); c!=-1; c = fgetc(tmpx)) {
						fputc(c, errors);
					}
					fputc('\n', errors);
					fclose(errors);
				}

				fclose(tmpx); tmpx=NULL;
				remove(x_txt);	//So we delete it.
				//and we should print an error message
				status("INVAL XCMD", 200);
				
				
			}
			//If we end up here then x.txt doesn't exist.
			lastXFps = -1;
			lastXSecs = -1;
			RunCommand("x");
		} else {
			if (tmpx==NULL && tmpxbuff==NULL) {
				//DebugPrintf(0, "Tmpx nonexistant, buffer nonexistant, clearing lastXFps and lastXSecs. fps=%i secs=%f", fps, secs);
				//DebugPrintf(0, "secs is %f", secs);
				lastXFps = -1;
				lastXSecs = -1;
			} else {
				//DebugPrintf(0, "Not buffer processing. Tmpx=%li, tmpxbuff=%li lastXFps=%i lastXSecs=%f fps=%i secs=%f", tmpx, tmpxbuff, lastXFps, lastXSecs, fps, secs);
				//DebugPrintf(0, "secs is %f", secs);
			}
			if (tmpxbuff!=NULL) {
				fclose(tmpxbuff); tmpxbuff=NULL;
			}
			if (tmpx!=NULL) {
				fclose(tmpx); tmpx=NULL;
			}
		}

		//MULTIPLAYER_DISABLED (This comment exists to make it is to find all the code that need to be reenabled to reenable multiplayer) (SL)
		/*
		#if defined(ALL) || defined(MULTIPLAYER)
		if (initCycles<4) {
			initCycles++;
		}
		#endif
		#if defined(ALL)
		if (option_multiplayer && initCycles==3) {
		#endif
		#if defined(MULTIPLAYER)
		if (initCycles==3) {
		#endif
		#if defined(ALL) || defined(MULTIPLAYER)
			//DebugPrintf(0, "Sending init messages.");
			SendInfo();
			SendRequestInfo();
			RequestServerTime();
		}
		#endif
		*/
		
		BUFFERCHECK
		//if (ontheroof) goto nop;	//Commenting this out allows right-clicking on the top of the drifter (SL)
		if ((mpul&1)&&!(p_mpul&1))
			select = 1;
		else
			select = 0;
		if ((mpul&2)&&!(p_mpul&2)&&!right_dblclick) {
			if (!right_dblclick_timing)
				right_dblclick_timing = CLOCK();
			else {
				if (CLOCK()-right_dblclick_timing<9) {
					right_dblclick = 1;
					right_dblclick_dir = user_beta;
				} else {
					right_dblclick_timing = CLOCK();
				}
			}
			
		}
		if (right_dblclick) {
			if (ap_targetting) {
				ap_targetting = 0;
				right_dblclick = 0;
				extract_ap_target_infos ();
				fix_remote_target ();
				goto nop;
			}
			if (ip_targetting) {
				ip_targetting = 0;
				right_dblclick = 0;
				if (ip_targetted != -1)
					fix_local_target ();
				else
					status ("NO TARGET", 50);
				goto nop;
			}
			//Previously: if (!holdtomiddle) {
			//Don't know why it was changed. (SL)
			if (!holdtomiddle && !ontheroof) {
				if (right_dblclick_dir > -135 && right_dblclick_dir < -45) {
					user_beta += 90;
					user_beta /= 1.5;
					xx = pos_x - 2900;
					pos_x -= xx * 0.25;
					if (landing_point)
						zz = pos_z + 104*15 + 1980;
					else
						zz = pos_z + 1940;
					pos_z -= zz * 0.25;
					if (fabs(xx)<25&&fabs(zz)<25&&fabs(user_beta)<1) {
						right_dblclick_timing = 0;
						right_dblclick = 0;
					}
					user_beta -= 90;
				}
				else {
					user_beta /= 1.5;
					zz = pos_z + 500;
					pos_z -= zz * 0.25;
					if (sys!=4) {
						if (fabs(zz)<25&&fabs(user_beta)<1) {
							right_dblclick_timing = 0;
							right_dblclick = 0;
						}
					}
					else {
						xx = pos_x + 1700;
						pos_x -= xx * 0.25;
						if (fabs(zz)<25&&fabs(xx)<25&&fabs(user_beta)<1) {
							right_dblclick_timing = 0;
							right_dblclick = 0;
						}
					}
				}
			}
		}
		//
		// Variazione angoli visivi.
		//
	   nop:	user_alfa += dlt_alfa;
		dlt_alfa /= 1.5; if (fabs(dlt_alfa)<0.25) dlt_alfa = 0;
		if (user_alfa<-89.9) {
			user_alfa = -89.9;
			dlt_alfa = 0;
		}
		if (user_alfa>89.9) {
			user_alfa = 89.9;
			dlt_alfa = 0;
		}
		user_beta += dlt_beta;
		dlt_beta /= 1.5; if (fabs(dlt_beta)<0.25) dlt_beta = 0;
		while (user_beta>180) user_beta -= 360;
		while (user_beta<-180) user_beta += 360;
		//
		// Variazione della posizione dell'utente nella navicella.
		//
		alfa = user_alfa;
		beta = user_beta - 90;
		change_angle_of_view ();
		p_Forward (shift);
		beta = user_beta;
		change_angle_of_view ();
		p_Forward (step);
		shift /= 1.5; if (fabs(shift)<0.5) shift = 0;
		step /= 1.25; if (fabs(step)<0.5) step = 0;
		if (pos_x<-3100) pos_x = -3100;
		if (pos_x>+3100) pos_x = +3100;
		if (pos_z>- 300) pos_z = - 300;
		if (pos_z<-5800) pos_z = -5800;
		//
		// Background nero, che verr… reso nebuloso...
		//
		/*if (vimana_shield==0) {
			if (outside_pp_temp>2500) {
				status("VIMANA SHIELD ACTIVATED", 52);
				vimana_shield=1;
			} else if (outside_pp_temp>2000) {
				status("PREPARING VIMANA SHIELD", 51);
			}
		} else {
			if (outside_pp_temp<=2000) {
				if (vimana_shield==1) status("VIMANA SHIELD OFF", 52);
				vimana_shield=0;
			} else if (outside_pp_temp<=2500) {
				status("VIMANA SHIELD OFF", 52);
				vimana_shield=2;
			}
		}*/
		
		r9aBugMessage();
		//#ifdef WINDOWS
		//FindCritter0();
		//#endif
		/*static int tempint=1;
		if (tempint) {
			tempint=0;
			//DebugPrintf(0, "sx=%li sy=%li sz=%li", ap_target_sx, ap_target_sy, ap_target_sz);
			//DebugPrintf(0, "x=%li y=%li z=%li", ap_target_x, ap_target_y, ap_target_z);
		}*/
		if (vimana_shield==1) {
			
		} else if (!stspeed) {
			//This skips the first 9 lines, thus preserving the top of the HUD. Additionally, due to QUADWORDS meaning 180 lines in space,
			//and action in pclear, this skips the bottom 9 lines too.
			pclear (adapted + 2880, 0);
		} else {
			
			pfade (adapted, 180, 8);
		}
		BUFFERCHECK
	
		//
		// gestione stella vicina
		//
		from_vehicle ();
		
		dxx   = dzat_x - nearstar_x;
		dyy   = dzat_y - nearstar_y;
		dzz   = dzat_z - nearstar_z;
		l_dsd = SQRT (dxx*dxx + dyy*dyy + dzz*dzz) + 1;
		//if (IsNaN(l_dsd)) l_dsd=NAN_DSD;
		satur = (12 * l_dsd) / nearstar_ray;
		fast_srand (nearstar_z);
		ir = fast_random(31) + 29;
		if (satur < ir) satur = ir;
		if (satur > 63) satur = 63;
		//
		if (l_dsd < 100 * nearstar_ray)
			whiteglobe (adapted, nearstar_x, nearstar_y, nearstar_z,
					3 * nearstar_ray, 0.3);
		for (ir = 0; ir < nearstar_nop; ir++) {
			if (nearstar_p_type[ir] == 10) {
				planet_xyz (ir);
				p_dsd = nearstar_p_qsortdist[ir];
				fast_srand (ir + nearstar_x);
				whiteglobe (adapted, plx, ply, plz,
					3 * nearstar_p_ray[ir], 0.15 - fast_flandom() * 0.3);
				if (p_dsd>5*nearstar_p_ray[ir]&&p_dsd<1000*nearstar_p_ray[ir])
					lens_flares_for (dzat_x, dzat_y, dzat_z, plx, ply, plz,
							(10 * nearstar_p_ray[ir]) / p_dsd,
							1 + (0.001 * p_dsd), 1, 0, 3, 0);
			}
		}
		if (l_dsd > 6 * nearstar_ray) {
			if (nearstar_class!=5&&nearstar_class!=6&&nearstar_class!=10) {
				if (nearstar_class!=11||gl_start<90) {
					if (l_dsd>5*nearstar_ray&&l_dsd<1000*nearstar_ray) {
						lens_flares_for (dzat_x, dzat_y, dzat_z,
								 nearstar_x, nearstar_y, nearstar_z,
								 (10 * nearstar_ray) / l_dsd, 1 + (0.001 * l_dsd), 1, 0, 3, 0);
					}
				}
			}
			psmooth_grays (adapted+2880);
		}
		//
		BUFFERCHECK
		mask_pixels (adapted+2880, 64);
		//
		BUFFERCHECK
		if (l_dsd < 8 * nearstar_ray) {
			if (farstar) {
				farstar = 0;
				load_starface ();
			}
			glass_bubble = 0;
			if (nearstar_spin) {
			 gl_start += nearstar_spin;
			 gl_start %= 360;
			 globe (gl_start, adapted, s_background, (Uchar maybefar*) n_globes_map, gl_bytes,
				nearstar_x, nearstar_y, nearstar_z, nearstar_ray, 64, satur);
			}
			else {
			 globe ((CLOCK()/360)%360, adapted, s_background,
				(Uchar maybefar*) n_globes_map, gl_bytes, nearstar_x, nearstar_y,
				nearstar_z, nearstar_ray, 64, satur);
			}
		}
		else
			farstar = 1;
		//
		if (l_dsd > 100 * nearstar_ray && l_dsd < 1550 * nearstar_ray) {
			ir = ((1600 * nearstar_ray) - l_dsd) / (100 * nearstar_ray);
			if (ir < 0) ir = 0;
			ir += 0x30;
			far_pixel_at (nearstar_x, nearstar_y,
					  nearstar_z, 0, ir);
			far_pixel_at (nearstar_x, nearstar_y,
					  nearstar_z, 0, ir);
			far_pixel_at (nearstar_x, nearstar_y,
					  nearstar_z, 0, ir);
		//} else if (l_dsd>1550*nearstar_ray) {
		//	nearstar_x=0;
		}
		BUFFERCHECK
		
		//
		// Riflessi del protagonista sulla vetrata (rimossi).
		/*
		if (!stspeed) {
			if (ilight) {
				from_user ();
				if (cam_z>-1000) {
					if (alfa>-10&&alfa<10)
						user_drawing_range = 55;
					else
						user_drawing_range = 70;
				}
				else
					user_drawing_range = 40;
				if (beta>-user_drawing_range&&beta<user_drawing_range) {
					cam_x = -4*beta;
					cam_y = 10*alfa;
					cam_z = 0;
					Forward (2*pos_z);
					alfa *= 2; beta *= 2;
					change_angle_of_view ();
					flares = 2;
					user ();
					flares = 0;
				}
			}
		}
		*/
		// Controllo gestore (indicando i comandi con lo sguardo).
		//
		active_screen = -1;
		from_user ();
		leftturn  = 0;
		rightturn = 0;
		infoarea  = 0;
		s_control = 0;
		s_command = 0;
		if (ontheroof) goto jpr;
		do {
			zz = fabs (cam_z);
			xx = fabs (cam_x);
			Forward (zz/2);
		} while (zz>25&&xx<3000);
		if (zz<25) {
			if (cam_x<-44*30) {
				if (cam_x>-68*30) {
					s_control = (cam_y + 25) / 50 + 3;
					if (s_control<1) s_control = 1;
					if (s_control>5) s_control = 5;
					if (select) {
						if (!ap_targetting&&!ip_targetting) {
							aso_countdown = 100;
							sys = s_control;
							dev_page = 0;
						}
					}
				}
			}
			else {
				if (cam_y<-50) {
					if (cam_x<68*30) {
						s_command = (cam_x + 44*30) / (27*30) + 1;
						if (s_command<1) s_command = 1;
						if (s_command>4) s_command = 4;
						if (select) {
							if (!ap_targetting&&!ip_targetting) {
								aso_countdown = 100;
								commands ();
								goto jpr;
							}
						}
					}
				}
				else
					infoarea = 1;
			}
		}
		if (select && pwr > 15000) {
			if (revcontrols) {
				if (cam_x > 2500) {
					dlt_nav_beta += 1.5;
					status ("PITCH - R", 25);
				}
				if (cam_x < -2500) {
					dlt_nav_beta -= 1.5;
					status ("PITCH - L", 25);
				}
			}
			else {
				if (cam_x > 2500) {
					dlt_nav_beta -= 1.5;
					status ("PITCH - L", 25);
				}
				if (cam_x < -2500) {
					dlt_nav_beta += 1.5;
					status ("PITCH - R", 25);
				}
			}
		}
		if (cam_x>2500)
			rightturn = 1;
		if (cam_x<-2500)
			leftturn = 1;
		//
		// Rotazione della navicella.
		// Attivazione schermi.
		//
	   jpr:
		if (!elight) {
			// Paratia destra:
			if (user_beta > -135 && user_beta < -45 && pos_z < -104*15 && pos_z > -262*15 && pos_x > 172*15) {
				active_screen = (pos_z + 104*15) / (-54*15);
			//} else {
				//printf("ok, it thinks we're not facing it. user_beta(%f) pos_z(%f) pos_x(%f) \n", user_beta, pos_z, pos_x);
			}
			// Paratia sinistra:
			//if (user_beta > +45 && user_beta < +135 && pos_z < -104*15 && pos_z > -154*15 && pos_x < -172*15)
				//active_screen = (pos_z + 104*15) / (-54*15) + 2;
		//} else {
			//printf("ok, elight is 0.\n");
		}
		navigation_beta += dlt_nav_beta;
		dlt_nav_beta /= 1.1; if (fabs(dlt_nav_beta)<0.5) dlt_nav_beta = 0;
		if (navigation_beta>=360) navigation_beta -= 360;
		if (navigation_beta<0) navigation_beta += 360;
		//
		// Tracciamento pianeti.
		//
		BUFFERCHECK
		dontDraw=0;
		from_vehicle ();
		planets ();
		BUFFERCHECK
		//
		// Controllo sulle richieste d'aiuto.
		//
		if (helptime && secs>helptime) {
			if (gburst) {
				status ("HELP CAME!", 50);
				gburst = 0;
			}
			if (secs<helptime+120) {
				stz = 0;
				if (secs<helptime+20)
					stz = pow (helptime + 20 - secs, 2) * 2000;
				if (secs>helptime+100)
					stz = pow (helptime + 100 - secs, 2) * 2000;
				if (!stz&&charge<3) charge = 3;
				other_vehicle_at ((stz + 16000) * cos (secs / 10),
						  4000 * sin (secs / 100),
						  (stz + 16000) * sin (secs / 10));
			} else if (!felisian) {
				helptime = 0;
			}
		}/* else if (!felisian) {
			helptime = 0;
		}*/
		

/*		if (RANDOM (300000) == 0 && felisian != 1 && !gburst){
								dist = 1;
								fast_srand (CLOCK());
								helptime = (flandom() * dist) + secs + 5;
								felisian = 1;
					}




		if (felisian == 1){
					if (helptime && secs>helptime) {
						if (secs<helptime+120) {
							status ("VISITOR!", 50);
							stz = 0;
							if (secs<helptime+20)
								stz = pow (helptime + 20 - secs, 2) * 2000;
							if (secs>helptime+100)
								stz = pow (helptime + 100 - secs, 2) * 2000;
							other_vehicle_at ((stz + 16000) * cos (secs / 10),
									  4000 * sin (secs / 100),
									  (stz + 16000) * sin (secs / 10));
						}
						else
						felisian = 0;
		}}

//temporarily removed because of bugs! (Mega)

*/



		#if defined(ALL)
		if (option_multiplayer) {
		#endif
			#if defined(ALL) || defined(MULTIPLAYER)
			//MULTIPLAYER_DISABLED (This comment exists to make it is to find all the code that need to be reenabled to reenable multiplayer) (SL)
			/*
			from_vehicle();
			DrawMultiplayerVehicles();
			*/
			#endif
		#if defined(ALL)
		}
		#endif
		//
		// Tracciamento della navicella.
		//
		BUFFERCHECK
		from_user ();
		BUFFERCHECK
		vehicle (opencapcount);
		BUFFERCHECK
		//
		// Tracciamento riflessi, aggiornamento dello schermo
		// del gestore, tracciamento dello schermo del gestore,
		// reazione visiva agli eventi interni alla navicella.
		//
		if (ontheroof && nohud) goto ext_1;
		from_user ();
		if (ontheroof && !nohud) goto roofie1;
		if (!opencapcount) reflexes ();
		roofie1:
		if (!(CLOCK()%10)) {
			clear_onboard_screen ();
			control (1, "flight control drive");
			control (2, "onboard devices");
			control (3, "preferences");
			control (4, "disable display");
			control (5, "extended");
			switch (sys) {
				case 1: control (1, "FLIGHT CONTROL DRIVE");
					if (sys!=psys) status ("FCS MENU", 50);
					fcs (); break;
				case 2:	control (2, "ONBOARD DEVICES");
					if (sys!=psys) status ("SELECT SUB", 50);
					devices (); break;
				case 3:	control (3, "PREFERENCES");
					if (sys!=psys) status ("PREFS MENU", 50);
					prefs (); break;
				case 4:	control (4, "DISABLE DISPLAY");
					if (sys!=psys) status ("SCREEN OFF", 50);
					break;
				case 5:	control (5, "EXTENDED");
					if (sys!=psys) status ("SELECT SUB", 50);
					extended (); break;
			}
			psys = sys;
		}
		if (ontheroof && !nohud) goto roofie;
		//
		if (!ap_targetting&&!ip_targetting) {
			setfx (4);
			dxx = pos_z / 88;
			if (dxx < -16) dxx = -16;
			entity = dxx;
			screen ();
			setfx (0);
		}
		//
		if (leftturn) {
			arrowcolor = 127 - 16 * (CLOCK()%4);
			digit_at ('-', -2900, -50, 12, arrowcolor, 0);
			if (revcontrols)
				digit_at ('>', -3000, -50, 12, arrowcolor, 0);
			else
				digit_at ('<', -3000, -50, 12, arrowcolor, 0);
		}
		if (rightturn) {
			arrowcolor = 127 - 16 * (CLOCK()%4);
			digit_at ('-', +2900, -50, 12, arrowcolor, 0);
			if (revcontrols)
				digit_at ('<', +3000, -50, 12, arrowcolor, 0);
			else
				digit_at ('>', +3000, -50, 12, arrowcolor, 0);
		}
		//
		// ***** H.U.D. OUTER LAYER *****
		// Fornisce informazioni sullo strato esterno dell'H.U.D.
		// Qualsiasi glifo verr… in seguito trattato con dithering.
		//
		roofie:
		if (active_screen != -1 && !ontheroof) goto nohud_1;
		//
		// Informazioni e schemi addizionali sull'H.U.D.
		// Tracciamento label della stella selezionata.
		// Tracciamento distanza dalla stella selezionata.
		//
		if (ap_targetting || ap_targetted) {
			alfa = 0; beta = 0; change_angle_of_view ();
			cam_x = 450; cam_y = 250; cam_z = -750;
			for (c = 0; c < 24; c++) {
				if (labstar && c == labstar_char) digit_at ('_', -6, -15, 5, 127 - 2 * (CLOCK()%32), 0);
				digit_at (star_label[c], -6, -15, 5, 127, 1);
				cam_x -= 40;
			}
			dxx = dzat_x - ap_target_x;
			dyy = dzat_y - ap_target_y;
			dzz = dzat_z - ap_target_z;
			l_dsd = SQRT (dxx*dxx + dyy*dyy + dzz*dzz) * 5E-5;

			//ldsp_dsd implements a smooth switchover from the interstellar distances to in-system distances, but it is only used for
			//showing the user the distance. l_dsd's actual value will still experience a sudden jump when ap_reached changes, but
			//the user won't see it. (SL)
			double ldisp_dsd = l_dsd;
			if (ldisp_dsd<.05) {
				ldisp_dsd *= 0.002;
			} else if (ldisp_dsd<.5) {
				ldisp_dsd *= ldisp_dsd*2.21777777777778 - .108888888889;
			}
			
			if (ap_reached && ap_target_id == nearstar_identity) l_dsd *= 0.002;	//Previously 0.01. We changed this to make in-system distances sensible. (SL)
			
			sprintf (temp_distance_buffer, "%01.2f", ldisp_dsd);
			cam_x = 450; cam_y = -180; cam_z = -750;
			c = 0; while (temp_distance_buffer[c] != 0) {
				digit_at (temp_distance_buffer[c], -6, -15, 5, 127, 1);
				cam_x -= 40;
				c++;
			}
			cam_x -= 40; digit_at ('L', -6, -15, 5, 112, 1);
			cam_x -= 40; digit_at ('.', -6, -15, 5, 112, 1);
			cam_x -= 40; digit_at ('Y', -6, -15, 5, 112, 1);
			cam_x -= 40; digit_at ('.', -6, -15, 5, 112, 1);
		}
		//
		// Tracciamento label del pianeta selezionato,
		// tracciamento distanza dal pianeta selezionato,
		// aggiornamento nome del pianeta-bersaglio.
		//
		if (ip_targetted!=-1) {
			update_planet_label ();
			alfa = 0; beta = 0; change_angle_of_view ();
			cam_x = 450; cam_y = 180; cam_z = -750;
			for (c = 0; c < 24; c++) {
				if (labplanet && c == labplanet_char) digit_at ('_', -6, -15, 5, 127 - 2 * (CLOCK()%32), 0);
				digit_at (planet_label[c], -6, -15, 5, 112, 1);
				cam_x -= 40;
			}
			planet_xyz (ip_targetted);
			dxx = dzat_x - plx;
			dyy = dzat_y - ply;
			dzz = dzat_z - plz;
			l_dsd = SQRT (dxx*dxx + dyy*dyy + dzz*dzz) * 1E-2;
			//if (IsNaN(l_dsd)) l_dsd=NAN_DSD;
			sprintf (temp_distance_buffer, "%01.2f", l_dsd);
			cam_x = 450; cam_y = -250; cam_z = -750;
			c = 0; while (temp_distance_buffer[c] != 0) {
				digit_at (temp_distance_buffer[c], -6, -15, 5, 120, 1);
				cam_x -= 40;
				c++;
			}
			cam_x -= 40; digit_at ('D', -6, -15, 5, 105, 1);
			cam_x -= 40; digit_at ('Y', -6, -15, 5, 105, 1);
			cam_x -= 40; digit_at ('A', -6, -15, 5, 105, 1);
			cam_x -= 40; digit_at ('M', -6, -15, 5, 105, 1);
			cam_x -= 40; digit_at ('S', -6, -15, 5, 105, 1);
		}
		//
		// Messaggio di reset, lampeggiante.
		//
		if (reset_signal && (reset_signal % 10) < 5) {
			alfa = 0; beta = 0; change_angle_of_view ();
			cam_x = 300; cam_y = 0; cam_z = -750;
			c = 0; while (sr_message[c] != 0) {
				digit_at (sr_message[c], -6, -15, 8, 127, 1);
				cam_x -= 60;
				c++;
			}
		}
		//
		// Tracciamento dello stato attuale dell'FCS.
		//
	   nohud_1: alfa = 0; beta = 0; change_angle_of_view ();
		cam_x = -512; cam_y = -275; cam_z = -750;
		c = strlen(fcs_status_extended) - 1;
		while (c >= 0) {
			digit_at (fcs_status_extended[c], -6, -15, 6, 120, 1);
			cam_x += 45;
			c--;
		}
		//
		// Link alla funzione di ricerca dei targets in real-time.
		//
		if (collecting_targets) {
			status ("SCANNING..", 100);
			collect_targets ();
			if (!collecting_targets) {
				if (targets)
					status ("DONE!", 100);
				else
					status ("NO TARGETS", 100);
			}
		}
		//
		// Visualizzazione/aggiornamento tabella "targets in range".
		//
		if (targets_in_range) {
			if (update_targets) {
				tgts_in_show = 0;
				c = topmost_target;
				while (targets && c < targets && tgts_in_show < 3) {
					#ifdef OLD_STARMAP
					tgt_label_pos = search_id_code (targets_table_id[c], 'S');
					if (tgt_label_pos > -1) {
						smh = OPENFILE (starmap_file, OPEN_RB);
						if (smh ISFILEVALID) {
							FILESEEK (smh, tgt_label_pos + 8, SEEK_SET);
							READFILE (smh, &target_name[tgts_in_show], 24);
							CLOSEFILE (smh);
							tgts_in_show++;
						}
					}
					#else
					#ifdef WINDOWS
					tgt_label_pos = system_labelled(targets_table_sx[c], targets_table_sy[c], targets_table_sz[c], current_galaxy);
					#else
					tgt_label_pos = system_labelled(targets_table_sx[c], targets_table_sy[c], targets_table_sz[c]);
					#endif
					if (tgt_label_pos != -1) {
						#ifdef WINDOWS
						FILE * tmpFile;
						if (current_galaxy==0) {
							tmpFile = fopen(starmap3_file, "rb");
						} else {
							tmpFile = fopen(starmap3b_file, "rb");
						}
						#else
						FILE * tmpFile = fopen(starmap3_file, "rb");
						#endif
						if (tmpFile!=NULL) {
							fseek(tmpFile, tgt_label_pos+5, SEEK_SET);
							fread(&target_name[tgts_in_show], 20, 1, tmpFile);
							target_name[tgts_in_show][20]=' ';
							fclose(tmpFile);
							tgts_in_show++;
						}
					}
					#endif
					c++;
				}
				update_targets = 0;
			}
			cam_x = 175; cam_y = 40; cam_z = -500;
			frame (225, 48, 285, 96, 2, 90);
			cam_y = 8 + 40;
			c = 0;
			while (c < tgts_in_show) {
				cam_x = 35 + 175;
				if (c == target_line)
					frame (226+35, 0, 277, 30, 1, 120);
				for (ir = 0; ir < 24; ir++) {
					digit_at (target_name[c][ir], -5, -10, 3.5, 174, 1);
					cam_x -= 23;
				}
				cam_y -= 55;
				c++;
			}
		}
	   ext_1:	//
		// Anti-aliasing e dithering (error-diffusion).
		// E` un procedimento molto peculiare, che fornisce effetti
		// straordinariamente belli su uno schermo che, di per s‚,
		// Š poco risolutivo, sia fisicamente che cromaticamente.
		//
		if (option_antialias_in_stardrifter){
			QUADWORDS -= 240;
			psmooth_64 (adapted, 200);
			psmooth_64 (adapted, 200);
			QUADWORDS += 240;
		}

		if (lightscale){
				mask_pixels (adapted+2880, 0);
		}



		if (lightscale2){
				mask_pixels (adapted+2880, 64);
		}
		//
		// Tracciamento di tutte le stelle visibili.
		//
		from_vehicle ();
		sky (0x405C);
		//
		// ***** H.U.D. INNER LAYER *****
		// Fornisce informazioni sullo strato interno dell'H.U.D.
		// Qualsiasi glifo non verr… trattato con dithering.
		//
		if (datasheetscroll) {
			areaclear (adapted, 11, 85, 0, 0, 1 + datasheetscroll, 9, 72);
			areaclear (adapted, 11, 95, 0, 0, 1 + datasheetscroll, 40, 112);
			c = (datasheetscroll / 4) - 1;
			if (c > 0) {
				switch (data) {
					case 1: // remote target data
						if (ap_targetted) {
							if (ap_targetted == 1) {
								wrouthud (14, 87, c, star_label);
								tmp_float = GetStarMass(ap_target_class, ap_target_ray, ap_target_x);
								wrouthud (14, 97, c,   "                 RADIUS:");
								wrouthud (14, 97, c,   "PRIMARY MASS:");
								sprintf (outhudbuffer, "                %1.4f", ap_target_ray);
								FitOutHudBuffer(16, 24);
								wrouthud (14, 103, c, outhudbuffer);
								sprintf (outhudbuffer, "%1.8f", tmp_float);
								FitOutHudBuffer(0, 8);
								sprintf (outhudbuffer+strlen(outhudbuffer), " BAL M");
								wrouthud (14, 103, c, outhudbuffer);
								
								wrouthud (14, 109, c, "              CENTIDYAMS");
								
								tmp_float = GetStarSurfaceTemperature(ap_target_class, ap_target_ray, tmp_float);
								wrouthud (14, 116, c, "SURFACE TEMPERATURE:");
								sprintf (outhudbuffer, "%1.0f@K&%1.0f@C&%1.0f@F", tmp_float + 273.15, tmp_float, tmp_float*1.8 + 32);
								wrouthud (14, 122, c, outhudbuffer);
								sprintf (outhudbuffer, "MAJOR BODIES: %d EST.", starnop (ap_target_x, ap_target_y, ap_target_z));
								wrouthud (14, 129, c, outhudbuffer);
							}
							else {
								wrouthud (14, 87, c, "DIRECT PARSIS TARGET");
							}
						}
						else
							wrouthud (14, 87, c, "REMOTE TARGET NOT SET");
						break;
					case 2: // local target data
						if (ip_targetted != -1) {
							wrouthud (14, 87, c, planet_label);
							if (nearstar_p_type[ip_targetted]==10) {
								Word pclass = (nearstar_p_type[ip_targetted]==10)?8:5;
								tmp_float = GetStarMass(pclass, nearstar_p_ray[ip_targetted], nearstar_p_orb_ray[ip_targetted]);
								wrouthud (14, 97, c,   "                 RADIUS:");
								wrouthud (14, 97, c,   "PRIMARY MASS:");
								sprintf (outhudbuffer, "                %1.4f", nearstar_p_ray[ip_targetted]);
								FitOutHudBuffer(16, 24);
								wrouthud (14, 103, c, outhudbuffer);
								sprintf (outhudbuffer, "%1.8f", tmp_float);
								FitOutHudBuffer(0, 8);
								sprintf (outhudbuffer+strlen(outhudbuffer), " BAL M");
								wrouthud (14, 103, c, outhudbuffer);
								
								wrouthud (14, 109, c, "              CENTIDYAMS");
								
								tmp_float = GetStarSurfaceTemperature(pclass, nearstar_p_ray[ip_targetted], tmp_float);
								wrouthud (14, 111, c, "SURF TEMP:");
								sprintf (outhudbuffer, "%1.0f@K&%1.0f@C&%1.0f@F", tmp_float + 273.15, tmp_float, tmp_float*1.8 + 32);
								wrouthud (14, 117, c, outhudbuffer);
								wrouthud (14, 123, c, "PERIOD OF REVOLUTION:");
								tmp_float = rtp (ip_targetted);
								p1 = tmp_float * 1e-9;
								p2 = tmp_float * 1e-6; p2 %= 1000;
								p3 = tmp_float * 1e-3; p3 %= 1000;
								p4 = (Dword)(tmp_float) % 1000;
								if (p1 < 2)
									sprintf (outhudbuffer, "%ld EPOCS, %03ld:%03ld:%03ld", p1, p2, p3, p4);
								else {
									if (p1 < 2047)
										sprintf (outhudbuffer, "%ld EPOCS, %03ld:%03ld:???", p1, p2, p3);
									else
										sprintf (outhudbuffer, "%ld EPOCS, %03ld:???:???", p1, p2);
								}
								wrouthud (14, 129, c, outhudbuffer);
							} else {
								wrouthud (14, 97, c, "PERIOD OF ROTATION:");
								if (nearstar_p_qsortindex[nearstar_nob-1] == ip_targetted) {
									if (nearstar_p_rtperiod[ip_targetted] > 0) {
										p1 = nearstar_p_rtperiod[ip_targetted]; p1 *= 360;
										p2 = p1 / 1000; p2 /= 1000;
										p3 = p1 / 1000; p3 %= 1000;
										p4 = p1 % 1000;
										sprintf (outhudbuffer, "TRIADS %03ld:%03ld:%03ld", p2, p3, p4);
										wrouthud (14, 103, c, outhudbuffer);
									}
									else {
										if (ip_reaching || ip_reached) {
											if (nearstar_p_type[ip_targetted] != 10)
												wrouthud (14, 103, c, "COMPUTING...");
											else
												wrouthud (14, 103, c, "NOT RESOLVABLE");
										}
										else
											wrouthud (14, 103, c, "TOO FAR TO ESTIMATE");
									}
								}
								else
									wrouthud (14, 103, c, "TOO FAR TO ESTIMATE");
								wrouthud (14, 110, c, "PERIOD OF REVOLUTION:");
								tmp_float = rtp (ip_targetted);
								p1 = tmp_float * 1e-9;
								p2 = tmp_float * 1e-6; p2 %= 1000;
								p3 = tmp_float * 1e-3; p3 %= 1000;
								p4 = (long)(tmp_float) % 1000;
								if (p1 < 2)
									sprintf (outhudbuffer, "%ld EPOCS, %03ld:%03ld:%03ld", p1, p2, p3, p4);
								else {
									if (p1 < 2047)
										sprintf (outhudbuffer, "%ld EPOCS, %03ld:%03ld:???", p1, p2, p3);
									else
										sprintf (outhudbuffer, "%ld EPOCS, %03ld:???:???", p1, p2);
								}
								wrouthud (14, 116, c, outhudbuffer);
								//wrouthud (14, 97, c,   "                 RADIUS:");
								
								sprintf (outhudbuffer, "           %s", planetd[nearstar_p_type[ip_targetted]]);
								wrouthud (14, 123, c, outhudbuffer);
								wrouthud (14, 123, c, "RADIUS:");
								
								sprintf (outhudbuffer, "%1.4f", nearstar_p_ray[ip_targetted]);
								FitOutHudBuffer(16, 24);
								sprintf (outhudbuffer+strlen(outhudbuffer), " CENTIDYAMS");
								wrouthud (14, 129, c, outhudbuffer);
								
								
							}
						}
						else
							wrouthud (14, 87, 21, "LOCAL TARGET NOT SET");
						break;
					case 3: // environment data
						wrouthud (14, 87, c, "EXTERNAL ENVIRONMENT");
						//tmp_float = GetStarMass(ap_target_class, ap_target_ray, ap_target_x);
						//tmp_float = GetStarSurfaceTemperature(ap_target_class, ap_target_ray, tmp_float);
									
						wrouthud (14, 97, c, "                     SUN");
						sprintf (outhudbuffer, "                %1.2f", dsd/100);
						FitOutHudBuffer(16, 24);
						wrouthud (14, 103, c, outhudbuffer);
						wrouthud (14, 109, c, "                   DYAMS");
						
						tmp_float = GetOrbitingTemperatureAt(dsd);
						
						if (tmp_float < -269) tmp_float = fast_flandom() - 269;
						
						sprintf (outhudbuffer, "TEMP. %1.2f", tmp_float + 273.15);
						FitOutHudBuffer(6, 13);
						sprintf (outhudbuffer+strlen(outhudbuffer), "@K");
						wrouthud (14, 97, c, outhudbuffer);
						
						sprintf (outhudbuffer, "      %1.2f", tmp_float);
						FitOutHudBuffer(6, 13);
						sprintf (outhudbuffer+strlen(outhudbuffer), "@C");
						wrouthud (14, 103, c, outhudbuffer);
						
						sprintf (outhudbuffer, "      %1.2f", tmp_float*1.8 + 32);
						FitOutHudBuffer(6, 13);
						sprintf (outhudbuffer+strlen(outhudbuffer), "@F");
						wrouthud (14, 109, c, outhudbuffer);
						SRAND (nearstar_identity);
						if (nearstar_class == 6 || nearstar_class == 5) {
							ir = RANDOM (50);
							if (nearstar_class == 5) {
								//ir >>= 2;
								ir -= dsd/5;	//125/dsd;
							} else {
								ir -= dsd/25;	//25/dsd;
							}
							if (ir <= 0) ir = 1;
						}
						else
							ir = 0;
						sprintf (outhudbuffer, "LI+ IONS: %ld MTPD EST.", ir);
						wrouthud (14, 119, c, outhudbuffer);
						tmp_float = 50 + RANDOM (10) - RANDOM (10);
						tmp_float *= (1 - eclipse);
						tmp_float *= 100 / dsd;
						if (nearstar_class == 11) {
							if (gl_start < 90)
								tmp_float *= 75 + RANDOM (50);
							else
								tmp_float *= 50;
						}
						if (nearstar_class == 10) tmp_float *= 0.25;
						if (nearstar_class == 9) tmp_float *= 3;
						if (nearstar_class == 8) tmp_float *= 1.5;
						if (nearstar_class == 7) tmp_float *= 25;
						if (nearstar_class == 6) tmp_float *= 0.01;
						if (nearstar_class == 5) tmp_float *= 0.1;
						if (nearstar_class == 4) tmp_float *= 10;
						if (nearstar_class == 3) tmp_float *= 0.5;
						if (nearstar_class == 2) tmp_float *= 18;
						if (nearstar_class == 1) tmp_float *= 5;
						SRAND (secs);
						tmp_float *= 1
							   + (float)(RANDOM(100)) * 0.001
							   - (float)(RANDOM(100)) * 0.001;
						sprintf (outhudbuffer, "RADIATION: %1.1f KR", tmp_float);
						wrouthud (14, 126, c, outhudbuffer);
						
						break;
					case 4:
						//debug
						wrouthud (14, 87, c, "DEBUG INFO");
						int rarity_factor;
						double distance_from_home;
					
						distance_from_home = SQRT (dzat_x*dzat_x + dzat_z*dzat_z);
						distance_from_home += 30 * fabs(dzat_y);
						rarity_factor = distance_from_home * 0.25e-8;
						double drarity = distance_from_home * 0.25e-8;
						rarity_factor = 1 << rarity_factor;
						rarity_factor--;
						
						sprintf (outhudbuffer, "    %1.8f", distance_from_home);
						FitOutHudBuffer(4, 24);
						wrouthud (14, 103, c, outhudbuffer);
						wrouthud (14, 103, c, "DFH");
					
						sprintf (outhudbuffer, "   %i", (int)rarity_factor);
						wrouthud (14, 109, c, outhudbuffer);
						wrouthud (14, 109, c, "RF");
					
						sprintf (outhudbuffer, "     %1.8f", drarity);
						FitOutHudBuffer(5, 24);
						wrouthud (14, 115, c, outhudbuffer);
						wrouthud (14, 115, c, "DRAR");
						
						if (ip_targetted>-1) {
							if (nearstar_p_type[ip_targetted]==3) {
								Dword gss_seed = (nearstar_p_ray[ip_targetted]
							 	 + nearstar_p_orb_ray[ip_targetted]
							 	 + nearstar_p_orb_orient[ip_targetted]) * 4112;	//I wonder what the 4112 is for (SL)
								SRAND (gss_seed);
								fast_srand (gss_seed);
								Dword ape_probability = 0; //(RANDOM(6)+RANDOM(6)+modRandom(6)+modRandom(6)+modRandom(6));
								for (Word a=0; a<8; a++) {
									ape_probability+=fast_random(1023)+1;
								}
								ape_probability-=4192;
								if (ape_probability>0) {
									ape_probability/=364;
									//ape_probability/=745;
									if (ape_probability>20) ape_probability=20;
								} else {
									ape_probability=0;
								}
								
								sprintf (outhudbuffer, "    %i", (int)ape_probability);
								wrouthud (14, 121, c, outhudbuffer);
								wrouthud (14, 121, c, "C0");
							} else {
								wrouthud (14, 121, c, "NOT FELISIAN");
							}
						} else {
							wrouthud (14, 121, c, "REQ. LOCAL TARGET");
						}
						/*
						sprintf (outhudbuffer, "   %1.8f", speedPC);
						FitOutHudBuffer(3, 24);
						wrouthud (14, 127, c, outhudbuffer);
						wrouthud (14, 127, c, "%C");*/
						break;
					case 5:
						wrouthud (14, 87, c, "SPEED INFO");
						sprintf (outhudbuffer, "%1.4f", (speedCentiDyamsPerS/100.0));
						FitOutHudBuffer(0, 16);
						sprintf(outhudbuffer+strlen(outhudbuffer), " DYAMS/S");
						wrouthud (14, 103, c, outhudbuffer);
						
						sprintf (outhudbuffer, "%1.4f", (speedMetersPerS/1000));
						FitOutHudBuffer(0, 19);
						sprintf(outhudbuffer+strlen(outhudbuffer), " KM/S");
						wrouthud (14, 109, c, outhudbuffer);
						
						sprintf (outhudbuffer, "%1.4f", (speedPC));
						FitOutHudBuffer(0, 20);
						sprintf(outhudbuffer+strlen(outhudbuffer), " * C");
						wrouthud (14, 115, c, outhudbuffer);
						
						wrouthud (14, 121, c, "1C IS THE SPEED OF LIGHT");
						
						sprintf (outhudbuffer, "           %1.4f", (speedWarp));
						FitOutHudBuffer(11, 24);
						wrouthud (14, 127, c, outhudbuffer);
						wrouthud (14, 127, c, "(TOS) WARP ");
						break;
					case 6: // local target data #2
						if (ip_targetted != -1) {
							wrouthud (14, 87, c, planet_label);
							tmp_float = nearstar_p_tilt[ip_targetted];
							sprintf (outhudbuffer, "TILT: %1.4f", tmp_float);
							wrouthud (14, 97, c, outhudbuffer);
							tmp_float = nearstar_p_orb_tilt[ip_targetted];
							sprintf (outhudbuffer, "ORBITAL TILT: %1.4f", tmp_float);
							wrouthud (14, 103, c, outhudbuffer);
							tmp_float = nearstar_p_orb_ecc[ip_targetted];
							wrouthud (14, 109, c, "ORBITAL ECCENTRICITY:");
							sprintf (outhudbuffer, "%1.4f", tmp_float);
							wrouthud (14, 115, c, outhudbuffer);
							if (nearstar_p_owner[ip_targetted] == -1) {
								for (double tick=localTargetTick+0; tick<localTargetTick+1000.0; tick+=0.1) {
									double xx;
									double alfa, beta;
									double p_m, p_riv, ors;
									double tmpPlz, tmpPly, tmpPlx;
									
									ors = nearstar_p_orb_ray[ip_targetted] * nearstar_p_orb_ray[ip_targetted];

									if (nearstar_p_owner[ip_targetted] > -1) {
										xx = nearstar_p_ray[nearstar_p_owner[ip_targetted]];
										p_m = qt_M_PI * xx * xx * xx * 0.44e-4;
										p_riv = SQRT (p_m / ors);
									}
									else
										p_riv = SQRT (s_m / ors);

									beta = (tick * p_riv * M_PI) / 180;
									alfa = nearstar_p_orb_tilt[ip_targetted] * deg;

									xx  = -nearstar_p_orb_ray[ip_targetted] * sin(beta) * cos(alfa);
									tmpPlz =  nearstar_p_orb_ray[ip_targetted] * cos(beta) * cos(alfa);
									tmpPly =  nearstar_p_orb_ray[ip_targetted] * sin(alfa);

									tmpPlz *= nearstar_p_orb_ecc[ip_targetted];

									beta = nearstar_p_orb_orient[ip_targetted];

									tmpPlx = xx * cos(beta) + tmpPlz * sin(beta);
									tmpPlz = tmpPlz * cos(beta) - xx * sin(beta);

									tmpPlx += nearstar_x;
									tmpPly += nearstar_y;
									tmpPlz += nearstar_z;

									if (nearstar_p_owner[ip_targetted] > -1) {
										//moonorigin (nearstar_p_owner[ip_targetted]);
										//tmpPlx += mox;
										//tmpPly += moy;
										//tmpPlz += moz;
									}
									
									double spdxx = nearstar_x - tmpPlx;
									double spdyy = nearstar_y - tmpPly;
									double spdzz = nearstar_z - tmpPlz;
									double spdsdSq = (spdxx*spdxx + spdyy*spdyy + spdzz*spdzz);
									double spl_dsd = SQRT (spdsdSq);
									if (spl_dsd<localTargetMinDist || localTargetMinDist==0) {
										localTargetMinDist = spl_dsd;
									} 
									if (spl_dsd>localTargetMaxDist) {
										localTargetMaxDist = spl_dsd;
									}
								}
								localTargetTick+=10000;
								tmp_float = localTargetMinDist;
								sprintf (outhudbuffer, "MIN DIST: %1.4f", tmp_float);
								wrouthud (14, 121, c, outhudbuffer);
								
								tmp_float = localTargetMaxDist;
								sprintf (outhudbuffer, "MAX DIST: %1.4f", tmp_float);
								wrouthud (14, 127, c, outhudbuffer);
							}
						}
						else
							wrouthud (14, 87, 21, "LOCAL TARGET NOT SET");
						break;
						
				}
			}
		}
		datasheetscroll += datasheetdelta;
		if (datasheetscroll > 100)
			datasheetscroll = 100;
		if (datasheetscroll < 0) {
			datasheetscroll = 0;
			data = 0;
		}
		if (about) {		 //about page & help page.
			ShowAboutPage(False);
		}
		if (sptype) { //planet type indicator
			ShowPTYPE();
		}
		/*
		if (mooses == 0) {
			Moose();
			mooses = 1;
		}
		ShowMoose(moosepage);
		*/
		
		if (helpison) {
			ShowMoose(0, 1, 1, 1);
			//ShowMoose(0, 1, 0, 0); //use single text file
		}
		
		/*if (newmessage) {
                        show_newmessage(helpmessageID);
                }*/
		//
		// Croce di puntamento planetaria.
		//
		BUFFERCHECK
		if ((ip_targetted != -1 && !ip_reached) || ip_targetting) {
			planet_xyz (ip_targetted);
			if (far_pixel_at (plx, ply, plz, 0, 1)) {
				asm {
					#ifdef WINDOWS
					push edi
					mov edi, [adapted]
					add edi, vptr
					sub edi, 640
					mov al, 126
					mov [edi-7], al
					mov [edi-6], al
					mov [edi-5], al
					mov [edi-4], al
					mov [edi+4], al
					mov [edi+5], al
					mov [edi+6], al
					mov [edi+7], al
					mov [edi-320*7], al
					mov [edi-320*6], al
					mov [edi-320*5], al
					mov [edi-320*4], al
					mov [edi+320*4], al
					mov [edi+320*5], al
					mov [edi+320*6], al
					mov [edi+320*7], al
					pop edi
					#else
					les di, dword ptr adapted
					add di, vptr
					sub di, 640
					mov al, 126
					mov es:[di-7], al
					mov es:[di-6], al
					mov es:[di-5], al
					mov es:[di-4], al
					mov es:[di+4], al
					mov es:[di+5], al
					mov es:[di+6], al
					mov es:[di+7], al
					mov es:[di-320*7], al
					mov es:[di-320*6], al
					mov es:[di-320*5], al
					mov es:[di-320*4], al
					mov es:[di+320*4], al
					mov es:[di+320*5], al
					mov es:[di+320*6], al
					mov es:[di+320*7], al
					#endif
				}
			}
		}
		BUFFERCHECK
		//
		// Croce di puntamento della stella-bersaglio,
		// aggiornamento nome della stella-bersaglio,
		// spostamenti interstellari suplucsi.
		//
		dxx = dzat_x - ap_target_x;
		dyy = dzat_y - ap_target_y;
		dzz = dzat_z - ap_target_z;
		double dsdSq = (dxx*dxx + dyy*dyy + dzz*dzz);
		l_dsd = SQRT (dsdSq);
		//FIXED: If you are stuck in +NAN LY land, you should be able to get out now. (SL)
		if (IsNaN(l_dsd)) {
			l_dsd=NAN_DSD;
			dzat_x = ap_target_x;
			dzat_y = ap_target_y;
			dzat_z = ap_target_z+NAN_DSD;
		}
		if (ap_targetting || l_dsd>10000) {
			pointer_cross_for (ap_target_x,
					   ap_target_y,
					   ap_target_z);
		}
		if (option_center_outerring_pointer)
			centerouter_cross ();
		if (option_x_axis_pointer)
			x_axis();
		if (option_y_axis_pointer)
			y_axis();
		if (option_z_axis_pointer)
			z_axis();
		BUFFERCHECK
		if (ap_targetting || ap_targetted) {
			update_star_label ();
			if (stspeed == 1 && ip_vimana==0) {
				if (ap_targetted == -1)
					ras = 75000;	//Increasing the distance away from parsis targs when we start - was 25000 originally. (SL)
				else {
					if (anti_rad)
						ras = 44 * ap_target_ray;
					else
						ras = 1.5 * ap_target_ray;
					if (l_dsd < 20000 && nsnp) {
						npcs = -12345;	//FIXED the duplicate-appearance planets in separate systems bug (SL)
						prepare_nearstar (COPY_NEARSTAR_FROM_AP_TARGET);
						nsnp = 0;
					}
				}
				if (l_dsd < ras) {
					if (ap_targetted == -1) {
						if (l_dsd+l_dsd<ras) {
							dxx=ap_target_x+ras; dzz=0;
							l_dsd = SQRT (dxx*dxx + dyy*dyy + dzz*dzz);
							status ("ALIGNING", 50);
							requested_vimana_coefficient =   0.005 * l_dsd;
							vimana_reaction_time = 0.01;
							goto ap_drive_mode;
						} else if (abs(ap_target_y-dzat_y)<1000) {
							status ("CALIBRATED", 50);
							ap_reached = 1;
							stspeed = 0;
						} else {
							dxx=0; dzz=0;
							l_dsd = SQRT (dxx*dxx + dyy*dyy + dzz*dzz);
							status ("ALIGNING", 50);
							requested_vimana_coefficient =   0.005 * l_dsd;
							vimana_reaction_time = 0.01;
							goto ap_drive_mode;
						}
					} else {
						status ("CALIBRATED", 50);
						ap_reached = 1;
						#ifdef WINDOWS
						if (vimana_shield==3) {
							vimana_shield = 0;
						}
						#endif
						stspeed = 0;
					}
				}
				else {
					if (l_dsd > 0.9999 * ap_target_initial_d) {
						requested_vimana_coefficient =   0.001 * l_dsd;
						status ("CHARGING", 0);
						vimana_reaction_time = 0.1;
						goto ap_drive_mode;
					}
					if (l_dsd < 7500 + ras) {
						requested_vimana_coefficient =   0.005 * l_dsd;
						status ("PARKING", 0);
						vimana_reaction_time = 0.01;
						goto ap_drive_mode;
					}
					if (l_dsd < 15000 + ras) {
						requested_vimana_coefficient =   0.005 * l_dsd;
						status ("LINKING", 0);
						vimana_reaction_time = 0.0025;
						goto ap_drive_mode;
					}
					if (l_dsd < 0.9990 * ap_target_initial_d) {
						requested_vimana_coefficient = 0.00001 * l_dsd;
						status ("DRIVING", 0);
						vimana_reaction_time = 0.05;
						goto ap_drive_mode;
					}
					requested_vimana_coefficient = 0.0002 * l_dsd;
					status ("IGNITION", 0);
					if (vimana_reaction_time != 0.08)
						vimana_reaction_time = 0.08;
				ap_drive_mode:
					current_vimana_coefficient +=
						(requested_vimana_coefficient -
						 current_vimana_coefficient)
						 * vimana_reaction_time;
					if (current_vimana_coefficient < 10)
						current_vimana_coefficient = 10;
					dzat_x -= dxx / current_vimana_coefficient;
					dzat_y -= dyy / current_vimana_coefficient;
					dzat_z -= dzz / current_vimana_coefficient;
					pwr    -= l_dsd * 1E-5;
				}
			}
		}
		BUFFERCHECK
		//
		// Sincronizzazione della navicella con i moti planetari,
		// spostamenti interplanetari suplucsi.
		//
	   resynctoplanet:
		if (ip_targetted != -1 && pwr > 15000) {
			planet_xyz (ip_targetted);
			dxx = dzat_x - plx;
			dyy = dzat_y - ply;
			dzz = dzat_z - plz;
			if (ip_reached && sync) {
				status ("TRACKING", 0);
				if (sync==1) { // fixed-point chase
					ang = (double)deg * (double)navigation_beta;
					hold_z = 1.8;
				}
				if (sync==2) { // far chase
					ang = (double)deg * (double)navigation_beta;
					hold_z = 5.4;
				}
				if (sync==3) { // syncrone orbit
					ang = (double)nearstar_p_rotation[ip_targetted] * (double)deg;
					hold_z = 1.8 + 0.1 * nearstar_p_ray[ip_targetted];
				}
				if (sync==4) { // high-speed orbit
					ang = 7 * secs * (double)deg;
					hold_z = 3.6;
				}
				if (sync==5) { // near chase
					ang = (double)deg * (double)navigation_beta;
					hold_z = 1.2;
				}
				if (sync==6) { // high-speed near chase
					ang = 7 * secs * (double)deg;
					hold_z = 1.2;
				}
				
				dxx += hold_z * nearstar_p_ray[ip_targetted] * sin (ang);
				dzz -= hold_z * nearstar_p_ray[ip_targetted] * cos (ang);
				if (_delay < 5) {
					dzat_x -= dxx * 0.05;
					dzat_y -= dyy * 0.05;
					dzat_z -= dzz * 0.05;
				}
				else {
					dzat_x -= dxx;
					dzat_y -= dyy;
					dzat_z -= dzz;
				}
					
			}
			if (ip_reaching) {
				l_dsd = SQRT (dxx*dxx + dyy*dyy + dzz*dzz);
				//if (IsNaN(l_dsd)) l_dsd=NAN_DSD;
				double ray2 = 2*nearstar_p_ray[ip_targetted];
				if (l_dsd > 0.99999 * ip_target_initial_d) {
					/*if (ip_vimana==2) {
					//if (l_dsd>2000+ray2) {
						ip_vimana=1;
						requested_vimana_coefficient =   0.001 * l_dsd;
						status ("CHARGING", 0);
						vimana_reaction_time = 0.1;
						stspeed = 1;
						goto ap_drive_mode2;
					} else {*/
						ip_vimana=0;
						requested_approach_coefficient =  25 * l_dsd;
						status ("WARMING UP", 0);
						reaction_time = 0.001;
						goto ip_drive_mode;
					//}
				}
				if (ip_vimana==2) {
					if (l_dsd>2000+ray2) {
						ip_vimana=1;
						requested_vimana_coefficient =   0.001 * l_dsd;
						status ("VIMANA", 20);
						vimana_reaction_time = 0.1;
						stspeed = 1;
						goto ap_drive_mode2;
					} else {
						status ("TOO CLOSE FOR VIMANA", 20);
						ip_vimana=0;
					}
				}
				if (ip_vimana==1) {
					if (l_dsd < 10000 + ray2) {
						requested_vimana_coefficient =   0.005 * l_dsd;
						status ("PARKING", 0);
						vimana_reaction_time = 0.01;
						goto ap_drive_mode2;
					} else if (l_dsd < 30000 + ray2) {
						requested_vimana_coefficient =   0.005 * l_dsd;
						status ("LINKING", 0);
						vimana_reaction_time = 0.0025;
						goto ap_drive_mode2;
					} else if (l_dsd < 0.9990 * ip_target_initial_d) {
						requested_vimana_coefficient = 0.00001 * l_dsd;
						status ("DRIVING", 0);
						vimana_reaction_time = 0.05;
						goto ap_drive_mode2;
					}
					requested_vimana_coefficient = 0.0002 * l_dsd;
					status ("IGNITION", 0);
					if (vimana_reaction_time != 0.08)
						vimana_reaction_time = 0.08;
				ap_drive_mode2:
					current_vimana_coefficient +=
						(requested_vimana_coefficient -
						 current_vimana_coefficient)
						 * vimana_reaction_time;
					if (current_vimana_coefficient < 10)
						current_vimana_coefficient = 10;
					if (l_dsd < 2000+ray2) {
						stspeed=0;
						ip_vimana=0;
						fix_local_target ();
						/*ip_target_initial_d = l_dsd;
						requested_approach_coefficient =  25 * l_dsd;
						status ("WARMING UP", 0);
						reaction_time = 0.001;
						goto ip_drive_mode;*/
					} else {
						dzat_x -= dxx / current_vimana_coefficient;
						dzat_y -= dyy / current_vimana_coefficient;
						dzat_z -= dzz / current_vimana_coefficient;
						
						pwr    -= l_dsd * 1E-5;
					}
				} else {
					if (l_dsd < 25 && ip_target_initial_d > 500) {
						requested_approach_coefficient =  50 * l_dsd;
						status ("REFINING", 0);
						reaction_time = 0.0002;
						goto ip_drive_mode;
					}
					if (l_dsd < 100 && ip_target_initial_d > 500) {
						requested_approach_coefficient =  15 * l_dsd;
						status ("BRAKING", 0);
						reaction_time = 0.0003;
						goto ip_drive_mode;
					}
					if (l_dsd < 0.99500 * ip_target_initial_d) {
						requested_approach_coefficient = 0.05 * l_dsd;
						status ("APPROACH", 0);
						reaction_time = 0.025;
						goto ip_drive_mode;
					}
					requested_approach_coefficient = 1.5 * l_dsd;
					status ("IGNITION", 0);
					reaction_time = 0.05;
					goto ip_drive_mode;
					
					
				ip_drive_mode:
					current_approach_coefficient +=
						(requested_approach_coefficient -
						 current_approach_coefficient)
						 * reaction_time;
					if (current_approach_coefficient < 10)
						current_approach_coefficient = 10;
					dzat_x -= dxx / current_approach_coefficient;
					dzat_z -= dzz / current_approach_coefficient;
					dzat_y -= dyy / (0.5 * current_approach_coefficient);
					pwr    -= l_dsd * 0.5E-5;
					if (l_dsd < ray2) {
						status ("STANDBY", 0);
						ip_reaching = 0;
						ip_reached = 1;
					}
				}
			}
		}
		BUFFERCHECK
		//
		// Gestione del consumo di litio.
		// Consumi supplementari, gestione ricariche.
		//
		additional_consumes ();
		//
		// Calcolo della distanza dalla stella pi— vicina,
		// per il controllo su radiazioni, eclissi, temperatura.
		//
		dxx = dzat_x - nearstar_x;
		dyy = dzat_y - nearstar_y;
		dzz = dzat_z - nearstar_z;
		dsd = SQRT (dxx*dxx + dyy*dyy + dzz*dzz) + 1;
		dsdSq = dsd*dsd;
		//DebugPrintf(0, "nearstar_x=%f, nearstar_y=%f, nearstar_z=%f dsd=%f", nearstar_x, nearstar_y, nearstar_z, dsd);
		
		//
		// Allontanamento d'emergenza della navicella dalla stella.
		//
		if (dsd < (0.44+(double)(2*anti_rad))*nearstar_ray) {
			status ("CORRECTION", 100);
			dzat_x += (dxx / dsd) * 0.1;
			dzat_y += (dyy / dsd) * 0.1;
			dzat_z += (dzz / dsd) * 0.1;
		}
		//
		// Manovre di approvvigionamento litio dallo spazio
		// attorno alle stelle di classe 5 o a certe di classe 6.
		// Le stelle di classe 6 sono pi— difficili da sfruttare,
		// ma danno i migliori risultati. Quelle di classe 5 sono
		// sempre adatte, ma con scarsi risultati.
		//
		BUFFERCHECK
		if (lithium_collector) {
			SRAND (nearstar_identity);
			ir = RANDOM (50);
			if (nearstar_class == 5) {
				ir -= dsd/125;	//125/dsd;
				if (ir <= 0) ir = 1;
			}
			else
				ir -= dsd/25;	//25/dsd;
			if (ir > 0) {
				if (pwr >= 20000 && charge >= 120) {
					status ("! FULL !", 100);
					lithium_collector = 0;
				}
				else {
					pwr += ir;
					if (pwr >= 20000) {
						if (charge < 120) {
							pwr = 15001;
							charge++;
						}
						else
							pwr = 20000;
					}
					status ("SCOPING...", 25);
				}
			}
			else {
				status ("GET CLOSER", 100);
				if (!reset_signal) lithium_collector = 0;
			}
		}
		//
		// Controllo eclissi.
		//
		stz = dzz * cos (deg * navigation_beta)
		    - dxx * sin (deg * navigation_beta)
		    - fabs (dyy) / 2;
		if (stz>dsd) stz = dsd;
		if (stz<0) stz = 0;
		stz /= 1.25;
		ras = (105 * nearstar_ray) / dsd;
		if (ras>66) ras = 66;
		if (ras<1) ras = 1;
		eclipse = 0;
		cur_eclipse=0;
		for (c=0; c<nearstar_nob; c++) {
		 if (nearstar_p_type[c]!=-1) {
			planet_xyz (c);
			dxx = dzat_x - plx;
			dyy = dzat_y - ply;
			dzz = dzat_z - plz;
			dpz = SQRT (dxx*dxx + dyy*dyy + dzz*dzz) + 0.001;
			if (dpz<10*nearstar_p_ray[c]) {
				watch (dzat_x, dzat_y, dzat_z,
				       nearstar_x, nearstar_y, nearstar_z);
				change_angle_of_view ();
				if (xy (dzat_x, dzat_y, dzat_z, plx, ply, plz)) {
					dasp = SQRT (delta_x * delta_x + delta_y * delta_y);
					rap = (105 * nearstar_p_ray[c]) / dpz;
					if (rap>66) rap = 66;
					eclipse = (dasp + ras - rap) / (2 * ras);
					if (eclipse>1) eclipse = 1;
					if (eclipse<0) eclipse = 0;
					eclipse = 1 - eclipse;
					if (eclipse>cur_eclipse) {
						cur_eclipse=eclipse;
					}
				}
			}
		 }
		}
		//
		// Reazione alle eclissi (oscura le tinte della navicella).
		// E abbassa la temperatura interna. Solo un po', perch‚ Š
		// contrastata dalla climatizzazione.
		//
		//
		BUFFERCHECK
		fast_srand (secs/2);
		#if defined(ALL)
		if (option_temperature==0) {
		#endif
		#if defined(ALL) || !defined(TEMPERATURE)
			pp_temp = 90 - dsd * 0.33;
			pp_temp -= 44;
			pp_temp *= fabs(pp_temp * 0.44);
			pp_temp -= (pp_temp + 273.15) * eclipse;
			if (pp_temp < -269) pp_temp = fast_flandom() - 269;
		#endif
		#if defined(ALL)
		} else {
		#endif
			#if defined(ALL) || defined(TEMPERATURE)
			pp_temp = GetOrbitingTemperatureAt(dsd);
			if (pp_temp < -269) pp_temp = fast_flandom() - 269;
	
			#endif
		#if defined(ALL)
		}
		#endif
		//outside_pp_temp = pp_temp;
		if (!ontheroof) {
			if (pp_temp < 0) pp_temp = 0;
			if (pp_temp > 40) pp_temp = 40;
			while (pp_temp < 14) pp_temp += fast_flandom() * 2.5;
			while (pp_temp > 32) pp_temp -= fast_flandom() * 2.5;
			l_dsd = (24 * nearstar_ray) / (dsd - stz);
			//if (IsNaN(l_dsd)) l_dsd=NAN_DSD;
			l_dsd -= l_dsd * eclipse; pp_temp += l_dsd;
			if (pp_temp > 40) pp_temp = 40;
			while (pp_temp > 38) pp_temp -= fast_flandom() * 2.5;
			pp_pressure = 1;
		}
		else
			pp_pressure = 0;
		//
		ilight += ilightv;
		if (ilight<0) ilight = 0;
		if (ilight>63) ilight = 63;
		l_dsd = (15 * nearstar_ray * nearstar_r) / (dsd - stz);
		//if (IsNaN(l_dsd)) l_dsd=NAN_DSD;
		l_dsd -= l_dsd * eclipse;
		if (elight)
			ir3 = ilight + 30 - CLOCK()%30 + l_dsd;
		else
			ir3 = ilight / 4 + l_dsd;
		if (ir3>nearstar_r+16) ir3 = nearstar_r+16;
		if (nearstar_class==11&&gl_start<90) ir = 5 * ir3;
		if (ir3>63) ir3 = 63;
		l_dsd = (7 * nearstar_ray * nearstar_g) / (dsd - stz);
		//if (IsNaN(l_dsd)) l_dsd=NAN_DSD;
		l_dsd -= l_dsd * eclipse;
		if (elight)
			ig3 = (ilight + 30 - CLOCK()%30) / 2 + l_dsd;
		else
			ig3 = ilight / 2 + l_dsd;
		if (ig3>nearstar_g+32) ig3 = nearstar_g+32;
		if (nearstar_class==11&&gl_start<90) ig3 = 5 * ig3;
		if (ig3>63) ig3 = 63;
		l_dsd = (7 * nearstar_ray * nearstar_b) / (dsd - stz);
		//if (IsNaN(l_dsd)) l_dsd=NAN_DSD;
		l_dsd -= l_dsd * eclipse;
		if (elight)
			ib3 = (ilight + 30 - CLOCK()%30) / 4 + l_dsd;
		else
			ib3 = ilight + l_dsd;
		if (nearstar_class==11&&gl_start<90) ib3 = 5 * ib3;
		if (ib3>63) ib3 = 63;
		if (gburst > 0 && gburst < 5) {
			ir3 += 8 * gburst;
			ig3 += 8 * gburst;
			ib3 += 8 * gburst;
		}
		if (ir3 != ir3e || ig3 != ig3e || ib3 != ib3e) {
			tavola_colori (range8088, 0, 64, ir3, ig3, ib3);
			ir3e = ir3; ig3e = ig3; ib3e = ib3;
		}
		//
		// Controllo del flag di richiesta di atterraggio.
		//
		if (land_now) {
			land_now = 0;
			landing_point = 0;
			holdtomiddle = 1;
			opencapdelta = 2;
			right_dblclick = 0;
			status ("UNLOCKING", 50);
		}
		//
		// Avanzamento contatore per le richieste d'aiuto.
		//
		if (gburst > 0) {
			gburst--;
			if (!gburst) {
				gburst = 63;
				status ("SIGNAL", 50);
			}
		}
		//
		// Countdown per il delay dei messaggi di stato dell'FCS.
		//
		if (fcs_status_delay)
			fcs_status_delay--;
		//
		// Countdown per il delay della funzione auto-sleep.
		//
		if (autoscreenoff) {
			aso_countdown--;
			if (aso_countdown <= 0) {
				aso_countdown = 100;
				sys = 4;
			}
		}
		//
		// Il protagonista sta sempre in una tutina... Š normale.
		// Vede le cose attraverso uno scafandro, non ingombrante
		// ma pur sempre uno scafandro. La funzione "surrounding"
		// disegna i bordi dello scafandro, illuminati in relazione
		// all'ambiente circostante.
		//
		surrounding (0, 180);
		// riduzione stanchezza (continua, eventualmente
		// dall'ultima volta che si Š scesi in superficie)
		// e variazioni nelle pulsazioni, pi— verosimili...
		fast_srand (secs/2);
		tiredness *= 0.9977;
		pp_pulse = (1 + tiredness) * 118;
		pp_pulse += fast_flandom () * 8;
		pp_pulse -= fast_flandom () * 8;
		// se si sta per scendere o si Š appena risaliti,
		// si deve trattenere il player nel mezzo della navicella,
		// in quanto si suppone che sia bloccato nella capsula.
		if (holdtomiddle || lifter) {
			pos_x *= 0.75;
			hold_z = pos_z + 3100;
			pos_z -= hold_z * 0.25;
		}
		// effetto di apertura della capsula:
		// quando Š totalmente aperta, si pu• scendere.
		// LQ significa Last Quadrant (ultimo quadrante visitato)
		if (opencapdelta < 0) {
			opencapcount += opencapdelta;
			if (opencapcount <= 0) {
				opencapdelta = 0;
				holdtomiddle = 0;
				sprintf (temp_distance_buffer, "LQ %03d:%03d", landing_pt_lon, landing_pt_lat);
				status (temp_distance_buffer, 100);
			}
		}
		// effetto di chiusura della capsula:
		// quando Š totalmente sigillata, scotty beam me down.
		// al ritorno, comincia a riaprire la capsula...
		BUFFERCHECK
		if (opencapdelta > 0) {
			opencapcount += opencapdelta;
			if (opencapcount >= 85) {
				if (ip_targetted==-1) {
					status("LOST PLANET LOCK!", 500);
				} else {
					opencapcount = 86;	//Fix so we don't wind up on 0.60 on the planet after a crash. (SL)
					opencapdelta = -2;
					freeze();
					BUFFERCHECK
					RecalcPlanetStuff(1);
					BUFFERCHECK
					entryflag = 0; planetary_main ();
					BUFFERCHECK
					//goto pretendtohavehadsurfacebin;
					if (exitflag) goto allstop;
					opencapcount = 86;
					opencapdelta = -2;
					holdtomiddle = 1;
					pp_gravity = 1;
					resolve = 0;
					_delay = 13; // solo al ritorno da superficie
					goto resynctoplanet;
				}
				opencapdelta = -2;
				
			}
		}
		//
		// Page swap.
		//
		QUADWORDS = 16000;
		if (_delay == 13) _delay = 0;
		
		
		/*	//TEMPORARY (for testing the changes to the albedo formula) (SL)
		char temptmp[120];
		sprintf(temptmp, "RAW ALBEDO %i ALBEDO %i OLD ALBEDO %i RAINY %3.3f", raw_albedo, albedo, old_albedo, rainy);
		wrouthud(0, 50, NULL, temptmp);
		*/
		
		BUFFERCHECK
		if (!_delay) {
			#ifdef WINDOWS
			WinBlit();
			#else
			pcopy (adaptor, adapted);
			#endif
		} else {
			pcopy (adapted, adapted);
			if (_delay>0 && _delay<10) _delay--;
		}
		BUFFERCHECK
		QUADWORDS = pqw;
		if (resolve == 1) {
		 while (resolve <= 63) {
			tavola_colori (return_palette, 0, 256,
				       resolve, resolve, resolve);
			ir = CLOCK(); while (ir == CLOCK()) {}
			resolve+=4;
			#ifdef WINDOWS
			//WinCycle();
			#endif
		 }
		}
		BUFFERCHECK
		if (resolve == 0)
			resolve = 1;
		//
		// Questa sezione controlla i pixels a ciclo continuo
		// che raffigurano le correnti convettive interne alle stelle,
		// ma entra in azione solo se la stella Š abbastanza vicina,
		// altrimenti non si vede che un globo bianco: i colori
		// delle stelle non sono propriamente colori, ma solo tenui
		// sfumature; in pratica, essendo quasi tutte ben oltre il
		// livello di saturazione dell'occhio, le stelle appaiono
		// in genere tutte bianche, a meno che non le si avvicini
		// davvero moltissimo.
		//
		if (dsd < 1000 * nearstar_ray) {
			ir = nearstar_r;
			ig = nearstar_g;
			ib = nearstar_b;
			c = nearstar_class;
			if (c == 8) {
				fast_srand (nearstar_identity);
				SRAND (fast_random(0x7FFF));
				c = RANDOM (star_classes);
				ir = class_rgb[c * 3 + 0];
				ig = class_rgb[c * 3 + 1];
				ib = class_rgb[c * 3 + 2];
			}
			switch (c) {
				case 0:
					ir2 = 64;
					ig2 = 54;
					ib2 = 28;
					break;
				case 1:
					ir2 = 36;
					ig2 = 50;
					ib2 = 64;
					break;
				case 2:
					ir2 = 24;
					ig2 = 32;
					ib2 = 48;
					break;
				case 3:
					ir2 = 64;
					ig2 = 24;
					ib2 = 12;
					break;
				case 4:
					ir2 = 64;
					ig2 = 40;
					ib2 = 32;
					break;
				case 5:
					ir2 = 28;
					ig2 = 20;
					ib2 = 12;
					break;
				case 6:
					ir2 = 32;
					ig2 = 32;
					ib2 = 32;
					break;
				case 7:
					ir2 = 32;
					ig2 = 44;
					ib2 = 64;
					break;
				case 8:
					ir2 = 64;
					ig2 = 60;
					ib2 = 32;
					break;
				case 9:
					fast_srand (nearstar_identity);
					ir2 = 32 + fast_random(31);
					ig2 = 32 + fast_random(31);
					ib2 = 16 + fast_random(31);
					break;
				case 10:
					ir2 = 32;
					ig2 = 26;
					ib2 = 22;
					break;
				case 11:
					ir2 = 36;
					ig2 = 48;
					ib2 = 64;
			}
			satur = (6.4 * dsd) / nearstar_ray;
			if (satur > 44) satur = 44;
			if (ir<satur) ir = satur;
			if (ig<satur) ig = satur;
			if (ib<satur) ib = satur;
			if (ir2<satur) ir2 = satur;
			if (ig2<satur) ig2 = satur;
			if (ib2<satur) ib2 = satur;
		}
		else {
			ir = 48;
			ig = 56;
			ib = 64;
			ir2 = 24;
			ig2 = 32;
			ib2 = 40;
		}
		if (ire == ir && ige == ig && ibe == ib &&
		    ir2e == ir2 && ig2e == ig2 && ib2e == ib2) {
			if (!sky_palette_ok) {
				sky_palette_ok = 1;
				goto last_sky_palette_redefinition;
			}
		}
		else {
			sky_palette_ok = 0;
			last_sky_palette_redefinition:
			if (ire < ir) ire++; if (ire > ir) ire--;
			if (ige < ig) ige++; if (ige > ig) ige--;
			if (ibe < ib) ibe++; if (ibe > ib) ibe--;
			if (ir2e < ir2) ir2e++; if (ir2e > ir2) ir2e--;
			if (ig2e < ig2) ig2e++; if (ig2e > ig2) ig2e--;
			if (ib2e < ib2) ib2e++; if (ib2e > ib2) ib2e--;
			shade (tmppal, 64+00, 24, 0, 0, 0, ir2e, ig2e, ib2e);
			shade (tmppal, 64+24, 16, ir2e, ig2e, ib2e, ire, ige, ibe);
			shade (tmppal, 64+40, 24, ire, ige, ibe, 64, 70, 76);
			tavola_colori (tmppal + 3*64, 64, 64, 63, 63, 63);
		}
		if (!farstar) {
			for (ir = 0; ir < 64800; ir++) {
				ig = (s_background[ir] + 1) % 64;
				ib = (s_background[ir] >> 6) << 6;
				s_background[ir] = ig + ib;
			}
			//QUADWORDS = 16200;
			//pcycle (s_background, 1);
			//QUADWORDS = pqw;
		}
		//
		BUFFERCHECK
		if ((ontheroof && option_speedup<1) || (!ontheroof && option_speedup<2)) {
			//status("NOT SPED UP", 20);
			sync_stop ();
		//} else {
			//status ("SPED UP", 20);
		}
		//
		// Hook per la gestione dei moti delle caratteristiche
		// di superficie dei pianeti (come le macchie che si
		// spostano e la turbolenza atmosferica): l'hook aggiorna
		// l'aspetto della superficie una volta ogni 5 minuti.
		//
		if (ip_targetted!=-1&&ip_reached) {
			if ((Dword)secs%300 == 0)
				npcs = -12345;
		}
		//
		// Input da tastiera: snapshot, fine sessione,
		// selezione bersagli, attribuzione labels etc...
		//
		if (ontheroof && nohud) {
			if (tasto_premuto()) {
				c = attendi_pressione_tasto();
				if (c==0) {
					c = attendi_pressione_tasto();
					if (c==83) {
						snapshot (0, 0);
					}
				} else {
					if (c=='*') snapshot (0, 1);
					if (c=='b') {
						snapshot (0, 0);
					}
					if (c==92) {
						nohud = 0;
						status("HUD ON", 50);
					}
				}
			} else {
				c = 0;
			}
			goto endmain;
		}
		//
		// non saprei...
		// un'istruzione di debug,
		// o la lascio come "codice segreto"?
		// fa istantaneamente il pieno di litio.
		//
		/*ir = ctrlkeys[0];
		ir &= 0x70;
		if (ir == 0x70) {
			charge = 120;
			pwr = 20000;
			ctrlkeys[0] = 0x20;
		}*/
		//
		// Comandi da tastiera.
		//
		if (goesk_e != -1) { // && active_screen == -1) { (removed because it b0rked GOESVIEWSCREEN keys)
			c = goesk_e; goesk_e = -1;
			goto goesk_e_reentry;
		}
		if (goesk_a != -1) { // && active_screen == -1) { (removed because it b0rked GOESVIEWSCREEN keys)
			c = goesk_a; goesk_a = -1;
			goto goesk_a_reentry;
		}

		if (active_screen == -1 && tasto_premuto()) {
			while (tasto_premuto()) {
				c = attendi_pressione_tasto();
				if (!c) {	//Extended keys
					c = attendi_pressione_tasto();
					goesk_e_reentry:
					if (targets_in_range) {
						if (c == 80) {
							if (target_line < 2) {
								if (topmost_target + target_line < targets - 1)
									target_line ++;
							}
							else {
								if (topmost_target < targets - 3) {
									topmost_target ++;
									update_targets = 1;
								}
							}
						}
						if (c == 72) {
							if (target_line > 0)
								target_line --;
							else {
								if (topmost_target > 0) {
									topmost_target --;
									update_targets = 1;
								}
							}
						}
						goto endmain;
					}
					if (c==75) {
						dlt_nav_beta += 1.5;
						status ("PITCH - R", 25);
						//fprintf(stderr, "PITCH-R\n");
						//printf("pitch changed. active_screen=%i elight=%i hitjpr=%i pos_z=%f user_beta=%f pos_x=%f.", (int)active_screen, (int)elight, hitjpr, pos_z, user_beta, pos_x);
					}
					if (c==77) {
						dlt_nav_beta -= 1.5;
						status ("PITCH - L", 25);
						//fprintf(stderr, "PITCH-L\n");
					}
					if (c==72) {
							//Disabled for now (SL)
						/*double outsideTemp = GetOrbitingTemperatureAt(dsd);
						if (outsideTemp>50000.0) {
							status ("TOO HOT!", 25);
						} else {
							lifter = -100;
						}*/
						
						lifter = -100;
					}
			         	if (c==0x3B){								// f1 - HELP & ABOUT
						if (about == 0){
							about = 1;
							sptype = 0;
							helpison = 0;
						}
						else {
							about = 0;
						}
					}
			         	if (c==0x3C){								// f2 - PTYPE indicator
						if (sptype == 0){
							sptype = 1;
							about = 0;
							helpison = 0;
						}
						else {
							sptype = 0;
						}
					}
					if (c==0x86){
                                         showplanet = (showplanet + 1);
                                         if (showplanet > 2) {
                                            showplanet = 0;
                                         }
                                        }
					if (c==83) {
						snapshot (0, 0);
					}
				if (c==0x43){								// f9 - help(/textreader, in the future)
					if (helpison == 1){
						helpison = 0;
						sptype = 0;
						about = 0;
					}
					else {
						helpison = 1;
						if (helppage == 0) {
							Moose("..\\DOCS\\help1.txt");
							helppage = 1;
							//Moose("..\\DOCS\\help.txt",helppage); //use single text file
						}
						about = 0;
						//portablegoes = 0;
					}
				}
					/*if (c==144) {
						Moose();
						moosepage++;
					}
					if (c==142) {
						moosepage--;
					}*/
				} else {	//Non-extended keys
					goesk_a_reentry:
					if (c=='*') {
						snapshot (0, 1);
						goto endmain;
					}
					if (data || about) {
						if (c == 27) {
							c = 0;
							datasheetdelta = -2;
							about=0;
							goto endmain;
						}
					}
					if (c==92 && ontheroof) {
						if (nohud == 0) {
							nohud = 1;
							status("HUD ON", 50);
						} else {
							nohud = 0;
							status("HUD OFF", 50);
						}
					}
					if (ap_targetting) {
						if (c == 27) {
							c = 0;
							ap_targetting = 0;
							ap_targetted = 0;
							status ("CANCELLED", 50);
							goto endmain;
						}
					}
				if (helpison == 1) {
					if (c=='+' || c=='-') {
						if (c=='+')
							helppage++;
						if (c=='-')
							helppage--;
						//sprintf (filetouse, "..\\DOCS\\help%i.txt" , helppage); //ACKBUGS
						//Moose(filetouse);                                       //ACKBUGS
						//ShowMoose(0, 1, 1, 0);

						//Moose("..\\DOCS\\help.txt",helppage);		//use single text file
						//ShowMoose(0, 1, 0, 0);						//use single text file
						goto endmain;
					}
				}
					if (labstar) {
						if (c == 27) {
							c = 0;
							labstar = 0;
							ap_target_previd = -1;
							goto endmain;
						}
						if (c >= 32 && c <= 126 && labstar_char < 20) {
							if (c >= 'a' && c <= 'z') c -= 32;
							star_label[labstar_char] = c;
							labstar_char++;
						}
						if (c == 8 && labstar_char > 0) {
							labstar_char--;
							star_label[labstar_char] = 32;
						}
						if (c == 13) {
							dev_page = 3;
							s_command = 1;
							dev_commands ();
						}
						goto endmain;
					}
					if (labplanet) {
						if (c == 27) {
							c = 0;
							labplanet = 0;
							prev_planet_id = -1;
							goto endmain;
						}
						if (c >= 32 && c <= 126 && labplanet_char < 20) {
							if (c >= 'a' && c <= 'z') c -= 32;
							planet_label[labplanet_char] = c;
							labplanet_char++;
						}
						if (c == 8 && labplanet_char > 0) {
							labplanet_char--;
							planet_label[labplanet_char] = 32;
						}
						if (c == 13) {
							dev_page = 3;
							s_command = 2;
							dev_commands ();
						}
						goto endmain;
					}
					if (targets_in_range) {
						if (c == 27) {
							c = 0;
							targets_in_range = 0;
							goto endmain;
						}
						if (c == 13) {
							if (!collecting_targets && topmost_target + target_line < targets) {
								ap_target_x = targets_table_px[topmost_target + target_line];
								ap_target_y = targets_table_py[topmost_target + target_line];
								ap_target_z = targets_table_pz[topmost_target + target_line];
								#ifndef OLD_STARMAP
								ap_target_sx = targets_table_sx[topmost_target + target_line];
								ap_target_sy = targets_table_sy[topmost_target + target_line];
								ap_target_sz = targets_table_sz[topmost_target + target_line];
								#endif
								extract_ap_target_infos ();
								fix_remote_target ();
							}
							goto endmain;
						}
					}
					if (ip_targetting) {
						if (c == 27) {
							c = 0;
							ip_targetted = -1;
							ip_targetting = 0;
							ip_reaching = 0;
							status ("CANCELLED", 50);
							goto endmain;
						}
						if (c == 8 && iptargetchar > 0) {
							iptargetchar--;
							iptargetstring[iptargetchar] = 0;
							status (iptargetstring, 100);
						}
						if (((c >= '0' && c <= '9') || c == '/') && iptargetchar < 10) {
							if (c == '/') {
								if (iptargetchar == 0) goto endmain;
								ir = 0;
								while (ir < iptargetchar) {
									if (iptargetstring[ir] == '/') goto endmain;
									ir++;
								}
							}
							iptargetstring[iptargetchar] = c;
							iptargetstring[iptargetchar+1] = 0;
							iptargetchar++;
							status (iptargetstring, 100);
						}
						if (c == 13) {
							if (iptargetchar == 0) goto endmain;
							ir = 0;
							while (ir < iptargetchar) {
								if (iptargetstring[ir] == '/') {
									iptargetstring[ir] = 0;
									iptargetmoon = atoi (iptargetstring);
									iptargetstring[ir] = '/';
									if (iptargetstring[ir + 1] != 0) {
										iptargetplanet = atoi (iptargetstring + ir + 1);
										goto searchmoon;
									}
									status ("NOT EXTANT", 100);
									goto endmain;
								}
								ir++;
							}
							iptargetplanet = atoi (iptargetstring);
							if (iptargetplanet > 0 && iptargetplanet <= nearstar_nop) {	//FIXED the 'target nonexistant planet' bug (from entering 128 or the like) (SL)
								ip_targetted = iptargetplanet - 1;
								fix_local_target ();
								ip_targetting = 0;
							}
							status ("NOT EXTANT", 100);
							goto endmain;
						searchmoon:	ir = 0;
							while (ir < nearstar_nob) {
								if (nearstar_p_owner[ir] == iptargetplanet-1 && nearstar_p_moonid[ir] == iptargetmoon-1) {
									ip_targetted = ir;
									fix_local_target ();
									ip_targetting = 0;
									goto endmain;
								}
								ir++;
							}
							status ("NOT EXTANT", 100);
						}
						goto endmain;
					}
					if (manual_target) {
						if (c == 27) {
							c = 0;
							manual_target = 0;
							ap_targetted = 0;
							status ("CANCELLED", 50);
							goto endmain;
						}
						if (c == 8 && mt_string_char > 0) {
							mt_string_char--;
							switch (mt_coord) {
								case 0: manual_x_string[mt_string_char] = 0;
									break;
								case 1: manual_y_string[mt_string_char] = 0;
									break;
								case 2: manual_z_string[mt_string_char] = 0;
							}
						}
						if ((c >= '0' && c <= '9' && mt_string_char < 14) || (c == '-' && mt_string_char == 0)) {
							switch (mt_coord) {
								case 0: manual_x_string[mt_string_char] = c;
									manual_x_string[mt_string_char+1] = 0;
									break;
								case 1: manual_y_string[mt_string_char] = c;
									manual_y_string[mt_string_char+1] = 0;
									break;
								case 2: manual_z_string[mt_string_char] = c;
									manual_z_string[mt_string_char+1] = 0;
							}
							mt_string_char++;
						}
						if (c == 13) {
							switch (mt_coord) {
								case 0: ap_target_x = atol (manual_x_string);
									#ifndef OLD_STARMAP
									ap_target_sx=0x7FFFFFFF;
									#endif
									manual_y_string[0] = 0; break;
								case 1: ap_target_y = - atol (manual_y_string);
									#ifndef OLD_STARMAP
									ap_target_sy=0x7FFFFFFF;
									#endif
									manual_z_string[0] = 0; break;
								case 2: ap_target_z = atol (manual_z_string);
									#ifndef OLD_STARMAP
									ap_target_sz=0x7FFFFFFF;
									#endif
									break;
							}
							mt_string_char = 0;
							mt_coord ++;
							if (mt_coord > 2) {
								manual_target = 0;
								TargetParsisOrStar();
								
							}
						}
						switch (mt_coord) {
							case 0: sprintf (temp_distance_buffer, "%s", manual_x_string);
								break;
							case 1: sprintf (temp_distance_buffer, "%s", manual_y_string);
								break;
							case 2: sprintf (temp_distance_buffer, "%s", manual_z_string);
						}
						if (mt_coord <= 2)
							status (temp_distance_buffer, 100);
						goto endmain;
					}
					if (!ap_targetting&&!ip_targetting) {
						aso_countdown = 100;
						if (option_controlset == 1) {
      						   switch (c) {
							case '1': sys = 1; dev_page = 0; break;
							case '2': sys = 2; dev_page = 0; break;
							case '3': sys = 3; dev_page = 0; break;
							case '4': sys = 4; dev_page = 0; break;
							case '5': sys = 5; dev_page = 0; break;
							case '6': s_command = 1; commands (); break;
							case '7': s_command = 2; commands (); break;
							case '8': s_command = 3; commands (); break;
							case '9': s_command = 4; commands (); break;
       							}
                                                } else {
                                                   switch (c) {
							case '5': sys = 1; dev_page = 0; break;
							case 'r': sys = 2; dev_page = 0; break;
							case 'd': sys = 3; dev_page = 0; break;
							case 'x': sys = 4; dev_page = 0; break;
							case '4': sys = 5; dev_page = 0; break;
							case '6': s_command = 1; commands (); break;
							case '7': s_command = 2; commands (); break;
							case '8': s_command = 3; commands (); break;
							case '9': s_command = 4; commands (); break;
						   }
						}
					}
					if ((c=='+' || c=='=') && showplanet == 0 && surlight < 63) surlight++;
					if (c=='-' && showplanet == 0 && surlight > 10) surlight--;
					if ((c=='+' || c=='=') && showplanet == 1 && showplanetadd < 8) showplanetadd++;
					if (c=='-' && showplanet == 1 && showplanetadd > 0) showplanetadd--;
					if (c==109 && showplanet == 1) {
                                          showplanetmode = showplanetmode + 1;
                                          if (showplanetmode > 1) {
                                            showplanetmode = 0;
                                          }
                                        }
                                         if (c==110 && showplanet == 1) {
                                          nightisoff = nightisoff + 1;
                                          if (nightisoff > 1) {
                                            nightisoff = 0;
                                          }
                                          RecalcPlanetStuff(1);
                                        }
					if (!ap_targetting&&!ip_targetting) {
						if (c==104){							// h - help request
							Uchar tmp_dev_page = dev_page;
							Uchar tmp_s_command = s_command;
							dev_page = 4;
							s_command = 2;
							dev_commands();
							s_command = tmp_s_command;
							dev_page = tmp_dev_page;
						}
						if (c==115){							// s - scope for lithium
							Uchar tmp_dev_page = dev_page;
							Uchar tmp_s_command = s_command;
							dev_page = 4;
							s_command = 3;
							dev_commands();
							s_command = tmp_s_command;
							dev_page = tmp_dev_page;
						}
						if ((option_controlset == 1 && c==114) || (option_controlset == 0 && c==116))  {				        // r/t - set remote target
							Uchar tmp_s_command = s_command;
							s_command=1;
							fcs_commands();
							s_command=tmp_s_command;
						}
						if (c==118) {							// v - vimana flight
							Uchar tmp_s_command = s_command;
							s_command=2;
							fcs_commands();
							s_command=tmp_s_command;
						}
						if (c==108) {							// L - set local target
							Uchar tmp_s_command = s_command;
							s_command=3;
							fcs_commands();
							s_command=tmp_s_command;
						}
					}

					if (c==105) {							// i - set internal light
						if (ilight == 0) {
							ilight += 1;
							ilightv = 1;
						} else {
							ilight -= 1;
							ilightv = -1;
						}
					}
					if (c==101) {    	 					// e - environment data
						Uchar tmp_dev_page = dev_page;
						Uchar tmp_s_command = s_command;
						dev_page = 2;
						s_command = 4;
						dev_commands();
						s_command = tmp_s_command;
						dev_page = tmp_dev_page;
					}
					if (c==113) {		 					// q - remote target data
						Uchar tmp_dev_page = dev_page;
						Uchar tmp_s_command = s_command;
						dev_page = 2;
						s_command = 2;
						dev_commands();
						s_command = tmp_s_command;
						dev_page = tmp_dev_page;
					}
					if (c==119) {							// w - local target data
						Uchar tmp_dev_page = dev_page;
						Uchar tmp_s_command = s_command;
						dev_page = 2;
						s_command = 3;
						dev_commands();
						s_command = tmp_s_command;
						dev_page = tmp_dev_page;
					}
					/*if (c=='d') {							// d - debug data
						Uchar tmp_dev_page = dev_page;
						Uchar tmp_s_command = s_command;
						dev_page = 2;
						s_command = 5;
						dev_commands();
						s_command = tmp_s_command;
						dev_page = tmp_dev_page;
					}*/
					if (c=='z') {							// z - speed data
						Uchar tmp_dev_page = dev_page;
						Uchar tmp_s_command = s_command;
						dev_page = 2;
						s_command = 6;
						dev_commands();
						s_command = tmp_s_command;
						dev_page = tmp_dev_page;
					}

					if (c==9) {								// TAB - antialiasing on/off
						if (option_antialias_in_stardrifter == 0) {
							option_antialias_in_stardrifter = 1;
						} else {
							option_antialias_in_stardrifter = 0;
						}
					}
					/*if (c=='a') {
						if (newmessage) {
							if (helpmessageID == 8) {
								helpmessageID = 0;
								newmessage = 0;
								goto endmessage;
							}
							if (helpmessageID == 6)
								helpmessageID = 8;
							if (helpmessageID == 4)
								helpmessageID = 6;
							if (helpmessageID == 1)
								helpmessageID = 4;
							if (helpmessageID == 0)
								helpmessageID = 1;
							endmessage:						

							if (helpmessageID == 3) {
								helpmessageID = 0;
								newmessage = 0;
							}					
							
							if (helpmessageID == 7) {
								helpmessageID = 0;
								newmessage = 0;
							}
							if (helpmessageID == 5)
								helpmessageID = 7;
							if (helpmessageID == 2)
								helpmessageID = 5;

						}
					}*/
					if (c=='b') {
						//if (!newmessage)
							snapshot (0, 0);
							/*else {
								if (helpmessageID == 0)
									helpmessageID = 2;
							}*/
					}
                                        if (c=='o') charge = charge - 1;
                                        if (c=='p') charge = charge + 1;
					if (c=='c') {
						//if (!newmessage) {
							if (cloudFilter==0) {
								cloudFilter=1;
					            npcs=-12345; resident_map1=-1; resident_map2=-1;
					            status("CLOUD FILTER ON", 50);
							} else if (cloudFilter==1) {
								cloudFilter=0;
								npcs=-12345; resident_map1=-1; resident_map2=-1;
								status("CLOUD FILTER OFF", 50);
							}
					    /*} else {
                           if (helpmessageID == 0)
                                helpmessageID = 3;
						}*/
					}
					if ((option_controlset == 1 && c==120) || (option_controlset == 0 && c==102)) {                     // x/f - terrain filter on/off
                                          	if (terrainFilter==0) {
							terrainFilter=1;
							npcs=-12345; resident_map1=-1; resident_map2=-1;
							status("TERRAIN FILTER ON", 50);
						} else if (terrainFilter==1) {
							terrainFilter=0;
							npcs=-12345; resident_map1=-1; resident_map2=-1;
							status("TERRAIN FILTER OFF", 50);
						}
					}
					if (c==47) {							// SLASH - lightscaling on/off
						if (lightscale == 0) {
							lightscale = 1;
							lightscale2 = 0;
						} else {
							lightscale = 0;
						}
					}
		
					if (c==63) {							// shift + shash (?) - advanced lightscaling on/off
						if (lightscale2 == 0) {
							lightscale2 = 1;
							lightscale = 0;
						} else {
							lightscale2 = 0;
						}
					}
				}
	endmain:
			#ifdef WINDOWS
			0;
			#endif
			}
		BUFFERCHECK
			
		}
		else
			c = 0;
		if (secspassed>=2) {
			/*
			//BEGIN TEMPORARY periodic snapshot code (SL)
			//Also see the declaration of tsecspassed.
			
			tsecspassed += secspassed;
			if (tsecspassed>30) {
				tsecspassed=0;
				snapshot (0, 1);
			}
			//END TEMPORARY periodic snapshot code
			*/
			
			distTravelledX = dzat_x-olddzat_x;
			distTravelledY = dzat_y-olddzat_y;
			distTravelledZ = dzat_z-olddzat_z;
			distTravelled = SQRT(distTravelledX*distTravelledX+distTravelledY*distTravelledY+distTravelledZ*distTravelledZ);
			speedCentiDyamsPerS = distTravelled / secspassed;
			speedMetersPerS = (distTravelled*CentidyamsToKilometers) / secspassed;
			double distTravelled2 = distTravelled * 5E-5;
			
			//ldsp_dsd implements a smooth switchover from the interstellar distances to in-system distances, but it is only used for
			//showing the user the distance. l_dsd's actual value will still experience a sudden jump when ap_reached changes, but
			//the user won't see it. (SL)
			double ldisp_dsd = distTravelled2;
			if (ldisp_dsd<.05) {
				ldisp_dsd *= 0.002;
			} else if (ldisp_dsd<.5) {
				ldisp_dsd *= ldisp_dsd*2.21777777777778 - .108888888889;
			}
			//ldisp_dsd is now in light years
			
			speedPC = (ldisp_dsd*LightYearsToLightSeconds) / secspassed;
			if (speedPC==0) {
				speedWarp=0;
			} else {
				speedWarp = pow((double)speedPC, (double)1/3);
				//1.8378279472878E-10 * (speedPC*speedPC*speedPC) + -2.2903721341513E-6*(speedPC*speedPC) + .0075578946613514*speedPC+2.5546585057447;
			}
			secspassed=0;
			olddzat_x=dzat_x; olddzat_y=dzat_y; olddzat_z=dzat_z;
		}
		BUFFERCHECK
		#ifdef WINDOWS
		//WinCycle();
		#endif
		
	} while ((c != 27 && !restart) || stspeed || ip_reaching || lifter);
	remove (surface_file);
	BUFFERCHECK
	
	allstop:
	_80_25_C ();
	if (restart) {
		frestart = fopen(restart_txt, "wt");
		if (frestart!=NULL) {
			fputc('Y', frestart);
			fclose(frestart);
		}
	}
	freeze ();
	#ifdef WINDOWS
	NgCleanup();
	ExitToWindows();
	#endif
	//XMS stuff for testing. (SL)
	//XmsFreeAll();
}
