File: sys_unix.c

package info (click to toggle)
uhexen2 1.5.6+dfsg-1
  • links: PTS
  • area: contrib
  • in suites: jessie, jessie-kfreebsd
  • size: 16,340 kB
  • ctags: 23,477
  • sloc: ansic: 188,956; asm: 14,958; makefile: 3,475; sh: 3,325; objc: 330; pascal: 213; cpp: 19
file content (1008 lines) | stat: -rw-r--r-- 23,418 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
/*
 * sys_unix.c -- Unix system interface code
 * $Id: sys_unix.c 5033 2013-01-07 10:00:49Z sezero $
 *
 * Copyright (C) 1996-1997  Id Software, Inc.
 * Copyright (C) 2001 contributors of the Anvil of Thyrion project
 * Copyright (C) 2004-2005  Steven Atkinson <stevenaaus@yahoo.com>
 * Copyright (C) 2005-2012  O.Sezer <sezero@users.sourceforge.net>
 *
 * 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.,
 * 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "quakedef.h"
#if defined(PLATFORM_OSX)
#include "sys_osx.h"	/* Mac OS X specifics */
#elif defined(SDLQUAKE)
#include "sys_sdl.h"	/* alternative implementations using SDL. */
#endif
#include "userdir.h"
#include "debuglog.h"

#include <errno.h>
#include <unistd.h>
#if USE_PASSWORD_FILE && DO_USERDIRS
#include <pwd.h>
#endif	/* USE_PASSWORD_FILE */
#include <sys/stat.h>
#include <sys/time.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <signal.h>
#include <dirent.h>
#include <fnmatch.h>
#include <time.h>
#include <utime.h>
#if defined(SDLQUAKE)
#include "sdl_inc.h"
#endif	/* SDLQUAKE */


// heapsize: minimum 16mb, standart 32 mb, max is 96 mb.
// -heapsize argument will abide by these min/max settings
// unless the -forcemem argument is used
#define MIN_MEM_ALLOC	0x1000000
#define STD_MEM_ALLOC	0x2000000
#define MAX_MEM_ALLOC	0x6000000

cvar_t		sys_nostdout = {"sys_nostdout", "0", CVAR_NONE};
cvar_t		sys_throttle = {"sys_throttle", "0.02", CVAR_ARCHIVE};

qboolean		isDedicated;
static double		starttime;
static qboolean		first = true;


/*
===============================================================================

FILE IO

===============================================================================
*/

int Sys_mkdir (const char *path, qboolean crash)
{
	int rc = mkdir (path, 0777);
	if (rc != 0 && errno == EEXIST)
		rc = 0;
	if (rc != 0 && crash)
	{
		rc = errno;
		Sys_Error("Unable to create directory %s: %s", path, strerror(rc));
	}
	return rc;
}

int Sys_rmdir (const char *path)
{
	return rmdir(path);
}

int Sys_unlink (const char *path)
{
	return unlink(path);
}

int Sys_rename (const char *oldp, const char *newp)
{
	return rename(oldp, newp);
}

long Sys_filesize (const char *path)
{
	struct stat	st;

	if (stat(path, &st) != 0)
		return -1;
	if (! S_ISREG(st.st_mode))
		return -1;

	return (long) st.st_size;
}

int Sys_FileType (const char *path)
{
	/*
	if (access(path, R_OK) == -1)
		return 0;
	*/
	struct stat	st;

	if (stat(path, &st) != 0)
		return FS_ENT_NONE;
	if (S_ISDIR(st.st_mode))
		return FS_ENT_DIRECTORY;
	if (S_ISREG(st.st_mode))
		return FS_ENT_FILE;

	return FS_ENT_NONE;
}

