shithub: qk2

Download patch

ref: 8717f3339df1de4076c311b02b077bd2449f2f7c
parent: 710f779fdacf57a6311c62c6e29a5e8e18576c3f
author: Konstantinn Bonnet <[email protected]>
date: Fri Mar 13 14:20:47 EDT 2015

make compilable/loadable and deal with 2c(1) warnings

- include (most) global definitions everywhere
- remove redundant definitions
- remove redefined types
- remove Q_stricmp, use Q_strcasecmp instead
- _DATE_ → "Nov 30 1997"
- #define random() → #define qrandom() since cpp would also replace
  occurances of just "random"

net_udp.c is bullshit, mkfile is broken, sound doesn't work.
some amd64-specific bugs.
ctf is mostly untouched.

--- a/client/cdaudio.h
+++ b/client/cdaudio.h
@@ -17,8 +17,7 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-
-int		CDAudio_Init(void);
+int	CDAudio_Init(void);
 void	CDAudio_Shutdown(void);
 void	CDAudio_Play(int track, qboolean looping);
 void	CDAudio_Stop(void);
--- a/client/cl_cin.c
+++ b/client/cl_cin.c
@@ -17,7 +17,11 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-#include "client.h"
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 
 typedef struct
 {
@@ -407,7 +411,6 @@
 			nodenum = cin.numhnodes1[nodenum];
 		}
 		nodenum = hnodes[nodenum*2 + (inbyte&1)];
-		inbyte >>=1;
 	}
 
 	if (input - in.data != in.count && input - in.data != in.count+1)
@@ -554,7 +557,7 @@
 
 	if (!cl.cinematicpalette_active)
 	{
-		re.CinematicSetPalette(cl.cinematicpalette);
+		re.CinematicSetPalette((uchar *)cl.cinematicpalette);
 		cl.cinematicpalette_active = true;
 	}
 
@@ -561,8 +564,7 @@
 	if (!cin.pic)
 		return true;
 
-	re.DrawStretchRaw (0, 0, viddef.width, viddef.height,
-		cin.width, cin.height, cin.pic);
+	re.DrawStretchRaw (0, 0, vid.width, vid.height, cin.width, cin.height, cin.pic);
 
 	return true;
 }
--- a/client/cl_ents.c
+++ b/client/cl_ents.c
@@ -19,7 +19,11 @@
 */
 // cl_ents.c -- entity parsing and management
 
-#include "client.h"
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 
 
 extern	struct model_s	*cl_mod_powerscreen;
@@ -36,7 +40,7 @@
 =========================================================================
 */
 
-#if 0
+/* the following are commented out in release
 
 typedef struct
 {
@@ -63,6 +67,8 @@
 	}
 }
 
+*/
+
 /*
 =====================
 CL_ParseProjectiles
@@ -70,6 +76,7 @@
 Flechettes are passed as efficient temporary entities
 =====================
 */
+/*
 void CL_ParseProjectiles (void)
 {
 	int		i, c, j;
@@ -146,6 +153,7 @@
 		}
 	}
 }
+*/
 
 /*
 =============
@@ -153,6 +161,7 @@
 
 =============
 */
+/*
 void CL_AddProjectiles (void)
 {
 	int		i, j;
@@ -189,7 +198,7 @@
 		V_AddEntity (&ent);
 	}
 }
-#endif
+*/
 
 /*
 =================
@@ -199,7 +208,7 @@
 =================
 */
 int	bitcounts[32];	/// just for protocol profiling
-int CL_ParseEntityBits (unsigned *bits)
+int CL_ParseEntityBits (int *bits)
 {
 	unsigned	b, total;
 	int			i;
@@ -389,7 +398,7 @@
 {
 	int			newnum;
 	int			bits;
-	entity_state_t	*oldstate;
+	entity_state_t	*oldstate = nil;
 	int			oldindex, oldnum;
 
 	newframe->parse_entities = cl.parse_entities;
@@ -668,9 +677,9 @@
 
 	memset (&cl.frame, 0, sizeof(cl.frame));
 
-#if 0
+/*
 	CL_ClearProjectiles(); // clear projectiles for new frame
-#endif
+*/
 
 	cl.frame.serverframe = MSG_ReadLong (&net_message);
 	cl.frame.deltaframe = MSG_ReadLong (&net_message);
@@ -722,7 +731,7 @@
 
 	// read areabits
 	len = MSG_ReadByte (&net_message);
-	MSG_ReadData (&net_message, &cl.frame.areabits, len);
+	MSG_ReadData (&net_message, cl.frame.areabits, len);
 
 	// read playerinfo
 	cmd = MSG_ReadByte (&net_message);
@@ -738,10 +747,10 @@
 		Com_Error (ERR_DROP, "CL_ParseFrame: not packetentities");
 	CL_ParsePacketEntities (old, &cl.frame);
 
-#if 0
+/*
 	if (cmd == svc_packetentities2)
 		CL_ParseProjectiles();
-#endif
+*/
 
 	// save the frame off in the backup array for later delta comparisons
 	cl.frames[cl.frame.serverframe & UPDATE_MASK] = cl.frame;
@@ -1353,7 +1362,6 @@
 {
 	int			i;
 	float		lerp, backlerp;
-	centity_t	*ent;
 	frame_t		*oldframe;
 	player_state_t	*ps, *ops;
 
@@ -1371,7 +1379,6 @@
 		|| abs(ops->pmove.origin[2] - ps->pmove.origin[2]) > 256*8)
 		ops = ps;		// don't interpolate
 
-	ent = &cl_entities[cl.playernum+1];
 	lerp = cl.lerpfrac;
 
 	// calculate the origin
@@ -1469,9 +1476,9 @@
 	CL_CalcViewValues ();
 	// PMM - moved this here so the heat beam has the right values for the vieworg, and can lock the beam to the gun
 	CL_AddPacketEntities (&cl.frame);
-#if 0
+/*
 	CL_AddProjectiles ();
-#endif
+*/
 	CL_AddTEnts ();
 	CL_AddParticles ();
 	CL_AddDLights ();
--- a/client/cl_fx.c
+++ b/client/cl_fx.c
@@ -19,7 +19,11 @@
 */
 // cl_fx.c -- entity effects parsing and management
 
-#include "client.h"
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 
 void CL_LogoutEffect (vec3_t org, int type);
 void CL_ItemRespawnParticles (vec3_t org);
@@ -942,7 +946,7 @@
 		p->accel[2] = -PARTICLE_GRAVITY;
 		p->alpha = 1.0;
 
-		p->alphavel = -1.0 / (0.5 + frand()*0.3);
+		p->alphavel = -1.0 / (0.5 + qfrand()*0.3);
 	}
 }
 
@@ -981,7 +985,7 @@
 		p->accel[2] = -PARTICLE_GRAVITY;
 		p->alpha = 1.0;
 
-		p->alphavel = -1.0 / (0.5 + frand()*0.3);
+		p->alphavel = -1.0 / (0.5 + qfrand()*0.3);
 	}
 }
 
@@ -1021,7 +1025,7 @@
 		p->accel[2] = PARTICLE_GRAVITY;
 		p->alpha = 1.0;
 
-		p->alphavel = -1.0 / (0.5 + frand()*0.3);
+		p->alphavel = -1.0 / (0.5 + qfrand()*0.3);
 	}
 }
 
@@ -1094,9 +1098,9 @@
 		else
 			p->color = 0xe0 + (rand()&7);	// yellow
 
-		p->org[0] = org[0] - 16 + frand()*32;
-		p->org[1] = org[1] - 16 + frand()*32;
-		p->org[2] = org[2] - 24 + frand()*56;
+		p->org[0] = org[0] - 16 + qfrand()*32;
+		p->org[1] = org[1] - 16 + qfrand()*32;
+		p->org[2] = org[2] - 24 + qfrand()*56;
 
 		for (j=0 ; j<3 ; j++)
 			p->vel[j] = crand()*20;
@@ -1105,7 +1109,7 @@
 		p->accel[2] = -PARTICLE_GRAVITY;
 		p->alpha = 1.0;
 
-		p->alphavel = -1.0 / (1.0 + frand()*0.3);
+		p->alphavel = -1.0 / (1.0 + qfrand()*0.3);
 	}
 }
 
@@ -1145,7 +1149,7 @@
 		p->accel[2] = -PARTICLE_GRAVITY*0.2;
 		p->alpha = 1.0;
 
-		p->alphavel = -1.0 / (1.0 + frand()*0.3);
+		p->alphavel = -1.0 / (1.0 + qfrand()*0.3);
 	}
 }
 
@@ -1182,7 +1186,7 @@
 		p->accel[2] = -PARTICLE_GRAVITY;
 		p->alpha = 1.0;
 
-		p->alphavel = -0.8 / (0.5 + frand()*0.3);
+		p->alphavel = -0.8 / (0.5 + qfrand()*0.3);
 	}
 }
 
@@ -1227,7 +1231,7 @@
 		p->accel[2] = PARTICLE_GRAVITY*4;
 		p->alpha = 1.0;
 
-		p->alphavel = -0.3 / (0.5 + frand()*0.3);
+		p->alphavel = -0.3 / (0.5 + qfrand()*0.3);
 	}
 }
 
@@ -1270,7 +1274,7 @@
 		p->accel[2] = -PARTICLE_GRAVITY;
 		p->alpha = 1.0;
 
-		p->alphavel = -1.0 / (0.5 + frand()*0.3);
+		p->alphavel = -1.0 / (0.5 + qfrand()*0.3);
 	}
 }
 
@@ -1313,7 +1317,7 @@
 		p->time = cl.time;
 
 		p->alpha = 1.0;
-		p->alphavel = -1.0 / (0.3+frand()*0.2);
+		p->alphavel = -1.0 / (0.3+qfrand()*0.2);
 		p->color = 0xe0;
 		for (j=0 ; j<3 ; j++)
 		{
@@ -1363,7 +1367,7 @@
 		p->time = cl.time;
 
 		p->alpha = 1.0;
-		p->alphavel = -1.0 / (0.8+frand()*0.2);
+		p->alphavel = -1.0 / (0.8+qfrand()*0.2);
 		p->color = 115;
 		for (j=0 ; j<3 ; j++)
 		{
@@ -1413,7 +1417,7 @@
 		p->time = cl.time;
 
 		p->alpha = 1.0;
-		p->alphavel = -1.0 / (0.8+frand()*0.2);
+		p->alphavel = -1.0 / (0.8+qfrand()*0.2);
 		p->color = color;
 		for (j=0 ; j<3 ; j++)
 		{
@@ -1487,7 +1491,7 @@
 			if (flags & EF_GIB)
 			{
 				p->alpha = 1.0;
-				p->alphavel = -1.0 / (1+frand()*0.4);
+				p->alphavel = -1.0 / (1+qfrand()*0.4);
 				p->color = 0xe8 + (rand()&7);
 				for (j=0 ; j<3 ; j++)
 				{
@@ -1500,7 +1504,7 @@
 			else if (flags & EF_GREENGIB)
 			{
 				p->alpha = 1.0;
-				p->alphavel = -1.0 / (1+frand()*0.4);
+				p->alphavel = -1.0 / (1+qfrand()*0.4);
 				p->color = 0xdb + (rand()&7);
 				for (j=0; j< 3; j++)
 				{
@@ -1513,7 +1517,7 @@
 			else
 			{
 				p->alpha = 1.0;
-				p->alphavel = -1.0 / (1+frand()*0.2);
+				p->alphavel = -1.0 / (1+qfrand()*0.2);
 				p->color = 4 + (rand()&7);
 				for (j=0 ; j<3 ; j++)
 				{
@@ -1591,7 +1595,7 @@
 			p->time = cl.time;
 
 			p->alpha = 1.0;
-			p->alphavel = -1.0 / (1+frand()*0.2);
+			p->alphavel = -1.0 / (1+qfrand()*0.2);
 			p->color = 0xdc + (rand()&3);
 			for (j=0 ; j<3 ; j++)
 			{
@@ -1651,7 +1655,7 @@
 		VectorMA (dir, s, up, dir);
 
 		p->alpha = 1.0;
-		p->alphavel = -1.0 / (1+frand()*0.2);
+		p->alphavel = -1.0 / (1+qfrand()*0.2);
 		p->color = clr + (rand()&7);
 		for (j=0 ; j<3 ; j++)
 		{
@@ -1681,7 +1685,7 @@
 		VectorClear (p->accel);
 
 		p->alpha = 1.0;
-		p->alphavel = -1.0 / (0.6+frand()*0.2);
+		p->alphavel = -1.0 / (0.6+qfrand()*0.2);
 		p->color = 0x0 + rand()&15;
 
 		for (j=0 ; j<3 ; j++)
@@ -1732,7 +1736,7 @@
 
 		p->time = cl.time;
 		p->alpha = 0.5;
-		p->alphavel = -1.0 / (0.3 + frand() * 0.2);
+		p->alphavel = -1.0 / (0.3 + qfrand() * 0.2);
 		p->color = 0xe4 + (rand()&3);
 
 		for (j=0; j<3; j++)
@@ -1795,7 +1799,7 @@
 		p->time = cl.time;
 
 		p->alpha = 1.0;
-		p->alphavel = -1.0 / (1+frand()*0.2);
+		p->alphavel = -1.0 / (1+qfrand()*0.2);
 		p->color = 4 + (rand()&7);
 		for (j=0 ; j<3 ; j++)
 		{
@@ -1815,15 +1819,16 @@
 ===============
 */
 
-#define	BEAMLENGTH			16
+#define	BEAMLENGTH	16
+
 void CL_FlyParticles (vec3_t origin, int count)
 {
 	int			i;
 	cparticle_t	*p;
 	float		angle;
-	float		sr, sp, sy, cr, cp, cy;
+	float		sp, sy, cp, cy;
 	vec3_t		forward;
-	float		dist = 64;
+	float		dist;
 	float		ltime;
 
 
@@ -1846,9 +1851,11 @@
 		angle = ltime * avelocities[i][1];
 		sp = sin(angle);
 		cp = cos(angle);
+		/*
 		angle = ltime * avelocities[i][2];
 		sr = sin(angle);
 		cr = cos(angle);
+		*/
 	
 		forward[0] = cp*cy;
 		forward[1] = cp*sy;
@@ -1917,15 +1924,14 @@
 ===============
 */
 
-#define	BEAMLENGTH			16
 void CL_BfgParticles (entity_t *ent)
 {
 	int			i;
 	cparticle_t	*p;
 	float		angle;
-	float		sr, sp, sy, cr, cp, cy;
+	float		sp, sy, cp, cy;
 	vec3_t		forward;
-	float		dist = 64;
+	float		dist;
 	vec3_t		v;
 	float		ltime;
 	
@@ -1945,9 +1951,11 @@
 		angle = ltime * avelocities[i][1];
 		sp = sin(angle);
 		cp = cos(angle);
+		/*
 		angle = ltime * avelocities[i][2];
 		sr = sin(angle);
 		cr = cos(angle);
+		*/
 	
 		forward[0] = cp*cy;
 		forward[1] = cp*sy;
@@ -2025,7 +2033,7 @@
 		p->time = cl.time;
 
 		p->alpha = 1.0;
-		p->alphavel = -1.0 / (0.3+frand()*0.2);
+		p->alphavel = -1.0 / (0.3+qfrand()*0.2);
 		p->color = 0xe0;
 		for (j=0 ; j<3 ; j++)
 		{
@@ -2121,7 +2129,7 @@
 		p->accel[2] = -PARTICLE_GRAVITY;
 		p->alpha = 1.0;
 
-		p->alphavel = -0.8 / (0.5 + frand()*0.3);
+		p->alphavel = -0.8 / (0.5 + qfrand()*0.3);
 	}
 }
 
@@ -2183,7 +2191,7 @@
 {
 	cparticle_t		*p, *next;
 	float			alpha;
-	float			time, time2;
+	float			time = 0, time2;
 	vec3_t			org;
 	int				color;
 	cparticle_t		*active, *tail;
--- a/client/cl_input.c
+++ b/client/cl_input.c
@@ -19,7 +19,11 @@
 */
 // cl.input.c  -- builds an intended movement command to send to the server
 
-#include "client.h"
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 
 cvar_t	*cl_nodelta;
 
@@ -198,12 +202,12 @@
 		key->downtime = sys_frame_time;
 	}
 
-#if 0
+/*
 	if (msec)
 	{
 		Com_Printf ("%i ", msec);
 	}
-#endif
+*/
 
 	val = (float)msec / frame_msec;
 	if (val < 0)
--- a/client/cl_inv.c
+++ b/client/cl_inv.c
@@ -19,7 +19,11 @@
 */
 // cl_inv.c -- client inventory screen
 
-#include "client.h"
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 
 /*
 ================
@@ -97,8 +101,8 @@
 	if (top < 0)
 		top = 0;
 
-	x = (viddef.width-256)/2;
-	y = (viddef.height-240)/2;
+	x = (vid.width-256)/2;
+	y = (vid.height-240)/2;
 
 	// repaint everything next frame
 	SCR_DirtyScreen ();
@@ -117,7 +121,7 @@
 		Com_sprintf (binding, sizeof(binding), "use %s", cl.configstrings[CS_ITEMS+item]);
 		bind = "";
 		for (j=0 ; j<256 ; j++)
-			if (keybindings[j] && !Q_stricmp (keybindings[j], binding))
+			if (keybindings[j] && !Q_strcasecmp (keybindings[j], binding))
 			{
 				bind = Key_KeynumToString(j);
 				break;
--- a/client/cl_main.c
+++ b/client/cl_main.c
@@ -19,7 +19,11 @@
 */
 // cl_main.c  -- client main loop
 
-#include "client.h"
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 
 cvar_t	*freelook;
 
@@ -206,7 +210,7 @@
 	//
 	// write out messages to hold the startup information
 	//
-	SZ_Init (&buf, buf_data, sizeof(buf_data));
+	SZ_Init (&buf, (uchar *)buf_data, sizeof(buf_data));
 
 	// send the serverdata
 	MSG_WriteByte (&buf, svc_serverdata);
@@ -303,35 +307,33 @@
 
 void CL_Setenv_f( void )
 {
-	int argc = Cmd_Argc();
+	int i, l = 0, argc;
+	char name[1024], val[1024] = {0}, *env;
 
-	if ( argc > 2 )
-	{
-		char buffer[1000];
-		int i;
+	argc = Cmd_Argc();
 
-		strcpy( buffer, Cmd_Argv(1) );
-		strcat( buffer, "=" );
-
-		for ( i = 2; i < argc; i++ )
+	if (argc > 2)
+	{
+		strncpy(name, Cmd_Argv(1), sizeof name);
+		for (i = 2; i < argc; i++)
 		{
-			strcat( buffer, Cmd_Argv( i ) );
-			strcat( buffer, " " );
+			strncpy (val+l, Cmd_Argv(i), sizeof name - l - 2);
+			strcat (val, " ");
+			l = strlen (val);
 		}
-
-		putenv( buffer );
+		putenv (name, val);
 	}
-	else if ( argc == 2 )
+	else if (argc == 2)
 	{
-		char *env = getenv( Cmd_Argv(1) );
-
-		if ( env )
+		env = getenv (Cmd_Argv(1));
+		if (env)
 		{
-			Com_Printf( "%s=%s\n", Cmd_Argv(1), env );
+			Com_Printf ("%s=%s\n", Cmd_Argv(1), env);
+			free (env);
 		}
 		else
 		{
-			Com_Printf( "%s undefined\n", Cmd_Argv(1), env );
+			Com_Printf ("%s undefined\n", Cmd_Argv(1), env);
 		}
 	}
 }
@@ -597,7 +599,7 @@
 
 // wipe the entire cl structure
 	memset (&cl, 0, sizeof(cl));
-	memset (&cl_entities, 0, sizeof(cl_entities));
+	memset (cl_entities, 0, sizeof(cl_entities));
 
 	SZ_Clear (&cls.netchan.message);
 
@@ -644,9 +646,9 @@
 	// send a disconnect message to the server
 	final[0] = clc_stringcmd;
 	strcpy ((char *)final+1, "disconnect");
-	Netchan_Transmit (&cls.netchan, strlen(final), final);
-	Netchan_Transmit (&cls.netchan, strlen(final), final);
-	Netchan_Transmit (&cls.netchan, strlen(final), final);
+	Netchan_Transmit (&cls.netchan, strlen((char *)final), final);
+	Netchan_Transmit (&cls.netchan, strlen((char *)final), final);
+	Netchan_Transmit (&cls.netchan, strlen((char *)final), final);
 
 	CL_ClearState ();
 
@@ -1063,9 +1065,9 @@
 		strncpy(sk, skin->string, sizeof(sk) - 1);
 		if ((p = strchr(sk, '/')) != NULL)
 			*p = 0;
-		if (Q_stricmp(sk, "male") == 0 || Q_stricmp(sk, "cyborg") == 0)
+		if (Q_strcasecmp(sk, "male") == 0 || Q_strcasecmp(sk, "cyborg") == 0)
 			Cvar_Set ("gender", "male");
-		else if (Q_stricmp(sk, "female") == 0 || Q_stricmp(sk, "crackhor") == 0)
+		else if (Q_strcasecmp(sk, "female") == 0 || Q_strcasecmp(sk, "crackhor") == 0)
 			Cvar_Set ("gender", "female");
 		else
 			Cvar_Set ("gender", "none");
@@ -1262,7 +1264,6 @@
 						precache_check = CS_PLAYERSKINS + i * PLAYER_MULT + 1;
 						return; // started a download
 					}
-					n++;
 					/*FALL THROUGH*/
 
 				case 1: // weapon model
@@ -1271,7 +1272,6 @@
 						precache_check = CS_PLAYERSKINS + i * PLAYER_MULT + 2;
 						return; // started a download
 					}
-					n++;
 					/*FALL THROUGH*/
 
 				case 2: // weapon skin
@@ -1280,7 +1280,6 @@
 						precache_check = CS_PLAYERSKINS + i * PLAYER_MULT + 3;
 						return; // started a download
 					}
-					n++;
 					/*FALL THROUGH*/
 
 				case 3: // skin
@@ -1289,7 +1288,6 @@
 						precache_check = CS_PLAYERSKINS + i * PLAYER_MULT + 4;
 						return; // started a download
 					}
-					n++;
 					/*FALL THROUGH*/
 
 				case 4: // skin_i
@@ -1701,13 +1699,12 @@
 	cls.realtime = curtime;
 
 	extratime = 0;
-#if 0
+/*
 	if (cls.frametime > (1.0 / cl_minfps->value))
 		cls.frametime = (1.0 / cl_minfps->value);
-#else
+*/
 	if (cls.frametime > (1.0 / 5))
 		cls.frametime = (1.0 / 5);
-#endif
 
 	// if in the debugger last frame, don't timeout
 	if (msec > 5000)
@@ -1784,14 +1781,13 @@
 
 	// all archived variables will now be loaded
 
-	Con_Init ();	
-#if defined __linux__ || defined __sgi
-	S_Init ();	
+	Con_Init ();
+/*	
 	VID_Init ();
-#else
-	VID_Init ();
 	S_Init ();	// sound must be initialized after window is created
-#endif
+*/
+	S_Init ();	
+	VID_Init ();
 	
 	V_Init ();
 	
--- a/client/cl_newfx.c
+++ b/client/cl_newfx.c
@@ -19,7 +19,11 @@
 */
 // cl_newfx.c -- MORE entity effects parsing and management
 
-#include "client.h"
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 
 extern cparticle_t	*active_particles, *free_particles;
 extern cparticle_t	particles[MAX_PARTICLES];
@@ -214,7 +218,7 @@
 		p->time = cl.time;
 
 		p->alpha = 1.0;
-		p->alphavel = -1.0 / (1+frand()*0.5);
+		p->alphavel = -1.0 / (1+qfrand()*0.5);
 		p->color = colorStart + (rand() % colorRun);
 		for (j=0 ; j<3 ; j++)
 		{
@@ -249,7 +253,7 @@
 		if (!free_particles)
 			return;
 		
-		if (frand() > 0.3)
+		if (qfrand() > 0.3)
 		{
 			p = free_particles;
 			free_particles = p->next;
@@ -260,7 +264,7 @@
 			p->time = cl.time;
 
 			p->alpha = 1.0;
-			p->alphavel =  -1.0 / (3.0+frand()*0.5);
+			p->alphavel =  -1.0 / (3.0+qfrand()*0.5);
 			p->color = color;
 			for (j=0 ; j<3 ; j++)
 			{
@@ -276,7 +280,7 @@
 	}
 }
 
-void CL_FlameEffects (centity_t *ent, vec3_t origin)
+void CL_FlameEffects (centity_t */*ent*/, vec3_t origin)
 {
 	int			n, count;
 	int			j;
@@ -298,7 +302,7 @@
 		p->time = cl.time;
 
 		p->alpha = 1.0;
-		p->alphavel = -1.0 / (1+frand()*0.2);
+		p->alphavel = -1.0 / (1+qfrand()*0.2);
 		p->color = 226 + (rand() % 4);
 		for (j=0 ; j<3 ; j++)
 		{
@@ -324,7 +328,7 @@
 		p->time = cl.time;
 
 		p->alpha = 1.0;
-		p->alphavel = -1.0 / (1+frand()*0.5);
+		p->alphavel = -1.0 / (1+qfrand()*0.5);
 		p->color = 0 + (rand() % 4);
 		for (j=0 ; j<3 ; j++)
 		{
@@ -374,7 +378,7 @@
 //		VectorCopy (accel, p->accel);
 		p->alpha = 1.0;
 
-		p->alphavel = -1.0 / (0.5 + frand()*alphavel);
+		p->alphavel = -1.0 / (0.5 + qfrand()*alphavel);
 //		p->alphavel = alphavel;
 	}
 }
@@ -415,7 +419,7 @@
 		p->time = cl.time;
 
 		p->alpha = 1.0;
-		p->alphavel = -1.0 / (1+frand()*0.1);
+		p->alphavel = -1.0 / (1+qfrand()*0.1);
 		p->color = 4 + (rand()&7);
 		for (j=0 ; j<3 ; j++)
 		{
@@ -487,7 +491,7 @@
 			VectorClear (p->accel);
 
 			p->alpha = 0.5;
-	//		p->alphavel = -1.0 / (1+frand()*0.2);
+	//		p->alphavel = -1.0 / (1+qfrand()*0.2);
 			// only last one frame!
 			p->alphavel = INSTANT_PARTICLE;
 	//		p->color = 0x74 + (rand()&7);
@@ -604,7 +608,7 @@
 			}
 		
 			p->alpha = 0.5;
-	//		p->alphavel = -1.0 / (1+frand()*0.2);
+	//		p->alphavel = -1.0 / (1+qfrand()*0.2);
 			p->alphavel = -1000.0;
 	//		p->color = 0x74 + (rand()&7);
 			p->color = 223 - (rand()&7);
@@ -665,7 +669,7 @@
 		s = sin(d)*30;
 
 		p->alpha = 1.0;
-		p->alphavel = -5.0 / (1+frand());
+		p->alphavel = -5.0 / (1+qfrand());
 		p->color = 223 - (rand()&7);
 
 		for (j=0 ; j<3 ; j++)
@@ -722,7 +726,7 @@
 			}
 		
 			p->alpha = 0.5;
-	//		p->alphavel = -1.0 / (1+frand()*0.2);
+	//		p->alphavel = -1.0 / (1+qfrand()*0.2);
 			p->alphavel = -1000.0;
 	//		p->color = 0x74 + (rand()&7);
 			p->color = 223 - (rand()&7);
@@ -785,7 +789,7 @@
 		p->accel[2] = -PARTICLE_GRAVITY/2;
 		p->alpha = 1.0;
 
-		p->alphavel = -1.0 / (0.5 + frand()*0.3);
+		p->alphavel = -1.0 / (0.5 + qfrand()*0.3);
 	}
 }
 
@@ -831,7 +835,7 @@
 		p->accel[2] = -PARTICLE_GRAVITY/2;
 		p->alpha = 1.0;
 
-		p->alphavel = -1.0 / (0.5 + frand()*0.3);
+		p->alphavel = -1.0 / (0.5 + qfrand()*0.3);
 	}
 	self->nextthink += self->thinkinterval;
 }
@@ -1059,7 +1063,7 @@
 		p->accel[0] = p->accel[1] = 0;
 		p->alpha = 1.0;
 
-		p->alphavel = -0.8 / (0.5 + frand()*0.3);
+		p->alphavel = -0.8 / (0.5 + qfrand()*0.3);
 	}
 
 }
@@ -1135,7 +1139,7 @@
 		p->time = cl.time;
 
 		p->alpha = 1.0;
-		p->alphavel = -1.0 / (0.8+frand()*0.2);
+		p->alphavel = -1.0 / (0.8+qfrand()*0.2);
 		p->color = color;
 		for (j=0 ; j<3 ; j++)
 		{
@@ -1180,7 +1184,7 @@
 		p->accel[2] = -PARTICLE_GRAVITY;
 		p->alpha = 1.0;
 
-		p->alphavel = -0.4 / (0.6 + frand()*0.2);
+		p->alphavel = -0.4 / (0.6 + qfrand()*0.2);
 	}
 }
 
@@ -1224,7 +1228,7 @@
 		p->accel[0] = p->accel[1] = p->accel[2] = 0;
 		p->alpha = 1.0;
 
-		p->alphavel = -1.0 / (0.5 + frand()*0.3);
+		p->alphavel = -1.0 / (0.5 + qfrand()*0.3);
 	}
 }
 
@@ -1266,7 +1270,7 @@
 		p->accel[2] = -PARTICLE_GRAVITY;
 		p->alpha = 1.0;
 
-		p->alphavel = -1.0 / (0.5 + frand()*0.3);
+		p->alphavel = -1.0 / (0.5 + qfrand()*0.3);
 	}
 }
 
@@ -1309,7 +1313,7 @@
 		p->time = cl.time;
 
 		p->alpha = 1.0;
-		p->alphavel = -1.0 / (0.3+frand()*0.2);
+		p->alphavel = -1.0 / (0.3+qfrand()*0.2);
 		p->color = 0xd0;
 		for (j=0 ; j<3 ; j++)
 		{
--- a/client/cl_parse.c
+++ b/client/cl_parse.c
@@ -19,7 +19,11 @@
 */
 // cl_parse.c  -- parse a message received from the server
 
-#include "client.h"
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 
 char *svc_strings[256] =
 {
@@ -189,7 +193,21 @@
 	S_EndRegistration ();
 }
 
+void rename (char *old, char *new)	/* FIXME: unsafe impl. */
+{
+	char *p;
+	Dir d;
 
+	if((p = strrchr(new, '/')) == nil)
+		p = new;
+	else
+		p++;
+	nulldir(&d);
+	d.name = p;
+	if(dirwstat(old, &d) < 0)
+		fprint(2, "rename: %r\n");
+}
+
 /*
 =====================
 CL_ParseDownload
@@ -201,7 +219,6 @@
 {
 	int		size, percent;
 	char	name[MAX_OSPATH];
-	int		r;
 
 	// read the data
 	size = MSG_ReadShort (&net_message);
@@ -243,7 +260,7 @@
 	{
 		// request next block
 // change display routines by zoid
-#if 0
+/*
 		Com_Printf (".");
 		if (10*(percent/10) != cls.downloadpercent)
 		{
@@ -250,7 +267,7 @@
 			cls.downloadpercent = 10*(percent/10);
 			Com_Printf ("%i%%", cls.downloadpercent);
 		}
-#endif
+*/
 		cls.downloadpercent = percent;
 
 		MSG_WriteByte (&cls.netchan.message, clc_stringcmd);
@@ -268,9 +285,7 @@
 		// rename the temp file to it's final name
 		CL_DownloadFileName(oldn, sizeof(oldn), cls.downloadtempname);
 		CL_DownloadFileName(newn, sizeof(newn), cls.downloadname);
-		r = rename (oldn, newn);
-		if (r)
-			Com_Printf ("failed to rename.\n");
+		rename (oldn, newn);	/* FIXME */
 
 		cls.download = NULL;
 		cls.downloadpercent = 0;
@@ -442,7 +457,7 @@
 
 		// if we don't have the skin and the model wasn't male,
 		// see if the male has it (this is for CTF's skins)
- 		if (!ci->skin && Q_stricmp(model_name, "male"))
+ 		if (!ci->skin && Q_strcasecmp(model_name, "male"))
 		{
 			// change model to male
 			strcpy(model_name, "male");
--- a/client/cl_pred.c
+++ b/client/cl_pred.c
@@ -17,10 +17,13 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 
-#include "client.h"
 
-
 /*
 ===================
 CL_CheckPredictionError
@@ -125,7 +128,7 @@
 		if (trace.allsolid || trace.startsolid ||
 		trace.fraction < tr->fraction)
 		{
-			trace.ent = (struct edict_s *)ent;
+			trace.ent = (edict_t *)ent;
 		 	if (tr->startsolid)
 			{
 				*tr = trace;
@@ -152,7 +155,7 @@
 	// check against world
 	t = CM_BoxTrace (start, end, mins, maxs, 0, MASK_PLAYERSOLID);
 	if (t.fraction < 1.0)
-		t.ent = (struct edict_s *)1;
+		t.ent = (edict_t *)1;
 
 	// check all other solid models
 	CL_ClipMoveToEntities (start, mins, maxs, end, &t);
@@ -243,8 +246,6 @@
 	pm.s = cl.frame.playerstate.pmove;
 
 //	SCR_DebugGraph (current - ack - 1, 0);
-
-	frame = 0;
 
 	// run frames
 	while (++ack < current)
--- a/client/cl_scrn.c
+++ b/client/cl_scrn.c
@@ -32,7 +32,11 @@
 
   */
 
-#include "client.h"
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 
 float		scr_con_current;	// aproaches scr_conlines at scr_conspeed
 float		scr_conlines;		// 0.0 to 1.0 lines of console to display
@@ -263,7 +267,7 @@
 	start = scr_centerstring;
 
 	if (scr_center_lines <= 4)
-		y = viddef.height*0.35;
+		y = vid.height*0.35;
 	else
 		y = 48;
 
@@ -273,7 +277,7 @@
 		for (l=0 ; l<40 ; l++)
 			if (start[l] == '\n' || !start[l])
 				break;
-		x = (viddef.width - l*8)/2;
+		x = (vid.width - l*8)/2;
 		SCR_AddDirtyPoint (x, y);
 		for (j=0 ; j<l ; j++, x+=8)
 		{
@@ -325,14 +329,14 @@
 
 	size = scr_viewsize->value;
 
-	scr_vrect.width = viddef.width*size/100;
+	scr_vrect.width = vid.width*size/100;
 	scr_vrect.width &= ~7;
 
-	scr_vrect.height = viddef.height*size/100;
+	scr_vrect.height = vid.height*size/100;
 	scr_vrect.height &= ~1;
 
-	scr_vrect.x = (viddef.width - scr_vrect.width)/2;
-	scr_vrect.y = (viddef.height - scr_vrect.height)/2;
+	scr_vrect.x = (vid.width - scr_vrect.width)/2;
+	scr_vrect.y = (vid.height - scr_vrect.height)/2;
 }
 
 
@@ -464,7 +468,7 @@
 		return;
 
 	re.DrawGetPicSize (&w, &h, "pause");
-	re.DrawPic ((viddef.width-w)/2, viddef.height/2 + 8, "pause");
+	re.DrawPic ((vid.width-w)/2, vid.height/2 + 8, "pause");
 }
 
 /*
@@ -481,7 +485,7 @@
 
 	scr_draw_loading = false;
 	re.DrawGetPicSize (&w, &h, "loading");
-	re.DrawPic ((viddef.width-w)/2, (viddef.height-h)/2, "loading");
+	re.DrawPic ((vid.width-w)/2, (vid.height-h)/2, "loading");
 }
 
 //=============================================================================
@@ -535,7 +539,7 @@
 	if (cls.state != ca_active || !cl.refresh_prepped)
 	{	// connected, but can't render
 		Con_DrawConsole (0.5);
-		re.DrawFill (0, viddef.height/2, viddef.width, viddef.height/2, 0);
+		re.DrawFill (0, vid.height/2, vid.width, vid.height/2, 0);
 		return;
 	}
 
@@ -612,11 +616,11 @@
 	*/
 	if ( a->model == b->model )
 	{
-		return ( ( int ) a->skin - ( int ) b->skin );
+		return (uintptr)a->skin - (uintptr)b->skin;
 	}
 	else
 	{
-		return ( ( int ) a->model - ( int ) b->model );
+		return (uintptr)a->model - (uintptr)b->model;
 	}
 }
 
@@ -678,7 +682,7 @@
 void SCR_DirtyScreen (void)
 {
 	SCR_AddDirtyPoint (0, 0);
-	SCR_AddDirtyPoint (viddef.width-1, viddef.height-1);
+	SCR_AddDirtyPoint (vid.width-1, vid.height-1);
 }
 
 /*
@@ -728,7 +732,7 @@
 	scr_dirty.y2 = -9999;
 
 	// don't bother with anything convered by the console)
-	top = scr_con_current*viddef.height;
+	top = scr_con_current*vid.height;
 	if (top >= clear.y1)
 		clear.y1 = top;
 
@@ -855,7 +859,6 @@
 		if (*string)
 		{
 			string++;	// skip the \n
-			x = margin;
 			y += 8;
 		}
 	}
@@ -955,7 +958,6 @@
 
 	x = 0;
 	y = 0;
-	width = 3;
 
 	while (s)
 	{
@@ -969,13 +971,13 @@
 		if (!strcmp(token, "xr"))
 		{
 			token = COM_Parse (&s);
-			x = viddef.width + atoi(token);
+			x = vid.width + atoi(token);
 			continue;
 		}
 		if (!strcmp(token, "xv"))
 		{
 			token = COM_Parse (&s);
-			x = viddef.width/2 - 160 + atoi(token);
+			x = vid.width/2 - 160 + atoi(token);
 			continue;
 		}
 
@@ -988,13 +990,13 @@
 		if (!strcmp(token, "yb"))
 		{
 			token = COM_Parse (&s);
-			y = viddef.height + atoi(token);
+			y = vid.height + atoi(token);
 			continue;
 		}
 		if (!strcmp(token, "yv"))
 		{
 			token = COM_Parse (&s);
-			y = viddef.height/2 - 120 + atoi(token);
+			y = vid.height/2 - 120 + atoi(token);
 			continue;
 		}
 
@@ -1018,9 +1020,9 @@
 			int		score, ping, time;
 
 			token = COM_Parse (&s);
-			x = viddef.width/2 - 160 + atoi(token);
+			x = vid.width/2 - 160 + atoi(token);
 			token = COM_Parse (&s);
-			y = viddef.height/2 - 120 + atoi(token);
+			y = vid.height/2 - 120 + atoi(token);
 			SCR_AddDirtyPoint (x, y);
 			SCR_AddDirtyPoint (x+159, y+31);
 
@@ -1057,9 +1059,9 @@
 			char	block[80];
 
 			token = COM_Parse (&s);
-			x = viddef.width/2 - 160 + atoi(token);
+			x = vid.width/2 - 160 + atoi(token);
 			token = COM_Parse (&s);
-			y = viddef.height/2 - 120 + atoi(token);
+			y = vid.height/2 - 120 + atoi(token);
 			SCR_AddDirtyPoint (x, y);
 			SCR_AddDirtyPoint (x+159, y+31);
 
@@ -1245,8 +1247,6 @@
 
 ================
 */
-#define	STAT_LAYOUTS		13
-
 void SCR_DrawLayout (void)
 {
 	if (!cl.frame.playerstate.stats[STAT_LAYOUTS])
@@ -1318,7 +1318,7 @@
 			re.CinematicSetPalette(NULL);
 			scr_draw_loading = false;
 			re.DrawGetPicSize (&w, &h, "loading");
-			re.DrawPic ((viddef.width-w)/2, (viddef.height-h)/2, "loading");
+			re.DrawPic ((vid.width-w)/2, (vid.height-h)/2, "loading");
 //			re.EndFrame();
 //			return;
 		} 
--- a/client/cl_tent.c
+++ b/client/cl_tent.c
@@ -19,7 +19,11 @@
 */
 // cl_tent.c -- client side temporary entities
 
-#include "client.h"
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 
 typedef enum
 {
@@ -594,13 +598,13 @@
 		else
 		{
 //				Com_Printf ("No free sustains!\n");
-			// FIXME - read the stuff anyway
-			cnt = MSG_ReadByte (&net_message);
+			// FIXME - read the stuff anyway	/* and toss the results */
+			MSG_ReadByte (&net_message);
 			MSG_ReadPos (&net_message, pos);
 			MSG_ReadDir (&net_message, dir);
-			r = MSG_ReadByte (&net_message);
-			magnitude = MSG_ReadShort (&net_message);
-			magnitude = MSG_ReadLong (&net_message); // really interval
+			MSG_ReadByte (&net_message);
+			MSG_ReadShort (&net_message);
+			MSG_ReadLong (&net_message); // really interval
 		}
 	}
 	else // instant
@@ -870,7 +874,7 @@
 		ex->lightcolor[2] = 0.5;
 		ex->ent.angles[1] = rand() % 360;
 		ex->ent.model = cl_mod_explo4;
-		if (frand() < 0.5)
+		if (qfrand() < 0.5)
 			ex->baseframe = 15;
 		ex->frames = 15;
 		CL_ExplosionParticles (pos);
@@ -898,7 +902,7 @@
 			ex->ent.model = cl_mod_explo4;			// PMM
 		else
 			ex->ent.model = cl_mod_explo4_big;
-		if (frand() < 0.5)
+		if (qfrand() < 0.5)
 			ex->baseframe = 15;
 		ex->frames = 15;
 		if ((type != TE_EXPLOSION1_BIG) && (type != TE_EXPLOSION1_NP))		// PMM
@@ -943,7 +947,7 @@
 
 	case TE_PARASITE_ATTACK:
 	case TE_MEDIC_CABLE_ATTACK:
-		ent = CL_ParseBeam (cl_mod_parasite_segment);
+		CL_ParseBeam (cl_mod_parasite_segment);		/* toss result */
 		break;
 
 	case TE_BOSSTPORT:			// boss teleporting to station
@@ -953,7 +957,7 @@
 		break;
 
 	case TE_GRAPPLE_CABLE:
-		ent = CL_ParseBeam2 (cl_mod_grapple_cable);
+		CL_ParseBeam2 (cl_mod_grapple_cable);		/* toss result */
 		break;
 
 	// RAFAEL
@@ -1072,7 +1076,7 @@
 		ex->lightcolor[2] = 0.5;
 		ex->ent.angles[1] = rand() % 360;
 		ex->ent.model = cl_mod_explo4;
-		if (frand() < 0.5)
+		if (qfrand() < 0.5)
 			ex->baseframe = 15;
 		ex->frames = 15;
 		if (type == TE_ROCKET_EXPLOSION_WATER)
@@ -1095,11 +1099,11 @@
 		break;
 
 	case TE_HEATBEAM:
-		ent = CL_ParsePlayerBeam (cl_mod_heatbeam);
+		CL_ParsePlayerBeam (cl_mod_heatbeam);		/* toss result */
 		break;
 
 	case TE_MONSTER_HEATBEAM:
-		ent = CL_ParsePlayerBeam (cl_mod_monster_heatbeam);
+		CL_ParsePlayerBeam (cl_mod_monster_heatbeam);	/* toss result */
 		break;
 
 	case TE_HEATBEAM_SPARKS:
@@ -1353,7 +1357,7 @@
 	float		yaw, pitch;
 	float		forward;
 	float		len, steps;
-	int			framenum;
+	int			framenum = 0;
 	float		model_length;
 	
 	float		hand_multiplier;
@@ -1710,7 +1714,7 @@
 }
 
 /* PMM - CL_Sustains */
-void CL_ProcessSustain ()
+void CL_ProcessSustain (void)
 {
 	cl_sustain_t	*s;
 	int				i;
--- a/client/cl_view.c
+++ b/client/cl_view.c
@@ -19,7 +19,11 @@
 */
 // cl_view.c -- player rendering positioning
 
-#include "client.h"
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 
 //=============
 //
@@ -257,7 +261,7 @@
 		return;		// no map loaded
 
 	SCR_AddDirtyPoint (0, 0);
-	SCR_AddDirtyPoint (viddef.width-1, viddef.height-1);
+	SCR_AddDirtyPoint (vid.width-1, vid.height-1);
 
 	// let the render dll load the map
 	strcpy (mapname, cl.configstrings[CS_MODELS+1] + 5);	// skip "maps/"
--- a/client/client.h
+++ b/client/client.h
@@ -19,24 +19,8 @@
 */
 // client.h -- primary header for client
 
-//define	PARANOID			// speed sapping error checking
+//#define	PARANOID			// speed sapping error checking
 
-#include <math.h>
-#include <string.h>
-#include <stdarg.h>
-#include <stdio.h>
-#include <stdlib.h>
-
-#include "ref.h"
-
-#include "vid.h"
-#include "screen.h"
-#include "sound.h"
-#include "input.h"
-#include "keys.h"
-#include "console.h"
-#include "cdaudio.h"
-
 //=============================================================================
 
 typedef struct
@@ -414,7 +398,7 @@
 // PGM
 // ========
 
-int CL_ParseEntityBits (unsigned *bits);
+int CL_ParseEntityBits (int *bits);
 void CL_ParseDelta (entity_state_t *from, entity_state_t *to, int number, int bits);
 void CL_ParseFrame (void);
 
@@ -576,7 +560,7 @@
 //
 void CL_PredictMovement (void);
 
-#if id386
+#ifdef id386
 void x86_TimerStart( void );
 void x86_TimerStop( void );
 void x86_TimerInit( unsigned long smallest, unsigned longest );
--- a/client/console.c
+++ b/client/console.c
@@ -17,10 +17,12 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-// console.c
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 
-#include "client.h"
-
 console_t	con;
 
 cvar_t		*con_notifytime;
@@ -247,7 +249,7 @@
 	int		i, j, width, oldwidth, oldtotallines, numlines, numchars;
 	char	tbuf[CON_TEXTSIZE];
 
-	width = (viddef.width >> 3) - 2;
+	width = (vid.width >> 3) - 2;
 
 	if (width == con.linewidth)
 		return;
@@ -457,7 +459,6 @@
 */
 void Con_DrawInput (void)
 {
-	int		y;
 	int		i;
 	char	*text;
 
@@ -480,8 +481,6 @@
 		text += 1 + key_linepos - con.linewidth;
 		
 // draw it
-	y = con.vislines-16;
-
 	for (i=0 ; i<con.linewidth ; i++)
 		re.DrawChar ( (i+1)<<3, con.vislines - 22, text[i]);
 
@@ -540,8 +539,8 @@
 		}
 
 		s = chat_buffer;
-		if (chat_bufferlen > (viddef.width>>3)-(skip+1))
-			s += chat_bufferlen - ((viddef.width>>3)-(skip+1));
+		if (chat_bufferlen > (vid.width>>3)-(skip+1))
+			s += chat_bufferlen - ((vid.width>>3)-(skip+1));
 		x = 0;
 		while(s[x])
 		{
@@ -555,7 +554,7 @@
 	if (v)
 	{
 		SCR_AddDirtyPoint (0,0);
-		SCR_AddDirtyPoint (viddef.width-1, v);
+		SCR_AddDirtyPoint (vid.width-1, v);
 	}
 }
 
@@ -576,34 +575,33 @@
 	char			version[64];
 	char			dlbar[1024];
 
-	lines = viddef.height * frac;
+	lines = vid.height * frac;
 	if (lines <= 0)
 		return;
 
-	if (lines > viddef.height)
-		lines = viddef.height;
+	if (lines > vid.height)
+		lines = vid.height;
 
 // draw the background
-	re.DrawStretchPic (0, -viddef.height+lines, viddef.width, viddef.height, "conback");
+	re.DrawStretchPic (0, -vid.height+lines, vid.width, vid.height, "conback");
 	SCR_AddDirtyPoint (0,0);
-	SCR_AddDirtyPoint (viddef.width-1,lines-1);
+	SCR_AddDirtyPoint (vid.width-1,lines-1);
 
 	Com_sprintf (version, sizeof(version), "v%4.2f", VERSION);
 	for (x=0 ; x<5 ; x++)
-		re.DrawChar (viddef.width-44+x*8, lines-12, 128 + version[x] );
+		re.DrawChar (vid.width-44+x*8, lines-12, 128 + version[x] );
 
 // draw the text
 	con.vislines = lines;
 	
-#if 0
+/*
 	rows = (lines-8)>>3;		// rows of text to draw
 
 	y = lines - 24;
-#else
+*/
 	rows = (lines-22)>>3;		// rows of text to draw
 
 	y = lines - 30;
-#endif
 
 // draw from the bottom up
 	if (con.display != con.current)
@@ -651,7 +649,7 @@
 			strcpy(dlbar, text);
 		strcat(dlbar, ": ");
 		i = strlen(dlbar);
-		dlbar[i++] = '\x80';
+		dlbar[i++] = 0x80;
 		// where's the dot go?
 		if (cls.downloadpercent == 0)
 			n = 0;
@@ -660,10 +658,10 @@
 			
 		for (j = 0; j < y; j++)
 			if (j == n)
-				dlbar[i++] = '\x83';
+				dlbar[i++] = 0x83;
 			else
-				dlbar[i++] = '\x81';
-		dlbar[i++] = '\x82';
+				dlbar[i++] = 0x81;
+		dlbar[i++] = 0x82;
 		dlbar[i] = 0;
 
 		sprintf(dlbar + strlen(dlbar), " %02d%%", cls.downloadpercent);
@@ -678,5 +676,3 @@
 // draw the input prompt, user text, and cursor if desired
 	Con_DrawInput ();
 }
-
-
--- a/client/keys.c
+++ b/client/keys.c
@@ -17,7 +17,11 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-#include "client.h"
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 
 /*
 
--- a/client/menu.c
+++ b/client/menu.c
@@ -17,12 +17,12 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
 #include <ctype.h>
-#ifdef _WIN32
-#include <io.h>
-#endif
-#include "client.h"
-#include "../client/qmenu.h"
+#include "../dat.h"
+#include "../fns.h"
 
 static int	m_main_cursor;
 
@@ -77,7 +77,7 @@
 	int w, h;
 
 	re.DrawGetPicSize (&w, &h, name );
-	re.DrawPic( viddef.width / 2 - w / 2, viddef.height / 2 - 110, name );
+	re.DrawPic( vid.width / 2 - w / 2, vid.height / 2 - 110, name );
 }
 
 void M_PushMenu ( void (*draw) (void), const char *(*key) (int k) )
@@ -268,7 +268,7 @@
 */
 void M_DrawCharacter (int cx, int cy, int num)
 {
-	re.DrawChar ( cx + ((viddef.width - 320)>>1), cy + ((viddef.height - 240)>>1), num);
+	re.DrawChar ( cx + ((vid.width - 320)>>1), cy + ((vid.height - 240)>>1), num);
 }
 
 void M_Print (int cx, int cy, char *str)
@@ -293,7 +293,7 @@
 
 void M_DrawPic (int x, int y, char *pic)
 {
-	re.DrawPic (x + ((viddef.width - 320)>>1), y + ((viddef.height - 240)>>1), pic);
+	re.DrawPic (x + ((vid.width - 320)>>1), y + ((vid.height - 240)>>1), pic);
 }
 
 
@@ -410,8 +410,8 @@
 		totalheight += ( h + 12 );
 	}
 
-	ystart = ( viddef.height / 2 - 110 );
-	xoffset = ( viddef.width - widest + 70 ) / 2;
+	ystart = ( vid.height / 2 - 110 );
+	xoffset = ( vid.width - widest + 70 ) / 2;
 
 	for ( i = 0; names[i] != 0; i++ )
 	{
@@ -510,17 +510,17 @@
 	Menu_Draw( &s_multiplayer_menu );
 }
 
-static void PlayerSetupFunc( void *unused )
+static void PlayerSetupFunc( void * )
 {
 	M_Menu_PlayerConfig_f();
 }
 
-static void JoinNetworkServerFunc( void *unused )
+static void JoinNetworkServerFunc( void * )
 {
 	M_Menu_JoinServer_f();
 }
 
-static void StartNetworkServerFunc( void *unused )
+static void StartNetworkServerFunc( void * )
 {
 	M_Menu_StartServer_f ();
 }
@@ -527,7 +527,7 @@
 
 void Multiplayer_MenuInit( void )
 {
-	s_multiplayer_menu.x = viddef.width * 0.50 - 64;
+	s_multiplayer_menu.x = vid.width * 0.50 - 64;
 	s_multiplayer_menu.nitems = 0;
 
 	s_join_network_server_action.generic.type	= MTYPE_ACTION;
@@ -739,7 +739,7 @@
 	int y = 0;
 	int i = 0;
 
-	s_keys_menu.x = viddef.width * 0.50;
+	s_keys_menu.x = vid.width * 0.50;
 	s_keys_menu.nitems = 0;
 	s_keys_menu.cursordraw = KeyCursorDrawFunc;
 
@@ -1033,37 +1033,37 @@
 static menulist_s		s_options_compatibility_list;
 static menulist_s		s_options_console_action;
 
-static void CrosshairFunc( void *unused )
+static void CrosshairFunc( void * )
 {
 	Cvar_SetValue( "crosshair", s_options_crosshair_box.curvalue );
 }
 
-static void JoystickFunc( void *unused )
+static void JoystickFunc( void * )
 {
 	Cvar_SetValue( "in_joystick", s_options_joystick_box.curvalue );
 }
 
-static void CustomizeControlsFunc( void *unused )
+static void CustomizeControlsFunc( void * )
 {
 	M_Menu_Keys_f();
 }
 
-static void AlwaysRunFunc( void *unused )
+static void AlwaysRunFunc( void * )
 {
 	Cvar_SetValue( "cl_run", s_options_alwaysrun_box.curvalue );
 }
 
-static void FreeLookFunc( void *unused )
+static void FreeLookFunc( void * )
 {
 	Cvar_SetValue( "freelook", s_options_freelook_box.curvalue );
 }
 
-static void MouseSpeedFunc( void *unused )
+static void MouseSpeedFunc( void * )
 {
 	Cvar_SetValue( "sensitivity", s_options_sensitivity_slider.curvalue / 2.0F );
 }
 
-static void NoAltTabFunc( void *unused )
+static void NoAltTabFunc( void * )
 {
 	Cvar_SetValue( "win_noalttab", s_options_noalttab_box.curvalue );
 }
@@ -1105,7 +1105,7 @@
 	s_options_noalttab_box.curvalue			= win_noalttab->value;
 }
 
-static void ControlsResetDefaultsFunc( void *unused )
+static void ControlsResetDefaultsFunc( void * )
 {
 	Cbuf_AddText ("exec default.cfg\n");
 	Cbuf_Execute();
@@ -1113,7 +1113,7 @@
 	ControlsSetMenuItemValues();
 }
 
-static void InvertMouseFunc( void *unused )
+static void InvertMouseFunc( void * )
 {
 	if ( s_options_invertmouse_box.curvalue == 0 )
 	{
@@ -1125,27 +1125,27 @@
 	}
 }
 
-static void LookspringFunc( void *unused )
+static void LookspringFunc( void * )
 {
 	Cvar_SetValue( "lookspring", s_options_lookspring_box.curvalue );
 }
 
-static void LookstrafeFunc( void *unused )
+static void LookstrafeFunc( void * )
 {
 	Cvar_SetValue( "lookstrafe", s_options_lookstrafe_box.curvalue );
 }
 
-static void UpdateVolumeFunc( void *unused )
+static void UpdateVolumeFunc( void * )
 {
 	Cvar_SetValue( "s_volume", s_options_sfxvolume_slider.curvalue / 10 );
 }
 
-static void UpdateCDVolumeFunc( void *unused )
+static void UpdateCDVolumeFunc( void * )
 {
 	Cvar_SetValue( "cd_nocd", !s_options_cdvolume_box.curvalue );
 }
 
-static void ConsoleFunc( void *unused )
+static void ConsoleFunc( void * )
 {
 	/*
 	** the proper way to do this is probably to have ToggleConsole_f accept a parameter
@@ -1165,7 +1165,7 @@
 	cls.key_dest = key_console;
 }
 
-static void UpdateSoundQualityFunc( void *unused )
+static void UpdateSoundQualityFunc( void * )
 {
 	if ( s_options_quality_list.curvalue )
 	{
@@ -1230,8 +1230,8 @@
 	/*
 	** configure controls menu and menu items
 	*/
-	s_options_menu.x = viddef.width / 2;
-	s_options_menu.y = viddef.height / 2 - 58;
+	s_options_menu.x = vid.width / 2;
+	s_options_menu.y = vid.height / 2 - 58;
 	s_options_menu.nitems = 0;
 
 	s_options_sfxvolume_slider.generic.type	= MTYPE_SLIDER;
@@ -1765,10 +1765,10 @@
 	/*
 	** draw the credits
 	*/
-	for ( i = 0, y = viddef.height - ( ( cls.realtime - credits_start_time ) / 40.0F ); credits[i] && y < viddef.height; y += 10, i++ )
+	for ( i = 0, y = vid.height - ( ( cls.realtime - credits_start_time ) / 40.0F ); credits[i] && y < vid.height; y += 10, i++ )
 	{
-		int j, stringoffset = 0;
-		int bold = false;
+		int j, stringoffset;
+		int bold;
 
 		if ( y <= -8 )
 			continue;
@@ -1788,7 +1788,7 @@
 		{
 			int x;
 
-			x = ( viddef.width - strlen( credits[i] ) * 8 - stringoffset * 8 ) / 2 + ( j + stringoffset ) * 8;
+			x = ( vid.width - strlen( credits[i] ) * 8 - stringoffset * 8 ) / 2 + ( j + stringoffset ) * 8;
 
 			if ( bold )
 				re.DrawChar( x, y, credits[i][j+stringoffset] + 128 );
@@ -1823,7 +1823,7 @@
 	int		n;
 	int		count;
 	char	*p;
-	int		isdeveloper = 0;
+	int		isdeveloper;
 
 	creditsBuffer = NULL;
 	count = FS_LoadFile ("credits", &creditsBuffer);
@@ -1904,35 +1904,35 @@
 	cls.key_dest = key_game;
 }
 
-static void EasyGameFunc( void *data )
+static void EasyGameFunc( void * )
 {
 	Cvar_ForceSet( "skill", "0" );
 	StartGame();
 }
 
-static void MediumGameFunc( void *data )
+static void MediumGameFunc( void * )
 {
 	Cvar_ForceSet( "skill", "1" );
 	StartGame();
 }
 
-static void HardGameFunc( void *data )
+static void HardGameFunc( void * )
 {
 	Cvar_ForceSet( "skill", "2" );
 	StartGame();
 }
 
-static void LoadGameFunc( void *unused )
+static void LoadGameFunc( void * )
 {
 	M_Menu_LoadGame_f ();
 }
 
-static void SaveGameFunc( void *unused )
+static void SaveGameFunc( void * )
 {
 	M_Menu_SaveGame_f();
 }
 
-static void CreditsFunc( void *unused )
+static void CreditsFunc( void * )
 {
 	M_Menu_Credits_f();
 }
@@ -1947,7 +1947,7 @@
 		0
 	};
 
-	s_game_menu.x = viddef.width * 0.50;
+	s_game_menu.x = vid.width * 0.50;
 	s_game_menu.nitems = 0;
 
 	s_easy_game_action.generic.type	= MTYPE_ACTION;
@@ -2080,8 +2080,8 @@
 {
 	int i;
 
-	s_loadgame_menu.x = viddef.width / 2 - 120;
-	s_loadgame_menu.y = viddef.height / 2 - 58;
+	s_loadgame_menu.x = vid.width / 2 - 120;
+	s_loadgame_menu.y = vid.height / 2 - 58;
 	s_loadgame_menu.nitems = 0;
 
 	Create_Savestrings();
@@ -2158,8 +2158,8 @@
 {
 	int i;
 
-	s_savegame_menu.x = viddef.width / 2 - 120;
-	s_savegame_menu.y = viddef.height / 2 - 58;
+	s_savegame_menu.x = vid.width / 2 - 120;
+	s_savegame_menu.y = vid.height / 2 - 58;
 	s_savegame_menu.nitems = 0;
 
 	Create_Savestrings();
@@ -2254,7 +2254,7 @@
 
 	index = ( menuaction_s * ) self - s_joinserver_server_actions;
 
-	if ( Q_stricmp( local_server_names[index], NO_SERVER_STRING ) == 0 )
+	if ( Q_strcasecmp( local_server_names[index], NO_SERVER_STRING ) == 0 )
 		return;
 
 	if (index >= m_num_servers)
@@ -2265,12 +2265,12 @@
 	M_ForceMenuOff ();
 }
 
-void AddressBookFunc( void *self )
+void AddressBookFunc( void * )
 {
 	M_Menu_AddressBook_f();
 }
 
-void NullCursorDraw( void *self )
+void NullCursorDraw( void * )
 {
 }
 
@@ -2294,7 +2294,7 @@
 	CL_PingServers_f();
 }
 
-void SearchLocalGamesFunc( void *self )
+void SearchLocalGamesFunc( void * )
 {
 	SearchLocalGames();
 }
@@ -2303,7 +2303,7 @@
 {
 	int i;
 
-	s_joinserver_menu.x = viddef.width * 0.50 - 120;
+	s_joinserver_menu.x = vid.width * 0.50 - 120;
 	s_joinserver_menu.nitems = 0;
 
 	s_joinserver_address_book_action.generic.type	= MTYPE_ACTION;
@@ -2389,7 +2389,7 @@
 static menulist_s	s_startmap_list;
 static menulist_s	s_rules_box;
 
-void DMOptionsFunc( void *self )
+void DMOptionsFunc( void * )
 {
 	if (s_rules_box.curvalue == 1)
 		return;
@@ -2396,7 +2396,7 @@
 	M_Menu_DMOptions_f();
 }
 
-void RulesChangeFunc ( void *self )
+void RulesChangeFunc ( void * )
 {
 	// DM
 	if (s_rules_box.curvalue == 0)
@@ -2433,7 +2433,7 @@
 //=====
 }
 
-void StartServerActionFunc( void *self )
+void StartServerActionFunc( void * )
 {
 	char	startmap[1024];
 	int		timelimit;
@@ -2472,21 +2472,21 @@
 	spot = NULL;
 	if (s_rules_box.curvalue == 1)		// PGM
 	{
- 		if(Q_stricmp(startmap, "bunk1") == 0)
+ 		if(Q_strcasecmp(startmap, "bunk1") == 0)
   			spot = "start";
- 		else if(Q_stricmp(startmap, "mintro") == 0)
+ 		else if(Q_strcasecmp(startmap, "mintro") == 0)
   			spot = "start";
- 		else if(Q_stricmp(startmap, "fact1") == 0)
+ 		else if(Q_strcasecmp(startmap, "fact1") == 0)
   			spot = "start";
- 		else if(Q_stricmp(startmap, "power1") == 0)
+ 		else if(Q_strcasecmp(startmap, "power1") == 0)
   			spot = "pstart";
- 		else if(Q_stricmp(startmap, "biggun") == 0)
+ 		else if(Q_strcasecmp(startmap, "biggun") == 0)
   			spot = "bstart";
- 		else if(Q_stricmp(startmap, "hangar1") == 0)
+ 		else if(Q_strcasecmp(startmap, "hangar1") == 0)
   			spot = "unitstart";
- 		else if(Q_stricmp(startmap, "city1") == 0)
+ 		else if(Q_strcasecmp(startmap, "city1") == 0)
   			spot = "unitstart";
- 		else if(Q_stricmp(startmap, "boss1") == 0)
+ 		else if(Q_strcasecmp(startmap, "boss1") == 0)
 			spot = "bosstart";
 	}
 
@@ -2592,7 +2592,6 @@
 
 	if ( fp != 0 )
 	{
-		fp = 0;
 		free( buffer );
 	}
 	else
@@ -2603,7 +2602,7 @@
 	/*
 	** initialize the menu stuff
 	*/
-	s_startserver_menu.x = viddef.width * 0.50;
+	s_startserver_menu.x = vid.width * 0.50;
 	s_startserver_menu.nitems = 0;
 
 	s_startmap_list.generic.type = MTYPE_SPINCONTROL;
@@ -2929,7 +2928,7 @@
 	int dmflags = Cvar_VariableValue( "dmflags" );
 	int y = 0;
 
-	s_dmoptions_menu.x = viddef.width * 0.50;
+	s_dmoptions_menu.x = vid.width * 0.50;
 	s_dmoptions_menu.nitems = 0;
 
 	s_falls_box.generic.type = MTYPE_SPINCONTROL;
@@ -3196,7 +3195,7 @@
 	};
 	int y = 0;
 
-	s_downloadoptions_menu.x = viddef.width * 0.50;
+	s_downloadoptions_menu.x = vid.width * 0.50;
 	s_downloadoptions_menu.nitems = 0;
 
 	s_download_title.generic.type = MTYPE_SEPARATOR;
@@ -3289,8 +3288,8 @@
 {
 	int i;
 
-	s_addressbook_menu.x = viddef.width / 2 - 142;
-	s_addressbook_menu.y = viddef.height / 2 - 58;
+	s_addressbook_menu.x = vid.width / 2 - 142;
+	s_addressbook_menu.y = vid.height / 2 - 58;
 	s_addressbook_menu.nitems = 0;
 
 	for ( i = 0; i < NUM_ADDRESSBOOK_ENTRIES; i++ )
@@ -3384,23 +3383,23 @@
 static const char *rate_names[] = { "28.8 Modem", "33.6 Modem", "Single ISDN",
 	"Dual ISDN/Cable", "T1/LAN", "User defined", 0 };
 
-void DownloadOptionsFunc( void *self )
+void DownloadOptionsFunc( void * )
 {
 	M_Menu_DownloadOptions_f();
 }
 
-static void HandednessCallback( void *unused )
+static void HandednessCallback( void * )
 {
 	Cvar_SetValue( "hand", s_player_handedness_box.curvalue );
 }
 
-static void RateCallback( void *unused )
+static void RateCallback( void * )
 {
 	if (s_player_rate_box.curvalue != sizeof(rate_tbl) / sizeof(*rate_tbl) - 1)
 		Cvar_SetValue( "rate", rate_tbl[s_player_rate_box.curvalue] );
 }
 
-static void ModelCallback( void *unused )
+static void ModelCallback( void * )
 {
 	s_player_skin_box.itemnames = s_pmi[s_player_model_box.curvalue].skindisplaynames;
 	s_player_skin_box.curvalue = 0;
@@ -3443,8 +3442,8 @@
 {
 	char findname[1024];
 	char scratch[1024];
-	int ndirs = 0, npms = 0;
-	char **dirnames;
+	int ndirs = 0, npms;
+	char **dirnames = NULL;
 	char *path = NULL;
 	int i;
 
@@ -3578,6 +3577,7 @@
 	}
 	if ( dirnames )
 		FreeFileList( dirnames, ndirs );
+	return true;
 }
 
 static int pmicmpfnc( const void *_a, const void *_b )
@@ -3609,7 +3609,7 @@
 	extern cvar_t *skin;
 	char currentdirectory[1024];
 	char currentskin[1024];
-	int i = 0;
+	int i;
 
 	int currentdirectoryindex = 0;
 	int currentskinindex = 0;
@@ -3650,7 +3650,7 @@
 	for ( i = 0; i < s_numplayermodels; i++ )
 	{
 		s_pmnames[i] = s_pmi[i].displayname;
-		if ( Q_stricmp( s_pmi[i].directory, currentdirectory ) == 0 )
+		if ( Q_strcasecmp( s_pmi[i].directory, currentdirectory ) == 0 )
 		{
 			int j;
 
@@ -3658,7 +3658,7 @@
 
 			for ( j = 0; j < s_pmi[i].nskins; j++ )
 			{
-				if ( Q_stricmp( s_pmi[i].skindisplaynames[j], currentskin ) == 0 )
+				if ( Q_strcasecmp( s_pmi[i].skindisplaynames[j], currentskin ) == 0 )
 				{
 					currentskinindex = j;
 					break;
@@ -3667,8 +3667,8 @@
 		}
 	}
 
-	s_player_config_menu.x = viddef.width / 2 - 95; 
-	s_player_config_menu.y = viddef.height / 2 - 97;
+	s_player_config_menu.x = vid.width / 2 - 95; 
+	s_player_config_menu.y = vid.height / 2 - 97;
 	s_player_config_menu.nitems = 0;
 
 	s_player_name_field.generic.type = MTYPE_FIELD;
@@ -3773,8 +3773,8 @@
 
 	memset( &refdef, 0, sizeof( refdef ) );
 
-	refdef.x = viddef.width / 2;
-	refdef.y = viddef.height / 2 - 72;
+	refdef.x = vid.width / 2;
+	refdef.y = vid.height / 2 - 72;
 	refdef.width = 144;
 	refdef.height = 168;
 	refdef.fov_x = 40;
@@ -3784,7 +3784,6 @@
 	if ( s_pmi[s_player_model_box.curvalue].skindisplaynames )
 	{
 		static int yaw;
-		int maxframe = 29;
 		entity_t entity;
 
 		memset( &entity, 0, sizeof( entity ) );
@@ -3813,7 +3812,7 @@
 
 		Menu_Draw( &s_player_config_menu );
 
-		M_DrawTextBox( ( refdef.x ) * ( 320.0F / viddef.width ) - 8, ( viddef.height / 2 ) * ( 240.0F / viddef.height) - 77, refdef.width / 8, refdef.height / 8 );
+		M_DrawTextBox( ( refdef.x ) * ( 320.0F / vid.width ) - 8, ( vid.height / 2 ) * ( 240.0F / vid.height) - 77, refdef.width / 8, refdef.height / 8 );
 		refdef.height += 4;
 
 		re.RenderFrame( &refdef );
@@ -3879,7 +3878,7 @@
 
 =======================================================================
 */
-#if 0
+/* commented out in release
 void M_Menu_Gallery_f( void )
 {
 	extern void Gallery_MenuDraw( void );
@@ -3887,7 +3886,7 @@
 
 	M_PushMenu( Gallery_MenuDraw, Gallery_MenuKey );
 }
-#endif
+*/
 
 /*
 =======================================================================
@@ -3927,7 +3926,7 @@
 	int		w, h;
 
 	re.DrawGetPicSize (&w, &h, "quit");
-	re.DrawPic ( (viddef.width-w)/2, (viddef.height-h)/2, "quit");
+	re.DrawPic ( (vid.width-w)/2, (vid.height-h)/2, "quit");
 }
 
 
@@ -3983,7 +3982,7 @@
 
 	// dim everything behind it down
 	if (cl.cinematictime > 0)
-		re.DrawFill (0,0,viddef.width, viddef.height, 0);
+		re.DrawFill (0,0,vid.width, vid.height, 0);
 	else
 		re.DrawFadeScreen ();
 
--- a/client/qmenu.c
+++ b/client/qmenu.c
@@ -17,33 +17,31 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-#include <string.h>
+
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
 #include <ctype.h>
+#include "../dat.h"
+#include "../fns.h"
 
-#include "client.h"
-#include "qmenu.h"
+void	 Action_DoEnter( menuaction_s *a );
+void	 Action_Draw( menuaction_s *a );
+void  Menu_DrawStatusBar( const char *string );
+void	 Menulist_DoEnter( menulist_s *l );
+void	 MenuList_Draw( menulist_s *l );
+void	 Separator_Draw( menuseparator_s *s );
+void	 Slider_DoSlide( menuslider_s *s, int dir );
+void	 Slider_Draw( menuslider_s *s );
+void	 SpinControl_DoEnter( menulist_s *s );
+void	 SpinControl_Draw( menulist_s *s );
+void	 SpinControl_DoSlide( menulist_s *s, int dir );
 
-static void	 Action_DoEnter( menuaction_s *a );
-static void	 Action_Draw( menuaction_s *a );
-static void  Menu_DrawStatusBar( const char *string );
-static void	 Menulist_DoEnter( menulist_s *l );
-static void	 MenuList_Draw( menulist_s *l );
-static void	 Separator_Draw( menuseparator_s *s );
-static void	 Slider_DoSlide( menuslider_s *s, int dir );
-static void	 Slider_Draw( menuslider_s *s );
-static void	 SpinControl_DoEnter( menulist_s *s );
-static void	 SpinControl_Draw( menulist_s *s );
-static void	 SpinControl_DoSlide( menulist_s *s, int dir );
-
 #define RCOLUMN_OFFSET  16
 #define LCOLUMN_OFFSET -16
 
 extern refexport_t re;
-extern viddef_t viddef;
 
-#define VID_WIDTH viddef.width
-#define VID_HEIGHT viddef.height
-
 #define Draw_Char re.DrawChar
 #define Draw_Fill re.DrawFill
 
@@ -339,7 +337,7 @@
 	height = ( ( menucommon_s * ) menu->items[menu->nitems-1])->y;
 	height += 10;
 
-	menu->y = ( VID_HEIGHT - height ) / 2;
+	menu->y = ( vid.height - height ) / 2;
 }
 
 void Menu_Draw( menuframework_s *menu )
@@ -418,16 +416,16 @@
 	if ( string )
 	{
 		int l = strlen( string );
-		int maxrow = VID_HEIGHT / 8;
-		int maxcol = VID_WIDTH / 8;
+		//int maxrow = vid.height / 8;
+		int maxcol = vid.width / 8;
 		int col = maxcol / 2 - l / 2;
 
-		Draw_Fill( 0, VID_HEIGHT-8, VID_WIDTH, 8, 4 );
-		Menu_DrawString( col*8, VID_HEIGHT - 8, string );
+		Draw_Fill( 0, vid.height-8, vid.width, 8, 4 );
+		Menu_DrawString( col*8, vid.height - 8, string );
 	}
 	else
 	{
-		Draw_Fill( 0, VID_HEIGHT-8, VID_WIDTH, 8, 0 );
+		Draw_Fill( 0, vid.height-8, vid.width, 8, 0 );
 	}
 }
 
--- a/client/qmenu.h
+++ b/client/qmenu.h
@@ -29,19 +29,6 @@
 #define MTYPE_SEPARATOR  	4
 #define MTYPE_FIELD			5
 
-#define	K_TAB			9
-#define	K_ENTER			13
-#define	K_ESCAPE		27
-#define	K_SPACE			32
-
-// normal keys should be passed as lowercased ascii
-
-#define	K_BACKSPACE		127
-#define	K_UPARROW		128
-#define	K_DOWNARROW		129
-#define	K_LEFTARROW		130
-#define	K_RIGHTARROW	131
-
 #define QMF_LEFT_JUSTIFY	0x00000001
 #define QMF_GRAYED			0x00000002
 #define QMF_NUMBERSONLY		0x00000004
--- a/client/ref.h
+++ b/client/ref.h
@@ -18,12 +18,10 @@
 
 */
 
-#include "../qcommon/qcommon.h"
-
 #define	MAX_DLIGHTS		32
 #define	MAX_ENTITIES	128
 #define	MAX_PARTICLES	4096
-#define	MAX_LIGHTSTYLES	256
+//#define	MAX_LIGHTSTYLES	256	/* macro redifinition */
 
 #define POWERSUIT_SCALE		4.0F
 
--- a/client/snd_dma.c
+++ b/client/snd_dma.c
@@ -19,12 +19,15 @@
 */
 // snd_dma.c -- main control for any streaming sound output device
 
-#include "client.h"
-#include "snd_loc.h"
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 
 void S_Play(void);
 void S_SoundList(void);
-void S_Update_();
+void S_Update_(void);
 void S_StopAllSounds(void);
 
 
@@ -1011,7 +1014,6 @@
 	int			i;
 	int			total;
 	channel_t	*ch;
-	channel_t	*combine;
 
 	if (!sound_started)
 		return;
@@ -1033,8 +1035,6 @@
 	VectorCopy(forward, listener_forward);
 	VectorCopy(right, listener_right);
 	VectorCopy(up, listener_up);
-
-	combine = NULL;
 
 	// update spatialization for dynamic sounds	
 	ch = channels;
--- a/client/snd_mem.c
+++ b/client/snd_mem.c
@@ -18,10 +18,12 @@
 
 */
 // snd_mem.c: sound caching
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 
-#include "client.h"
-#include "snd_loc.h"
-
 int			cache_full_cycle;
 
 byte *S_Alloc (int size);
@@ -189,7 +191,7 @@
 
 short GetLittleShort(void)
 {
-	short val = 0;
+	short val;
 	val = *data_p;
 	val = val + (*(data_p+1)<<8);
 	data_p += 2;
@@ -198,7 +200,7 @@
 
 int GetLittleLong(void)
 {
-	int val = 0;
+	int val;
 	val = *data_p;
 	val = val + (*(data_p+1)<<8);
 	val = val + (*(data_p+2)<<16);
@@ -230,7 +232,7 @@
 //			Sys_Error ("FindNextChunk: %i length is past the 1 meg sanity limit", iff_chunk_len);
 		data_p -= 8;
 		last_chunk = data_p + 8 + ( (iff_chunk_len + 1) & ~1 );
-		if (!strncmp(data_p, name, 4))
+		if (!strncmp((char *)data_p, name, 4))
 			return;
 	}
 }
@@ -253,7 +255,7 @@
 		memcpy (str, data_p, 4);
 		data_p += 4;
 		iff_chunk_len = GetLittleLong();
-		Com_Printf ("0x%x : %s (%d)\n", (int)(data_p - 4), str, iff_chunk_len);
+		Com_Printf ("0x%x : %s (%p)\n", (uintptr)(data_p - 4), str, iff_chunk_len);
 		data_p += (iff_chunk_len + 1) & ~1;
 	} while (data_p < iff_end);
 }
@@ -280,7 +282,7 @@
 
 // find "RIFF" chunk
 	FindChunk("RIFF");
-	if (!(data_p && !strncmp(data_p+8, "WAVE", 4)))
+	if (!(data_p && !strncmp((char *)data_p+8, "WAVE", 4)))
 	{
 		Com_Printf("Missing RIFF/WAVE chunks\n");
 		return info;
@@ -321,7 +323,7 @@
 		FindNextChunk ("LIST");
 		if (data_p)
 		{
-			if (!strncmp (data_p + 28, "mark", 4))
+			if (!strncmp ((char *)data_p + 28, "mark", 4))
 			{	// this is not a proper parse, but it works with cooledit...
 				data_p += 24;
 				i = GetLittleLong ();	// samples in loop
--- a/client/snd_mix.c
+++ b/client/snd_mix.c
@@ -19,8 +19,11 @@
 */
 // snd_mix.c -- portable code to mix sounds for snd_dma.c
 
-#include "client.h"
-#include "snd_loc.h"
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 
 #define	PAINTBUFFER_SIZE	2048
 portable_samplepair_t paintbuffer[PAINTBUFFER_SIZE];
@@ -28,11 +31,7 @@
 int 	*snd_p, snd_linear_count, snd_vol;
 short	*snd_out;
 
-void S_WriteLinearBlastStereo16 (void);
 
-#if !(defined __linux__ && defined __i386__)
-#if	!id386
-
 void S_WriteLinearBlastStereo16 (void)
 {
 	int		i;
@@ -57,54 +56,7 @@
 			snd_out[i+1] = val;
 	}
 }
-#else
-__declspec( naked ) void S_WriteLinearBlastStereo16 (void)
-{
-	__asm {
 
- push edi
- push ebx
- mov ecx,ds:dword ptr[snd_linear_count]
- mov ebx,ds:dword ptr[snd_p]
- mov edi,ds:dword ptr[snd_out]
-LWLBLoopTop:
- mov eax,ds:dword ptr[-8+ebx+ecx*4]
- sar eax,8
- cmp eax,07FFFh
- jg LClampHigh
- cmp eax,0FFFF8000h
- jnl LClampDone
- mov eax,0FFFF8000h
- jmp LClampDone
-LClampHigh:
- mov eax,07FFFh
-LClampDone:
- mov edx,ds:dword ptr[-4+ebx+ecx*4]
- sar edx,8
- cmp edx,07FFFh
- jg LClampHigh2
- cmp edx,0FFFF8000h
- jnl LClampDone2
- mov edx,0FFFF8000h
- jmp LClampDone2
-LClampHigh2:
- mov edx,07FFFh
-LClampDone2:
- shl edx,16
- and eax,0FFFFh
- or edx,eax
- mov ds:dword ptr[-4+edi+ecx*2],edx
- sub ecx,2
- jnz LWLBLoopTop
- pop ebx
- pop edi
- ret
-	}
-}
-
-#endif
-#endif
-
 void S_TransferStereo16 (unsigned long *pbuf, int endtime)
 {
 	int		lpos;
@@ -361,10 +313,6 @@
 	}
 }
 
-
-#if !(defined __linux__ && defined __i386__)
-#if	!id386
-
 void S_PaintChannelFrom8 (channel_t *ch, sfxcache_t *sc, int count, int offset)
 {
 	int 	data;
@@ -380,7 +328,7 @@
 		
 	lscale = snd_scaletable[ ch->leftvol >> 11];
 	rscale = snd_scaletable[ ch->rightvol >> 11];
-	sfx = (signed char *)sc->data + ch->pos;
+	sfx = (uchar *)sc->data + ch->pos;
 
 	samp = &paintbuffer[offset];
 
@@ -394,81 +342,6 @@
 	ch->pos += count;
 }
 
-#else
-
-__declspec( naked ) void S_PaintChannelFrom8 (channel_t *ch, sfxcache_t *sc, int count, int offset)
-{
-	__asm {
- push esi
- push edi
- push ebx
- push ebp
- mov ebx,ds:dword ptr[4+16+esp]
- mov esi,ds:dword ptr[8+16+esp]
- mov eax,ds:dword ptr[4+ebx]
- mov edx,ds:dword ptr[8+ebx]
- cmp eax,255
- jna LLeftSet
- mov eax,255
-LLeftSet:
- cmp edx,255
- jna LRightSet
- mov edx,255
-LRightSet:
- and eax,0F8h
- add esi,20
- and edx,0F8h
- mov edi,ds:dword ptr[16+ebx]
- mov ecx,ds:dword ptr[12+16+esp]
- add esi,edi
- shl eax,7
- add edi,ecx
- shl edx,7
- mov ds:dword ptr[16+ebx],edi
- add eax,offset snd_scaletable
- add edx,offset snd_scaletable
- sub ebx,ebx
- mov bl,ds:byte ptr[-1+esi+ecx*1]
- test ecx,1
- jz LMix8Loop
- mov edi,ds:dword ptr[eax+ebx*4]
- mov ebp,ds:dword ptr[edx+ebx*4]
- add edi,ds:dword ptr[paintbuffer+0-8+ecx*8]
- add ebp,ds:dword ptr[paintbuffer+4-8+ecx*8]
- mov ds:dword ptr[paintbuffer+0-8+ecx*8],edi
- mov ds:dword ptr[paintbuffer+4-8+ecx*8],ebp
- mov bl,ds:byte ptr[-2+esi+ecx*1]
- dec ecx
- jz LDone
-LMix8Loop:
- mov edi,ds:dword ptr[eax+ebx*4]
- mov ebp,ds:dword ptr[edx+ebx*4]
- add edi,ds:dword ptr[paintbuffer+0-8+ecx*8]
- add ebp,ds:dword ptr[paintbuffer+4-8+ecx*8]
- mov bl,ds:byte ptr[-2+esi+ecx*1]
- mov ds:dword ptr[paintbuffer+0-8+ecx*8],edi
- mov ds:dword ptr[paintbuffer+4-8+ecx*8],ebp
- mov edi,ds:dword ptr[eax+ebx*4]
- mov ebp,ds:dword ptr[edx+ebx*4]
- mov bl,ds:byte ptr[-3+esi+ecx*1]
- add edi,ds:dword ptr[paintbuffer+0-8*2+ecx*8]
- add ebp,ds:dword ptr[paintbuffer+4-8*2+ecx*8]
- mov ds:dword ptr[paintbuffer+0-8*2+ecx*8],edi
- mov ds:dword ptr[paintbuffer+4-8*2+ecx*8],ebp
- sub ecx,2
- jnz LMix8Loop
-LDone:
- pop ebp
- pop ebx
- pop edi
- pop esi
- ret
-	}
-}
-
-#endif
-#endif
-
 void S_PaintChannelFrom16 (channel_t *ch, sfxcache_t *sc, int count, int offset)
 {
 	int data;
@@ -494,4 +367,3 @@
 
 	ch->pos += count;
 }
-
--- a/client/sound.h
+++ b/client/sound.h
@@ -24,7 +24,7 @@
 void S_Shutdown (void);
 
 // if origin is NULL, the sound will be dynamically sourced from the entity
-void S_StartSound (vec3_t origin, int entnum, int entchannel, struct sfx_s *sfx, float fvol,  float attenuation, float timeofs);
+void S_StartSound (vec3_t origin, int entnum, int entchannel, sfx_t *sfx, float fvol,  float attenuation, float timeofs);
 void S_StartLocalSound (char *s);
 
 void S_RawSamples (int samples, int rate, int width, int channels, byte *data);
@@ -35,10 +35,8 @@
 void S_Activate (qboolean active);
 
 void S_BeginRegistration (void);
-struct sfx_s *S_RegisterSound (char *sample);
+sfx_t *S_RegisterSound (char *sample);
 void S_EndRegistration (void);
-
-struct sfx_s *S_FindName (char *name, qboolean create);
 
 // the sound code makes callbacks to the client for entitiy position
 // information, so entities can be dynamically re-spatialized
--- a/client/vid.h
+++ b/client/vid.h
@@ -19,18 +19,28 @@
 */
 // vid.h -- video driver defs
 
-typedef struct vrect_s
-{
-	int				x,y,width,height;
-} vrect_t;
+typedef uchar pixel_t;
 
-typedef struct
+typedef struct vrect_t vrect_t;
+typedef struct viddef_t viddef_t;
+
+struct vrect_t
 {
-	int		width;		
-	int		height;
-} viddef_t;
+	int	x, y, width, height;
+	vrect_t	*pnext;
+};
 
-extern	viddef_t	viddef;				// global video state
+struct viddef_t
+{
+	int	width;          
+	int	height;
+	pixel_t	*buffer;                // invisible buffer
+	pixel_t	*colormap;              // 256 * VID_GRADES size
+	pixel_t	*alphamap;              // 256 * 256 translucency map
+	int	rowbytes;               // may be > width if displayed in a window
+					// can be negative for stupid dibs
+};
+extern viddef_t vid;
 
 // Video module initialisation etc
 void	VID_Init (void);
--- a/ctf/g_ai.c
+++ b/ctf/g_ai.c
@@ -17,8 +17,8 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-// g_ai.c
-
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 
 qboolean FindTarget (edict_t *self);
--- a/ctf/g_chase.c
+++ b/ctf/g_chase.c
@@ -17,6 +17,8 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 
 
--- a/ctf/g_cmds.c
+++ b/ctf/g_cmds.c
@@ -17,6 +17,8 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 #include "m_player.h"
 
@@ -176,12 +178,12 @@
 
 	name = gi.args();
 
-	if (Q_stricmp(name, "all") == 0)
+	if (Q_strcasecmp(name, "all") == 0)
 		give_all = true;
 	else
 		give_all = false;
 
-	if (give_all || Q_stricmp(gi.argv(1), "health") == 0)
+	if (give_all || Q_strcasecmp(gi.argv(1), "health") == 0)
 	{
 		if (gi.argc() == 3)
 			ent->health = atoi(gi.argv(2));
@@ -191,7 +193,7 @@
 			return;
 	}
 
-	if (give_all || Q_stricmp(name, "weapons") == 0)
+	if (give_all || Q_strcasecmp(name, "weapons") == 0)
 	{
 		for (i=0 ; i<game.num_items ; i++)
 		{
@@ -206,7 +208,7 @@
 			return;
 	}
 
-	if (give_all || Q_stricmp(name, "ammo") == 0)
+	if (give_all || Q_strcasecmp(name, "ammo") == 0)
 	{
 		for (i=0 ; i<game.num_items ; i++)
 		{
@@ -221,7 +223,7 @@
 			return;
 	}
 
-	if (give_all || Q_stricmp(name, "armor") == 0)
+	if (give_all || Q_strcasecmp(name, "armor") == 0)
 	{
 		gitem_armor_t	*info;
 
@@ -239,7 +241,7 @@
 			return;
 	}
 
-	if (give_all || Q_stricmp(name, "Power Shield") == 0)
+	if (give_all || Q_strcasecmp(name, "Power Shield") == 0)
 	{
 		it = FindItem("Power Shield");
 		it_ent = G_Spawn();
@@ -446,7 +448,7 @@
 	char		*s;
 
 //ZOID--special case for tech powerups
-	if (Q_stricmp(gi.args(), "tech") == 0 && (it = CTFWhat_Tech(ent)) != NULL) {
+	if (Q_strcasecmp(gi.args(), "tech") == 0 && (it = CTFWhat_Tech(ent)) != NULL) {
 		it->drop (ent, it);
 		return;
 	}
@@ -960,27 +962,27 @@
 
 	cmd = gi.argv(0);
 
-	if (Q_stricmp (cmd, "players") == 0)
+	if (Q_strcasecmp (cmd, "players") == 0)
 	{
 		Cmd_Players_f (ent);
 		return;
 	}
-	if (Q_stricmp (cmd, "say") == 0)
+	if (Q_strcasecmp (cmd, "say") == 0)
 	{
 		Cmd_Say_f (ent, false, false);
 		return;
 	}
-	if (Q_stricmp (cmd, "say_team") == 0 || Q_stricmp (cmd, "steam") == 0)
+	if (Q_strcasecmp (cmd, "say_team") == 0 || Q_strcasecmp (cmd, "steam") == 0)
 	{
 		CTFSay_Team(ent, gi.args());
 		return;
 	}
-	if (Q_stricmp (cmd, "score") == 0)
+	if (Q_strcasecmp (cmd, "score") == 0)
 	{
 		Cmd_Score_f (ent);
 		return;
 	}
-	if (Q_stricmp (cmd, "help") == 0)
+	if (Q_strcasecmp (cmd, "help") == 0)
 	{
 		Cmd_Help_f (ent);
 		return;
@@ -989,75 +991,75 @@
 	if (level.intermissiontime)
 		return;
 
-	if (Q_stricmp (cmd, "use") == 0)
+	if (Q_strcasecmp (cmd, "use") == 0)
 		Cmd_Use_f (ent);
-	else if (Q_stricmp (cmd, "drop") == 0)
+	else if (Q_strcasecmp (cmd, "drop") == 0)
 		Cmd_Drop_f (ent);
-	else if (Q_stricmp (cmd, "give") == 0)
+	else if (Q_strcasecmp (cmd, "give") == 0)
 		Cmd_Give_f (ent);
-	else if (Q_stricmp (cmd, "god") == 0)
+	else if (Q_strcasecmp (cmd, "god") == 0)
 		Cmd_God_f (ent);
-	else if (Q_stricmp (cmd, "notarget") == 0)
+	else if (Q_strcasecmp (cmd, "notarget") == 0)
 		Cmd_Notarget_f (ent);
-	else if (Q_stricmp (cmd, "noclip") == 0)
+	else if (Q_strcasecmp (cmd, "noclip") == 0)
 		Cmd_Noclip_f (ent);
-	else if (Q_stricmp (cmd, "inven") == 0)
+	else if (Q_strcasecmp (cmd, "inven") == 0)
 		Cmd_Inven_f (ent);
-	else if (Q_stricmp (cmd, "invnext") == 0)
+	else if (Q_strcasecmp (cmd, "invnext") == 0)
 		SelectNextItem (ent, -1);
-	else if (Q_stricmp (cmd, "invprev") == 0)
+	else if (Q_strcasecmp (cmd, "invprev") == 0)
 		SelectPrevItem (ent, -1);
-	else if (Q_stricmp (cmd, "invnextw") == 0)
+	else if (Q_strcasecmp (cmd, "invnextw") == 0)
 		SelectNextItem (ent, IT_WEAPON);
-	else if (Q_stricmp (cmd, "invprevw") == 0)
+	else if (Q_strcasecmp (cmd, "invprevw") == 0)
 		SelectPrevItem (ent, IT_WEAPON);
-	else if (Q_stricmp (cmd, "invnextp") == 0)
+	else if (Q_strcasecmp (cmd, "invnextp") == 0)
 		SelectNextItem (ent, IT_POWERUP);
-	else if (Q_stricmp (cmd, "invprevp") == 0)
+	else if (Q_strcasecmp (cmd, "invprevp") == 0)
 		SelectPrevItem (ent, IT_POWERUP);
-	else if (Q_stricmp (cmd, "invuse") == 0)
+	else if (Q_strcasecmp (cmd, "invuse") == 0)
 		Cmd_InvUse_f (ent);
-	else if (Q_stricmp (cmd, "invdrop") == 0)
+	else if (Q_strcasecmp (cmd, "invdrop") == 0)
 		Cmd_InvDrop_f (ent);
-	else if (Q_stricmp (cmd, "weapprev") == 0)
+	else if (Q_strcasecmp (cmd, "weapprev") == 0)
 		Cmd_WeapPrev_f (ent);
-	else if (Q_stricmp (cmd, "weapnext") == 0)
+	else if (Q_strcasecmp (cmd, "weapnext") == 0)
 		Cmd_WeapNext_f (ent);
-	else if (Q_stricmp (cmd, "weaplast") == 0)
+	else if (Q_strcasecmp (cmd, "weaplast") == 0)
 		Cmd_WeapLast_f (ent);
-	else if (Q_stricmp (cmd, "kill") == 0)
+	else if (Q_strcasecmp (cmd, "kill") == 0)
 		Cmd_Kill_f (ent);
-	else if (Q_stricmp (cmd, "putaway") == 0)
+	else if (Q_strcasecmp (cmd, "putaway") == 0)
 		Cmd_PutAway_f (ent);
-	else if (Q_stricmp (cmd, "wave") == 0)
+	else if (Q_strcasecmp (cmd, "wave") == 0)
 		Cmd_Wave_f (ent);
 //ZOID
-	else if (Q_stricmp (cmd, "team") == 0)
+	else if (Q_strcasecmp (cmd, "team") == 0)
 	{
 		CTFTeam_f (ent);
-	} else if (Q_stricmp(cmd, "id") == 0) {
+	} else if (Q_strcasecmp(cmd, "id") == 0) {
 		CTFID_f (ent);
-	} else if (Q_stricmp(cmd, "yes") == 0) {
+	} else if (Q_strcasecmp(cmd, "yes") == 0) {
 		CTFVoteYes(ent);
-	} else if (Q_stricmp(cmd, "no") == 0) {
+	} else if (Q_strcasecmp(cmd, "no") == 0) {
 		CTFVoteNo(ent);
-	} else if (Q_stricmp(cmd, "ready") == 0) {
+	} else if (Q_strcasecmp(cmd, "ready") == 0) {
 		CTFReady(ent);
-	} else if (Q_stricmp(cmd, "notready") == 0) {
+	} else if (Q_strcasecmp(cmd, "notready") == 0) {
 		CTFNotReady(ent);
-	} else if (Q_stricmp(cmd, "ghost") == 0) {
+	} else if (Q_strcasecmp(cmd, "ghost") == 0) {
 		CTFGhost(ent);
-	} else if (Q_stricmp(cmd, "admin") == 0) {
+	} else if (Q_strcasecmp(cmd, "admin") == 0) {
 		CTFAdmin(ent);
-	} else if (Q_stricmp(cmd, "stats") == 0) {
+	} else if (Q_strcasecmp(cmd, "stats") == 0) {
 		CTFStats(ent);
-	} else if (Q_stricmp(cmd, "warp") == 0) {
+	} else if (Q_strcasecmp(cmd, "warp") == 0) {
 		CTFWarp(ent);
-	} else if (Q_stricmp(cmd, "boot") == 0) {
+	} else if (Q_strcasecmp(cmd, "boot") == 0) {
 		CTFBoot(ent);
-	} else if (Q_stricmp(cmd, "playerlist") == 0) {
+	} else if (Q_strcasecmp(cmd, "playerlist") == 0) {
 		CTFPlayerList(ent);
-	} else if (Q_stricmp(cmd, "observer") == 0) {
+	} else if (Q_strcasecmp(cmd, "observer") == 0) {
 		CTFObserver(ent);
 	}
 //ZOID
--- a/ctf/g_combat.c
+++ b/ctf/g_combat.c
@@ -17,8 +17,8 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-// g_combat.c
-
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 
 /*
--- a/ctf/g_ctf.c
+++ b/ctf/g_ctf.c
@@ -17,6 +17,8 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 #include "m_player.h"
 
@@ -1533,9 +1535,9 @@
 		return;
 	}
 
-	if (Q_stricmp(t, "red") == 0)
+	if (Q_strcasecmp(t, "red") == 0)
 		desired_team = CTF_TEAM1;
-	else if (Q_stricmp(t, "blue") == 0)
+	else if (Q_strcasecmp(t, "blue") == 0)
 		desired_team = CTF_TEAM2;
 	else {
 		gi.cprintf(ent, PRINT_HIGH, "Unknown team %s.\n", t);
@@ -3946,7 +3948,7 @@
 
 	token = strtok(mlist, seps);
 	while (token != NULL) {
-		if (Q_stricmp(token, gi.argv(1)) == 0)
+		if (Q_strcasecmp(token, gi.argv(1)) == 0)
 			break;
 		token = strtok(NULL, seps);
 	}
--- a/ctf/g_func.c
+++ b/ctf/g_func.c
@@ -17,6 +17,8 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 
 /*
@@ -858,7 +860,7 @@
 
 	while ((t = G_Find (t, FOFS(targetname), self->target)))
 	{
-		if (Q_stricmp(t->classname, "func_areaportal") == 0)
+		if (Q_strcasecmp(t->classname, "func_areaportal") == 0)
 		{
 			gi.SetAreaPortalState (t->style, open);
 		}
--- a/ctf/g_items.c
+++ b/ctf/g_items.c
@@ -17,6 +17,8 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 
 
@@ -84,7 +86,7 @@
 	{
 		if (!it->classname)
 			continue;
-		if (!Q_stricmp(it->classname, classname))
+		if (!Q_strcasecmp(it->classname, classname))
 			return it;
 	}
 
@@ -107,7 +109,7 @@
 	{
 		if (!it->pickup_name)
 			continue;
-		if (!Q_stricmp(it->pickup_name, pickup_name))
+		if (!Q_strcasecmp(it->pickup_name, pickup_name))
 			return it;
 	}
 
--- a/ctf/g_local.h
+++ b/ctf/g_local.h
@@ -19,18 +19,11 @@
 */
 // g_local.h -- local definitions for game module
 
-#include "../q_shared.h"
-
 // define GAME_INCLUDE so that game.h does not define the
 // short, server-visible gclient_t and edict_t structures,
 // because we define the full size ones in this file
 #define	GAME_INCLUDE
-#include "game.h"
 
-//ZOID
-#include "p_menu.h"
-//ZOID
-
 // the "gameversion" client command will print this plus compile date
 #define	GAMEVERSION	"baseq2"
 
@@ -241,10 +234,10 @@
 typedef struct gitem_s
 {
 	char		*classname;	// spawning name
-	qboolean	(*pickup)(struct edict_s *ent, struct edict_s *other);
-	void		(*use)(struct edict_s *ent, struct gitem_s *item);
-	void		(*drop)(struct edict_s *ent, struct gitem_s *item);
-	void		(*weaponthink)(struct edict_s *ent);
+	qboolean	(*pickup)(edict_t *ent, edict_t *other);
+	void		(*use)(edict_t *ent, struct gitem_s *item);
+	void		(*drop)(edict_t *ent, struct gitem_s *item);
+	void		(*weaponthink)(edict_t *ent);
 	char		*pickup_sound;
 	char		*world_model;
 	int			world_model_flags;
@@ -510,13 +503,13 @@
 
 extern	edict_t			*g_edicts;
 
-#define	FOFS(x) (int)&(((edict_t *)0)->x)
-#define	STOFS(x) (int)&(((spawn_temp_t *)0)->x)
-#define	LLOFS(x) (int)&(((level_locals_t *)0)->x)
-#define	CLOFS(x) (int)&(((gclient_t *)0)->x)
+#define	FOFS(x) (uintptr)&(((edict_t *)0)->x)
+#define	STOFS(x) (uintptr)&(((spawn_temp_t *)0)->x)
+#define	LLOFS(x) (uintptr)&(((level_locals_t *)0)->x)
+#define	CLOFS(x) (uintptr)&(((gclient_t *)0)->x)
 
-#define random()	((rand () & 0x7fff) / ((float)0x7fff))
-#define crandom()	(2.0 * (random() - 0.5))
+#define qrandom()	((rand () & 0x7fff) / ((float)0x7fff))
+#define crandom()	(2.0 * (qrandom() - 0.5))
 
 extern	cvar_t	*maxentities;
 extern	cvar_t	*deathmatch;
@@ -983,7 +976,7 @@
 };
 
 
-struct edict_s
+struct edict_t
 {
 	entity_state_t	s;
 	struct gclient_s	*client;	// NULL if not a player
@@ -1131,8 +1124,3 @@
 	moveinfo_t		moveinfo;
 	monsterinfo_t	monsterinfo;
 };
-
-//ZOID
-#include "g_ctf.h"
-//ZOID
-
--- a/ctf/g_main.c
+++ b/ctf/g_main.c
@@ -17,7 +17,8 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 
 game_locals_t	game;
@@ -137,34 +138,7 @@
 	return &globals;
 }
 
-#ifndef GAME_HARD_LINKED
-// this is only here so the functions in q_shared.c and q_shwin.c can link
-void Sys_Error (char *error, ...)
-{
-	va_list		argptr;
-	char		text[1024];
 
-	va_start (argptr, error);
-	vsprintf (text, error, argptr);
-	va_end (argptr);
-
-	gi.error (ERR_FATAL, "%s", text);
-}
-
-void Com_Printf (char *msg, ...)
-{
-	va_list		argptr;
-	char		text[1024];
-
-	va_start (argptr, msg);
-	vsprintf (text, msg, argptr);
-	va_end (argptr);
-
-	gi.dprintf ("%s", text);
-}
-
-#endif
-
 //======================================================================
 
 
@@ -239,7 +213,7 @@
 		f = NULL;
 		t = strtok(s, seps);
 		while (t != NULL) {
-			if (Q_stricmp(t, level.mapname) == 0) {
+			if (Q_strcasecmp(t, level.mapname) == 0) {
 				// it's in the list, go to the next one
 				t = strtok(NULL, seps);
 				if (t == NULL) { // end of list, go to first one
--- a/ctf/g_misc.c
+++ b/ctf/g_misc.c
@@ -17,8 +17,8 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-// g_misc.c
-
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 
 
--- a/ctf/g_monster.c
+++ b/ctf/g_monster.c
@@ -17,6 +17,8 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 
 
--- a/ctf/g_phys.c
+++ b/ctf/g_phys.c
@@ -17,8 +17,8 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-// g_phys.c
-
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 
 /*
--- a/ctf/g_save.c
+++ b/ctf/g_save.c
@@ -17,7 +17,8 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 
 field_t fields[] = {
--- a/ctf/g_spawn.c
+++ b/ctf/g_spawn.c
@@ -17,7 +17,8 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 
 typedef struct
@@ -384,7 +385,7 @@
 
 	for (f=fields ; f->name ; f++)
 	{
-		if (!Q_stricmp(f->name, key))
+		if (!Q_strcasecmp(f->name, key))
 		{	// found it
 			if (f->flags & FFL_SPAWNTEMP)
 				b = (byte *)&st;
--- a/ctf/g_svcmds.c
+++ b/ctf/g_svcmds.c
@@ -17,7 +17,8 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 
 
@@ -40,7 +41,7 @@
 	char	*cmd;
 
 	cmd = gi.argv(1);
-	if (Q_stricmp (cmd, "test") == 0)
+	if (Q_strcasecmp (cmd, "test") == 0)
 		Svcmd_Test_f ();
 	else
 		gi.cprintf (NULL, PRINT_HIGH, "Unknown server command \"%s\"\n", cmd);
--- a/ctf/g_target.c
+++ b/ctf/g_target.c
@@ -17,6 +17,8 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 
 /*QUAKED target_temp_entity (1 0 0) (-8 -8 -8) (8 8 8)
--- a/ctf/g_trigger.c
+++ b/ctf/g_trigger.c
@@ -17,6 +17,8 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 
 
--- a/ctf/g_utils.c
+++ b/ctf/g_utils.c
@@ -18,7 +18,8 @@
 
 */
 // g_utils.c -- misc utility functions for game module
-
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 
 
@@ -58,7 +59,7 @@
 		s = *(char **) ((byte *)from + fieldofs);
 		if (!s)
 			continue;
-		if (!Q_stricmp (s, match))
+		if (!Q_strcasecmp (s, match))
 			return from;
 	}
 
@@ -234,8 +235,8 @@
 		while ((t = G_Find (t, FOFS(targetname), ent->target)))
 		{
 			// doors fire area portals in a specific way
-			if (!Q_stricmp(t->classname, "func_areaportal") &&
-				(!Q_stricmp(ent->classname, "func_door") || !Q_stricmp(ent->classname, "func_door_rotating")))
+			if (!Q_strcasecmp(t->classname, "func_areaportal") &&
+				(!Q_strcasecmp(ent->classname, "func_door") || !Q_strcasecmp(ent->classname, "func_door_rotating")))
 				continue;
 
 			if (t == ent)
--- a/ctf/g_weapon.c
+++ b/ctf/g_weapon.c
@@ -17,6 +17,8 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 
 
--- a/ctf/game.h
+++ b/ctf/game.h
@@ -56,13 +56,13 @@
 #define	MAX_ENT_CLUSTERS	16
 
 
-typedef struct edict_s edict_t;
-typedef struct gclient_s gclient_t;
+typedef struct edict_t edict_t;
+typedef struct gclient_t gclient_t;
 
 
 #ifndef GAME_INCLUDE
 
-struct gclient_s
+struct gclient_t
 {
 	player_state_t	ps;		// communicated by server to clients
 	int				ping;
@@ -71,10 +71,10 @@
 };
 
 
-struct edict_s
+struct edict_t
 {
 	entity_state_t	s;
-	struct gclient_s	*client;
+	gclient_t	*client;
 	qboolean	inuse;
 	int			linkcount;
 
@@ -233,7 +233,7 @@
 	// can vary in size from one game to another.
 	// 
 	// The size will be fixed when ge->Init() is called
-	struct edict_s	*edicts;
+	edict_t	*edicts;
 	int			edict_size;
 	int			num_edicts;		// current number, <= max_edicts
 	int			max_edicts;
--- a/ctf/m_move.c
+++ b/ctf/m_move.c
@@ -18,7 +18,8 @@
 
 */
 // m_move.c -- monster movement
-
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 
 #define	STEPSIZE	18
--- a/ctf/p_client.c
+++ b/ctf/p_client.c
@@ -17,6 +17,8 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 #include "m_player.h"
 
@@ -880,7 +882,7 @@
 		target = spot->targetname;
 		if (!target)
 			target = "";
-		if ( Q_stricmp(game.spawnpoint, target) == 0 )
+		if ( Q_strcasecmp(game.spawnpoint, target) == 0 )
 		{	// this is a coop spawn point for one of the clients here
 			index--;
 			if (!index)
@@ -925,7 +927,7 @@
 			if (!game.spawnpoint[0] || !spot->targetname)
 				continue;
 
-			if (Q_stricmp(game.spawnpoint, spot->targetname) == 0)
+			if (Q_strcasecmp(game.spawnpoint, spot->targetname) == 0)
 				break;
 		}
 
--- a/ctf/p_hud.c
+++ b/ctf/p_hud.c
@@ -17,6 +17,8 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 
 
--- a/ctf/p_menu.c
+++ b/ctf/p_menu.c
@@ -17,6 +17,8 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 
 // Note that the pmenu entries are duplicated
--- a/ctf/p_trail.c
+++ b/ctf/p_trail.c
@@ -17,6 +17,8 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 
 
--- a/ctf/p_view.c
+++ b/ctf/p_view.c
@@ -17,7 +17,8 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 #include "m_player.h"
 
--- a/ctf/p_weapon.c
+++ b/ctf/p_weapon.c
@@ -17,8 +17,8 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-// g_weapon.c
-
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 #include "m_player.h"
 
@@ -559,7 +559,7 @@
 		return;
 
 	if ((CTFApplyHaste(ent) ||
-		(Q_stricmp(ent->client->pers.weapon->pickup_name, "Grapple") == 0 &&
+		(Q_strcasecmp(ent->client->pers.weapon->pickup_name, "Grapple") == 0 &&
 		ent->client->weaponstate != WEAPON_FIRING))
 		&& oldstate == ent->client->weaponstate) {
 		Weapon_Generic2 (ent, FRAME_ACTIVATE_LAST, FRAME_FIRE_LAST, 
--- a/ctf/q_shared.c
+++ b/ctf/q_shared.c
@@ -17,7 +17,8 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-#include "../q_shared.h"
+#include "../dat.h"
+#include "../fns.h"
 
 #define DEG2RAD( a ) ( a * M_PI ) / 180.0F
 
@@ -1180,17 +1181,6 @@
 
 ============================================================================
 */
-
-// FIXME: replace all Q_stricmp with Q_strcasecmp
-int Q_stricmp (char *s1, char *s2)
-{
-#if defined(WIN32)
-	return _stricmp (s1, s2);
-#else
-	return strcasecmp (s1, s2);
-#endif
-}
-
 
 int Q_strncasecmp (char *s1, char *s2, int n)
 {
--- /dev/null
+++ b/dat.h
@@ -1,0 +1,30 @@
+/* FIXME: separate fns + merge some */
+/* common */
+#include "../q_shared.h"
+/* game dll */
+#include "../game/game.h"
+/* ctf dll */
+/*
+#include "../ctf/game.h"
+#include "../ctf/p_menu.h"
+#include "../ctf/g_ctf.h"
+*/
+/* more common */
+#include "../qcommon/qcommon.h"
+#include "../qcommon/qfiles.h"
+/* client */
+#include "../client/cdaudio.h"
+#include "../client/ref.h"
+#include "../client/vid.h"
+#include "../client/screen.h"
+#include "../client/snd_loc.h"
+#include "../client/sound.h"
+#include "../client/input.h"
+#include "../client/keys.h"
+#include "../client/console.h"
+#include "../client/client.h"
+#include "../client/qmenu.h"
+/* refresh */
+#include "../ref/r_local.h"
+/* server */
+#include "../server/server.h"
--- a/game/g_ai.c
+++ b/game/g_ai.c
@@ -17,8 +17,12 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-// g_ai.c
-
+#define	GAME_INCLUDE
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 
 qboolean FindTarget (edict_t *self);
@@ -143,11 +147,11 @@
 		if (self->monsterinfo.idle_time)
 		{
 			self->monsterinfo.idle (self);
-			self->monsterinfo.idle_time = level.time + 15 + random() * 15;
+			self->monsterinfo.idle_time = level.time + 15 + qrandom() * 15;
 		}
 		else
 		{
-			self->monsterinfo.idle_time = level.time + random() * 15;
+			self->monsterinfo.idle_time = level.time + qrandom() * 15;
 		}
 	}
 }
@@ -173,11 +177,11 @@
 		if (self->monsterinfo.idle_time)
 		{
 			self->monsterinfo.search (self);
-			self->monsterinfo.idle_time = level.time + 15 + random() * 15;
+			self->monsterinfo.idle_time = level.time + 15 + qrandom() * 15;
 		}
 		else
 		{
-			self->monsterinfo.idle_time = level.time + random() * 15;
+			self->monsterinfo.idle_time = level.time + qrandom() * 15;
 		}
 	}
 }
@@ -674,16 +678,16 @@
 	else if (skill->value >= 2)
 		chance *= 2;
 
-	if (random () < chance)
+	if (qrandom() < chance)
 	{
 		self->monsterinfo.attack_state = AS_MISSILE;
-		self->monsterinfo.attack_finished = level.time + 2*random();
+		self->monsterinfo.attack_finished = level.time + 2*qrandom();
 		return true;
 	}
 
 	if (self->flags & FL_FLY)
 	{
-		if (random() < 0.3)
+		if (qrandom() < 0.3)
 			self->monsterinfo.attack_state = AS_SLIDING;
 		else
 			self->monsterinfo.attack_state = AS_STRAIGHT;
@@ -768,7 +772,7 @@
 used by ai_run and ai_stand
 =============
 */
-qboolean ai_checkattack (edict_t *self, float dist)
+qboolean ai_checkattack (edict_t *self, float /*dist*/)
 {
 	vec3_t		temp;
 	qboolean	hesDeadJim;
--- a/game/g_chase.c
+++ b/game/g_chase.c
@@ -17,6 +17,12 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
+#define	GAME_INCLUDE
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 
 void UpdateChaseCam(edict_t *ent)
--- a/game/g_cmds.c
+++ b/game/g_cmds.c
@@ -17,6 +17,12 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
+#define	GAME_INCLUDE
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 #include "m_player.h"
 
@@ -166,12 +172,12 @@
 
 	name = gi.args();
 
-	if (Q_stricmp(name, "all") == 0)
+	if (Q_strcasecmp(name, "all") == 0)
 		give_all = true;
 	else
 		give_all = false;
 
-	if (give_all || Q_stricmp(gi.argv(1), "health") == 0)
+	if (give_all || Q_strcasecmp(gi.argv(1), "health") == 0)
 	{
 		if (gi.argc() == 3)
 			ent->health = atoi(gi.argv(2));
@@ -181,7 +187,7 @@
 			return;
 	}
 
-	if (give_all || Q_stricmp(name, "weapons") == 0)
+	if (give_all || Q_strcasecmp(name, "weapons") == 0)
 	{
 		for (i=0 ; i<game.num_items ; i++)
 		{
@@ -196,7 +202,7 @@
 			return;
 	}
 
-	if (give_all || Q_stricmp(name, "ammo") == 0)
+	if (give_all || Q_strcasecmp(name, "ammo") == 0)
 	{
 		for (i=0 ; i<game.num_items ; i++)
 		{
@@ -211,7 +217,7 @@
 			return;
 	}
 
-	if (give_all || Q_stricmp(name, "armor") == 0)
+	if (give_all || Q_strcasecmp(name, "armor") == 0)
 	{
 		gitem_armor_t	*info;
 
@@ -229,7 +235,7 @@
 			return;
 	}
 
-	if (give_all || Q_stricmp(name, "Power Shield") == 0)
+	if (give_all || Q_strcasecmp(name, "Power Shield") == 0)
 	{
 		it = FindItem("Power Shield");
 		it_ent = G_Spawn();
@@ -914,27 +920,27 @@
 
 	cmd = gi.argv(0);
 
-	if (Q_stricmp (cmd, "players") == 0)
+	if (Q_strcasecmp (cmd, "players") == 0)
 	{
 		Cmd_Players_f (ent);
 		return;
 	}
-	if (Q_stricmp (cmd, "say") == 0)
+	if (Q_strcasecmp (cmd, "say") == 0)
 	{
 		Cmd_Say_f (ent, false, false);
 		return;
 	}
-	if (Q_stricmp (cmd, "say_team") == 0)
+	if (Q_strcasecmp (cmd, "say_team") == 0)
 	{
 		Cmd_Say_f (ent, true, false);
 		return;
 	}
-	if (Q_stricmp (cmd, "score") == 0)
+	if (Q_strcasecmp (cmd, "score") == 0)
 	{
 		Cmd_Score_f (ent);
 		return;
 	}
-	if (Q_stricmp (cmd, "help") == 0)
+	if (Q_strcasecmp (cmd, "help") == 0)
 	{
 		Cmd_Help_f (ent);
 		return;
@@ -943,49 +949,49 @@
 	if (level.intermissiontime)
 		return;
 
-	if (Q_stricmp (cmd, "use") == 0)
+	if (Q_strcasecmp (cmd, "use") == 0)
 		Cmd_Use_f (ent);
-	else if (Q_stricmp (cmd, "drop") == 0)
+	else if (Q_strcasecmp (cmd, "drop") == 0)
 		Cmd_Drop_f (ent);
-	else if (Q_stricmp (cmd, "give") == 0)
+	else if (Q_strcasecmp (cmd, "give") == 0)
 		Cmd_Give_f (ent);
-	else if (Q_stricmp (cmd, "god") == 0)
+	else if (Q_strcasecmp (cmd, "god") == 0)
 		Cmd_God_f (ent);
-	else if (Q_stricmp (cmd, "notarget") == 0)
+	else if (Q_strcasecmp (cmd, "notarget") == 0)
 		Cmd_Notarget_f (ent);
-	else if (Q_stricmp (cmd, "noclip") == 0)
+	else if (Q_strcasecmp (cmd, "noclip") == 0)
 		Cmd_Noclip_f (ent);
-	else if (Q_stricmp (cmd, "inven") == 0)
+	else if (Q_strcasecmp (cmd, "inven") == 0)
 		Cmd_Inven_f (ent);
-	else if (Q_stricmp (cmd, "invnext") == 0)
+	else if (Q_strcasecmp (cmd, "invnext") == 0)
 		SelectNextItem (ent, -1);
-	else if (Q_stricmp (cmd, "invprev") == 0)
+	else if (Q_strcasecmp (cmd, "invprev") == 0)
 		SelectPrevItem (ent, -1);
-	else if (Q_stricmp (cmd, "invnextw") == 0)
+	else if (Q_strcasecmp (cmd, "invnextw") == 0)
 		SelectNextItem (ent, IT_WEAPON);
-	else if (Q_stricmp (cmd, "invprevw") == 0)
+	else if (Q_strcasecmp (cmd, "invprevw") == 0)
 		SelectPrevItem (ent, IT_WEAPON);
-	else if (Q_stricmp (cmd, "invnextp") == 0)
+	else if (Q_strcasecmp (cmd, "invnextp") == 0)
 		SelectNextItem (ent, IT_POWERUP);
-	else if (Q_stricmp (cmd, "invprevp") == 0)
+	else if (Q_strcasecmp (cmd, "invprevp") == 0)
 		SelectPrevItem (ent, IT_POWERUP);
-	else if (Q_stricmp (cmd, "invuse") == 0)
+	else if (Q_strcasecmp (cmd, "invuse") == 0)
 		Cmd_InvUse_f (ent);
-	else if (Q_stricmp (cmd, "invdrop") == 0)
+	else if (Q_strcasecmp (cmd, "invdrop") == 0)
 		Cmd_InvDrop_f (ent);
-	else if (Q_stricmp (cmd, "weapprev") == 0)
+	else if (Q_strcasecmp (cmd, "weapprev") == 0)
 		Cmd_WeapPrev_f (ent);
-	else if (Q_stricmp (cmd, "weapnext") == 0)
+	else if (Q_strcasecmp (cmd, "weapnext") == 0)
 		Cmd_WeapNext_f (ent);
-	else if (Q_stricmp (cmd, "weaplast") == 0)
+	else if (Q_strcasecmp (cmd, "weaplast") == 0)
 		Cmd_WeapLast_f (ent);
-	else if (Q_stricmp (cmd, "kill") == 0)
+	else if (Q_strcasecmp (cmd, "kill") == 0)
 		Cmd_Kill_f (ent);
-	else if (Q_stricmp (cmd, "putaway") == 0)
+	else if (Q_strcasecmp (cmd, "putaway") == 0)
 		Cmd_PutAway_f (ent);
-	else if (Q_stricmp (cmd, "wave") == 0)
+	else if (Q_strcasecmp (cmd, "wave") == 0)
 		Cmd_Wave_f (ent);
-	else if (Q_stricmp(cmd, "playerlist") == 0)
+	else if (Q_strcasecmp(cmd, "playerlist") == 0)
 		Cmd_PlayerList_f(ent);
 	else	// anything that doesn't match a command will be a chat
 		Cmd_Say_f (ent, false, true);
--- a/game/g_combat.c
+++ b/game/g_combat.c
@@ -17,8 +17,12 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-// g_combat.c
-
+#define	GAME_INCLUDE
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 
 /*
@@ -131,10 +135,10 @@
 SpawnDamage
 ================
 */
-void SpawnDamage (int type, vec3_t origin, vec3_t normal, int damage)
+void SpawnDamage (int type, vec3_t origin, vec3_t normal, int /*damage*/)
 {
-	if (damage > 255)
-		damage = 255;
+	//if (damage > 255)
+	//	damage = 255;
 	gi.WriteByte (svc_temp_entity);
 	gi.WriteByte (type);
 //	gi.WriteByte (damage);
@@ -173,10 +177,10 @@
 	gclient_t	*client;
 	int			save;
 	int			power_armor_type;
-	int			index;
+	int			index = 0;
 	int			damagePerCell;
 	int			pa_te_type;
-	int			power;
+	int			power = 0;
 	int			power_used;
 
 	if (!damage)
@@ -367,10 +371,10 @@
 	}
 }
 
-qboolean CheckTeamDamage (edict_t *targ, edict_t *attacker)
+qboolean CheckTeamDamage (edict_t */*targ*/, edict_t */*attacker*/)
 {
-		//FIXME make the next line real and uncomment this block
-		// if ((ability to damage a teammate == OFF) && (targ's team == attacker's team))
+	//FIXME make the next line real and uncomment this block
+	// if ((ability to damage a teammate == OFF) && (targ's team == attacker's team))
 	return false;
 }
 
--- a/game/g_func.c
+++ b/game/g_func.c
@@ -17,6 +17,12 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
+#define	GAME_INCLUDE
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 
 /*
@@ -425,7 +431,7 @@
 }
 
 
-void Use_Plat (edict_t *ent, edict_t *other, edict_t *activator)
+void Use_Plat (edict_t *ent, edict_t */*other*/, edict_t */*activator*/)
 { 
 	if (ent->think)
 		return;		// already down
@@ -433,7 +439,7 @@
 }
 
 
-void Touch_Plat_Center (edict_t *ent, edict_t *other, cplane_t *plane, csurface_t *surf)
+void Touch_Plat_Center (edict_t *ent, edict_t *other, cplane_t */*plane*/, csurface_t */*surf*/)
 {
 	if (!other->client)
 		return;
@@ -597,13 +603,13 @@
 	T_Damage (other, self, self, vec3_origin, other->s.origin, vec3_origin, self->dmg, 1, 0, MOD_CRUSH);
 }
 
-void rotating_touch (edict_t *self, edict_t *other, cplane_t *plane, csurface_t *surf)
+void rotating_touch (edict_t *self, edict_t *other, cplane_t */*plane*/, csurface_t */*surf*/)
 {
 	if (self->avelocity[0] || self->avelocity[1] || self->avelocity[2])
 		T_Damage (other, self, self, vec3_origin, other->s.origin, vec3_origin, self->dmg, 1, 0, MOD_CRUSH);
 }
 
-void rotating_use (edict_t *self, edict_t *other, edict_t *activator)
+void rotating_use (edict_t *self, edict_t */*other*/, edict_t */*activator*/)
 {
 	if (!VectorCompare (self->avelocity, vec3_origin))
 	{
@@ -734,13 +740,13 @@
 	Move_Calc (self, self->moveinfo.end_origin, button_wait);
 }
 
-void button_use (edict_t *self, edict_t *other, edict_t *activator)
+void button_use (edict_t *self, edict_t */*other*/, edict_t *activator)
 {
 	self->activator = activator;
 	button_fire (self);
 }
 
-void button_touch (edict_t *self, edict_t *other, cplane_t *plane, csurface_t *surf)
+void button_touch (edict_t *self, edict_t *other, cplane_t */*plane*/, csurface_t */*surf*/)
 {
 	if (!other->client)
 		return;
@@ -752,7 +758,7 @@
 	button_fire (self);
 }
 
-void button_killed (edict_t *self, edict_t *inflictor, edict_t *attacker, int damage, vec3_t point)
+void button_killed (edict_t *self, edict_t */*inflictor*/, edict_t *attacker, int /*damage*/, vec3_t /*point*/)
 {
 	self->activator = attacker;
 	self->health = self->max_health;
@@ -858,7 +864,7 @@
 
 	while ((t = G_Find (t, FOFS(targetname), self->target)))
 	{
-		if (Q_stricmp(t->classname, "func_areaportal") == 0)
+		if (Q_strcasecmp(t->classname, "func_areaportal") == 0)
 		{
 			gi.SetAreaPortalState (t->style, open);
 		}
@@ -946,7 +952,7 @@
 	door_use_areaportals (self, true);
 }
 
-void door_use (edict_t *self, edict_t *other, edict_t *activator)
+void door_use (edict_t *self, edict_t */*other*/, edict_t *activator)
 {
 	edict_t	*ent;
 
@@ -977,7 +983,7 @@
 	}
 };
 
-void Touch_DoorTrigger (edict_t *self, edict_t *other, cplane_t *plane, csurface_t *surf)
+void Touch_DoorTrigger (edict_t *self, edict_t *other, cplane_t */*plane*/, csurface_t */*surf*/)
 {
 	if (other->health <= 0)
 		return;
@@ -1110,7 +1116,7 @@
 	}
 }
 
-void door_killed (edict_t *self, edict_t *inflictor, edict_t *attacker, int damage, vec3_t point)
+void door_killed (edict_t *self, edict_t */*inflictor*/, edict_t *attacker, int /*damage*/, vec3_t /*point*/)
 {
 	edict_t	*ent;
 
@@ -1122,7 +1128,7 @@
 	door_use (self->teammaster, attacker, attacker);
 }
 
-void door_touch (edict_t *self, edict_t *other, cplane_t *plane, csurface_t *surf)
+void door_touch (edict_t *self, edict_t *other, cplane_t */*plane*/, csurface_t */*surf*/)
 {
 	if (!other->client)
 		return;
@@ -1630,7 +1636,7 @@
 	}
 }
 
-void train_use (edict_t *self, edict_t *other, edict_t *activator)
+void train_use (edict_t *self, edict_t */*other*/, edict_t *activator)
 {
 	self->activator = activator;
 
@@ -1696,7 +1702,7 @@
 
 /*QUAKED trigger_elevator (0.3 0.1 0.6) (-8 -8 -8) (8 8 8)
 */
-void trigger_elevator_use (edict_t *self, edict_t *other, edict_t *activator)
+void trigger_elevator_use (edict_t *self, edict_t *other, edict_t */*activator*/)
 {
 	edict_t *target;
 
@@ -1774,7 +1780,7 @@
 	self->nextthink = level.time + self->wait + crandom() * self->random;
 }
 
-void func_timer_use (edict_t *self, edict_t *other, edict_t *activator)
+void func_timer_use (edict_t *self, edict_t */*other*/, edict_t *activator)
 {
 	self->activator = activator;
 
@@ -1822,7 +1828,7 @@
 speed	default 100
 */
 
-void func_conveyor_use (edict_t *self, edict_t *other, edict_t *activator)
+void func_conveyor_use (edict_t *self, edict_t */*other*/, edict_t */*activator*/)
 {
 	if (self->spawnflags & 1)
 	{
@@ -1883,7 +1889,7 @@
 void door_secret_move6 (edict_t *self);
 void door_secret_done (edict_t *self);
 
-void door_secret_use (edict_t *self, edict_t *other, edict_t *activator)
+void door_secret_use (edict_t *self, edict_t */*other*/, edict_t */*activator*/)
 {
 	// make sure we're not already moving
 	if (!VectorCompare(self->s.origin, vec3_origin))
@@ -1957,7 +1963,7 @@
 	T_Damage (other, self, self, vec3_origin, other->s.origin, vec3_origin, self->dmg, 1, 0, MOD_CRUSH);
 }
 
-void door_secret_die (edict_t *self, edict_t *inflictor, edict_t *attacker, int damage, vec3_t point)
+void door_secret_die (edict_t *self, edict_t */*inflictor*/, edict_t *attacker, int /*damage*/, vec3_t /*point*/)
 {
 	self->takedamage = DAMAGE_NO;
 	door_secret_use (self, attacker, attacker);
@@ -2034,7 +2040,7 @@
 /*QUAKED func_killbox (1 0 0) ?
 Kills everything inside when fired, irrespective of protection.
 */
-void use_killbox (edict_t *self, edict_t *other, edict_t *activator)
+void use_killbox (edict_t *self, edict_t */*other*/, edict_t */*activator*/)
 {
 	KillBox (self);
 }
--- a/game/g_items.c
+++ b/game/g_items.c
@@ -17,6 +17,12 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
+#define	GAME_INCLUDE
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 
 
@@ -84,7 +90,7 @@
 	{
 		if (!it->classname)
 			continue;
-		if (!Q_stricmp(it->classname, classname))
+		if (!Q_strcasecmp(it->classname, classname))
 			return it;
 	}
 
@@ -107,7 +113,7 @@
 	{
 		if (!it->pickup_name)
 			continue;
-		if (!Q_stricmp(it->pickup_name, pickup_name))
+		if (!Q_strcasecmp(it->pickup_name, pickup_name))
 			return it;
 	}
 
@@ -702,7 +708,7 @@
 	return POWER_ARMOR_NONE;
 }
 
-void Use_PowerArmor (edict_t *ent, gitem_t *item)
+void Use_PowerArmor (edict_t *ent, gitem_t */*item*/)
 {
 	int		index;
 
@@ -758,7 +764,7 @@
 Touch_Item
 ===============
 */
-void Touch_Item (edict_t *ent, edict_t *other, cplane_t *plane, csurface_t *surf)
+void Touch_Item (edict_t *ent, edict_t *other, cplane_t */*plane*/, csurface_t */*surf*/)
 {
 	qboolean	taken;
 
@@ -889,7 +895,7 @@
 	return dropped;
 }
 
-void Use_Item (edict_t *ent, edict_t *other, edict_t *activator)
+void Use_Item (edict_t *ent, edict_t */*other*/, edict_t */*activator*/)
 {
 	ent->svflags &= ~SVF_NOCLIENT;
 	ent->use = NULL;
--- a/game/g_local.h
+++ b/game/g_local.h
@@ -19,13 +19,9 @@
 */
 // g_local.h -- local definitions for game module
 
-#include "../q_shared.h"
-
 // define GAME_INCLUDE so that game.h does not define the
 // short, server-visible gclient_t and edict_t structures,
 // because we define the full size ones in this file
-#define	GAME_INCLUDE
-#include "game.h"
 
 // the "gameversion" client command will print this plus compile date
 #define	GAMEVERSION	"baseq2"
@@ -234,10 +230,10 @@
 typedef struct gitem_s
 {
 	char		*classname;	// spawning name
-	qboolean	(*pickup)(struct edict_s *ent, struct edict_s *other);
-	void		(*use)(struct edict_s *ent, struct gitem_s *item);
-	void		(*drop)(struct edict_s *ent, struct gitem_s *item);
-	void		(*weaponthink)(struct edict_s *ent);
+	qboolean	(*pickup)(edict_t *ent, edict_t *other);
+	void		(*use)(edict_t *ent, struct gitem_s *item);
+	void		(*drop)(edict_t *ent, struct gitem_s *item);
+	void		(*weaponthink)(edict_t *ent);
 	char		*pickup_sound;
 	char		*world_model;
 	int			world_model_flags;
@@ -501,13 +497,13 @@
 
 extern	edict_t			*g_edicts;
 
-#define	FOFS(x) (int)&(((edict_t *)0)->x)
-#define	STOFS(x) (int)&(((spawn_temp_t *)0)->x)
-#define	LLOFS(x) (int)&(((level_locals_t *)0)->x)
-#define	CLOFS(x) (int)&(((gclient_t *)0)->x)
+#define	FOFS(x) (uintptr)&(((edict_t *)0)->x)
+#define	STOFS(x) (uintptr)&(((spawn_temp_t *)0)->x)
+#define	LLOFS(x) (uintptr)&(((level_locals_t *)0)->x)
+#define	CLOFS(x) (uintptr)&(((gclient_t *)0)->x)
 
-#define random()	((rand () & 0x7fff) / ((float)0x7fff))
-#define crandom()	(2.0 * (random() - 0.5))
+#define qrandom()	((rand () & 0x7fff) / ((float)0x7fff))	/* >_< arrrrggghh */
+#define crandom()	(2.0 * (qrandom() - 0.5))
 
 extern	cvar_t	*maxentities;
 extern	cvar_t	*deathmatch;
@@ -873,13 +869,20 @@
 
 // this structure is cleared on each PutClientInServer(),
 // except for 'client->pers'
-struct gclient_s
+struct gclient_t
 {
 	// known to server
 	player_state_t	ps;				// communicated by server to clients
 	int				ping;
 
-	// private to game
+// the server expects the first part
+// of gclient_s to be a player_state_t
+// but the rest of it is opaque
+
+	// DO NOT MODIFY ANYTHING ABOVE THIS, THE SERVER
+	// EXPECTS THE FIELDS IN THAT ORDER!
+	//================================
+
 	client_persistant_t	pers;
 	client_respawn_t	resp;
 	pmove_state_t		old_pmove;	// for detecting out-of-pmove changes
@@ -958,13 +961,10 @@
 };
 
 
-struct edict_s
+struct edict_t
 {
 	entity_state_t	s;
-	struct gclient_s	*client;	// NULL if not a player
-									// the server expects the first part
-									// of gclient_s to be a player_state_t
-									// but the rest of it is opaque
+	gclient_t	*client;	// NULL if not a player
 
 	qboolean	inuse;
 	int			linkcount;
@@ -979,7 +979,7 @@
 
 	//================================
 
-	int			svflags;
+	int			svflags;	// SCF_NOCLIENT, SVF_DEADMONSTER, SVF_MONSTER, etc.
 	vec3_t		mins, maxs;
 	vec3_t		absmin, absmax, size;
 	solid_t		solid;
@@ -986,11 +986,10 @@
 	int			clipmask;
 	edict_t		*owner;
 
-
 	// DO NOT MODIFY ANYTHING ABOVE THIS, THE SERVER
 	// EXPECTS THE FIELDS IN THAT ORDER!
-
 	//================================
+
 	int			movetype;
 	int			flags;
 
@@ -1106,4 +1105,3 @@
 	moveinfo_t		moveinfo;
 	monsterinfo_t	monsterinfo;
 };
-
--- a/game/g_main.c
+++ b/game/g_main.c
@@ -17,7 +17,12 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-
+#define	GAME_INCLUDE
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 
 game_locals_t	game;
@@ -137,34 +142,7 @@
 	return &globals;
 }
 
-#ifndef GAME_HARD_LINKED
-// this is only here so the functions in q_shared.c and q_shwin.c can link
-void Sys_Error (char *error, ...)
-{
-	va_list		argptr;
-	char		text[1024];
 
-	va_start (argptr, error);
-	vsprintf (text, error, argptr);
-	va_end (argptr);
-
-	gi.error (ERR_FATAL, "%s", text);
-}
-
-void Com_Printf (char *msg, ...)
-{
-	va_list		argptr;
-	char		text[1024];
-
-	va_start (argptr, msg);
-	vsprintf (text, msg, argptr);
-	va_end (argptr);
-
-	gi.dprintf ("%s", text);
-}
-
-#endif
-
 //======================================================================
 
 
@@ -234,7 +212,7 @@
 		f = NULL;
 		t = strtok(s, seps);
 		while (t != NULL) {
-			if (Q_stricmp(t, level.mapname) == 0) {
+			if (Q_strcasecmp(t, level.mapname) == 0) {
 				// it's in the list, go to the next one
 				t = strtok(NULL, seps);
 				if (t == NULL) { // end of list, go to first one
--- a/game/g_misc.c
+++ b/game/g_misc.c
@@ -17,8 +17,12 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-// g_misc.c
-
+#define	GAME_INCLUDE
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 
 
@@ -28,7 +32,7 @@
 
 //=====================================================
 
-void Use_Areaportal (edict_t *ent, edict_t *other, edict_t *activator)
+void Use_Areaportal (edict_t *ent, edict_t */*other*/, edict_t */*activator*/)
 {
 	ent->count ^= 1;		// toggle state
 //	gi.dprintf ("portalstate: %i = %i\n", ent->style, ent->count);
@@ -59,7 +63,7 @@
 {
 	v[0] = 100.0 * crandom();
 	v[1] = 100.0 * crandom();
-	v[2] = 200.0 + 100.0 * random();
+	v[2] = 200.0 + 100.0 * qrandom();
 
 	if (damage < 50)
 		VectorScale (v, 0.7, v);
@@ -97,11 +101,11 @@
 	if (self->s.frame == 10)
 	{
 		self->think = G_FreeEdict;
-		self->nextthink = level.time + 8 + random()*10;
+		self->nextthink = level.time + 8 + qrandom()*10;
 	}
 }
 
-void gib_touch (edict_t *self, edict_t *other, cplane_t *plane, csurface_t *surf)
+void gib_touch (edict_t *self, edict_t */*other*/, cplane_t *plane, csurface_t */*surf*/)
 {
 	vec3_t	normal_angles, right;
 
@@ -127,7 +131,7 @@
 	}
 }
 
-void gib_die (edict_t *self, edict_t *inflictor, edict_t *attacker, int damage, vec3_t point)
+void gib_die (edict_t *self, edict_t */*inflictor*/, edict_t */*attacker*/, int /*damage*/, vec3_t /*point*/)
 {
 	G_FreeEdict (self);
 }
@@ -170,12 +174,12 @@
 	VelocityForDamage (damage, vd);
 	VectorMA (self->velocity, vscale, vd, gib->velocity);
 	ClipGibVelocity (gib);
-	gib->avelocity[0] = random()*600;
-	gib->avelocity[1] = random()*600;
-	gib->avelocity[2] = random()*600;
+	gib->avelocity[0] = qrandom()*600;
+	gib->avelocity[1] = qrandom()*600;
+	gib->avelocity[2] = qrandom()*600;
 
 	gib->think = G_FreeEdict;
-	gib->nextthink = level.time + 10 + random()*10;
+	gib->nextthink = level.time + 10 + qrandom()*10;
 
 	gi.linkentity (gib);
 }
@@ -220,7 +224,7 @@
 	self->avelocity[YAW] = crandom()*600;
 
 	self->think = G_FreeEdict;
-	self->nextthink = level.time + 10 + random()*10;
+	self->nextthink = level.time + 10 + qrandom()*10;
 
 	gi.linkentity (self);
 }
@@ -278,7 +282,7 @@
 debris
 =================
 */
-void debris_die (edict_t *self, edict_t *inflictor, edict_t *attacker, int damage, vec3_t point)
+void debris_die (edict_t *self, edict_t */*inflictor*/, edict_t */*attacker*/, int /*damage*/, vec3_t /*point*/)
 {
 	G_FreeEdict (self);
 }
@@ -297,11 +301,11 @@
 	VectorMA (self->velocity, speed, v, chunk->velocity);
 	chunk->movetype = MOVETYPE_BOUNCE;
 	chunk->solid = SOLID_NOT;
-	chunk->avelocity[0] = random()*600;
-	chunk->avelocity[1] = random()*600;
-	chunk->avelocity[2] = random()*600;
+	chunk->avelocity[0] = qrandom()*600;
+	chunk->avelocity[1] = qrandom()*600;
+	chunk->avelocity[2] = qrandom()*600;
 	chunk->think = G_FreeEdict;
-	chunk->nextthink = level.time + 5 + random()*5;
+	chunk->nextthink = level.time + 5 + qrandom()*5;
 	chunk->s.frame = 0;
 	chunk->flags = 0;
 	chunk->classname = "debris";
@@ -339,7 +343,7 @@
 	this path_corner targeted touches it
 */
 
-void path_corner_touch (edict_t *self, edict_t *other, cplane_t *plane, csurface_t *surf)
+void path_corner_touch (edict_t *self, edict_t *other, cplane_t */*plane*/, csurface_t */*surf*/)
 {
 	vec3_t		v;
 	edict_t		*next;
@@ -419,7 +423,7 @@
 when first activated before going after the activator.  If
 hold is selected, it will stay here.
 */
-void point_combat_touch (edict_t *self, edict_t *other, cplane_t *plane, csurface_t *surf)
+void point_combat_touch (edict_t *self, edict_t *other, cplane_t */*plane*/, csurface_t */*surf*/)
 {
 	edict_t	*activator;
 
@@ -542,7 +546,7 @@
 
 #define START_OFF	1
 
-static void light_use (edict_t *self, edict_t *other, edict_t *activator)
+static void light_use (edict_t *self, edict_t */*other*/, edict_t */*activator*/)
 {
 	if (self->spawnflags & START_OFF)
 	{
@@ -590,7 +594,7 @@
 				the wall will initially be present
 */
 
-void func_wall_use (edict_t *self, edict_t *other, edict_t *activator)
+void func_wall_use (edict_t *self, edict_t */*other*/, edict_t */*activator*/)
 {
 	if (self->solid == SOLID_NOT)
 	{
@@ -662,7 +666,7 @@
 This is solid bmodel that will fall if it's support it removed.
 */
 
-void func_object_touch (edict_t *self, edict_t *other, cplane_t *plane, csurface_t *surf)
+void func_object_touch (edict_t *self, edict_t *other, cplane_t *plane, csurface_t */*surf*/)
 {
 	// only squash thing we fall on top of
 	if (!plane)
@@ -680,7 +684,7 @@
 	self->touch = func_object_touch;
 }
 
-void func_object_use (edict_t *self, edict_t *other, edict_t *activator)
+void func_object_use (edict_t *self, edict_t */*other*/, edict_t */*activator*/)
 {
 	self->solid = SOLID_BSP;
 	self->svflags &= ~SVF_NOCLIENT;
@@ -742,7 +746,7 @@
 it explodes.  You get one large chunk per 100 of mass (up to 8) and
 one small chunk per 25 of mass (up to 16).  So 800 gives the most.
 */
-void func_explosive_explode (edict_t *self, edict_t *inflictor, edict_t *attacker, int damage, vec3_t point)
+void func_explosive_explode (edict_t *self, edict_t *inflictor, edict_t *attacker, int /*damage*/, vec3_t /*point*/)
 {
 	vec3_t	origin;
 	vec3_t	chunkorigin;
@@ -806,12 +810,12 @@
 		G_FreeEdict (self);
 }
 
-void func_explosive_use(edict_t *self, edict_t *other, edict_t *activator)
+void func_explosive_use(edict_t *self, edict_t *other, edict_t */*activator*/)
 {
 	func_explosive_explode (self, self, other, self->health, vec3_origin);
 }
 
-void func_explosive_spawn (edict_t *self, edict_t *other, edict_t *activator)
+void func_explosive_spawn (edict_t *self, edict_t */*other*/, edict_t */*activator*/)
 {
 	self->solid = SOLID_BSP;
 	self->svflags &= ~SVF_NOCLIENT;
@@ -870,7 +874,7 @@
 health (80), and dmg (150).
 */
 
-void barrel_touch (edict_t *self, edict_t *other, cplane_t *plane, csurface_t *surf)
+void barrel_touch (edict_t *self, edict_t *other, cplane_t */*plane*/, csurface_t */*surf*/)
 
 {
 	float	ratio;
@@ -963,7 +967,7 @@
 		BecomeExplosion1 (self);
 }
 
-void barrel_delay (edict_t *self, edict_t *inflictor, edict_t *attacker, int damage, vec3_t point)
+void barrel_delay (edict_t *self, edict_t */*inflictor*/, edict_t *attacker, int /*damage*/, vec3_t /*point*/)
 {
 	self->takedamage = DAMAGE_NO;
 	self->nextthink = level.time + 2 * FRAMETIME;
@@ -1018,7 +1022,7 @@
 /*QUAKED misc_blackhole (1 .5 0) (-8 -8 -8) (8 8 8)
 */
 
-void misc_blackhole_use (edict_t *ent, edict_t *other, edict_t *activator)
+void misc_blackhole_use (edict_t *ent, edict_t */*other*/, edict_t */*activator*/)
 {
 	/*
 	gi.WriteByte (svc_temp_entity);
@@ -1154,7 +1158,7 @@
 		gi.sound (self, CHAN_BODY, gi.soundindex ("tank/thud.wav"), 1, ATTN_NORM, 0);
 }
 
-void commander_body_use (edict_t *self, edict_t *other, edict_t *activator)
+void commander_body_use (edict_t *self, edict_t */*other*/, edict_t */*activator*/)
 {
 	self->think = commander_body_think;
 	self->nextthink = level.time + FRAMETIME;
@@ -1214,7 +1218,7 @@
 /*QUAKED misc_deadsoldier (1 .5 0) (-16 -16 0) (16 16 16) ON_BACK ON_STOMACH BACK_DECAP FETAL_POS SIT_DECAP IMPALED
 This is the dead player model. Comes in 6 exciting different poses!
 */
-void misc_deadsoldier_die (edict_t *self, edict_t *inflictor, edict_t *attacker, int damage, vec3_t point)
+void misc_deadsoldier_die (edict_t *self, edict_t */*inflictor*/, edict_t */*attacker*/, int damage, vec3_t /*point*/)
 {
 	int		n;
 
@@ -1327,7 +1331,7 @@
 /*QUAKED misc_viper_bomb (1 0 0) (-8 -8 -8) (8 8 8)
 "dmg"	how much boom should the bomb make?
 */
-void misc_viper_bomb_touch (edict_t *self, edict_t *other, cplane_t *plane, csurface_t *surf)
+void misc_viper_bomb_touch (edict_t *self, edict_t */*other*/, cplane_t */*plane*/, csurface_t */*surf*/)
 {
 	G_UseTargets (self, self->activator);
 
@@ -1355,7 +1359,7 @@
 	self->s.angles[2] = diff + 10;
 }
 
-void misc_viper_bomb_use (edict_t *self, edict_t *other, edict_t *activator)
+void misc_viper_bomb_use (edict_t *self, edict_t */*other*/, edict_t *activator)
 {
 	edict_t	*viper;
 
@@ -1449,7 +1453,7 @@
 		self->nextthink = level.time + FRAMETIME;
 }
 
-void misc_satellite_dish_use (edict_t *self, edict_t *other, edict_t *activator)
+void misc_satellite_dish_use (edict_t *self, edict_t */*other*/, edict_t */*activator*/)
 {
 	self->s.frame = 0;
 	self->think = misc_satellite_dish_think;
@@ -1503,9 +1507,9 @@
 	ent->movetype = MOVETYPE_TOSS;
 	ent->svflags |= SVF_MONSTER;
 	ent->deadflag = DEAD_DEAD;
-	ent->avelocity[0] = random()*200;
-	ent->avelocity[1] = random()*200;
-	ent->avelocity[2] = random()*200;
+	ent->avelocity[0] = qrandom()*200;
+	ent->avelocity[1] = qrandom()*200;
+	ent->avelocity[2] = qrandom()*200;
 	ent->think = G_FreeEdict;
 	ent->nextthink = level.time + 30;
 	gi.linkentity (ent);
@@ -1524,9 +1528,9 @@
 	ent->movetype = MOVETYPE_TOSS;
 	ent->svflags |= SVF_MONSTER;
 	ent->deadflag = DEAD_DEAD;
-	ent->avelocity[0] = random()*200;
-	ent->avelocity[1] = random()*200;
-	ent->avelocity[2] = random()*200;
+	ent->avelocity[0] = qrandom()*200;
+	ent->avelocity[1] = qrandom()*200;
+	ent->avelocity[2] = qrandom()*200;
 	ent->think = G_FreeEdict;
 	ent->nextthink = level.time + 30;
 	gi.linkentity (ent);
@@ -1545,9 +1549,9 @@
 	ent->movetype = MOVETYPE_TOSS;
 	ent->svflags |= SVF_MONSTER;
 	ent->deadflag = DEAD_DEAD;
-	ent->avelocity[0] = random()*200;
-	ent->avelocity[1] = random()*200;
-	ent->avelocity[2] = random()*200;
+	ent->avelocity[0] = qrandom()*200;
+	ent->avelocity[1] = qrandom()*200;
+	ent->avelocity[2] = qrandom()*200;
 	ent->think = G_FreeEdict;
 	ent->nextthink = level.time + 30;
 	gi.linkentity (ent);
@@ -1574,7 +1578,7 @@
 /*QUAKED target_string (0 0 1) (-8 -8 -8) (8 8 8)
 */
 
-void target_string_use (edict_t *self, edict_t *other, edict_t *activator)
+void target_string_use (edict_t *self, edict_t */*other*/, edict_t */*activator*/)
 {
 	edict_t *e;
 	int		n, l;
@@ -1674,6 +1678,8 @@
 
 void func_clock_think (edict_t *self)
 {
+	Tm *t;
+
 	if (!self->enemy)
 	{
 		self->enemy = G_Find (NULL, FOFS(targetname), self->target);
@@ -1693,12 +1699,8 @@
 	}
 	else
 	{
-		struct tm	*ltime;
-		time_t		gmtime;
-
-		time(&gmtime);
-		ltime = localtime(&gmtime);
-		Com_sprintf (self->message, CLOCK_MESSAGE_SIZE, "%2i:%2i:%2i", ltime->tm_hour, ltime->tm_min, ltime->tm_sec);
+		t = localtime(time(nil));
+		Com_sprintf (self->message, CLOCK_MESSAGE_SIZE, "%2i:%2i:%2i", t->hour, t->min, t->sec);
 		if (self->message[3] == ' ')
 			self->message[3] = '0';
 		if (self->message[6] == ' ')
@@ -1737,7 +1739,7 @@
 	self->nextthink = level.time + 1;
 }
 
-void func_clock_use (edict_t *self, edict_t *other, edict_t *activator)
+void func_clock_use (edict_t *self, edict_t */*other*/, edict_t *activator)
 {
 	if (!(self->spawnflags & 8))
 		self->use = NULL;
@@ -1780,7 +1782,7 @@
 
 //=================================================================================
 
-void teleporter_touch (edict_t *self, edict_t *other, cplane_t *plane, csurface_t *surf)
+void teleporter_touch (edict_t *self, edict_t *other, cplane_t */*plane*/, csurface_t */*surf*/)
 {
 	edict_t		*dest;
 	int			i;
--- a/game/g_monster.c
+++ b/game/g_monster.c
@@ -17,6 +17,12 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
+#define	GAME_INCLUDE
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 
 
@@ -88,7 +94,7 @@
 	gi.multicast (start, MULTICAST_PVS);
 }
 
-void monster_fire_bfg (edict_t *self, vec3_t start, vec3_t aimdir, int damage, int speed, int kick, float damage_radius, int flashtype)
+void monster_fire_bfg (edict_t *self, vec3_t start, vec3_t aimdir, int damage, int speed, int /*kick*/, float damage_radius, int flashtype)
 {
 	fire_bfg (self, start, aimdir, damage, speed, damage_radius);
 
@@ -125,11 +131,11 @@
 	if (self->waterlevel)
 		return;
 
-	if (random() > 0.5)
+	if (qrandom() > 0.5)
 		return;
 
 	self->think = M_FliesOn;
-	self->nextthink = level.time + 5 + 10 * random();
+	self->nextthink = level.time + 5 + 10 * qrandom();
 }
 
 void AttackFinished (edict_t *self, float time)
@@ -291,7 +297,7 @@
 		if (!(ent->svflags & SVF_DEADMONSTER))
 		{
 			if (ent->watertype & CONTENTS_LAVA)
-				if (random() <= 0.5)
+				if (qrandom() <= 0.5)
 					gi.sound (ent, CHAN_BODY, gi.soundindex("player/lava1.wav"), 1, ATTN_NORM, 0);
 				else
 					gi.sound (ent, CHAN_BODY, gi.soundindex("player/lava2.wav"), 1, ATTN_NORM, 0);
@@ -437,7 +443,7 @@
 Using a monster makes it angry at the current activator
 ================
 */
-void monster_use (edict_t *self, edict_t *other, edict_t *activator)
+void monster_use (edict_t *self, edict_t */*other*/, edict_t *activator)
 {
 	if (self->enemy)
 		return;
@@ -480,7 +486,7 @@
 	}
 }
 
-void monster_triggered_spawn_use (edict_t *self, edict_t *other, edict_t *activator)
+void monster_triggered_spawn_use (edict_t *self, edict_t */*other*/, edict_t *activator)
 {
 	// we have a one frame delay here so we don't telefrag the guy who activated us
 	self->think = monster_triggered_spawn;
--- a/game/g_phys.c
+++ b/game/g_phys.c
@@ -17,8 +17,12 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-// g_phys.c
-
+#define	GAME_INCLUDE
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 
 /*
@@ -602,11 +606,11 @@
 		// otherwise, just stay in place until the obstacle is gone
 		if (part->blocked)
 			part->blocked (part, obstacle);
-#if 0
+/*
 		// if the pushed entity went away and the pusher is still there
 		if (!obstacle->inuse && part->inuse)
 			goto retry;
-#endif
+*/
 	}
 	else
 	{
--- a/game/g_save.c
+++ b/game/g_save.c
@@ -17,7 +17,12 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-
+#define	GAME_INCLUDE
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 
 #define Function(f) {#f, f}
@@ -169,7 +174,7 @@
 	// latched vars
 	sv_cheats = gi.cvar ("cheats", "0", CVAR_SERVERINFO|CVAR_LATCH);
 	gi.cvar ("gamename", GAMEVERSION , CVAR_SERVERINFO | CVAR_LATCH);
-	gi.cvar ("gamedate", __DATE__ , CVAR_SERVERINFO | CVAR_LATCH);
+	gi.cvar ("gamedate", "Nov 30 1997" , CVAR_SERVERINFO | CVAR_LATCH);
 
 	maxclients = gi.cvar ("maxclients", "4", CVAR_SERVERINFO | CVAR_LATCH);
 	maxspectators = gi.cvar ("maxspectators", "4", CVAR_SERVERINFO);
@@ -223,7 +228,7 @@
 
 //=========================================================
 
-void WriteField1 (FILE *f, field_t *field, byte *base)
+void WriteField1 (FILE *, field_t *field, byte *base)
 {
 	void		*p;
 	int			len;
@@ -471,7 +476,7 @@
 		gi.error ("Couldn't open %s", filename);
 
 	memset (str, 0, sizeof(str));
-	strcpy (str, __DATE__);
+	strcpy (str, "Nov 30 1997");
 	fwrite (str, sizeof(str), 1, f);
 
 	game.autosaved = autosave;
@@ -497,7 +502,7 @@
 		gi.error ("Couldn't open %s", filename);
 
 	fread (str, sizeof(str), 1, f);
-	if (strcmp (str, __DATE__))
+	if (strcmp (str, "Nov 30 1997"))
 	{
 		fclose (f);
 		gi.error ("Savegame from an older version.\n");
--- a/game/g_spawn.c
+++ b/game/g_spawn.c
@@ -17,7 +17,12 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-
+#define	GAME_INCLUDE
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 
 typedef struct
@@ -364,7 +369,7 @@
 
 	for (f=fields ; f->name ; f++)
 	{
-		if (!(f->flags & FFL_NOSPAWN) && !Q_stricmp(f->name, key))
+		if (!(f->flags & FFL_NOSPAWN) && !Q_strcasecmp(f->name, key))
 		{	// found it
 			if (f->flags & FFL_SPAWNTEMP)
 				b = (byte *)&st;
@@ -567,7 +572,7 @@
 		entities = ED_ParseEdict (entities, ent);
 
 		// yet another map hack
-		if (!Q_stricmp(level.mapname, "command") && !Q_stricmp(ent->classname, "trigger_once") && !Q_stricmp(ent->model, "*27"))
+		if (!Q_strcasecmp(level.mapname, "command") && !Q_strcasecmp(ent->classname, "trigger_once") && !Q_strcasecmp(ent->model, "*27"))
 			ent->spawnflags &= ~SPAWNFLAG_NOT_HARD;
 
 		// remove things (except the world) from different skill levels or deathmatch
@@ -622,7 +627,7 @@
 
 //===================================================================
 
-#if 0
+/*
 	// cursor positioning
 	xl <value>
 	xr <value>
@@ -643,7 +648,7 @@
 	ifbit <stat> <value>
 	endif
 
-#endif
+*/
 
 char *single_statusbar = 
 "yb	-24 "
--- a/game/g_svcmds.c
+++ b/game/g_svcmds.c
@@ -17,7 +17,12 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-
+#define	GAME_INCLUDE
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 
 
@@ -284,15 +289,15 @@
 	char	*cmd;
 
 	cmd = gi.argv(1);
-	if (Q_stricmp (cmd, "test") == 0)
+	if (Q_strcasecmp (cmd, "test") == 0)
 		Svcmd_Test_f ();
-	else if (Q_stricmp (cmd, "addip") == 0)
+	else if (Q_strcasecmp (cmd, "addip") == 0)
 		SVCmd_AddIP_f ();
-	else if (Q_stricmp (cmd, "removeip") == 0)
+	else if (Q_strcasecmp (cmd, "removeip") == 0)
 		SVCmd_RemoveIP_f ();
-	else if (Q_stricmp (cmd, "listip") == 0)
+	else if (Q_strcasecmp (cmd, "listip") == 0)
 		SVCmd_ListIP_f ();
-	else if (Q_stricmp (cmd, "writeip") == 0)
+	else if (Q_strcasecmp (cmd, "writeip") == 0)
 		SVCmd_WriteIP_f ();
 	else
 		gi.cprintf (NULL, PRINT_HIGH, "Unknown server command \"%s\"\n", cmd);
--- a/game/g_target.c
+++ b/game/g_target.c
@@ -17,6 +17,12 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
+#define	GAME_INCLUDE
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 
 /*QUAKED target_temp_entity (1 0 0) (-8 -8 -8) (8 8 8)
@@ -23,7 +29,7 @@
 Fire an origin based temp entity event to the clients.
 "style"		type byte
 */
-void Use_Target_Tent (edict_t *ent, edict_t *other, edict_t *activator)
+void Use_Target_Tent (edict_t *ent, edict_t */*other*/, edict_t */*activator*/)
 {
 	gi.WriteByte (svc_temp_entity);
 	gi.WriteByte (ent->style);
@@ -55,7 +61,7 @@
 Looped sounds are always atten 3 / vol 1, and the use function toggles it on/off.
 Multiple identical looping sounds will just increase volume without any speed cost.
 */
-void Use_Target_Speaker (edict_t *ent, edict_t *other, edict_t *activator)
+void Use_Target_Speaker (edict_t *ent, edict_t */*other*/, edict_t */*activator*/)
 {
 	int		chan;
 
@@ -115,7 +121,7 @@
 
 //==========================================================
 
-void Use_Target_Help (edict_t *ent, edict_t *other, edict_t *activator)
+void Use_Target_Help (edict_t *ent, edict_t */*other*/, edict_t */*activator*/)
 {
 	if (ent->spawnflags & 1)
 		strncpy (game.helpmessage1, ent->message, sizeof(game.helpmessage2)-1);
@@ -151,7 +157,7 @@
 Counts a secret found.
 These are single use targets.
 */
-void use_target_secret (edict_t *ent, edict_t *other, edict_t *activator)
+void use_target_secret (edict_t *ent, edict_t */*other*/, edict_t *activator)
 {
 	gi.sound (ent, CHAN_VOICE, ent->noise_index, 1, ATTN_NORM, 0);
 
@@ -176,7 +182,7 @@
 	ent->svflags = SVF_NOCLIENT;
 	level.total_secrets++;
 	// map bug hack
-	if (!Q_stricmp(level.mapname, "mine3") && ent->s.origin[0] == 280 && ent->s.origin[1] == -2048 && ent->s.origin[2] == -624)
+	if (!Q_strcasecmp(level.mapname, "mine3") && ent->s.origin[0] == 280 && ent->s.origin[1] == -2048 && ent->s.origin[2] == -624)
 		ent->message = "You have found a secret area.";
 }
 
@@ -186,7 +192,7 @@
 Counts a goal completed.
 These are single use targets.
 */
-void use_target_goal (edict_t *ent, edict_t *other, edict_t *activator)
+void use_target_goal (edict_t *ent, edict_t */*other*/, edict_t *activator)
 {
 	gi.sound (ent, CHAN_VOICE, ent->noise_index, 1, ATTN_NORM, 0);
 
@@ -241,7 +247,7 @@
 	self->delay = save;
 }
 
-void use_target_explosion (edict_t *self, edict_t *other, edict_t *activator)
+void use_target_explosion (edict_t *self, edict_t */*other*/, edict_t *activator)
 {
 	self->activator = activator;
 
@@ -309,7 +315,7 @@
 	}
 
 	// ugly hack because *SOMEBODY* screwed up their map
-   if((Q_stricmp(level.mapname, "fact1") == 0) && (Q_stricmp(ent->map, "fact3") == 0))
+   if((Q_strcasecmp(level.mapname, "fact1") == 0) && (Q_strcasecmp(ent->map, "fact3") == 0))
 	   ent->map = "fact3$secret1";
 
 	ent->use = use_target_changelevel;
@@ -335,7 +341,7 @@
 		useful for lava/sparks
 */
 
-void use_target_splash (edict_t *self, edict_t *other, edict_t *activator)
+void use_target_splash (edict_t *self, edict_t */*other*/, edict_t *activator)
 {
 	gi.WriteByte (svc_temp_entity);
 	gi.WriteByte (TE_SPLASH);
@@ -377,7 +383,7 @@
 */
 void ED_CallSpawn (edict_t *ent);
 
-void use_target_spawner (edict_t *self, edict_t *other, edict_t *activator)
+void use_target_spawner (edict_t *self, edict_t */*other*/, edict_t */*activator*/)
 {
 	edict_t	*ent;
 
@@ -413,8 +419,9 @@
 speed	default is 1000
 */
 
-void use_target_blaster (edict_t *self, edict_t *other, edict_t *activator)
+void use_target_blaster (edict_t *self, edict_t */*other*/, edict_t */*activator*/)
 {
+	/*
 	int effect;
 
 	if (self->spawnflags & 2)
@@ -423,6 +430,7 @@
 		effect = EF_HYPERBLASTER;
 	else
 		effect = EF_BLASTER;
+	*/
 
 	fire_blaster (self, self->s.origin, self->movedir, self->dmg, self->speed, EF_BLASTER, MOD_TARGET_BLASTER);
 	gi.sound (self, CHAN_VOICE, self->noise_index, 1, ATTN_NORM, 0);
@@ -448,7 +456,7 @@
 /*QUAKED target_crosslevel_trigger (.5 .5 .5) (-8 -8 -8) (8 8 8) trigger1 trigger2 trigger3 trigger4 trigger5 trigger6 trigger7 trigger8
 Once this trigger is touched/used, any trigger_crosslevel_target with the same trigger number is automatically used when a level is started within the same unit.  It is OK to check multiple triggers.  Message, delay, target, and killtarget also work.
 */
-void trigger_crosslevel_trigger_use (edict_t *self, edict_t *other, edict_t *activator)
+void trigger_crosslevel_trigger_use (edict_t *self, edict_t */*other*/, edict_t */*activator*/)
 {
 	game.serverflags |= self->spawnflags;
 	G_FreeEdict (self);
@@ -573,7 +581,7 @@
 	self->nextthink = 0;
 }
 
-void target_laser_use (edict_t *self, edict_t *other, edict_t *activator)
+void target_laser_use (edict_t *self, edict_t */*other*/, edict_t *activator)
 {
 	self->activator = activator;
 	if (self->spawnflags & 1)
@@ -676,7 +684,7 @@
 	}
 }
 
-void target_lightramp_use (edict_t *self, edict_t *other, edict_t *activator)
+void target_lightramp_use (edict_t *self, edict_t */*other*/, edict_t */*activator*/)
 {
 	if (!self->enemy)
 	{
@@ -782,7 +790,7 @@
 		self->nextthink = level.time + FRAMETIME;
 }
 
-void target_earthquake_use (edict_t *self, edict_t *other, edict_t *activator)
+void target_earthquake_use (edict_t *self, edict_t */*other*/, edict_t *activator)
 {
 	self->timestamp = level.time + self->count;
 	self->nextthink = level.time + FRAMETIME;
--- a/game/g_trigger.c
+++ b/game/g_trigger.c
@@ -17,6 +17,12 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
+#define	GAME_INCLUDE
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 
 
@@ -63,13 +69,13 @@
 	}
 }
 
-void Use_Multi (edict_t *ent, edict_t *other, edict_t *activator)
+void Use_Multi (edict_t *ent, edict_t */*other*/, edict_t *activator)
 {
 	ent->activator = activator;
 	multi_trigger (ent);
 }
 
-void Touch_Multi (edict_t *self, edict_t *other, cplane_t *plane, csurface_t *surf)
+void Touch_Multi (edict_t *self, edict_t *other, cplane_t */*plane*/, csurface_t */*surf*/)
 {
 	if(other->client)
 	{
@@ -108,7 +114,7 @@
 4)
 set "message" to text string
 */
-void trigger_enable (edict_t *self, edict_t *other, edict_t *activator)
+void trigger_enable (edict_t *self, edict_t */*other*/, edict_t */*activator*/)
 {
 	self->solid = SOLID_TRIGGER;
 	self->use = Use_Multi;
@@ -186,7 +192,7 @@
 /*QUAKED trigger_relay (.5 .5 .5) (-8 -8 -8) (8 8 8)
 This fixed size trigger cannot be touched, it can only be fired by other events.
 */
-void trigger_relay_use (edict_t *self, edict_t *other, edict_t *activator)
+void trigger_relay_use (edict_t *self, edict_t */*other*/, edict_t *activator)
 {
 	G_UseTargets (self, activator);
 }
@@ -209,7 +215,7 @@
 A relay trigger that only fires it's targets if player has the proper key.
 Use "item" to specify the required key, for example "key_data_cd"
 */
-void trigger_key_use (edict_t *self, edict_t *other, edict_t *activator)
+void trigger_key_use (edict_t *self, edict_t */*other*/, edict_t *activator)
 {
 	int			index;
 
@@ -323,7 +329,7 @@
 After the counter has been triggered "count" times (default 2), it will fire all of it's targets and remove itself.
 */
 
-void trigger_counter_use(edict_t *self, edict_t *other, edict_t *activator)
+void trigger_counter_use(edict_t *self, edict_t */*other*/, edict_t *activator)
 {
 	if (self->count == 0)
 		return;
@@ -391,7 +397,7 @@
 
 static int windsound;
 
-void trigger_push_touch (edict_t *self, edict_t *other, cplane_t *plane, csurface_t *surf)
+void trigger_push_touch (edict_t *self, edict_t *other, cplane_t */*plane*/, csurface_t */*surf*/)
 {
 	if (strcmp(other->classname, "grenade") == 0)
 	{
@@ -452,7 +458,7 @@
 "dmg"			default 5 (whole numbers only)
 
 */
-void hurt_use (edict_t *self, edict_t *other, edict_t *activator)
+void hurt_use (edict_t *self, edict_t */*other*/, edict_t */*activator*/)
 {
 	if (self->solid == SOLID_NOT)
 		self->solid = SOLID_TRIGGER;
@@ -465,7 +471,7 @@
 }
 
 
-void hurt_touch (edict_t *self, edict_t *other, cplane_t *plane, csurface_t *surf)
+void hurt_touch (edict_t *self, edict_t *other, cplane_t */*plane*/, csurface_t */*surf*/)
 {
 	int		dflags;
 
@@ -529,7 +535,7 @@
 gravity for the level.
 */
 
-void trigger_gravity_touch (edict_t *self, edict_t *other, cplane_t *plane, csurface_t *surf)
+void trigger_gravity_touch (edict_t *self, edict_t *other, cplane_t */*plane*/, csurface_t */*surf*/)
 {
 	other->gravity = self->gravity;
 }
@@ -563,7 +569,7 @@
 "height" default to 200, the speed thrown upwards
 */
 
-void trigger_monsterjump_touch (edict_t *self, edict_t *other, cplane_t *plane, csurface_t *surf)
+void trigger_monsterjump_touch (edict_t *self, edict_t *other, cplane_t */*plane*/, csurface_t */*surf*/)
 {
 	if (other->flags & (FL_FLY | FL_SWIM) )
 		return;
--- a/game/g_turret.c
+++ b/game/g_turret.c
@@ -17,8 +17,12 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-// g_turret.c
-
+#define	GAME_INCLUDE
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 
 
@@ -87,7 +91,7 @@
 	VectorMA (start, self->move_origin[1], r, start);
 	VectorMA (start, self->move_origin[2], u, start);
 
-	damage = 100 + random() * 50;
+	damage = 100 + qrandom() * 50;
 	speed = 550 + 50 * skill->value;
 	fire_rocket (self->teammaster->owner, start, f, damage, speed, 150, damage);
 	gi.positioned_sound (start, self, CHAN_WEAPON, gi.soundindex("weapons/rocklf1a.wav"), 1, ATTN_NORM, 0);
@@ -271,7 +275,7 @@
 Instead it must target the turret_breach.
 */
 
-void infantry_die (edict_t *self, edict_t *inflictor, edict_t *attacker, int damage);
+void infantry_die (edict_t *self, edict_t *inflictor, edict_t *attacker, int damage, vec3_t point);
 void infantry_stand (edict_t *self);
 void monster_use (edict_t *self, edict_t *other, edict_t *activator);
 
@@ -292,7 +296,7 @@
 	self->target_ent->owner = NULL;
 	self->target_ent->teammaster->owner = NULL;
 
-	infantry_die (self, inflictor, attacker, damage);
+	infantry_die (self, inflictor, attacker, damage, point);
 }
 
 qboolean FindTarget (edict_t *self);
--- a/game/g_utils.c
+++ b/game/g_utils.c
@@ -18,7 +18,12 @@
 
 */
 // g_utils.c -- misc utility functions for game module
-
+#define	GAME_INCLUDE
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 
 
@@ -58,7 +63,7 @@
 		s = *(char **) ((byte *)from + fieldofs);
 		if (!s)
 			continue;
-		if (!Q_stricmp (s, match))
+		if (!Q_strcasecmp (s, match))
 			return from;
 	}
 
@@ -232,8 +237,8 @@
 		while ((t = G_Find (t, FOFS(targetname), ent->target)))
 		{
 			// doors fire area portals in a specific way
-			if (!Q_stricmp(t->classname, "func_areaportal") &&
-				(!Q_stricmp(ent->classname, "func_door") || !Q_stricmp(ent->classname, "func_door_rotating")))
+			if (!Q_strcasecmp(t->classname, "func_areaportal") &&
+				(!Q_strcasecmp(ent->classname, "func_door") || !Q_strcasecmp(ent->classname, "func_door_rotating")))
 				continue;
 
 			if (t == ent)
--- a/game/g_weapon.c
+++ b/game/g_weapon.c
@@ -17,6 +17,12 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
+#define	GAME_INCLUDE
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 
 
@@ -39,7 +45,7 @@
 	// easy mode only ducks one quarter the time
 	if (skill->value == 0)
 	{
-		if (random() > 0.25)
+		if (qrandom() > 0.25)
 			return;
 	}
 	VectorMA (start, 8192, dir, end);
@@ -452,7 +458,7 @@
 	G_FreeEdict (ent);
 }
 
-static void Grenade_Touch (edict_t *ent, edict_t *other, cplane_t *plane, csurface_t *surf)
+static void Grenade_Touch (edict_t *ent, edict_t *other, cplane_t */*plane*/, csurface_t *surf)
 {
 	if (other == ent->owner)
 		return;
@@ -467,7 +473,7 @@
 	{
 		if (ent->spawnflags & 1)
 		{
-			if (random() > 0.5)
+			if (qrandom() > 0.5)
 				gi.sound (ent, CHAN_VOICE, gi.soundindex ("weapons/hgrenb1a.wav"), 1, ATTN_NORM, 0);
 			else
 				gi.sound (ent, CHAN_VOICE, gi.soundindex ("weapons/hgrenb2a.wav"), 1, ATTN_NORM, 0);
--- a/game/game.h
+++ b/game/game.h
@@ -17,26 +17,7 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-/*
-Copyright (C) 1997-2001 Id Software, Inc.
 
-This program is free software; you can redistribute it and/or
-modify it under the terms of the GNU General Public License
-as published by the Free Software Foundation; either version 2
-of the License, or (at your option) any later version.
-
-This program is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
-
-See the GNU General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with this program; if not, write to the Free Software
-Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
-
-*/
-
 // game.h -- game dll information visible to server
 
 #define	GAME_API_VERSION	3
@@ -67,14 +48,13 @@
 
 #define	MAX_ENT_CLUSTERS	16
 
+typedef struct edict_t edict_t;
+typedef struct gclient_t gclient_t;
 
-typedef struct edict_s edict_t;
-typedef struct gclient_s gclient_t;
 
-
 #ifndef GAME_INCLUDE
 
-struct gclient_s
+struct gclient_t
 {
 	player_state_t	ps;		// communicated by server to clients
 	int				ping;
@@ -83,10 +63,10 @@
 };
 
 
-struct edict_s
+struct edict_t
 {
 	entity_state_t	s;
-	struct gclient_s	*client;
+	gclient_t	*client;
 	qboolean	inuse;
 	int			linkcount;
 
@@ -245,10 +225,10 @@
 	// can vary in size from one game to another.
 	// 
 	// The size will be fixed when ge->Init() is called
-	struct edict_s	*edicts;
+	edict_t	*edicts;
 	int			edict_size;
 	int			num_edicts;		// current number, <= max_edicts
 	int			max_edicts;
 } game_export_t;
 
-game_export_t *GetGameApi (game_import_t *import);
+game_export_t *GetGameAPI (game_import_t *import);
--- a/game/m_actor.c
+++ b/game/m_actor.c
@@ -17,8 +17,12 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-// g_actor.c
-
+#define GAME_INCLUDE
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 #include "m_actor.h"
 
@@ -227,7 +231,7 @@
 	"Check your targets"
 };
 
-void actor_pain (edict_t *self, edict_t *other, float kick, int damage)
+void actor_pain (edict_t *self, edict_t *other, float /*kick*/, int /*damage*/)
 {
 	int		n;
 
@@ -240,7 +244,7 @@
 	self->pain_debounce_time = level.time + 3;
 //	gi.sound (self, CHAN_VOICE, actor.sound_pain, 1, ATTN_NORM, 0);
 
-	if ((other->client) && (random() < 0.4))
+	if ((other->client) && (qrandom() < 0.4))
 	{
 		vec3_t	v;
 		char	*name;
@@ -247,7 +251,7 @@
 
 		VectorSubtract (other->s.origin, self->s.origin, v);
 		self->ideal_yaw = vectoyaw (v);
-		if (random() < 0.5)
+		if (qrandom() < 0.5)
 			self->monsterinfo.currentmove = &actor_move_flipoff;
 		else
 			self->monsterinfo.currentmove = &actor_move_taunt;
@@ -336,7 +340,7 @@
 };
 mmove_t actor_move_death2 = {FRAME_death201, FRAME_death213, actor_frames_death2, actor_dead};
 
-void actor_die (edict_t *self, edict_t *inflictor, edict_t *attacker, int damage, vec3_t point)
+void actor_die (edict_t *self, edict_t */*inflictor*/, edict_t */*attacker*/, int damage, vec3_t /*point*/)
 {
 	int		n;
 
@@ -398,7 +402,7 @@
 }
 
 
-void actor_use (edict_t *self, edict_t *other, edict_t *activator)
+void actor_use (edict_t *self, edict_t */*other*/, edict_t */*activator*/)
 {
 	vec3_t		v;
 
@@ -493,7 +497,7 @@
 "height"		speed thrown upwards (default 200)
 */
 
-void target_actor_touch (edict_t *self, edict_t *other, cplane_t *plane, csurface_t *surf)
+void target_actor_touch (edict_t *self, edict_t *other, cplane_t */*plane*/, csurface_t */*surf*/)
 {
 	vec3_t	v;
 
--- a/game/m_actor.h
+++ b/game/m_actor.h
@@ -17,8 +17,6 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-// G:\quake2\baseq2\models/player_y
-
 // This file generated by ModelGen - Do NOT Modify
 
 #define FRAME_attak01         	0
--- a/game/m_berserk.c
+++ b/game/m_berserk.c
@@ -17,14 +17,12 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-/*
-==============================================================================
-
-BERSERK
-
-==============================================================================
-*/
-
+#define GAME_INCLUDE
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 #include "m_berserk.h"
 
@@ -36,7 +34,7 @@
 static int sound_sight;
 static int sound_search;
 
-void berserk_sight (edict_t *self, edict_t *other)
+void berserk_sight (edict_t *self, edict_t */*other*/)
 {
 	gi.sound (self, CHAN_VOICE, sound_sight, 1, ATTN_NORM, 0);
 }
@@ -92,7 +90,7 @@
 {
 	if (self->monsterinfo.aiflags & AI_STAND_GROUND)
 		return;
-	if (random() > 0.15)
+	if (qrandom() > 0.15)
 		return;
 
 	self->monsterinfo.currentmove = &berserk_move_stand_fidget;
@@ -219,7 +217,7 @@
 mmove_t berserk_move_attack_club = {FRAME_att_c9, FRAME_att_c20, berserk_frames_attack_club, berserk_run};
 
 
-void berserk_strike (edict_t *self)
+void berserk_strike (edict_t */*self*/)
 {
 	//FIXME play impact sound
 }
@@ -312,7 +310,7 @@
 };
 mmove_t berserk_move_pain2 = {FRAME_painb1, FRAME_painb20, berserk_frames_pain2, berserk_run};
 
-void berserk_pain (edict_t *self, edict_t *other, float kick, int damage)
+void berserk_pain (edict_t *self, edict_t */*other*/, float /*kick*/, int damage)
 {
 	if (self->health < (self->max_health / 2))
 		self->s.skinnum = 1;
@@ -326,7 +324,7 @@
 	if (skill->value == 3)
 		return;		// no pain anims in nightmare
 
-	if ((damage < 20) || (random() < 0.5))
+	if ((damage < 20) || (qrandom() < 0.5))
 		self->monsterinfo.currentmove = &berserk_move_pain1;
 	else
 		self->monsterinfo.currentmove = &berserk_move_pain2;
@@ -378,7 +376,7 @@
 mmove_t berserk_move_death2 = {FRAME_deathc1, FRAME_deathc8, berserk_frames_death2, berserk_dead};
 
 
-void berserk_die (edict_t *self, edict_t *inflictor, edict_t *attacker, int damage, vec3_t point)
+void berserk_die (edict_t *self, edict_t */*inflictor*/, edict_t */*attacker*/, int damage, vec3_t /*point*/)
 {
 	int		n;
 
--- a/game/m_berserk.h
+++ b/game/m_berserk.h
@@ -17,8 +17,6 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-// G:\quake2\baseq2\models/monsters/berserk
-
 // This file generated by ModelGen - Do NOT Modify
 
 #define FRAME_stand1          	0
--- a/game/m_boss2.c
+++ b/game/m_boss2.c
@@ -17,14 +17,12 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-/*
-==============================================================================
-
-boss2
-
-==============================================================================
-*/
-
+#define GAME_INCLUDE
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 #include "m_boss2.h"
 
@@ -40,7 +38,7 @@
 
 void boss2_search (edict_t *self)
 {
-	if (random() < 0.5)
+	if (qrandom() < 0.5)
 		gi.sound (self, CHAN_VOICE, sound_search1, 1, ATTN_NONE, 0);
 }
 
@@ -443,7 +441,7 @@
 	}
 	else 
 	{
-		if (random() <= 0.6)
+		if (qrandom() <= 0.6)
 			self->monsterinfo.currentmove = &boss2_move_attack_pre_mg;
 		else
 			self->monsterinfo.currentmove = &boss2_move_attack_rocket;
@@ -458,7 +456,7 @@
 void boss2_reattack_mg (edict_t *self)
 {
 	if ( infront(self, self->enemy) )
-		if (random() <= 0.7)
+		if (qrandom() <= 0.7)
 			self->monsterinfo.currentmove = &boss2_move_attack_mg;
 		else
 			self->monsterinfo.currentmove = &boss2_move_attack_post_mg;
@@ -467,7 +465,7 @@
 }
 
 
-void boss2_pain (edict_t *self, edict_t *other, float kick, int damage)
+void boss2_pain (edict_t *self, edict_t */*other*/, float /*kick*/, int damage)
 {
 	if (self->health < (self->max_health / 2))
 		self->s.skinnum = 1;
@@ -504,7 +502,7 @@
 	gi.linkentity (self);
 }
 
-void boss2_die (edict_t *self, edict_t *inflictor, edict_t *attacker, int damage, vec3_t point)
+void boss2_die (edict_t *self, edict_t */*inflictor*/, edict_t */*attacker*/, int /*damage*/, vec3_t /*point*/)
 {
 	gi.sound (self, CHAN_VOICE, sound_death, 1, ATTN_NONE, 0);
 	self->deadflag = DEAD_DEAD;
@@ -511,7 +509,7 @@
 	self->takedamage = DAMAGE_NO;
 	self->count = 0;
 	self->monsterinfo.currentmove = &boss2_move_death;
-#if 0
+/*
 	int		n;
 
 	self->s.sound = 0;
@@ -534,7 +532,7 @@
 	self->deadflag = DEAD_DEAD;
 	self->takedamage = DAMAGE_YES;
 	self->monsterinfo.currentmove = &boss2_move_death;
-#endif
+*/
 }
 
 qboolean Boss2_CheckAttack (edict_t *self)
@@ -543,7 +541,6 @@
 	vec3_t	temp;
 	float	chance;
 	trace_t	tr;
-	qboolean	enemy_infront;
 	int			enemy_range;
 	float		enemy_yaw;
 
@@ -562,7 +559,7 @@
 			return false;
 	}
 	
-	enemy_infront = infront(self, self->enemy);
+	infront(self, self->enemy);	/* qboolean enemy_infront = */
 	enemy_range = range(self, self->enemy);
 	VectorSubtract (self->enemy->s.origin, self->s.origin, temp);
 	enemy_yaw = vectoyaw(temp);
@@ -611,16 +608,16 @@
 		return false;
 	}
 
-	if (random () < chance)
+	if (qrandom() < chance)
 	{
 		self->monsterinfo.attack_state = AS_MISSILE;
-		self->monsterinfo.attack_finished = level.time + 2*random();
+		self->monsterinfo.attack_finished = level.time + 2*qrandom();
 		return true;
 	}
 
 	if (self->flags & FL_FLY)
 	{
-		if (random() < 0.3)
+		if (qrandom() < 0.3)
 			self->monsterinfo.attack_state = AS_SLIDING;
 		else
 			self->monsterinfo.attack_state = AS_STRAIGHT;
--- a/game/m_boss2.h
+++ b/game/m_boss2.h
@@ -17,8 +17,6 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-// G:\quake2\baseq2\models/monsters/boss2
-
 // This file generated by ModelGen - Do NOT Modify
 
 #define FRAME_stand30         	0
--- a/game/m_boss3.c
+++ b/game/m_boss3.c
@@ -17,18 +17,16 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-/*
-==============================================================================
-
-boss3
-
-==============================================================================
-*/
-
+#define GAME_INCLUDE
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 #include "m_boss32.h"
 
-void Use_Boss3 (edict_t *ent, edict_t *other, edict_t *activator)
+void Use_Boss3 (edict_t *ent, edict_t */*other*/, edict_t */*activator*/)
 {
 	gi.WriteByte (svc_temp_entity);
 	gi.WriteByte (TE_BOSSTPORT);
--- a/game/m_boss31.c
+++ b/game/m_boss31.c
@@ -17,14 +17,13 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-/*
-==============================================================================
-
-jorg
-
-==============================================================================
-*/
-
+// jorg
+#define GAME_INCLUDE
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 #include "m_boss31.h"
 
@@ -54,7 +53,7 @@
 {
 	float r;
 
-	r = random();
+	r = qrandom();
 
 	if (r <= 0.3)
 		gi.sound (self, CHAN_VOICE, sound_search1, 1, ATTN_NORM, 0);
@@ -394,7 +393,7 @@
 void jorg_reattack1(edict_t *self)
 {
 	if (visible(self, self->enemy))
-		if (random() < 0.9)
+		if (qrandom() < 0.9)
 			self->monsterinfo.currentmove = &jorg_move_attack1;
 		else
 		{
@@ -413,7 +412,7 @@
 	self->monsterinfo.currentmove = &jorg_move_attack1;
 }
 
-void jorg_pain (edict_t *self, edict_t *other, float kick, int damage)
+void jorg_pain (edict_t *self, edict_t */*other*/, float /*kick*/, int damage)
 {
 
 	if (self->health < (self->max_health / 2))
@@ -426,7 +425,7 @@
 
 	// Lessen the chance of him going into his pain frames if he takes little damage
 	if (damage <= 40)
-		if (random()<=0.6)
+		if (qrandom()<=0.6)
 			return;
 
 	/* 
@@ -435,16 +434,16 @@
 	*/
 	
 	if ( (self->s.frame >= FRAME_attak101) && (self->s.frame <= FRAME_attak108) )
-		if (random() <= 0.005)
+		if (qrandom() <= 0.005)
 			return;
 
 	if ( (self->s.frame >= FRAME_attak109) && (self->s.frame <= FRAME_attak114) )
-		if (random() <= 0.00005)
+		if (qrandom() <= 0.00005)
 			return;
 
 
 	if ( (self->s.frame >= FRAME_attak201) && (self->s.frame <= FRAME_attak208) )
-		if (random() <= 0.005)
+		if (qrandom() <= 0.005)
 			return;
 
 
@@ -464,7 +463,7 @@
 	}
 	else
 	{
-		if (random() <= 0.3)
+		if (qrandom() <= 0.3)
 		{
 			gi.sound (self, CHAN_VOICE, sound_pain3, 1, ATTN_NORM,0);
 			self->monsterinfo.currentmove = &jorg_move_pain3;
@@ -539,12 +538,14 @@
 void jorg_attack(edict_t *self)
 {
 	vec3_t	vec;
-	float	range;
 	
 	VectorSubtract (self->enemy->s.origin, self->s.origin, vec);
+	/*
+	float range;
 	range = VectorLength (vec);
+	*/
 
-	if (random() <= 0.75)
+	if (qrandom() <= 0.75)
 	{
 		gi.sound (self, CHAN_VOICE, sound_attack1, 1, ATTN_NORM,0);
 		self->s.sound = gi.soundindex ("boss3/w_loop.wav");
@@ -557,14 +558,12 @@
 	}
 }
 
-void jorg_dead (edict_t *self)
+void jorg_dead (edict_t */*self*/)
 {
-#if 0
+/*
 	edict_t	*tempent;
-	/*
-	VectorSet (self->mins, -16, -16, -24);
-	VectorSet (self->maxs, 16, 16, -8);
-	*/
+	//VectorSet (self->mins, -16, -16, -24);
+	//VectorSet (self->maxs, 16, 16, -8);
 	
 	// Jorg is on modelindex2. Do not clear him.
 	VectorSet (self->mins, -60, -60, 0);
@@ -582,11 +581,11 @@
 	self->killtarget = 0;
 	self->target = 0;
 	SP_monster_makron (tempent);
-#endif
+*/
 }
 
 
-void jorg_die (edict_t *self, edict_t *inflictor, edict_t *attacker, int damage, vec3_t point)
+void jorg_die (edict_t *self, edict_t */*inflictor*/, edict_t */*attacker*/, int /*damage*/, vec3_t /*point*/)
 {
 	gi.sound (self, CHAN_VOICE, sound_death, 1, ATTN_NORM, 0);
 	self->deadflag = DEAD_DEAD;
@@ -602,7 +601,6 @@
 	vec3_t	temp;
 	float	chance;
 	trace_t	tr;
-	qboolean	enemy_infront;
 	int			enemy_range;
 	float		enemy_yaw;
 
@@ -621,7 +619,7 @@
 			return false;
 	}
 	
-	enemy_infront = infront(self, self->enemy);
+	infront(self, self->enemy);	/* qboolean enemy_infront = */
 	enemy_range = range(self, self->enemy);
 	VectorSubtract (self->enemy->s.origin, self->s.origin, temp);
 	enemy_yaw = vectoyaw(temp);
@@ -670,16 +668,16 @@
 		return false;
 	}
 
-	if (random () < chance)
+	if (qrandom() < chance)
 	{
 		self->monsterinfo.attack_state = AS_MISSILE;
-		self->monsterinfo.attack_finished = level.time + 2*random();
+		self->monsterinfo.attack_finished = level.time + 2*qrandom();
 		return true;
 	}
 
 	if (self->flags & FL_FLY)
 	{
-		if (random() < 0.3)
+		if (qrandom() < 0.3)
 			self->monsterinfo.attack_state = AS_SLIDING;
 		else
 			self->monsterinfo.attack_state = AS_STRAIGHT;
--- a/game/m_boss31.h
+++ b/game/m_boss31.h
@@ -17,8 +17,6 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-// G:\quake2\baseq2\models/monsters/boss3/jorg
-
 // This file generated by ModelGen - Do NOT Modify
 
 #define FRAME_attak101        	0
--- a/game/m_boss32.c
+++ b/game/m_boss32.c
@@ -17,14 +17,13 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-/*
-==============================================================================
-
-Makron -- Final Boss
-
-==============================================================================
-*/
-
+// Makron -- Final Boss
+#define GAME_INCLUDE
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 #include "m_boss32.h"
 
@@ -57,7 +56,7 @@
 {
 	float r;
 
-	r=random();
+	r=qrandom();
 	if (r <= 0.3)
 		gi.sound (self, CHAN_AUTO, sound_taunt1, 1, ATTN_NONE, 0);
 	else if (r <= 0.6)
@@ -552,7 +551,7 @@
 }	
 
 
-void makron_pain (edict_t *self, edict_t *other, float kick, int damage)
+void makron_pain (edict_t *self, edict_t */*other*/, float /*kick*/, int damage)
 {
 
 	if (self->health < (self->max_health / 2))
@@ -563,7 +562,7 @@
 
 	// Lessen the chance of him going into his pain frames
 	if (damage <=25)
-		if (random()<0.2)
+		if (qrandom()<0.2)
 			return;
 
 	self->pain_debounce_time = level.time + 3;
@@ -584,13 +583,13 @@
 	else
 	{
 		if (damage <= 150)
-			if (random() <= 0.45)
+			if (qrandom() <= 0.45)
 			{
 				gi.sound (self, CHAN_VOICE, sound_pain6, 1, ATTN_NONE,0);
 				self->monsterinfo.currentmove = &makron_move_pain6;
 			}
 		else
-			if (random() <= 0.35)
+			if (qrandom() <= 0.35)
 			{
 				gi.sound (self, CHAN_VOICE, sound_pain6, 1, ATTN_NONE,0);
 				self->monsterinfo.currentmove = &makron_move_pain6;
@@ -598,7 +597,7 @@
 	}
 };
 
-void makron_sight(edict_t *self, edict_t *other)
+void makron_sight(edict_t *self, edict_t */*other*/)
 {
 	self->monsterinfo.currentmove = &makron_move_sight;
 };
@@ -606,15 +605,13 @@
 void makron_attack(edict_t *self)
 {
 	vec3_t	vec;
-	float	range;
 	float	r;
 
-	r = random();
+	r = qrandom();
 
 	VectorSubtract (self->enemy->s.origin, self->s.origin, vec);
-	range = VectorLength (vec);
+	//float range = VectorLength (vec);
 
-
 	if (r <= 0.3)
 		self->monsterinfo.currentmove = &makron_move_attack3;
 	else if (r <= 0.6)
@@ -670,7 +667,7 @@
 }
 
 
-void makron_die (edict_t *self, edict_t *inflictor, edict_t *attacker, int damage, vec3_t point)
+void makron_die (edict_t *self, edict_t */*inflictor*/, edict_t */*attacker*/, int damage, vec3_t /*point*/)
 {
 	edict_t *tempent;
 
@@ -714,7 +711,6 @@
 	vec3_t	temp;
 	float	chance;
 	trace_t	tr;
-	qboolean	enemy_infront;
 	int			enemy_range;
 	float		enemy_yaw;
 
@@ -733,7 +729,7 @@
 			return false;
 	}
 	
-	enemy_infront = infront(self, self->enemy);
+	infront(self, self->enemy);	/* qboolean enemy_infront = */
 	enemy_range = range(self, self->enemy);
 	VectorSubtract (self->enemy->s.origin, self->s.origin, temp);
 	enemy_yaw = vectoyaw(temp);
@@ -782,16 +778,16 @@
 		return false;
 	}
 
-	if (random () < chance)
+	if (qrandom () < chance)
 	{
 		self->monsterinfo.attack_state = AS_MISSILE;
-		self->monsterinfo.attack_finished = level.time + 2*random();
+		self->monsterinfo.attack_finished = level.time + 2*qrandom();
 		return true;
 	}
 
 	if (self->flags & FL_FLY)
 	{
-		if (random() < 0.3)
+		if (qrandom() < 0.3)
 			self->monsterinfo.attack_state = AS_SLIDING;
 		else
 			self->monsterinfo.attack_state = AS_STRAIGHT;
--- a/game/m_boss32.h
+++ b/game/m_boss32.h
@@ -17,8 +17,6 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-// G:\quake2\baseq2\models/monsters/boss3/rider
-
 // This file generated by ModelGen - Do NOT Modify
 
 #define FRAME_attak101        	0
--- a/game/m_brain.c
+++ b/game/m_brain.c
@@ -17,14 +17,12 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-/*
-==============================================================================
-
-brain
-
-==============================================================================
-*/
-
+#define GAME_INCLUDE
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 #include "m_brain.h"
 
@@ -45,7 +43,7 @@
 static int	sound_melee3;
 
 
-void brain_sight (edict_t *self, edict_t *other)
+void brain_sight (edict_t *self, edict_t */*other*/)
 {
 	gi.sound (self, CHAN_VOICE, sound_sight, 1, ATTN_NORM, 0);
 }
@@ -175,10 +173,10 @@
 mmove_t brain_move_walk1 = {FRAME_walk101, FRAME_walk111, brain_frames_walk1, NULL};
 
 // walk2 is FUBAR, do not use
-#if 0
+/*
 void brain_walk2_cycle (edict_t *self)
 {
-	if (random() > 0.1)
+	if (qrandom() > 0.1)
 		self->monsterinfo.nextframe = FRAME_walk220;
 }
 
@@ -229,11 +227,11 @@
 	ai_walk,	-5,	NULL
 };
 mmove_t brain_move_walk2 = {FRAME_walk201, FRAME_walk240, brain_frames_walk2, NULL};
-#endif
+*/
 
 void brain_walk (edict_t *self)
 {
-//	if (random() <= 0.5)
+//	if (qrandom() <= 0.5)
 		self->monsterinfo.currentmove = &brain_move_walk1;
 //	else
 //		self->monsterinfo.currentmove = &brain_move_walk2;
@@ -351,7 +349,7 @@
 
 void brain_dodge (edict_t *self, edict_t *attacker, float eta)
 {
-	if (random() > 0.25)
+	if (qrandom() > 0.25)
 		return;
 
 	if (!self->enemy)
@@ -502,7 +500,7 @@
 
 void brain_melee(edict_t *self)
 {
-	if (random() <= 0.5)
+	if (qrandom() <= 0.5)
 		self->monsterinfo.currentmove = &brain_move_attack1;
 	else
 		self->monsterinfo.currentmove = &brain_move_attack2;
@@ -539,7 +537,7 @@
 }
 
 
-void brain_pain (edict_t *self, edict_t *other, float kick, int damage)
+void brain_pain (edict_t *self, edict_t */*other*/, float /*kick*/, int /*damage*/)
 {
 	float	r;
 
@@ -553,7 +551,7 @@
 	if (skill->value == 3)
 		return;		// no pain anims in nightmare
 
-	r = random();
+	r = qrandom();
 	if (r < 0.33)
 	{
 		gi.sound (self, CHAN_VOICE, sound_pain1, 1, ATTN_NORM, 0);
@@ -583,7 +581,7 @@
 
 
 
-void brain_die (edict_t *self, edict_t *inflictor, edict_t *attacker, int damage, vec3_t point)
+void brain_die (edict_t *self, edict_t */*inflictor*/, edict_t */*attacker*/, int damage, vec3_t /*point*/)
 {
 	int		n;
 
@@ -610,7 +608,7 @@
 	gi.sound (self, CHAN_VOICE, sound_death, 1, ATTN_NORM, 0);
 	self->deadflag = DEAD_DEAD;
 	self->takedamage = DAMAGE_YES;
-	if (random() <= 0.5)
+	if (qrandom() <= 0.5)
 		self->monsterinfo.currentmove = &brain_move_death1;
 	else
 		self->monsterinfo.currentmove = &brain_move_death2;
--- a/game/m_brain.h
+++ b/game/m_brain.h
@@ -17,8 +17,6 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-// G:\quake2\baseq2\models/monsters/brain
-
 // This file generated by ModelGen - Do NOT Modify
 
 #define FRAME_walk101         	0
--- a/game/m_chick.c
+++ b/game/m_chick.c
@@ -17,14 +17,12 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-/*
-==============================================================================
-
-chick
-
-==============================================================================
-*/
-
+#define GAME_INCLUDE
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 #include "m_chick.h"
 
@@ -55,7 +53,7 @@
 
 void ChickMoan (edict_t *self)
 {
-	if (random() < 0.5)
+	if (qrandom() < 0.5)
 		gi.sound (self, CHAN_VOICE, sound_idle1, 1, ATTN_IDLE, 0);
 	else
 		gi.sound (self, CHAN_VOICE, sound_idle2, 1, ATTN_IDLE, 0);
@@ -100,7 +98,7 @@
 {
 	if (self->monsterinfo.aiflags & AI_STAND_GROUND)
 		return;
-	if (random() <= 0.3)
+	if (qrandom() <= 0.3)
 		self->monsterinfo.currentmove = &chick_move_fidget;
 }
 
@@ -263,7 +261,7 @@
 };
 mmove_t chick_move_pain3 = {FRAME_pain301, FRAME_pain321, chick_frames_pain3, chick_run};
 
-void chick_pain (edict_t *self, edict_t *other, float kick, int damage)
+void chick_pain (edict_t *self, edict_t */*other*/, float /*kick*/, int damage)
 {
 	float	r;
 
@@ -275,7 +273,7 @@
 
 	self->pain_debounce_time = level.time + 3;
 
-	r = random();
+	r = qrandom();
 	if (r < 0.33)
 		gi.sound (self, CHAN_VOICE, sound_pain1, 1, ATTN_NORM, 0);
 	else if (r < 0.66)
@@ -350,7 +348,7 @@
 };
 mmove_t chick_move_death1 = {FRAME_death101, FRAME_death112, chick_frames_death1, chick_dead};
 
-void chick_die (edict_t *self, edict_t *inflictor, edict_t *attacker, int damage, vec3_t point)
+void chick_die (edict_t *self, edict_t */*inflictor*/, edict_t */*attacker*/, int damage, vec3_t /*point*/)
 {
 	int		n;
 
@@ -427,9 +425,9 @@
 };
 mmove_t chick_move_duck = {FRAME_duck01, FRAME_duck07, chick_frames_duck, chick_run};
 
-void chick_dodge (edict_t *self, edict_t *attacker, float eta)
+void chick_dodge (edict_t *self, edict_t *attacker, float /*eta*/)
 {
-	if (random() > 0.25)
+	if (qrandom() > 0.25)
 		return;
 
 	if (!self->enemy)
@@ -532,7 +530,7 @@
 	{
 		if (range (self, self->enemy) > RANGE_MELEE)
 			if ( visible (self, self->enemy) )
-				if (random() <= 0.6)
+				if (qrandom() <= 0.6)
 				{
 					self->monsterinfo.currentmove = &chick_move_attack1;
 					return;
@@ -575,7 +573,7 @@
 	if (self->enemy->health > 0)
 	{
 		if (range (self, self->enemy) == RANGE_MELEE)
-			if (random() <= 0.9)
+			if (qrandom() <= 0.9)
 			{				
 				self->monsterinfo.currentmove = &chick_move_slash;
 				return;
@@ -616,7 +614,7 @@
 	self->monsterinfo.currentmove = &chick_move_start_attack1;
 }
 
-void chick_sight(edict_t *self, edict_t *other)
+void chick_sight(edict_t *self, edict_t */*other*/)
 {
 	gi.sound (self, CHAN_VOICE, sound_sight, 1, ATTN_NORM, 0);
 }
--- a/game/m_chick.h
+++ b/game/m_chick.h
@@ -17,8 +17,6 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-// G:\quake2\baseq2\models/monsters/bitch
-
 // This file generated by qdata - Do NOT Modify
 
 #define FRAME_attak101        	0
--- a/game/m_flash.c
+++ b/game/m_flash.c
@@ -17,9 +17,12 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-// m_flash.c
-
-#include "../q_shared.h"
+#define GAME_INCLUDE
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 
 // this file is included in both the game dll and quake2,
 // the game needs it to source shot locations, the client
--- a/game/m_flipper.c
+++ b/game/m_flipper.c
@@ -17,14 +17,12 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-/*
-==============================================================================
-
-FLIPPER
-
-==============================================================================
-*/
-
+#define GAME_INCLUDE
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 #include "m_flipper.h"
 
@@ -220,7 +218,7 @@
 	self->monsterinfo.currentmove = &flipper_move_attack;
 }
 
-void flipper_pain (edict_t *self, edict_t *other, float kick, int damage)
+void flipper_pain (edict_t *self, edict_t */*other*/, float /*kick*/, int /*damage*/)
 {
 	int		n;
 
@@ -324,12 +322,12 @@
 };
 mmove_t flipper_move_death = {FRAME_flpdth01, FRAME_flpdth56, flipper_frames_death, flipper_dead};
 
-void flipper_sight (edict_t *self, edict_t *other)
+void flipper_sight (edict_t *self, edict_t */*other*/)
 {
 	gi.sound (self, CHAN_VOICE, sound_sight, 1, ATTN_NORM, 0);
 }
 
-void flipper_die (edict_t *self, edict_t *inflictor, edict_t *attacker, int damage, vec3_t point)
+void flipper_die (edict_t *self, edict_t */*inflictor*/, edict_t */*attacker*/, int damage, vec3_t /*point*/)
 {
 	int		n;
 
--- a/game/m_flipper.h
+++ b/game/m_flipper.h
@@ -17,8 +17,6 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-// G:\quake2\baseq2\models/monsters/flipper
-
 // This file generated by ModelGen - Do NOT Modify
 
 #define FRAME_flpbit01        	0
--- a/game/m_float.c
+++ b/game/m_float.c
@@ -17,14 +17,12 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-/*
-==============================================================================
-
-floater
-
-==============================================================================
-*/
-
+#define GAME_INCLUDE
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 #include "m_float.h"
 
@@ -38,7 +36,7 @@
 static int	sound_sight;
 
 
-void floater_sight (edict_t *self, edict_t *other)
+void floater_sight (edict_t *self, edict_t */*other*/)
 {
 	gi.sound (self, CHAN_VOICE, sound_sight, 1, ATTN_NORM, 0);
 }
@@ -196,7 +194,7 @@
 
 void floater_stand (edict_t *self)
 {
-	if (random() <= 0.5)		
+	if (qrandom() <= 0.5)		
 		self->monsterinfo.currentmove = &floater_move_stand1;
 	else
 		self->monsterinfo.currentmove = &floater_move_stand2;
@@ -556,7 +554,7 @@
 
 void floater_melee(edict_t *self)
 {
-	if (random() < 0.5)		
+	if (qrandom() < 0.5)
 		self->monsterinfo.currentmove = &floater_move_attack3;
 	else
 		self->monsterinfo.currentmove = &floater_move_attack2;
@@ -563,7 +561,7 @@
 }
 
 
-void floater_pain (edict_t *self, edict_t *other, float kick, int damage)
+void floater_pain (edict_t *self, edict_t */*other*/, float /*kick*/, int /*damage*/)
 {
 	int		n;
 
@@ -600,7 +598,7 @@
 	gi.linkentity (self);
 }
 
-void floater_die (edict_t *self, edict_t *inflictor, edict_t *attacker, int damage, vec3_t point)
+void floater_die (edict_t *self, edict_t */*inflictor*/, edict_t */*attacker*/, int /*damage*/, vec3_t /*point*/)
 {
 	gi.sound (self, CHAN_VOICE, sound_death1, 1, ATTN_NORM, 0);
 	BecomeExplosion1(self);
@@ -652,7 +650,7 @@
 
 	gi.linkentity (self);
 
-	if (random() <= 0.5)		
+	if (qrandom() <= 0.5)
 		self->monsterinfo.currentmove = &floater_move_stand1;	
 	else
 		self->monsterinfo.currentmove = &floater_move_stand2;	
--- a/game/m_float.h
+++ b/game/m_float.h
@@ -17,8 +17,6 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-// G:\quake2\baseq2\models/monsters/float
-
 // This file generated by ModelGen - Do NOT Modify
 
 #define FRAME_actvat01        	0
--- a/game/m_flyer.c
+++ b/game/m_flyer.c
@@ -17,14 +17,12 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-/*
-==============================================================================
-
-flyer
-
-==============================================================================
-*/
-
+#define GAME_INCLUDE
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 #include "m_flyer.h"
 
@@ -49,7 +47,7 @@
 void flyer_nextmove (edict_t *self);
 
 
-void flyer_sight (edict_t *self, edict_t *other)
+void flyer_sight (edict_t *self, edict_t */*other*/)
 {
 	gi.sound (self, CHAN_VOICE, sound_sight, 1, ATTN_NORM, 0);
 }
@@ -478,7 +476,7 @@
 
 void flyer_loop_melee (edict_t *self)
 {
-/*	if (random() <= 0.5)	
+/*	if (qrandom() <= 0.5)	
 		self->monsterinfo.currentmove = &flyer_move_attack1;
 	else */
 	self->monsterinfo.currentmove = &flyer_move_loop_melee;
@@ -488,7 +486,7 @@
 
 void flyer_attack (edict_t *self)
 {
-/*	if (random() <= 0.5)	
+/*	if (qrandom() <= 0.5)	
 		self->monsterinfo.currentmove = &flyer_move_attack1;
 	else */
 	self->monsterinfo.currentmove = &flyer_move_attack2;
@@ -520,7 +518,7 @@
 void flyer_check_melee(edict_t *self)
 {
 	if (range (self, self->enemy) == RANGE_MELEE)
-		if (random() <= 0.8)
+		if (qrandom() <= 0.8)
 			self->monsterinfo.currentmove = &flyer_move_loop_melee;
 		else
 			self->monsterinfo.currentmove = &flyer_move_end_melee;
@@ -528,7 +526,7 @@
 		self->monsterinfo.currentmove = &flyer_move_end_melee;
 }
 
-void flyer_pain (edict_t *self, edict_t *other, float kick, int damage)
+void flyer_pain (edict_t *self, edict_t */*other*/, float /*kick*/, int /*damage*/)
 {
 	int		n;
 
@@ -561,7 +559,7 @@
 }
 
 
-void flyer_die(edict_t *self, edict_t *inflictor, edict_t *attacker, int damage, vec3_t point)
+void flyer_die(edict_t *self, edict_t */*inflictor*/, edict_t */*attacker*/, int /*damage*/, vec3_t /*point*/)
 {
 	gi.sound (self, CHAN_VOICE, sound_die, 1, ATTN_NORM, 0);
 	BecomeExplosion1(self);
@@ -579,7 +577,7 @@
 	}
 
 	// fix a map bug in jail5.bsp
-	if (!Q_stricmp(level.mapname, "jail5") && (self->s.origin[2] == -104))
+	if (!Q_strcasecmp(level.mapname, "jail5") && (self->s.origin[2] == -104))
 	{
 		self->targetname = self->target;
 		self->target = NULL;
--- a/game/m_flyer.h
+++ b/game/m_flyer.h
@@ -17,8 +17,6 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-// G:\quake2\baseq2\models/monsters/flyer
-
 // This file generated by ModelGen - Do NOT Modify
 
 #define ACTION_nothing			0
--- a/game/m_gladiator.c
+++ b/game/m_gladiator.c
@@ -17,14 +17,12 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-/*
-==============================================================================
-
-GLADIATOR
-
-==============================================================================
-*/
-
+#define GAME_INCLUDE
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 #include "m_gladiator.h"
 
@@ -46,7 +44,7 @@
 	gi.sound (self, CHAN_VOICE, sound_idle, 1, ATTN_IDLE, 0);
 }
 
-void gladiator_sight (edict_t *self, edict_t *other)
+void gladiator_sight (edict_t *self, edict_t */*other*/)
 {
 	gi.sound (self, CHAN_VOICE, sound_sight, 1, ATTN_NORM, 0);
 }
@@ -237,7 +235,7 @@
 };
 mmove_t gladiator_move_pain_air = {FRAME_painup1, FRAME_painup7, gladiator_frames_pain_air, gladiator_run};
 
-void gladiator_pain (edict_t *self, edict_t *other, float kick, int damage)
+void gladiator_pain (edict_t *self, edict_t */*other*/, float /*kick*/, int /*damage*/)
 {
 
 	if (self->health < (self->max_health / 2))
@@ -252,7 +250,7 @@
 
 	self->pain_debounce_time = level.time + 3;
 
-	if (random() < 0.5)
+	if (qrandom() < 0.5)
 		gi.sound (self, CHAN_VOICE, sound_pain1, 1, ATTN_NORM, 0);
 	else
 		gi.sound (self, CHAN_VOICE, sound_pain2, 1, ATTN_NORM, 0);
@@ -305,7 +303,7 @@
 };
 mmove_t gladiator_move_death = {FRAME_death1, FRAME_death22, gladiator_frames_death, gladiator_dead};
 
-void gladiator_die (edict_t *self, edict_t *inflictor, edict_t *attacker, int damage, vec3_t point)
+void gladiator_die (edict_t *self, edict_t */*inflictor*/, edict_t */*attacker*/, int damage, vec3_t /*point*/)
 {
 	int		n;
 
--- a/game/m_gladiator.h
+++ b/game/m_gladiator.h
@@ -17,8 +17,6 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-// G:\quake2\baseq2\models/monsters/gladiatr
-
 // This file generated by ModelGen - Do NOT Modify
 
 #define FRAME_stand1          	0
--- a/game/m_gunner.c
+++ b/game/m_gunner.c
@@ -17,14 +17,12 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-/*
-==============================================================================
-
-GUNNER
-
-==============================================================================
-*/
-
+#define GAME_INCLUDE
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 #include "m_gunner.h"
 
@@ -43,7 +41,7 @@
 	gi.sound (self, CHAN_VOICE, sound_idle, 1, ATTN_IDLE, 0);
 }
 
-void gunner_sight (edict_t *self, edict_t *other)
+void gunner_sight (edict_t *self, edict_t */*other*/)
 {
 	gi.sound (self, CHAN_VOICE, sound_sight, 1, ATTN_NORM, 0);
 }
@@ -125,7 +123,7 @@
 {
 	if (self->monsterinfo.aiflags & AI_STAND_GROUND)
 		return;
-	if (random() <= 0.05)
+	if (qrandom() <= 0.05)
 		self->monsterinfo.currentmove = &gunner_move_fidget;
 }
 
@@ -280,7 +278,7 @@
 };
 mmove_t gunner_move_pain1 = {FRAME_pain101, FRAME_pain118, gunner_frames_pain1, gunner_run};
 
-void gunner_pain (edict_t *self, edict_t *other, float kick, int damage)
+void gunner_pain (edict_t *self, edict_t */*other*/, float /*kick*/, int damage)
 {
 	if (self->health < (self->max_health / 2))
 		self->s.skinnum = 1;
@@ -332,7 +330,7 @@
 };
 mmove_t gunner_move_death = {FRAME_death01, FRAME_death11, gunner_frames_death, gunner_dead};
 
-void gunner_die (edict_t *self, edict_t *inflictor, edict_t *attacker, int damage, vec3_t point)
+void gunner_die (edict_t *self, edict_t */*inflictor*/, edict_t */*attacker*/, int damage, vec3_t /*point*/)
 {
 	int		n;
 
@@ -367,7 +365,7 @@
 	self->monsterinfo.aiflags |= AI_DUCKED;
 	if (skill->value >= 2)
 	{
-		if (random() > 0.5)
+		if (qrandom() > 0.5)
 			GunnerGrenade (self);
 	}
 
@@ -406,9 +404,9 @@
 };
 mmove_t	gunner_move_duck = {FRAME_duck01, FRAME_duck08, gunner_frames_duck, gunner_run};
 
-void gunner_dodge (edict_t *self, edict_t *attacker, float eta)
+void gunner_dodge (edict_t *self, edict_t *attacker, float /*eta*/)
 {
-	if (random() > 0.25)
+	if (qrandom() > 0.25)
 		return;
 
 	if (!self->enemy)
@@ -552,7 +550,7 @@
 	}
 	else
 	{
-		if (random() <= 0.5)
+		if (qrandom() <= 0.5)
 			self->monsterinfo.currentmove = &gunner_move_attack_grenade;
 		else
 			self->monsterinfo.currentmove = &gunner_move_attack_chain;
@@ -568,7 +566,7 @@
 {
 	if (self->enemy->health > 0)
 		if ( visible (self, self->enemy) )
-			if (random() <= 0.5)
+			if (qrandom() <= 0.5)
 			{
 				self->monsterinfo.currentmove = &gunner_move_fire_chain;
 				return;
--- a/game/m_gunner.h
+++ b/game/m_gunner.h
@@ -17,8 +17,6 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-// G:\quake2\baseq2\models/gunner
-
 // This file generated by ModelGen - Do NOT Modify
 
 #define FRAME_stand01         	0
--- a/game/m_hover.c
+++ b/game/m_hover.c
@@ -17,14 +17,12 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-/*
-==============================================================================
-
-hover
-
-==============================================================================
-*/
-
+#define GAME_INCLUDE
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 #include "m_hover.h"
 
@@ -40,7 +38,7 @@
 static int	sound_search2;
 
 
-void hover_sight (edict_t *self, edict_t *other)
+void hover_sight (edict_t *self, edict_t */*other*/)
 {
 	gi.sound (self, CHAN_VOICE, sound_sight, 1, ATTN_NORM, 0);
 }
@@ -47,7 +45,7 @@
 
 void hover_search (edict_t *self)
 {
-	if (random() < 0.5)
+	if (qrandom() < 0.5)
 		gi.sound (self, CHAN_VOICE, sound_search1, 1, ATTN_NORM, 0);
 	else
 		gi.sound (self, CHAN_VOICE, sound_search2, 1, ATTN_NORM, 0);
@@ -422,7 +420,7 @@
 {
 	if (self->enemy->health > 0 )
 		if (visible (self, self->enemy) )
-			if (random() <= 0.6)		
+			if (qrandom() <= 0.6)		
 			{
 				self->monsterinfo.currentmove = &hover_move_attack1;
 				return;
@@ -484,7 +482,7 @@
 }
 
 
-void hover_pain (edict_t *self, edict_t *other, float kick, int damage)
+void hover_pain (edict_t *self, edict_t */*other*/, float /*kick*/, int damage)
 {
 	if (self->health < (self->max_health / 2))
 		self->s.skinnum = 1;
@@ -499,7 +497,7 @@
 
 	if (damage <= 25)
 	{
-		if (random() < 0.5)
+		if (qrandom() < 0.5)
 		{
 			gi.sound (self, CHAN_VOICE, sound_pain1, 1, ATTN_NORM, 0);
 			self->monsterinfo.currentmove = &hover_move_pain3;
@@ -538,7 +536,7 @@
 	gi.linkentity (self);
 }
 
-void hover_die (edict_t *self, edict_t *inflictor, edict_t *attacker, int damage, vec3_t point)
+void hover_die (edict_t *self, edict_t */*inflictor*/, edict_t */*attacker*/, int damage, vec3_t /*point*/)
 {
 	int		n;
 
@@ -559,7 +557,7 @@
 		return;
 
 // regular death
-	if (random() < 0.5)
+	if (qrandom() < 0.5)
 		gi.sound (self, CHAN_VOICE, sound_death1, 1, ATTN_NORM, 0);
 	else
 		gi.sound (self, CHAN_VOICE, sound_death2, 1, ATTN_NORM, 0);
--- a/game/m_hover.h
+++ b/game/m_hover.h
@@ -17,8 +17,6 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-// G:\quake2\baseq2\models/monsters/hover
-
 // This file generated by ModelGen - Do NOT Modify
 
 #define FRAME_stand01         	0
--- a/game/m_infantry.c
+++ b/game/m_infantry.c
@@ -17,14 +17,12 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-/*
-==============================================================================
-
-INFANTRY
-
-==============================================================================
-*/
-
+#define GAME_INCLUDE
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 #include "m_infantry.h"
 
@@ -212,7 +210,7 @@
 };
 mmove_t infantry_move_pain2 = {FRAME_pain201, FRAME_pain210, infantry_frames_pain2, infantry_run};
 
-void infantry_pain (edict_t *self, edict_t *other, float kick, int damage)
+void infantry_pain (edict_t *self, edict_t */*other*/, float /*kick*/, int /*damage*/)
 {
 	int		n;
 
@@ -296,7 +294,7 @@
 	monster_fire_bullet (self, start, forward, 3, 4, DEFAULT_BULLET_HSPREAD, DEFAULT_BULLET_VSPREAD, flash_number);
 }
 
-void infantry_sight (edict_t *self, edict_t *other)
+void infantry_sight (edict_t *self, edict_t */*other*/)
 {
 	gi.sound (self, CHAN_BODY, sound_sight, 1, ATTN_NORM, 0);
 }
@@ -383,7 +381,7 @@
 mmove_t infantry_move_death3 = {FRAME_death301, FRAME_death309, infantry_frames_death3, infantry_dead};
 
 
-void infantry_die (edict_t *self, edict_t *inflictor, edict_t *attacker, int damage, vec3_t point)
+void infantry_die (edict_t *self, edict_t */*inflictor*/, edict_t */*attacker*/, int damage, vec3_t /*point*/)
 {
 	int		n;
 
@@ -463,9 +461,9 @@
 };
 mmove_t infantry_move_duck = {FRAME_duck01, FRAME_duck05, infantry_frames_duck, infantry_run};
 
-void infantry_dodge (edict_t *self, edict_t *attacker, float eta)
+void infantry_dodge (edict_t *self, edict_t *attacker, float /*eta*/)
 {
-	if (random() > 0.25)
+	if (qrandom() > 0.25)
 		return;
 
 	if (!self->enemy)
--- a/game/m_infantry.h
+++ b/game/m_infantry.h
@@ -17,8 +17,6 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-// G:\quake2\baseq2\models/monsters/infantry
-
 // This file generated by ModelGen - Do NOT Modify
 
 #define FRAME_gun02           	0
--- a/game/m_insane.c
+++ b/game/m_insane.c
@@ -17,14 +17,12 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-/*
-==============================================================================
-
-insane
-
-==============================================================================
-*/
-
+#define GAME_INCLUDE
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 #include "m_insane.h"
 
@@ -433,7 +431,7 @@
 
 void insane_cross (edict_t *self)
 {
-	if (random() < 0.8)		
+	if (qrandom() < 0.8)		
 		self->monsterinfo.currentmove = &insane_move_cross;
 	else
 		self->monsterinfo.currentmove = &insane_move_struggle_cross;
@@ -450,7 +448,7 @@
 	if (self->spawnflags & 4)
 		self->monsterinfo.currentmove = &insane_move_crawl;
 	else
-		if (random() <= 0.5)
+		if (qrandom() <= 0.5)
 			self->monsterinfo.currentmove = &insane_move_walk_normal;
 		else
 			self->monsterinfo.currentmove = &insane_move_walk_insane;
@@ -467,7 +465,7 @@
 	if (self->spawnflags & 4)				// Crawling?
 		self->monsterinfo.currentmove = &insane_move_runcrawl;
 	else
-		if (random() <= 0.5)				// Else, mix it up
+		if (qrandom() <= 0.5)				// Else, mix it up
 			self->monsterinfo.currentmove = &insane_move_run_normal;
 		else
 			self->monsterinfo.currentmove = &insane_move_run_insane;
@@ -474,7 +472,7 @@
 }
 
 
-void insane_pain (edict_t *self, edict_t *other, float kick, int damage)
+void insane_pain (edict_t *self, edict_t */*other*/, float /*kick*/, int /*damage*/)
 {
 	int	l,r;
 
@@ -526,8 +524,8 @@
 //	if ( (self->s.frame == FRAME_stand94) || (self->s.frame == FRAME_stand65) )
 	if (self->spawnflags & 32)				// Always stand
 		return;
-	if (random() < 0.3)
-		if (random() < 0.5)
+	if (qrandom() < 0.3)
+		if (qrandom() < 0.5)
 			self->monsterinfo.currentmove = &insane_move_uptodown;
 		else
 			self->monsterinfo.currentmove = &insane_move_jumpdown; 
@@ -538,7 +536,7 @@
 	// If Hold_Ground and Crawl are set
 	if ( (self->spawnflags & 4) && (self->spawnflags & 16) )
 		return;
-	if (random() < 0.5)
+	if (qrandom() < 0.5)
 		self->monsterinfo.currentmove = &insane_move_downtoup;				
 
 }
@@ -554,7 +552,7 @@
 	else if ( (self->spawnflags & 4) && (self->spawnflags & 16) )
 		self->monsterinfo.currentmove = &insane_move_down;
 	else
-		if (random() < 0.5)
+		if (qrandom() < 0.5)
 			self->monsterinfo.currentmove = &insane_move_stand_normal;
 		else
 			self->monsterinfo.currentmove = &insane_move_stand_insane;
@@ -578,7 +576,7 @@
 }
 
 
-void insane_die (edict_t *self, edict_t *inflictor, edict_t *attacker, int damage, vec3_t point)
+void insane_die (edict_t *self, edict_t */*inflictor*/, edict_t */*attacker*/, int damage, vec3_t /*point*/)
 {
 	int		n;
 
--- a/game/m_insane.h
+++ b/game/m_insane.h
@@ -17,8 +17,6 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-// G:\quake2\baseq2\models/monsters/insane
-
 // This file generated by ModelGen - Do NOT Modify
 
 #define FRAME_stand1          	0
--- a/game/m_medic.c
+++ b/game/m_medic.c
@@ -17,14 +17,12 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-/*
-==============================================================================
-
-MEDIC
-
-==============================================================================
-*/
-
+#define GAME_INCLUDE
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 #include "m_medic.h"
 
@@ -113,7 +111,7 @@
 	}
 }
 
-void medic_sight (edict_t *self, edict_t *other)
+void medic_sight (edict_t *self, edict_t */*other*/)
 {
 	gi.sound (self, CHAN_VOICE, sound_sight, 1, ATTN_NORM, 0);
 }
@@ -314,7 +312,7 @@
 };
 mmove_t medic_move_pain2 = {FRAME_painb1, FRAME_painb15, medic_frames_pain2, medic_run};
 
-void medic_pain (edict_t *self, edict_t *other, float kick, int damage)
+void medic_pain (edict_t *self, edict_t */*other*/, float /*kick*/, int /*damage*/)
 {
 	if (self->health < (self->max_health / 2))
 		self->s.skinnum = 1;
@@ -327,7 +325,7 @@
 	if (skill->value == 3)
 		return;		// no pain anims in nightmare
 
-	if (random() < 0.5)
+	if (qrandom() < 0.5)
 	{
 		self->monsterinfo.currentmove = &medic_move_pain1;
 		gi.sound (self, CHAN_VOICE, sound_pain1, 1, ATTN_NORM, 0);
@@ -410,7 +408,7 @@
 };
 mmove_t medic_move_death = {FRAME_death1, FRAME_death30, medic_frames_death, medic_dead};
 
-void medic_die (edict_t *self, edict_t *inflictor, edict_t *attacker, int damage, vec3_t point)
+void medic_die (edict_t *self, edict_t */*inflictor*/, edict_t */*attacker*/, int damage, vec3_t /*point*/)
 {
 	int		n;
 
@@ -491,9 +489,9 @@
 };
 mmove_t medic_move_duck = {FRAME_duck1, FRAME_duck16, medic_frames_duck, medic_run};
 
-void medic_dodge (edict_t *self, edict_t *attacker, float eta)
+void medic_dodge (edict_t *self, edict_t *attacker, float /*eta*/)
 {
-	if (random() > 0.25)
+	if (qrandom() > 0.25)
 		return;
 
 	if (!self->enemy)
@@ -527,7 +525,7 @@
 void medic_continue (edict_t *self)
 {
 	if (visible (self, self->enemy) )
-		if (random() <= 0.95)
+		if (qrandom() <= 0.95)
 			self->monsterinfo.currentmove = &medic_move_attackHyperBlaster;
 }
 
--- a/game/m_medic.h
+++ b/game/m_medic.h
@@ -17,8 +17,6 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-// G:\quake2\baseq2\models/monsters/medic
-
 // This file generated by ModelGen - Do NOT Modify
 
 #define FRAME_walk1           	0
--- a/game/m_move.c
+++ b/game/m_move.c
@@ -18,7 +18,12 @@
 
 */
 // m_move.c -- monster movement
-
+#define GAME_INCLUDE
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 
 #define	STEPSIZE	18
--- a/game/m_mutant.c
+++ b/game/m_mutant.c
@@ -17,14 +17,12 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-/*
-==============================================================================
-
-mutant
-
-==============================================================================
-*/
-
+#define GAME_INCLUDE
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 #include "m_mutant.h"
 
@@ -59,7 +57,7 @@
 		gi.sound (self, CHAN_VOICE, sound_step3, 1, ATTN_NORM, 0);
 }
 
-void mutant_sight (edict_t *self, edict_t *other)
+void mutant_sight (edict_t *self, edict_t */*other*/)
 {
 	gi.sound (self, CHAN_VOICE, sound_sight, 1, ATTN_NORM, 0);
 }
@@ -152,7 +150,7 @@
 
 void mutant_idle_loop (edict_t *self)
 {
-	if (random() < 0.75)
+	if (qrandom() < 0.75)
 		self->monsterinfo.nextframe = FRAME_stand155;
 }
 
@@ -279,7 +277,7 @@
 	if (!self->enemy || !self->enemy->inuse || self->enemy->health <= 0)
 		return;
 
-	if ( ((skill->value == 3) && (random() < 0.5)) || (range(self, self->enemy) == RANGE_MELEE) )
+	if ( ((skill->value == 3) && (qrandom() < 0.5)) || (range(self, self->enemy) == RANGE_MELEE) )
 		self->monsterinfo.nextframe = FRAME_attack09;
 }
 
@@ -305,7 +303,7 @@
 // ATTACK
 //
 
-void mutant_jump_touch (edict_t *self, edict_t *other, cplane_t *plane, csurface_t *surf)
+void mutant_jump_touch (edict_t *self, edict_t *other, cplane_t */*plane*/, csurface_t */*surf*/)
 {
 	if (self->health <= 0)
 	{
@@ -324,7 +322,7 @@
 			VectorCopy (self->velocity, normal);
 			VectorNormalize(normal);
 			VectorMA (self->s.origin, self->maxs[0], normal, point);
-			damage = 40 + 10 * random();
+			damage = 40 + 10 * qrandom();
 			T_Damage (other, self, self, self->velocity, point, normal, damage, damage, 0, MOD_UNKNOWN);
 		}
 	}
@@ -423,7 +421,7 @@
 		return false;
 	if (distance > 100)
 	{
-		if (random() < 0.9)
+		if (qrandom() < 0.9)
 			return false;
 	}
 
@@ -493,7 +491,7 @@
 };
 mmove_t mutant_move_pain3 = {FRAME_pain301, FRAME_pain311, mutant_frames_pain3, mutant_run};
 
-void mutant_pain (edict_t *self, edict_t *other, float kick, int damage)
+void mutant_pain (edict_t *self, edict_t */*other*/, float /*kick*/, int /*damage*/)
 {
 	float	r;
 
@@ -508,7 +506,7 @@
 	if (skill->value == 3)
 		return;		// no pain anims in nightmare
 
-	r = random();
+	r = qrandom();
 	if (r < 0.33)
 	{
 		gi.sound (self, CHAN_VOICE, sound_pain1, 1, ATTN_NORM, 0);
@@ -571,7 +569,7 @@
 };
 mmove_t mutant_move_death2 = {FRAME_death201, FRAME_death210, mutant_frames_death2, mutant_dead};
 
-void mutant_die (edict_t *self, edict_t *inflictor, edict_t *attacker, int damage, vec3_t point)
+void mutant_die (edict_t *self, edict_t */*inflictor*/, edict_t */*attacker*/, int damage, vec3_t /*point*/)
 {
 	int		n;
 
@@ -595,7 +593,7 @@
 	self->takedamage = DAMAGE_YES;
 	self->s.skinnum = 1;
 
-	if (random() < 0.5)
+	if (qrandom() < 0.5)
 		self->monsterinfo.currentmove = &mutant_move_death1;
 	else
 		self->monsterinfo.currentmove = &mutant_move_death2;
--- a/game/m_mutant.h
+++ b/game/m_mutant.h
@@ -17,8 +17,6 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-// G:\quake2\baseq2\models/monsters/mutant
-
 // This file generated by ModelGen - Do NOT Modify
 
 #define FRAME_attack01        	0
--- a/game/m_parasite.c
+++ b/game/m_parasite.c
@@ -17,14 +17,12 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-/*
-==============================================================================
-
-parasite
-
-==============================================================================
-*/
-
+#define GAME_INCLUDE
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 #include "m_parasite.h"
 
@@ -62,7 +60,7 @@
 	gi.sound (self, CHAN_WEAPON, sound_reelin, 1, ATTN_NORM, 0);
 }
 
-void parasite_sight (edict_t *self, edict_t *other)
+void parasite_sight (edict_t *self, edict_t */*other*/)
 {
 	gi.sound (self, CHAN_WEAPON, sound_sight, 1, ATTN_NORM, 0);
 }
@@ -128,7 +126,7 @@
 
 void parasite_refidget (edict_t *self)
 { 
-	if (random() <= 0.8)
+	if (qrandom() <= 0.8)
 		self->monsterinfo.currentmove = &parasite_move_fidget;
 	else
 		self->monsterinfo.currentmove = &parasite_move_end_fidget;
@@ -272,7 +270,7 @@
 };
 mmove_t parasite_move_pain1 = {FRAME_pain101, FRAME_pain111, parasite_frames_pain1, parasite_start_run};
 
-void parasite_pain (edict_t *self, edict_t *other, float kick, int damage)
+void parasite_pain (edict_t *self, edict_t */*other*/, float /*kick*/, int /*damage*/)
 {
 	if (self->health < (self->max_health / 2))
 		self->s.skinnum = 1;
@@ -285,7 +283,7 @@
 	if (skill->value == 3)
 		return;		// no pain anims in nightmare
 
-	if (random() < 0.5)
+	if (qrandom() < 0.5)
 		gi.sound (self, CHAN_VOICE, sound_pain1, 1, ATTN_NORM, 0);
 	else
 		gi.sound (self, CHAN_VOICE, sound_pain2, 1, ATTN_NORM, 0);
@@ -432,7 +430,7 @@
 
 void parasite_attack (edict_t *self)
 {
-//	if (random() <= 0.2)
+//	if (qrandom() <= 0.2)
 //		self->monsterinfo.currentmove = &parasite_move_break;
 //	else
 		self->monsterinfo.currentmove = &parasite_move_drain;
@@ -468,7 +466,7 @@
 };
 mmove_t parasite_move_death = {FRAME_death101, FRAME_death107, parasite_frames_death, parasite_dead};
 
-void parasite_die (edict_t *self, edict_t *inflictor, edict_t *attacker, int damage, vec3_t point)
+void parasite_die (edict_t *self, edict_t */*inflictor*/, edict_t */*attacker*/, int damage, vec3_t /*point*/)
 {
 	int		n;
 
--- a/game/m_parasite.h
+++ b/game/m_parasite.h
@@ -17,8 +17,6 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-// G:\quake2\baseq2\models/monsters/parasite
-
 // This file generated by ModelGen - Do NOT Modify
 
 #define FRAME_break01           0
--- a/game/m_player.h
+++ b/game/m_player.h
@@ -17,8 +17,6 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-// G:\quake2\baseq2\models/player_x/frames
-
 // This file generated by qdata - Do NOT Modify
 
 #define FRAME_stand01         	0
--- a/game/m_rider.h
+++ b/game/m_rider.h
@@ -1,5 +1,3 @@
-// G:\quake2\baseq2\models/monsters/boss3/rider
-
 // This file generated by ModelGen - Do NOT Modify
 
 #define FRAME_stand201        	0
--- a/game/m_soldier.c
+++ b/game/m_soldier.c
@@ -17,14 +17,12 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-/*
-==============================================================================
-
-SOLDIER
-
-==============================================================================
-*/
-
+#define GAME_INCLUDE
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 #include "m_soldier.h"
 
@@ -43,7 +41,7 @@
 
 void soldier_idle (edict_t *self)
 {
-	if (random() > 0.8)
+	if (qrandom() > 0.8)
 		gi.sound (self, CHAN_VOICE, sound_idle, 1, ATTN_IDLE, 0);
 }
 
@@ -144,7 +142,7 @@
 };
 mmove_t soldier_move_stand3 = {FRAME_stand301, FRAME_stand339, soldier_frames_stand3, soldier_stand};
 
-#if 0
+/*
 mframe_t soldier_frames_stand4 [] =
 {
 	ai_stand, 0, NULL,
@@ -206,11 +204,11 @@
 	ai_stand, 0, NULL
 };
 mmove_t soldier_move_stand4 = {FRAME_stand401, FRAME_stand452, soldier_frames_stand4, NULL};
-#endif
+*/
 
 void soldier_stand (edict_t *self)
 {
-	if ((self->monsterinfo.currentmove == &soldier_move_stand3) || (random() < 0.8))
+	if ((self->monsterinfo.currentmove == &soldier_move_stand3) || (qrandom() < 0.8))
 		self->monsterinfo.currentmove = &soldier_move_stand1;
 	else
 		self->monsterinfo.currentmove = &soldier_move_stand3;
@@ -223,7 +221,7 @@
 
 void soldier_walk1_random (edict_t *self)
 {
-	if (random() > 0.1)
+	if (qrandom() > 0.1)
 		self->monsterinfo.nextframe = FRAME_walk101;
 }
 
@@ -282,7 +280,7 @@
 
 void soldier_walk (edict_t *self)
 {
-	if (random() < 0.5)
+	if (qrandom() < 0.5)
 		self->monsterinfo.currentmove = &soldier_move_walk1;
 	else
 		self->monsterinfo.currentmove = &soldier_move_walk2;
@@ -406,7 +404,7 @@
 mmove_t soldier_move_pain4 = {FRAME_pain401, FRAME_pain417, soldier_frames_pain4, soldier_run};
 
 
-void soldier_pain (edict_t *self, edict_t *other, float kick, int damage)
+void soldier_pain (edict_t *self, edict_t */*other*/, float /*kick*/, int /*damage*/)
 {
 	float	r;
 	int		n;
@@ -440,7 +438,7 @@
 	if (skill->value == 3)
 		return;		// no pain anims in nightmare
 
-	r = random();
+	r = qrandom();
 
 	if (r < 0.33)
 		self->monsterinfo.currentmove = &soldier_move_pain1;
@@ -538,7 +536,7 @@
 	if (self->enemy->health <= 0)
 		return;
 
-	if ( ((skill->value == 3) && (random() < 0.5)) || (range(self, self->enemy) == RANGE_MELEE) )
+	if ( ((skill->value == 3) && (qrandom() < 0.5)) || (range(self, self->enemy) == RANGE_MELEE) )
 		self->monsterinfo.nextframe = FRAME_attak102;
 	else
 		self->monsterinfo.nextframe = FRAME_attak110;
@@ -552,7 +550,7 @@
 	if (self->enemy->health <= 0)
 		return;
 
-	if ( ((skill->value == 3) && (random() < 0.5)) || (range(self, self->enemy) == RANGE_MELEE) )
+	if ( ((skill->value == 3) && (qrandom() < 0.5)) || (range(self, self->enemy) == RANGE_MELEE) )
 		self->monsterinfo.nextframe = FRAME_attak102;
 }
 
@@ -588,7 +586,7 @@
 	if (self->enemy->health <= 0)
 		return;
 
-	if ( ((skill->value == 3) && (random() < 0.5)) || (range(self, self->enemy) == RANGE_MELEE) )
+	if ( ((skill->value == 3) && (qrandom() < 0.5)) || (range(self, self->enemy) == RANGE_MELEE) )
 		self->monsterinfo.nextframe = FRAME_attak204;
 	else
 		self->monsterinfo.nextframe = FRAME_attak216;
@@ -602,7 +600,7 @@
 	if (self->enemy->health <= 0)
 		return;
 
-	if ( ((skill->value == 3) && (random() < 0.5)) || (range(self, self->enemy) == RANGE_MELEE) )
+	if ( ((skill->value == 3) && (qrandom() < 0.5)) || (range(self, self->enemy) == RANGE_MELEE) )
 		self->monsterinfo.nextframe = FRAME_attak204;
 }
 
@@ -685,7 +683,7 @@
 //	if (self->enemy->health <= 0)
 //		return;
 //
-//	if ( ((skill->value == 3) && (random() < 0.5)) || (range(self, self->enemy) == RANGE_MELEE) )
+//	if ( ((skill->value == 3) && (qrandom() < 0.5)) || (range(self, self->enemy) == RANGE_MELEE) )
 //		self->monsterinfo.nextframe = FRAME_attak402;
 }
 
@@ -700,7 +698,7 @@
 };
 mmove_t soldier_move_attack4 = {FRAME_attak401, FRAME_attak406, soldier_frames_attack4, soldier_run};
 
-#if 0
+/*
 // ATTACK5 (prone)
 
 void soldier_fire5 (edict_t *self)
@@ -713,7 +711,7 @@
 	if (self->enemy->health <= 0)
 		return;
 
-	if ( ((skill->value == 3) && (random() < 0.5)) || (range(self, self->enemy) == RANGE_MELEE) )
+	if ( ((skill->value == 3) && (qrandom() < 0.5)) || (range(self, self->enemy) == RANGE_MELEE) )
 		self->monsterinfo.nextframe = FRAME_attak505;
 }
 
@@ -729,7 +727,7 @@
 	ai_charge, 0, soldier_attack5_refire
 };
 mmove_t soldier_move_attack5 = {FRAME_attak501, FRAME_attak508, soldier_frames_attack5, soldier_run};
-#endif
+*/
 
 // ATTACK6 (run & shoot)
 
@@ -773,7 +771,7 @@
 {
 	if (self->s.skinnum < 4)
 	{
-		if (random() < 0.5)
+		if (qrandom() < 0.5)
 			self->monsterinfo.currentmove = &soldier_move_attack1;
 		else
 			self->monsterinfo.currentmove = &soldier_move_attack2;
@@ -789,9 +787,9 @@
 // SIGHT
 //
 
-void soldier_sight(edict_t *self, edict_t *other)
+void soldier_sight(edict_t *self, edict_t */*other*/)
 {
-	if (random() < 0.5)
+	if (qrandom() < 0.5)
 		gi.sound (self, CHAN_VOICE, sound_sight1, 1, ATTN_NORM, 0);
 	else
 		gi.sound (self, CHAN_VOICE, sound_sight2, 1, ATTN_NORM, 0);
@@ -798,7 +796,7 @@
 
 	if ((skill->value > 0) && (range(self, self->enemy) >= RANGE_MID))
 	{
-		if (random() > 0.5)
+		if (qrandom() > 0.5)
 			self->monsterinfo.currentmove = &soldier_move_attack6;
 	}
 }
@@ -829,7 +827,7 @@
 {
 	float	r;
 
-	r = random();
+	r = qrandom();
 	if (r > 0.25)
 		return;
 
@@ -843,7 +841,7 @@
 	}
 
 	self->monsterinfo.pausetime = level.time + eta + 0.3;
-	r = random();
+	r = qrandom();
 
 	if (skill->value == 1)
 	{
@@ -1141,7 +1139,7 @@
 };
 mmove_t soldier_move_death6 = {FRAME_death601, FRAME_death610, soldier_frames_death6, soldier_dead};
 
-void soldier_die (edict_t *self, edict_t *inflictor, edict_t *attacker, int damage, vec3_t point)
+void soldier_die (edict_t *self, edict_t */*inflictor*/, edict_t */*attacker*/, int damage, vec3_t point)
 {
 	int		n;
 
--- a/game/m_soldier.h
+++ b/game/m_soldier.h
@@ -17,8 +17,6 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-// G:\quake2\baseq2\models/monsters/soldier
-
 // This file generated by ModelGen - Do NOT Modify
 
 #define FRAME_attak101        	0
--- a/game/m_supertank.c
+++ b/game/m_supertank.c
@@ -17,14 +17,12 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-/*
-==============================================================================
-
-SUPERTANK
-
-==============================================================================
-*/
-
+#define GAME_INCLUDE
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 #include "m_supertank.h"
 
@@ -48,7 +46,7 @@
 
 void supertank_search (edict_t *self)
 {
-	if (random() < 0.5)
+	if (qrandom() < 0.5)
 		gi.sound (self, CHAN_VOICE, sound_search1, 1, ATTN_NORM, 0);
 	else
 		gi.sound (self, CHAN_VOICE, sound_search2, 1, ATTN_NORM, 0);
@@ -441,7 +439,7 @@
 void supertank_reattack1(edict_t *self)
 {
 	if (visible(self, self->enemy))
-		if (random() < 0.9)
+		if (qrandom() < 0.9)
 			self->monsterinfo.currentmove = &supertank_move_attack1;
 		else
 			self->monsterinfo.currentmove = &supertank_move_end_attack1;	
@@ -449,7 +447,7 @@
 		self->monsterinfo.currentmove = &supertank_move_end_attack1;
 }
 
-void supertank_pain (edict_t *self, edict_t *other, float kick, int damage)
+void supertank_pain (edict_t *self, edict_t */*other*/, float /*kick*/, int damage)
 {
 
 	if (self->health < (self->max_health / 2))
@@ -460,7 +458,7 @@
 
 	// Lessen the chance of him going into his pain frames
 	if (damage <=25)
-		if (random()<0.2)
+		if (qrandom()<0.2)
 			return;
 
 	// Don't go into pain if he's firing his rockets
@@ -557,7 +555,7 @@
 	VectorSubtract (self->enemy->s.origin, self->s.origin, vec);
 	range = VectorLength (vec);
 
-	//r = random();
+	//r = qrandom();
 
 	// Attack 1 == Chaingun
 	// Attack 2 == Rocket Launcher
@@ -568,7 +566,7 @@
 	}
 	else
 	{	// fire rockets more often at distance
-		if (random() < 0.3)
+		if (qrandom() < 0.3)
 			self->monsterinfo.currentmove = &supertank_move_attack1;
 		else
 			self->monsterinfo.currentmove = &supertank_move_attack2;
@@ -654,7 +652,7 @@
 }
 
 
-void supertank_die (edict_t *self, edict_t *inflictor, edict_t *attacker, int damage, vec3_t point)
+void supertank_die (edict_t *self, edict_t */*inflictor*/, edict_t */*attacker*/, int /*damage*/, vec3_t /*point*/)
 {
 	gi.sound (self, CHAN_VOICE, sound_death, 1, ATTN_NORM, 0);
 	self->deadflag = DEAD_DEAD;
--- a/game/m_supertank.h
+++ b/game/m_supertank.h
@@ -17,8 +17,6 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-// G:\quake2\baseq2\models/monsters/boss1/backup
-
 // This file generated by ModelGen - Do NOT Modify
 
 #define FRAME_attak1_1        	0
--- a/game/m_tank.c
+++ b/game/m_tank.c
@@ -17,14 +17,12 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-/*
-==============================================================================
-
-TANK
-
-==============================================================================
-*/
-
+#define GAME_INCLUDE
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 #include "m_tank.h"
 
@@ -46,7 +44,7 @@
 // misc
 //
 
-void tank_sight (edict_t *self, edict_t *other)
+void tank_sight (edict_t *self, edict_t */*other*/)
 {
 	gi.sound (self, CHAN_VOICE, sound_sight, 1, ATTN_NORM, 0);
 }
@@ -285,7 +283,7 @@
 mmove_t	tank_move_pain3 = {FRAME_pain301, FRAME_pain316, tank_frames_pain3, tank_run};
 
 
-void tank_pain (edict_t *self, edict_t *other, float kick, int damage)
+void tank_pain (edict_t *self, edict_t */*other*/, float /*kick*/, int damage)
 {
 	if (self->health < (self->max_health / 2))
 			self->s.skinnum |= 1;
@@ -297,7 +295,7 @@
 			return;
 
 	if (damage <= 30)
-		if (random() > 0.2)
+		if (qrandom() > 0.2)
 			return;
 	
 	// If hard or nightmare, don't go into pain while attacking
@@ -469,7 +467,7 @@
 	if (skill->value >= 2)
 		if (visible (self, self->enemy))
 			if (self->enemy->health > 0)
-				if (random() <= 0.6)
+				if (qrandom() <= 0.6)
 				{
 					self->monsterinfo.currentmove = &tank_move_reattack_blast;
 					return;
@@ -639,7 +637,7 @@
 	if ( skill->value >= 2 )
 		if (self->enemy->health > 0)
 			if (visible(self, self->enemy) )
-				if (random() <= 0.4)
+				if (qrandom() <= 0.4)
 				{
 					self->monsterinfo.currentmove = &tank_move_attack_fire_rocket;
 					return;
@@ -668,7 +666,7 @@
 	VectorSubtract (self->enemy->s.origin, self->s.origin, vec);
 	range = VectorLength (vec);
 
-	r = random();
+	r = qrandom();
 
 	if (range <= 125)
 	{
@@ -750,7 +748,7 @@
 };
 mmove_t	tank_move_death = {FRAME_death101, FRAME_death132, tank_frames_death1, tank_dead};
 
-void tank_die (edict_t *self, edict_t *inflictor, edict_t *attacker, int damage, vec3_t point)
+void tank_die (edict_t *self, edict_t */*inflictor*/, edict_t */*attacker*/, int damage, vec3_t /*point*/)
 {
 	int		n;
 
--- a/game/m_tank.h
+++ b/game/m_tank.h
@@ -17,8 +17,6 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-// G:\quake2\baseq2\models/monsters/tank
-
 // This file generated by qdata - Do NOT Modify
 
 #define FRAME_stand01         	0
--- a/game/p_client.c
+++ b/game/p_client.c
@@ -17,6 +17,12 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
+#define GAME_INCLUDE
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 #include "m_player.h"
 
@@ -53,7 +59,7 @@
 		VectorSubtract(self->s.origin, spot->s.origin, d);
 		if (VectorLength(d) < 384)
 		{
-			if ((!self->targetname) || Q_stricmp(self->targetname, spot->targetname) != 0)
+			if ((!self->targetname) || Q_strcasecmp(self->targetname, spot->targetname) != 0)
 			{
 //				gi.dprintf("FixCoopSpots changed %s at %s targetname from %s to %s\n", self->classname, vtos(self->s.origin), self->targetname, spot->targetname);
 				self->targetname = spot->targetname;
@@ -67,11 +73,11 @@
 // some maps don't have any coop spots at all, so we need to create them
 // where they should have been
 
-static void SP_CreateCoopSpots (edict_t *self)
+static void SP_CreateCoopSpots (edict_t */*self*/)
 {
 	edict_t	*spot;
 
-	if(Q_stricmp(level.mapname, "security") == 0)
+	if(Q_strcasecmp(level.mapname, "security") == 0)
 	{
 		spot = G_Spawn();
 		spot->classname = "info_player_coop";
@@ -109,7 +115,7 @@
 {
 	if (!coop->value)
 		return;
-	if(Q_stricmp(level.mapname, "security") == 0)
+	if(Q_strcasecmp(level.mapname, "security") == 0)
 	{
 		// invoke one of our gross, ugly, disgusting hacks
 		self->think = SP_CreateCoopSpots;
@@ -142,20 +148,20 @@
 		return;
 	}
 
-	if((Q_stricmp(level.mapname, "jail2") == 0)   ||
-	   (Q_stricmp(level.mapname, "jail4") == 0)   ||
-	   (Q_stricmp(level.mapname, "mine1") == 0)   ||
-	   (Q_stricmp(level.mapname, "mine2") == 0)   ||
-	   (Q_stricmp(level.mapname, "mine3") == 0)   ||
-	   (Q_stricmp(level.mapname, "mine4") == 0)   ||
-	   (Q_stricmp(level.mapname, "lab") == 0)     ||
-	   (Q_stricmp(level.mapname, "boss1") == 0)   ||
-	   (Q_stricmp(level.mapname, "fact3") == 0)   ||
-	   (Q_stricmp(level.mapname, "biggun") == 0)  ||
-	   (Q_stricmp(level.mapname, "space") == 0)   ||
-	   (Q_stricmp(level.mapname, "command") == 0) ||
-	   (Q_stricmp(level.mapname, "power2") == 0) ||
-	   (Q_stricmp(level.mapname, "strike") == 0))
+	if((Q_strcasecmp(level.mapname, "jail2") == 0)   ||
+	   (Q_strcasecmp(level.mapname, "jail4") == 0)   ||
+	   (Q_strcasecmp(level.mapname, "mine1") == 0)   ||
+	   (Q_strcasecmp(level.mapname, "mine2") == 0)   ||
+	   (Q_strcasecmp(level.mapname, "mine3") == 0)   ||
+	   (Q_strcasecmp(level.mapname, "mine4") == 0)   ||
+	   (Q_strcasecmp(level.mapname, "lab") == 0)     ||
+	   (Q_strcasecmp(level.mapname, "boss1") == 0)   ||
+	   (Q_strcasecmp(level.mapname, "fact3") == 0)   ||
+	   (Q_strcasecmp(level.mapname, "biggun") == 0)  ||
+	   (Q_strcasecmp(level.mapname, "space") == 0)   ||
+	   (Q_strcasecmp(level.mapname, "command") == 0) ||
+	   (Q_strcasecmp(level.mapname, "power2") == 0) ||
+	   (Q_strcasecmp(level.mapname, "strike") == 0))
 	{
 		// invoke one of our gross, ugly, disgusting hacks
 		self->think = SP_FixCoopSpots;
@@ -168,7 +174,7 @@
 The deathmatch intermission point will be at one of these
 Use 'angles' instead of 'angle', so you can set pitch or roll as well as yaw.  'pitch yaw roll'
 */
-void SP_info_player_intermission(void)
+void SP_info_player_intermission (edict_t */*ent*/)
 {
 }
 
@@ -176,7 +182,7 @@
 //=======================================================================
 
 
-void player_pain (edict_t *self, edict_t *other, float kick, int damage)
+void player_pain (edict_t */*self*/, edict_t */*other*/, float /*kick*/, int /*damage*/)
 {
 	// player pain is handled at the end of the frame in P_DamageFeedback
 }
@@ -208,7 +214,7 @@
 	return false;
 }
 
-void ClientObituary (edict_t *self, edict_t *inflictor, edict_t *attacker)
+void ClientObituary (edict_t *self, edict_t */*inflictor*/, edict_t *attacker)
 {
 	int			mod;
 	char		*message;
@@ -498,7 +504,7 @@
 player_die
 ==================
 */
-void player_die (edict_t *self, edict_t *inflictor, edict_t *attacker, int damage, vec3_t point)
+void player_die (edict_t *self, edict_t *inflictor, edict_t *attacker, int damage, vec3_t /*point*/)
 {
 	int		n;
 
@@ -840,8 +846,6 @@
 	if (!index)
 		return NULL;
 
-	spot = NULL;
-
 	// assume there are four coop spots at each spawnpoint
 	while (1)
 	{
@@ -852,7 +856,7 @@
 		target = spot->targetname;
 		if (!target)
 			target = "";
-		if ( Q_stricmp(game.spawnpoint, target) == 0 )
+		if ( Q_strcasecmp(game.spawnpoint, target) == 0 )
 		{	// this is a coop spawn point for one of the clients here
 			index--;
 			if (!index)
@@ -859,9 +863,6 @@
 				return spot;		// this is it
 		}
 	}
-
-
-	return spot;
 }
 
 
@@ -892,7 +893,7 @@
 			if (!game.spawnpoint[0] || !spot->targetname)
 				continue;
 
-			if (Q_stricmp(game.spawnpoint, spot->targetname) == 0)
+			if (Q_strcasecmp(game.spawnpoint, spot->targetname) == 0)
 				break;
 		}
 
@@ -928,7 +929,7 @@
 	}
 }
 
-void body_die (edict_t *self, edict_t *inflictor, edict_t *attacker, int damage, vec3_t point)
+void body_die (edict_t *self, edict_t */*inflictor*/, edict_t */*attacker*/, int damage, vec3_t /*point*/)
 {
 	int	n;
 
--- a/game/p_hud.c
+++ b/game/p_hud.c
@@ -17,6 +17,12 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
+#define GAME_INCLUDE
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 
 
@@ -170,7 +176,6 @@
 	int		sorted[MAX_CLIENTS];
 	int		sortedscores[MAX_CLIENTS];
 	int		score, total;
-	int		picnum;
 	int		x, y;
 	gclient_t	*cl;
 	edict_t		*cl_ent;
@@ -213,7 +218,7 @@
 		cl = &game.clients[sorted[i]];
 		cl_ent = g_edicts + 1 + sorted[i];
 
-		picnum = gi.imageindex ("i_fixme");
+		gi.imageindex ("i_fixme");	/* int picnum = */
 		x = (i>=6) ? 160 : 0;
 		y = 32 + 32 * (i%6);
 
@@ -377,7 +382,7 @@
 void G_SetStats (edict_t *ent)
 {
 	gitem_t		*item;
-	int			index, cells;
+	int			index, cells = 0;
 	int			power_armor_type;
 
 	//
--- a/game/p_trail.c
+++ b/game/p_trail.c
@@ -17,6 +17,12 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
+#define GAME_INCLUDE
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 
 
--- a/game/p_view.c
+++ b/game/p_view.c
@@ -17,7 +17,12 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-
+#define GAME_INCLUDE
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 #include "m_player.h"
 
@@ -39,7 +44,7 @@
 
 ===============
 */
-float SV_CalcRoll (vec3_t angles, vec3_t velocity)
+float SV_CalcRoll (vec3_t /*angles*/, vec3_t velocity)
 {
 	float	sign;
 	float	side;
--- a/game/p_weapon.c
+++ b/game/p_weapon.c
@@ -17,8 +17,12 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-// g_weapon.c
-
+#define GAME_INCLUDE
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 #include "g_local.h"
 #include "m_player.h"
 
@@ -764,7 +768,7 @@
 	float	damage_radius;
 	int		radius_damage;
 
-	damage = 100 + (int)(random() * 20.0);
+	damage = 100 + (int)(qrandom() * 20.0);
 	radius_damage = 120;
 	damage_radius = 120;
 	if (is_quad)
@@ -1026,12 +1030,12 @@
 	ent->client->anim_priority = ANIM_ATTACK;
 	if (ent->client->ps.pmove.pm_flags & PMF_DUCKED)
 	{
-		ent->s.frame = FRAME_crattak1 - (int) (random()+0.25);
+		ent->s.frame = FRAME_crattak1 - (int) (qrandom()+0.25);
 		ent->client->anim_end = FRAME_crattak9;
 	}
 	else
 	{
-		ent->s.frame = FRAME_attack1 - (int) (random()+0.25);
+		ent->s.frame = FRAME_attack1 - (int) (qrandom()+0.25);
 		ent->client->anim_end = FRAME_attack8;
 	}
 }
--- a/game/q_shared.c
+++ b/game/q_shared.c
@@ -17,7 +17,12 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-#include "../q_shared.h"
+#define GAME_INCLUDE
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 
 #define DEG2RAD( a ) ( a * M_PI ) / 180.0F
 
@@ -250,30 +255,16 @@
 
 float Q_fabs (float f)
 {
-#if 0
+/*
 	if (f >= 0)
 		return f;
 	return -f;
-#else
+*/
 	int tmp = * ( int * ) &f;
 	tmp &= 0x7FFFFFFF;
 	return * ( float * ) &tmp;
-#endif
 }
 
-#if defined _M_IX86 && !defined C_ONLY
-#pragma warning (disable:4035)
-__declspec( naked ) long Q_ftol( float f )
-{
-	static int tmp;
-	__asm fld dword ptr [esp+4]
-	__asm fistp tmp
-	__asm mov eax, tmp
-	__asm ret
-}
-#pragma warning (default:4035)
-#endif
-
 /*
 ===============
 LerpAngle
@@ -292,12 +283,12 @@
 
 float	anglemod(float a)
 {
-#if 0
+/*
 	if (a >= 0)
 		a -= 360*(int)(a/360);
 	else
 		a += 360*( 1 + (int)(-a/360) );
-#endif
+*/
 	a = (360.0/65536) * ((int)(a*(65536/360.0)) & 65535);
 	return a;
 }
@@ -345,7 +336,6 @@
 Returns 1, 2, or 1 + 2
 ==================
 */
-#if !id386 || defined __linux__ 
 int BoxOnPlaneSide (vec3_t emins, vec3_t emaxs, struct cplane_s *p)
 {
 	float	dist1, dist2;
@@ -412,241 +402,7 @@
 
 	return sides;
 }
-#else
-#pragma warning( disable: 4035 )
 
-__declspec( naked ) int BoxOnPlaneSide (vec3_t emins, vec3_t emaxs, struct cplane_s *p)
-{
-	static int bops_initialized;
-	static int Ljmptab[8];
-
-	__asm {
-
-		push ebx
-			
-		cmp bops_initialized, 1
-		je  initialized
-		mov bops_initialized, 1
-		
-		mov Ljmptab[0*4], offset Lcase0
-		mov Ljmptab[1*4], offset Lcase1
-		mov Ljmptab[2*4], offset Lcase2
-		mov Ljmptab[3*4], offset Lcase3
-		mov Ljmptab[4*4], offset Lcase4
-		mov Ljmptab[5*4], offset Lcase5
-		mov Ljmptab[6*4], offset Lcase6
-		mov Ljmptab[7*4], offset Lcase7
-			
-initialized:
-
-		mov edx,ds:dword ptr[4+12+esp]
-		mov ecx,ds:dword ptr[4+4+esp]
-		xor eax,eax
-		mov ebx,ds:dword ptr[4+8+esp]
-		mov al,ds:byte ptr[17+edx]
-		cmp al,8
-		jge Lerror
-		fld ds:dword ptr[0+edx]
-		fld st(0)
-		jmp dword ptr[Ljmptab+eax*4]
-Lcase0:
-		fmul ds:dword ptr[ebx]
-		fld ds:dword ptr[0+4+edx]
-		fxch st(2)
-		fmul ds:dword ptr[ecx]
-		fxch st(2)
-		fld st(0)
-		fmul ds:dword ptr[4+ebx]
-		fld ds:dword ptr[0+8+edx]
-		fxch st(2)
-		fmul ds:dword ptr[4+ecx]
-		fxch st(2)
-		fld st(0)
-		fmul ds:dword ptr[8+ebx]
-		fxch st(5)
-		faddp st(3),st(0)
-		fmul ds:dword ptr[8+ecx]
-		fxch st(1)
-		faddp st(3),st(0)
-		fxch st(3)
-		faddp st(2),st(0)
-		jmp LSetSides
-Lcase1:
-		fmul ds:dword ptr[ecx]
-		fld ds:dword ptr[0+4+edx]
-		fxch st(2)
-		fmul ds:dword ptr[ebx]
-		fxch st(2)
-		fld st(0)
-		fmul ds:dword ptr[4+ebx]
-		fld ds:dword ptr[0+8+edx]
-		fxch st(2)
-		fmul ds:dword ptr[4+ecx]
-		fxch st(2)
-		fld st(0)
-		fmul ds:dword ptr[8+ebx]
-		fxch st(5)
-		faddp st(3),st(0)
-		fmul ds:dword ptr[8+ecx]
-		fxch st(1)
-		faddp st(3),st(0)
-		fxch st(3)
-		faddp st(2),st(0)
-		jmp LSetSides
-Lcase2:
-		fmul ds:dword ptr[ebx]
-		fld ds:dword ptr[0+4+edx]
-		fxch st(2)
-		fmul ds:dword ptr[ecx]
-		fxch st(2)
-		fld st(0)
-		fmul ds:dword ptr[4+ecx]
-		fld ds:dword ptr[0+8+edx]
-		fxch st(2)
-		fmul ds:dword ptr[4+ebx]
-		fxch st(2)
-		fld st(0)
-		fmul ds:dword ptr[8+ebx]
-		fxch st(5)
-		faddp st(3),st(0)
-		fmul ds:dword ptr[8+ecx]
-		fxch st(1)
-		faddp st(3),st(0)
-		fxch st(3)
-		faddp st(2),st(0)
-		jmp LSetSides
-Lcase3:
-		fmul ds:dword ptr[ecx]
-		fld ds:dword ptr[0+4+edx]
-		fxch st(2)
-		fmul ds:dword ptr[ebx]
-		fxch st(2)
-		fld st(0)
-		fmul ds:dword ptr[4+ecx]
-		fld ds:dword ptr[0+8+edx]
-		fxch st(2)
-		fmul ds:dword ptr[4+ebx]
-		fxch st(2)
-		fld st(0)
-		fmul ds:dword ptr[8+ebx]
-		fxch st(5)
-		faddp st(3),st(0)
-		fmul ds:dword ptr[8+ecx]
-		fxch st(1)
-		faddp st(3),st(0)
-		fxch st(3)
-		faddp st(2),st(0)
-		jmp LSetSides
-Lcase4:
-		fmul ds:dword ptr[ebx]
-		fld ds:dword ptr[0+4+edx]
-		fxch st(2)
-		fmul ds:dword ptr[ecx]
-		fxch st(2)
-		fld st(0)
-		fmul ds:dword ptr[4+ebx]
-		fld ds:dword ptr[0+8+edx]
-		fxch st(2)
-		fmul ds:dword ptr[4+ecx]
-		fxch st(2)
-		fld st(0)
-		fmul ds:dword ptr[8+ecx]
-		fxch st(5)
-		faddp st(3),st(0)
-		fmul ds:dword ptr[8+ebx]
-		fxch st(1)
-		faddp st(3),st(0)
-		fxch st(3)
-		faddp st(2),st(0)
-		jmp LSetSides
-Lcase5:
-		fmul ds:dword ptr[ecx]
-		fld ds:dword ptr[0+4+edx]
-		fxch st(2)
-		fmul ds:dword ptr[ebx]
-		fxch st(2)
-		fld st(0)
-		fmul ds:dword ptr[4+ebx]
-		fld ds:dword ptr[0+8+edx]
-		fxch st(2)
-		fmul ds:dword ptr[4+ecx]
-		fxch st(2)
-		fld st(0)
-		fmul ds:dword ptr[8+ecx]
-		fxch st(5)
-		faddp st(3),st(0)
-		fmul ds:dword ptr[8+ebx]
-		fxch st(1)
-		faddp st(3),st(0)
-		fxch st(3)
-		faddp st(2),st(0)
-		jmp LSetSides
-Lcase6:
-		fmul ds:dword ptr[ebx]
-		fld ds:dword ptr[0+4+edx]
-		fxch st(2)
-		fmul ds:dword ptr[ecx]
-		fxch st(2)
-		fld st(0)
-		fmul ds:dword ptr[4+ecx]
-		fld ds:dword ptr[0+8+edx]
-		fxch st(2)
-		fmul ds:dword ptr[4+ebx]
-		fxch st(2)
-		fld st(0)
-		fmul ds:dword ptr[8+ecx]
-		fxch st(5)
-		faddp st(3),st(0)
-		fmul ds:dword ptr[8+ebx]
-		fxch st(1)
-		faddp st(3),st(0)
-		fxch st(3)
-		faddp st(2),st(0)
-		jmp LSetSides
-Lcase7:
-		fmul ds:dword ptr[ecx]
-		fld ds:dword ptr[0+4+edx]
-		fxch st(2)
-		fmul ds:dword ptr[ebx]
-		fxch st(2)
-		fld st(0)
-		fmul ds:dword ptr[4+ecx]
-		fld ds:dword ptr[0+8+edx]
-		fxch st(2)
-		fmul ds:dword ptr[4+ebx]
-		fxch st(2)
-		fld st(0)
-		fmul ds:dword ptr[8+ecx]
-		fxch st(5)
-		faddp st(3),st(0)
-		fmul ds:dword ptr[8+ebx]
-		fxch st(1)
-		faddp st(3),st(0)
-		fxch st(3)
-		faddp st(2),st(0)
-LSetSides:
-		faddp st(2),st(0)
-		fcomp ds:dword ptr[12+edx]
-		xor ecx,ecx
-		fnstsw ax
-		fcomp ds:dword ptr[12+edx]
-		and ah,1
-		xor ah,1
-		add cl,ah
-		fnstsw ax
-		and ah,1
-		add ah,ah
-		add cl,ah
-		pop ebx
-		mov eax,ecx
-		ret
-Lerror:
-		int 3
-	}
-}
-#pragma warning( default: 4035 )
-#endif
-
 void ClearBounds (vec3_t mins, vec3_t maxs)
 {
 	mins[0] = mins[1] = mins[2] = 99999;
@@ -1175,16 +931,6 @@
 
 ============================================================================
 */
-
-// FIXME: replace all Q_stricmp with Q_strcasecmp
-int Q_stricmp (char *s1, char *s2)
-{
-#if defined(WIN32)
-	return _stricmp (s1, s2);
-#else
-	return strcasecmp (s1, s2);
-#endif
-}
 
 
 int Q_strncasecmp (char *s1, char *s2, int n)
--- a/mkfile
+++ b/mkfile
@@ -52,12 +52,12 @@
 	$SVDIR/sv_user.$O\
 	$SVDIR/sv_world.$O\
 	$P9DIR/cd_9.$O\
+	$P9DIR/in_9.$O\
 	$P9DIR/q_sh9.$O\
 	$P9DIR/vid_menu.$O\
 	$P9DIR/vid_so.$O\
 	$P9DIR/snd_9.$O\
 	$P9DIR/sys_9.$O\
-	$P9DIR/glob.$O\
 	$P9DIR/net_udp.$O\
 
 CLHFILES=\
@@ -261,13 +261,11 @@
 	$SRDIR/r_surf.$O\
 	$GMDIR/q_shared.$O\
 	$P9DIR/q_sh9.$O\
-	$P9DIR/glob.$O\
 	$P9DIR/rw_9.$O\
 
 SRHFILES=\
 	$SRDIR/adivtab.h\
 	$SRDIR/r_local.h\
-	$SRDIR/r_model.h\
 	$SRDIR/rand1k.h\
 
 CMHFILES=\
@@ -275,12 +273,11 @@
 	$CMDIR/qcommon.h\
 	$CMDIR/qfiles.h\
 
-# only build and link needed modules for main game
-# *ofiles: ofiles needed for each module
-# *hfiles: hfiles in each module directory...
 OFILES= $CLOFILES $GMOFILES $SROFILES
 HFILES= $CLHFILES $GMHFILES $SRHFILES $CMHFILES \
 	anorms.h\
+	dat.h\
+	fns.h\
 	q_shared.h\
 
 </sys/src/cmd/mkone
--- a/plan9/cd_9.c
+++ b/plan9/cd_9.c
@@ -1,72 +1,64 @@
-// Quake is a trademark of Id Software, Inc., (c) 1996 Id Software, Inc. All
-// rights reserved.
-
+#include <u.h>
+#include <libc.h>
 #include <stdio.h>
-#include <unistd.h>
-#include <stdlib.h>
-#include <sys/ioctl.h>
-#include <sys/file.h>
-#include <sys/types.h>
-#include <fcntl.h>
-#include <string.h>
-#include <time.h>
-#include <errno.h>
+#include "../dat.h"
+#include "../fns.h"
 
-#include <linux/cdrom.h>
+qboolean cdValid = false;
+qboolean playing = false;
+qboolean wasPlaying = false;
+qboolean initialized = false;
+qboolean enabled = true;
+qboolean playLooping = false;
+float cdvolume;
+byte remap[100];
+byte playTrack;
+byte maxTrack;
+int cdfile = -1;
 
-#include "../client/client.h"
-
-static qboolean cdValid = false;
-static qboolean	playing = false;
-static qboolean	wasPlaying = false;
-static qboolean	initialized = false;
-static qboolean	enabled = true;
-static qboolean playLooping = false;
-static float	cdvolume;
-static byte 	remap[100];
-static byte		playTrack;
-static byte		maxTrack;
-
-static int cdfile = -1;
-
-//static char cd_dev[64] = "/dev/cdrom";
-
 cvar_t	*cd_volume;
 cvar_t *cd_nocd;
 cvar_t *cd_dev;
 
-void CDAudio_Pause(void);
 
-static void CDAudio_Eject(void)
+void CDAudio_Eject(void)
 {
 	if (cdfile == -1 || !enabled)
-		return; // no cd init'd
+		return;
 
+	Com_DPrintf("CDAudio_Eject: PORTME\n");
+	/*
 	if ( ioctl(cdfile, CDROMEJECT) == -1 ) 
 		Com_DPrintf("ioctl cdromeject failed\n");
+	*/
 }
 
-
-static void CDAudio_CloseDoor(void)
+void CDAudio_CloseDoor(void)
 {
 	if (cdfile == -1 || !enabled)
-		return; // no cd init'd
+		return;
 
+	Com_DPrintf("CDAudio_CloseDoor: PORTME\n");
+	/*
 	if ( ioctl(cdfile, CDROMCLOSETRAY) == -1 ) 
 		Com_DPrintf("ioctl cdromclosetray failed\n");
+	*/
 }
 
-static int CDAudio_GetAudioDiskInfo(void)
+int CDAudio_GetAudioDiskInfo(void)
 {
-	struct cdrom_tochdr tochdr;
-
 	cdValid = false;
+	Com_DPrintf("CDAudio_GetAudioDiskInfo: PORTME\n");
+	return -1;
 
+	/*
+	struct cdrom_tochdr tochdr;
+
 	if ( ioctl(cdfile, CDROMREADTOCHDR, &tochdr) == -1 ) 
-    {
-      Com_DPrintf("ioctl cdromreadtochdr failed\n");
-	  return -1;
-    }
+	{
+		Com_DPrintf("ioctl cdromreadtochdr failed\n");
+		return -1;
+	}
 
 	if (tochdr.cdth_trk0 < 1)
 	{
@@ -76,19 +68,32 @@
 
 	cdValid = true;
 	maxTrack = tochdr.cdth_trk1;
-
 	return 0;
+	*/
 }
 
+void CDAudio_Pause(void)
+{
+	if (cdfile == -1 || !enabled)
+		return;
+	if (!playing)
+		return;
 
+	Com_DPrintf("CDAudio_GetAudioDiskInfo: PORTME\n");
+
+	/*
+	if ( ioctl(cdfile, CDROMPAUSE) == -1 ) 
+		Com_DPrintf("ioctl cdrompause failed\n");
+
+	wasPlaying = playing;
+	playing = false;
+	*/
+}
+
 void CDAudio_Play(int track, qboolean looping)
 {
-	struct cdrom_tocentry entry;
-	struct cdrom_ti ti;
-
 	if (cdfile == -1 || !enabled)
 		return;
-	
 	if (!cdValid)
 	{
 		CDAudio_GetAudioDiskInfo();
@@ -97,7 +102,6 @@
 	}
 
 	track = remap[track];
-
 	if (track < 1 || track > maxTrack)
 	{
 		Com_DPrintf("CDAudio: Bad track number %u.\n", track);
@@ -104,10 +108,17 @@
 		return;
 	}
 
+	USED(looping);
+	Com_DPrintf("CDAudio_Play: PORTME\n");
+
+	/*
+	struct cdrom_tocentry entry;
+	struct cdrom_ti ti;
+
 	// don't try to play a non-audio track
 	entry.cdte_track = track;
 	entry.cdte_format = CDROM_MSF;
-    if ( ioctl(cdfile, CDROMREADTOCENTRY, &entry) == -1 )
+	if ( ioctl(cdfile, CDROMREADTOCENTRY, &entry) == -1 )
 	{
 		Com_DPrintf("ioctl cdromreadtocentry failed\n");
 		return;
@@ -129,13 +140,11 @@
 	ti.cdti_trk1 = track;
 	ti.cdti_ind0 = 1;
 	ti.cdti_ind1 = 99;
-
 	if ( ioctl(cdfile, CDROMPLAYTRKIND, &ti) == -1 ) 
-    {
+	{
 		Com_DPrintf("ioctl cdromplaytrkind failed\n");
 		return;
-    }
-
+	}
 	if ( ioctl(cdfile, CDROMRESUME) == -1 ) 
 		Com_DPrintf("ioctl cdromresume failed\n");
 
@@ -145,6 +154,7 @@
 
 	if (cd_volume->value == 0.0)
 		CDAudio_Pause ();
+	*/
 }
 
 
@@ -152,54 +162,42 @@
 {
 	if (cdfile == -1 || !enabled)
 		return;
-	
 	if (!playing)
 		return;
 
+	Com_DPrintf("CDAudio_Stop: PORTME\n");
+
+	/*
 	if ( ioctl(cdfile, CDROMSTOP) == -1 )
 		Com_DPrintf("ioctl cdromstop failed (%d)\n", errno);
 
 	wasPlaying = false;
 	playing = false;
+	*/
 }
 
-void CDAudio_Pause(void)
-{
-	if (cdfile == -1 || !enabled)
-		return;
-
-	if (!playing)
-		return;
-
-	if ( ioctl(cdfile, CDROMPAUSE) == -1 ) 
-		Com_DPrintf("ioctl cdrompause failed\n");
-
-	wasPlaying = playing;
-	playing = false;
-}
-
-
 void CDAudio_Resume(void)
 {
 	if (cdfile == -1 || !enabled)
 		return;
-	
 	if (!cdValid)
 		return;
-
 	if (!wasPlaying)
 		return;
-	
+
+	Com_DPrintf("CDAudio_Stop: PORTME\n");
+
+	/*
 	if ( ioctl(cdfile, CDROMRESUME) == -1 ) 
 		Com_DPrintf("ioctl cdromresume failed\n");
 	playing = true;
+	*/
 }
 
 static void CD_f (void)
 {
 	char	*command;
-	int		ret;
-	int		n;
+	int n, ret;
 
 	if (Cmd_Argc() < 2)
 		return;
@@ -315,12 +313,8 @@
 
 void CDAudio_Update(void)
 {
-	struct cdrom_subchnl subchnl;
-	static time_t lastchk;
-
 	if (cdfile == -1 || !enabled)
 		return;
-
 	if (cd_volume && cd_volume->value != cdvolume)
 	{
 		if (cdvolume)
@@ -337,6 +331,12 @@
 		}
 	}
 
+	Com_DPrintf("CDAudio_Stop: PORTME\n");
+
+	/*
+	struct cdrom_subchnl subchnl;
+	static time_t lastchk;
+
 	if (playing && lastchk < time(NULL)) {
 		lastchk = time(NULL) + 2; //two seconds between chks
 		subchnl.cdsc_format = CDROM_MSF;
@@ -352,13 +352,13 @@
 				CDAudio_Play(playTrack, true);
 		}
 	}
+	*/
 }
 
 int CDAudio_Init(void)
 {
 	int i;
-	cvar_t			*cv;
-	extern uid_t saved_euid;
+	cvar_t	*cv;
 
 	cv = Cvar_Get ("nocdaudio", "0", CVAR_NOSET);
 	if (cv->value)
@@ -372,14 +372,9 @@
 
 	cd_dev = Cvar_Get("cd_dev", "/dev/cdrom", CVAR_ARCHIVE);
 
-	seteuid(saved_euid);
-
-	cdfile = open(cd_dev->string, O_RDONLY);
-
-	seteuid(getuid());
-
-	if (cdfile == -1) {
-		Com_Printf("CDAudio_Init: open of \"%s\" failed (%i)\n", cd_dev->string, errno);
+	if((cdfile = open(cd_dev->string, OREAD)) < 0){
+		fprint(2, "CDAudio_Init: %r\n");
+		Com_Printf("CDAudio_Init: failed to open \"%s\"\n", cd_dev);
 		cdfile = -1;
 		return -1;
 	}
--- a/plan9/glob.c
+++ /dev/null
@@ -1,164 +1,0 @@
-
-#include <stdio.h>
-#include "../linux/glob.h"
-
-/* Like glob_match, but match PATTERN against any final segment of TEXT.  */
-static int glob_match_after_star(char *pattern, char *text)
-{
-	register char *p = pattern, *t = text;
-	register char c, c1;
-
-	while ((c = *p++) == '?' || c == '*')
-		if (c == '?' && *t++ == '\0')
-			return 0;
-
-	if (c == '\0')
-		return 1;
-
-	if (c == '\\')
-		c1 = *p;
-	else
-		c1 = c;
-
-	while (1) {
-		if ((c == '[' || *t == c1) && glob_match(p - 1, t))
-			return 1;
-		if (*t++ == '\0')
-			return 0;
-	}
-}
-
-/* Return nonzero if PATTERN has any special globbing chars in it.  */
-static int glob_pattern_p(char *pattern)
-{
-	register char *p = pattern;
-	register char c;
-	int open = 0;
-
-	while ((c = *p++) != '\0')
-		switch (c) {
-		case '?':
-		case '*':
-			return 1;
-
-		case '[':		/* Only accept an open brace if there is a close */
-			open++;		/* brace to match it.  Bracket expressions must be */
-			continue;	/* complete, according to Posix.2 */
-		case ']':
-			if (open)
-				return 1;
-			continue;
-
-		case '\\':
-			if (*p++ == '\0')
-				return 0;
-		}
-
-	return 0;
-}
-
-/* Match the pattern PATTERN against the string TEXT;
-   return 1 if it matches, 0 otherwise.
-
-   A match means the entire string TEXT is used up in matching.
-
-   In the pattern string, `*' matches any sequence of characters,
-   `?' matches any character, [SET] matches any character in the specified set,
-   [!SET] matches any character not in the specified set.
-
-   A set is composed of characters or ranges; a range looks like
-   character hyphen character (as in 0-9 or A-Z).
-   [0-9a-zA-Z_] is the set of characters allowed in C identifiers.
-   Any other character in the pattern must be matched exactly.
-
-   To suppress the special syntactic significance of any of `[]*?!-\',
-   and match the character exactly, precede it with a `\'.
-*/
-
-int glob_match(char *pattern, char *text)
-{
-	register char *p = pattern, *t = text;
-	register char c;
-
-	while ((c = *p++) != '\0')
-		switch (c) {
-		case '?':
-			if (*t == '\0')
-				return 0;
-			else
-				++t;
-			break;
-
-		case '\\':
-			if (*p++ != *t++)
-				return 0;
-			break;
-
-		case '*':
-			return glob_match_after_star(p, t);
-
-		case '[':
-			{
-				register char c1 = *t++;
-				int invert;
-
-				if (!c1)
-					return (0);
-
-				invert = ((*p == '!') || (*p == '^'));
-				if (invert)
-					p++;
-
-				c = *p++;
-				while (1) {
-					register char cstart = c, cend = c;
-
-					if (c == '\\') {
-						cstart = *p++;
-						cend = cstart;
-					}
-					if (c == '\0')
-						return 0;
-
-					c = *p++;
-					if (c == '-' && *p != ']') {
-						cend = *p++;
-						if (cend == '\\')
-							cend = *p++;
-						if (cend == '\0')
-							return 0;
-						c = *p++;
-					}
-					if (c1 >= cstart && c1 <= cend)
-						goto match;
-					if (c == ']')
-						break;
-				}
-				if (!invert)
-					return 0;
-				break;
-
-			  match:
-				/* Skip the rest of the [...] construct that already matched.  */
-				while (c != ']') {
-					if (c == '\0')
-						return 0;
-					c = *p++;
-					if (c == '\0')
-						return 0;
-					else if (c == '\\')
-						++p;
-				}
-				if (invert)
-					return 0;
-				break;
-			}
-
-		default:
-			if (c != *t++)
-				return 0;
-		}
-
-	return *t == '\0';
-}
-
--- a/plan9/glob.h
+++ /dev/null
@@ -1,1 +1,0 @@
-int glob_match(char *pattern, char *text);
--- a/plan9/in_9.c
+++ b/plan9/in_9.c
@@ -1,29 +1,340 @@
-// in_null.c -- for systems without a mouse
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include <draw.h>
+#include <thread.h>
+#include <mouse.h>
+#include <keyboard.h>
+#include "../dat.h"
+#include "../fns.h"
 
-#include "../client/client.h"
-
 cvar_t	*in_mouse;
 cvar_t	*in_joystick;
+cvar_t	*m_filter;
+cvar_t	*m_windowed;
+cvar_t	*sensitivity;
+cvar_t	*lookstrafe;
+cvar_t	*m_side;
+cvar_t	*m_yaw;
+cvar_t	*m_pitch;
+cvar_t	*m_forward;
+cvar_t	*freelook;
 
-void IN_Init (void)
+qboolean mouseon;
+qboolean mlooking;
+int mx, my, mbtn, dx, dy, oldmx, oldmy, oldmbtn;
+int oldmwin;
+
+typedef struct Kev Kev;
+struct Kev{
+	int key;
+	int down;
+};
+enum{
+	Nbuf	= 64
+};
+Channel *kchan;
+int ktid = -1, mtid = -1;
+
+/* rw_9.c */
+extern int resized;
+extern Point center;
+extern refimport_t ri;
+
+void IN_Grabm(int on)
 {
-    in_mouse = Cvar_Get ("in_mouse", "1", CVAR_ARCHIVE);
-    in_joystick = Cvar_Get ("in_joystick", "0", CVAR_ARCHIVE);
+	static char nocurs[2*4+2*2*16];
+	static int fd = -1;
+
+	if(mouseon == on)
+		return;
+	if(mouseon = on){
+		if((fd = open("/dev/cursor", ORDWR|OCEXEC)) < 0){
+			sysfatal("IN_Grabm:open: %r\n");
+			return;
+		}
+		write(fd, nocurs, sizeof nocurs);
+	}else if(fd >= 0){
+		close(fd);
+		fd = -1;
+	}
 }
 
-void IN_Shutdown (void)
+void IN_Commands (void)
 {
+	int i;
+
+	if(!mouseon)
+		return;
+	for(i = 0; i < 3; i++){
+		if(mbtn & 1<<i && ~oldmbtn & 1<<i)
+			Key_Event(K_MOUSE1+i, true, Sys_Milliseconds());
+		if(~mbtn & 1<<i && oldmbtn & 1<<i)
+			Key_Event(K_MOUSE1+i, false, Sys_Milliseconds());
+	}
+	oldmbtn = mbtn;
 }
 
-void IN_Commands (void)
+void KBD_Update (void)
 {
+	Kev ev;
+	int r;
+
+	if(oldmwin != m_windowed->value){
+		oldmwin = m_windowed->value;
+		if(!m_windowed->value)
+			IN_Grabm(0);
+		else
+			IN_Grabm(1);
+	}
+	while((r = nbrecv(kchan, &ev)) > 0)
+		Key_Event(ev.key, ev.down, Sys_Milliseconds());
+	if(r < 0)
+		sysfatal("KBD_Update:nbrecv: %r\n");
 }
 
 void IN_Move (usercmd_t *cmd)
 {
+	if(!mouseon)
+		return;
+
+	if(m_filter->value){
+		mx = (mx + oldmx) * 0.5;
+		my = (my + oldmy) * 0.5;
+	}else{
+		mx = dx;
+		my = dy;
+	}
+	oldmx = dx;
+	oldmy = dy;
+	if(!mx && !my)
+		return;
+	mx *= sensitivity->value;
+	my *= sensitivity->value;
+	dx = dy = 0;
+
+	/* add mouse x/y movement to cmd */
+	if(in_strafe.state & 1 || lookstrafe->value && mlooking)
+		cmd->sidemove += m_side->value * mx;
+	else
+		cl.viewangles[YAW] -= m_yaw->value * mx;
+	if((mlooking || freelook->value) && ~in_strafe.state & 1)
+		cl.viewangles[PITCH] += m_pitch->value * my;
+	else
+		cmd->forwardmove -= m_forward->value * my;
 }
 
-void IN_Activate (qboolean active)
+/* called on focus/unfocus in win32 */
+void IN_Activate (qboolean)
 {
 }
 
+/* called every frame even if not generating commands */
+void IN_Frame (void)
+{
+}
+
+void IN_ForceCenterView (void)
+{
+	cl.viewangles[PITCH] = 0;
+}
+
+void IN_MLookDown (void)
+{
+	mlooking = true;
+}
+
+void IN_MLookUp (void)
+{
+	mlooking = false;
+	IN_CenterView();
+}
+
+int runetokey (Rune r)
+{
+	int k = 0;
+
+	switch(r){
+	case Kpgup:	k = K_PGUP; break;
+	case Kpgdown:	k = K_PGDN; break;
+	case Khome:	k = K_HOME; break;
+	case Kend:	k = K_END; break;
+	case Kleft:	k = K_LEFTARROW; break;
+	case Kright:	k = K_RIGHTARROW; break;
+	case Kdown:	k = K_DOWNARROW; break;
+	case Kup:	k = K_UPARROW; break;
+	case Kesc:	k = K_ESCAPE; break;
+	case '\n':	k = K_ENTER; break;
+	case '\t':	k = K_TAB; break;
+	case KF|1:	k = K_F1; break;
+	case KF|2:	k = K_F2; break;
+	case KF|3:	k = K_F3; break;
+	case KF|4:	k = K_F4; break;
+	case KF|5:	k = K_F5; break;
+	case KF|6:	k = K_F6; break;
+	case KF|7:	k = K_F7; break;
+	case KF|8:	k = K_F8; break;
+	case KF|9:	k = K_F9; break;
+	case KF|10:	k = K_F10; break;
+	case KF|11:	k = K_F11; break;
+	case KF|12:	k = K_F12; break;
+	case Kbs:	k = K_BACKSPACE; break;
+	case Kdel:	k = K_DEL; break;
+	case Kbreak:	k = K_PAUSE; break;
+	case Kshift:	k = K_SHIFT; break;
+	case Kctl:	k = K_CTRL; break;
+	case Kalt:
+	case Kaltgr:	k = K_ALT; break;
+	case Kins:	k = K_INS; break;
+	default:
+		if(r < 0x80)
+			k = r;
+	};
+	return k;
+}
+
+void kproc (void *)
+{
+	int n, k, fd;
+	char buf[128], kdown[128] = {0}, *s;
+	Rune r;
+	Kev ev;
+
+	if((fd = open("/dev/kbd", OREAD)) < 0)
+		sysfatal("open /dev/kbd: %r");
+
+	while((n = read(fd, buf, sizeof buf)) > 0){
+		buf[n-1] = 0;
+		switch(*buf){
+		case 'c':
+		default:
+			continue;
+		case 'k':
+			s = buf+1;
+			while(*s){
+				s += chartorune(&r, s);
+				if(utfrune(kdown+1, r) == nil){
+					if(k = runetokey(r)){
+						ev.key = k;
+						ev.down = true;
+						if(nbsend(kchan, &ev) < 0)
+							sysfatal("kproc:nbsend: %r\n");
+					}
+				}
+			}
+			break;
+		case 'K':
+			s = kdown+1;
+			while(*s){
+				s += chartorune(&r, s);
+				if(utfrune(buf+1, r) == nil){
+					if(k = runetokey(r)){
+						ev.key = k;
+						ev.down = false;
+						if(nbsend(kchan, &ev) < 0)
+							sysfatal("mproc:nbsend: %r\n");
+					}
+				}
+			}
+			break;
+		}
+		strcpy(kdown, buf);
+	}
+	close(fd);
+	ktid = -1;
+}
+
+void mproc (void *)
+{
+	int b, n, nerr = 0, fd;
+	char buf[1+5*12];
+	int x, y;
+
+	if((fd = open("/dev/mouse", ORDWR)) < 0)
+		sysfatal("open /dev/mouse: %r");
+
+	for(;;){
+		if((n = read(fd, buf, sizeof buf)) != 1+4*12){
+			fprint(2, "mproc:read: bad count %d not 49: %r\n", n);
+			if(n < 0 || ++nerr > 10)
+				break;
+			continue;
+		}
+		nerr = 0;
+		switch(*buf){
+		case 'r':
+			resized = 1;
+			/* fall through */
+		case 'm':
+			if(!mouseon)
+				break;
+
+			x = atoi(buf+1+0*12) - center.x;
+			y = atoi(buf+1+1*12) - center.y;
+			b = atoi(buf+1+2*12);
+
+			mbtn = b&1 | (b&2)<<1 | (b&4)>>1;
+			dx += x;
+			dy += y;
+			if(m_windowed->value && (x != 0 || y != 0))
+				fprint(fd, "m%d %d", center.x, center.y);
+			break;
+		}
+	}
+	close(fd);
+	mtid = -1;
+}
+
+void IN_Shutdown (void)
+{
+	IN_Grabm(0);
+	if(ktid != -1){
+		threadkill(ktid);
+		ktid = -1;
+	}
+	if(mtid != -1){
+		threadkill(mtid);
+		mtid = -1;
+	}
+	if(kchan != nil){
+		chanfree(kchan);
+		kchan = nil;
+	}
+	mouseon = false;
+}
+
+void sucks (void *, char *note)
+{
+	if(!strncmp(note, "sys:", 4))
+		IN_Shutdown();
+	noted(NDFLT);
+}
+
+void IN_Init (void)
+{
+	in_mouse = ri.Cvar_Get("in_mouse", "1", CVAR_ARCHIVE);
+	in_joystick = ri.Cvar_Get("in_joystick", "0", CVAR_ARCHIVE);
+	m_windowed = ri.Cvar_Get("m_windowed", "0", CVAR_ARCHIVE);
+	m_filter = ri.Cvar_Get("m_filter", "0", 0);
+	freelook = ri.Cvar_Get("freelook", "0", 0);
+	lookstrafe = ri.Cvar_Get("lookstrafe", "0", 0);
+	sensitivity = ri.Cvar_Get("sensitivity", "3", 0);
+	m_pitch = ri.Cvar_Get("m_pitch", "0.022", 0);
+	m_yaw = ri.Cvar_Get("m_yaw", "0.022", 0);
+	m_forward = ri.Cvar_Get("m_forward", "1", 0);
+	m_side = ri.Cvar_Get("m_side", "0.8", 0);
+
+	ri.Cmd_AddCommand("+mlook", IN_MLookDown);
+	ri.Cmd_AddCommand("-mlook", IN_MLookUp);
+	ri.Cmd_AddCommand("force_centerview", IN_ForceCenterView);
+
+	notify(sucks);
+	kchan = chancreate(sizeof(Kev), Nbuf);
+	if((ktid = proccreate(kproc, nil, 8192)) < 0)
+		sysfatal("proccreate kproc: %r");
+	if(m_windowed->value)
+		IN_Grabm(1);
+	if((mtid = proccreate(mproc, nil, 8192)) < 0)
+		sysfatal("proccreate mproc: %r");
+	mx = my = 0;
+}
--- a/plan9/net_udp.c
+++ b/plan9/net_udp.c
@@ -1,128 +1,72 @@
-// net_wins.c
-
-#include "../qcommon/qcommon.h"
-
-#include <unistd.h>
-#include <sys/socket.h>
-#include <sys/time.h>
-#include <netinet/in.h>
-#include <netdb.h>
-#include <sys/param.h>
-#include <sys/ioctl.h>
-#include <sys/uio.h>
-#include <errno.h>
-
-#ifdef NeXT
+#include <u.h>
 #include <libc.h>
-#endif
+#include <stdio.h>
+#include <ctype.h>
+#include <bio.h>
+#include <ndb.h>
+#include "../dat.h"
+#include "../fns.h"
 
-netadr_t	net_local_adr;
+/* FIXME: only loopback works, the rest is complete bullshit */
 
-#define	LOOPBACK	0x7f000001
+typedef struct Loopmsg Loopmsg;
+typedef struct Loopback Loopback;
 
-#define	MAX_LOOPBACK	4
+enum{
+	LOOPBACK	= 0x7f000001,
+	MAX_LOOPBACK	= 4
+};
 
-typedef struct
-{
+struct Loopmsg{
 	byte	data[MAX_MSGLEN];
-	int		datalen;
-} loopmsg_t;
+	int	datalen;
+};
+struct Loopback{
+	Loopmsg	msgs[MAX_LOOPBACK];
+	int	get;
+	int	send;
+};
+Loopback	loopbacks[2];
 
-typedef struct
-{
-	loopmsg_t	msgs[MAX_LOOPBACK];
-	int			get, send;
-} loopback_t;
+int	ipfd[2], ipxfd[2];
+netadr_t laddr;
 
-loopback_t	loopbacks[2];
-int			ip_sockets[2];
-int			ipx_sockets[2];
 
-int NET_Socket (char *net_interface, int port);
-char *NET_ErrorString (void);
-
-//=============================================================================
-
-void NetadrToSockadr (netadr_t *a, struct sockaddr_in *s)
+qboolean NET_CompareAdr (netadr_t a, netadr_t b)
 {
-	memset (s, 0, sizeof(*s));
-
-	if (a->type == NA_BROADCAST)
-	{
-		s->sin_family = AF_INET;
-
-		s->sin_port = a->port;
-		*(int *)&s->sin_addr = -1;
-	}
-	else if (a->type == NA_IP)
-	{
-		s->sin_family = AF_INET;
-
-		*(int *)&s->sin_addr = *(int *)&a->ip;
-		s->sin_port = a->port;
-	}
+	return (a.ip[0] == b.ip[0] && a.ip[1] == b.ip[1] && a.ip[2] == b.ip[2] && a.ip[3] == b.ip[3] && a.port == b.port);
 }
 
-void SockadrToNetadr (struct sockaddr_in *s, netadr_t *a)
+/* compares without the port */
+qboolean NET_CompareBaseAdr (netadr_t a, netadr_t b)
 {
-	*(int *)&a->ip = *(int *)&s->sin_addr;
-	a->port = s->sin_port;
-	a->type = NA_IP;
-}
-
-
-qboolean	NET_CompareAdr (netadr_t a, netadr_t b)
-{
-	if (a.ip[0] == b.ip[0] && a.ip[1] == b.ip[1] && a.ip[2] == b.ip[2] && a.ip[3] == b.ip[3] && a.port == b.port)
-		return true;
-	return false;
-}
-
-/*
-===================
-NET_CompareBaseAdr
-
-Compares without the port
-===================
-*/
-qboolean	NET_CompareBaseAdr (netadr_t a, netadr_t b)
-{
-	if (a.type != b.type)
+	if(a.type != b.type)
 		return false;
-
-	if (a.type == NA_LOOPBACK)
+	switch(a.type){
+	case NA_LOOPBACK:
 		return true;
-
-	if (a.type == NA_IP)
-	{
-		if (a.ip[0] == b.ip[0] && a.ip[1] == b.ip[1] && a.ip[2] == b.ip[2] && a.ip[3] == b.ip[3])
-			return true;
+	case NA_IP:
+		return (a.ip[0] == b.ip[0] && a.ip[1] == b.ip[1] && a.ip[2] == b.ip[2] && a.ip[3] == b.ip[3]);
+	case NA_IPX:
+		return !memcmp(a.ipx, b.ipx, 10);
+	default:
 		return false;
 	}
-
-	if (a.type == NA_IPX)
-	{
-		if ((memcmp(a.ipx, b.ipx, 10) == 0))
-			return true;
-		return false;
-	}
 }
 
-char	*NET_AdrToString (netadr_t a)
+char *NET_AdrToString (netadr_t a)
 {
-	static	char	s[64];
+	static char s[64];
 	
-	Com_sprintf (s, sizeof(s), "%i.%i.%i.%i:%i", a.ip[0], a.ip[1], a.ip[2], a.ip[3], ntohs(a.port));
-
+	Com_sprintf(s, sizeof(s), "%i.%i.%i.%i:%hi", a.ip[0], a.ip[1], a.ip[2], a.ip[3], a.port << 8 | a.port >> 8);
 	return s;
 }
 
-char	*NET_BaseAdrToString (netadr_t a)
+char *NET_BaseAdrToString (netadr_t a)
 {
-	static	char	s[64];
+	static char s[64];
 	
-	Com_sprintf (s, sizeof(s), "%i.%i.%i.%i", a.ip[0], a.ip[1], a.ip[2], a.ip[3]);
-
+	Com_sprintf(s, sizeof(s), "%i.%i.%i.%i", a.ip[0], a.ip[1], a.ip[2], a.ip[3]);
 	return s;
 }
 
@@ -137,92 +81,62 @@
 192.246.40.70:28000
 =============
 */
-qboolean	NET_StringToSockaddr (char *s, struct sockaddr *sadr)
+qboolean NET_StringToAdr (char *s, netadr_t *a)
 {
-	struct hostent	*h;
-	char	*colon;
-	char	copy[128];
-	
-	memset (sadr, 0, sizeof(*sadr));
-	((struct sockaddr_in *)sadr)->sin_family = AF_INET;
-	
-	((struct sockaddr_in *)sadr)->sin_port = 0;
+	int i;
+	char *e, *p, *ss;
+	Ndb *db;
+	Ndbtuple *nt;
 
-	strcpy (copy, s);
-	// strip off a trailing :port if present
-	for (colon = copy ; *colon ; colon++)
-		if (*colon == ':')
-		{
-			*colon = 0;
-			((struct sockaddr_in *)sadr)->sin_port = htons((short)atoi(colon+1));	
-		}
-	
-	if (copy[0] >= '0' && copy[0] <= '9')
-	{
-		*(int *)&((struct sockaddr_in *)sadr)->sin_addr = inet_addr(copy);
-	}
-	else
-	{
-		if (! (h = gethostbyname(copy)) )
-			return 0;
-		*(int *)&((struct sockaddr_in *)sadr)->sin_addr = *(int *)h->h_addr_list[0];
-	}
-	
-	return true;
-}
-
-/*
-=============
-NET_StringToAdr
-
-localhost
-idnewt
-idnewt:28000
-192.246.40.70
-192.246.40.70:28000
-=============
-*/
-qboolean	NET_StringToAdr (char *s, netadr_t *a)
-{
-	struct sockaddr_in sadr;
-	
-	if (!strcmp (s, "localhost"))
-	{
-		memset (a, 0, sizeof(*a));
+	if(!strcmp(s, "localhost")){
+		memset(a, 0, sizeof(*a));
 		a->type = NA_LOOPBACK;
 		return true;
 	}
 
-	if (!NET_StringToSockaddr (s, (struct sockaddr *)&sadr))
+	/* FIXMEGASHIT */
+	if((ss = smprint("%s", s)) == nil)		/* don't fuck with someone else's s */
+		sysfatal("NET_StringToAdr:smprint: %r");
+	p = ss;
+	if((e = strchr(p, ':')) != nil){
+		*e++ = '\0';
+		a->port = atoi(e);
+	}
+	db = ndbopen(nil);
+	if((nt = ndbgetipaddr(db, ss)) == nil){
+		ndbclose(db);
 		return false;
-	
-	SockadrToNetadr (&sadr, a);
+	}
+	if((ss = smprint("%s", nt->val)) == nil)	/* get copy of first value found */
+		sysfatal("NET_StringToAdr:smprint: %r");
+	p = ss;
+	for(i = 0; i < 4; i++){
+		if((e = strchr(p, '.')) != nil)
+			*e++ = '\0';
+		a->ip[i] = atoi(p);
+		p = e;
+	}
+	a->type = NA_IP;
 
+	free(ss);
+	ndbfree(nt);
+	ndbclose(db);
 	return true;
 }
 
-
-qboolean	NET_IsLocalAddress (netadr_t adr)
+qboolean NET_IsLocalAddress (netadr_t adr)
 {
-	return NET_CompareAdr (adr, net_local_adr);
+	return NET_CompareAdr (adr, laddr);
 }
 
-/*
-=============================================================================
-
-LOOPBACK BUFFERS FOR LOCAL PLAYER
-
-=============================================================================
-*/
-
-qboolean	NET_GetLoopPacket (netsrc_t sock, netadr_t *net_from, sizebuf_t *net_message)
+qboolean NET_GetLoopPacket (netsrc_t sock, netadr_t *net_from, sizebuf_t *net_message)
 {
-	int		i;
-	loopback_t	*loop;
+	int i;
+	Loopback *loop;
 
 	loop = &loopbacks[sock];
 
-	if (loop->send - loop->get > MAX_LOOPBACK)
+	if(loop->send - loop->get > MAX_LOOPBACK)
 		loop->get = loop->send - MAX_LOOPBACK;
 
 	if (loop->get >= loop->send)
@@ -231,307 +145,185 @@
 	i = loop->get & (MAX_LOOPBACK-1);
 	loop->get++;
 
-	memcpy (net_message->data, loop->msgs[i].data, loop->msgs[i].datalen);
+	memcpy(net_message->data, loop->msgs[i].data, loop->msgs[i].datalen);
 	net_message->cursize = loop->msgs[i].datalen;
-	*net_from = net_local_adr;
+	*net_from = laddr;
 	return true;
-
 }
 
-
-void NET_SendLoopPacket (netsrc_t sock, int length, void *data, netadr_t to)
+void NET_SendLoopPacket (netsrc_t sock, int length, void *data, netadr_t /*to*/)
 {
-	int		i;
-	loopback_t	*loop;
+	Loopback *loop;
+	int i;
 
 	loop = &loopbacks[sock^1];
-
 	i = loop->send & (MAX_LOOPBACK-1);
 	loop->send++;
-
-	memcpy (loop->msgs[i].data, data, length);
+	memcpy(loop->msgs[i].data, data, length);
 	loop->msgs[i].datalen = length;
 }
 
-//=============================================================================
-
-qboolean	NET_GetPacket (netsrc_t sock, netadr_t *net_from, sizebuf_t *net_message)
+qboolean NET_GetPacket (netsrc_t src, netadr_t *from, sizebuf_t *d)
 {
-	int 	ret;
-	struct sockaddr_in	from;
-	int		fromlen;
-	int		net_socket;
-	int		protocol;
-	int		err;
+	int n, protocol, fd;
+	NetConnInfo *nci;
+	char addr[21];
 
-	if (NET_GetLoopPacket (sock, net_from, net_message))
+	if(NET_GetLoopPacket(src, from, d))
 		return true;
 
-	for (protocol = 0 ; protocol < 2 ; protocol++)
-	{
-		if (protocol == 0)
-			net_socket = ip_sockets[sock];
+	for(protocol = 0 ; protocol < 2 ; protocol++){
+		if(protocol == 0)
+			fd = ipfd[src];
 		else
-			net_socket = ipx_sockets[sock];
-
-		if (!net_socket)
+			fd = ipxfd[src];
+		if(!fd)
 			continue;
 
-		fromlen = sizeof(from);
-		ret = recvfrom (net_socket, net_message->data, net_message->maxsize
-			, 0, (struct sockaddr *)&from, &fromlen);
-		if (ret == -1)
-		{
-			err = errno;
-
-			if (err == EWOULDBLOCK || err == ECONNREFUSED)
-				continue;
-			Com_Printf ("NET_GetPacket: %s", NET_ErrorString());
+		if((n = read(fd, d->data, d->maxsize)) < 0){
+			fprint(2, "NET_GetPacket:read: %r\n");
+			Com_Printf("NET_GetPacket: error reading packet\n");
 			continue;
 		}
-
-		if (ret == net_message->maxsize)
-		{
-			Com_Printf ("Oversize packet from %s\n", NET_AdrToString (*net_from));
+		if(n == d->maxsize){
+			Com_Printf("Oversize packet from %s\n", NET_AdrToString(*from));
 			continue;
 		}
+		d->cursize = n;
 
-		net_message->cursize = ret;
-		SockadrToNetadr (&from, net_from);
+		/* FIXME */
+		if((nci = getnetconninfo(nil, fd)) == nil){
+			fprint(2, "NET_GetPacket:getnetconninfo: %r\n");
+			return true;
+		}
+		seprint(addr, addr+sizeof(addr), "%s:%s", nci->rsys, nci->rserv);
+		NET_StringToAdr(addr, from);
 		return true;
 	}
-
 	return false;
 }
 
-//=============================================================================
-
-void NET_SendPacket (netsrc_t sock, int length, void *data, netadr_t to)
+void NET_SendPacket (netsrc_t src, int length, void *data, netadr_t to)
 {
-	int		ret;
-	struct sockaddr_in	addr;
-	int		net_socket;
+	int fd = 0;
 
-	if ( to.type == NA_LOOPBACK )
-	{
-		NET_SendLoopPacket (sock, length, data, to);
+	switch(to.type){
+	case NA_LOOPBACK:
+		NET_SendLoopPacket(src, length, data, to);
 		return;
-	}
-
-	if (to.type == NA_BROADCAST)
-	{
-		net_socket = ip_sockets[sock];
-		if (!net_socket)
+	case NA_BROADCAST:
+	case NA_IP:
+		fd = ipfd[src];
+		if(!fd)
 			return;
-	}
-	else if (to.type == NA_IP)
-	{
-		net_socket = ip_sockets[sock];
-		if (!net_socket)
+		break;
+	case NA_IPX:
+	case NA_BROADCAST_IPX:
+		fd = ipxfd[src];
+		if(!fd)
 			return;
+		break;
+	default:
+		Com_Error(ERR_FATAL, "NET_SendPacket: bad address type");
 	}
-	else if (to.type == NA_IPX)
-	{
-		net_socket = ipx_sockets[sock];
-		if (!net_socket)
-			return;
+	if(write(fd, data, length) != length){
+		fprint(2, "NET_SendPacket:write: %r\n");
+		Com_Printf("NET_SendPacket: bad write\n");
 	}
-	else if (to.type == NA_BROADCAST_IPX)
-	{
-		net_socket = ipx_sockets[sock];
-		if (!net_socket)
-			return;
-	}
-	else
-		Com_Error (ERR_FATAL, "NET_SendPacket: bad address type");
+}
 
-	NetadrToSockadr (&to, &addr);
+int NET_Socket (char *ifc, int port)
+{
+	int fd;
+	char addr[21], dir[40], *p;
 
-	ret = sendto (net_socket, data, length, 0, (struct sockaddr *)&addr, sizeof(addr) );
-	if (ret == -1)
-	{
-		Com_Printf ("NET_SendPacket ERROR: %i\n", NET_ErrorString());
+	/* FIXMEGAFUCKEDUPSHIT */
+	p = seprint(addr, addr+sizeof(addr), "udp!*");
+	if(ifc != nil || Q_strcasecmp(ifc, "localhost"))
+		p = seprint(p-1, addr+sizeof(addr), "%s", ifc);
+	if(port == PORT_ANY)
+		seprint(p, addr+sizeof(addr), "!%hud", (ushort)port);
+
+	if((fd = announce(addr, dir)) < 0){
+		fprint(2, "NET_Socket:announce: %r\n");
+		Com_Printf("Net_Socket: announce failed!\n");
+		return false;
 	}
+	return fd;	/* FIXME: NO! */
 }
 
-
-//=============================================================================
-
-
-
-
-/*
-====================
-NET_OpenIP
-====================
-*/
 void NET_OpenIP (void)
 {
 	cvar_t	*port, *ip;
 
-	port = Cvar_Get ("port", va("%i", PORT_SERVER), CVAR_NOSET);
-	ip = Cvar_Get ("ip", "localhost", CVAR_NOSET);
+	port = Cvar_Get("port", va("%i", PORT_SERVER), CVAR_NOSET);
+	ip = Cvar_Get("ip", "localhost", CVAR_NOSET);
 
-	if (!ip_sockets[NS_SERVER])
-		ip_sockets[NS_SERVER] = NET_Socket (ip->string, port->value);
-	if (!ip_sockets[NS_CLIENT])
-		ip_sockets[NS_CLIENT] = NET_Socket (ip->string, PORT_ANY);
+	/* FIXME: those are ctl fd's! */
+	if(!ipfd[NS_SERVER])
+		ipfd[NS_SERVER] = NET_Socket(ip->string, port->value);
+	if(!ipfd[NS_CLIENT])
+		ipfd[NS_CLIENT] = NET_Socket(ip->string, PORT_ANY);
 }
 
-/*
-====================
-NET_OpenIPX
-====================
-*/
 void NET_OpenIPX (void)
 {
 }
 
-
-/*
-====================
-NET_Config
-
-A single player game will only use the loopback code
-====================
-*/
-void	NET_Config (qboolean multiplayer)
+/* a single player game will only use the loopback code */
+void NET_Config (qboolean multiplayer)
 {
-	int		i;
+	int i;
 
-	if (!multiplayer)
-	{	// shut down any existing sockets
-		for (i=0 ; i<2 ; i++)
-		{
-			if (ip_sockets[i])
-			{
-				close (ip_sockets[i]);
-				ip_sockets[i] = 0;
+	if(!multiplayer){	/* shut down any existing sockets */
+		for(i=0 ; i<2 ; i++){
+			if(ipfd[i]){
+				close(ipfd[i]);
+				ipfd[i] = 0;
 			}
-			if (ipx_sockets[i])
-			{
-				close (ipx_sockets[i]);
-				ipx_sockets[i] = 0;
+			if(ipxfd[i]){
+				close(ipxfd[i]);
+				ipxfd[i] = 0;
 			}
 		}
 	}
-	else
-	{	// open sockets
-		NET_OpenIP ();
-		NET_OpenIPX ();
+	else{			/* open sockets */
+		NET_OpenIP();
+		NET_OpenIPX();
 	}
 }
 
-
-//===================================================================
-
-
-/*
-====================
-NET_Init
-====================
-*/
 void NET_Init (void)
 {
 }
 
-
-/*
-====================
-NET_Socket
-====================
-*/
-int NET_Socket (char *net_interface, int port)
+void NET_Shutdown (void)
 {
-	int newsocket;
-	struct sockaddr_in address;
-	qboolean _true = true;
-	int	i = 1;
-
-	if ((newsocket = socket (PF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1)
-	{
-		Com_Printf ("ERROR: UDP_OpenSocket: socket:", NET_ErrorString());
-		return 0;
-	}
-
-	// make it non-blocking
-	if (ioctl (newsocket, FIONBIO, &_true) == -1)
-	{
-		Com_Printf ("ERROR: UDP_OpenSocket: ioctl FIONBIO:%s\n", NET_ErrorString());
-		return 0;
-	}
-
-	// make it broadcast capable
-	if (setsockopt(newsocket, SOL_SOCKET, SO_BROADCAST, (char *)&i, sizeof(i)) == -1)
-	{
-		Com_Printf ("ERROR: UDP_OpenSocket: setsockopt SO_BROADCAST:%s\n", NET_ErrorString());
-		return 0;
-	}
-
-	if (!net_interface || !net_interface[0] || !stricmp(net_interface, "localhost"))
-		address.sin_addr.s_addr = INADDR_ANY;
-	else
-		NET_StringToSockaddr (net_interface, (struct sockaddr *)&address);
-
-	if (port == PORT_ANY)
-		address.sin_port = 0;
-	else
-		address.sin_port = htons((short)port);
-
-	address.sin_family = AF_INET;
-
-	if( bind (newsocket, (void *)&address, sizeof(address)) == -1)
-	{
-		Com_Printf ("ERROR: UDP_OpenSocket: bind: %s\n", NET_ErrorString());
-		close (newsocket);
-		return 0;
-	}
-
-	return newsocket;
+	NET_Config(false);	// close sockets
 }
 
-
-/*
-====================
-NET_Shutdown
-====================
-*/
-void	NET_Shutdown (void)
+/* sleeps msec or until net socket is ready */
+void NET_Sleep(int /*msec*/)
 {
-	NET_Config (false);	// close sockets
-}
+	/* PORTME */
 
-
-/*
-====================
-NET_ErrorString
-====================
-*/
-char *NET_ErrorString (void)
-{
-	int		code;
-
-	code = errno;
-	return strerror (code);
-}
-
-// sleeps msec or until net socket is ready
-void NET_Sleep(int msec)
-{
+	/*
     struct timeval timeout;
 	fd_set	fdset;
 	extern cvar_t *dedicated;
 	extern qboolean stdin_active;
+	*/
 
-	if (!ip_sockets[NS_SERVER] || (dedicated && !dedicated->value))
+	if(!ipfd[NS_SERVER] || dedicated && !dedicated->value)
 		return; // we're not a server, just run full speed
 
+	/*
 	FD_ZERO(&fdset);
 	if (stdin_active)
 		FD_SET(0, &fdset); // stdin is processed too
-	FD_SET(ip_sockets[NS_SERVER], &fdset); // network socket
+	FD_SET(ipfd[NS_SERVER], &fdset); // network socket
 	timeout.tv_sec = msec/1000;
 	timeout.tv_usec = (msec%1000)*1000;
-	select(ip_sockets[NS_SERVER]+1, &fdset, NULL, NULL, &timeout);
+	select(ipfd[NS_SERVER]+1, &fdset, NULL, NULL, &timeout);
+	*/
 }
-
--- a/plan9/q_sh9.c
+++ b/plan9/q_sh9.c
@@ -1,35 +1,189 @@
-#include <sys/types.h>
-#include <errno.h>
+#include <u.h>
+#include <libc.h>
 #include <stdio.h>
-#include <dirent.h>
-#include <sys/stat.h>
-#include <unistd.h>
-#include <sys/mman.h>
-#include <sys/time.h>
+#include "../dat.h"
+#include "../fns.h"
 
-#include "../linux/glob.h"
-
-#include "../qcommon/qcommon.h"
-
-//===============================================================================
-
 byte *membase;
 int maxhunksize;
 int curhunksize;
+int curtime;
+char findbase[MAX_OSPATH], findpath[MAX_OSPATH], findpattern[MAX_OSPATH];
+int fdir = -1;
+Dir *ddir;
 
+int	glob_match(char *, char *);
+
+
+/* Like glob_match, but match PATTERN against any final segment of TEXT.  */
+int glob_match_after_star(char *pattern, char *text)
+{
+	char *p = pattern, *t = text;
+	char c, c1;
+
+	while ((c = *p++) == '?' || c == '*')
+		if (c == '?' && *t++ == '\0')
+			return 0;
+
+	if (c == '\0')
+		return 1;
+
+	if (c == '\\')
+		c1 = *p;
+	else
+		c1 = c;
+
+	while (1) {
+		if ((c == '[' || *t == c1) && glob_match(p - 1, t))
+			return 1;
+		if (*t++ == '\0')
+			return 0;
+	}
+}
+
+/* Return nonzero if PATTERN has any special globbing chars in it.  */
+int glob_pattern_p(char *pattern)
+{
+	char *p = pattern;
+	char c;
+	int open = 0;
+
+	while ((c = *p++) != '\0')
+		switch (c) {
+		case '?':
+		case '*':
+			return 1;
+
+		case '[':		/* Only accept an open brace if there is a close */
+			open++;		/* brace to match it.  Bracket expressions must be */
+			continue;	/* complete, according to Posix.2 */
+		case ']':
+			if (open)
+				return 1;
+			continue;
+
+		case '\\':
+			if (*p++ == '\0')
+				return 0;
+		}
+
+	return 0;
+}
+
+/* Match the pattern PATTERN against the string TEXT;
+   return 1 if it matches, 0 otherwise.
+
+   A match means the entire string TEXT is used up in matching.
+
+   In the pattern string, `*' matches any sequence of characters,
+   `?' matches any character, [SET] matches any character in the specified set,
+   [!SET] matches any character not in the specified set.
+
+   A set is composed of characters or ranges; a range looks like
+   character hyphen character (as in 0-9 or A-Z).
+   [0-9a-zA-Z_] is the set of characters allowed in C identifiers.
+   Any other character in the pattern must be matched exactly.
+
+   To suppress the special syntactic significance of any of `[]*?!-\',
+   and match the character exactly, precede it with a `\'.
+*/
+
+int glob_match(char *pattern, char *text)
+{
+	char *p = pattern, *t = text;
+	char c, c1, cstart, cend;
+	int invert;
+
+	while ((c = *p++) != '\0')
+		switch (c) {
+		case '?':
+			if (*t == '\0')
+				return 0;
+			else
+				++t;
+			break;
+
+		case '\\':
+			if (*p++ != *t++)
+				return 0;
+			break;
+
+		case '*':
+			return glob_match_after_star(p, t);
+
+		case '[':
+			{
+				c1 = *t++;
+
+				if (!c1)
+					return (0);
+
+				invert = ((*p == '!') || (*p == '^'));
+				if (invert)
+					p++;
+
+				c = *p++;
+				while (1) {
+					cstart = c;
+					cend = c;
+
+					if (c == '\\') {
+						cstart = *p++;
+						cend = cstart;
+					}
+					if (c == '\0')
+						return 0;
+
+					c = *p++;
+					if (c == '-' && *p != ']') {
+						cend = *p++;
+						if (cend == '\\')
+							cend = *p++;
+						if (cend == '\0')
+							return 0;
+						c = *p++;
+					}
+					if (c1 >= cstart && c1 <= cend)
+						goto match;
+					if (c == ']')
+						break;
+				}
+				if (!invert)
+					return 0;
+				break;
+
+			  match:
+				/* Skip the rest of the [...] construct that already matched.  */
+				while (c != ']') {
+					if (c == '\0')
+						return 0;
+					c = *p++;
+					if (c == '\0')
+						return 0;
+					else if (c == '\\')
+						++p;
+				}
+				if (invert)
+					return 0;
+				break;
+			}
+
+		default:
+			if (c != *t++)
+				return 0;
+		}
+
+	return *t == '\0';
+}
+
 void *Hunk_Begin (int maxsize)
 {
 	// reserve a huge chunk of memory, but don't commit any yet
-	maxhunksize = maxsize + sizeof(int);
+	maxhunksize = maxsize;
 	curhunksize = 0;
-	membase = mmap(0, maxhunksize, PROT_READ|PROT_WRITE, 
-		MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
-	if (membase == NULL || membase == (byte *)-1)
-		Sys_Error("unable to virtual allocate %d bytes", maxsize);
-
-	*((int *)membase) = curhunksize;
-
-	return membase + sizeof(int);
+	if((membase = mallocz(maxhunksize, 1)) == nil)
+		sysfatal("Hunk_Begin:malloc %d: %r", maxhunksize);
+	return membase;
 }
 
 void *Hunk_Alloc (int size)
@@ -38,9 +192,9 @@
 
 	// round to cacheline
 	size = (size+31)&~31;
-	if (curhunksize + size > maxhunksize)
+	if(curhunksize + size > maxhunksize)
 		Sys_Error("Hunk_Alloc overflow");
-	buf = membase + sizeof(int) + curhunksize;
+	buf = membase + curhunksize;
 	curhunksize += size;
 	return buf;
 }
@@ -47,159 +201,111 @@
 
 int Hunk_End (void)
 {
-	byte *n;
-
-	n = mremap(membase, maxhunksize, curhunksize + sizeof(int), 0);
-	if (n != membase)
-		Sys_Error("Hunk_End:  Could not remap virtual block (%d)", errno);
-	*((int *)membase) = curhunksize + sizeof(int);
-	
+	if(realloc(membase, curhunksize) != membase)
+		sysfatal("Hunk_End:realloc: %r");
 	return curhunksize;
 }
 
 void Hunk_Free (void *base)
 {
-	byte *m;
-
-	if (base) {
-		m = ((byte *)base) - sizeof(int);
-		if (munmap(m, *((int *)m)))
-			Sys_Error("Hunk_Free: munmap failed (%d)", errno);
-	}
+	if(base != nil)
+		free(base);
 }
 
-//===============================================================================
-
-
-/*
-================
-Sys_Milliseconds
-================
-*/
-int curtime;
 int Sys_Milliseconds (void)
 {
-	struct timeval tp;
-	struct timezone tzp;
-	static int		secbase;
+	static long msbase;
 
-	gettimeofday(&tp, &tzp);
-	
-	if (!secbase)
-	{
-		secbase = tp.tv_sec;
-		return tp.tv_usec/1000;
-	}
-
-	curtime = (tp.tv_sec - secbase)*1000 + tp.tv_usec/1000;
-	
+	if(msbase == 0)
+		msbase = time(nil)*1000;
+	curtime = nsec()/1000000 - msbase;
 	return curtime;
 }
 
 void Sys_Mkdir (char *path)
 {
-    mkdir (path, 0777);
-}
+	int d;
 
-char *strlwr (char *s)
-{
-	while (*s) {
-		*s = tolower(*s);
-		s++;
-	}
+	if((d = create(path, OREAD, DMDIR|0777)) < 0)
+		fprint(2, "Sys_mkdir:create: %r\n");
+	else
+		close(d);
 }
 
-//============================================
-
-static	char	findbase[MAX_OSPATH];
-static	char	findpath[MAX_OSPATH];
-static	char	findpattern[MAX_OSPATH];
-static	DIR		*fdir;
-
-static qboolean CompareAttributes(char *path, char *name,
-	unsigned musthave, unsigned canthave )
+qboolean CompareAttributes (Dir *d, uint musthave, uint canthave)
 {
-	struct stat st;
-	char fn[MAX_OSPATH];
-
-// . and .. never match
-	if (strcmp(name, ".") == 0 || strcmp(name, "..") == 0)
+	if(d->mode & DMDIR && canthave & SFF_SUBDIR)
 		return false;
-
-	sprintf(fn, "%s/%s", path, name);
-	if (stat(fn, &st) == -1)
-		return false; // shouldn't happen
-
-	if ( ( st.st_mode & S_IFDIR ) && ( canthave & SFF_SUBDIR ) )
+	if(musthave & SFF_SUBDIR && ~d->mode & DMDIR)
 		return false;
-
-	if ( ( musthave & SFF_SUBDIR ) && !( st.st_mode & S_IFDIR ) )
-		return false;
-
 	return true;
 }
 
-char *Sys_FindFirst (char *path, unsigned musthave, unsigned canhave)
+char *Sys_FindFirst (char *path, uint musthave, uint canhave)
 {
-	struct dirent *d;
 	char *p;
+	long n;
 
-	if (fdir)
-		Sys_Error ("Sys_BeginFind without close");
+	if(fdir != -1)
+		Sys_Error("Sys_BeginFind without close");
 
-//	COM_FilePath (path, findbase);
-	strcpy(findbase, path);
-
-	if ((p = strrchr(findbase, '/')) != NULL) {
+	strncpy(findbase, path, sizeof findbase-1);
+	if((p = strrchr(findbase, '/')) != nil){
 		*p = 0;
-		strcpy(findpattern, p + 1);
-	} else
+		strncpy(findpattern, p+1, sizeof findpattern-1);
+	}else
 		strcpy(findpattern, "*");
-
-	if (strcmp(findpattern, "*.*") == 0)
+	if(strcmp(findpattern, "*.*") == 0)
 		strcpy(findpattern, "*");
-	
-	if ((fdir = opendir(findbase)) == NULL)
-		return NULL;
-	while ((d = readdir(fdir)) != NULL) {
-		if (!*findpattern || glob_match(findpattern, d->d_name)) {
-//			if (*findpattern)
-//				printf("%s matched %s\n", findpattern, d->d_name);
-			if (CompareAttributes(findbase, d->d_name, musthave, canhave)) {
-				sprintf (findpath, "%s/%s", findbase, d->d_name);
+	if(*findpattern == '\0'){
+		Com_Printf("Sys_BeginFind: empty pattern\n");
+		return nil;
+	}
+
+	if((fdir = open(findbase, OREAD)) < 0){
+		fprint(2, "Sys_BeginFind:open: %r\n");
+		return nil;
+	}
+
+	while((n = dirread(fdir, &ddir)) > 0){
+		if(glob_match(findpattern, ddir->name)){
+			if(CompareAttributes(ddir, musthave, canhave)){
+				sprintf(findpath, "%s/%s", findbase, ddir->name);
 				return findpath;
 			}
 		}
 	}
-	return NULL;
+	if(n < 0)
+		fprint(2, "Sys_BeginFind:dirread: %r\n");
+	return nil;
 }
 
-char *Sys_FindNext (unsigned musthave, unsigned canhave)
+char *Sys_FindNext (uint musthave, uint canhave)
 {
-	struct dirent *d;
+	long n;
 
-	if (fdir == NULL)
-		return NULL;
-	while ((d = readdir(fdir)) != NULL) {
-		if (!*findpattern || glob_match(findpattern, d->d_name)) {
-//			if (*findpattern)
-//				printf("%s matched %s\n", findpattern, d->d_name);
-			if (CompareAttributes(findbase, d->d_name, musthave, canhave)) {
-				sprintf (findpath, "%s/%s", findbase, d->d_name);
+	if(fdir = -1){
+		Sys_Error("Sys_FindNext without open");
+		return nil;
+	}
+	while((n = dirread(fdir, &ddir)) > 0){
+		if(glob_match(findpattern, ddir->name)){
+			if(CompareAttributes(ddir, musthave, canhave)){
+				sprintf(findpath, "%s/%s", findbase, ddir->name);
 				return findpath;
 			}
 		}
 	}
-	return NULL;
+	if(n < 0)
+		fprint(2, "Sys_BeginFind:dirread: %r\n");
+	return nil;
 }
 
 void Sys_FindClose (void)
 {
-	if (fdir != NULL)
-		closedir(fdir);
-	fdir = NULL;
+	if(fdir != -1){
+		close(fdir);
+		free(ddir);
+		fdir = -1;
+	}
 }
-
-
-//============================================
-
--- a/plan9/rw_9.c
+++ b/plan9/rw_9.c
@@ -1,1093 +1,174 @@
-/*
-** RW_X11.C
-**
-** This file contains ALL Linux specific stuff having to do with the
-** software refresh.  When a port is being made the following functions
-** must be implemented by the port:
-**
-** SWimp_EndFrame
-** SWimp_Init
-** SWimp_InitGraphics
-** SWimp_SetPalette
-** SWimp_Shutdown
-** SWimp_SwitchFullscreen
-*/
-
-#include <ctype.h>
-#include <sys/time.h>
-#include <sys/types.h>
-#include <unistd.h>
-#include <signal.h>
-#include <stdlib.h>
+#include <u.h>
+#include <libc.h>
+#include <draw.h>
 #include <stdio.h>
-#include <string.h>
-#include <sys/ipc.h>
-#include <sys/shm.h>
+#include <ctype.h>
+#include "../dat.h"
+#include "../fns.h"
 
-#include <X11/Xlib.h>
-#include <X11/Xutil.h>
-#include <X11/Xatom.h>
-#include <X11/keysym.h>
-#include <X11/extensions/XShm.h>
+qboolean rwon;
+uchar *framebuf;
+Image *fbim;
+int resized;
+Point center;
 
-#include "../ref_soft/r_local.h"
-#include "../client/keys.h"
-#include "../linux/rw_linux.h"
+typedef ulong PIXEL;
+PIXEL st2d_8to24table[256];
+int shiftmask_fl;
+int r_shift, g_shift, b_shift;
+uint r_mask, g_mask, b_mask;
 
-/*****************************************************************************/
 
-static qboolean			doShm;
-static Display			*x_disp;
-static Colormap			x_cmap;
-static Window			x_win;
-static GC				x_gc;
-static Visual			*x_vis;
-static XVisualInfo		*x_visinfo;
-//static XImage			*x_image;
-
-#define STD_EVENT_MASK (StructureNotifyMask | KeyPressMask \
-	     | KeyReleaseMask | ExposureMask | PointerMotionMask | \
-	     ButtonPressMask | ButtonReleaseMask)
-
-static int				x_shmeventtype;
-//static XShmSegmentInfo	x_shminfo;
-
-static qboolean			oktodraw = false;
-static qboolean			X11_active = false;
-
-int XShmQueryExtension(Display *);
-int XShmGetEventBase(Display *);
-
-int current_framebuffer;
-static XImage			*x_framebuffer[2] = { 0, 0 };
-static XShmSegmentInfo	x_shminfo[2];
-
-struct
+void shiftmask_init (void)
 {
-	int key;
-	int down;
-} keyq[64];
-int keyq_head=0;
-int keyq_tail=0;
+	uint x;
 
-int config_notify=0;
-int config_notify_width;
-int config_notify_height;
-						      
-typedef unsigned short PIXEL;
-
-// Console variables that we need to access from this module
-
-/*****************************************************************************/
-/* MOUSE                                                                     */
-/*****************************************************************************/
-
-// this is inside the renderer shared lib, so these are called from vid_so
-
-static qboolean        mouse_avail;
-static int     mouse_buttonstate;
-static int     mouse_oldbuttonstate;
-static int   mouse_x, mouse_y;
-static int	old_mouse_x, old_mouse_y;
-static int		mx, my;
-static float old_windowed_mouse;
-static int p_mouse_x, p_mouse_y;
-
-static cvar_t	*_windowed_mouse;
-static cvar_t	*m_filter;
-static cvar_t	*in_mouse;
-
-static qboolean	mlooking;
-
-// state struct passed in Init
-static in_state_t	*in_state;
-
-static cvar_t *sensitivity;
-static cvar_t *lookstrafe;
-static cvar_t *m_side;
-static cvar_t *m_yaw;
-static cvar_t *m_pitch;
-static cvar_t *m_forward;
-static cvar_t *freelook;
-
-static void Force_CenterView_f (void)
-{
-	in_state->viewangles[PITCH] = 0;
+	r_mask = 0xff0000;
+	g_mask = 0xff00;
+	b_mask = 0xff;
+	for(r_shift = -8, x = 1; x < r_mask; x <<= 1)
+		r_shift++;
+	for(g_shift = -8, x = 1; x < g_mask; x <<= 1)
+		g_shift++;
+	for(b_shift = -8, x = 1; x < b_mask; x <<= 1)
+		b_shift++;
+	shiftmask_fl = 1;
 }
 
-static void RW_IN_MLookDown (void) 
-{ 
-	mlooking = true; 
-}
-
-static void RW_IN_MLookUp (void) 
+PIXEL rgb24 (int r, int g, int b)
 {
-	mlooking = false;
-	in_state->IN_CenterView_fp ();
-}
+	PIXEL p = 0;
 
-void RW_IN_Init(in_state_t *in_state_p)
-{
-	int mtype;
-	int i;
+	if(shiftmask_fl == 0)
+		shiftmask_init();
 
-	in_state = in_state_p;
-
-	// mouse variables
-	_windowed_mouse = ri.Cvar_Get ("_windowed_mouse", "0", CVAR_ARCHIVE);
-	m_filter = ri.Cvar_Get ("m_filter", "0", 0);
-    in_mouse = ri.Cvar_Get ("in_mouse", "1", CVAR_ARCHIVE);
-	freelook = ri.Cvar_Get( "freelook", "0", 0 );
-	lookstrafe = ri.Cvar_Get ("lookstrafe", "0", 0);
-	sensitivity = ri.Cvar_Get ("sensitivity", "3", 0);
-	m_pitch = ri.Cvar_Get ("m_pitch", "0.022", 0);
-	m_yaw = ri.Cvar_Get ("m_yaw", "0.022", 0);
-	m_forward = ri.Cvar_Get ("m_forward", "1", 0);
-	m_side = ri.Cvar_Get ("m_side", "0.8", 0);
-
-	ri.Cmd_AddCommand ("+mlook", RW_IN_MLookDown);
-	ri.Cmd_AddCommand ("-mlook", RW_IN_MLookUp);
-
-	ri.Cmd_AddCommand ("force_centerview", Force_CenterView_f);
-
-	mouse_x = mouse_y = 0.0;
-	mouse_avail = true;
-}
-
-void RW_IN_Shutdown(void)
-{
-	mouse_avail = false;
-}
-
-/*
-===========
-IN_Commands
-===========
-*/
-void RW_IN_Commands (void)
-{
-	int i;
-   
-	if (!mouse_avail) 
-		return;
-   
-	for (i=0 ; i<3 ; i++) {
-		if ( (mouse_buttonstate & (1<<i)) && !(mouse_oldbuttonstate & (1<<i)) )
-			in_state->Key_Event_fp (K_MOUSE1 + i, true);
-
-		if ( !(mouse_buttonstate & (1<<i)) && (mouse_oldbuttonstate & (1<<i)) )
-			in_state->Key_Event_fp (K_MOUSE1 + i, false);
-	}
-	mouse_oldbuttonstate = mouse_buttonstate;
-}
-
-/*
-===========
-IN_Move
-===========
-*/
-void RW_IN_Move (usercmd_t *cmd)
-{
-	if (!mouse_avail)
-		return;
-   
-	if (m_filter->value)
-	{
-		mouse_x = (mx + old_mouse_x) * 0.5;
-		mouse_y = (my + old_mouse_y) * 0.5;
-	} else {
-		mouse_x = mx;
-		mouse_y = my;
-	}
-
-	old_mouse_x = mx;
-	old_mouse_y = my;
-
-	if (!mouse_x && !mouse_y)
-		return;
-
-	mouse_x *= sensitivity->value;
-	mouse_y *= sensitivity->value;
-
-// add mouse X/Y movement to cmd
-	if ( (*in_state->in_strafe_state & 1) || 
-		(lookstrafe->value && mlooking ))
-		cmd->sidemove += m_side->value * mouse_x;
+	if(r_shift > 0)
+		p = r<<r_shift & r_mask;
+	else if(r_shift < 0)
+        	p = r>>-r_shift & r_mask;
 	else
-		in_state->viewangles[YAW] -= m_yaw->value * mouse_x;
-
-	if ( (mlooking || freelook->value) && 
-		!(*in_state->in_strafe_state & 1))
-	{
-		in_state->viewangles[PITCH] += m_pitch->value * mouse_y;
-	}
+		p |= r & r_mask;
+	if(g_shift > 0)
+		p |= g<<g_shift & g_mask;
+	else if(g_shift < 0)
+		p |= g>>-g_shift & g_mask;
 	else
-	{
-		cmd->forwardmove -= m_forward->value * mouse_y;
-	}
-	mx = my = 0;
+		p |= g & g_mask;
+	if(b_shift > 0)
+		p |= b<<b_shift & b_mask;
+	else if(b_shift < 0)
+		p |= b>>-b_shift & b_mask;
+	else
+		p |= b & b_mask;
+	return p;
 }
 
-void RW_IN_Frame (void)
+void st3_fixup (void)
 {
-}
-
-void RW_IN_Activate(void)
-{
-}
-
-/*****************************************************************************/
-
-static PIXEL st2d_8to16table[256];
-static int shiftmask_fl=0;
-static long r_shift,g_shift,b_shift;
-static unsigned long r_mask,g_mask,b_mask;
-
-void shiftmask_init()
-{
-    unsigned int x;
-    r_mask=x_vis->red_mask;
-    g_mask=x_vis->green_mask;
-    b_mask=x_vis->blue_mask;
-    for(r_shift=-8,x=1;x<r_mask;x=x<<1)r_shift++;
-    for(g_shift=-8,x=1;x<g_mask;x=x<<1)g_shift++;
-    for(b_shift=-8,x=1;x<b_mask;x=x<<1)b_shift++;
-    shiftmask_fl=1;
-}
-
-PIXEL xlib_rgb(int r,int g,int b)
-{
-    PIXEL p;
-    if(shiftmask_fl==0) shiftmask_init();
-    p=0;
-
-    if(r_shift>0) {
-        p=(r<<(r_shift))&r_mask;
-    } else if(r_shift<0) {
-        p=(r>>(-r_shift))&r_mask;
-    } else p|=(r&r_mask);
-
-    if(g_shift>0) {
-        p|=(g<<(g_shift))&g_mask;
-    } else if(g_shift<0) {
-        p|=(g>>(-g_shift))&g_mask;
-    } else p|=(g&g_mask);
-
-    if(b_shift>0) {
-        p|=(b<<(b_shift))&b_mask;
-    } else if(b_shift<0) {
-        p|=(b>>(-b_shift))&b_mask;
-    } else p|=(b&b_mask);
-
-    return p;
-}
-
-void st2_fixup( XImage *framebuf, int x, int y, int width, int height)
-{
-	int xi,yi;
-	unsigned char *src;
+	int x, y;
+	uchar *src;
 	PIXEL *dest;
 
-	if( (x<0)||(y<0) )return;
-
-	for (yi = y; yi < (y+height); yi++) {
-		src = &framebuf->data [yi * framebuf->bytes_per_line];
+	for(y = 0; y < vid.height; y++){
+		src = &framebuf[y*vid.rowbytes];
 		dest = (PIXEL*)src;
-		for(xi = (x+width-1); xi >= x; xi -= 8) {
-			dest[xi  ] = st2d_8to16table[src[xi  ]];
-			dest[xi-1] = st2d_8to16table[src[xi-1]];
-			dest[xi-2] = st2d_8to16table[src[xi-2]];
-			dest[xi-3] = st2d_8to16table[src[xi-3]];
-			dest[xi-4] = st2d_8to16table[src[xi-4]];
-			dest[xi-5] = st2d_8to16table[src[xi-5]];
-			dest[xi-6] = st2d_8to16table[src[xi-6]];
-			dest[xi-7] = st2d_8to16table[src[xi-7]];
-		}
-	}
-}
 
-// ========================================================================
-// makes a null cursor
-// ========================================================================
-
-static Cursor CreateNullCursor(Display *display, Window root)
-{
-    Pixmap cursormask; 
-    XGCValues xgc;
-    GC gc;
-    XColor dummycolour;
-    Cursor cursor;
-
-    cursormask = XCreatePixmap(display, root, 1, 1, 1/*depth*/);
-    xgc.function = GXclear;
-    gc =  XCreateGC(display, cursormask, GCFunction, &xgc);
-    XFillRectangle(display, cursormask, gc, 0, 0, 1, 1);
-    dummycolour.pixel = 0;
-    dummycolour.red = 0;
-    dummycolour.flags = 04;
-    cursor = XCreatePixmapCursor(display, cursormask, cursormask,
-          &dummycolour,&dummycolour, 0,0);
-    XFreePixmap(display,cursormask);
-    XFreeGC(display,gc);
-    return cursor;
-}
-
-void ResetFrameBuffer(void)
-{
-	int mem;
-	int pwidth;
-
-	if (x_framebuffer[0])
-	{
-		free(x_framebuffer[0]->data);
-		free(x_framebuffer[0]);
-	}
-
-// alloc an extra line in case we want to wrap, and allocate the z-buffer
-	pwidth = x_visinfo->depth / 8;
-	if (pwidth == 3) pwidth = 4;
-	mem = ((vid.width*pwidth+7)&~7) * vid.height;
-
-	x_framebuffer[0] = XCreateImage(	x_disp,
-		x_vis,
-		x_visinfo->depth,
-		ZPixmap,
-		0,
-		malloc(mem),
-		vid.width, vid.height,
-		32,
-		0);
-
-	if (!x_framebuffer[0])
-		Sys_Error("VID: XCreateImage failed\n");
-
-	vid.buffer = (byte*) (x_framebuffer[0]);
-}
-
-void ResetSharedFrameBuffers(void)
-{
-	int size;
-	int key;
-	int minsize = getpagesize();
-	int frm;
-
-	for (frm=0 ; frm<2 ; frm++)
-	{
-	// free up old frame buffer memory
-		if (x_framebuffer[frm])
-		{
-			XShmDetach(x_disp, &x_shminfo[frm]);
-			free(x_framebuffer[frm]);
-			shmdt(x_shminfo[frm].shmaddr);
+		/* vid.width % 8 not always 0
+		for(x = vid.width-1; x >= 0; x -= 8) {
+			dest[x  ] = st2d_8to24table[src[x  ]];
+			dest[x-1] = st2d_8to24table[src[x-1]];
+			dest[x-2] = st2d_8to24table[src[x-2]];
+			dest[x-3] = st2d_8to24table[src[x-3]];
+			dest[x-4] = st2d_8to24table[src[x-4]];
+			dest[x-5] = st2d_8to24table[src[x-5]];
+			dest[x-6] = st2d_8to24table[src[x-6]];
+			dest[x-7] = st2d_8to24table[src[x-7]];
 		}
+		*/
 
-	// create the image
-		x_framebuffer[frm] = XShmCreateImage(	x_disp,
-						x_vis,
-						x_visinfo->depth,
-						ZPixmap,
-						0,
-						&x_shminfo[frm],
-						vid.width,
-						vid.height );
-
-	// grab shared memory
-
-		size = x_framebuffer[frm]->bytes_per_line
-			* x_framebuffer[frm]->height;
-		if (size < minsize)
-			Sys_Error("VID: Window must use at least %d bytes\n", minsize);
-
-		key = random();
-		x_shminfo[frm].shmid = shmget((key_t)key, size, IPC_CREAT|0777);
-		if (x_shminfo[frm].shmid==-1)
-			Sys_Error("VID: Could not get any shared memory\n");
-
-		// attach to the shared memory segment
-		x_shminfo[frm].shmaddr =
-			(void *) shmat(x_shminfo[frm].shmid, 0, 0);
-
-		ri.Con_Printf(PRINT_ALL, 
-			"MITSHM shared memory (id=%d, addr=0x%lx)\n", 
-			x_shminfo[frm].shmid,
-			(long) x_shminfo[frm].shmaddr);
-
-		x_framebuffer[frm]->data = x_shminfo[frm].shmaddr;
-
-	// get the X server to attach to it
-
-		if (!XShmAttach(x_disp, &x_shminfo[frm]))
-			Sys_Error("VID: XShmAttach() failed\n");
-		XSync(x_disp, 0);
-		shmctl(x_shminfo[frm].shmid, IPC_RMID, 0);
+		for(x = vid.width-1; x >= 0; x--)
+			dest[x] = st2d_8to24table[src[x]];
 	}
-
 }
 
-// ========================================================================
-// Tragic death handler
-// ========================================================================
-
-void TragicDeath(int signal_num)
+void resetfb (void)
 {
-	XAutoRepeatOn(x_disp);
-	XCloseDisplay(x_disp);
-	Sys_Error("This death brought to you by the number %d\n", signal_num);
-}
-
-int XLateKey(XKeyEvent *ev)
-{
-
-	int key;
-	char buf[64];
-	KeySym keysym;
-
-	key = 0;
-
-	XLookupString(ev, buf, sizeof buf, &keysym, 0);
-
-	switch(keysym)
-	{
-		case XK_KP_Page_Up:	 key = K_KP_PGUP; break;
-		case XK_Page_Up:	 key = K_PGUP; break;
-
-		case XK_KP_Page_Down: key = K_KP_PGDN; break;
-		case XK_Page_Down:	 key = K_PGDN; break;
-
-		case XK_KP_Home: key = K_KP_HOME; break;
-		case XK_Home:	 key = K_HOME; break;
-
-		case XK_KP_End:  key = K_KP_END; break;
-		case XK_End:	 key = K_END; break;
-
-		case XK_KP_Left: key = K_KP_LEFTARROW; break;
-		case XK_Left:	 key = K_LEFTARROW; break;
-
-		case XK_KP_Right: key = K_KP_RIGHTARROW; break;
-		case XK_Right:	key = K_RIGHTARROW;		break;
-
-		case XK_KP_Down: key = K_KP_DOWNARROW; break;
-		case XK_Down:	 key = K_DOWNARROW; break;
-
-		case XK_KP_Up:   key = K_KP_UPARROW; break;
-		case XK_Up:		 key = K_UPARROW;	 break;
-
-		case XK_Escape: key = K_ESCAPE;		break;
-
-		case XK_KP_Enter: key = K_KP_ENTER;	break;
-		case XK_Return: key = K_ENTER;		 break;
-
-		case XK_Tab:		key = K_TAB;			 break;
-
-		case XK_F1:		 key = K_F1;				break;
-
-		case XK_F2:		 key = K_F2;				break;
-
-		case XK_F3:		 key = K_F3;				break;
-
-		case XK_F4:		 key = K_F4;				break;
-
-		case XK_F5:		 key = K_F5;				break;
-
-		case XK_F6:		 key = K_F6;				break;
-
-		case XK_F7:		 key = K_F7;				break;
-
-		case XK_F8:		 key = K_F8;				break;
-
-		case XK_F9:		 key = K_F9;				break;
-
-		case XK_F10:		key = K_F10;			 break;
-
-		case XK_F11:		key = K_F11;			 break;
-
-		case XK_F12:		key = K_F12;			 break;
-
-		case XK_BackSpace: key = K_BACKSPACE; break;
-
-		case XK_KP_Delete: key = K_KP_DEL; break;
-		case XK_Delete: key = K_DEL; break;
-
-		case XK_Pause:	key = K_PAUSE;		 break;
-
-		case XK_Shift_L:
-		case XK_Shift_R:	key = K_SHIFT;		break;
-
-		case XK_Execute: 
-		case XK_Control_L: 
-		case XK_Control_R:	key = K_CTRL;		 break;
-
-		case XK_Alt_L:	
-		case XK_Meta_L: 
-		case XK_Alt_R:	
-		case XK_Meta_R: key = K_ALT;			break;
-
-		case XK_KP_Begin: key = K_KP_5;	break;
-
-		case XK_Insert:key = K_INS; break;
-		case XK_KP_Insert: key = K_KP_INS; break;
-
-		case XK_KP_Multiply: key = '*'; break;
-		case XK_KP_Add:  key = K_KP_PLUS; break;
-		case XK_KP_Subtract: key = K_KP_MINUS; break;
-		case XK_KP_Divide: key = K_KP_SLASH; break;
-
-#if 0
-		case 0x021: key = '1';break;/* [!] */
-		case 0x040: key = '2';break;/* [@] */
-		case 0x023: key = '3';break;/* [#] */
-		case 0x024: key = '4';break;/* [$] */
-		case 0x025: key = '5';break;/* [%] */
-		case 0x05e: key = '6';break;/* [^] */
-		case 0x026: key = '7';break;/* [&] */
-		case 0x02a: key = '8';break;/* [*] */
-		case 0x028: key = '9';;break;/* [(] */
-		case 0x029: key = '0';break;/* [)] */
-		case 0x05f: key = '-';break;/* [_] */
-		case 0x02b: key = '=';break;/* [+] */
-		case 0x07c: key = '\'';break;/* [|] */
-		case 0x07d: key = '[';break;/* [}] */
-		case 0x07b: key = ']';break;/* [{] */
-		case 0x022: key = '\'';break;/* ["] */
-		case 0x03a: key = ';';break;/* [:] */
-		case 0x03f: key = '/';break;/* [?] */
-		case 0x03e: key = '.';break;/* [>] */
-		case 0x03c: key = ',';break;/* [<] */
-#endif
-
-		default:
-			key = *(unsigned char*)buf;
-			if (key >= 'A' && key <= 'Z')
-				key = key - 'A' + 'a';
-			break;
-	} 
-
-	return key;
-}
-
-void GetEvent(void)
-{
-	XEvent x_event;
-	int b;
-   
-	XNextEvent(x_disp, &x_event);
-	switch(x_event.type) {
-	case KeyPress:
-		keyq[keyq_head].key = XLateKey(&x_event.xkey);
-		keyq[keyq_head].down = true;
-		keyq_head = (keyq_head + 1) & 63;
-		break;
-	case KeyRelease:
-		keyq[keyq_head].key = XLateKey(&x_event.xkey);
-		keyq[keyq_head].down = false;
-		keyq_head = (keyq_head + 1) & 63;
-		break;
-
-	case MotionNotify:
-		if (_windowed_mouse->value) {
-			mx += ((int)x_event.xmotion.x - (int)(vid.width/2));
-			my += ((int)x_event.xmotion.y - (int)(vid.height/2));
-
-			/* move the mouse to the window center again */
-			XSelectInput(x_disp,x_win, STD_EVENT_MASK & ~PointerMotionMask);
-			XWarpPointer(x_disp,None,x_win,0,0,0,0, 
-				(vid.width/2),(vid.height/2));
-			XSelectInput(x_disp,x_win, STD_EVENT_MASK);
-		} else {
-			mx = ((int)x_event.xmotion.x - (int)p_mouse_x);
-			my = ((int)x_event.xmotion.y - (int)p_mouse_y);
-			p_mouse_x=x_event.xmotion.x;
-			p_mouse_y=x_event.xmotion.y;
-		}
-		break;
-
-	case ButtonPress:
-		b=-1;
-		if (x_event.xbutton.button == 1)
-			b = 0;
-		else if (x_event.xbutton.button == 2)
-			b = 2;
-		else if (x_event.xbutton.button == 3)
-			b = 1;
-		if (b>=0)
-			mouse_buttonstate |= 1<<b;
-		break;
-
-	case ButtonRelease:
-		b=-1;
-		if (x_event.xbutton.button == 1)
-			b = 0;
-		else if (x_event.xbutton.button == 2)
-			b = 2;
-		else if (x_event.xbutton.button == 3)
-			b = 1;
-		if (b>=0)
-			mouse_buttonstate &= ~(1<<b);
-		break;
-	
-	case ConfigureNotify:
-		config_notify_width = x_event.xconfigure.width;
-		config_notify_height = x_event.xconfigure.height;
-		config_notify = 1;
-		break;
-
-	default:
-		if (doShm && x_event.type == x_shmeventtype)
-			oktodraw = true;
+	vid.width = Dx(screen->r);
+	vid.height = Dy(screen->r);
+	if(framebuf != nil){
+		free(framebuf);
+		framebuf = nil;
 	}
-   
-	if (old_windowed_mouse != _windowed_mouse->value) {
-		old_windowed_mouse = _windowed_mouse->value;
-
-		if (!_windowed_mouse->value) {
-			/* ungrab the pointer */
-			XUngrabPointer(x_disp,CurrentTime);
-		} else {
-			/* grab the pointer */
-			XGrabPointer(x_disp,x_win,True,0,GrabModeAsync,
-				GrabModeAsync,x_win,None,CurrentTime);
-		}
+	if(fbim != nil){
+		freeimage(fbim);
+		fbim = nil;
 	}
+	if((framebuf = malloc(sizeof *framebuf * vid.width * vid.height * screen->depth/8)) == nil)
+		sysfatal("resetfb:malloc: %r");
+	if((fbim = allocimage(display, Rect(0, 0, vid.width, vid.height), screen->chan, 1, DNofill)) == nil)
+		sysfatal("resetfb: %r");
+	vid.buffer = framebuf;
+	vid.rowbytes = vid.width * screen->depth/8;
+	center = addpt(screen->r.min, Pt(vid.width/2, vid.height/2));
+	sw_mode->modified = true;	/* make ref_soft refresh its shit */
 }
 
-/*****************************************************************************/
-
-/*
-** SWimp_Init
-**
-** This routine is responsible for initializing the implementation
-** specific stuff in a software rendering subsystem.
-*/
-int SWimp_Init( void *hInstance, void *wndProc )
+int SWimp_Init (void */*hInstance*/, void */*wndProc*/)
 {
-// open the display
-	x_disp = XOpenDisplay(0);
-	if (!x_disp)
-	{
-		if (getenv("DISPLAY"))
-			Sys_Error("VID: Could not open display [%s]\n",
-				getenv("DISPLAY"));
-		else
-			Sys_Error("VID: Could not open local display\n");
-	}
+	srand(getpid());
 
-// catch signals so i can turn on auto-repeat
-
-	{
-		struct sigaction sa;
-		sigaction(SIGINT, 0, &sa);
-		sa.sa_handler = TragicDeath;
-		sigaction(SIGINT, &sa, 0);
-		sigaction(SIGTERM, &sa, 0);
-	}
-
+	if(initdraw(nil, nil, "quake2") < 0)
+		sysfatal("VID_Init:initdraw: %r\n");
+	resetfb();
+	rwon = true;
 	return true;
 }
 
-/*
-** SWimp_InitGraphics
-**
-** This initializes the software refresh's implementation specific
-** graphics subsystem.  In the case of Windows it creates DIB or
-** DDRAW surfaces.
-**
-** The necessary width and height parameters are grabbed from
-** vid.width and vid.height.
-*/
-static qboolean SWimp_InitGraphics( qboolean fullscreen )
-{
-	int pnum, i;
-	XVisualInfo template;
-	int num_visuals;
-	int template_mask;
-
-	srandom(getpid());
-
-	// free resources in use
-	SWimp_Shutdown ();
-
-	// let the sound and input subsystems know about the new window
-	ri.Vid_NewWindow (vid.width, vid.height);
-
-	XAutoRepeatOff(x_disp);
-
-// for debugging only
-	XSynchronize(x_disp, True);
-
-// check for command-line window size
-	template_mask = 0;
-
-#if 0
-// specify a visual id
-	if ((pnum=COM_CheckParm("-visualid")))
-	{
-		if (pnum >= com_argc-1)
-			Sys_Error("VID: -visualid <id#>\n");
-		template.visualid = Q_atoi(com_argv[pnum+1]);
-		template_mask = VisualIDMask;
-	}
-
-// If not specified, use default visual
-	else
-#endif
-	{
-		int screen;
-		screen = XDefaultScreen(x_disp);
-		template.visualid =
-			XVisualIDFromVisual(XDefaultVisual(x_disp, screen));
-		template_mask = VisualIDMask;
-	}
-
-// pick a visual- warn if more than one was available
-	x_visinfo = XGetVisualInfo(x_disp, template_mask, &template, &num_visuals);
-	if (num_visuals > 1)
-	{
-		printf("Found more than one visual id at depth %d:\n", template.depth);
-		for (i=0 ; i<num_visuals ; i++)
-			printf("	-visualid %d\n", (int)(x_visinfo[i].visualid));
-	}
-	else if (num_visuals == 0)
-	{
-		if (template_mask == VisualIDMask)
-			Sys_Error("VID: Bad visual id %d\n", template.visualid);
-		else
-			Sys_Error("VID: No visuals at depth %d\n", template.depth);
-	}
-
-#if 0
-	if (verbose)
-	{
-		printf("Using visualid %d:\n", (int)(x_visinfo->visualid));
-		printf("	screen %d\n", x_visinfo->screen);
-		printf("	red_mask 0x%x\n", (int)(x_visinfo->red_mask));
-		printf("	green_mask 0x%x\n", (int)(x_visinfo->green_mask));
-		printf("	blue_mask 0x%x\n", (int)(x_visinfo->blue_mask));
-		printf("	colormap_size %d\n", x_visinfo->colormap_size);
-		printf("	bits_per_rgb %d\n", x_visinfo->bits_per_rgb);
-	}
-#endif
-
-	x_vis = x_visinfo->visual;
-
-// setup attributes for main window
-	{
-	   int attribmask = CWEventMask  | CWColormap | CWBorderPixel;
-	   XSetWindowAttributes attribs;
-	   Colormap tmpcmap;
-	   
-	   tmpcmap = XCreateColormap(x_disp, XRootWindow(x_disp,
-							 x_visinfo->screen), x_vis, AllocNone);
-	   
-	   attribs.event_mask = STD_EVENT_MASK;
-	   attribs.border_pixel = 0;
-	   attribs.colormap = tmpcmap;
-
-// create the main window
-		x_win = XCreateWindow(	x_disp,
-			XRootWindow(x_disp, x_visinfo->screen),
-			0, 0,	// x, y
-			vid.width, vid.height,
-			0, // borderwidth
-			x_visinfo->depth,
-			InputOutput,
-			x_vis,
-			attribmask,
-			&attribs );
-		XStoreName(x_disp, x_win, "Quake II");
-
-		if (x_visinfo->class != TrueColor)
-			XFreeColormap(x_disp, tmpcmap);
-	}
-
-	if (x_visinfo->depth == 8)
-	{
-	// create and upload the palette
-		if (x_visinfo->class == PseudoColor)
-		{
-			x_cmap = XCreateColormap(x_disp, x_win, x_vis, AllocAll);
-			XSetWindowColormap(x_disp, x_win, x_cmap);
-		}
-
-	}
-
-// inviso cursor
-	XDefineCursor(x_disp, x_win, CreateNullCursor(x_disp, x_win));
-
-// create the GC
-	{
-		XGCValues xgcvalues;
-		int valuemask = GCGraphicsExposures;
-		xgcvalues.graphics_exposures = False;
-		x_gc = XCreateGC(x_disp, x_win, valuemask, &xgcvalues );
-	}
-
-// map the window
-	XMapWindow(x_disp, x_win);
-
-// wait for first exposure event
-	{
-		XEvent event;
-		do
-		{
-			XNextEvent(x_disp, &event);
-			if (event.type == Expose && !event.xexpose.count)
-				oktodraw = true;
-		} while (!oktodraw);
-	}
-// now safe to draw
-
-// even if MITSHM is available, make sure it's a local connection
-	if (XShmQueryExtension(x_disp))
-	{
-		char *displayname;
-		doShm = true;
-		displayname = (char *) getenv("DISPLAY");
-		if (displayname)
-		{
-			char *d = displayname;
-			while (*d && (*d != ':')) d++;
-			if (*d) *d = 0;
-			if (!(!strcasecmp(displayname, "unix") || !*displayname))
-				doShm = false;
-		}
-	}
-
-	if (doShm)
-	{
-		x_shmeventtype = XShmGetEventBase(x_disp) + ShmCompletion;
-		ResetSharedFrameBuffers();
-	}
-	else
-		ResetFrameBuffer();
-
-	current_framebuffer = 0;
-	vid.rowbytes = x_framebuffer[0]->bytes_per_line;
-	vid.buffer = x_framebuffer[0]->data;
-
-//	XSynchronize(x_disp, False);
-
-	X11_active = true;
-
-	return true;
-}
-
-/*
-** SWimp_EndFrame
-**
-** This does an implementation specific copy from the backbuffer to the
-** front buffer.  In the Win32 case it uses BitBlt or BltFast depending
-** on whether we're using DIB sections/GDI or DDRAW.
-*/
+/* copy backbuffer to front buffer */
 void SWimp_EndFrame (void)
 {
-// if the window changes dimension, skip this frame
-#if 0
-	if (config_notify)
-	{
-		fprintf(stderr, "config notify\n");
-		config_notify = 0;
-		vid.width = config_notify_width & ~7;
-		vid.height = config_notify_height;
-		if (doShm)
-			ResetSharedFrameBuffers();
-		else
-			ResetFrameBuffer();
-		vid.rowbytes = x_framebuffer[0]->bytes_per_line;
-		vid.buffer = x_framebuffer[current_framebuffer]->data;
-		vid.recalc_refdef = 1;				// force a surface cache flush
-		Con_CheckResize();
-		Con_Clear_f();
+	if(resized){		/* skip frame if window resizes */
+		resized = 0;
+		if(getwindow(display, Refnone) < 0)
+			sysfatal("SWimp_EndFrame:getwindow: %r\n");
+		resetfb();
 		return;
 	}
-#endif
-
-	if (doShm)
-	{
-
-		if (x_visinfo->depth != 8)
-			st2_fixup( x_framebuffer[current_framebuffer], 
-				0, 0, vid.width, vid.height);	
-		if (!XShmPutImage(x_disp, x_win, x_gc,
-			x_framebuffer[current_framebuffer], 0, 0,
-			0, 0, vid.width, vid.height, True))
-				Sys_Error("VID_Update: XShmPutImage failed\n");
-		oktodraw = false;
-		while (!oktodraw) 
-			GetEvent();
-		current_framebuffer = !current_framebuffer;
-		vid.buffer = x_framebuffer[current_framebuffer]->data;
-		XSync(x_disp, False);
-	}
-	else
-	{
-		if (x_visinfo->depth != 8)
-			st2_fixup( x_framebuffer[current_framebuffer], 
-				0, 0, vid.width, vid.height);
-		XPutImage(x_disp, x_win, x_gc, x_framebuffer[0],
-			0, 0, 0, 0, vid.width, vid.height);
-		XSync(x_disp, False);
-	}
+	st3_fixup();
+	loadimage(fbim, fbim->r, framebuf, vid.height * vid.rowbytes);
+	draw(screen, screen->r, fbim, nil, ZP);
+	flushimage(display, 1);
 }
 
-/*
-** SWimp_SetMode
-*/
-rserr_t SWimp_SetMode( int *pwidth, int *pheight, int mode, qboolean fullscreen )
+rserr_t SWimp_SetMode (int */*pwidth*/, int */*pheight*/, int /*mode*/, qboolean /*fullscreen*/)
 {
-	rserr_t retval = rserr_ok;
-
-	ri.Con_Printf (PRINT_ALL, "setting mode %d:", mode );
-
-	if ( !ri.Vid_GetModeInfo( pwidth, pheight, mode ) )
-	{
-		ri.Con_Printf( PRINT_ALL, " invalid mode\n" );
-		return rserr_invalid_mode;
-	}
-
-	ri.Con_Printf( PRINT_ALL, " %d %d\n", *pwidth, *pheight);
-
-	if ( !SWimp_InitGraphics( false ) ) {
-		// failed to set a valid mode in windowed mode
-		return rserr_invalid_mode;
-	}
-
-	R_GammaCorrectAndSetPalette( ( const unsigned char * ) d_8to24table );
-
-	return retval;
+	return rserr_ok;
 }
 
-/*
-** SWimp_SetPalette
-**
-** System specific palette setting routine.  A NULL palette means
-** to use the existing palette.  The palette is expected to be in
-** a padded 4-byte xRGB format.
-*/
-void SWimp_SetPalette( const unsigned char *palette )
+/* nil palette == use existing; palette is expected to be in padded 4-byte xRGB format */
+void SWimp_SetPalette (uchar *palette)
 {
 	int i;
-	XColor colors[256];
 
-	if (!X11_active)
+	if(!rwon)
 		return;
-
-    if ( !palette )
-        palette = ( const unsigned char * ) sw_state.currentpalette;
- 
-	for(i=0;i<256;i++)
-		st2d_8to16table[i]= xlib_rgb(palette[i*4],
-			palette[i*4+1],palette[i*4+2]);
-
-	if (x_visinfo->class == PseudoColor && x_visinfo->depth == 8)
-	{
-		for (i=0 ; i<256 ; i++)
-		{
-			colors[i].pixel = i;
-			colors[i].flags = DoRed|DoGreen|DoBlue;
-			colors[i].red = palette[i*4] * 257;
-			colors[i].green = palette[i*4+1] * 257;
-			colors[i].blue = palette[i*4+2] * 257;
-		}
-		XStoreColors(x_disp, x_cmap, colors, 256);
-	}
+	if(!palette)
+        	palette = (uchar *)sw_state.currentpalette;
+	for(i = 0; i < 256; i++)
+		st2d_8to24table[i] = rgb24(palette[i*4], palette[i*4+1], palette[i*4+2]);
 }
 
-/*
-** SWimp_Shutdown
-**
-** System specific graphics subsystem shutdown routine.  Destroys
-** DIBs or DDRAW surfaces as appropriate.
-*/
-void SWimp_Shutdown( void )
+void SWimp_Shutdown (void)
 {
-	int i;
-
-	if (!X11_active)
+	if(!rwon)
 		return;
-
-	if (doShm) {
-		for (i = 0; i < 2; i++)
-			if (x_framebuffer[i]) {
-				XShmDetach(x_disp, &x_shminfo[i]);
-				free(x_framebuffer[i]);
-				shmdt(x_shminfo[i].shmaddr);
-				x_framebuffer[i] = NULL;
-			}
-	} else if (x_framebuffer[0]) {
-		free(x_framebuffer[0]->data);
-		free(x_framebuffer[0]);
-		x_framebuffer[0] = NULL;
-	}
-
-	XDestroyWindow(	x_disp, x_win );
-
-	XAutoRepeatOn(x_disp);
-//	XCloseDisplay(x_disp);
-
-	X11_active = false;
+	if(framebuf != nil)
+		free(framebuf);
+	if(fbim != nil)
+		freeimage(fbim);
+	rwon = false;
 }
 
-/*
-** SWimp_AppActivate
-*/
-void SWimp_AppActivate( qboolean active )
+void SWimp_AppActivate (qboolean /*active*/)
 {
 }
-
-//===============================================================================
-
-/*
-================
-Sys_MakeCodeWriteable
-================
-*/
-void Sys_MakeCodeWriteable (unsigned long startaddr, unsigned long length)
-{
-
-	int r;
-	unsigned long addr;
-	int psize = getpagesize();
-
-	addr = (startaddr & ~(psize-1)) - psize;
-
-//	fprintf(stderr, "writable code %lx(%lx)-%lx, length=%lx\n", startaddr,
-//			addr, startaddr+length, length);
-
-	r = mprotect((char*)addr, length + startaddr - addr + psize, 7);
-
-	if (r < 0)
-    		Sys_Error("Protection change failed\n");
-
-}
-
-/*****************************************************************************/
-/* KEYBOARD                                                                  */
-/*****************************************************************************/
-
-Key_Event_fp_t Key_Event_fp;
-
-void KBD_Init(Key_Event_fp_t fp)
-{
-	Key_Event_fp = fp;
-}
-
-void KBD_Update(void)
-{
-// get events from x server
-	if (x_disp)
-	{
-		while (XPending(x_disp)) 
-			GetEvent();
-		while (keyq_head != keyq_tail)
-		{
-			Key_Event_fp(keyq[keyq_tail].key, keyq[keyq_tail].down);
-			keyq_tail = (keyq_tail + 1) & 63;
-		}
-	}
-}
-
-void KBD_Close(void)
-{
-}
-
-
--- a/plan9/rw_linux.h
+++ /dev/null
@@ -1,16 +1,0 @@
-
-
-typedef void (*Key_Event_fp_t)(int key, qboolean down);
-
-extern void (*KBD_Update_fp)(void);
-extern void (*KBD_Init_fp)(Key_Event_fp_t fp);
-extern void (*KBD_Close_fp)(void);
-
-typedef struct in_state {
-	// Pointers to functions back in client, set by vid_so
-	void (*IN_CenterView_fp)(void);
-	Key_Event_fp_t Key_Event_fp;
-	vec_t *viewangles;
-	int *in_strafe_state;
-} in_state_t;
-
--- a/plan9/snd_9.c
+++ b/plan9/snd_9.c
@@ -1,266 +1,123 @@
-#include <unistd.h>
-#include <fcntl.h>
-#include <stdlib.h>
-#include <sys/types.h>
-#include <sys/ioctl.h>
-#include <sys/mman.h>
-#include <sys/shm.h>
-#include <sys/wait.h>
-#include <linux/soundcard.h>
+#include <u.h>
+#include <libc.h>
 #include <stdio.h>
+#include <thread.h>
+#include "../dat.h"
+#include "../fns.h"
 
-#include "../client/client.h"
-#include "../client/snd_loc.h"
+int sndon;
 
+enum{
+	Nbuf	= 32
+};
 int audio_fd;
-int snd_inited;
+int wpos;
+int stid = -1;
+Channel *schan;
 
 cvar_t *sndbits;
 cvar_t *sndspeed;
 cvar_t *sndchannels;
 cvar_t *snddevice;
+cvar_t *nosound;
 
-static int tryrates[] = { 11025, 22051, 44100, 8000 };
 
-qboolean SNDDMA_Init(void)
+void sproc (void *)
 {
+	int n;
 
-	int rc;
-    int fmt;
-	int tmp;
-    int i;
-    char *s;
-	struct audio_buf_info info;
-	int caps;
-	extern uid_t saved_euid;
+	for(;;){
+		if(recv(schan, nil) < 0){
+			fprint(2, "sproc:recv %r\n");
+			break;
+		}
+		if((n = write(audio_fd, dma.buffer, dma.samplebits/8 * dma.samples)) < 0){
+			fprint(2, "sproc:write %r\n");
+			break;
+		}
+		wpos += n;
+	}
+	stid = -1;
+}
 
-	if (snd_inited)
-		return;
+qboolean SNDDMA_Init(void)
+{
+	if(sndon)
+		return false;
 
-	if (!snddevice) {
+	if(COM_CheckParm("-nosound"))	/* FIXME */
+		return false;
+
+	if(!snddevice){
 		sndbits = Cvar_Get("sndbits", "16", CVAR_ARCHIVE);
-		sndspeed = Cvar_Get("sndspeed", "0", CVAR_ARCHIVE);
+		sndspeed = Cvar_Get("sndspeed", "44100", CVAR_ARCHIVE);
 		sndchannels = Cvar_Get("sndchannels", "2", CVAR_ARCHIVE);
-		snddevice = Cvar_Get("snddevice", "/dev/dsp", CVAR_ARCHIVE);
+		snddevice = Cvar_Get("snddevice", "/dev/audio", CVAR_ARCHIVE);
 	}
 
-// open /dev/dsp, confirm capability to mmap, and get size of dma buffer
-
-	if (!audio_fd) {
-		seteuid(saved_euid);
-
-		audio_fd = open(snddevice->string, O_RDWR);
-
-		seteuid(getuid());
-
-		if (audio_fd < 0)
-		{
-			perror(snddevice->string);
-			Com_Printf("Could not open %s\n", snddevice->string);
-			return 0;
-		}
+	if((audio_fd = open(snddevice->string, OWRITE)) < 0){
+		fprint(2, "SNDDMA_Init:open %r\n");
+		return false;
 	}
 
-    rc = ioctl(audio_fd, SNDCTL_DSP_RESET, 0);
-    if (rc < 0)
-	{
-		perror(snddevice->string);
-		Com_Printf("Could not reset %s\n", snddevice->string);
-		close(audio_fd);
-		return 0;
-	}
-
-	if (ioctl(audio_fd, SNDCTL_DSP_GETCAPS, &caps)==-1)
-	{
-		perror(snddevice->string);
-        Com_Printf("Sound driver too old\n");
-		close(audio_fd);
-		return 0;
-	}
-
-	if (!(caps & DSP_CAP_TRIGGER) || !(caps & DSP_CAP_MMAP))
-	{
-		Com_Printf("Sorry but your soundcard can't do this\n");
-		close(audio_fd);
-		return 0;
-	}
-
-    if (ioctl(audio_fd, SNDCTL_DSP_GETOSPACE, &info)==-1)
-    {   
-        perror("GETOSPACE");
-		Com_Printf("Um, can't do GETOSPACE?\n");
-		close(audio_fd);
-		return 0;
-    }
-    
-// set sample bits & speed
-
-    dma.samplebits = (int)sndbits->value;
-	if (dma.samplebits != 16 && dma.samplebits != 8)
-    {
-        ioctl(audio_fd, SNDCTL_DSP_GETFMTS, &fmt);
-        if (fmt & AFMT_S16_LE) dma.samplebits = 16;
-        else if (fmt & AFMT_U8) dma.samplebits = 8;
-    }
-
+	dma.samplebits = (int)sndbits->value;
+	if(dma.samplebits != 16 && dma.samplebits != 8)
+		dma.samplebits = 16;
 	dma.speed = (int)sndspeed->value;
-	if (!dma.speed) {
-        for (i=0 ; i<sizeof(tryrates)/4 ; i++)
-            if (!ioctl(audio_fd, SNDCTL_DSP_SPEED, &tryrates[i])) break;
-        dma.speed = tryrates[i];
-    }
-
+	if(dma.speed != 44100)
+		dma.speed = 44100;
 	dma.channels = (int)sndchannels->value;
-	if (dma.channels < 1 || dma.channels > 2)
+	if(dma.channels < 1 || dma.channels > 2)
 		dma.channels = 2;
-	
-	dma.samples = info.fragstotal * info.fragsize / (dma.samplebits/8);
+	dma.samples = 1024;
 	dma.submission_chunk = 1;
-
-// memory map the dma buffer
-
-	if (!dma.buffer)
-		dma.buffer = (unsigned char *) mmap(NULL, info.fragstotal
-			* info.fragsize, PROT_WRITE, MAP_FILE|MAP_SHARED, audio_fd, 0);
-	if (!dma.buffer)
-	{
-		perror(snddevice->string);
-		Com_Printf("Could not mmap %s\n", snddevice->string);
-		close(audio_fd);
-		return 0;
-	}
-
-	tmp = 0;
-	if (dma.channels == 2)
-		tmp = 1;
-    rc = ioctl(audio_fd, SNDCTL_DSP_STEREO, &tmp);
-    if (rc < 0)
-    {
-		perror(snddevice->string);
-        Com_Printf("Could not set %s to stereo=%d", snddevice->string, dma.channels);
-		close(audio_fd);
-        return 0;
-    }
-	if (tmp)
-		dma.channels = 2;
-	else
-		dma.channels = 1;
-
-    rc = ioctl(audio_fd, SNDCTL_DSP_SPEED, &dma.speed);
-    if (rc < 0)
-    {
-		perror(snddevice->string);
-        Com_Printf("Could not set %s speed to %d", snddevice->string, dma.speed);
-		close(audio_fd);
-        return 0;
-    }
-
-    if (dma.samplebits == 16)
-    {
-        rc = AFMT_S16_LE;
-        rc = ioctl(audio_fd, SNDCTL_DSP_SETFMT, &rc);
-        if (rc < 0)
-		{
-			perror(snddevice->string);
-			Com_Printf("Could not support 16-bit data.  Try 8-bit.\n");
-			close(audio_fd);
-			return 0;
-		}
-    }
-    else if (dma.samplebits == 8)
-    {
-        rc = AFMT_U8;
-        rc = ioctl(audio_fd, SNDCTL_DSP_SETFMT, &rc);
-        if (rc < 0)
-		{
-			perror(snddevice->string);
-			Com_Printf("Could not support 8-bit data.\n");
-			close(audio_fd);
-			return 0;
-		}
-    }
-	else
-	{
-		perror(snddevice->string);
-		Com_Printf("%d-bit sound not supported.", dma.samplebits);
-		close(audio_fd);
-		return 0;
-	}
-
-// toggle the trigger & start her up
-
-    tmp = 0;
-    rc  = ioctl(audio_fd, SNDCTL_DSP_SETTRIGGER, &tmp);
-	if (rc < 0)
-	{
-		perror(snddevice->string);
-		Com_Printf("Could not toggle.\n");
-		close(audio_fd);
-		return 0;
-	}
-    tmp = PCM_ENABLE_OUTPUT;
-    rc = ioctl(audio_fd, SNDCTL_DSP_SETTRIGGER, &tmp);
-	if (rc < 0)
-	{
-		perror(snddevice->string);
-		Com_Printf("Could not toggle.\n");
-		close(audio_fd);
-		return 0;
-	}
-
+	if((dma.buffer = mallocz(dma.samplebits/8 * dma.samples, 1)) == nil)
+		sysfatal("SNDDMA_Init:mallocz: %r\n");
 	dma.samplepos = 0;
+	sndon = 1;
 
-	snd_inited = 1;
-	return 1;
-
+	schan = chancreate(sizeof(int), Nbuf);
+	if((stid = proccreate(sproc, nil, 8192)) < 0){
+		stid = -1;
+		SNDDMA_Shutdown();
+		sysfatal("SNDDMA_Init:proccreate: %r\n");
+	}
+	return true;
 }
 
 int SNDDMA_GetDMAPos(void)
 {
-
-	struct count_info count;
-
-	if (!snd_inited) return 0;
-
-	if (ioctl(audio_fd, SNDCTL_DSP_GETOPTR, &count)==-1)
-	{
-		perror(snddevice->string);
-		Com_Printf("Uh, sound dead.\n");
-		close(audio_fd);
-		snd_inited = 0;
+	if(!sndon)
 		return 0;
-	}
-//	dma.samplepos = (count.bytes / (dma.samplebits / 8)) & (dma.samples-1);
-//	fprintf(stderr, "%d    \r", count.ptr);
-	dma.samplepos = count.ptr / (dma.samplebits / 8);
-
+	dma.samplepos = wpos / (dma.samplebits/8);
 	return dma.samplepos;
-
 }
 
 void SNDDMA_Shutdown(void)
 {
-#if 0
-	if (snd_inited)
-	{
-		close(audio_fd);
-		snd_inited = 0;
+	if(!sndon)
+		return;
+	if(stid != -1){
+		threadkill(stid);
+		stid = -1;
 	}
-#endif
+	if(schan != nil){
+		chanfree(schan);
+		schan = nil;
+	}
+	free(dma.buffer);
+	close(audio_fd);
+	sndon = 0;
 }
 
-/*
-==============
-SNDDMA_Submit
-
-Send sound to device if buffer isn't really the dma buffer
-===============
-*/
 void SNDDMA_Submit(void)
 {
+	if(nbsend(schan, nil) < 0){
+		fprint(2, "SNDDMA_Submit:nbsend: %r\n");
+		SNDDMA_Shutdown();
+	}
 }
 
 void SNDDMA_BeginPainting (void)
 {
 }
-
--- a/plan9/sys_9.c
+++ b/plan9/sys_9.c
@@ -1,253 +1,89 @@
-#include <unistd.h>
-#include <signal.h>
-#include <stdlib.h>
-#include <limits.h>
-#include <sys/time.h>
-#include <sys/types.h>
-#include <unistd.h>
-#include <fcntl.h>
-#include <stdarg.h>
+#include <u.h>
+#include <libc.h>
 #include <stdio.h>
-#include <sys/ipc.h>
-#include <sys/shm.h>
-#include <sys/stat.h>
-#include <string.h>
 #include <ctype.h>
-#include <sys/wait.h>
-#include <sys/mman.h>
-#include <errno.h>
-#include <mntent.h>
+#include <thread.h>
+#include "../dat.h"
+#include "../fns.h"
 
-#include <dlfcn.h>
+mainstacksize = 512*1024;	/* FIXME */
 
-#include "../qcommon/qcommon.h"
-
-#include "../linux/rw_linux.h"
-
 cvar_t *nostdout;
-
-unsigned	sys_frame_time;
-
-uid_t saved_euid;
+uint sys_frame_time;
 qboolean stdin_active = true;
 
-// =======================================================================
-// General routines
-// =======================================================================
+void KBD_Update(void);
 
+
+/* prints to "debugging console" */
 void Sys_ConsoleOutput (char *string)
 {
-	if (nostdout && nostdout->value)
+	if(nostdout != nil && nostdout->value)
 		return;
-
-	fputs(string, stdout);
+	print("%s", string);
 }
 
-void Sys_Printf (char *fmt, ...)
-{
-	va_list		argptr;
-	char		text[1024];
-	unsigned char		*p;
-
-	va_start (argptr,fmt);
-	vsprintf (text,fmt,argptr);
-	va_end (argptr);
-
-	if (strlen(text) > sizeof(text))
-		Sys_Error("memory overwrite in Sys_Printf");
-
-    if (nostdout && nostdout->value)
-        return;
-
-	for (p = (unsigned char *)text; *p; p++) {
-		*p &= 0x7f;
-		if ((*p > 128 || *p < 32) && *p != 10 && *p != 13 && *p != 9)
-			printf("[%02x]", *p);
-		else
-			putc(*p, stdout);
-	}
-}
-
 void Sys_Quit (void)
 {
-	CL_Shutdown ();
-	Qcommon_Shutdown ();
-    fcntl (0, F_SETFL, fcntl (0, F_GETFL, 0) & ~FNDELAY);
-	_exit(0);
+	CL_Shutdown();
+	Qcommon_Shutdown();
+	threadexitsall(nil);
 }
 
 void Sys_Init(void)
 {
-#if id386
-//	Sys_SetFPCW();
-#endif
+	//Sys_SetFPCW();
 }
 
 void Sys_Error (char *error, ...)
 { 
-    va_list     argptr;
-    char        string[1024];
+	char buf[1024], *out;
+	va_list arg;
 
-// change stdin to non blocking
-    fcntl (0, F_SETFL, fcntl (0, F_GETFL, 0) & ~FNDELAY);
+	CL_Shutdown();
+	Qcommon_Shutdown();
 
-	CL_Shutdown ();
-	Qcommon_Shutdown ();
-    
-    va_start (argptr,error);
-    vsprintf (string,error,argptr);
-    va_end (argptr);
-	fprintf(stderr, "Error: %s\n", string);
+	va_start(arg, error);
+	out = vseprint(buf, buf+sizeof(buf), error, arg);
+	va_end(arg);
+	write(2, buf, out-buf);
+	print("\n");
+	sysfatal("ending.");
+}
 
-	_exit (1);
-
-} 
-
-void Sys_Warn (char *warning, ...)
-{ 
-    va_list     argptr;
-    char        string[1024];
-    
-    va_start (argptr,warning);
-    vsprintf (string,warning,argptr);
-    va_end (argptr);
-	fprintf(stderr, "Warning: %s", string);
-} 
-
-/*
-============
-Sys_FileTime
-
-returns -1 if not present
-============
-*/
-int	Sys_FileTime (char *path)
+int Sys_FileTime (char *path)
 {
-	struct	stat	buf;
-	
-	if (stat (path,&buf) == -1)
+	uchar sb[1024];
+
+	if(stat(path, sb, sizeof sb) < 0){
+		fprint(2, "Sys_FileTime:stat: %r\n");
 		return -1;
-	
-	return buf.st_mtime;
+	}
+	return *((int *)(sb+25));
 }
 
-void floating_point_exception_handler(int whatever)
-{
-//	Sys_Warn("floating point exception\n");
-	signal(SIGFPE, floating_point_exception_handler);
-}
-
 char *Sys_ConsoleInput(void)
 {
-    static char text[256];
-    int     len;
-	fd_set	fdset;
-    struct timeval timeout;
+	static char text[256];
+	int n;
 
-	if (!dedicated || !dedicated->value)
-		return NULL;
+	if(!dedicated || !dedicated->value || !stdin_active)
+		return nil;
 
-	if (!stdin_active)
-		return NULL;
-
-	FD_ZERO(&fdset);
-	FD_SET(0, &fdset); // stdin
-	timeout.tv_sec = 0;
-	timeout.tv_usec = 0;
-	if (select (1, &fdset, NULL, NULL, &timeout) == -1 || !FD_ISSET(0, &fdset))
-		return NULL;
-
-	len = read (0, text, sizeof(text));
-	if (len == 0) { // eof!
+	if((n = read(0, text, sizeof(text))) < 0)
+		return nil;
+	if(n == 0){
 		stdin_active = false;
-		return NULL;
+		return nil;
 	}
-
-	if (len < 1)
-		return NULL;
-	text[len-1] = 0;    // rip off the /n and terminate
-
+	text[n-1] = '\0';	/* rip off \n */
 	return text;
 }
 
-/*****************************************************************************/
-
-static void *game_library;
-
-/*
-=================
-Sys_UnloadGame
-=================
-*/
 void Sys_UnloadGame (void)
 {
-	if (game_library) 
-		dlclose (game_library);
-	game_library = NULL;
 }
 
-/*
-=================
-Sys_GetGameAPI
-
-Loads the game dll
-=================
-*/
-void *Sys_GetGameAPI (void *parms)
-{
-	void	*(*GetGameAPI) (void *);
-
-	char	name[MAX_OSPATH];
-	char	curpath[MAX_OSPATH];
-	char	*path;
-#ifdef __i386__
-	const char *gamename = "gamei386.so";
-#elif defined __alpha__
-	const char *gamename = "gameaxp.so";
-#else
-#error Unknown arch
-#endif
-
-	setreuid(getuid(), getuid());
-	setegid(getgid());
-
-	if (game_library)
-		Com_Error (ERR_FATAL, "Sys_GetGameAPI without Sys_UnloadingGame");
-
-	getcwd(curpath, sizeof(curpath));
-
-	Com_Printf("------- Loading %s -------", gamename);
-
-	// now run through the search paths
-	path = NULL;
-	while (1)
-	{
-		path = FS_NextPath (path);
-		if (!path)
-			return NULL;		// couldn't find one anywhere
-		sprintf (name, "%s/%s/%s", curpath, path, gamename);
-		game_library = dlopen (name, RTLD_NOW );
-		if (game_library)
-		{
-			Com_DPrintf ("LoadLibrary (%s)\n",name);
-			break;
-		}
-		else
-			printf("dlerror: %s\n", dlerror());
-	}
-
-	GetGameAPI = (void *)dlsym (game_library, "GetGameAPI");
-	if (!GetGameAPI)
-	{
-		Sys_UnloadGame ();		
-		return NULL;
-	}
-
-	return GetGameAPI (parms);
-}
-
-/*****************************************************************************/
-
 void Sys_AppActivate (void)
 {
 }
@@ -255,127 +91,37 @@
 void Sys_SendKeyEvents (void)
 {
 #ifndef DEDICATED_ONLY
-	if (KBD_Update_fp)
-		KBD_Update_fp();
+	KBD_Update();
 #endif
+	sys_frame_time = Sys_Milliseconds();	// grab frame time 
+}
 
-	// grab frame time 
-	sys_frame_time = Sys_Milliseconds();
+char *Sys_GetClipboardData (void)
+{
+	return nil;
 }
 
-/*****************************************************************************/
-
-char *Sys_GetClipboardData(void)
+void Sys_CopyProtect (void)
 {
-	return NULL;
 }
 
-int main (int argc, char **argv)
+void threadmain (int argc, char *argv[])
 {
-	int 	time, oldtime, newtime;
+	int time, oldtime, newtime;
 
-	// go back to real user for config loads
-	saved_euid = geteuid();
-	seteuid(getuid());
+	setfcr(getfcr() & ~(FPOVFL|FPUNFL|FPINVAL|FPZDIV));	/* assumed ignored in code */
 
 	Qcommon_Init(argc, argv);
 
-	fcntl(0, F_SETFL, fcntl (0, F_GETFL, 0) | FNDELAY);
-
 	nostdout = Cvar_Get("nostdout", "0", 0);
-	if (!nostdout->value) {
-		fcntl(0, F_SETFL, fcntl (0, F_GETFL, 0) | FNDELAY);
-//		printf ("Linux Quake -- Version %0.3f\n", LINUX_VERSION);
-	}
 
-    oldtime = Sys_Milliseconds ();
-    while (1)
-    {
-// find time spent rendering last frame
-		do {
-			newtime = Sys_Milliseconds ();
+	oldtime = Sys_Milliseconds();
+	for(;;){
+		do{
+			newtime = Sys_Milliseconds();
 			time = newtime - oldtime;
-		} while (time < 1);
-        Qcommon_Frame (time);
+		}while(time < 1);	// find time spent rendering last frame
+		Qcommon_Frame(time);
 		oldtime = newtime;
-    }
-
-}
-
-void Sys_CopyProtect(void)
-{
-	FILE *mnt;
-	struct mntent *ent;
-	char path[MAX_OSPATH];
-	struct stat st;
-	qboolean found_cd = false;
-
-	static qboolean checked = false;
-
-	if (checked)
-		return;
-
-	if ((mnt = setmntent("/etc/mtab", "r")) == NULL)
-		Com_Error(ERR_FATAL, "Can't read mount table to determine mounted cd location.");
-
-	while ((ent = getmntent(mnt)) != NULL) {
-		if (strcmp(ent->mnt_type, "iso9660") == 0) {
-			// found a cd file system
-			found_cd = true;
-			sprintf(path, "%s/%s", ent->mnt_dir, "install/data/quake2.exe");
-			if (stat(path, &st) == 0) {
-				// found it
-				checked = true;
-				endmntent(mnt);
-				return;
-			}
-			sprintf(path, "%s/%s", ent->mnt_dir, "Install/Data/quake2.exe");
-			if (stat(path, &st) == 0) {
-				// found it
-				checked = true;
-				endmntent(mnt);
-				return;
-			}
-			sprintf(path, "%s/%s", ent->mnt_dir, "quake2.exe");
-			if (stat(path, &st) == 0) {
-				// found it
-				checked = true;
-				endmntent(mnt);
-				return;
-			}
-		}
 	}
-	endmntent(mnt);
-
-	if (found_cd)
-		Com_Error (ERR_FATAL, "Could not find a Quake2 CD in your CD drive.");
-	Com_Error (ERR_FATAL, "Unable to find a mounted iso9660 file system.\n"
-		"You must mount the Quake2 CD in a cdrom drive in order to play.");
 }
-
-#if 0
-/*
-================
-Sys_MakeCodeWriteable
-================
-*/
-void Sys_MakeCodeWriteable (unsigned long startaddr, unsigned long length)
-{
-
-	int r;
-	unsigned long addr;
-	int psize = getpagesize();
-
-	addr = (startaddr & ~(psize-1)) - psize;
-
-//	fprintf(stderr, "writable code %lx(%lx)-%lx, length=%lx\n", startaddr,
-//			addr, startaddr+length, length);
-
-	r = mprotect((char*)addr, length + startaddr - addr + psize, 7);
-
-	if (r < 0)
-    		Sys_Error("Protection change failed\n");
-
-}
-
-#endif
--- a/plan9/vid_menu.c
+++ b/plan9/vid_menu.c
@@ -1,437 +1,138 @@
-#include "../client/client.h"
-#include "../client/qmenu.h"
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 
-#define REF_SOFT	0
-#define REF_SOFTX11	1
-#define REF_OPENGL	2
-
-extern cvar_t *vid_ref;
 extern cvar_t *vid_fullscreen;
 extern cvar_t *vid_gamma;
 extern cvar_t *scr_viewsize;
 
-static cvar_t *gl_mode;
-static cvar_t *gl_driver;
-static cvar_t *gl_picmip;
-static cvar_t *gl_ext_palettedtexture;
+extern void M_PopMenu(void);
 
-static cvar_t *sw_mode;
-static cvar_t *sw_stipplealpha;
+menuframework_s	vmenu;
+menuslider_s	ssizeslide;
+menuslider_s	gammaslide;
+menulist_s	fullscrbox;
+menuaction_s	applyaction;
+menuaction_s	defaultsaction;
 
-static cvar_t *_windowed_mouse;
 
-extern void M_ForceMenuOff( void );
-
-/*
-====================================================================
-
-MENU INTERACTION
-
-====================================================================
-*/
-#define SOFTWARE_MENU 0
-#define OPENGL_MENU   1
-
-static menuframework_s  s_software_menu;
-static menuframework_s	s_opengl_menu;
-static menuframework_s *s_current_menu;
-static int				s_current_menu_index;
-
-static menulist_s		s_mode_list[2];
-static menulist_s		s_ref_list[2];
-static menuslider_s		s_tq_slider;
-static menuslider_s		s_screensize_slider[2];
-static menuslider_s		s_brightness_slider[2];
-static menulist_s  		s_fs_box[2];
-static menulist_s  		s_stipple_box;
-static menulist_s  		s_paletted_texture_box;
-static menulist_s  		s_windowed_mouse;
-static menuaction_s		s_apply_action[2];
-static menuaction_s		s_defaults_action[2];
-
-static void DriverCallback( void *unused )
+void vmssize (void *s)
 {
-	s_ref_list[!s_current_menu_index].curvalue = s_ref_list[s_current_menu_index].curvalue;
-
-	if ( s_ref_list[s_current_menu_index].curvalue < 2 )
-	{
-		s_current_menu = &s_software_menu;
-		s_current_menu_index = 0;
-	}
-	else
-	{
-		s_current_menu = &s_opengl_menu;
-		s_current_menu_index = 1;
-	}
-
+	Cvar_SetValue("viewsize", ((menuslider_s *)s)->curvalue * 10);
 }
 
-static void ScreenSizeCallback( void *s )
+void vmgamma (void *s)
 {
-	menuslider_s *slider = ( menuslider_s * ) s;
-
-	Cvar_SetValue( "viewsize", slider->curvalue * 10 );
+	// invert sense so greater = brighter, and scale to a range of 0.5 to 1.3
+	Cvar_SetValue("vid_gamma", 0.8 - (((menuslider_s *)s)->curvalue/10.0 - 0.5) + 0.5);
 }
 
-static void BrightnessCallback( void *s )
+void vmreset (void *)
 {
-	menuslider_s *slider = ( menuslider_s * ) s;
-
-	if ( s_current_menu_index == 0)
-		s_brightness_slider[1].curvalue = s_brightness_slider[0].curvalue;
-	else
-		s_brightness_slider[0].curvalue = s_brightness_slider[1].curvalue;
-
-	if ( stricmp( vid_ref->string, "soft" ) == 0 ||
-		 stricmp( vid_ref->string, "softx" ) == 0 )
-	{
-		float gamma = ( 0.8 - ( slider->curvalue/10.0 - 0.5 ) ) + 0.5;
-
-		Cvar_SetValue( "vid_gamma", gamma );
-	}
-}
-
-static void ResetDefaults( void *unused )
-{
 	VID_MenuInit();
 }
 
-static void ApplyChanges( void *unused )
+void vmapply (void *)
 {
-	float gamma;
-
-	/*
-	** make values consistent
-	*/
-	s_fs_box[!s_current_menu_index].curvalue = s_fs_box[s_current_menu_index].curvalue;
-	s_brightness_slider[!s_current_menu_index].curvalue = s_brightness_slider[s_current_menu_index].curvalue;
-	s_ref_list[!s_current_menu_index].curvalue = s_ref_list[s_current_menu_index].curvalue;
-
-	/*
-	** invert sense so greater = brighter, and scale to a range of 0.5 to 1.3
-	*/
-	gamma = ( 0.8 - ( s_brightness_slider[s_current_menu_index].curvalue/10.0 - 0.5 ) ) + 0.5;
-
-	Cvar_SetValue( "vid_gamma", gamma );
-	Cvar_SetValue( "sw_stipplealpha", s_stipple_box.curvalue );
-	Cvar_SetValue( "gl_picmip", 3 - s_tq_slider.curvalue );
-	Cvar_SetValue( "vid_fullscreen", s_fs_box[s_current_menu_index].curvalue );
-	Cvar_SetValue( "gl_ext_palettedtexture", s_paletted_texture_box.curvalue );
-	Cvar_SetValue( "sw_mode", s_mode_list[SOFTWARE_MENU].curvalue );
-	Cvar_SetValue( "gl_mode", s_mode_list[OPENGL_MENU].curvalue );
-	Cvar_SetValue( "_windowed_mouse", s_windowed_mouse.curvalue);
-
-	switch ( s_ref_list[s_current_menu_index].curvalue )
-	{
-	case REF_SOFT:
-		Cvar_Set( "vid_ref", "soft" );
-		break;
-	case REF_SOFTX11:
-		Cvar_Set( "vid_ref", "softx" );
-		break;
-	case REF_OPENGL:
-		Cvar_Set( "vid_ref", "gl" );
-		Cvar_Set( "gl_driver", "opengl32" );
-		break;
-	}
-
-#if 0
-	/*
-	** update appropriate stuff if we're running OpenGL and gamma
-	** has been modified
-	*/
-	if ( stricmp( vid_ref->string, "gl" ) == 0 )
-	{
-		if ( vid_gamma->modified )
-		{
-			vid_ref->modified = true;
-			if ( stricmp( gl_driver->string, "3dfxgl" ) == 0 )
-			{
-				char envbuffer[1024];
-				float g;
-
-				vid_ref->modified = true;
-
-				g = 2.00 * ( 0.8 - ( vid_gamma->value - 0.5 ) ) + 1.0F;
-				Com_sprintf( envbuffer, sizeof(envbuffer), "SST_GAMMA=%f", g );
-				putenv( envbuffer );
-
-				vid_gamma->modified = false;
-			}
-		}
-	}
-#endif
-
+	Cvar_SetValue("vid_gamma", 0.8 - (gammaslide.curvalue/10.0 - 0.5) + 0.5);
+	Cvar_SetValue("vid_fullscreen", fullscrbox.curvalue);
 	M_ForceMenuOff();
 }
 
-/*
-** VID_MenuInit
-*/
-void VID_MenuInit( void )
+void VID_MenuInit (void)
 {
-	static const char *resolutions[] = 
-	{
-		"[320 240  ]",
-		"[400 300  ]",
-		"[512 384  ]",
-		"[640 480  ]",
-		"[800 600  ]",
-		"[960 720  ]",
-		"[1024 768 ]",
-		"[1152 864 ]",
-		"[1280 1024]",
-		"[1600 1200]",
-		0
-	};
-	static const char *refs[] =
-	{
-		"[software      ]",
-		"[software X11  ]",
-		"[default OpenGL]",
-		0
-	};
-	static const char *yesno_names[] =
-	{
-		"no",
-		"yes",
-		0
-	};
-	int i;
+	static char *yesno[] = {"no", "yes", nil};
 
-	if ( !gl_driver )
-		gl_driver = Cvar_Get( "gl_driver", "opengl32", 0 );
-	if ( !gl_picmip )
-		gl_picmip = Cvar_Get( "gl_picmip", "0", 0 );
-	if ( !gl_mode )
-		gl_mode = Cvar_Get( "gl_mode", "3", 0 );
-	if ( !sw_mode )
-		sw_mode = Cvar_Get( "sw_mode", "0", 0 );
-	if ( !gl_ext_palettedtexture )
-		gl_ext_palettedtexture = Cvar_Get( "gl_ext_palettedtexture", "1", CVAR_ARCHIVE );
+	if(!scr_viewsize)
+		scr_viewsize = Cvar_Get("viewsize", "100", CVAR_ARCHIVE);
+	ssizeslide.curvalue = scr_viewsize->value/10;
 
-	if ( !sw_stipplealpha )
-		sw_stipplealpha = Cvar_Get( "sw_stipplealpha", "0", CVAR_ARCHIVE );
+	vmenu.x = vid.width * 0.50;
+	vmenu.nitems = 0;
 
-	if ( !_windowed_mouse)
-        _windowed_mouse = Cvar_Get( "_windowed_mouse", "0", CVAR_ARCHIVE );
+	ssizeslide.generic.type = MTYPE_SLIDER;
+	ssizeslide.generic.x = 0;
+	ssizeslide.generic.y = 20;
+	ssizeslide.generic.name = "screen size";
+	ssizeslide.minvalue = 3;
+	ssizeslide.maxvalue = 12;
+	ssizeslide.generic.callback = vmssize;
 
-	s_mode_list[SOFTWARE_MENU].curvalue = sw_mode->value;
-	s_mode_list[OPENGL_MENU].curvalue = gl_mode->value;
+	gammaslide.generic.type = MTYPE_SLIDER;
+	gammaslide.generic.x = 0;
+	gammaslide.generic.y = 30;
+	gammaslide.generic.name = "gamma";
+	gammaslide.generic.callback = vmgamma;
+	gammaslide.minvalue = 5;
+	gammaslide.maxvalue = 13;
+	gammaslide.curvalue = (1.3 - vid_gamma->value + 0.5) * 10;
 
-	if ( !scr_viewsize )
-		scr_viewsize = Cvar_Get ("viewsize", "100", CVAR_ARCHIVE);
+	fullscrbox.generic.type = MTYPE_SPINCONTROL;
+	fullscrbox.generic.x = 0;
+	fullscrbox.generic.y = 40;
+	fullscrbox.generic.name = "fullscreen";
+	fullscrbox.itemnames = yesno;
+	fullscrbox.curvalue = vid_fullscreen->value;
 
-	s_screensize_slider[SOFTWARE_MENU].curvalue = scr_viewsize->value/10;
-	s_screensize_slider[OPENGL_MENU].curvalue = scr_viewsize->value/10;
+	defaultsaction.generic.type = MTYPE_ACTION;
+	defaultsaction.generic.name = "reset to default";
+	defaultsaction.generic.x = 0;
+	defaultsaction.generic.y = 90;
+	defaultsaction.generic.callback = vmreset;
 
-	if ( strcmp( vid_ref->string, "soft" ) == 0)
-	{
-		s_current_menu_index = SOFTWARE_MENU;
-		s_ref_list[0].curvalue = s_ref_list[1].curvalue = REF_SOFT;
-	}
-	else if (strcmp( vid_ref->string, "softx" ) == 0 ) 
-	{
-		s_current_menu_index = SOFTWARE_MENU;
-		s_ref_list[0].curvalue = s_ref_list[1].curvalue = REF_SOFTX11;
-	}
-	else if ( strcmp( vid_ref->string, "gl" ) == 0 )
-	{
-		s_current_menu_index = OPENGL_MENU;
-		s_ref_list[s_current_menu_index].curvalue = REF_OPENGL;
-#if 0
-		if ( strcmp( gl_driver->string, "3dfxgl" ) == 0 )
-			s_ref_list[s_current_menu_index].curvalue = REF_3DFX;
-		else if ( strcmp( gl_driver->string, "pvrgl" ) == 0 )
-			s_ref_list[s_current_menu_index].curvalue = REF_POWERVR;
-		else if ( strcmp( gl_driver->string, "opengl32" ) == 0 )
-			s_ref_list[s_current_menu_index].curvalue = REF_OPENGL;
-		else
-			s_ref_list[s_current_menu_index].curvalue = REF_VERITE;
-#endif
-	}
+	applyaction.generic.type = MTYPE_ACTION;
+	applyaction.generic.name = "apply";
+	applyaction.generic.x = 0;
+	applyaction.generic.y = 100;
+	applyaction.generic.callback = vmapply;
 
-	s_software_menu.x = viddef.width * 0.50;
-	s_software_menu.nitems = 0;
-	s_opengl_menu.x = viddef.width * 0.50;
-	s_opengl_menu.nitems = 0;
+	Menu_AddItem(&vmenu, (void *)&ssizeslide);
+	Menu_AddItem(&vmenu, (void *)&gammaslide);
+	Menu_AddItem(&vmenu, (void *)&fullscrbox);
+	Menu_AddItem(&vmenu, (void *)&defaultsaction);
+	Menu_AddItem(&vmenu, (void *)&applyaction);
 
-	for ( i = 0; i < 2; i++ )
-	{
-		s_ref_list[i].generic.type = MTYPE_SPINCONTROL;
-		s_ref_list[i].generic.name = "driver";
-		s_ref_list[i].generic.x = 0;
-		s_ref_list[i].generic.y = 0;
-		s_ref_list[i].generic.callback = DriverCallback;
-		s_ref_list[i].itemnames = refs;
-
-		s_mode_list[i].generic.type = MTYPE_SPINCONTROL;
-		s_mode_list[i].generic.name = "video mode";
-		s_mode_list[i].generic.x = 0;
-		s_mode_list[i].generic.y = 10;
-		s_mode_list[i].itemnames = resolutions;
-
-		s_screensize_slider[i].generic.type	= MTYPE_SLIDER;
-		s_screensize_slider[i].generic.x		= 0;
-		s_screensize_slider[i].generic.y		= 20;
-		s_screensize_slider[i].generic.name	= "screen size";
-		s_screensize_slider[i].minvalue = 3;
-		s_screensize_slider[i].maxvalue = 12;
-		s_screensize_slider[i].generic.callback = ScreenSizeCallback;
-
-		s_brightness_slider[i].generic.type	= MTYPE_SLIDER;
-		s_brightness_slider[i].generic.x	= 0;
-		s_brightness_slider[i].generic.y	= 30;
-		s_brightness_slider[i].generic.name	= "brightness";
-		s_brightness_slider[i].generic.callback = BrightnessCallback;
-		s_brightness_slider[i].minvalue = 5;
-		s_brightness_slider[i].maxvalue = 13;
-		s_brightness_slider[i].curvalue = ( 1.3 - vid_gamma->value + 0.5 ) * 10;
-
-		s_fs_box[i].generic.type = MTYPE_SPINCONTROL;
-		s_fs_box[i].generic.x	= 0;
-		s_fs_box[i].generic.y	= 40;
-		s_fs_box[i].generic.name	= "fullscreen";
-		s_fs_box[i].itemnames = yesno_names;
-		s_fs_box[i].curvalue = vid_fullscreen->value;
-
-		s_defaults_action[i].generic.type = MTYPE_ACTION;
-		s_defaults_action[i].generic.name = "reset to default";
-		s_defaults_action[i].generic.x    = 0;
-		s_defaults_action[i].generic.y    = 90;
-		s_defaults_action[i].generic.callback = ResetDefaults;
-
-		s_apply_action[i].generic.type = MTYPE_ACTION;
-		s_apply_action[i].generic.name = "apply";
-		s_apply_action[i].generic.x    = 0;
-		s_apply_action[i].generic.y    = 100;
-		s_apply_action[i].generic.callback = ApplyChanges;
-	}
-
-	s_stipple_box.generic.type = MTYPE_SPINCONTROL;
-	s_stipple_box.generic.x	= 0;
-	s_stipple_box.generic.y	= 60;
-	s_stipple_box.generic.name	= "stipple alpha";
-	s_stipple_box.curvalue = sw_stipplealpha->value;
-	s_stipple_box.itemnames = yesno_names;
-
-	s_windowed_mouse.generic.type = MTYPE_SPINCONTROL;
-	s_windowed_mouse.generic.x  = 0;
-	s_windowed_mouse.generic.y  = 72;
-	s_windowed_mouse.generic.name   = "windowed mouse";
-	s_windowed_mouse.curvalue = _windowed_mouse->value;
-	s_windowed_mouse.itemnames = yesno_names;
-
-	s_tq_slider.generic.type	= MTYPE_SLIDER;
-	s_tq_slider.generic.x		= 0;
-	s_tq_slider.generic.y		= 60;
-	s_tq_slider.generic.name	= "texture quality";
-	s_tq_slider.minvalue = 0;
-	s_tq_slider.maxvalue = 3;
-	s_tq_slider.curvalue = 3-gl_picmip->value;
-
-	s_paletted_texture_box.generic.type = MTYPE_SPINCONTROL;
-	s_paletted_texture_box.generic.x	= 0;
-	s_paletted_texture_box.generic.y	= 70;
-	s_paletted_texture_box.generic.name	= "8-bit textures";
-	s_paletted_texture_box.itemnames = yesno_names;
-	s_paletted_texture_box.curvalue = gl_ext_palettedtexture->value;
-
-	Menu_AddItem( &s_software_menu, ( void * ) &s_ref_list[SOFTWARE_MENU] );
-	Menu_AddItem( &s_software_menu, ( void * ) &s_mode_list[SOFTWARE_MENU] );
-	Menu_AddItem( &s_software_menu, ( void * ) &s_screensize_slider[SOFTWARE_MENU] );
-	Menu_AddItem( &s_software_menu, ( void * ) &s_brightness_slider[SOFTWARE_MENU] );
-	Menu_AddItem( &s_software_menu, ( void * ) &s_fs_box[SOFTWARE_MENU] );
-	Menu_AddItem( &s_software_menu, ( void * ) &s_stipple_box );
-	Menu_AddItem( &s_software_menu, ( void * ) &s_windowed_mouse );
-
-	Menu_AddItem( &s_opengl_menu, ( void * ) &s_ref_list[OPENGL_MENU] );
-	Menu_AddItem( &s_opengl_menu, ( void * ) &s_mode_list[OPENGL_MENU] );
-	Menu_AddItem( &s_opengl_menu, ( void * ) &s_screensize_slider[OPENGL_MENU] );
-	Menu_AddItem( &s_opengl_menu, ( void * ) &s_brightness_slider[OPENGL_MENU] );
-	Menu_AddItem( &s_opengl_menu, ( void * ) &s_fs_box[OPENGL_MENU] );
-	Menu_AddItem( &s_opengl_menu, ( void * ) &s_tq_slider );
-	Menu_AddItem( &s_opengl_menu, ( void * ) &s_paletted_texture_box );
-
-	Menu_AddItem( &s_software_menu, ( void * ) &s_defaults_action[SOFTWARE_MENU] );
-	Menu_AddItem( &s_software_menu, ( void * ) &s_apply_action[SOFTWARE_MENU] );
-	Menu_AddItem( &s_opengl_menu, ( void * ) &s_defaults_action[OPENGL_MENU] );
-	Menu_AddItem( &s_opengl_menu, ( void * ) &s_apply_action[OPENGL_MENU] );
-
-	Menu_Center( &s_software_menu );
-	Menu_Center( &s_opengl_menu );
-	s_opengl_menu.x -= 8;
-	s_software_menu.x -= 8;
+	Menu_Center(&vmenu);
+	vmenu.x -= 8;
 }
 
-/*
-================
-VID_MenuDraw
-================
-*/
 void VID_MenuDraw (void)
 {
 	int w, h;
 
-	if ( s_current_menu_index == 0 )
-		s_current_menu = &s_software_menu;
-	else
-		s_current_menu = &s_opengl_menu;
-
-	/*
-	** draw the banner
-	*/
-	re.DrawGetPicSize( &w, &h, "m_banner_video" );
-	re.DrawPic( viddef.width / 2 - w / 2, viddef.height /2 - 110, "m_banner_video" );
-
-	/*
-	** move cursor to a reasonable starting position
-	*/
-	Menu_AdjustCursor( s_current_menu, 1 );
-
-	/*
-	** draw the menu
-	*/
-	Menu_Draw( s_current_menu );
+	re.DrawGetPicSize(&w, &h, "m_banner_video");
+	re.DrawPic(vid.width/2 - w/2, vid.height/2 - 110, "m_banner_video");
+	Menu_AdjustCursor(&vmenu, 1);	// starting position
+	Menu_Draw(&vmenu);
 }
 
-/*
-================
-VID_MenuKey
-================
-*/
-const char *VID_MenuKey( int key )
+char *VID_MenuKey (int key)
 {
-	extern void M_PopMenu( void );
+	static char *sound = "misc/menu1.wav";
 
-	menuframework_s *m = s_current_menu;
-	static const char *sound = "misc/menu1.wav";
-
-	switch ( key )
-	{
+	switch(key){
 	case K_ESCAPE:
 		M_PopMenu();
 		return NULL;
 	case K_UPARROW:
-		m->cursor--;
-		Menu_AdjustCursor( m, -1 );
+		vmenu.cursor--;
+		Menu_AdjustCursor(&vmenu, -1);
 		break;
 	case K_DOWNARROW:
-		m->cursor++;
-		Menu_AdjustCursor( m, 1 );
+		vmenu.cursor++;
+		Menu_AdjustCursor(&vmenu, 1);
 		break;
 	case K_LEFTARROW:
-		Menu_SlideItem( m, -1 );
+		Menu_SlideItem(&vmenu, -1);
 		break;
 	case K_RIGHTARROW:
-		Menu_SlideItem( m, 1 );
+		Menu_SlideItem(&vmenu, 1);
 		break;
 	case K_ENTER:
-		Menu_SelectItem( m );
+		Menu_SelectItem(&vmenu);
 		break;
 	}
-
 	return sound;
 }
-
-
--- a/plan9/vid_so.c
+++ b/plan9/vid_so.c
@@ -1,251 +1,63 @@
-// Main windowed and fullscreen graphics interface module. This module
-// is used for both the software and OpenGL rendering versions of the
-// Quake refresh engine.
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 
-#define SO_FILE "/etc/quake2.conf"
+refexport_t	GetRefAPI(refimport_t);
 
-#include <assert.h>
-#include <dlfcn.h> // ELF dl loader
-#include <sys/stat.h>
-#include <unistd.h>
-#include <errno.h>
+cvar_t *vid_gamma;
+cvar_t *vid_ref;		// Name of Refresh DLL loaded
+cvar_t *vid_xpos;		// X coordinate of window position
+cvar_t *vid_ypos;		// Y coordinate of window position
+cvar_t *vid_fullscreen;
+refexport_t re;			/* exported functions from refresh DLL */
 
-#include "../client/client.h"
 
-#include "../linux/rw_linux.h"
-
-// Structure containing functions exported from refresh DLL
-refexport_t	re;
-
-// Console variables that we need to access from this module
-cvar_t		*vid_gamma;
-cvar_t		*vid_ref;			// Name of Refresh DLL loaded
-cvar_t		*vid_xpos;			// X coordinate of window position
-cvar_t		*vid_ypos;			// Y coordinate of window position
-cvar_t		*vid_fullscreen;
-
-// Global variables used internally by this module
-viddef_t	viddef;				// global video state; used by other modules
-void		*reflib_library;		// Handle to refresh DLL 
-qboolean	reflib_active = 0;
-
-#define VID_NUM_MODES ( sizeof( vid_modes ) / sizeof( vid_modes[0] ) )
-
-/** KEYBOARD **************************************************************/
-
-void Do_Key_Event(int key, qboolean down);
-
-void (*KBD_Update_fp)(void);
-void (*KBD_Init_fp)(Key_Event_fp_t fp);
-void (*KBD_Close_fp)(void);
-
-/** MOUSE *****************************************************************/
-
-in_state_t in_state;
-
-void (*RW_IN_Init_fp)(in_state_t *in_state_p);
-void (*RW_IN_Shutdown_fp)(void);
-void (*RW_IN_Activate_fp)(qboolean active);
-void (*RW_IN_Commands_fp)(void);
-void (*RW_IN_Move_fp)(usercmd_t *cmd);
-void (*RW_IN_Frame_fp)(void);
-
-void Real_IN_Init (void);
-
-/*
-==========================================================================
-
-DLL GLUE
-
-==========================================================================
-*/
-
-#define	MAXPRINTMSG	4096
 void VID_Printf (int print_level, char *fmt, ...)
 {
-	va_list		argptr;
-	char		msg[MAXPRINTMSG];
-	static qboolean	inupdate;
+	va_list argptr;
+	char msg[4096];
 	
-	va_start (argptr,fmt);
-	vsprintf (msg,fmt,argptr);
-	va_end (argptr);
-
-	if (print_level == PRINT_ALL)
-		Com_Printf ("%s", msg);
+	va_start(argptr, fmt);
+	vsprintf(msg, fmt, argptr);
+	va_end(argptr);
+	if(print_level == PRINT_ALL)
+		Com_Printf("%s", msg);
 	else
-		Com_DPrintf ("%s", msg);
+		Com_DPrintf("%s", msg);
 }
 
 void VID_Error (int err_level, char *fmt, ...)
 {
-	va_list		argptr;
-	char		msg[MAXPRINTMSG];
-	static qboolean	inupdate;
+	va_list argptr;
+	char msg[4096];
 	
-	va_start (argptr,fmt);
-	vsprintf (msg,fmt,argptr);
-	va_end (argptr);
-
-	Com_Error (err_level,"%s", msg);
+	va_start(argptr, fmt);
+	vsprintf(msg, fmt, argptr);
+	va_end(argptr);
+	Com_Error(err_level, "%s", msg);
 }
 
-//==========================================================================
-
-/*
-============
-VID_Restart_f
-
-Console command to re-start the video mode and refresh DLL. We do this
-simply by setting the modified flag for the vid_ref variable, which will
-cause the entire video mode and refresh DLL to be reset on the next frame.
-============
-*/
-void VID_Restart_f (void)
+void VID_CheckChanges (void)
 {
-	vid_ref->modified = true;
 }
 
-/*
-** VID_GetModeInfo
-*/
-typedef struct vidmode_s
+void VID_Shutdown (void)
 {
-	const char *description;
-	int         width, height;
-	int         mode;
-} vidmode_t;
-
-vidmode_t vid_modes[] =
-{
-	{ "Mode 0: 320x240",   320, 240,   0 },
-	{ "Mode 1: 400x300",   400, 300,   1 },
-	{ "Mode 2: 512x384",   512, 384,   2 },
-	{ "Mode 3: 640x480",   640, 480,   3 },
-	{ "Mode 4: 800x600",   800, 600,   4 },
-	{ "Mode 5: 960x720",   960, 720,   5 },
-	{ "Mode 6: 1024x768",  1024, 768,  6 },
-	{ "Mode 7: 1152x864",  1152, 864,  7 },
-	{ "Mode 8: 1280x1024",  1280, 1024, 8 },
-	{ "Mode 9: 1600x1200", 1600, 1200, 9 }
-};
-
-qboolean VID_GetModeInfo( int *width, int *height, int mode )
-{
-	if ( mode < 0 || mode >= VID_NUM_MODES )
-		return false;
-
-	*width  = vid_modes[mode].width;
-	*height = vid_modes[mode].height;
-
-	return true;
+	re.Shutdown();
 }
 
-/*
-** VID_NewWindow
-*/
-void VID_NewWindow ( int width, int height)
+void VID_Init (void)
 {
-	viddef.width  = width;
-	viddef.height = height;
-}
+	refimport_t ri;
 
-void VID_FreeReflib (void)
-{
-	if (reflib_library) {
-		if (KBD_Close_fp)
-			KBD_Close_fp();
-		if (RW_IN_Shutdown_fp)
-			RW_IN_Shutdown_fp();
-		dlclose(reflib_library);
-	}
+	vid_ref = Cvar_Get("vid_ref", "libdraw", CVAR_ARCHIVE);
+	vid_xpos = Cvar_Get("vid_xpos", "3", CVAR_ARCHIVE);
+	vid_ypos = Cvar_Get("vid_ypos", "22", CVAR_ARCHIVE);
+	vid_fullscreen = Cvar_Get("vid_fullscreen", "0", CVAR_ARCHIVE);
+	vid_gamma = Cvar_Get("vid_gamma", "1", CVAR_ARCHIVE);
 
-	KBD_Init_fp = NULL;
-	KBD_Update_fp = NULL;
-	KBD_Close_fp = NULL;
-	RW_IN_Init_fp = NULL;
-	RW_IN_Shutdown_fp = NULL;
-	RW_IN_Activate_fp = NULL;
-	RW_IN_Commands_fp = NULL;
-	RW_IN_Move_fp = NULL;
-	RW_IN_Frame_fp = NULL;
-
-	memset (&re, 0, sizeof(re));
-	reflib_library = NULL;
-	reflib_active  = false;
-}
-
-/*
-==============
-VID_LoadRefresh
-==============
-*/
-qboolean VID_LoadRefresh( char *name )
-{
-	refimport_t	ri;
-	GetRefAPI_t	GetRefAPI;
-	char	fn[MAX_OSPATH];
-	struct stat st;
-	extern uid_t saved_euid;
-	FILE *fp;
-	
-	if ( reflib_active )
-	{
-		if (KBD_Close_fp)
-			KBD_Close_fp();
-		if (RW_IN_Shutdown_fp)
-			RW_IN_Shutdown_fp();
-		KBD_Close_fp = NULL;
-		RW_IN_Shutdown_fp = NULL;
-		re.Shutdown();
-		VID_FreeReflib ();
-	}
-
-	Com_Printf( "------- Loading %s -------\n", name );
-
-	//regain root
-	seteuid(saved_euid);
-
-	if ((fp = fopen(SO_FILE, "r")) == NULL) {
-		Com_Printf( "LoadLibrary(\"%s\") failed: can't open " SO_FILE " (required for location of ref libraries)\n", name);
-		return false;
-	}
-	fgets(fn, sizeof(fn), fp);
-	fclose(fp);
-	if (*fn && fn[strlen(fn) - 1] == '\n')
-		fn[strlen(fn) - 1] = 0;
-
-	strcat(fn, "/");
-	strcat(fn, name);
-
-	// permission checking
-	if (strstr(fn, "softx") == NULL) { // softx doesn't require root
-		if (stat(fn, &st) == -1) {
-			Com_Printf( "LoadLibrary(\"%s\") failed: %s\n", name, strerror(errno));
-			return false;
-		}
-		if (st.st_uid != 0) {
-			Com_Printf( "LoadLibrary(\"%s\") failed: ref is not owned by root\n", name);
-			return false;
-		}
-#if 0
-		if ((st.st_mode & 0777) & ~0700) {
-			Com_Printf( "LoadLibrary(\"%s\") failed: invalid permissions, must be 700 for security considerations\n", name);
-			return false;
-		}
-#endif
-	} else {
-		// softx requires we give up root now
-		setreuid(getuid(), getuid());
-		setegid(getgid());
-	}
-
-	if ( ( reflib_library = dlopen( fn, RTLD_NOW ) ) == 0 )
-	{
-		Com_Printf( "LoadLibrary(\"%s\") failed: %s\n", name , dlerror());
-		return false;
-	}
-
 	ri.Cmd_AddCommand = Cmd_AddCommand;
 	ri.Cmd_RemoveCommand = Cmd_RemoveCommand;
 	ri.Cmd_Argc = Cmd_Argc;
@@ -259,231 +71,8 @@
 	ri.Cvar_Get = Cvar_Get;
 	ri.Cvar_Set = Cvar_Set;
 	ri.Cvar_SetValue = Cvar_SetValue;
-	ri.Vid_GetModeInfo = VID_GetModeInfo;
 	ri.Vid_MenuInit = VID_MenuInit;
-	ri.Vid_NewWindow = VID_NewWindow;
 
-	if ( ( GetRefAPI = (void *) dlsym( reflib_library, "GetRefAPI" ) ) == 0 )
-		Com_Error( ERR_FATAL, "dlsym failed on %s", name );
-
-	re = GetRefAPI( ri );
-
-	if (re.api_version != API_VERSION)
-	{
-		VID_FreeReflib ();
-		Com_Error (ERR_FATAL, "%s has incompatible api_version", name);
-	}
-
-	/* Init IN (Mouse) */
-	in_state.IN_CenterView_fp = IN_CenterView;
-	in_state.Key_Event_fp = Do_Key_Event;
-	in_state.viewangles = cl.viewangles;
-	in_state.in_strafe_state = &in_strafe.state;
-
-	if ((RW_IN_Init_fp = dlsym(reflib_library, "RW_IN_Init")) == NULL ||
-		(RW_IN_Shutdown_fp = dlsym(reflib_library, "RW_IN_Shutdown")) == NULL ||
-		(RW_IN_Activate_fp = dlsym(reflib_library, "RW_IN_Activate")) == NULL ||
-		(RW_IN_Commands_fp = dlsym(reflib_library, "RW_IN_Commands")) == NULL ||
-		(RW_IN_Move_fp = dlsym(reflib_library, "RW_IN_Move")) == NULL ||
-		(RW_IN_Frame_fp = dlsym(reflib_library, "RW_IN_Frame")) == NULL)
-		Sys_Error("No RW_IN functions in REF.\n");
-
-	Real_IN_Init();
-
-	if ( re.Init( 0, 0 ) == -1 )
-	{
-		re.Shutdown();
-		VID_FreeReflib ();
-		return false;
-	}
-
-	/* Init KBD */
-#if 1
-	if ((KBD_Init_fp = dlsym(reflib_library, "KBD_Init")) == NULL ||
-		(KBD_Update_fp = dlsym(reflib_library, "KBD_Update")) == NULL ||
-		(KBD_Close_fp = dlsym(reflib_library, "KBD_Close")) == NULL)
-		Sys_Error("No KBD functions in REF.\n");
-#else
-	{
-		void KBD_Init(void);
-		void KBD_Update(void);
-		void KBD_Close(void);
-
-		KBD_Init_fp = KBD_Init;
-		KBD_Update_fp = KBD_Update;
-		KBD_Close_fp = KBD_Close;
-	}
-#endif
-	KBD_Init_fp(Do_Key_Event);
-
-	// give up root now
-	setreuid(getuid(), getuid());
-	setegid(getgid());
-
-	Com_Printf( "------------------------------------\n");
-	reflib_active = true;
-	return true;
+	re = GetRefAPI(ri);
+	re.Init(nil, nil);
 }
-
-/*
-============
-VID_CheckChanges
-
-This function gets called once just before drawing each frame, and it's sole purpose in life
-is to check to see if any of the video mode parameters have changed, and if they have to 
-update the rendering DLL and/or video mode to match.
-============
-*/
-void VID_CheckChanges (void)
-{
-	char name[100];
-	cvar_t *sw_mode;
-
-	if ( vid_ref->modified )
-	{
-		S_StopAllSounds();
-	}
-
-	while (vid_ref->modified)
-	{
-		/*
-		** refresh has changed
-		*/
-		vid_ref->modified = false;
-		vid_fullscreen->modified = true;
-		cl.refresh_prepped = false;
-		cls.disable_screen = true;
-
-		sprintf( name, "ref_%s.so", vid_ref->string );
-		if ( !VID_LoadRefresh( name ) )
-		{
-			if ( strcmp (vid_ref->string, "soft") == 0 ||
-				strcmp (vid_ref->string, "softx") == 0 ) {
-Com_Printf("Refresh failed\n");
-				sw_mode = Cvar_Get( "sw_mode", "0", 0 );
-				if (sw_mode->value != 0) {
-Com_Printf("Trying mode 0\n");
-					Cvar_SetValue("sw_mode", 0);
-					if ( !VID_LoadRefresh( name ) )
-						Com_Error (ERR_FATAL, "Couldn't fall back to software refresh!");
-				} else
-					Com_Error (ERR_FATAL, "Couldn't fall back to software refresh!");
-			}
-
-			Cvar_Set( "vid_ref", "soft" );
-
-			/*
-			** drop the console if we fail to load a refresh
-			*/
-			if ( cls.key_dest != key_console )
-			{
-				Con_ToggleConsole_f();
-			}
-		}
-		cls.disable_screen = false;
-	}
-
-}
-
-/*
-============
-VID_Init
-============
-*/
-void VID_Init (void)
-{
-	/* Create the video variables so we know how to start the graphics drivers */
-	// if DISPLAY is defined, try X
-	if (getenv("DISPLAY"))
-		vid_ref = Cvar_Get ("vid_ref", "softx", CVAR_ARCHIVE);
-	else
-		vid_ref = Cvar_Get ("vid_ref", "soft", CVAR_ARCHIVE);
-	vid_xpos = Cvar_Get ("vid_xpos", "3", CVAR_ARCHIVE);
-	vid_ypos = Cvar_Get ("vid_ypos", "22", CVAR_ARCHIVE);
-	vid_fullscreen = Cvar_Get ("vid_fullscreen", "0", CVAR_ARCHIVE);
-	vid_gamma = Cvar_Get( "vid_gamma", "1", CVAR_ARCHIVE );
-
-	/* Add some console commands that we want to handle */
-	Cmd_AddCommand ("vid_restart", VID_Restart_f);
-
-	/* Disable the 3Dfx splash screen */
-	putenv("FX_GLIDE_NO_SPLASH=0");
-		
-	/* Start the graphics mode and load refresh DLL */
-	VID_CheckChanges();
-}
-
-/*
-============
-VID_Shutdown
-============
-*/
-void VID_Shutdown (void)
-{
-	if ( reflib_active )
-	{
-		if (KBD_Close_fp)
-			KBD_Close_fp();
-		if (RW_IN_Shutdown_fp)
-			RW_IN_Shutdown_fp();
-		KBD_Close_fp = NULL;
-		RW_IN_Shutdown_fp = NULL;
-		re.Shutdown ();
-		VID_FreeReflib ();
-	}
-}
-
-
-/*****************************************************************************/
-/* INPUT                                                                     */
-/*****************************************************************************/
-
-cvar_t	*in_joystick;
-
-// This if fake, it's acutally done by the Refresh load
-void IN_Init (void)
-{
-	in_joystick	= Cvar_Get ("in_joystick", "0", CVAR_ARCHIVE);
-}
-
-void Real_IN_Init (void)
-{
-	if (RW_IN_Init_fp)
-		RW_IN_Init_fp(&in_state);
-}
-
-void IN_Shutdown (void)
-{
-	if (RW_IN_Shutdown_fp)
-		RW_IN_Shutdown_fp();
-}
-
-void IN_Commands (void)
-{
-	if (RW_IN_Commands_fp)
-		RW_IN_Commands_fp();
-}
-
-void IN_Move (usercmd_t *cmd)
-{
-	if (RW_IN_Move_fp)
-		RW_IN_Move_fp(cmd);
-}
-
-void IN_Frame (void)
-{
-	if (RW_IN_Frame_fp)
-		RW_IN_Frame_fp();
-}
-
-void IN_Activate (qboolean active)
-{
-	if (RW_IN_Activate_fp)
-		RW_IN_Activate_fp(active);
-}
-
-void Do_Key_Event(int key, qboolean down)
-{
-	Key_Event(key, down, Sys_Milliseconds());
-}
-
--- a/q_shared.h
+++ b/q_shared.h
@@ -17,49 +17,18 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-	
+
 // q_shared.h -- included first by ALL program modules
 
-#ifdef _WIN32
-// unknown pragmas are SUPPOSED to be ignored, but....
-#pragma warning(disable : 4244)     // MIPS
-#pragma warning(disable : 4136)     // X86
-#pragma warning(disable : 4051)     // ALPHA
+#pragma pack on
 
-#pragma warning(disable : 4018)     // signed/unsigned mismatch
-#pragma warning(disable : 4305)		// truncation from const double to float
+//#define id386
 
-#endif
-
-#include <assert.h>
-#include <math.h>
-#include <stdio.h>
-#include <stdarg.h>
-#include <string.h>
-#include <stdlib.h>
-#include <time.h>
-
-#if (defined _M_IX86 || defined __i386__) && !defined C_ONLY && !defined __sun__
-#define id386	1
-#else
-#define id386	0
-#endif
-
-#if defined _M_ALPHA && !defined C_ONLY
-#define idaxp	1
-#else
-#define idaxp	0
-#endif
-
 typedef unsigned char 		byte;
 typedef enum {false, true}	qboolean;
 
+typedef struct edict_t edict_t;
 
-#ifndef NULL
-#define NULL ((void *)0)
-#endif
-
-
 // angle indexes
 #define	PITCH				0		// up / down
 #define	YAW					1		// left / right
@@ -92,16 +61,6 @@
 #define	PRINT_CHAT			3		// chat messages
 
 
-
-#define	ERR_FATAL			0		// exit the entire game with a popup window
-#define	ERR_DROP			1		// print to console and disconnect from game
-#define	ERR_DISCONNECT		2		// don't kill server
-
-#define	PRINT_ALL			0
-#define PRINT_DEVELOPER		1		// only print when "developer 1"
-#define PRINT_ALERT			2		
-
-
 // destination class for gi.multicast()
 typedef enum
 {
@@ -145,11 +104,7 @@
 // microsoft's fabs seems to be ungodly slow...
 //float Q_fabs (float f);
 //#define	fabs(f) Q_fabs(f)
-#if !defined C_ONLY && !defined __linux__ && !defined __sgi
-extern long Q_ftol( float f );
-#else
 #define Q_ftol( f ) ( long ) (f)
-#endif
 
 #define DotProduct(x,y)			(x[0]*y[0]+x[1]*y[1]+x[2]*y[2])
 #define VectorSubtract(a,b,c)	(c[0]=a[0]-b[0],c[1]=a[1]-b[1],c[2]=a[2]-b[2])
@@ -225,7 +180,6 @@
 //=============================================
 
 // portable case insensitive compare
-int Q_stricmp (char *s1, char *s2);
 int Q_strcasecmp (char *s1, char *s2);
 int Q_strncasecmp (char *s1, char *s2, int n);
 
@@ -284,8 +238,8 @@
 /*
 ** pass in an attribute mask of things you wish to REJECT
 */
-char	*Sys_FindFirst (char *path, unsigned musthave, unsigned canthave );
-char	*Sys_FindNext ( unsigned musthave, unsigned canthave );
+char	*Sys_FindFirst (char *path, uint musthave, uint canthave );
+char	*Sys_FindNext ( uint musthave, uint canthave );
 void	Sys_FindClose (void);
 
 
@@ -451,7 +405,7 @@
 	cplane_t	plane;		// surface normal at impact
 	csurface_t	*surface;	// surface hit
 	int			contents;	// contents on other side of surface hit
-	struct edict_s	*ent;		// not set by CM_*() functions
+	edict_t	*ent;		// not set by CM_*() functions
 } trace_t;
 
 
@@ -529,7 +483,7 @@
 
 	// results (out)
 	int			numtouch;
-	struct edict_s	*touchents[MAXTOUCH];
+	edict_t	*touchents[MAXTOUCH];
 
 	vec3_t		viewangles;			// clamped
 	float		viewheight;
@@ -536,7 +490,7 @@
 
 	vec3_t		mins, maxs;			// bounding box size
 
-	struct edict_s	*groundentity;
+	edict_t	*groundentity;
 	int			watertype;
 	int			waterlevel;
 
--- a/qcommon/cmd.c
+++ b/qcommon/cmd.c
@@ -19,7 +19,11 @@
 */
 // cmd.c -- Quake script command processing module
 
-#include "qcommon.h"
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 
 void Cmd_ForwardToServer (void);
 
@@ -158,7 +162,7 @@
 */
 void Cbuf_InsertFromDefer (void)
 {
-	Cbuf_InsertText (defer_text_buf);
+	Cbuf_InsertText ((char *)defer_text_buf);
 	defer_text_buf[0] = 0;
 }
 
--- a/qcommon/cmodel.c
+++ b/qcommon/cmodel.c
@@ -19,7 +19,11 @@
 */
 // cmodel.c -- model loading
 
-#include "qcommon.h"
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 
 typedef struct
 {
@@ -152,7 +156,7 @@
 
 	numcmodels = count;
 
-	for ( i=0 ; i<count ; i++, in++, out++)
+	for ( i=0 ; i<count ; i++, in++)
 	{
 		out = &map_cmodels[i];
 
@@ -596,7 +600,7 @@
 	*checksum = last_checksum;
 
 	header = *(dheader_t *)buf;
-	for (i=0 ; i<sizeof(dheader_t)/4 ; i++)
+	for (i=0 ; i<sizeof(dheader_t)/sizeof(int) ; i++)
 		((int *)&header)[i] = LittleLong ( ((int *)&header)[i]);
 
 	if (header.version != BSPVERSION)
@@ -1272,11 +1276,11 @@
 	}
 
 
-#if 0
-CM_RecursiveHullCheck (node->children[0], p1f, p2f, p1, p2);
-CM_RecursiveHullCheck (node->children[1], p1f, p2f, p1, p2);
-return;
-#endif
+	/*
+	CM_RecursiveHullCheck (node->children[0], p1f, p2f, p1, p2);
+	CM_RecursiveHullCheck (node->children[1], p1f, p2f, p1, p2);
+	return;
+	*/
 
 	// see which sides we need to consider
 	if (t1 >= offset && t2 >= offset)
--- a/qcommon/common.c
+++ b/qcommon/common.c
@@ -18,8 +18,11 @@
 
 */
 // common.c -- misc functions used in client and server
-#include "qcommon.h"
-#include <setjmp.h>
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 
 #define	MAXPRINTMSG	4096
 
@@ -1208,11 +1211,11 @@
 
 ====================
 */
-byte	COM_BlockSequenceCheckByte (byte *base, int length, int sequence, int challenge)
+byte	COM_BlockSequenceCheckByte (byte */*base*/, int /*length*/, int /*sequence*/, int /*challenge*/)
 {
 	Sys_Error("COM_BlockSequenceCheckByte called\n");
 
-#if 0
+/*
 	int		checksum;
 	byte	buf[68];
 	byte	*p;
@@ -1248,7 +1251,7 @@
 	checksum &= 0xff;
 
 	return checksum;
-#endif
+*/
 	return 0;
 }
 
@@ -1363,7 +1366,7 @@
 
 //========================================================
 
-float	frand(void)
+float	qfrand(void)
 {
 	return (rand()&32767)* (1.0/32767);
 }
@@ -1450,7 +1453,7 @@
 	dedicated = Cvar_Get ("dedicated", "0", CVAR_NOSET);
 #endif
 
-	s = va("%4.2f %s %s %s", VERSION, CPUSTRING, __DATE__, BUILDSTRING);
+	s = va("%4.2f %s Nov 30 1997 %s", VERSION, CPUSTRING, BUILDSTRING);
 	Cvar_Get ("version", s, CVAR_SERVERINFO|CVAR_NOSET);
 
 
@@ -1491,7 +1494,7 @@
 void Qcommon_Frame (int msec)
 {
 	char	*s;
-	int		time_before, time_between, time_after;
+	int		time_before = 0, time_between = 0, time_after = 0;
 
 	if (setjmp (abortframe) )
 		return;			// an ERR_DROP was thrown
--- a/qcommon/crc.c
+++ b/qcommon/crc.c
@@ -17,9 +17,11 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-/* crc.c */
-
-#include "qcommon.h"
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 
 // this is a 16 bit, non-reflected CRC using the polynomial 0x1021
 // and the initial and final xor values shown below...  in other words, the
--- a/qcommon/cvar.c
+++ b/qcommon/cvar.c
@@ -19,7 +19,11 @@
 */
 // cvar.c -- dynamic variable tracking
 
-#include "qcommon.h"
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 
 cvar_t	*cvar_vars;
 
--- a/qcommon/files.c
+++ b/qcommon/files.c
@@ -17,9 +17,12 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 
-#include "qcommon.h"
-
 // define this to dissalow any data but the demo pak file
 //#define	NO_ADDONS
 
@@ -156,18 +159,12 @@
 /*
 	Developer_searchpath
 */
-int	Developer_searchpath (int who)
+int	Developer_searchpath (int /*who*/)
 {
 	
-	int		ch;
 	// PMM - warning removal
 //	char	*start;
 	searchpath_t	*search;
-	
-	if (who == 1) // xatrix
-		ch = 'x';
-	else if (who == 2)
-		ch = 'r';
 
 	for (search = fs_searchpaths ; search ; search = search->next)
 	{
@@ -397,8 +394,6 @@
 	byte	*buf;
 	int		len;
 
-	buf = NULL;	// quiet compiler warning
-
 // look for it in the filesystem or pack files
 	len = FS_FOpenFile (path, &h);
 	if (!h)
@@ -482,6 +477,8 @@
 #ifdef NO_ADDONS
 	if (checksum != PAK0_CHECKSUM)
 		return NULL;
+#else
+	USED(checksum);
 #endif
 // parse the directory
 	for (i=0 ; i<numpackfiles ; i++)
@@ -688,7 +685,7 @@
 {
 	char *s;
 	int nfiles = 0;
-	char **list = 0;
+	char **list;
 
 	s = Sys_FindFirst( findname, musthave, canthave );
 	while ( s )
@@ -715,9 +712,6 @@
 		if ( s[strlen(s)-1] != '.' )
 		{
 			list[nfiles] = strdup( s );
-#ifdef _WIN32
-			strlwr( list[nfiles] );
-#endif
 			nfiles++;
 		}
 		s = Sys_FindNext( musthave, canthave );
--- a/qcommon/md4.c
+++ b/qcommon/md4.c
@@ -1,6 +1,10 @@
 /* GLOBAL.H - RSAREF types and constants */
 
-#include <string.h>
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 
 /* POINTER defines a generic pointer type */
 typedef unsigned char *POINTER;
@@ -9,11 +13,7 @@
 typedef unsigned short int UINT2;
 
 /* UINT4 defines a four byte word */
-#ifdef __alpha__
-typedef unsigned int UINT4;
-#else
 typedef unsigned long int UINT4;
-#endif
 
   
 /* MD4.H - header file for MD4C.C */
@@ -22,9 +22,9 @@
 
 All rights reserved.
   
-License to copy and use this software is granted provided that it is identified as the �RSA Data Security, Inc. MD4 Message-Digest Algorithm� in all material mentioning or referencing this software or this function.
-License is also granted to make and use derivative works provided that such works are identified as �derived from the RSA Data Security, Inc. MD4 Message-Digest Algorithm� in all material mentioning or referencing the derived work.
-RSA Data Security, Inc. makes no representations concerning either the merchantability of this software or the suitability of this software for any particular purpose. It is provided �as is� without express or implied warranty of any kind.
+License to copy and use this software is granted provided that it is identified as the �RSA Data Security, Inc. MD4 Message-Digest Algorithm� in all material mentioning or referencing this software or this function.
+License is also granted to make and use derivative works provided that such works are identified as �derived from the RSA Data Security, Inc. MD4 Message-Digest Algorithm� in all material mentioning or referencing the derived work.
+RSA Data Security, Inc. makes no representations concerning either the merchantability of this software or the suitability of this software for any particular purpose. It is provided �as is� without express or implied warranty of any kind.
   
 These notices must be retained in any copies of any part of this documentation and/or software. */
 
--- a/qcommon/net_chan.c
+++ b/qcommon/net_chan.c
@@ -17,9 +17,12 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 
-#include "qcommon.h"
-
 /*
 
 packet header
@@ -299,7 +302,6 @@
 {
 	unsigned	sequence, sequence_ack;
 	unsigned	reliable_ack, reliable_message;
-	int			qport;
 
 // get sequence numbers		
 	MSG_BeginReading (msg);
@@ -308,7 +310,7 @@
 
 	// read the qport if we are a server
 	if (chan->sock == NS_SERVER)
-		qport = MSG_ReadShort (msg);
+		MSG_ReadShort (msg);	/* toss read */
 
 	reliable_message = sequence >> 31;
 	reliable_ack = sequence_ack >> 31;
--- a/qcommon/pmove.c
+++ b/qcommon/pmove.c
@@ -17,11 +17,13 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 
-#include "qcommon.h"
 
-
-
 #define	STEPSIZE	18
 
 // all of the locals will be zeroed before each
@@ -171,7 +173,7 @@
 		VectorCopy (trace.plane.normal, planes[numplanes]);
 		numplanes++;
 
-#if 0
+/* commented out in release
 	float		rub;
 
 		//
@@ -212,7 +214,7 @@
 			break;
 		}
 
-#else
+*/
 //
 // modify original_velocity so it parallels all of the clip planes
 //
@@ -244,7 +246,6 @@
 			d = DotProduct (dir, pml.velocity);
 			VectorScale (dir, d, pml.velocity);
 		}
-#endif
 		//
 		// if velocity is against the original velocity, stop dead
 		// to avoid tiny occilations in sloping corners
@@ -307,13 +308,13 @@
 		VectorCopy (trace.endpos, pml.origin);
 	}
 
-#if 0
+/*
 	VectorSubtract (pml.origin, up, delta);
 	up_dist = DotProduct (delta, start_v);
 
 	VectorSubtract (down_o, start_o, delta);
 	down_dist = DotProduct (delta, start_v);
-#else
+*/
 	VectorCopy(pml.origin, up);
 
 	// decide which one went farther
@@ -321,7 +322,6 @@
         + (down_o[1] - start_o[1])*(down_o[1] - start_o[1]);
     up_dist = (up[0] - start_o[0])*(up[0] - start_o[0])
         + (up[1] - start_o[1])*(up[1] - start_o[1]);
-#endif
 
 	if (down_dist > up_dist || trace.plane.normal[2] < MIN_STEP_NORMAL)
 	{
@@ -585,12 +585,12 @@
 	smove = pm->cmd.sidemove;
 	
 //!!!!! pitch should be 1/3 so this isn't needed??!
-#if 0
+/*
 	pml.forward[2] = 0;
 	pml.right[2] = 0;
 	VectorNormalize (pml.forward);
 	VectorNormalize (pml.right);
-#endif
+*/
 
 	for (i=0 ; i<2 ; i++)
 		wishvel[i] = pml.forward[i]*fmove + pml.right[i]*smove;
@@ -727,10 +727,10 @@
 			}
 		}
 
-#if 0
+/*
 		if (trace.fraction < 1.0 && trace.ent && pml.velocity[2] < 0)
 			pml.velocity[2] = 0;
-#endif
+*/
 
 		if (pm->numtouch < MAXTOUCH && trace.ent)
 		{
@@ -1120,8 +1120,6 @@
 //	Com_DPrintf ("using previous_origin\n");
 }
 
-#if 0
-//NO LONGER USED
 /*
 ================
 PM_InitialSnapPosition
@@ -1128,6 +1126,7 @@
 
 ================
 */
+/* NO LONGER USED
 void PM_InitialSnapPosition (void)
 {
 	int		x, y, z;
@@ -1158,7 +1157,7 @@
 
 	Com_DPrintf ("Bad InitialSnapPosition\n");
 }
-#else
+*/
 /*
 ================
 PM_InitialSnapPosition
@@ -1192,8 +1191,6 @@
 
 	Com_DPrintf ("Bad InitialSnapPosition\n");
 }
-
-#endif
 
 /*
 ================
--- a/qcommon/qcommon.h
+++ b/qcommon/qcommon.h
@@ -17,12 +17,9 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-
 // qcommon.h -- definitions common between client and server, but not game.dll
+/* FIXME: ^- lies */
 
-#include "../q_shared.h"
-
-
 #define	VERSION		3.19
 
 #define	BASEDIRNAME	"baseq2"
@@ -352,10 +349,6 @@
 
 */
 
-#define	EXEC_NOW	0		// don't return until completed
-#define	EXEC_INSERT	1		// insert at current position, but don't run yet
-#define	EXEC_APPEND	2		// add to end of the command buffer
-
 void Cbuf_Init (void);
 // allocates an initial text buffer that will grow as needed
 
@@ -622,8 +615,6 @@
 */
 
 
-#include "../qcommon/qfiles.h"
-
 cmodel_t	*CM_LoadMap (char *name, qboolean clientload, unsigned *checksum);
 cmodel_t	*CM_InlineModel (char *name);	// *1, *2, etc
 
@@ -722,10 +713,10 @@
 ==============================================================
 */
 
-
 #define	ERR_FATAL	0		// exit the entire game with a popup window
 #define	ERR_DROP	1		// print to console and disconnect from game
 #define	ERR_QUIT	2		// not an error, just a normal exit
+#define	ERR_DISCONNECT	2		// don't kill server
 
 #define	EXEC_NOW	0		// don't return until completed
 #define	EXEC_INSERT	1		// insert at current position, but don't run yet
@@ -747,7 +738,7 @@
 unsigned	Com_BlockChecksum (void *buffer, int length);
 byte		COM_BlockSequenceCRCByte (byte *base, int length, int sequence);
 
-float	frand(void);	// 0 ti 1
+float	qfrand(void);	// 0 ti 1
 float	crand(void);	// -1 to 1
 
 extern	cvar_t	*developer;
@@ -792,8 +783,6 @@
 void	Sys_AppActivate (void);
 
 void	Sys_UnloadGame (void);
-void	*Sys_GetGameAPI (void *parms);
-// loads the game dll and calls the api init function
 
 char	*Sys_ConsoleInput (void);
 void	Sys_ConsoleOutput (char *string);
@@ -821,6 +810,3 @@
 void SV_Init (void);
 void SV_Shutdown (char *finalmsg, qboolean reconnect);
 void SV_Frame (int msec);
-
-
-
--- a/qcommon/qfiles.h
+++ b/qcommon/qfiles.h
@@ -329,6 +329,7 @@
 
 // these definitions also need to be in q_shared.h!
 
+/* ^-- macro redefinitions
 // lower bits are stronger, and will eat weaker brushes completely
 #define	CONTENTS_SOLID			1		// an eye is never valid in a solid
 #define	CONTENTS_WINDOW			2		// translucent, but not watery
@@ -374,7 +375,7 @@
 #define	SURF_TRANS66	0x20
 #define	SURF_FLOWING	0x40	// scroll towards angle
 #define	SURF_NODRAW		0x80	// don't bother referencing the texture
-
+*/
 
 
 
--- a/ref/r_aclip.c
+++ b/ref/r_aclip.c
@@ -19,7 +19,11 @@
 */
 // r_aclip.c: clip routines for drawing Alias models directly to the screen
 
-#include "r_local.h"
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 
 static finalvert_t		fv[2][8];
 
@@ -60,8 +64,6 @@
 }
 
 
-#if	!id386
-
 void R_Alias_clip_left (finalvert_t *pfv0, finalvert_t *pfv1, finalvert_t *out)
 {
 	float		scale;
@@ -179,8 +181,6 @@
 		out->zi = pfv1->zi + ( pfv0->zi - pfv1->zi) * scale + 0.5;
 	}
 }
-
-#endif
 
 
 int R_AliasClip (finalvert_t *in, finalvert_t *out, int flag, int count,
--- a/ref/r_alias.c
+++ b/ref/r_alias.c
@@ -22,7 +22,11 @@
 /*
 ** use a real variable to control lerping
 */
-#include "r_local.h"
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 
 #define LIGHT_MIN	5		// lowest light value we'll allow, to avoid the
 							//  need for inner-loop light clamping
@@ -55,8 +59,6 @@
 static vec3_t	s_alias_forward, s_alias_right, s_alias_up;
 
 
-#define NUMVERTEXNORMALS	162
-
 float	r_avertexnormals[NUMVERTEXNORMALS][3] = {
 #include "../anorms.h"
 };
@@ -105,7 +107,7 @@
 	vec3_t        mins, maxs;
 	vec3_t        transformed_min, transformed_max;
 	qboolean      zclipped = false, zfullyclipped = true;
-	float         minz = 9999.0F;
+	//float         minz = 9999.0F;
 
 	/*
 	** get the exact frame bounding box
@@ -265,7 +267,7 @@
 
 	// put work vertexes on stack, cache aligned
 	pfinalverts = (finalvert_t *)
-			(((long)&finalverts[0] + CACHE_SIZE - 1) & ~(CACHE_SIZE - 1));
+			(((uintptr)&finalverts[0] + CACHE_SIZE - 1) & ~(CACHE_SIZE - 1));
 
 	aliasbatchedtransformdata.num_points = s_pmdl->num_xyz;
 	aliasbatchedtransformdata.last_verts = r_lastframe->verts;
@@ -429,326 +431,8 @@
 R_AliasTransformFinalVerts
 ================
 */
-#if id386 && !defined __linux__
 void R_AliasTransformFinalVerts( int numpoints, finalvert_t *fv, dtrivertx_t *oldv, dtrivertx_t *newv )
 {
-	float  lightcos;
-	float	lerped_vert[3];
-	int    byte_to_dword_ptr_var;
-	int    tmpint;
-
-	float  one = 1.0F;
-	float  zi;
-
-	static float  FALIAS_Z_CLIP_PLANE = ALIAS_Z_CLIP_PLANE;
-	static float  PS_SCALE = POWERSUIT_SCALE;
-
-	__asm mov ecx, numpoints
-
-	/*
-	lerped_vert[0] = r_lerp_move[0] + oldv->v[0]*r_lerp_backv[0] + newv->v[0]*r_lerp_frontv[0];
-	lerped_vert[1] = r_lerp_move[1] + oldv->v[1]*r_lerp_backv[1] + newv->v[1]*r_lerp_frontv[1];
-	lerped_vert[2] = r_lerp_move[2] + oldv->v[2]*r_lerp_backv[2] + newv->v[2]*r_lerp_frontv[2];
-	*/
-top_of_loop:
-
-	__asm mov esi, oldv
-	__asm mov edi, newv
-
-	__asm xor ebx, ebx
-
-	__asm mov bl, byte ptr [esi+DTRIVERTX_V0]
-	__asm mov byte_to_dword_ptr_var, ebx
-	__asm fild dword ptr byte_to_dword_ptr_var      
-	__asm fmul dword ptr [r_lerp_backv+0]                  ; oldv[0]*rlb[0]
-
-	__asm mov bl, byte ptr [esi+DTRIVERTX_V1]
-	__asm mov byte_to_dword_ptr_var, ebx
-	__asm fild dword ptr byte_to_dword_ptr_var
-	__asm fmul dword ptr [r_lerp_backv+4]                  ; oldv[1]*rlb[1] | oldv[0]*rlb[0]
-
-	__asm mov bl, byte ptr [esi+DTRIVERTX_V2]
-	__asm mov byte_to_dword_ptr_var, ebx
-	__asm fild dword ptr byte_to_dword_ptr_var
-	__asm fmul dword ptr [r_lerp_backv+8]                  ; oldv[2]*rlb[2] | oldv[1]*rlb[1] | oldv[0]*rlb[0]
-
-	__asm mov bl, byte ptr [edi+DTRIVERTX_V0]
-	__asm mov byte_to_dword_ptr_var, ebx
-	__asm fild dword ptr byte_to_dword_ptr_var      
-	__asm fmul dword ptr [r_lerp_frontv+0]                 ; newv[0]*rlf[0] | oldv[2]*rlb[2] | oldv[1]*rlb[1] | oldv[0]*rlb[0]
-
-	__asm mov bl, byte ptr [edi+DTRIVERTX_V1]
-	__asm mov byte_to_dword_ptr_var, ebx
-	__asm fild dword ptr byte_to_dword_ptr_var
-	__asm fmul dword ptr [r_lerp_frontv+4]                 ; newv[1]*rlf[1] | newv[0]*rlf[0] | oldv[2]*rlb[2] | oldv[1]*rlb[1] | oldv[0]*rlb[0]
-
-	__asm mov bl, byte ptr [edi+DTRIVERTX_V2]
-	__asm mov byte_to_dword_ptr_var, ebx
-	__asm fild dword ptr byte_to_dword_ptr_var
-	__asm fmul dword ptr [r_lerp_frontv+8]                 ; newv[2]*rlf[2] | newv[1]*rlf[1] | newv[0]*rlf[0] | oldv[2]*rlb[2] | oldv[1]*rlb[1] | oldv[0]*rlb[0]
-
-	__asm fxch st(5)                     ; oldv[0]*rlb[0] | newv[1]*rlf[1] | newv[0]*rlf[0] | oldv[2]*rlb[2] | oldv[1]*rlb[1] | newv[2]*rlf[2]
-	__asm faddp st(2), st                ; newv[1]*rlf[1] | oldv[0]*rlb[0] + newv[0]*rlf[0] | oldv[2]*rlb[2] | oldv[1]*rlb[1] | newv[2]*rlf[2]
-	__asm faddp st(3), st                ; oldv[0]*rlb[0] + newv[0]*rlf[0] | oldv[2]*rlb[2] | oldv[1]*rlb[1] + newv[1]*rlf[1] | newv[2]*rlf[2]
-	__asm fxch st(1)                     ; oldv[2]*rlb[2] | oldv[0]*rlb[0] + newv[0]*rlf[0] | oldv[1]*rlb[1] + newv[1]*rlf[1] | newv[2]*rlf[2]
-	__asm faddp st(3), st                ; oldv[0]*rlb[0] + newv[0]*rlf[0] | oldv[1]*rlb[1] + newv[1]*rlf[1] | oldv[2]*rlb[2] + newv[2]*rlf[2]
-	__asm fadd dword ptr [r_lerp_move+0] ; lv0 | oldv[1]*rlb[1] + newv[1]*rlf[1] | oldv[2]*rlb[2] + newv[2]*rlf[2]
-	__asm fxch st(1)                     ; oldv[1]*rlb[1] + newv[1]*rlf[1] | lv0 | oldv[2]*rlb[2] + newv[2]*rlf[2]
-	__asm fadd dword ptr [r_lerp_move+4] ; lv1 | lv0 | oldv[2]*rlb[2] + newv[2]*rlf[2]
-	__asm fxch st(2)                     ; oldv[2]*rlb[2] + newv[2]*rlf[2] | lv0 | lv1
-	__asm fadd dword ptr [r_lerp_move+8] ; lv2 | lv0 | lv1
-	__asm fxch st(1)                     ; lv0 | lv2 | lv1
-	__asm fstp dword ptr [lerped_vert+0] ; lv2 | lv1
-	__asm fstp dword ptr [lerped_vert+8] ; lv2
-	__asm fstp dword ptr [lerped_vert+4] ; (empty)
-
-	__asm mov  eax, currententity
-	__asm mov  eax, dword ptr [eax+ENTITY_FLAGS]
-	__asm mov  ebx, RF_SHELL_RED | RF_SHELL_GREEN | RF_SHELL_BLUE | RF_SHELL_DOUBLE | RF_SHELL_HALF_DAM
-	__asm and  eax, ebx
-	__asm jz   not_powersuit
-
-	/*
-	**    lerped_vert[0] += lightnormal[0] * POWERSUIT_SCALE
-	**    lerped_vert[1] += lightnormal[1] * POWERSUIT_SCALE
-	**    lerped_vert[2] += lightnormal[2] * POWERSUIT_SCALE
-	*/
-
-	__asm xor ebx, ebx
-	__asm mov bl,  byte ptr [edi+DTRIVERTX_LNI]
-	__asm mov eax, 12
-	__asm mul ebx
-	__asm lea eax, [r_avertexnormals+eax]
-
-	__asm fld  dword ptr [eax+0]				; n[0]
-	__asm fmul PS_SCALE							; n[0] * PS
-	__asm fld  dword ptr [eax+4]				; n[1] | n[0] * PS
-	__asm fmul PS_SCALE							; n[1] * PS | n[0] * PS
-	__asm fld  dword ptr [eax+8]				; n[2] | n[1] * PS | n[0] * PS
-	__asm fmul PS_SCALE							; n[2] * PS | n[1] * PS | n[0] * PS
-	__asm fld  dword ptr [lerped_vert+0]		; lv0 | n[2] * PS | n[1] * PS | n[0] * PS
-	__asm faddp st(3), st						; n[2] * PS | n[1] * PS | n[0] * PS + lv0
-	__asm fld  dword ptr [lerped_vert+4]		; lv1 | n[2] * PS | n[1] * PS | n[0] * PS + lv0
-	__asm faddp st(2), st						; n[2] * PS | n[1] * PS + lv1 | n[0] * PS + lv0
-	__asm fadd dword ptr [lerped_vert+8]		; n[2] * PS + lv2 | n[1] * PS + lv1 | n[0] * PS + lv0
-	__asm fxch st(2)							; LV0 | LV1 | LV2
-	__asm fstp dword ptr [lerped_vert+0]		; LV1 | LV2
-	__asm fstp dword ptr [lerped_vert+4]		; LV2
-	__asm fstp dword ptr [lerped_vert+8]		; (empty)
-
-not_powersuit:
-
-	/*
-	fv->flags = 0;
-
-	fv->xyz[0] = DotProduct(lerped_vert, aliastransform[0]) + aliastransform[0][3];
-	fv->xyz[1] = DotProduct(lerped_vert, aliastransform[1]) + aliastransform[1][3];
-	fv->xyz[2] = DotProduct(lerped_vert, aliastransform[2]) + aliastransform[2][3];
-	*/
-	__asm mov  eax, fv
-	__asm mov  dword ptr [eax+FINALVERT_FLAGS], 0
-
-	__asm fld  dword ptr [lerped_vert+0]           ; lv0
-	__asm fmul dword ptr [aliastransform+0]        ; lv0*at[0][0]
-	__asm fld  dword ptr [lerped_vert+4]           ; lv1 | lv0*at[0][0]
-	__asm fmul dword ptr [aliastransform+4]        ; lv1*at[0][1] | lv0*at[0][0]
-	__asm fld  dword ptr [lerped_vert+8]           ; lv2 | lv1*at[0][1] | lv0*at[0][0]
-	__asm fmul dword ptr [aliastransform+8]        ; lv2*at[0][2] | lv1*at[0][1] | lv0*at[0][0]
-	__asm fxch st(2)                               ; lv0*at[0][0] | lv1*at[0][1] | lv2*at[0][2]
-	__asm faddp st(1), st                          ; lv0*at[0][0] + lv1*at[0][1] | lv2*at[0][2]
-	__asm faddp st(1), st                          ; lv0*at[0][0] + lv1*at[0][1] + lv2*at[0][2]
-	__asm fadd  dword ptr [aliastransform+12]      ; FV.X
-
-	__asm fld  dword ptr [lerped_vert+0]           ; lv0
-	__asm fmul dword ptr [aliastransform+16]       ; lv0*at[1][0]
-	__asm fld  dword ptr [lerped_vert+4]           ; lv1 | lv0*at[1][0]
-	__asm fmul dword ptr [aliastransform+20]       ; lv1*at[1][1] | lv0*at[1][0]
-	__asm fld  dword ptr [lerped_vert+8]           ; lv2 | lv1*at[1][1] | lv0*at[1][0]
-	__asm fmul dword ptr [aliastransform+24]       ; lv2*at[1][2] | lv1*at[1][1] | lv0*at[1][0]
-	__asm fxch st(2)                               ; lv0*at[1][0] | lv1*at[1][1] | lv2*at[1][2]
-	__asm faddp st(1), st                          ; lv0*at[1][0] + lv1*at[1][1] | lv2*at[1][2]
-	__asm faddp st(1), st                          ; lv0*at[1][0] + lv1*at[1][1] + lv2*at[1][2]
-	__asm fadd dword ptr [aliastransform+28]       ; FV.Y | FV.X
-	__asm fxch st(1)                               ; FV.X | FV.Y
-	__asm fstp  dword ptr [eax+FINALVERT_X]        ; FV.Y
-	
-	__asm fld  dword ptr [lerped_vert+0]           ; lv0
-	__asm fmul dword ptr [aliastransform+32]       ; lv0*at[2][0]
-	__asm fld  dword ptr [lerped_vert+4]           ; lv1 | lv0*at[2][0]
-	__asm fmul dword ptr [aliastransform+36]       ; lv1*at[2][1] | lv0*at[2][0]
-	__asm fld  dword ptr [lerped_vert+8]           ; lv2 | lv1*at[2][1] | lv0*at[2][0]
-	__asm fmul dword ptr [aliastransform+40]       ; lv2*at[2][2] | lv1*at[2][1] | lv0*at[2][0]
-	__asm fxch st(2)                               ; lv0*at[2][0] | lv1*at[2][1] | lv2*at[2][2]
-	__asm faddp st(1), st                          ; lv0*at[2][0] + lv1*at[2][1] | lv2*at[2][2]
-	__asm faddp st(1), st                          ; lv0*at[2][0] + lv1*at[2][1] + lv2*at[2][2]
-	__asm fadd dword ptr [aliastransform+44]       ; FV.Z | FV.Y
-	__asm fxch st(1)                               ; FV.Y | FV.Z
-	__asm fstp dword ptr [eax+FINALVERT_Y]         ; FV.Z
-	__asm fstp dword ptr [eax+FINALVERT_Z]         ; (empty)
-
-	/*
-	**  lighting
-	**
-	**  plightnormal = r_avertexnormals[newv->lightnormalindex];
-	**	lightcos = DotProduct (plightnormal, r_plightvec);
-	**	temp = r_ambientlight;
-	*/
-	__asm xor ebx, ebx
-	__asm mov bl,  byte ptr [edi+DTRIVERTX_LNI]
-	__asm mov eax, 12
-	__asm mul ebx
-	__asm lea eax, [r_avertexnormals+eax]
-	__asm lea ebx, r_plightvec
-
-	__asm fld  dword ptr [eax+0]
-	__asm fmul dword ptr [ebx+0]
-	__asm fld  dword ptr [eax+4]
-	__asm fmul dword ptr [ebx+4]
-	__asm fld  dword ptr [eax+8]
-	__asm fmul dword ptr [ebx+8]
-	__asm fxch st(2)
-	__asm faddp st(1), st
-	__asm faddp st(1), st
-	__asm fstp dword ptr lightcos
-	__asm mov eax, lightcos
-	__asm mov ebx, r_ambientlight
-
-	/*
-	if (lightcos < 0)
-	{
-		temp += (int)(r_shadelight * lightcos);
-
-		// clamp; because we limited the minimum ambient and shading light, we
-		// don't have to clamp low light, just bright
-		if (temp < 0)
-			temp = 0;
-	}
-
-	fv->v[4] = temp;
-	*/
-	__asm or  eax, eax
-	__asm jns store_fv4
-
-	__asm fld   dword ptr r_shadelight
-	__asm fmul  dword ptr lightcos
-	__asm fistp dword ptr tmpint
-	__asm add   ebx, tmpint
-
-	__asm or    ebx, ebx
-	__asm jns   store_fv4
-	__asm mov   ebx, 0
-
-store_fv4:
-	__asm mov edi, fv
-	__asm mov dword ptr [edi+FINALVERT_V4], ebx
-
-	__asm mov edx, dword ptr [edi+FINALVERT_FLAGS]
-
-	/*
-	** do clip testing and projection here
-	*/
-	/*
-	if ( dest_vert->xyz[2] < ALIAS_Z_CLIP_PLANE )
-	{
-		dest_vert->flags |= ALIAS_Z_CLIP;
-	}
-	else
-	{
-		R_AliasProjectAndClipTestFinalVert( dest_vert );
-	}
-	*/
-	__asm mov eax, dword ptr [edi+FINALVERT_Z]
-	__asm and eax, eax
-	__asm js  alias_z_clip
-	__asm cmp eax, FALIAS_Z_CLIP_PLANE
-	__asm jl  alias_z_clip
-
-	/*
-	This is the code to R_AliasProjectAndClipTestFinalVert
-
-	float	zi;
-	float	x, y, z;
-
-	x = fv->xyz[0];
-	y = fv->xyz[1];
-	z = fv->xyz[2];
-	zi = 1.0 / z;
-
-	fv->v[5] = zi * s_ziscale;
-
-	fv->v[0] = (x * aliasxscale * zi) + aliasxcenter;
-	fv->v[1] = (y * aliasyscale * zi) + aliasycenter;
-	*/
-	__asm fld   one                             ; 1
-	__asm fdiv  dword ptr [edi+FINALVERT_Z]     ; zi
-
-	__asm mov   eax, dword ptr [edi+32]
-	__asm mov   eax, dword ptr [edi+64]
-
-	__asm fst   zi                              ; zi
-	__asm fmul  s_ziscale                       ; fv5
-	__asm fld   dword ptr [edi+FINALVERT_X]     ; x | fv5
-	__asm fmul  aliasxscale                     ; x * aliasxscale | fv5
-	__asm fld   dword ptr [edi+FINALVERT_Y]     ; y | x * aliasxscale | fv5
-	__asm fmul  aliasyscale                     ; y * aliasyscale | x * aliasxscale | fv5
-	__asm fxch  st(1)                           ; x * aliasxscale | y * aliasyscale | fv5
-	__asm fmul  zi                              ; x * asx * zi | y * asy | fv5
-	__asm fadd  aliasxcenter                    ; fv0 | y * asy | fv5
-	__asm fxch  st(1)                           ; y * asy | fv0 | fv5
-	__asm fmul  zi                              ; y * asy * zi | fv0 | fv5
-	__asm fadd  aliasycenter                    ; fv1 | fv0 | fv5
-	__asm fxch  st(2)                           ; fv5 | fv0 | fv1
-	__asm fistp dword ptr [edi+FINALVERT_V5]    ; fv0 | fv1
-	__asm fistp dword ptr [edi+FINALVERT_V0]    ; fv1
-	__asm fistp dword ptr [edi+FINALVERT_V1]    ; (empty)
-
-	/*
-	if (fv->v[0] < r_refdef.aliasvrect.x)
-		fv->flags |= ALIAS_LEFT_CLIP;
-	if (fv->v[1] < r_refdef.aliasvrect.y)
-		fv->flags |= ALIAS_TOP_CLIP;
-	if (fv->v[0] > r_refdef.aliasvrectright)
-		fv->flags |= ALIAS_RIGHT_CLIP;
-	if (fv->v[1] > r_refdef.aliasvrectbottom)
-		fv->flags |= ALIAS_BOTTOM_CLIP;
-	*/
-	__asm mov eax, dword ptr [edi+FINALVERT_V0]
-	__asm mov ebx, dword ptr [edi+FINALVERT_V1]
-
-	__asm cmp eax, r_refdef.aliasvrect.x
-	__asm jge ct_alias_top
-	__asm or  edx, ALIAS_LEFT_CLIP
-ct_alias_top:
-	__asm cmp ebx, r_refdef.aliasvrect.y
-	__asm jge ct_alias_right
-	__asm or edx, ALIAS_TOP_CLIP
-ct_alias_right:
-	__asm cmp eax, r_refdef.aliasvrectright
-	__asm jle ct_alias_bottom
-	__asm or edx, ALIAS_RIGHT_CLIP
-ct_alias_bottom:
-	__asm cmp ebx, r_refdef.aliasvrectbottom
-	__asm jle end_of_loop
-	__asm or  edx, ALIAS_BOTTOM_CLIP
-
-	__asm jmp end_of_loop
-
-alias_z_clip:
-	__asm or  edx, ALIAS_Z_CLIP
-
-end_of_loop:
-
-	__asm mov dword ptr [edi+FINALVERT_FLAGS], edx
-	__asm add oldv, DTRIVERTX_SIZE
-	__asm add newv, DTRIVERTX_SIZE
-	__asm add fv, FINALVERT_SIZE
-
-	__asm dec ecx
-	__asm jnz top_of_loop
-}
-#else
-void R_AliasTransformFinalVerts( int numpoints, finalvert_t *fv, dtrivertx_t *oldv, dtrivertx_t *newv )
-{
 	int i;
 
 	for ( i = 0; i < numpoints; i++, fv++, oldv++, newv++ )
@@ -804,8 +488,6 @@
 	}
 }
 
-#endif
-
 /*
 ================
 R_AliasProjectAndClipTestFinalVert
@@ -1002,7 +684,7 @@
 **
 ** Precomputes lerp coefficients used for the whole frame.
 */
-void R_AliasSetUpLerpData( dmdl_t *pmdl, float backlerp )
+void R_AliasSetUpLerpData( dmdl_t */*pmdl*/, float backlerp )
 {
 	float	frontlerp;
 	vec3_t	translation, vectors[3];
--- a/ref/r_bsp.c
+++ b/ref/r_bsp.c
@@ -17,9 +17,11 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-// r_bsp.c
-
-#include "r_local.h"
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 
 //
 // current entity info
--- a/ref/r_draw.c
+++ b/ref/r_draw.c
@@ -17,10 +17,11 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-
-// draw.c
-
-#include "r_local.h"
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 
 
 image_t		*draw_chars;				// 8*8 graphic characters
--- a/ref/r_edge.c
+++ b/ref/r_edge.c
@@ -17,11 +17,12 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-// r_edge.c
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 
-#include "r_local.h"
-
-#ifndef id386
 void R_SurfacePatch (void)
 {
 }
@@ -33,16 +34,15 @@
 void R_EdgeCodeEnd (void)
 {
 }
-#endif
 
 
-#if 0
+/*
 the complex cases add new polys on most lines, so dont optimize for keeping them the same
 have multiple free span lists to try to get better coherence?
 low depth complexity -- 1 to 3 or so
 
 have a sentinal at both ends?
-#endif
+*/
 
 
 edge_t	*auxedges;
@@ -139,9 +139,6 @@
 	}
 }
 
-
-#if	!id386
-
 /*
 ==============
 R_InsertNewEdges
@@ -183,11 +180,7 @@
 	} while ((edgestoadd = next_edge) != NULL);
 }
 
-#endif	// !id386
-	
 
-#if	!id386
-
 /*
 ==============
 R_RemoveEdges
@@ -203,11 +196,7 @@
 	} while ((pedge = pedge->nextremove) != NULL);
 }
 
-#endif	// !id386
 
-
-#if	!id386
-
 /*
 ==============
 R_StepActiveU
@@ -273,9 +262,7 @@
 	}
 }
 
-#endif	// !id386
 
-
 /*
 ==============
 R_CleanupSpan
@@ -429,8 +416,6 @@
 }
 
 
-#if	!id386
-
 /*
 ==============
 R_LeadingEdge
@@ -590,9 +575,7 @@
 	R_CleanupSpan ();
 }
 
-#endif	// !id386
 
-
 /*
 ==============
 R_GenerateSpansBackward
@@ -640,7 +623,7 @@
 	surf_t	*s;
 
 	basespan_p = (espan_t *)
-			((long)(basespans + CACHE_SIZE - 1) & ~(CACHE_SIZE - 1));
+			((uintptr)(basespans + CACHE_SIZE - 1) & ~(CACHE_SIZE - 1));
 	max_span_p = &basespan_p[MAXSPANS - r_refdef.vrect.width];
 
 	span_p = basespan_p;
@@ -800,14 +783,11 @@
 */
 void D_CalcGradients (msurface_t *pface)
 {
-	mplane_t	*pplane;
 	float		mipscale;
 	vec3_t		p_temp1;
 	vec3_t		p_saxis, p_taxis;
 	float		t;
 
-	pplane = pface->plane;
-
 	mipscale = 1.0 / (float)(1 << miplevel);
 
 	TransformVector (pface->texinfo->vecs[0], p_saxis);
@@ -994,9 +974,7 @@
 		currententity = &r_worldentity;
 
 	pface = s->msurf;
-#if 1
-	miplevel = D_MipLevelForScale(s->nearzi * scale_for_mip * pface->texinfo->mipadjust);
-#else
+/* commented out in release
 	{
 		float dot;
 		float normal[3];
@@ -1021,7 +999,8 @@
 
 		miplevel = D_MipLevelForScale(s->nearzi * scale_for_mip * pface->texinfo->mipadjust);
 	}
-#endif
+*/
+	miplevel = D_MipLevelForScale(s->nearzi * scale_for_mip * pface->texinfo->mipadjust);
 
 // FIXME: make this passed in to D_CacheSurface
 	pcurrentcache = D_CacheSurface (pface, miplevel);
@@ -1074,7 +1053,7 @@
 
 		// make a stable color for each surface by taking the low
 		// bits of the msurface pointer
-		D_FlatFillSurface (s, (int)s->msurf & 0xFF);
+		D_FlatFillSurface (s, (uintptr)s->msurf & 0xFF);
 		D_DrawZSpans (s->spans);
 	}
 }
--- a/ref/r_image.c
+++ b/ref/r_image.c
@@ -17,10 +17,13 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 
-#include "r_local.h"
 
-
 #define	MAX_RIMAGES	1024
 image_t		r_images[MAX_RIMAGES];
 int			numr_images;
@@ -208,9 +211,9 @@
 	int		row, column;
 	byte	*buf_p;
 	byte	*buffer;
-	int		length;
 	TargaHeader		targa_header;
 	byte			*targa_rgba;
+	uchar	red = 0, green = 0, blue = 0, alphabyte = 0, packetHeader, packetSize, j;
 
 	*pic = NULL;
 
@@ -217,7 +220,7 @@
 	//
 	// load the file
 	//
-	length = ri.FS_LoadFile (name, (void **)&buffer);
+	ri.FS_LoadFile (name, (void **)&buffer);	/* int length = */
 	if (!buffer)
 	{
 		ri.Con_Printf (PRINT_DEVELOPER, "Bad tga file %s\n", name);
@@ -273,7 +276,6 @@
 		for(row=rows-1; row>=0; row--) {
 			pixbuf = targa_rgba + row*columns*4;
 			for(column=0; column<columns; column++) {
-				unsigned char red,green,blue,alphabyte;
 				switch (targa_header.pixel_size) {
 					case 24:
 							
@@ -300,7 +302,6 @@
 		}
 	}
 	else if (targa_header.image_type==10) {   // Runlength encoded RGB images
-		unsigned char red,green,blue,alphabyte,packetHeader,packetSize,j;
 		for(row=rows-1; row>=0; row--) {
 			pixbuf = targa_rgba + row*columns*4;
 			for(column=0; column<columns; ) {
--- a/ref/r_light.c
+++ b/ref/r_light.c
@@ -17,10 +17,12 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-// r_light.c
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 
-#include "r_local.h"
-
 int	r_dlightframecount;
 
 
@@ -227,7 +229,6 @@
 	float		r;
 	int			lnum;
 	dlight_t	*dl;
-	float		light;
 	vec3_t		dist;
 	float		add;
 	
@@ -255,7 +256,6 @@
 	//
 	// add dynamic lights
 	//
-	light = 0;
 	for (lnum=0 ; lnum<r_newrefdef.num_dlights ; lnum++)
 	{
 		dl = &r_newrefdef.dlights[lnum];
--- a/ref/r_local.h
+++ b/ref/r_local.h
@@ -17,17 +17,10 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-  
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <math.h>
-#include <stdarg.h>
 
-#include "../client/ref.h"
-
 #define REF_VERSION     "SOFT 0.01"
 
+/* macro redefinitions
 // up / down
 #define PITCH   0
 
@@ -36,8 +29,8 @@
 
 // fall over
 #define ROLL    2
+*/
 
-
 /*
 
   skins will be outline flood filled and mip mapped
@@ -70,28 +63,6 @@
 	byte		*pixels[4];				// mip levels
 } image_t;
 
-
-//===================================================================
-
-typedef unsigned char pixel_t;
-
-typedef struct vrect_s
-{
-	int                             x,y,width,height;
-	struct vrect_s  *pnext;
-} vrect_t;
-
-typedef struct
-{
-	pixel_t                 *buffer;                // invisible buffer
-	pixel_t                 *colormap;              // 256 * VID_GRADES size
-	pixel_t                 *alphamap;              // 256 * 256 translucency map
-	int                             rowbytes;               // may be > width if displayed in a window
-									// can be negative for stupid dibs
-	int						width;          
-	int						height;
-} viddef_t;
-
 typedef enum
 {
 	rserr_ok,
@@ -102,8 +73,6 @@
 	rserr_unknown
 } rserr_t;
 
-extern viddef_t vid;
-
 // !!! if this is changed, it must be changed in asm_draw.h too !!!
 typedef struct
 {
@@ -135,8 +104,241 @@
 
 extern oldrefdef_t      r_refdef;
 
-#include "r_model.h"
+/* r_model.h */
 
+/*
+d*_t structures are on-disk representations
+m*_t structures are in-memory
+*/
+
+
+/*
+==============================================================================
+
+BRUSH MODELS
+
+==============================================================================
+*/
+
+
+//
+// in memory representation
+//
+// !!! if this is changed, it must be changed in asm_draw.h too !!!
+typedef struct
+{
+	vec3_t		position;
+} mvertex_t;
+
+#define	SIDE_FRONT	0
+#define	SIDE_BACK	1
+#define	SIDE_ON		2
+
+
+// plane_t structure
+// !!! if this is changed, it must be changed in asm_i386.h too !!!
+typedef struct mplane_s
+{
+	vec3_t	normal;
+	float	dist;
+	byte	type;			// for texture axis selection and fast side tests
+	byte	signbits;		// signx + signy<<1 + signz<<1
+	byte	pad[2];
+} mplane_t;
+
+
+// FIXME: differentiate from texinfo SURF_ flags
+#define	SURF_PLANEBACK		2
+#define	SURF_DRAWSKY		4			// sky brush face
+#define SURF_DRAWTURB		0x10
+#define SURF_DRAWBACKGROUND	0x40
+#define SURF_DRAWSKYBOX		0x80		// sky box
+
+#define SURF_FLOW			0x100		//PGM
+
+// !!! if this is changed, it must be changed in asm_draw.h too !!!
+typedef struct
+{
+	unsigned short	v[2];
+	unsigned int	cachededgeoffset;
+} medge_t;
+
+typedef struct mtexinfo_s
+{
+	float		vecs[2][4];
+	float		mipadjust;
+	image_t		*image;
+	int			flags;
+	int			numframes;
+	struct mtexinfo_s	*next;		// animation chain
+} mtexinfo_t;
+
+typedef struct msurface_s
+{
+	int			visframe;		// should be drawn when node is crossed
+
+	int			dlightframe;
+	int			dlightbits;
+
+	mplane_t	*plane;
+	int			flags;
+
+	int			firstedge;	// look up in model->surfedges[], negative numbers
+	int			numedges;	// are backwards edges
+	
+// surface generation data
+	struct surfcache_s	*cachespots[MIPLEVELS];
+
+	short		texturemins[2];
+	short		extents[2];
+
+	mtexinfo_t	*texinfo;
+	
+// lighting info
+	byte		styles[MAXLIGHTMAPS];
+	byte		*samples;		// [numstyles*surfsize]
+
+	struct msurface_s *nextalphasurface;
+} msurface_t;
+
+
+#define	CONTENTS_NODE	-1
+typedef struct mnode_s
+{
+// common with leaf
+	int			contents;		// CONTENTS_NODE, to differentiate from leafs
+	int			visframe;		// node needs to be traversed if current
+	
+	short		minmaxs[6];		// for bounding box culling
+
+	struct mnode_s	*parent;
+
+// node specific
+	mplane_t	*plane;
+	struct mnode_s	*children[2];	
+
+	unsigned short		firstsurface;
+	unsigned short		numsurfaces;
+} mnode_t;
+
+
+
+typedef struct mleaf_s
+{
+// common with node
+	int			contents;		// wil be something other than CONTENTS_NODE
+	int			visframe;		// node needs to be traversed if current
+
+	short		minmaxs[6];		// for bounding box culling
+
+	struct mnode_s	*parent;
+
+// leaf specific
+	int			cluster;
+	int			area;
+
+	msurface_t	**firstmarksurface;
+	int			nummarksurfaces;
+	int			key;			// BSP sequence number for leaf's contents
+} mleaf_t;
+
+
+//===================================================================
+
+//
+// Whole model
+//
+
+typedef enum {mod_bad, mod_brush, mod_sprite, mod_alias } modtype_t;
+
+typedef struct model_s
+{
+	char		name[MAX_QPATH];
+
+	int			registration_sequence;
+
+	modtype_t	type;
+	int			numframes;
+	
+	int			flags;
+
+//
+// volume occupied by the model graphics
+//		
+	vec3_t		mins, maxs;
+
+//
+// solid volume for clipping (sent from server)
+//
+	qboolean	clipbox;
+	vec3_t		clipmins, clipmaxs;
+
+//
+// brush model
+//
+	int			firstmodelsurface, nummodelsurfaces;
+
+	int			numsubmodels;
+	dmodel_t	*submodels;
+
+	int			numplanes;
+	mplane_t	*planes;
+
+	int			numleafs;		// number of visible leafs, not counting 0
+	mleaf_t		*leafs;
+
+	int			numvertexes;
+	mvertex_t	*vertexes;
+
+	int			numedges;
+	medge_t		*edges;
+
+	int			numnodes;
+	int			firstnode;
+	mnode_t		*nodes;
+
+	int			numtexinfo;
+	mtexinfo_t	*texinfo;
+
+	int			numsurfaces;
+	msurface_t	*surfaces;
+
+	int			numsurfedges;
+	int			*surfedges;
+
+	int			nummarksurfaces;
+	msurface_t	**marksurfaces;
+
+	dvis_t		*vis;
+
+	byte		*lightdata;
+
+	// for alias models and sprites
+	image_t		*skins[MAX_MD2SKINS];
+	void		*extradata;
+	int			extradatasize;
+} model_t;
+
+//============================================================================
+
+void	Mod_Init (void);
+void	Mod_ClearAll (void);
+model_t *Mod_ForName (char *name, qboolean crash);
+void	*Mod_Extradata (model_t *mod);	// handles caching
+void	Mod_TouchModel (char *name);
+
+mleaf_t *Mod_PointInLeaf (float *p, model_t *model);
+byte	*Mod_ClusterPVS (int cluster, model_t *model);
+
+void Mod_Modellist_f (void);
+void Mod_FreeAll (void);
+void Mod_Free (model_t *mod);
+
+extern	int		registration_sequence;
+
+/* end r_model.h */
+
+
 #define CACHE_SIZE      32
 
 /*
@@ -250,9 +452,9 @@
 ** if you change this structure be sure to change the #defines
 ** listed after it!
 */
-#define SMALL_FINALVERT 0
+//#define SMALL_FINALVERT
 
-#if SMALL_FINALVERT
+#ifdef SMALL_FINALVERT
 
 typedef struct finalvert_s {
 	short           u, v, s, t;
@@ -624,15 +826,6 @@
 void R_TransformFrustum (void);
 void R_DrawSurfaceBlock16 (void);
 void R_DrawSurfaceBlock8 (void);
-
-#if     id386
-
-void R_DrawSurfaceBlock8_mip0 (void);
-void R_DrawSurfaceBlock8_mip1 (void);
-void R_DrawSurfaceBlock8_mip2 (void);
-void R_DrawSurfaceBlock8_mip3 (void);
-
-#endif
 
 void R_GenSkyTile (void *pdest);
 void R_GenSkyTile16 (void *pdest);
--- a/ref/r_main.c
+++ b/ref/r_main.c
@@ -17,10 +17,12 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-// r_main.c
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 
-#include "r_local.h"
-
 viddef_t	vid;
 refimport_t	ri;
 
@@ -143,8 +145,6 @@
 #define	STRINGER(x) "x"
 
 
-#if	!id386
-
 // r_vars.c
 
 // all global and static refresh variables are collected in a contiguous block
@@ -184,8 +184,6 @@
 unsigned int	d_zwidth;
 
 
-#endif	// !id386
-
 byte	r_notexture_buffer[1024];
 
 /*
@@ -199,7 +197,7 @@
 	byte	*dest;
 	
 // create a simple checkerboard texture for the default
-	r_notexture_mip = (image_t *)&r_notexture_buffer;
+	r_notexture_mip = (image_t *)r_notexture_buffer;
 	
 	r_notexture_mip->width = r_notexture_mip->height = 16;
 	r_notexture_mip->pixels[0] = &r_notexture_buffer[sizeof(image_t)];
@@ -316,13 +314,6 @@
 	r_refdef.xOrigin = XCENTERING;
 	r_refdef.yOrigin = YCENTERING;
 
-// TODO: collect 386-specific code in one place
-#if	id386
-	Sys_MakeCodeWriteable ((long)R_EdgeCodeStart,
-					     (long)R_EdgeCodeEnd - (long)R_EdgeCodeStart);
-	Sys_SetFPCW ();		// get bit masks for FPCW	(FIXME: is this id386?)
-#endif	// id386
-
 	r_aliasuvscale = 1.0;
 
 	R_Register ();
@@ -477,7 +468,7 @@
 		}
 	}
 
-#if 0
+/*
 	for (i=0 ; i<r_worldmodel->vis->numclusters ; i++)
 	{
 		if (vis[i>>3] & (1<<(i&7)))
@@ -492,7 +483,7 @@
 			} while (node);
 		}
 	}
-#endif
+*/
 }
 
 /*
@@ -866,13 +857,13 @@
 	else
 	{
 		r_edges =  (edge_t *)
-				(((long)&ledges[0] + CACHE_SIZE - 1) & ~(CACHE_SIZE - 1));
+				(((uintptr)&ledges[0] + CACHE_SIZE - 1) & ~(CACHE_SIZE - 1));
 	}
 
 	if (r_surfsonstack)
 	{
 		surfaces =  (surf_t *)
-				(((long)&lsurfs[0] + CACHE_SIZE - 1) & ~(CACHE_SIZE - 1));
+				(((uintptr)&lsurfs[0] + CACHE_SIZE - 1) & ~(CACHE_SIZE - 1));
 		surf_max = &surfaces[r_cnumsurfs];
 	// surface 0 doesn't really exist; it's just a dummy because index 0
 	// is used to indicate no edge attached to surface
@@ -1092,7 +1083,7 @@
 /*
 ** R_BeginFrame
 */
-void R_BeginFrame( float camera_separation )
+void R_BeginFrame( float /*camera_separation*/ )
 {
 	extern void Draw_BuildGammaTable( void );
 
@@ -1176,7 +1167,7 @@
 
 	// clear screen to black to avoid any palette flash
 	w = abs(vid.rowbytes)>>2;	// stupid negative pitch win32 stuff...
-	for (i=0 ; i<vid.height ; i++, d+=w)
+	for (i=0 ; i<vid.height ; i++)
 	{
 		d = (int *)(vid.buffer + i*vid.rowbytes);
 		for (j=0 ; j<w ; j++)
@@ -1392,31 +1383,3 @@
 
 	return re;
 }
-
-#ifndef REF_HARD_LINKED
-// this is only here so the functions in q_shared.c and q_shwin.c can link
-void Sys_Error (char *error, ...)
-{
-	va_list		argptr;
-	char		text[1024];
-
-	va_start (argptr, error);
-	vsprintf (text, error, argptr);
-	va_end (argptr);
-
-	ri.Sys_Error (ERR_FATAL, "%s", text);
-}
-
-void Com_Printf (char *fmt, ...)
-{
-	va_list		argptr;
-	char		text[1024];
-
-	va_start (argptr, fmt);
-	vsprintf (text, fmt, argptr);
-	va_end (argptr);
-
-	ri.Con_Printf (PRINT_ALL, "%s", text);
-}
-
-#endif
--- a/ref/r_misc.c
+++ b/ref/r_misc.c
@@ -17,10 +17,12 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-// r_misc.c
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 
-#include "r_local.h"
-
 #define NUM_MIPS	4
 
 cvar_t	*sw_mipcap;
@@ -49,24 +51,6 @@
 */
 void D_Patch (void)
 {
-#if id386
-	extern void D_Aff8Patch( void );
-	static qboolean protectset8 = false;
-	extern void D_PolysetAff8Start( void );
-
-	if (!protectset8)
-	{
-		Sys_MakeCodeWriteable ((int)D_PolysetAff8Start,
-						     (int)D_Aff8Patch - (int)D_PolysetAff8Start);
-		Sys_MakeCodeWriteable ((long)R_Surf8Start,
-						 (long)R_Surf8End - (long)R_Surf8Start);
-		protectset8 = true;
-	}
-	colormap = vid.colormap;
-
-	R_Surf8Patch ();
-	D_Aff8Patch();
-#endif
 }
 /*
 ================
@@ -206,9 +190,6 @@
 }
 
 
-#if !(defined __linux__ && defined __i386__)
-#if !id386
-
 /*
 ================
 TransformVector
@@ -221,57 +202,7 @@
 	out[2] = DotProduct(in,vpn);		
 }
 
-#else
 
-__declspec( naked ) void TransformVector( vec3_t vin, vec3_t vout )
-{
-	__asm mov eax, dword ptr [esp+4]
-	__asm mov edx, dword ptr [esp+8]
-
-	__asm fld  dword ptr [eax+0]
-	__asm fmul dword ptr [vright+0]
-	__asm fld  dword ptr [eax+0]
-	__asm fmul dword ptr [vup+0]
-	__asm fld  dword ptr [eax+0]
-	__asm fmul dword ptr [vpn+0]
-
-	__asm fld  dword ptr [eax+4]
-	__asm fmul dword ptr [vright+4]
-	__asm fld  dword ptr [eax+4]
-	__asm fmul dword ptr [vup+4]
-	__asm fld  dword ptr [eax+4]
-	__asm fmul dword ptr [vpn+4]
-
-	__asm fxch st(2)
-
-	__asm faddp st(5), st(0)
-	__asm faddp st(3), st(0)
-	__asm faddp st(1), st(0)
-
-	__asm fld  dword ptr [eax+8]
-	__asm fmul dword ptr [vright+8]
-	__asm fld  dword ptr [eax+8]
-	__asm fmul dword ptr [vup+8]
-	__asm fld  dword ptr [eax+8]
-	__asm fmul dword ptr [vpn+8]
-
-	__asm fxch st(2)
-
-	__asm faddp st(5), st(0)
-	__asm faddp st(3), st(0)
-	__asm faddp st(1), st(0)
-
-	__asm fstp dword ptr [edx+8]
-	__asm fstp dword ptr [edx+4]
-	__asm fstp dword ptr [edx+0]
-
-	__asm ret
-}
-
-#endif
-#endif
-
-
 /*
 ================
 R_TransformPlane
@@ -513,21 +444,6 @@
 
 	d_aflatcolor = 0;
 }
-
-
-#if	!id386
-
-/*
-================
-R_SurfacePatch
-================
-*/
-void R_SurfacePatch (void)
-{
-	// we only patch code on Intel
-}
-
-#endif	// !id386
 
 
 /* 
--- a/ref/r_model.c
+++ b/ref/r_model.c
@@ -22,7 +22,11 @@
 // models are the only shared resource between a client and server running
 // on the same machine.
 
-#include "r_local.h"
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 
 model_t	*loadmodel;
 char	loadname[32];	// for hunk tags
@@ -206,8 +210,6 @@
 		else
 			node = node->children[1];
 	}
-	
-	return NULL;	// never reached
 }
 
 
@@ -226,9 +228,9 @@
 	row = (model->vis->numclusters+7)>>3;	
 	out = decompressed;
 
-#if 0
+	/*
 	memcpy (out, in, row);
-#else
+	*/
 	if (!in)
 	{	// no vis info, so make all visible
 		while (row)
@@ -255,7 +257,6 @@
 			c--;
 		}
 	} while (out - decompressed < row);
-#endif
 	
 	return decompressed;
 }
@@ -496,12 +497,12 @@
 			out->mipadjust = 2;
 		else
 			out->mipadjust = 1;
-#if 0
+		/*
 		if (len1 + len2 < 0.001)
 			out->mipadjust = 1;		// don't crash
 		else
 			out->mipadjust = 1 / floor( (len1+len2)/2 + 0.1 );
-#endif
+		*/
 
 		out->flags = LittleLong (in->flags);
 
--- a/ref/r_model.h
+++ /dev/null
@@ -1,256 +1,0 @@
-/*
-Copyright (C) 1997-2001 Id Software, Inc.
-
-This program is free software; you can redistribute it and/or
-modify it under the terms of the GNU General Public License
-as published by the Free Software Foundation; either version 2
-of the License, or (at your option) any later version.
-
-This program is distributed in the hope that it will be useful,
-but WITHOUT ANY WARRANTY; without even the implied warranty of
-MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
-
-See the GNU General Public License for more details.
-
-You should have received a copy of the GNU General Public License
-along with this program; if not, write to the Free Software
-Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
-
-*/
-
-#ifndef __MODEL__
-#define __MODEL__
-
-/*
-
-d*_t structures are on-disk representations
-m*_t structures are in-memory
-
-*/
-
-
-/*
-==============================================================================
-
-BRUSH MODELS
-
-==============================================================================
-*/
-
-
-//
-// in memory representation
-//
-// !!! if this is changed, it must be changed in asm_draw.h too !!!
-typedef struct
-{
-	vec3_t		position;
-} mvertex_t;
-
-#define	SIDE_FRONT	0
-#define	SIDE_BACK	1
-#define	SIDE_ON		2
-
-
-// plane_t structure
-// !!! if this is changed, it must be changed in asm_i386.h too !!!
-typedef struct mplane_s
-{
-	vec3_t	normal;
-	float	dist;
-	byte	type;			// for texture axis selection and fast side tests
-	byte	signbits;		// signx + signy<<1 + signz<<1
-	byte	pad[2];
-} mplane_t;
-
-
-// FIXME: differentiate from texinfo SURF_ flags
-#define	SURF_PLANEBACK		2
-#define	SURF_DRAWSKY		4			// sky brush face
-#define SURF_DRAWTURB		0x10
-#define SURF_DRAWBACKGROUND	0x40
-#define SURF_DRAWSKYBOX		0x80		// sky box
-
-#define SURF_FLOW			0x100		//PGM
-
-// !!! if this is changed, it must be changed in asm_draw.h too !!!
-typedef struct
-{
-	unsigned short	v[2];
-	unsigned int	cachededgeoffset;
-} medge_t;
-
-typedef struct mtexinfo_s
-{
-	float		vecs[2][4];
-	float		mipadjust;
-	image_t		*image;
-	int			flags;
-	int			numframes;
-	struct mtexinfo_s	*next;		// animation chain
-} mtexinfo_t;
-
-typedef struct msurface_s
-{
-	int			visframe;		// should be drawn when node is crossed
-
-	int			dlightframe;
-	int			dlightbits;
-
-	mplane_t	*plane;
-	int			flags;
-
-	int			firstedge;	// look up in model->surfedges[], negative numbers
-	int			numedges;	// are backwards edges
-	
-// surface generation data
-	struct surfcache_s	*cachespots[MIPLEVELS];
-
-	short		texturemins[2];
-	short		extents[2];
-
-	mtexinfo_t	*texinfo;
-	
-// lighting info
-	byte		styles[MAXLIGHTMAPS];
-	byte		*samples;		// [numstyles*surfsize]
-
-	struct msurface_s *nextalphasurface;
-} msurface_t;
-
-
-#define	CONTENTS_NODE	-1
-typedef struct mnode_s
-{
-// common with leaf
-	int			contents;		// CONTENTS_NODE, to differentiate from leafs
-	int			visframe;		// node needs to be traversed if current
-	
-	short		minmaxs[6];		// for bounding box culling
-
-	struct mnode_s	*parent;
-
-// node specific
-	mplane_t	*plane;
-	struct mnode_s	*children[2];	
-
-	unsigned short		firstsurface;
-	unsigned short		numsurfaces;
-} mnode_t;
-
-
-
-typedef struct mleaf_s
-{
-// common with node
-	int			contents;		// wil be something other than CONTENTS_NODE
-	int			visframe;		// node needs to be traversed if current
-
-	short		minmaxs[6];		// for bounding box culling
-
-	struct mnode_s	*parent;
-
-// leaf specific
-	int			cluster;
-	int			area;
-
-	msurface_t	**firstmarksurface;
-	int			nummarksurfaces;
-	int			key;			// BSP sequence number for leaf's contents
-} mleaf_t;
-
-
-//===================================================================
-
-//
-// Whole model
-//
-
-typedef enum {mod_bad, mod_brush, mod_sprite, mod_alias } modtype_t;
-
-typedef struct model_s
-{
-	char		name[MAX_QPATH];
-
-	int			registration_sequence;
-
-	modtype_t	type;
-	int			numframes;
-	
-	int			flags;
-
-//
-// volume occupied by the model graphics
-//		
-	vec3_t		mins, maxs;
-
-//
-// solid volume for clipping (sent from server)
-//
-	qboolean	clipbox;
-	vec3_t		clipmins, clipmaxs;
-
-//
-// brush model
-//
-	int			firstmodelsurface, nummodelsurfaces;
-
-	int			numsubmodels;
-	dmodel_t	*submodels;
-
-	int			numplanes;
-	mplane_t	*planes;
-
-	int			numleafs;		// number of visible leafs, not counting 0
-	mleaf_t		*leafs;
-
-	int			numvertexes;
-	mvertex_t	*vertexes;
-
-	int			numedges;
-	medge_t		*edges;
-
-	int			numnodes;
-	int			firstnode;
-	mnode_t		*nodes;
-
-	int			numtexinfo;
-	mtexinfo_t	*texinfo;
-
-	int			numsurfaces;
-	msurface_t	*surfaces;
-
-	int			numsurfedges;
-	int			*surfedges;
-
-	int			nummarksurfaces;
-	msurface_t	**marksurfaces;
-
-	dvis_t		*vis;
-
-	byte		*lightdata;
-
-	// for alias models and sprites
-	image_t		*skins[MAX_MD2SKINS];
-	void		*extradata;
-	int			extradatasize;
-} model_t;
-
-//============================================================================
-
-void	Mod_Init (void);
-void	Mod_ClearAll (void);
-model_t *Mod_ForName (char *name, qboolean crash);
-void	*Mod_Extradata (model_t *mod);	// handles caching
-void	Mod_TouchModel (char *name);
-
-mleaf_t *Mod_PointInLeaf (float *p, model_t *model);
-byte	*Mod_ClusterPVS (int cluster, model_t *model);
-
-void Mod_Modellist_f (void);
-void Mod_FreeAll (void);
-void Mod_Free (model_t *mod);
-
-extern	int		registration_sequence;
-
-#endif	// __MODEL__
--- a/ref/r_part.c
+++ b/ref/r_part.c
@@ -17,7 +17,11 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-#include "r_local.h"
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 
 vec3_t r_pright, r_pup, r_ppn;
 
@@ -34,407 +38,6 @@
 
 static partparms_t partparms;
 
-#if id386 && !defined __linux__
-
-static unsigned s_prefetch_address;
-
-/*
-** BlendParticleXX
-**
-** Inputs:
-** EAX = color
-** EDI = pdest
-**
-** Scratch:
-** EBX = scratch (dstcolor)
-** EBP = scratch
-**
-** Outputs:
-** none
-*/
-__declspec(naked) void BlendParticle33( void )
-{
-	//	return vid.alphamap[color + dstcolor*256];
-	__asm mov ebp, vid.alphamap
-	__asm xor ebx, ebx
-
-	__asm mov bl,  byte ptr [edi]
-	__asm shl ebx, 8
-
-	__asm add ebp, ebx
-	__asm add ebp, eax
-
-	__asm mov al,  byte ptr [ebp]
-
-	__asm mov byte ptr [edi], al
-
-	__asm ret
-}
-
-__declspec(naked) void BlendParticle66( void )
-{
-	//	return vid.alphamap[pcolor*256 + dstcolor];
-	__asm mov ebp, vid.alphamap
-	__asm xor ebx, ebx
-
-	__asm shl eax,  8
-	__asm mov bl,   byte ptr [edi]
-
-	__asm add ebp, ebx
-	__asm add ebp, eax
-
-	__asm mov al,  byte ptr [ebp]
-
-	__asm mov byte ptr [edi], al
-
-	__asm ret
-}
-
-__declspec(naked) void BlendParticle100( void )
-{
-	__asm mov byte ptr [edi], al
-	__asm ret
-}
-
-/*
-** R_DrawParticle (asm version)
-**
-** Since we use __declspec( naked ) we don't have a stack frame
-** that we can use.  Since I want to reserve EBP anyway, I tossed
-** all the important variables into statics.  This routine isn't
-** meant to be re-entrant, so this shouldn't cause any problems
-** other than a slightly higher global memory footprint.
-**
-*/
-__declspec(naked) void R_DrawParticle( void )
-{
-	static vec3_t	local, transformed;
-	static float	zi;
-	static int      u, v, tmp;
-	static short    izi;
-	static int      ebpsave;
-
-	static byte (*blendfunc)(void);
-
-	/*
-	** must be memvars since x86 can't load constants
-	** directly.  I guess I could use fld1, but that
-	** actually costs one more clock than fld [one]!
-	*/
-	static float    particle_z_clip    = PARTICLE_Z_CLIP;
-	static float    one                = 1.0F;
-	static float    point_five         = 0.5F;
-	static float    eight_thousand_hex = 0x8000;
-
-	/*
-	** save trashed variables
-	*/
-	__asm mov  ebpsave, ebp
-	__asm push esi
-	__asm push edi
-
-	/*
-	** transform the particle
-	*/
-	// VectorSubtract (pparticle->origin, r_origin, local);
-	__asm mov  esi, partparms.particle
-	__asm fld  dword ptr [esi+0]          ; p_o.x
-	__asm fsub dword ptr [r_origin+0]     ; p_o.x-r_o.x
-	__asm fld  dword ptr [esi+4]          ; p_o.y | p_o.x-r_o.x
-	__asm fsub dword ptr [r_origin+4]     ; p_o.y-r_o.y | p_o.x-r_o.x
-	__asm fld  dword ptr [esi+8]          ; p_o.z | p_o.y-r_o.y | p_o.x-r_o.x
-	__asm fsub dword ptr [r_origin+8]     ; p_o.z-r_o.z | p_o.y-r_o.y | p_o.x-r_o.x
-	__asm fxch st(2)                      ; p_o.x-r_o.x | p_o.y-r_o.y | p_o.z-r_o.z
-	__asm fstp dword ptr [local+0]        ; p_o.y-r_o.y | p_o.z-r_o.z
-	__asm fstp dword ptr [local+4]        ; p_o.z-r_o.z
-	__asm fstp dword ptr [local+8]        ; (empty)
-
-	// transformed[0] = DotProduct(local, r_pright);
-	// transformed[1] = DotProduct(local, r_pup);
-	// transformed[2] = DotProduct(local, r_ppn);
-	__asm fld  dword ptr [local+0]        ; l.x
-	__asm fmul dword ptr [r_pright+0]     ; l.x*pr.x
-	__asm fld  dword ptr [local+4]        ; l.y | l.x*pr.x
-	__asm fmul dword ptr [r_pright+4]     ; l.y*pr.y | l.x*pr.x
-	__asm fld  dword ptr [local+8]        ; l.z | l.y*pr.y | l.x*pr.x
-	__asm fmul dword ptr [r_pright+8]     ; l.z*pr.z | l.y*pr.y | l.x*pr.x
-	__asm fxch st(2)                      ; l.x*pr.x | l.y*pr.y | l.z*pr.z
-	__asm faddp st(1), st                 ; l.x*pr.x + l.y*pr.y | l.z*pr.z
-	__asm faddp st(1), st                 ; l.x*pr.x + l.y*pr.y + l.z*pr.z
-	__asm fstp  dword ptr [transformed+0] ; (empty)
-
-	__asm fld  dword ptr [local+0]        ; l.x
-	__asm fmul dword ptr [r_pup+0]        ; l.x*pr.x
-	__asm fld  dword ptr [local+4]        ; l.y | l.x*pr.x
-	__asm fmul dword ptr [r_pup+4]        ; l.y*pr.y | l.x*pr.x
-	__asm fld  dword ptr [local+8]        ; l.z | l.y*pr.y | l.x*pr.x
-	__asm fmul dword ptr [r_pup+8]        ; l.z*pr.z | l.y*pr.y | l.x*pr.x
-	__asm fxch st(2)                      ; l.x*pr.x | l.y*pr.y | l.z*pr.z
-	__asm faddp st(1), st                 ; l.x*pr.x + l.y*pr.y | l.z*pr.z
-	__asm faddp st(1), st                 ; l.x*pr.x + l.y*pr.y + l.z*pr.z
-	__asm fstp  dword ptr [transformed+4] ; (empty)
-
-	__asm fld  dword ptr [local+0]        ; l.x
-	__asm fmul dword ptr [r_ppn+0]        ; l.x*pr.x
-	__asm fld  dword ptr [local+4]        ; l.y | l.x*pr.x
-	__asm fmul dword ptr [r_ppn+4]        ; l.y*pr.y | l.x*pr.x
-	__asm fld  dword ptr [local+8]        ; l.z | l.y*pr.y | l.x*pr.x
-	__asm fmul dword ptr [r_ppn+8]        ; l.z*pr.z | l.y*pr.y | l.x*pr.x
-	__asm fxch st(2)                      ; l.x*pr.x | l.y*pr.y | l.z*pr.z
-	__asm faddp st(1), st                 ; l.x*pr.x + l.y*pr.y | l.z*pr.z
-	__asm faddp st(1), st                 ; l.x*pr.x + l.y*pr.y + l.z*pr.z
-	__asm fstp  dword ptr [transformed+8] ; (empty)
-
-	/*
-	** make sure that the transformed particle is not in front of
-	** the particle Z clip plane.  We can do the comparison in 
-	** integer space since we know the sign of one of the inputs
-	** and can figure out the sign of the other easily enough.
-	*/
-	//	if (transformed[2] < PARTICLE_Z_CLIP)
-	//		return;
-
-	__asm mov  eax, dword ptr [transformed+8]
-	__asm and  eax, eax
-	__asm js   end
-	__asm cmp  eax, particle_z_clip
-	__asm jl   end
-
-	/*
-	** project the point by initiating the 1/z calc
-	*/
-	//	zi = 1.0 / transformed[2];
-	__asm fld   one
-	__asm fdiv  dword ptr [transformed+8]
-
-	/*
-	** bind the blend function pointer to the appropriate blender
-	** while we're dividing
-	*/
-	//if ( level == PARTICLE_33 )
-	//	blendparticle = BlendParticle33;
-	//else if ( level == PARTICLE_66 )
-	//	blendparticle = BlendParticle66;
-	//else 
-	//	blendparticle = BlendParticle100;
-
-	__asm cmp partparms.level, PARTICLE_66
-	__asm je  blendfunc_66
-	__asm jl  blendfunc_33
-	__asm lea ebx, BlendParticle100
-	__asm jmp done_selecting_blend_func
-blendfunc_33:
-	__asm lea ebx, BlendParticle33
-	__asm jmp done_selecting_blend_func
-blendfunc_66:
-	__asm lea ebx, BlendParticle66
-done_selecting_blend_func:
-	__asm mov blendfunc, ebx
-
-	// prefetch the next particle
-	__asm mov ebp, s_prefetch_address
-	__asm mov ebp, [ebp]
-
-	// finish the above divide
-	__asm fstp  zi
-
-	// u = (int)(xcenter + zi * transformed[0] + 0.5);
-	// v = (int)(ycenter - zi * transformed[1] + 0.5);
-	__asm fld   zi                           ; zi
-	__asm fmul  dword ptr [transformed+0]    ; zi * transformed[0]
-	__asm fld   zi                           ; zi | zi * transformed[0]
-	__asm fmul  dword ptr [transformed+4]    ; zi * transformed[1] | zi * transformed[0]
-	__asm fxch  st(1)                        ; zi * transformed[0] | zi * transformed[1]
-	__asm fadd  xcenter                      ; xcenter + zi * transformed[0] | zi * transformed[1]
-	__asm fxch  st(1)                        ; zi * transformed[1] | xcenter + zi * transformed[0]
-	__asm fld   ycenter                      ; ycenter | zi * transformed[1] | xcenter + zi * transformed[0]
-    __asm fsubrp st(1), st(0)                ; ycenter - zi * transformed[1] | xcenter + zi * transformed[0]
-  	__asm fxch  st(1)                        ; xcenter + zi * transformed[0] | ycenter + zi * transformed[1]
-  	__asm fadd  point_five                   ; xcenter + zi * transformed[0] + 0.5 | ycenter - zi * transformed[1]
-  	__asm fxch  st(1)                        ; ycenter - zi * transformed[1] | xcenter + zi * transformed[0] + 0.5 
-  	__asm fadd  point_five                   ; ycenter - zi * transformed[1] + 0.5 | xcenter + zi * transformed[0] + 0.5 
-  	__asm fxch  st(1)                        ; u | v
-  	__asm fistp dword ptr [u]                ; v
-  	__asm fistp dword ptr [v]                ; (empty)
-
-	/*
-	** clip out the particle
-	*/
-
-	//	if ((v > d_vrectbottom_particle) || 
-	//		(u > d_vrectright_particle) ||
-	//		(v < d_vrecty) ||
-	//		(u < d_vrectx))
-	//	{
-	//		return;
-	//	}
-
-	__asm mov ebx, u
-	__asm mov ecx, v
-	__asm cmp ecx, d_vrectbottom_particle
-	__asm jg  end
-	__asm cmp ecx, d_vrecty
-	__asm jl  end
-	__asm cmp ebx, d_vrectright_particle
-	__asm jg  end
-	__asm cmp ebx, d_vrectx
-	__asm jl  end
-
-	/*
-	** compute addresses of zbuffer, framebuffer, and 
-	** compute the Z-buffer reference value.
-	**
-	** EBX      = U
-	** ECX      = V
-	**
-	** Outputs:
-	** ESI = Z-buffer address
-	** EDI = framebuffer address
-	*/
-	// ESI = d_pzbuffer + (d_zwidth * v) + u;
-	__asm mov esi, d_pzbuffer             ; esi = d_pzbuffer
-	__asm mov eax, d_zwidth               ; eax = d_zwidth
-	__asm mul ecx                         ; eax = d_zwidth*v
-	__asm add eax, ebx                    ; eax = d_zwidth*v+u
-	__asm shl eax, 1                      ; eax = 2*(d_zwidth*v+u)
-	__asm add esi, eax                    ; esi = ( short * ) ( d_pzbuffer + ( d_zwidth * v ) + u )
-
-	// initiate
-	// izi = (int)(zi * 0x8000);
-	__asm fld  zi
-	__asm fmul eight_thousand_hex
-
-	// EDI = pdest = d_viewbuffer + d_scantable[v] + u;
-	__asm lea edi, [d_scantable+ecx*4]
-	__asm mov edi, [edi]
-	__asm add edi, d_viewbuffer
-	__asm add edi, ebx
-
-	// complete
-	// izi = (int)(zi * 0x8000);
-	__asm fistp tmp
-	__asm mov   eax, tmp
-	__asm mov   izi, ax
-
-	/*
-	** determine the screen area covered by the particle,
-	** which also means clamping to a min and max
-	*/
-	//	pix = izi >> d_pix_shift;
-	__asm xor edx, edx
-	__asm mov dx, izi
-	__asm mov ecx, d_pix_shift
-	__asm shr dx, cl
-
-	//	if (pix < d_pix_min)
-	//		pix = d_pix_min;
-	__asm cmp edx, d_pix_min
-	__asm jge check_pix_max
-	__asm mov edx, d_pix_min
-	__asm jmp skip_pix_clamp
-
-	//	else if (pix > d_pix_max)
-	//		pix = d_pix_max;
-check_pix_max:
-	__asm cmp edx, d_pix_max
-	__asm jle skip_pix_clamp
-	__asm mov edx, d_pix_max
-
-skip_pix_clamp:
-
-	/*
-	** render the appropriate pixels
-	**
-	** ECX = count (used for inner loop)
-	** EDX = count (used for outer loop)
-	** ESI = zbuffer
-	** EDI = framebuffer
-	*/
-	__asm mov ecx, edx
-
-	__asm cmp ecx, 1
-	__asm ja  over
-
-over:
-
-	/*
-	** at this point:
-	**
-	** ECX = count
-	*/
-	__asm push ecx
-	__asm push edi
-	__asm push esi
-
-top_of_pix_vert_loop:
-
-top_of_pix_horiz_loop:
-
-	//	for ( ; count ; count--, pz += d_zwidth, pdest += screenwidth)
-	//	{
-	//		for (i=0 ; i<pix ; i++)
-	//		{
-	//			if (pz[i] <= izi)
-	//			{
-	//				pdest[i] = blendparticle( color, pdest[i] );
-	//			}
-	//		}
-	//	}
-	__asm xor   eax, eax
-
-	__asm mov   ax, word ptr [esi]
-
-	__asm cmp   ax, izi
-	__asm jg    end_of_horiz_loop
-
-#if ENABLE_ZWRITES_FOR_PARTICLES
-  	__asm mov   bp, izi
-  	__asm mov   word ptr [esi], bp
-#endif
-
-	__asm mov   eax, partparms.color
-
-	__asm call  [blendfunc]
-
-	__asm add   edi, 1
-	__asm add   esi, 2
-
-end_of_horiz_loop:
-
-	__asm dec   ecx
-	__asm jnz   top_of_pix_horiz_loop
-
-	__asm pop   esi
-	__asm pop   edi
-
-	__asm mov   ebp, d_zwidth
-	__asm shl   ebp, 1
-
-	__asm add   esi, ebp
-	__asm add   edi, [r_screenwidth]
-
-	__asm pop   ecx
-	__asm push  ecx
-
-	__asm push  edi
-	__asm push  esi
-
-	__asm dec   edx
-	__asm jnz   top_of_pix_vert_loop
-
-	__asm pop   ecx
-	__asm pop   ecx
-	__asm pop   ecx
-
-end:
-	__asm pop edi
-	__asm pop esi
-	__asm mov ebp, ebpsave
-	__asm ret
-}
-
-#else
-
 static byte BlendParticle33( int pcolor, int dstcolor )
 {
 	return vid.alphamap[pcolor + dstcolor*256];
@@ -445,9 +48,8 @@
 	return vid.alphamap[pcolor*256+dstcolor];
 }
 
-static byte BlendParticle100( int pcolor, int dstcolor )
+static byte BlendParticle100( int pcolor, int /*dstcolor*/ )
 {
-	dstcolor = dstcolor;
 	return pcolor;
 }
 
@@ -474,7 +76,6 @@
 	short	*pz;
 	int      color = pparticle->color;
 	int		i, izi, pix, count, u, v;
-	byte  (*blendparticle)( int, int );
 
 	/*
 	** transform the particle
@@ -491,6 +92,8 @@
 	/*
 	** bind the blend function pointer to the appropriate blender
 	*/
+	/*
+	byte  (*blendparticle)( int, int );
 	if ( level == PARTICLE_33 )
 		blendparticle = BlendParticle33;
 	else if ( level == PARTICLE_66 )
@@ -497,6 +100,7 @@
 		blendparticle = BlendParticle66;
 	else 
 		blendparticle = BlendParticle100;
+	*/
 
 	/*
 	** project the point
@@ -583,8 +187,6 @@
     }
 }
 
-#endif	// !id386
-
 /*
 ** R_DrawParticles
 **
@@ -603,10 +205,6 @@
 	VectorScale( vup, yscaleshrink, r_pup );
 	VectorCopy( vpn, r_ppn );
 
-#if id386 && !defined __linux__
-	__asm fldcw word ptr [fpu_sp24_cw]
-#endif
-
 	for (p=r_newrefdef.particles, i=0 ; i<r_newrefdef.num_particles ; i++,p++)
 	{
 
@@ -620,19 +218,6 @@
 		partparms.particle = p;
 		partparms.color    = p->color;
 
-#if id386 && !defined __linux__
-		if ( i < r_newrefdef.num_particles-1 )
-			s_prefetch_address = ( unsigned int ) ( p + 1 );
-		else
-			s_prefetch_address = ( unsigned int ) r_newrefdef.particles;
-#endif
-
 		R_DrawParticle();
 	}
-
-#if id386 && !defined __linux__
-	__asm fldcw word ptr [fpu_chop_cw]
-#endif
-
 }
-
--- a/ref/r_poly.c
+++ b/ref/r_poly.c
@@ -17,8 +17,11 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-#include <assert.h>
-#include "r_local.h"
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 
 #define AFFINE_SPANLET_SIZE      16
 #define AFFINE_SPANLET_SIZE_BITS 4
@@ -883,7 +886,7 @@
 
 	} while (i != s_maxindex);
 
-	pspan->count = DS_SPAN_LIST_END;	// mark the end of the span list 
+	pspan->count = DS_SPAN_LIST_END;	// mark the end of the span list
 }
 
 /*
@@ -1005,7 +1008,6 @@
 {
 	int			i, lindex, lnumverts;
 	medge_t		*pedges, *r_pedge;
-	int			vertpage;
 	float		*vec;
 	vec5_t     *pverts;
 	float       tmins[2] = { 0, 0 };
@@ -1015,7 +1017,6 @@
 	// reconstruct the polygon
 	pedges = currentmodel->edges;
 	lnumverts = fa->numedges;
-	vertpage = 0;
 
 	pverts = r_clip_verts[0];
 
--- a/ref/r_polyse.c
+++ b/ref/r_polyse.c
@@ -20,7 +20,11 @@
 // d_polyset.c: routines for drawing sets of polygons sharing the same
 // texture (used for Alias models)
 
-#include "r_local.h"
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 
 int	rand1k[] = {
 #include "rand1k.h"
@@ -411,265 +415,6 @@
 R_PolysetCalcGradients
 ================
 */
-#if id386 && !defined __linux__
-void R_PolysetCalcGradients( int skinwidth )
-{
-	static float xstepdenominv, ystepdenominv, t0, t1;
-	static float p01_minus_p21, p11_minus_p21, p00_minus_p20, p10_minus_p20;
-	static float one = 1.0F, negative_one = -1.0F;
-	static unsigned long t0_int, t1_int;
-
-	extern unsigned long fpu_sp24_ceil_cw, fpu_ceil_cw, fpu_chop_cw;
-
-	/*
-	p00_minus_p20 = r_p0[0] - r_p2[0];
-	p01_minus_p21 = r_p0[1] - r_p2[1];
-	p10_minus_p20 = r_p1[0] - r_p2[0];
-	p11_minus_p21 = r_p1[1] - r_p2[1];
-	*/
-
-	__asm mov eax, dword ptr [r_p0+0]
-	__asm mov ebx, dword ptr [r_p0+4]
-	__asm sub eax, dword ptr [r_p2+0]
-	__asm sub ebx, dword ptr [r_p2+4]
-	__asm mov p00_minus_p20, eax
-	__asm mov p01_minus_p21, ebx
-	__asm fild dword ptr p00_minus_p20
-	__asm fild dword ptr p01_minus_p21
-	__asm mov eax, dword ptr [r_p1+0]
-	__asm mov ebx, dword ptr [r_p1+4]
-	__asm sub eax, dword ptr [r_p2+0]
-	__asm sub ebx, dword ptr [r_p2+4]
-	__asm fstp p01_minus_p21
-	__asm fstp p00_minus_p20
-	__asm mov p10_minus_p20, eax
-	__asm mov p11_minus_p21, ebx
-	__asm fild dword ptr p10_minus_p20
-	__asm fild dword ptr p11_minus_p21
-	__asm fstp p11_minus_p21
-	__asm fstp p10_minus_p20
-
-	/*
-	xstepdenominv = 1.0 / (float)d_xdenom;
-
-	ystepdenominv = -xstepdenominv;
-	*/
-
-	/*
-	** put FPU in single precision ceil mode
-	*/
-	__asm fldcw word ptr [fpu_sp24_ceil_cw]
-//	__asm fldcw word ptr [fpu_ceil_cw]
-
-	__asm fild  dword ptr d_xdenom    ; d_xdenom
-	__asm fdivr one                   ; 1 / d_xdenom
-	__asm fst   xstepdenominv         ; 
-	__asm fmul  negative_one          ; -( 1 / d_xdenom )
-
-// ceil () for light so positive steps are exaggerated, negative steps
-// diminished,  pushing us away from underflow toward overflow. Underflow is
-// very visible, overflow is very unlikely, because of ambient lighting
-	/*
-	t0 = r_p0[4] - r_p2[4];
-	t1 = r_p1[4] - r_p2[4];
-	r_lstepx = (int)
-			ceil((t1 * p01_minus_p21 - t0 * p11_minus_p21) * xstepdenominv);
-	r_lstepy = (int)
-			ceil((t1 * p00_minus_p20 - t0 * p10_minus_p20) * ystepdenominv);
-	*/
-	__asm mov   eax, dword ptr [r_p0+16]
-	__asm mov   ebx, dword ptr [r_p1+16]
-	__asm sub   eax, dword ptr [r_p2+16]
-	__asm sub   ebx, dword ptr [r_p2+16]
-
-	__asm fstp  ystepdenominv       ; (empty)
-
-	__asm mov   t0_int, eax
-	__asm mov   t1_int, ebx
-	__asm fild  t0_int              ; t0
-	__asm fild  t1_int              ; t1 | t0
-	__asm fxch  st(1)               ; t0 | t1
-	__asm fstp  t0                  ; t1
-	__asm fst   t1                  ; t1
-	__asm fmul  p01_minus_p21       ; t1 * p01_minus_p21
-	__asm fld   t0                  ; t0 | t1 * p01_minus_p21
-	__asm fmul  p11_minus_p21       ; t0 * p11_minus_p21 | t1 * p01_minus_p21
-	__asm fld   t1                  ; t1 | t0 * p11_minus_p21 | t1 * p01_minus_p21
-	__asm fmul  p00_minus_p20       ; t1 * p00_minus_p20 | t0 * p11_minus_p21 | t1 * p01_minus_p21
-	__asm fld   t0                  ; t0 | t1 * p00_minus_p20 | t0 * p11_minus_p21 | t1 * p01_minus_p21
-	__asm fmul  p10_minus_p20       ; t0 * p10_minus_p20 | t1 * p00_minus_p20 | t0 * p11_minus_p21 | t1 * p01_minus_p21
-	__asm fxch  st(2)               ; t0 * p11_minus_p21 | t0 * p10_minus_p20 | t1 * p00_minus_p20 | t1 * p01_minus_p21
-	__asm fsubp st(3), st           ; t0 * p10_minus_p20 | t1 * p00_minus_p20 | t1 * p01_minus_p21 - t0 * p11_minus_p21
-	__asm fsubrp st(1), st          ; t1 * p00_minus_p20 - t0 * p10_minus_p20 | t1 * p01_minus_p21 - t0 * p11_minus_p21
-	__asm fxch  st(1)               ; t1 * p01_minus_p21 - t0 * p11_minus_p21 | t1 * p00_minus_p20 - t0 * p10_minus_p20
-	__asm fmul  xstepdenominv       ; r_lstepx | t1 * p00_minus_p20 - t0 * p10_minus_p20
-	__asm fxch  st(1)
-	__asm fmul  ystepdenominv       ; r_lstepy | r_lstepx
-	__asm fxch  st(1)               ; r_lstepx | r_lstepy
-	__asm fistp dword ptr [r_lstepx]
-	__asm fistp dword ptr [r_lstepy]
-
-	/*
-	** put FPU back into extended precision chop mode
-	*/
-	__asm fldcw word ptr [fpu_chop_cw]
-
-	/*
-	t0 = r_p0[2] - r_p2[2];
-	t1 = r_p1[2] - r_p2[2];
-	r_sstepx = (int)((t1 * p01_minus_p21 - t0 * p11_minus_p21) *
-			xstepdenominv);
-	r_sstepy = (int)((t1 * p00_minus_p20 - t0* p10_minus_p20) *
-			ystepdenominv);
-	*/
-	__asm mov eax, dword ptr [r_p0+8]
-	__asm mov ebx, dword ptr [r_p1+8]
-	__asm sub eax, dword ptr [r_p2+8]
-	__asm sub ebx, dword ptr [r_p2+8]
-	__asm mov   t0_int, eax
-	__asm mov   t1_int, ebx
-	__asm fild  t0_int              ; t0
-	__asm fild  t1_int              ; t1 | t0
-	__asm fxch  st(1)               ; t0 | t1
-	__asm fstp  t0                  ; t1
-	__asm fst   t1                  ; (empty)
-
-	__asm fmul  p01_minus_p21       ; t1 * p01_minus_p21
-	__asm fld   t0                  ; t0 | t1 * p01_minus_p21
-	__asm fmul  p11_minus_p21       ; t0 * p11_minus_p21 | t1 * p01_minus_p21
-	__asm fld   t1                  ; t1 | t0 * p11_minus_p21 | t1 * p01_minus_p21
-	__asm fmul  p00_minus_p20       ; t1 * p00_minus_p20 | t0 * p11_minus_p21 | t1 * p01_minus_p21
-	__asm fld   t0                  ; t0 | t1 * p00_minus_p20 | t0 * p11_minus_p21 | t1 * p01_minus_p21
-	__asm fmul  p10_minus_p20       ; t0 * p10_minus_p20 | t1 * p00_minus_p20 | t0 * p11_minus_p21 | t1 * p01_minus_p21
-	__asm fxch  st(2)               ; t0 * p11_minus_p21 | t0 * p10_minus_p20 | t1 * p00_minus_p20 | t1 * p01_minus_p21
-	__asm fsubp st(3), st           ; t0 * p10_minus_p20 | t1 * p00_minus_p20 | t1 * p01_minus_p21 - t0 * p11_minus_p21
-	__asm fsubrp st(1), st           ; t1 * p00_minus_p20 - t0 * p10_minus_p20 | t1 * p01_minus_p21 - t0 * p11_minus_p21
-	__asm fxch  st(1)               ; t1 * p01_minus_p21 - t0 * p11_minus_p21 | t1 * p00_minus_p20 - t0 * p10_minus_p20
-	__asm fmul  xstepdenominv       ; r_lstepx | t1 * p00_minus_p20 - t0 * p10_minus_p20
-	__asm fxch  st(1)
-	__asm fmul  ystepdenominv       ; r_lstepy | r_lstepx
-	__asm fxch  st(1)               ; r_lstepx | r_lstepy
-	__asm fistp dword ptr [r_sstepx]
-	__asm fistp dword ptr [r_sstepy]
-
-	/*
-	t0 = r_p0[3] - r_p2[3];
-	t1 = r_p1[3] - r_p2[3];
-	r_tstepx = (int)((t1 * p01_minus_p21 - t0 * p11_minus_p21) *
-			xstepdenominv);
-	r_tstepy = (int)((t1 * p00_minus_p20 - t0 * p10_minus_p20) *
-			ystepdenominv);
-	*/
-	__asm mov eax, dword ptr [r_p0+12]
-	__asm mov ebx, dword ptr [r_p1+12]
-	__asm sub eax, dword ptr [r_p2+12]
-	__asm sub ebx, dword ptr [r_p2+12]
-
-	__asm mov   t0_int, eax
-	__asm mov   t1_int, ebx
-	__asm fild  t0_int              ; t0
-	__asm fild  t1_int              ; t1 | t0
-	__asm fxch  st(1)               ; t0 | t1
-	__asm fstp  t0                  ; t1
-	__asm fst   t1                  ; (empty)
-
-	__asm fmul  p01_minus_p21       ; t1 * p01_minus_p21
-	__asm fld   t0                  ; t0 | t1 * p01_minus_p21
-	__asm fmul  p11_minus_p21       ; t0 * p11_minus_p21 | t1 * p01_minus_p21
-	__asm fld   t1                  ; t1 | t0 * p11_minus_p21 | t1 * p01_minus_p21
-	__asm fmul  p00_minus_p20       ; t1 * p00_minus_p20 | t0 * p11_minus_p21 | t1 * p01_minus_p21
-	__asm fld   t0                  ; t0 | t1 * p00_minus_p20 | t0 * p11_minus_p21 | t1 * p01_minus_p21
-	__asm fmul  p10_minus_p20       ; t0 * p10_minus_p20 | t1 * p00_minus_p20 | t0 * p11_minus_p21 | t1 * p01_minus_p21
-	__asm fxch  st(2)               ; t0 * p11_minus_p21 | t0 * p10_minus_p20 | t1 * p00_minus_p20 | t1 * p01_minus_p21
-	__asm fsubp st(3), st           ; t0 * p10_minus_p20 | t1 * p00_minus_p20 | t1 * p01_minus_p21 - t0 * p11_minus_p21
-	__asm fsubrp st(1), st           ; t1 * p00_minus_p20 - t0 * p10_minus_p20 | t1 * p01_minus_p21 - t0 * p11_minus_p21
-	__asm fxch  st(1)               ; t1 * p01_minus_p21 - t0 * p11_minus_p21 | t1 * p00_minus_p20 - t0 * p10_minus_p20
-	__asm fmul  xstepdenominv       ; r_lstepx | t1 * p00_minus_p20 - t0 * p10_minus_p20
-	__asm fxch  st(1)
-	__asm fmul  ystepdenominv       ; r_lstepy | r_lstepx
-	__asm fxch  st(1)               ; r_lstepx | r_lstepy
-	__asm fistp dword ptr [r_tstepx]
-	__asm fistp dword ptr [r_tstepy]
-
-	/*
-	t0 = r_p0[5] - r_p2[5];
-	t1 = r_p1[5] - r_p2[5];
-	r_zistepx = (int)((t1 * p01_minus_p21 - t0 * p11_minus_p21) *
-			xstepdenominv);
-	r_zistepy = (int)((t1 * p00_minus_p20 - t0 * p10_minus_p20) *
-			ystepdenominv);
-	*/
-	__asm mov eax, dword ptr [r_p0+20]
-	__asm mov ebx, dword ptr [r_p1+20]
-	__asm sub eax, dword ptr [r_p2+20]
-	__asm sub ebx, dword ptr [r_p2+20]
-
-	__asm mov   t0_int, eax
-	__asm mov   t1_int, ebx
-	__asm fild  t0_int              ; t0
-	__asm fild  t1_int              ; t1 | t0
-	__asm fxch  st(1)               ; t0 | t1
-	__asm fstp  t0                  ; t1
-	__asm fst   t1                  ; (empty)
-
-	__asm fmul  p01_minus_p21       ; t1 * p01_minus_p21
-	__asm fld   t0                  ; t0 | t1 * p01_minus_p21
-	__asm fmul  p11_minus_p21       ; t0 * p11_minus_p21 | t1 * p01_minus_p21
-	__asm fld   t1                  ; t1 | t0 * p11_minus_p21 | t1 * p01_minus_p21
-	__asm fmul  p00_minus_p20       ; t1 * p00_minus_p20 | t0 * p11_minus_p21 | t1 * p01_minus_p21
-	__asm fld   t0                  ; t0 | t1 * p00_minus_p20 | t0 * p11_minus_p21 | t1 * p01_minus_p21
-	__asm fmul  p10_minus_p20       ; t0 * p10_minus_p20 | t1 * p00_minus_p20 | t0 * p11_minus_p21 | t1 * p01_minus_p21
-	__asm fxch  st(2)               ; t0 * p11_minus_p21 | t0 * p10_minus_p20 | t1 * p00_minus_p20 | t1 * p01_minus_p21
-	__asm fsubp st(3), st           ; t0 * p10_minus_p20 | t1 * p00_minus_p20 | t1 * p01_minus_p21 - t0 * p11_minus_p21
-	__asm fsubrp st(1), st           ; t1 * p00_minus_p20 - t0 * p10_minus_p20 | t1 * p01_minus_p21 - t0 * p11_minus_p21
-	__asm fxch  st(1)               ; t1 * p01_minus_p21 - t0 * p11_minus_p21 | t1 * p00_minus_p20 - t0 * p10_minus_p20
-	__asm fmul  xstepdenominv       ; r_lstepx | t1 * p00_minus_p20 - t0 * p10_minus_p20
-	__asm fxch  st(1)
-	__asm fmul  ystepdenominv       ; r_lstepy | r_lstepx
-	__asm fxch  st(1)               ; r_lstepx | r_lstepy
-	__asm fistp dword ptr [r_zistepx]
-	__asm fistp dword ptr [r_zistepy]
-
-	/*
-#if	id386ALIAS
-	a_sstepxfrac = r_sstepx << 16;
-	a_tstepxfrac = r_tstepx << 16;
-#else
-	a_sstepxfrac = r_sstepx & 0xFFFF;
-	a_tstepxfrac = r_tstepx & 0xFFFF;
-#endif
-	*/
-	__asm mov eax, d_pdrawspans
-	__asm cmp eax, offset R_PolysetDrawSpans8_Opaque
-	__asm mov eax, r_sstepx
-	__asm mov ebx, r_tstepx
-	__asm jne translucent
-//#if id386ALIAS
-	__asm shl eax, 16
-	__asm shl ebx, 16
-	__asm jmp done_with_steps
-//#else
-translucent:
-	__asm and eax, 0ffffh
-	__asm and ebx, 0ffffh
-//#endif
-done_with_steps:
-	__asm mov a_sstepxfrac, eax
-	__asm mov a_tstepxfrac, ebx
-
-	/*
-	a_ststepxwhole = skinwidth * (r_tstepx >> 16) + (r_sstepx >> 16);
-	*/
-	__asm mov ebx, r_tstepx
-	__asm mov ecx, r_sstepx
-	__asm sar ebx, 16
-	__asm mov eax, skinwidth
-	__asm mul ebx
-	__asm sar ecx, 16
-	__asm add eax, ecx
-	__asm mov a_ststepxwhole, eax
-}
-#else
 void R_PolysetCalcGradients (int skinwidth)
 {
 	float	xstepdenominv, ystepdenominv, t0, t1;
@@ -715,25 +460,11 @@
 	r_zistepy = (int)((t1 * p00_minus_p20 - t0 * p10_minus_p20) *
 			ystepdenominv);
 
-//#if	id386ALIAS
-#if id386
-	if ( d_pdrawspans == R_PolysetDrawSpans8_Opaque )
-	{
-		a_sstepxfrac = r_sstepx << 16;
-		a_tstepxfrac = r_tstepx << 16;
-	}
-	else
-#endif
-	{
-//#else
-		a_sstepxfrac = r_sstepx & 0xFFFF;
-		a_tstepxfrac = r_tstepx & 0xFFFF;
-	}
-//#endif
+	a_sstepxfrac = r_sstepx & 0xFFFF;
+	a_tstepxfrac = r_tstepx & 0xFFFF;
 
 	a_ststepxwhole = skinwidth * (r_tstepx >> 16) + (r_sstepx >> 16);
 }
-#endif
 
 /*
 ================
@@ -1034,7 +765,6 @@
 	} while (pspanpackage->count != -999999);
 }
 
-#if !id386
 void R_PolysetDrawSpans8_Opaque (spanpackage_t *pspanpackage)
 {
 	int		lcount;
@@ -1103,7 +833,6 @@
 		pspanpackage++;
 	} while (pspanpackage->count != -999999);
 }
-#endif
 
 
 /*
@@ -1182,21 +911,10 @@
 
 	d_ptex = (byte *)r_affinetridesc.pskin + (plefttop[2] >> 16) +
 			(plefttop[3] >> 16) * r_affinetridesc.skinwidth;
-//#if	id386ALIAS
-#if id386
-	if ( d_pdrawspans == R_PolysetDrawSpans8_Opaque )
-	{
-		d_sfrac = (plefttop[2] & 0xFFFF) << 16;
-		d_tfrac = (plefttop[3] & 0xFFFF) << 16;
-	}
-//#else
-	else
-#endif
-	{
-		d_sfrac = plefttop[2] & 0xFFFF;
-		d_tfrac = plefttop[3] & 0xFFFF;
-	}
-//#endif
+
+	d_sfrac = plefttop[2] & 0xFFFF;
+	d_tfrac = plefttop[3] & 0xFFFF;
+
 	d_light = plefttop[4];
 	d_zi = plefttop[5];
 
@@ -1225,21 +943,8 @@
 		R_PolysetSetUpForLineScan(plefttop[0], plefttop[1],
 							  pleftbottom[0], pleftbottom[1]);
 
-//#if	id386ALIAS
-#if id386
-		if ( d_pdrawspans == R_PolysetDrawSpans8_Opaque )
-		{
-			d_pzbasestep = (d_zwidth + ubasestep) << 1;
-			d_pzextrastep = d_pzbasestep + 2;
-		}
-//#else
-		else
-#endif
-		{
-			d_pzbasestep = d_zwidth + ubasestep;
-			d_pzextrastep = d_pzbasestep + 1;
-		}
-//#endif
+		d_pzbasestep = d_zwidth + ubasestep;
+		d_pzextrastep = d_pzbasestep + 1;
 
 		d_pdestbasestep = r_screenwidth + ubasestep;
 		d_pdestextrastep = d_pdestbasestep + 1;
@@ -1258,21 +963,10 @@
 		d_ptexbasestep = ((r_sstepy + r_sstepx * ubasestep) >> 16) +
 				((r_tstepy + r_tstepx * ubasestep) >> 16) *
 				r_affinetridesc.skinwidth;
-//#if	id386ALIAS
-#if id386
-		if ( d_pdrawspans == R_PolysetDrawSpans8_Opaque )
-		{
-			d_sfracbasestep = (r_sstepy + r_sstepx * ubasestep) << 16;
-			d_tfracbasestep = (r_tstepy + r_tstepx * ubasestep) << 16;
-		}
-		else
-#endif
-		{
-//#else
-			d_sfracbasestep = (r_sstepy + r_sstepx * ubasestep) & 0xFFFF;
-			d_tfracbasestep = (r_tstepy + r_tstepx * ubasestep) & 0xFFFF;
-		}
-//#endif
+
+		d_sfracbasestep = (r_sstepy + r_sstepx * ubasestep) & 0xFFFF;
+		d_tfracbasestep = (r_tstepy + r_tstepx * ubasestep) & 0xFFFF;
+
 		d_lightbasestep = r_lstepy + working_lstepx * ubasestep;
 		d_zibasestep = r_zistepy + r_zistepx * ubasestep;
 
@@ -1279,34 +973,14 @@
 		d_ptexextrastep = ((r_sstepy + r_sstepx * d_countextrastep) >> 16) +
 				((r_tstepy + r_tstepx * d_countextrastep) >> 16) *
 				r_affinetridesc.skinwidth;
-//#if	id386ALIAS
-#if id386
-		if ( d_pdrawspans == R_PolysetDrawSpans8_Opaque )
-		{
-			d_sfracextrastep = (r_sstepy + r_sstepx*d_countextrastep) << 16;
-			d_tfracextrastep = (r_tstepy + r_tstepx*d_countextrastep) << 16;
-		}
-		else
-#endif
-		{
-//#else
-			d_sfracextrastep = (r_sstepy + r_sstepx*d_countextrastep) & 0xFFFF;
-			d_tfracextrastep = (r_tstepy + r_tstepx*d_countextrastep) & 0xFFFF;
-		}
-//#endif
+
+		d_sfracextrastep = (r_sstepy + r_sstepx*d_countextrastep) & 0xFFFF;
+		d_tfracextrastep = (r_tstepy + r_tstepx*d_countextrastep) & 0xFFFF;
+
 		d_lightextrastep = d_lightbasestep + working_lstepx;
 		d_ziextrastep = d_zibasestep + r_zistepx;
 
-#if id386
-		if ( d_pdrawspans == R_PolysetDrawSpans8_Opaque )
-		{
-			R_PolysetScanLeftEdge (initialleftheight);
-		}
-		else
-#endif
-		{
-			R_PolysetScanLeftEdge_C(initialleftheight);
-		}
+		R_PolysetScanLeftEdge_C(initialleftheight);
 	}
 
 //
@@ -1348,8 +1022,6 @@
 		// FIXME: need to clamp l, s, t, at both ends?
 			d_pedgespanpackage->light = d_light;
 			d_pedgespanpackage->zi = d_zi;
-
-			d_pedgespanpackage++;
 		}
 		else
 		{
@@ -1359,21 +1031,8 @@
 			d_pdestbasestep = r_screenwidth + ubasestep;
 			d_pdestextrastep = d_pdestbasestep + 1;
 
-//#if	id386ALIAS
-#if id386
-			if ( d_pdrawspans == R_PolysetDrawSpans8_Opaque )
-			{
-				d_pzbasestep = (d_zwidth + ubasestep) << 1;
-				d_pzextrastep = d_pzbasestep + 2;
-			}
-//#else
-			else
-#endif
-			{
-				d_pzbasestep = d_zwidth + ubasestep;
-				d_pzextrastep = d_pzbasestep + 1;
-			}
-//#endif
+			d_pzbasestep = d_zwidth + ubasestep;
+			d_pzextrastep = d_pzbasestep + 1;
 
 			if (ubasestep < 0)
 				working_lstepx = r_lstepx - 1;
@@ -1384,21 +1043,10 @@
 			d_ptexbasestep = ((r_sstepy + r_sstepx * ubasestep) >> 16) +
 					((r_tstepy + r_tstepx * ubasestep) >> 16) *
 					r_affinetridesc.skinwidth;
-//#if	id386ALIAS
-#if id386
-			if ( d_pdrawspans == R_PolysetDrawSpans8_Opaque )
-			{
-				d_sfracbasestep = (r_sstepy + r_sstepx * ubasestep) << 16;
-				d_tfracbasestep = (r_tstepy + r_tstepx * ubasestep) << 16;
-			}
-//#else
-			else
-#endif
-			{
-				d_sfracbasestep = (r_sstepy + r_sstepx * ubasestep) & 0xFFFF;
-				d_tfracbasestep = (r_tstepy + r_tstepx * ubasestep) & 0xFFFF;
-			}
-//#endif
+
+			d_sfracbasestep = (r_sstepy + r_sstepx * ubasestep) & 0xFFFF;
+			d_tfracbasestep = (r_tstepy + r_tstepx * ubasestep) & 0xFFFF;
+
 			d_lightbasestep = r_lstepy + working_lstepx * ubasestep;
 			d_zibasestep = r_zistepy + r_zistepx * ubasestep;
 
@@ -1405,34 +1053,15 @@
 			d_ptexextrastep = ((r_sstepy + r_sstepx * d_countextrastep) >> 16) +
 					((r_tstepy + r_tstepx * d_countextrastep) >> 16) *
 					r_affinetridesc.skinwidth;
-//#if	id386ALIAS
-#if id386
-			if ( d_pdrawspans == R_PolysetDrawSpans8_Opaque )
-			{
-				d_sfracextrastep = ((r_sstepy+r_sstepx*d_countextrastep) & 0xFFFF)<<16;
-				d_tfracextrastep = ((r_tstepy+r_tstepx*d_countextrastep) & 0xFFFF)<<16;
-			}
-			else
-#endif
-//#endif
-			{
-				d_sfracextrastep = (r_sstepy+r_sstepx*d_countextrastep) & 0xFFFF;
-				d_tfracextrastep = (r_tstepy+r_tstepx*d_countextrastep) & 0xFFFF;
-			}
-//#endif
+
+
+			d_sfracextrastep = (r_sstepy+r_sstepx*d_countextrastep) & 0xFFFF;
+			d_tfracextrastep = (r_tstepy+r_tstepx*d_countextrastep) & 0xFFFF;
+
 			d_lightextrastep = d_lightbasestep + working_lstepx;
 			d_ziextrastep = d_zibasestep + r_zistepx;
 
-#if id386
-			if ( d_pdrawspans == R_PolysetDrawSpans8_Opaque )
-			{
-				R_PolysetScanLeftEdge (height);
-			}
-			else
-#endif
-			{
-				R_PolysetScanLeftEdge_C(height);
-			}
+			R_PolysetScanLeftEdge_C(height);
 		}
 	}
 
@@ -1535,5 +1164,3 @@
 
 	pedgetable = &edgetables[edgetableindex];
 }
-
-
--- a/ref/r_rast.c
+++ b/ref/r_rast.c
@@ -17,12 +17,12 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-// r_rast.c
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 
-#include <assert.h>
-
-#include "r_local.h"
-
 #define MAXLEFTCLIPEDGES		100
 
 // !!! if these are changed, they must be changed in asm_draw.h too !!!
@@ -209,8 +209,6 @@
 }
 
 
-#if	!id386
-
 /*
 ================
 R_EmitEdge
@@ -491,9 +489,7 @@
 	R_EmitEdge (pv0, pv1);
 }
 
-#endif	// !id386
 
-
 /*
 ================
 R_EmitCachedEdge
@@ -503,7 +499,7 @@
 {
 	edge_t		*pedge_t;
 
-	pedge_t = (edge_t *)((unsigned long)r_edges + r_pedge->cachededgeoffset);
+	pedge_t = (edge_t *)((uintptr)r_edges + r_pedge->cachededgeoffset);
 
 	if (!pedge_t->surfs[0])
 		pedge_t->surfs[0] = surface_p - surfaces;
@@ -606,9 +602,9 @@
 				}
 				else
 				{
-					if ((((unsigned long)edge_p - (unsigned long)r_edges) >
+					if ((((uintptr)edge_p - (uintptr)r_edges) >
 						 r_pedge->cachededgeoffset) &&
-						(((edge_t *)((unsigned long)r_edges +
+						(((edge_t *)((uintptr)r_edges +
 						 r_pedge->cachededgeoffset))->owner == r_pedge))
 					{
 						R_EmitCachedEdge ();
@@ -652,9 +648,9 @@
 				{
 				// it's cached if the cached edge is valid and is owned
 				// by this medge_t
-					if ((((unsigned long)edge_p - (unsigned long)r_edges) >
+					if ((((uintptr)edge_p - (uintptr)r_edges) >
 						 r_pedge->cachededgeoffset) &&
-						(((edge_t *)((unsigned long)r_edges +
+						(((edge_t *)((uintptr)r_edges +
 						 r_pedge->cachededgeoffset))->owner == r_pedge))
 					{
 						R_EmitCachedEdge ();
--- a/ref/r_scan.c
+++ b/ref/r_scan.c
@@ -17,12 +17,13 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-// d_scan.c
-//
 // Portable C scan-level rasterization code, all pixel depths.
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 
-#include "r_local.h"
-
 unsigned char	*r_turb_pbase, *r_turb_pdest;
 fixed16_t		r_turb_s, r_turb_t, r_turb_sstep, r_turb_tstep;
 int				*r_turb_turb;
@@ -92,8 +93,6 @@
 }
 
 
-#if	!id386
-
 /*
 =============
 D_DrawTurbulent8Span
@@ -113,9 +112,7 @@
 	} while (--r_turb_spancount > 0);
 }
 
-#endif	// !id386
 
-
 /*
 =============
 Turbulent8
@@ -387,8 +384,6 @@
 //====================
 
 
-#if	!id386
-
 /*
 =============
 D_DrawSpans16
@@ -524,11 +519,7 @@
 	} while ((pspan = pspan->pnext) != NULL);
 }
 
-#endif
 
-
-#if	!id386
-
 /*
 =============
 D_DrawZSpans
@@ -561,7 +552,7 @@
 	// we count on FP exceptions being turned off to avoid range problems
 		izi = (int)(zi * 0x8000 * 0x10000);
 
-		if ((long)pdest & 0x02)
+		if ((uintptr)pdest & 0x02)
 		{
 			*pdest++ = (short)(izi >> 16);
 			izi += izistep;
@@ -586,6 +577,3 @@
 
 	} while ((pspan = pspan->pnext) != NULL);
 }
-
-#endif
-
--- a/ref/r_sprite.c
+++ b/ref/r_sprite.c
@@ -17,8 +17,11 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-// r_sprite.c
-#include "r_local.h"
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 
 extern polydesc_t r_polydesc;
 
@@ -46,7 +49,7 @@
 
 
 	s_psprite = (dsprite_t *)currentmodel->extradata;
-#if 0
+/*
 	if (currententity->frame >= s_psprite->numframes
 		|| currententity->frame < 0)
 	{
@@ -54,7 +57,7 @@
 			currententity->frame);
 		currententity->frame = 0;
 	}
-#endif
+*/
 	currententity->frame %= s_psprite->numframes;
 
 	s_psprframe = &s_psprite->frames[currententity->frame];
--- a/ref/r_surf.c
+++ b/ref/r_surf.c
@@ -19,7 +19,11 @@
 */
 // r_surf.c: surface-related refresh code
 
-#include "r_local.h"
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 
 drawsurf_t	r_drawsurf;
 
@@ -163,7 +167,6 @@
 
 //=============================================================================
 
-#if	!id386
 
 /*
 ================
@@ -364,9 +367,7 @@
 	}
 }
 
-#endif
 
-
 //============================================================================
 
 
@@ -450,7 +451,7 @@
 	if ((size <= 0) || (size > 0x10000))
 		ri.Sys_Error (ERR_FATAL,"D_SCAlloc: bad cache size %d\n", size);
 	
-	size = (int)&((surfcache_t *)0)->data[size];
+	size = (int)(uintptr)&((surfcache_t *)0)->data[size];
 	size = (size + 3) & ~3;
 	if (size > sc_size)
 		ri.Sys_Error (ERR_FATAL,"D_SCAlloc: %i > cache size of %i",size, sc_size);
--- a/server/server.h
+++ b/server/server.h
@@ -17,16 +17,8 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
-// server.h
+//#define PARANOID			// speed sapping error checking
 
-
-//define	PARANOID			// speed sapping error checking
-
-#include "../qcommon/qcommon.h"
-#include "../game/game.h"
-
-//=============================================================================
-
 #define	MAX_MASTERS	8				// max recipients for heartbeat packets
 
 typedef enum {
@@ -77,7 +69,7 @@
 					// connection for a couple seconds
 	cs_connected,	// has been assigned to a client_t, but not in game yet
 	cs_spawned		// client is fully in game
-} client_state_t;
+} clstate_t;
 
 typedef struct
 {
@@ -94,7 +86,7 @@
 
 typedef struct client_s
 {
-	client_state_t	state;
+	clstate_t	state;
 
 	char			userinfo[MAX_INFO_STRING];		// name, etc
 
--- a/server/sv_ccmds.c
+++ b/server/sv_ccmds.c
@@ -17,9 +17,12 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 
-#include "server.h"
-
 /*
 ===============================================================================
 
@@ -337,8 +340,7 @@
 	cvar_t	*var;
 	char	name[MAX_OSPATH], string[128];
 	char	comment[32];
-	time_t	aclock;
-	struct tm	*newtime;
+	Tm	*newtime;
 
 	Com_DPrintf("SV_WriteServerFile(%s)\n", autosave ? "true" : "false");
 
@@ -354,11 +356,9 @@
 
 	if (!autosave)
 	{
-		time (&aclock);
-		newtime = localtime (&aclock);
-		Com_sprintf (comment,sizeof(comment), "%2i:%i%i %2i/%2i  ", newtime->tm_hour
-			, newtime->tm_min/10, newtime->tm_min%10,
-			newtime->tm_mon+1, newtime->tm_mday);
+		newtime = localtime (time(nil));
+		Com_sprintf (comment,sizeof(comment), "%2i:%i%i %2i/%2i  ", newtime->hour
+			, newtime->min/10, newtime->min%10, newtime->mon+1, newtime->mday);
 		strncat (comment, sv.configstrings[CS_NAME], sizeof(comment)-1-strlen(comment) );
 	}
 	else
@@ -925,7 +925,7 @@
 	//
 	// write a single giant fake message with all the startup info
 	//
-	SZ_Init (&buf, buf_data, sizeof(buf_data));
+	SZ_Init (&buf, (byte *)buf_data, sizeof(buf_data));
 
 	//
 	// serverdata needs to go over for all types of servers
--- a/server/sv_ents.c
+++ b/server/sv_ents.c
@@ -17,9 +17,12 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 
-#include "server.h"
-
 /*
 =============================================================================
 
@@ -28,7 +31,7 @@
 =============================================================================
 */
 
-#if 0
+/* commented out in release
 
 // because there can be a lot of projectiles, there is a special
 // network protocol for them
@@ -113,7 +116,7 @@
 			MSG_WriteByte (msg, bits[i]);
 	}
 }
-#endif
+*/
 
 /*
 =============
@@ -124,17 +127,17 @@
 */
 void SV_EmitPacketEntities (client_frame_t *from, client_frame_t *to, sizebuf_t *msg)
 {
-	entity_state_t	*oldent, *newent;
+	entity_state_t	*oldent = nil, *newent = nil;
 	int		oldindex, newindex;
 	int		oldnum, newnum;
 	int		from_num_entities;
 	int		bits;
 
-#if 0
+/*
 	if (numprojs)
 		MSG_WriteByte (msg, svc_packetentities2);
 	else
-#endif
+*/
 		MSG_WriteByte (msg, svc_packetentities);
 
 	if (!from)
@@ -203,10 +206,10 @@
 
 	MSG_WriteShort (msg, 0);	// end of packetentities
 
-#if 0
+/*
 	if (numprojs)
 		SV_EmitProjectileUpdate(msg);
-#endif
+*/
 }
 
 
@@ -538,9 +541,7 @@
 	if (!clent->client)
 		return;		// not in game yet
 
-#if 0
-	numprojs = 0; // no projectiles yet
-#endif
+	//numprojs = 0; // no projectiles yet
 
 	// this is the frame we are creating
 	frame = &client->frames[sv.framenum & UPDATE_MASK];
@@ -645,10 +646,10 @@
 			}
 		}
 
-#if 0
+/*
 		if (SV_AddProjectileUpdate(ent))
 			continue; // added as a special projectile
-#endif
+*/
 
 		// add it to the circular client_entities array
 		state = &svs.client_entities[svs.next_client_entities%svs.num_client_entities];
--- a/server/sv_game.c
+++ b/server/sv_game.c
@@ -19,7 +19,11 @@
 */
 // sv_game.c -- interface to the game dll
 
-#include "server.h"
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 
 game_export_t	*ge;
 
@@ -85,7 +89,7 @@
 {
 	char		msg[1024];
 	va_list		argptr;
-	int			n;
+	int		n = 0;
 
 	if (ent)
 	{
@@ -383,7 +387,7 @@
 	import.SetAreaPortalState = CM_SetAreaPortalState;
 	import.AreasConnected = CM_AreasConnected;
 
-	ge = (game_export_t *)Sys_GetGameAPI (&import);
+	ge = GetGameAPI(&import);
 
 	if (!ge)
 		Com_Error (ERR_DROP, "failed to load game DLL");
@@ -393,4 +397,3 @@
 
 	ge->Init ();
 }
-
--- a/server/sv_init.c
+++ b/server/sv_init.c
@@ -17,9 +17,12 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 
-#include "server.h"
-
 server_static_t	svs;				// persistant server info
 server_t		sv;					// local server
 
@@ -416,7 +419,7 @@
 		Cvar_Set ("nextserver", "");
 
 	//ZOID special hack for end game screen in coop mode
-	if (Cvar_VariableValue ("coop") && !Q_stricmp(level, "victory.pcx"))
+	if (Cvar_VariableValue ("coop") && !Q_strcasecmp(level, "victory.pcx"))
 		Cvar_Set ("nextserver", "gamemap \"*base1\"");
 
 	// if there is a $, use the remainder as a spawnpoint
--- a/server/sv_main.c
+++ b/server/sv_main.c
@@ -17,9 +17,12 @@
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
 */
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 
-#include "server.h"
-
 netadr_t	master_adr[MAX_MASTERS];	// address of group servers
 
 client_t	*sv_client;			// current client
@@ -147,11 +150,11 @@
 void SVC_Status (void)
 {
 	Netchan_OutOfBandPrint (NS_SERVER, net_from, "print\n%s", SV_StatusString());
-#if 0
+/*
 	Com_BeginRedirect (RD_PACKET, sv_outputbuf, SV_OUTPUTBUF_LENGTH, SV_FlushRedirect);
 	Com_Printf (SV_StatusString());
 	Com_EndRedirect ();
-#endif
+*/
 }
 
 /*
@@ -530,12 +533,12 @@
 		if (cl->state != cs_spawned )
 			continue;
 
-#if 0
+/*
 		if (cl->lastframe > 0)
 			cl->frame_latency[sv.framenum&(LATENCY_COUNTS-1)] = sv.framenum - cl->lastframe + 1;
 		else
 			cl->frame_latency[sv.framenum&(LATENCY_COUNTS-1)] = 0;
-#endif
+*/
 
 		total = 0;
 		count = 0;
@@ -550,11 +553,8 @@
 		if (!count)
 			cl->ping = 0;
 		else
-#if 0
-			cl->ping = total*100/count - 100;
-#else
+			//cl->ping = total*100/count - 100;
 			cl->ping = total / count;
-#endif
 
 		// let the game dll know about the ping
 		cl->edict->client->ping = cl->ping;
@@ -705,7 +705,7 @@
 	edict_t	*ent;
 	int		i;
 
-	for (i=0 ; i<ge->num_edicts ; i++, ent++)
+	for (i=0 ; i<ge->num_edicts ; i++)
 	{
 		ent = EDICT_NUM(i);
 		// events only last for a single message
--- a/server/sv_send.c
+++ b/server/sv_send.c
@@ -19,7 +19,11 @@
 */
 // sv_main.c -- server main program
 
-#include "server.h"
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 
 /*
 =============================================================================
@@ -175,10 +179,7 @@
 		area1 = CM_LeafArea (leafnum);
 	}
 	else
-	{
-		leafnum = 0;	// just to avoid compiler warnings
-		area1 = 0;
-	}
+		area1 = 0;	// just to avoid compiler warnings
 
 	// if doing a serverrecord, store everything
 	if (svs.demofile)
@@ -189,7 +190,6 @@
 	case MULTICAST_ALL_R:
 		reliable = true;	// intentional fallthrough
 	case MULTICAST_ALL:
-		leafnum = 0;
 		mask = NULL;
 		break;
 
--- a/server/sv_user.c
+++ b/server/sv_user.c
@@ -19,7 +19,11 @@
 */
 // sv_user.c -- server code for moving users
 
-#include "server.h"
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 
 edict_t	*sv_player;
 
--- a/server/sv_world.c
+++ b/server/sv_world.c
@@ -19,7 +19,11 @@
 */
 // world.c -- world query functions
 
-#include "server.h"
+#include <u.h>
+#include <libc.h>
+#include <stdio.h>
+#include "../dat.h"
+#include "../fns.h"
 
 /*
 ===============================================================================
@@ -33,7 +37,7 @@
 // (type *)STRUCT_FROM_LINK(link_t *link, type, member)
 // ent = STRUCT_FROM_LINK(link,entity_t,order)
 // FIXME: remove this mess!
-#define	STRUCT_FROM_LINK(l,t,m) ((t *)((byte *)l - (int)&(((t *)0)->m)))
+#define	STRUCT_FROM_LINK(l,t,m) ((t *)((byte *)l - (uintptr)&(((t *)0)->m)))
 
 #define	EDICT_FROM_AREA(l) STRUCT_FROM_LINK(l,edict_t,area)
 
@@ -355,10 +359,7 @@
 {
 	link_t		*l, *next, *start;
 	edict_t		*check;
-	int			count;
 
-	count = 0;
-
 	// touch linked edicts
 	if (area_type == AREA_SOLID)
 		start = &node->solid_edicts;
@@ -434,7 +435,6 @@
 	int			i, num;
 	int			contents, c2;
 	int			headnode;
-	float		*angles;
 
 	// get base contents from world
 	contents = CM_PointContents (p, sv.models[1]->headnode);
@@ -448,9 +448,13 @@
 
 		// might intersect, so do an exact clip
 		headnode = SV_HullForEntity (hit);
+
+		/* unused
+		float *angles;
 		angles = hit->s.angles;
 		if (hit->solid != SOLID_BSP)
 			angles = vec3_origin;	// boxes don't rotate
+		*/
 
 		c2 = CM_TransformedPointContents (p, headnode, hit->s.origin, hit->s.angles);
 
@@ -588,11 +592,11 @@
 */
 void SV_TraceBounds (vec3_t start, vec3_t mins, vec3_t maxs, vec3_t end, vec3_t boxmins, vec3_t boxmaxs)
 {
-#if 0
-// debug to test against everything
-boxmins[0] = boxmins[1] = boxmins[2] = -9999;
-boxmaxs[0] = boxmaxs[1] = boxmaxs[2] = 9999;
-#else
+/*
+	// debug to test against everything
+	boxmins[0] = boxmins[1] = boxmins[2] = -9999;
+	boxmaxs[0] = boxmaxs[1] = boxmaxs[2] = 9999;
+*/
 	int		i;
 	
 	for (i=0 ; i<3 ; i++)
@@ -608,7 +612,6 @@
 			boxmaxs[i] = start[i] + maxs[i] + 1;
 		}
 	}
-#endif
 }
 
 /*