#define	COPY_READ_BUFSIZE		8192	/* BUFSIZ */
int Sys_CopyFile (const char *frompath, const char *topath)
{
	char	buf[COPY_READ_BUFSIZE];
	FILE	*in, *out;
	struct stat	st;
	int		err = 0;
//	off_t		remaining, count;
	size_t		remaining, count;

	if (stat(frompath, &st) != 0)
	{
		Con_Printf ("%s: unable to stat %s\n", __thisfunc__, frompath);
		return 1;
	}
	in = fopen (frompath, "rb");
	if (!in)
	{
		Con_Printf ("%s: unable to open %s\n", __thisfunc__, frompath);
		return 1;
	}
	out = fopen (topath, "wb");
	if (!out)
	{
		Con_Printf ("%s: unable to create %s\n", __thisfunc__, topath);
		fclose (in);
		return 1;
	}

	remaining = st.st_size;
	memset (buf, 0, sizeof(buf));
	while (remaining)
	{
		if (remaining < sizeof(buf))
			count = remaining;
		else
			count = sizeof(buf);

		fread (buf, 1, count, in);
		err = ferror (in);
		if (err)
			break;

		fwrite (buf, 1, count, out);
		err = ferror (out);
		if (err)
			break;

		remaining -= count;
	}

	fclose (in);
	fclose (out);

	if (!err)
	{
	// restore the file's timestamp
		struct utimbuf		tm;
		tm.actime = time (NULL);
		tm.modtime = st.st_mtime;
		utime (topath, &tm);
	}

	return err;
}

/*
=================================================
simplified findfirst/findnext implementation:
Sys_FindFirstFile and Sys_FindNextFile return
filenames only, not a dirent struct. this is
what we presently need in this engine.
=================================================
*/
static DIR		*finddir;
static struct dirent	*finddata;
static char		*findpath, *findpattern;

const char *Sys_FindFirstFile (const char *path, const char *pattern)
{
	if (finddir)
		Sys_Error ("Sys_FindFirst without FindClose");

	finddir = opendir (path);
	if (!finddir)
		return NULL;

	findpattern = Z_Strdup (pattern);
	findpath = Z_Strdup (path);

	return Sys_FindNextFile();
}

const char *Sys_FindNextFile (void)
{
	struct stat	test;

	if (!finddir)
		return NULL;

	while ((finddata = readdir(finddir)) != NULL)
	{
		if (!fnmatch (findpattern, finddata->d_name, FNM_PATHNAME))
		{
			if ( (stat(va("%s/%s", findpath, finddata->d_name), &test) == 0)
						&& S_ISREG(test.st_mode))
				return finddata->d_name;
		}
	}

	return NULL;
}

void Sys_FindClose (void)
{
	if (finddir != NULL)
	{
		closedir(finddir);
		finddir = NULL;
	}
	if (findpath != NULL)
	{
		Z_Free (findpath);
		findpath = NULL;
	}
	if (findpattern != NULL)
	{
		Z_Free (findpattern);
		findpattern = NULL;
	}
}

/*
===============================================================================

SYSTEM IO

===============================================================================
*/

/*
================
Sys_MakeCodeWriteable
================
*/
#if id386 && !defined(GLQUAKE)
void Sys_MakeCodeWriteable (unsigned long startaddr, unsigned long length)
{
	int		r;
	unsigned long	endaddr = startaddr + length;
// systems with mprotect but not getpagesize (or similar) probably don't
// need to page align the arguments to mprotect (eg, QNX)
#if !(defined(__QNX__) || defined(__QNXNTO__))
//	int		psize = getpagesize ();
	long		psize = sysconf (_SC_PAGESIZE);
	startaddr &= ~(psize - 1);
	endaddr = (endaddr + psize - 1) & ~(psize - 1);
#endif
	r = mprotect ((char *) startaddr, endaddr - startaddr, PROT_WRITE | PROT_READ | PROT_EXEC);

	if (r == -1)
		Sys_Error("Protection change failed\n");
}
#endif	/* id386, !GLQUAKE */


/*
================
Sys_Init
================
*/
static void Sys_Init (void)
{
/* do we really need these with opengl ?? */
	Sys_SetFPCW();
}


#if !defined(Sys_ErrorMessage)
#define Sys_ErrorMessage(T)	do {} while (0)
#endif

#define ERROR_PREFIX	"\nFATAL ERROR: "
void Sys_Error (const char *error, ...)
{
	va_list		argptr;
	char		text[MAX_PRINTMSG];
	const char	text2[] = ERROR_PREFIX;
	const unsigned char	*p;

	va_start (argptr, error);
	q_vsnprintf (text, sizeof(text), error, argptr);
	va_end (argptr);

	if (con_debuglog)
	{
		LOG_Print (ERROR_PREFIX);
		LOG_Print (text);
		LOG_Print ("\n\n");
	}

	Host_Shutdown ();

	for (p = (const unsigned char *) text2; *p; p++)
		putc (*p, stderr);
	for (p = (const unsigned char *) text ; *p; p++)
		putc (*p, stderr);
	putc ('\n', stderr);
	putc ('\n', stderr);
	if (!isDedicated)
		Sys_ErrorMessage (text);

	exit (1);
}

void Sys_PrintTerm (const char *msgtxt)
{
	const unsigned char	*p;

	if (sys_nostdout.integer)
		return;

	for (p = (const unsigned char *) msgtxt; *p; p++)
		putc (*p, stdout);
}

void Sys_Quit (void)
{
	Host_Shutdown();

	exit (0);
}


/*
================
Sys_DoubleTime
================
*/
double Sys_DoubleTime (void)
{
	struct timeval	tp;
	double		now;

	gettimeofday (&tp, NULL);

	now = tp.tv_sec + tp.tv_usec / 1e6;

	if (first)
	{
		first = false;
		starttime = now;
		return 0.0;
	}

	return now - starttime;
}

char *Sys_DateTimeString (char *buf)
{
	static char strbuf[24];
	time_t t;
	struct tm *l;
	int val;

	if (!buf) buf = strbuf;

	t = time(NULL);
	l = localtime(&t);

	val = l->tm_mon + 1;	/* tm_mon: months since January [0,11] */
	buf[0] = val / 10 + '0';
	buf[1] = val % 10 + '0';
	buf[2] = '/';
	val = l->tm_mday;
	buf[3] = val / 10 + '0';
	buf[4] = val % 10 + '0';
	buf[5] = '/';
	val = l->tm_year / 100 + 19;	/* tm_year: #years since 1900. */
	buf[6] = val / 10 + '0';
	buf[7] = val % 10 + '0';
	val = l->tm_year % 100;
	buf[8] = val / 10 + '0';
	buf[9] = val % 10 + '0';

	buf[10] = ' ';

	val = l->tm_hour;
	buf[11] = val / 10 + '0';
	buf[12] = val % 10 + '0';
	buf[13] = ':';
	val = l->tm_min;
	buf[14] = val / 10 + '0';
	buf[15] = val % 10 + '0';
	buf[16] = ':';
	val = l->tm_sec;
	buf[17] = val / 10 + '0';
	buf[18] = val % 10 + '0';

	buf[19] = '\0';

	return buf;
}


/*
================
Sys_ConsoleInput
================
*/
const char *Sys_ConsoleInput (void)
{
	static char	con_text[256];
	static int	textlen;
	char		c;
	fd_set		set;
	struct timeval	timeout;

	FD_ZERO (&set);
	FD_SET (0, &set);	// stdin
	timeout.tv_sec = 0;
	timeout.tv_usec = 0;

	while (select (1, &set, NULL, NULL, &timeout))
	{
		read (0, &c, 1);
		if (c == '\n' || c == '\r')
		{
			con_text[textlen] = '\0';
			textlen = 0;
			return con_text;
		}
		else if (c == 8)
		{
			if (textlen)
			{
				textlen--;
				con_text[textlen] = '\0';
			}
			continue;
		}
		con_text[textlen] = c;
		textlen++;
		if (textlen < (int) sizeof(con_text))
			con_text[textlen] = '\0';
		else
		{
		// buffer is full
			textlen = 0;
			con_text[0] = '\0';
			Sys_PrintTerm("\nConsole input too long!\n");
			break;
		}
	}

	return NULL;
}

void Sys_Sleep (unsigned long msecs)
{
	usleep (msecs * 1000);
}

void Sys_SendKeyEvents (void)
{
	IN_SendKeyEvents();
}

#if !defined(Sys_GetClipboardData)
#define Sys_GetClipboardData Sys_GetClipboardData /* */
char *Sys_GetClipboardData (void)
{
	return NULL;
}
#endif

#if !defined(Sys_GetBasedir)
#define Sys_GetBasedir UNIX_GetBasedir
static int UNIX_GetBasedir (char *argv0, char *dst, size_t dstsize)
{
	char	*tmp;

	if (getcwd(dst, dstsize - 1) == NULL)
		return -1;

	tmp = dst;
	while (*tmp != 0)
		tmp++;
	while (*tmp == 0 && tmp != dst)
	{
		--tmp;
		if (tmp != dst && *tmp == '/')
			*tmp = 0;
	}

	return 0;
}
#endif /* Sys_GetBasedir */

#if DO_USERDIRS
static int Sys_GetUserdir (char *dst, size_t dstsize)
{
	size_t		n;
	const char	*home_dir = NULL;
#if USE_PASSWORD_FILE
	struct passwd	*pwent;

	pwent = getpwuid( getuid() );
	if (pwent == NULL)
		perror("getpwuid");
	else
		home_dir = pwent->pw_dir;
#endif
	if (home_dir == NULL)
		home_dir = getenv("HOME");
	if (home_dir == NULL)
		return 1;

/* what would be a maximum path for a file in the user's directory...
 * $HOME/AOT_USERDIR/game_dir/dirname1/dirname2/dirname3/filename.ext
 * still fits in the MAX_OSPATH == 256 definition, but just in case.
 */
	n = strlen(home_dir) + strlen(AOT_USERDIR) + 50;
	if (n >= dstsize)
	{
		Sys_Error ("%s: Insufficient bufsize %d. Need at least %d.",
					__thisfunc__, (int)dstsize, (int)n);
	}

	q_snprintf (dst, dstsize, "%s/%s", home_dir, AOT_USERDIR);
	return 0;
}
#endif	/* DO_USERDIRS */

static void Sys_CheckSDL (void)
{
#if defined(SDLQUAKE)
	const SDL_version *sdl_version;

	sdl_version = SDL_Linked_Version();
	Sys_Printf("Found SDL version %i.%i.%i\n",sdl_version->major,sdl_version->minor,sdl_version->patch);
	if (SDL_VERSIONNUM(sdl_version->major,sdl_version->minor,sdl_version->patch) < SDL_REQUIREDVERSION)
	{	/*reject running under SDL versions older than what is stated in sdl_inc.h */
		Sys_Error("You need at least v%d.%d.%d of SDL to run this game.", SDL_MIN_X,SDL_MIN_Y,SDL_MIN_Z);
	}
# if defined(SDL_NEW_VERSION_REJECT)
	if (SDL_VERSIONNUM(sdl_version->major,sdl_version->minor,sdl_version->patch) >= SDL_NEW_VERSION_REJECT)
	{	/*reject running under SDL versions newer than what is stated in sdl_inc.h */
		Sys_Error("Your version of SDL library is incompatible with me.\n"
			  "You need a library version in the line of %d.%d.%d\n", SDL_MIN_X,SDL_MIN_Y,SDL_MIN_Z);
	}
# endif /* SDL_NEW_VERSION_REJECT */
#endif	/* SDLQUAKE */
}

static void PrintVersion (void)
{
	Sys_Printf ("Hammer of Thyrion, release %s (%s)\n", HOT_VERSION_STR, HOT_VERSION_REL_DATE);
	Sys_Printf ("running on %s engine %4.2f (%s)\n", ENGINE_NAME, ENGINE_VERSION, PLATFORM_STRING);
	Sys_Printf ("More info / sending bug reports:  http://uhexen2.sourceforge.net\n");
}

#include "snd_sys.h"

/* Summarise command line options and inspect for correctness.
 * No attempt is made to validate arg type is integer or whatever.
 * Note: dos, windows options are not handled here.
 * S.A. 22 Jan 2009  */
typedef struct
{
	const char	*option;
	const char	*alias1;
	const char	*alias2;
	int		num_args; /* only 0, 1 (and -1:one optional arg) are currently implemented */
	const char	*descrip; /* if option = "" , descrip is an help section title */
} option_t;

static option_t options[] =
{
/* GENERAL */
	{"","","",0,"General"},
#ifndef DEMOBUILD
#   if defined(H2MP)
	{"-noportals",	"",		"",	0, "Disable the mission pack support"},
#   else
	{"-portals",	"-h2mp",	"",	0, "Play Portal of Praevus mission pack"},
#   endif
#endif
	{"-game",	"",		"",	1, "Play this mod"},
	{"-basedir",	"",		"",	1, "Use this directory as base"},
	{"-nomouse",	"",		"",	0, "Disable mouse"},
	{"-heapsize",	"",		"",	1, "Kilobytes memory for heap"},
	{"-v",		"--version",	"",	0, "Display version information"},
	{"-h",		"--help",	"-?",	0, "Show help"},
/* VIDEO */
	{"","","",0,"Video"},
#ifndef SVGAQUAKE
	{"-f",		"-fullscreen",	"",	0, "Run fullscreen"},
	{"-w",		"-window",	"",	0, "Run as a window"},
#endif
	{"-width",	"",		"",	1, "Set screen width"},
	{"-height",	"",		"",	1, "Set screen height (requires -width)"},
	{"-force",	"",		"",	0, "Skip some video sanity checks"},
	{"-conwidth",	"",		"",	1, "Set console width (in pixels)"},
#ifdef GLQUAKE
	{"-bpp",	"",		"",	1, "Depth for GL fullscreen mode"},
	{"-sync",	"-vsync",	"",	0, "Enable sync with monitor refresh"},
	{"-g",		"-gllibrary",	"",	1, "Select 3D rendering library"},
	{"-fsaa",	"",		"",	1, "Enable N sample antialiasing"},
	{"-paltex",	"",		"",	0, "Enable 8-bit textures"},
	{"-nomtex",	"",		"",	0, "Disable multitexture detection/usage"},
#endif
/* SOUND */
	{"","","",0,"Sound"},

#if !defined(_NO_SOUND)
#if SOUND_NUMDRIVERS
	{"-s",		"-nosound",	"",	0, "Disable sound"},
#endif
#if (SOUND_NUMDRIVERS > 1)
#if HAVE_OSS_SOUND
	{"-sndoss",	"",		"",	0, "Use OSS sound"},
#endif
#if HAVE_ALSA_SOUND
	{"-sndalsa",	"",		"",	0, "Use ALSA sound (alsa > 1.0.1)"},
#endif
#if HAVE_SUN_SOUND
	{"-sndsun",	"-sndbsd",	"",	0, "Use SUN/BSD sound"},
#endif
#if HAVE_SDL_SOUND
	{"-sndsdl",	"",		"",	0, "Use SDL sound"},
#endif
#endif	/*  SOUND_NUMDRIVERS */
#endif	/* _NO_SOUND */
	{"-sndspeed",	"",		"",	1, "Sound sampling rate"},
	{"-sndbits",	"",		"",	1, "Sound sampling bits"},
	{"-alsadev",	"",		"",	1, "Alsa device name"},
	{"-ossdev",	"",		"",	1, "OSS device name"},
	{"-sndmono",	"",		"",	0, "Set mono playback"},
/* MUSIC */
	{"","","",0,"Music"},

	{"-nomidi",	"",		"",	0, "Disable midi device"},
	{"-nocdaudio",	"",		"",	0, "Disable CD playback"},
	{"-cddev",	"",		"",	1, "Use this CD device"},
/* NETWORK */
	{"","","",0,"Network"},

	{"-listen",	"",		"",	-1, "Enable multiplayer with max N players"},
	{"-dedicated",	"",		"",	-1, "Enable dedicated server with max N players"},
	{"-nolan",	"",		"",	0, "Disable local area network"},
	{"-noudp",	"",		"",	0, "Disable udp"},
	{"-noifscan",	"",		"",	0, "Disable net interface scan"},
	{"-ip",		"-bindip",	"",	1, "Use this IP address"},
	{"-localip",	"",		"",	1, "Use this local IP address"},
	{"-port",	"",		"",	1, "Use this port"},
	{"-udpport",	"",		"",	1, "Use this udp port"},
	{"-ipxport",	"",		"",	1, "Use this ipx port"},
/* DEBUG */
	{"","","",0,"Debugging"},

	{"-condebug",	"-debuglog",	"",	0, "Do extra debug logging"},
	{"-developer",	"",		"",	0, "Set developer cvar"},
	{"-devlog",	"",		"",	0, "Log some dev events when !developer"},
	{"-safemode",	"",		"",	0, "Disable some hardware features"},
/* extra OPENGL */
#ifdef GLQUAKE
	{"","","",0,"Extra OpenGL"},

	{"-lm_1",	"",		"",	0, "use GL_LUMINANCE light format"},
	{"-lm_4",	"",		"",	0, "use GL_RGBA      light format"},
# ifdef USE_3DFXGAMMA
	{"-3dfxgamma",	"",		"",	0, "enable 3dfx gamma support"},
# endif
#endif
/* SVGA */
#ifdef SVGAQUAKE
	{"","","",0,"SVGA"},
	{"-mode",	"",		"",	1, "SVGA mode"},
	{"-mdev",	"",		"",	1, "Use this mouse device"},
	{"-mrate",	"",		"",	1, "Mouse sampling rate"},
	{"-nokbd",	"",		"",	0, "Disable keyboard"},
#endif
/* MISCELLANEOUS */
	{"","","",0,"Miscellaneous"},
	{"-forcemem",	"",		"",	0, "Force memory option"},
	{"-surfcachesize","",		"",	1, "Surface cache size"},
	{"-protocol",	"",		"",	1, "Request different game version"},
	{"-particles",	"",		"",	1, "Set number of particles"},
	{"-fullsbar",	"",		"",	0, "Enable full status bar (unused)"},
	{"-nojoy",	"",		"",	0, "Disable joystick"},
	{"-zone",	"",		"",	1, "Zone memory size"},
/* end used to terminate options */
	{"end","","",0,""}
};

static void CheckArgs (int argc, char **argv)
{
	/* Check each argv[] against the options registered above -
	 * If it's not a valid option, exit with error message.
	 * Else, skip checking the next option.num_arg argv[].
	 * (num_args=-1 means a single argv[] is optional).
	 * Also allow for game commands like "+r_shadow 1"  */
	int	i, j, valid, skip;
	int	num_avail_options;
	char	string[40];

	/* find how many options are registered */
	for (i = 1; ; i++)
	{
		if (options[i].option[0] == 0)
			continue;
		if (strcmp(options[i].option, "end") == 0)
			break;
	}
	num_avail_options = i;

	if (argc <= 1)
		return;

	skip = 0;

	for (i = 1; i < argc; i++)
	{
		if (skip == 1) {
			/* one arg only */
			skip = 0;
			continue;
		}
		if (skip == -1) {
			/* optional single arg */
			skip = 0;
			if (argv[i][0] != '-')
				continue;
		}
		if (skip == -2) {
			/* parsing +game_command */
			/* +game command found... skip till we find an "-option" */
			if (argv[i][0] != '-')
				continue;
			else
				skip = 0;
		}

		if ( !strcmp(argv[i], "-v") || !strcmp(argv[i], "-version" ) ||
			!strcmp(argv[i], "--version"))
		{
			exit(0);
		}
		if ( !strcmp(argv[i], "-h") || !strcmp(argv[i], "-help" ) ||
			!strcmp(argv[i], "-?") || !strcmp(argv[i], "--help"))
		{
			Sys_Printf ("\nUsage: %s [options] [+gamecommands]\n", argv[0]);
			for (j = 0; j < num_avail_options; j++)
			{
				if (options[j].option[0]) {
				    sprintf (string, "     %s", options[j].option);
				    if (options[j].alias1[0]) {
					    strcat (string, " | ");
					    strcat (string, options[j].alias1);
				    }
				    if (options[j].num_args == 1)
					    strcat (string, " ARG");
				    if (options[j].num_args == -1)
					    strcat (string, " [ARG]");
				    Sys_Printf  ("%-30s%s\n", string, options[j].descrip);
				} else {
				    /* print header */
				    Sys_Printf  ("\n%s Options:\n", options[j].descrip);
				}
			}
			exit (0);
		}

		valid = 0; /* check this arg is valid */

		for (j = 0; j < num_avail_options; j++)
		{
			if (!options[j].option[0]) 
				continue;

			valid = (strcmp(options[j].option, argv[i]) == 0) |
				(strcmp(options[j].alias1, argv[i]) == 0) |
				(strcmp(options[j].alias2, argv[i]) == 0);
			if (valid)
				break;
		}

		if (valid) {
			switch (options[j].num_args) {
			case 1:
				/* ensure there is one, and skip checking next arg */
				if (i == argc-1) {
					Sys_Printf ("\n%s: missing arg for option \"%s\"\n",argv[0],argv[i]);
					exit(1);
				}
				/* this assumes that strings beginning with "-" and "+" will
				 * never be valid values for an option */
				if (argv[i+1][0] == '-' || argv[i+1][0] == '+') {
					Sys_Printf ("\n%s: Missing arg for option \"%s\"\n",argv[0],argv[i]);
					exit(1);
				}
				skip = 1;
				break;
			case -1:
				skip = -1;
				break;
#if 0
			case 0:
				/* doesn't accept args: make sure there aren't any. */
				if (argv[i+1][0] != '-' && argv[i+1][0] != '+') {
					Sys_Printf ("\n%s: Unwanted arg for option \"%s\"\n",argv[0],argv[i]);
					exit(1);
				}
#endif
			}
		} else {
			if (argv[i][0] == '+') {
				skip = -2;
			} else {
				Sys_Printf ("\n%s: illegal arg \"%s\"\n", argv[0], argv[i]);
				exit (1);
			}
		}
	}
}

/*
===============================================================================

MAIN

===============================================================================
*/
static quakeparms_t	parms;
static char	cwd[MAX_OSPATH];
#if DO_USERDIRS
static char	userdir[MAX_OSPATH];
#endif
#if defined(SDLQUAKE)
static Uint8		appState;
#endif

int main (int argc, char **argv)
{
	int			i;
	double		time, oldtime, newtime;

	PrintVersion();

	CheckArgs(argc, argv);

	memset (cwd, 0, sizeof(cwd));
	if (Sys_GetBasedir(argv[0], cwd, sizeof(cwd)) != 0)
		Sys_Error ("Couldn't determine current directory");

#if DO_USERDIRS
	memset (userdir, 0, sizeof(userdir));
	if (Sys_GetUserdir(userdir, sizeof(userdir)) != 0)
		Sys_Error ("Couldn't determine userspace directory");
	Sys_mkdir(userdir, true);
#endif

	/* initialize the host params */
	memset (&parms, 0, sizeof(parms));
	parms.basedir = "/usr/share/games/hexen2";
#if DO_USERDIRS
	parms.userdir = userdir;
#else
	parms.userdir = cwd;
#endif
	parms.argc = argc;
	parms.argv = argv;
	host_parms = &parms;

	LOG_Init (&parms);

	Sys_Printf("basedir is: %s\n", parms.basedir);
	Sys_Printf("userdir is: %s\n", parms.userdir);

	COM_ValidateByteorder ();

	isDedicated = (COM_CheckParm ("-dedicated") != 0);

	Sys_CheckSDL ();

	if (isDedicated)
		parms.memsize = MIN_MEM_ALLOC;
	else
		parms.memsize = STD_MEM_ALLOC;

	i = COM_CheckParm ("-heapsize");
	if (i && i < com_argc-1)
	{
		parms.memsize = atoi (com_argv[i+1]) * 1024;

		if ((parms.memsize > MAX_MEM_ALLOC) && !(COM_CheckParm ("-forcemem")))
		{
			Sys_Printf ("Requested memory (%d Mb) too large, using the default maximum.\n", parms.memsize/(1024*1024));
			Sys_Printf ("If you are sure, use the -forcemem switch.\n");
			parms.memsize = MAX_MEM_ALLOC;
		}
		else if ((parms.memsize < MIN_MEM_ALLOC) && !(COM_CheckParm ("-forcemem")))
		{
			Sys_Printf ("Requested memory (%d Mb) too little, using the default minimum.\n", parms.memsize/(1024*1024));
			Sys_Printf ("If you are sure, use the -forcemem switch.\n");
			parms.memsize = MIN_MEM_ALLOC;
		}
	}

	parms.membase = malloc (parms.memsize);

	if (!parms.membase)
		Sys_Error ("Insufficient memory.\n");

	Sys_Init ();

	Host_Init();

	oldtime = Sys_DoubleTime ();

	/* main window message loop */
	while (1)
	{
	    if (isDedicated)
	    {
		newtime = Sys_DoubleTime ();
		time = newtime - oldtime;

		while (time < sys_ticrate.value )
		{
			usleep (1000);
			newtime = Sys_DoubleTime ();
			time = newtime - oldtime;
		}

		Host_Frame (time);
		oldtime = newtime;
	    }
	    else
	    {
#if defined(SDLQUAKE)
		appState = SDL_GetAppState();
		/* If we have no input focus at all, sleep a bit */
		if ( !(appState & (SDL_APPMOUSEFOCUS | SDL_APPINPUTFOCUS)) || cl.paused)
		{
			usleep (16000);
		}
		/* If we're minimised, sleep a bit more */
		if ( !(appState & SDL_APPACTIVE))
		{
			scr_skipupdate = 1;
			usleep (32000);
		}
		else
		{
			scr_skipupdate = 0;
		}
#endif	/* SDLQUAKE */
		newtime = Sys_DoubleTime ();
		time = newtime - oldtime;

		Host_Frame (time);

		if (time < sys_throttle.value)
			usleep (1000);

		oldtime = newtime;
	    }
	}

	return 0;
}