summaryrefslogtreecommitdiff
path: root/source/sys_win.c
blob: 06d6ebdc802311d297ff4a18ce422c5e6d48e793 (plain)
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
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
/*
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.

*/

#include "win_local.h"
#include "q_field.h"
#include "q_list.h"
#include "prompt.h"
#include <mmsystem.h>
#ifdef DEDICATED_ONLY
#include <winsvc.h>
#endif
#ifdef USE_DBGHELP
#include <dbghelp.h>
#endif
#include <float.h>

sysAPI_t	sys;

#define MAX_CONSOLE_INPUT_EVENTS	16

static HANDLE		hinput = INVALID_HANDLE_VALUE;
static HANDLE		houtput = INVALID_HANDLE_VALUE;

static cvar_t		    *sys_viewlog;
static commandPrompt_t	sys_con;
static int				sys_hidden;
static CONSOLE_SCREEN_BUFFER_INFO	sbinfo;
static qboolean			gotConsole;
static volatile qboolean	errorEntered;
static volatile qboolean	shouldExit;

#ifdef DEDICATED_ONLY
static SERVICE_STATUS_HANDLE	statusHandle;
#endif

HINSTANCE	hGlobalInstance;

qboolean iswinnt;

cvar_t	*sys_basedir;
cvar_t  *sys_libdir;
cvar_t  *sys_refdir;
cvar_t  *sys_homedir;

static char		currentDirectory[MAX_OSPATH];

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

SYSTEM IO

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

void Sys_DebugBreak( void ) {
	DebugBreak();
}

/*
================
Sys_Printf
================
*/
void Sys_Printf( const char *fmt, ... ) {
	va_list		argptr;
	char		msg[MAXPRINTMSG];

	va_start( argptr, fmt );
	Q_vsnprintf( msg, sizeof( msg ), fmt, argptr );
	va_end( argptr );

    Sys_ConsoleOutput( msg );
}

/*
================
Sys_Error
================
*/
void Sys_Error( const char *error, ... ) {
	va_list		argptr;
	char		text[MAXPRINTMSG];

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

	errorEntered = qtrue;

	Sys_Printf( S_COLOR_RED "********************\n"
                            "FATAL: %s\n"
                            "********************\n", text );
#ifdef DEDICATED_ONLY
	if( !statusHandle )
#endif
	{
		if( gotConsole ) {
			Sleep( INFINITE );
		}
		MessageBoxA( NULL, text, APPLICATION " Fatal Error", MB_ICONERROR | MB_OK );
	}

	exit( 1 );
}

/*
================
Sys_Quit
================
*/
void Sys_Quit( void ) {
	timeEndPeriod( 1 );

#ifndef DEDICATED_ONLY
	if( dedicated && dedicated->integer ) {
		FreeConsole();
    }
#else
	if( !statusHandle )
#endif
		exit( 0 );
}

static void Sys_HideInput( void ) {
	DWORD		dummy;
	int i;

	if( !sys_hidden ) {
		for( i = 0; i <= sys_con.inputLine.cursorPos; i++ ) {
			WriteFile( houtput, "\b \b", 3, &dummy, NULL );	
		}
	}
	sys_hidden++;
}

static void Sys_ShowInput( void ) {
	DWORD		dummy;
	int i;

	if( !sys_hidden ) {
		Com_EPrintf( "Sys_ShowInput: not hidden\n" );
		return;
	}

	sys_hidden--;
	if( !sys_hidden ) {
		WriteFile( houtput, "]", 1, &dummy, NULL );	
		for( i = 0; i < sys_con.inputLine.cursorPos; i++ ) {
			WriteFile( houtput, &sys_con.inputLine.text[i], 1, &dummy, NULL );	
		}
	}
}

/*
================
Sys_ConsoleInput
================
*/
void Sys_RunConsole( void ) {
	INPUT_RECORD	recs[MAX_CONSOLE_INPUT_EVENTS];
	DWORD		dummy;
	int		ch;
	DWORD numread, numevents;
	int i;
	inputField_t *f;
	char *s;

	if( hinput == INVALID_HANDLE_VALUE ) {
		return;
	}

	if( !gotConsole ) {
		return;
	}

	f = &sys_con.inputLine;
	while( 1 ) {
		if( !GetNumberOfConsoleInputEvents( hinput, &numevents ) ) {
			Com_EPrintf( "Error %lu getting number of console events.\n"
				"Console IO disabled.\n", GetLastError() );
			gotConsole = qfalse;
			return;
		}

		if( numevents <= 0 )
			break;
		if( numevents > MAX_CONSOLE_INPUT_EVENTS ) {
		    numevents = MAX_CONSOLE_INPUT_EVENTS;
		}

		if( !ReadConsoleInput( hinput, recs, numevents, &numread ) ) {
			Com_EPrintf( "Error %lu reading console input.\n"
				"Console IO disabled.\n", GetLastError() );
			gotConsole = qfalse;
			return;
		}
			
		for( i = 0; i < numread; i++ ) {
			if( recs[i].EventType == WINDOW_BUFFER_SIZE_EVENT ) {
				sys_con.widthInChars = recs[i].Event.WindowBufferSizeEvent.dwSize.X;
				continue;
			}
			if( recs[i].EventType != KEY_EVENT ) {
				continue;
			}
	
			if( !recs[i].Event.KeyEvent.bKeyDown ) {
				continue;
			}

			switch( recs[i].Event.KeyEvent.wVirtualKeyCode ) {
			case VK_UP:
				Sys_HideInput();
				Prompt_HistoryUp( &sys_con );
				Sys_ShowInput();
				break;
			case VK_DOWN:
				Sys_HideInput();
				Prompt_HistoryDown( &sys_con );
				Sys_ShowInput();
				break;
			case VK_RETURN:
				Sys_HideInput();
				s = Prompt_Action( &sys_con );
				if( s ) {
					if( *s == '\\' || *s == '/' ) {
						s++;
					}
					Sys_Printf( "]%s\n", s );
                    Cbuf_AddText( s );
                    Cbuf_AddText( "\n" );
				} else {
					WriteFile( houtput, "\n", 2, &dummy, NULL );	
				}
				Sys_ShowInput();
				break;
			case VK_BACK:
				if( f->cursorPos ) {
					f->cursorPos--;
					f->text[f->cursorPos] = 0;
					WriteFile( houtput, "\b \b", 3, &dummy, NULL );	
				}
				break;
			case VK_TAB:
				Sys_HideInput();
				Prompt_CompleteCommand( &sys_con, qfalse );
				f->cursorPos = ( int )strlen( f->text );
				Sys_ShowInput();
				break;
			default:
				ch = recs[i].Event.KeyEvent.uChar.AsciiChar;
				if( ch < 32 ) {
					break;
				}
				if( f->cursorPos < sizeof( f->text ) - 1 ) {
					WriteFile( houtput, &ch, 1, &dummy, NULL );
					f->text[f->cursorPos] = ch;
					f->text[f->cursorPos+1] = 0;
					f->cursorPos++;
				}
				break;
			}
		}
	}	
}

#define FOREGROUND_BLACK	0
#define FOREGROUND_WHITE	(FOREGROUND_BLUE|FOREGROUND_GREEN|FOREGROUND_RED)

static WORD textColors[8] = {
	FOREGROUND_BLACK,
	FOREGROUND_RED,
	FOREGROUND_GREEN,
	FOREGROUND_RED|FOREGROUND_GREEN,
	FOREGROUND_BLUE,
	FOREGROUND_BLUE|FOREGROUND_GREEN,
	FOREGROUND_RED|FOREGROUND_BLUE,
	FOREGROUND_WHITE
};

/*
================
Sys_ConsoleOutput

Print text to the dedicated console
================
*/
void Sys_ConsoleOutput( const char *string ) {
	DWORD		dummy;
	char	text[MAXPRINTMSG];
	char *maxp, *p;
	int length;	
	WORD attr, w;
	int c;

	if( houtput == INVALID_HANDLE_VALUE ) {
		return;
	}

	if( !gotConsole ) {
		p = text;
		maxp = text + sizeof( text ) - 1;
		while( *string ) {
			if( Q_IsColorString( string ) ) {
				string += 2;
				continue;
			}
			*p++ = *string++ & 127;
			if( p == maxp ) {
				break;
			}
		}

		*p = 0;

		length = p - text;
		WriteFile( houtput, text, length, &dummy, NULL );
		return;
	}

	Sys_HideInput();

	attr = sbinfo.wAttributes & ~FOREGROUND_WHITE;
	
	while( *string ) {
		if( Q_IsColorString( string ) ) {
			c = string[1];
			string += 2;
			if( c == COLOR_ALT ) {
				w = attr | FOREGROUND_GREEN;
			} else if( c == COLOR_RESET ) {
				w = sbinfo.wAttributes;
			} else {
				w = attr | textColors[ ColorIndex( c ) ];
			}
			SetConsoleTextAttribute( houtput, w );
			continue;
		}

		p = text;
		maxp = text + sizeof( text ) - 1;
		do {
			*p++ = *string++ & 127;
			if( p == maxp ) {
				break;
			}
		} while( *string && !Q_IsColorString( string ) );

		*p = 0;

		length = p - text;
		WriteFile( houtput, text, length, &dummy, NULL );
	}

	SetConsoleTextAttribute( houtput, sbinfo.wAttributes );

	Sys_ShowInput();
}

void Sys_SetConsoleTitle( const char *title ) {
	if( gotConsole ) {
        SetConsoleTitle( title );
    }
}

static BOOL WINAPI Sys_ConsoleCtrlHandler( DWORD dwCtrlType ) {
	if( errorEntered ) {
		exit( 1 );
	}
	/* 32 bit writes are guranteed to be atomic */
	shouldExit = qtrue;
	return TRUE;
}

static void Sys_ConsoleInit( void ) {
	DWORD mode;

#ifdef DEDICATED_ONLY
	if( statusHandle ) {
		return;
	}
#else
	if( !AllocConsole() ) {
		Com_EPrintf( "Couldn't create system console.\n"
			"Console IO disabled.\n" );
		return;
	}
#endif

	hinput = GetStdHandle( STD_INPUT_HANDLE );
	houtput = GetStdHandle( STD_OUTPUT_HANDLE );
	if( !GetConsoleScreenBufferInfo( houtput, &sbinfo ) ) {
		Com_EPrintf( "Couldn't get console buffer info.\n"
			"Console IO disabled.\n" );
		return;
	}

	SetConsoleTitle( APPLICATION " console" );
	SetConsoleCtrlHandler( Sys_ConsoleCtrlHandler, TRUE );
	GetConsoleMode( hinput, &mode );
	mode |= ENABLE_WINDOW_INPUT;
	SetConsoleMode( hinput, mode );
	sys_con.widthInChars = sbinfo.dwSize.X;
	sys_con.printf = Sys_Printf;
	gotConsole = qtrue;

	Com_DPrintf( "System console initialized (%d cols, %d rows).\n",
		sbinfo.dwSize.X, sbinfo.dwSize.Y );
}

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

SERVICE CONTROL

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

#ifdef DEDICATED_ONLY

static void Sys_InstallService_f( void ) {
	char servicePath[256];
	char serviceName[1024];
	SC_HANDLE scm, service;
	DWORD error, length;
	char *commandline;

	if( Cmd_Argc() < 3 ) {
		Com_Printf( "Usage: %s <servicename> <+command> [...]\n"
			"Example: %s test +set net_port 27910 +map q2dm1\n",
				Cmd_Argv( 0 ), Cmd_Argv( 0 ) );
		return;
	}

	scm = OpenSCManager( NULL, SERVICES_ACTIVE_DATABASE, SC_MANAGER_ALL_ACCESS );
	if( !scm ) {
		error = GetLastError();
		if( error == ERROR_ACCESS_DENIED ) {
			Com_Printf( "Insufficient privileges for opening Service Control Manager.\n" );
		} else {
			Com_EPrintf( "%#lx opening Service Control Manager.\n", error );
		}
		return;
	}

	Q_concat( serviceName, sizeof( serviceName ), "Q2PRO - ", Cmd_Argv( 1 ), NULL );

	length = GetModuleFileName( NULL, servicePath, MAX_PATH );
	if( !length ) {
		error = GetLastError();
		Com_EPrintf( "%#lx getting module file name.\n", error );
		goto fail;
	}
	commandline = Cmd_RawArgsFrom( 2 );
	if( length + strlen( commandline ) + 10 > sizeof( servicePath ) - 1 ) {
		Com_Printf( "Oversize service command line.\n" );
		goto fail;
	}
	strcpy( servicePath + length, " -service " );
	strcpy( servicePath + length + 10, commandline );

	service = CreateService(
			scm,
			serviceName,
			serviceName,
			SERVICE_START,
			SERVICE_WIN32_OWN_PROCESS,
			SERVICE_AUTO_START,
			SERVICE_ERROR_IGNORE,
			servicePath,
			NULL,
			NULL,
			NULL,
			NULL,
			NULL );

	if( !service ) {
		error = GetLastError();
		if( error == ERROR_SERVICE_EXISTS || error == ERROR_DUPLICATE_SERVICE_NAME ) {
			Com_Printf( "Service already exists.\n" );
		} else {
			Com_EPrintf( "%#lx creating service.\n", error );
		}
		goto fail;
	}

	Com_Printf( "Service created successfully.\n" );

	CloseServiceHandle( service );

fail:
	CloseServiceHandle( scm );
}

static void Sys_DeleteService_f( void ) {
	char serviceName[256];
	SC_HANDLE scm, service;
	DWORD error;

	if( Cmd_Argc() < 2 ) {
		Com_Printf( "Usage: %s <servicename>\n", Cmd_Argv( 0 ) );
		return;
	}

	scm = OpenSCManager( NULL, SERVICES_ACTIVE_DATABASE, SC_MANAGER_ALL_ACCESS );
	if( !scm ) {
		error = GetLastError();
		if( error == ERROR_ACCESS_DENIED ) {
			Com_Printf( "Insufficient privileges for opening Service Control Manager.\n" );
		} else {
			Com_EPrintf( "%#lx opening Service Control Manager.\n", error );
		}
		return;
	}

	Q_concat( serviceName, sizeof( serviceName ), "Q2PRO - ", Cmd_Argv( 1 ), NULL );

	service = OpenService(
			scm,
			serviceName,
			DELETE );

	if( !service ) {
		error = GetLastError();
		if( error == ERROR_SERVICE_DOES_NOT_EXIST ) {
			Com_Printf( "Service doesn't exist.\n" );
		} else {
			Com_EPrintf( "%#lx opening service.\n", error );
		}
		goto fail;
	}

	if( !DeleteService( service ) ) {
		error = GetLastError();
		if( error == ERROR_SERVICE_MARKED_FOR_DELETE ) {
			Com_Printf( "Service has already been marked for deletion.\n" );
		} else {
			Com_EPrintf( "%#lx deleting service.\n", error );
		}
	} else {
		Com_Printf( "Service deleted successfully.\n" );
	}

	CloseServiceHandle( service );

fail:
	CloseServiceHandle( scm );
}

#endif

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

HUNK

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

void Hunk_Begin( mempool_t *pool, size_t maxsize ) {
	// reserve a huge chunk of memory, but don't commit any yet
	pool->cursize = 0;
	pool->maxsize = ( maxsize + 4095 ) & ~4095;
	pool->base = VirtualAlloc( NULL, pool->maxsize, MEM_RESERVE, PAGE_NOACCESS );
	if( !pool->base ) {
		Com_Error( ERR_FATAL,
            "VirtualAlloc reserve %"PRIz" bytes failed. GetLastError() = %lu",
			pool->maxsize, GetLastError() );
	}
}

void *Hunk_Alloc( mempool_t *pool, size_t size ) {
	void	*buf;

	// round to cacheline
	size = ( size + 31 ) & ~ 31;

	pool->cursize += size;
	if( pool->cursize > pool->maxsize )
		Com_Error( ERR_FATAL, "%s: couldn't allocate %"PRIz" bytes", __func__, size );

	// commit pages as needed
	buf = VirtualAlloc( pool->base, pool->cursize, MEM_COMMIT, PAGE_READWRITE );
	if( !buf ) {
		Com_Error( ERR_FATAL,
            "VirtualAlloc commit %"PRIz" bytes failed. GetLastError() = %lu",
			pool->cursize, GetLastError() );
	}

	return ( byte * )pool->base + pool->cursize - size;
}

void Hunk_End( mempool_t *pool ) {
}

void Hunk_Free( mempool_t *pool ) {
	if( pool->base ) {
		if( !VirtualFree( pool->base, 0, MEM_RELEASE ) ) {
			Com_Error( ERR_FATAL, "VirtualFree failed. GetLastError() = %lu",
				GetLastError() );
		}
	}

	memset( pool, 0, sizeof( *pool ) );
}

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

MISC

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

static inline time_t Sys_FileTimeToUnixTime( FILETIME *f ) {
	ULARGE_INTEGER u = *( ULARGE_INTEGER * )f;
	return ( time_t )( ( u.QuadPart - 116444736000000000U ) / 10000000 );
}

unsigned Sys_Milliseconds( void ) {
	return timeGetTime();
}

/*
================
Sys_Mkdir
================
*/
qboolean Sys_Mkdir( const char *path ) {
	if( !CreateDirectoryA( path, NULL ) ) {
        return qfalse;
    }
    return qtrue;
}

qboolean Sys_RemoveFile( const char *path ) {
	if( !DeleteFileA( path ) ) {
		return qfalse;
	}
	return qtrue;
}

qboolean Sys_RenameFile( const char *from, const char *to ) {
	if( !MoveFileA( from, to ) ) {
		return qfalse;
	}
	return qtrue;
}

void Sys_AddDefaultConfig( void ) {
}

/*
================
Sys_GetPathInfo
================
*/
qboolean Sys_GetPathInfo( const char *path, fsFileInfo_t *info ) {
	WIN32_FILE_ATTRIBUTE_DATA	data;

	if( !GetFileAttributesExA( path, GetFileExInfoStandard, &data ) ) {
		return qfalse;
	}

	if( info ) {
		info->size = data.nFileSizeLow;
		info->ctime = Sys_FileTimeToUnixTime( &data.ftCreationTime );
		info->mtime = Sys_FileTimeToUnixTime( &data.ftLastWriteTime );
	}

	return qtrue;
}

qboolean Sys_GetFileInfo( FILE *fp, fsFileInfo_t *info ) {
    int pos;

    pos = ftell( fp );
    fseek( fp, 0, SEEK_END );
    info->size = ftell( fp );
    info->ctime = 0;
    info->mtime = 0;
    fseek( fp, pos, SEEK_SET );

    return qtrue;
}

/*
================
Sys_GetClipboardData

================
*/
char *Sys_GetClipboardData( void ) {
	HANDLE clipdata;
	char *data = NULL;
	char *cliptext;

	if( OpenClipboard( NULL ) == FALSE ) {
		Com_DPrintf( "Couldn't open clipboard.\n" );
		return data;
	}

	if( ( clipdata = GetClipboardData( CF_TEXT ) ) != NULL ) {
		if( ( cliptext = GlobalLock( clipdata ) ) != NULL ) {
			data = Z_CopyString( cliptext );
			GlobalUnlock( clipdata );
		}
	}
	CloseClipboard();
	
	return data;
}

/*
================
Sys_SetClipboardData

================
*/
void Sys_SetClipboardData( const char *data ) {
	HANDLE clipdata;
	char *cliptext;
	size_t length;

	if( !data[0] ) {
		return;
	}

	if( OpenClipboard( NULL ) == FALSE ) {
		Com_DPrintf( "Couldn't open clipboard.\n" );
		return;
	}

	EmptyClipboard();

	length = strlen( data ) + 1;
	if( ( clipdata = GlobalAlloc( GMEM_MOVEABLE | GMEM_DDESHARE, length ) ) != NULL ) {
		if( ( cliptext = GlobalLock( clipdata ) ) != NULL ) {
			memcpy( cliptext, data, length );
			GlobalUnlock( clipdata );
			SetClipboardData( CF_TEXT, clipdata );
		}
	}
	
	CloseClipboard();
}


/*
================
Sys_FillAPI
================
*/
void Sys_FillAPI( sysAPI_t *api ) {
	api->Milliseconds = Sys_Milliseconds;
	api->GetClipboardData = Sys_GetClipboardData;
	api->SetClipboardData = Sys_SetClipboardData;
	api->HunkBegin = Hunk_Begin;
	api->HunkAlloc = Hunk_Alloc;
    api->HunkEnd = Hunk_End;
	api->HunkFree = Hunk_Free;
}

void Sys_FixFPCW( void ) {
    _controlfp( _PC_24|_RC_NEAR, _MCW_PC|_MCW_RC );
}

void Sys_Sleep( int msec ) {
    Sleep( msec );
}

void Sys_Setenv( const char *name, const char *value ) {
#if( _MSC_VER >= 1400 )
	_putenv_s( name, value );
#else
	_putenv( va( "%s=%s", name, value ) );
#endif
}


/*
================
Sys_Init
================
*/
void Sys_Init( void ) {
	OSVERSIONINFO	vinfo;

	timeBeginPeriod( 1 );

	vinfo.dwOSVersionInfoSize = sizeof( vinfo );

	if( !GetVersionEx( &vinfo ) ) {
		Sys_Error( "Couldn't get OS info" );
	}

	iswinnt = qtrue;
	if( vinfo.dwMajorVersion < 4 ) {
		Sys_Error( APPLICATION " requires windows version 4 or greater" );
	}
	if( vinfo.dwPlatformId == VER_PLATFORM_WIN32s ) {
		Sys_Error( APPLICATION " doesn't run on Win32s" );
	} else if( vinfo.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS ) {
		if( vinfo.dwMinorVersion == 0 ) {
			Sys_Error( APPLICATION " doesn't run on Win95" );
		}
		iswinnt = qfalse;
	}

	// basedir <path>
	// allows the game to run from outside the data tree
	sys_basedir = Cvar_Get( "basedir", currentDirectory, CVAR_NOSET );
    
	// homedir <path>
	// specifies per-user writable directory for demos, screenshots, etc
	sys_homedir = Cvar_Get( "homedir", "", CVAR_NOSET );

	sys_libdir = Cvar_Get( "libdir", currentDirectory, CVAR_NOSET );
	sys_refdir = Cvar_Get( "refdir", va( "%s\\baseq2pro", currentDirectory ), CVAR_NOSET );

	sys_viewlog = Cvar_Get( "sys_viewlog", "0", CVAR_NOSET );

#ifdef DEDICATED_ONLY
	Cmd_AddCommand( "installservice", Sys_InstallService_f );
	Cmd_AddCommand( "deleteservice", Sys_DeleteService_f );
#endif

	houtput = GetStdHandle( STD_OUTPUT_HANDLE );
	if( dedicated->integer || sys_viewlog->integer ) {
		Sys_ConsoleInit();
	}

	Sys_FillAPI( &sys );
}

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

DLL LOADING

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

void Sys_FreeLibrary( void *handle ) {
    if( !handle ) {
        return;
    }
    if( !FreeLibrary( handle ) ) {
        Com_Error( ERR_FATAL, "FreeLibrary failed on %p", handle );
    }
}

void *Sys_LoadLibrary( const char *path, const char *sym, void **handle ) {
    HMODULE module;
    void    *entry;

    *handle = NULL;

    module = LoadLibraryA( path );
	if( !module ) {
	    Com_DPrintf( "%s failed: LoadLibrary returned %lu on %s\n",
            __func__, GetLastError(), path );
		return NULL;
	}

	entry = GetProcAddress( module, sym );
	if( !entry ) {
		Com_DPrintf( "%s failed: GetProcAddress returned %lu on %s\n",
            __func__, GetLastError(), path );
		FreeLibrary( module );
		return NULL;
	}

    *handle = module;

	Com_DPrintf( "%s succeeded: %s\n", __func__, path );

	return entry;
}

void *Sys_GetProcAddress( void *handle, const char *sym ) {
	return GetProcAddress( handle, sym );
}
//=======================================================================

/*
=================
Sys_ListFilteredFiles
=================
*/
static void Sys_ListFilteredFiles(  void        **listedFiles,
                                    int         *count,
                                    const char  *path,
								    const char  *filter,
                                    int         flags,
                                    size_t      length )
{
	WIN32_FIND_DATAA	findInfo;
	HANDLE		findHandle;
	char	findPath[MAX_OSPATH];
	char	dirPath[MAX_OSPATH];
	char	*name;

	if( *count >= MAX_LISTED_FILES ) {
		return;
	}

	Q_concat( findPath, sizeof( findPath ), path, "\\*", NULL );

	findHandle = FindFirstFileA( findPath, &findInfo );
	if( findHandle == INVALID_HANDLE_VALUE ) {
		return;
	}

	do {
		if( !strcmp( findInfo.cFileName, "." ) || !strcmp( findInfo.cFileName, ".." ) ) {
			continue;
		}

		if( findInfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) {
			Q_concat( dirPath, sizeof( dirPath ), path, "\\", findInfo.cFileName, NULL );
			Sys_ListFilteredFiles( listedFiles, count, dirPath, filter, flags, length );
		}

		if( ( flags & FS_SEARCHDIRS_MASK ) == FS_SEARCHDIRS_ONLY ) {
			if( !( findInfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) ) {
				continue;
			}
		} else if( ( flags & FS_SEARCHDIRS_MASK ) == FS_SEARCHDIRS_NO ) {
			if( findInfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) {
				continue;
			}
		}

		Q_concat( dirPath, sizeof( dirPath ), path, "\\", findInfo.cFileName, NULL );
		if( !FS_WildCmp( filter, dirPath + length ) ) {
			continue;
		}

		name = ( flags & FS_SEARCH_SAVEPATH ) ? dirPath + length : findInfo.cFileName;

        // reformat it back to quake filesystem style
        FS_ReplaceSeparators( name, '/' );

		if( flags & FS_SEARCH_EXTRAINFO ) {
			time_t ctime = Sys_FileTimeToUnixTime( &findInfo.ftCreationTime );
			time_t mtime = Sys_FileTimeToUnixTime( &findInfo.ftLastWriteTime );
			listedFiles[( *count )++] = FS_CopyInfo( name, findInfo.nFileSizeLow, ctime, mtime );
		} else {
			listedFiles[( *count )++] = FS_CopyString( name );
		}

	} while( *count < MAX_LISTED_FILES && FindNextFileA( findHandle, &findInfo ) != FALSE );

	FindClose( findHandle );
}

/*
=================
Sys_ListFiles
=================
*/
void **Sys_ListFiles(   const char  *rawPath,
                        const char  *extension,
                        int         flags,
                        size_t      length,
                        int         *numFiles )
{
	WIN32_FIND_DATAA	findInfo;
	HANDLE		findHandle;
	char	path[MAX_OSPATH];
	char	findPath[MAX_OSPATH];
	void	*listedFiles[MAX_LISTED_FILES];
	int		count;
	char	*name;

	count = 0;

	if( numFiles ) {
		*numFiles = 0;
	}

	Q_strncpyz( path, rawPath, sizeof( path ) );
	FS_ReplaceSeparators( path, '\\' );

	if( flags & FS_SEARCH_BYFILTER ) {
		Q_strncpyz( findPath, extension, sizeof( findPath ) );
		FS_ReplaceSeparators( findPath, '\\' );
		Sys_ListFilteredFiles( listedFiles, &count, path, findPath, flags, length );
	} else {
		if( !extension || strchr( extension, ';' ) ) {
			Q_concat( findPath, sizeof( findPath ), path, "\\*", NULL );
		} else {
			if( *extension == '.' ) {
				extension++;
			}
			Q_concat( findPath, sizeof( findPath ), path, "\\*.", extension, NULL );
			extension = NULL; // do not check later
		}
		
		findHandle = FindFirstFileA( findPath, &findInfo );
		if( findHandle == INVALID_HANDLE_VALUE ) {
			return NULL;
		}

		do {
			if( !strcmp( findInfo.cFileName, "." ) || !strcmp( findInfo.cFileName, ".." ) ) {
				continue;
			}

			if( ( flags & FS_SEARCHDIRS_MASK ) == FS_SEARCHDIRS_ONLY ) {
				if( !( findInfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) ) {
					continue;
				}
			} else if( ( flags & FS_SEARCHDIRS_MASK ) == FS_SEARCHDIRS_NO ) {
				if( findInfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ) {
					continue;
				}
			}

			if( extension && !FS_ExtCmp( extension, findInfo.cFileName ) ) {
    			continue;
			}

			name = ( flags & FS_SEARCH_SAVEPATH ) ? va( "%s\\%s", path, findInfo.cFileName ) : findInfo.cFileName;
            
        	// reformat it back to quake filesystem style
		    FS_ReplaceSeparators( name, '/' );

			if( flags & FS_SEARCH_EXTRAINFO ) {
				time_t ctime = Sys_FileTimeToUnixTime( &findInfo.ftCreationTime );
				time_t mtime = Sys_FileTimeToUnixTime( &findInfo.ftLastWriteTime );
				listedFiles[count++] = FS_CopyInfo( name, findInfo.nFileSizeLow, ctime, mtime );
			} else {
				listedFiles[count++] = FS_CopyString( name );
			}
		} while( count < MAX_LISTED_FILES && FindNextFileA( findHandle, &findInfo ) != FALSE );

		FindClose( findHandle );
	}

	if( !count ) {
		return NULL;
	}

	if( numFiles ) {
		*numFiles = count;
	}

	return FS_CopyList( listedFiles, count );
}

/*
=================
Sys_GetCurrentDirectory
=================
*/
char *Sys_GetCurrentDirectory( void ) {
	return currentDirectory;
}

//=======================================================================

#if !( defined DEDICATED_ONLY ) && ( USE_ANTICHEAT & 1 )

typedef PVOID (*FNINIT)( VOID );

PRIVATE PVOID anticheatApi;
PRIVATE FNINIT anticheatInit;
PRIVATE HMODULE anticheatHandle;

//
// r1ch.net anticheat support
//
qboolean Sys_GetAntiCheatAPI( void ) {
	qboolean updated = qfalse;

	//already loaded, just reinit
	if( anticheatInit ) {
		anticheatApi = anticheatInit();
		if( !anticheatApi ) {
	        Com_Printf( S_COLOR_RED "Anticheat failed to reinitialize!\n" );
            FreeLibrary( anticheatHandle );
            anticheatHandle = NULL;
            anticheatInit = NULL;
			return qfalse;
        }
		return qtrue;
	}

	//windows version check
	if( !iswinnt ) {
		Com_Printf( S_COLOR_YELLOW
			"Anticheat requires Windows 2000/XP/2003.\n" );
		return qfalse;
	}

reInit:
	anticheatHandle = LoadLibrary( "anticheat" );
	if( !anticheatHandle ) {
		Com_Printf( S_COLOR_RED "Anticheat failed to load.\n" );
		return qfalse;
    }

	//this should never fail unless the anticheat.dll is bad
    anticheatInit = ( FNINIT )GetProcAddress(
        anticheatHandle, "Initialize" );
    if( !anticheatInit ) {
        Com_Printf( S_COLOR_RED "Couldn't get API of anticheat.dll!\n"
                    "Please check you are using a valid "
                    "anticheat.dll from http://antiche.at/" );
        FreeLibrary( anticheatHandle );
        anticheatHandle = NULL;
        return qfalse;
    }

	anticheatApi = anticheatInit();
	if( anticheatApi ) {
        return qtrue; // succeeded
    }

    FreeLibrary( anticheatHandle );
    anticheatHandle = NULL;
    anticheatInit = NULL;
    if( !updated ) {
        updated = qtrue;
        goto reInit;
    }

	Com_Printf( S_COLOR_RED "Anticheat failed to initialize.\n" );

    return qfalse;
}

#endif /* USE_ANTICHEAT */

#if USE_DBGHELP

typedef DWORD (WINAPI *SETSYMOPTIONS)( DWORD );
typedef BOOL (WINAPI *SYMGETMODULEINFO64)( HANDLE, DWORD64, PIMAGEHLP_MODULE64 );
typedef BOOL (WINAPI *SYMINITIALIZE)( HANDLE, PSTR, BOOL );
typedef BOOL (WINAPI *SYMCLEANUP)( HANDLE );
typedef BOOL (WINAPI *ENUMERATELOADEDMODULES64)( HANDLE, PENUMLOADED_MODULES_CALLBACK64, PVOID );
typedef BOOL (WINAPI *STACKWALK64)( DWORD, HANDLE, HANDLE, LPSTACKFRAME64, PVOID,
	PREAD_PROCESS_MEMORY_ROUTINE64, PFUNCTION_TABLE_ACCESS_ROUTINE64, PGET_MODULE_BASE_ROUTINE64,
	PTRANSLATE_ADDRESS_ROUTINE64 );
typedef BOOL (WINAPI *SYMFROMADDR)( HANDLE, DWORD64, PDWORD64, PSYMBOL_INFO );
typedef PVOID (WINAPI *SYMFUNCTIONTABLEACCESS64)( HANDLE, DWORD64 );
typedef DWORD64 (WINAPI *SYMGETMODULEBASE64)( HANDLE, DWORD64 );

typedef HINSTANCE (WINAPI *SHELLEXECUTE)( HWND, LPCSTR, LPCSTR, LPCSTR, LPCSTR, INT );

PRIVATE SETSYMOPTIONS pSymSetOptions;
PRIVATE SYMGETMODULEINFO64 pSymGetModuleInfo64;
PRIVATE SYMINITIALIZE pSymInitialize;
PRIVATE SYMCLEANUP pSymCleanup;
PRIVATE ENUMERATELOADEDMODULES64 pEnumerateLoadedModules64;
PRIVATE STACKWALK64 pStackWalk64;
PRIVATE SYMFROMADDR pSymFromAddr;
PRIVATE SYMFUNCTIONTABLEACCESS64 pSymFunctionTableAccess64;
PRIVATE SYMGETMODULEBASE64 pSymGetModuleBase64;
PRIVATE SHELLEXECUTE pShellExecute;

PRIVATE HANDLE processHandle, threadHandle;

PRIVATE FILE *crashReport;

PRIVATE CHAR moduleName[MAX_PATH];

PRIVATE BOOL CALLBACK EnumModulesCallback(
	PTSTR ModuleName,
	DWORD64 ModuleBase,
	ULONG ModuleSize,
	PVOID UserContext )
{
	IMAGEHLP_MODULE64 moduleInfo;
	DWORD64 pc = ( DWORD64 )UserContext;
	BYTE buffer[4096];
	PBYTE data;
	UINT numBytes;
	VS_FIXEDFILEINFO *info;
	char version[64];
	char *symbols;

	strcpy( version, "unknown" );
	if( GetFileVersionInfo( ModuleName, 0, sizeof( buffer ), buffer ) ) {
		if( VerQueryValue( buffer, "\\", &data, &numBytes ) ) {
			info = ( VS_FIXEDFILEINFO * )data;
			sprintf( version, "%u.%u.%u.%u",
				HIWORD( info->dwFileVersionMS ),
				LOWORD( info->dwFileVersionMS ),
				HIWORD( info->dwFileVersionLS ),
				LOWORD( info->dwFileVersionLS ) );
		}
	}
	
	symbols = "failed";
	moduleInfo.SizeOfStruct = sizeof( moduleInfo );
	if( pSymGetModuleInfo64( processHandle, ModuleBase, &moduleInfo ) ) {
		ModuleName = moduleInfo.ModuleName;
		switch( moduleInfo.SymType ) {
			case SymCoff: symbols = "COFF"; break;
			case SymExport: symbols = "export"; break;
			case SymNone: symbols = "none"; break;
			case SymPdb: symbols = "PDB"; break;
			default: symbols = "unknown"; break;
		}
	}
	
	fprintf( crashReport, "%p %p %s (version %s, symbols %s) ",
		ModuleBase, ModuleBase + ModuleSize, ModuleName, version, symbols );
	if( pc >= ModuleBase && pc < ModuleBase + ModuleSize ) {
		strncpy( moduleName, ModuleName, sizeof( moduleName ) - 1 );
        moduleName[ sizeof( moduleName ) - 1 ] = 0;
		fprintf( crashReport, "*\n" );
	} else {
		fprintf( crashReport, "\n" );
	}

	return TRUE;
}

PRIVATE DWORD Sys_ExceptionHandler( DWORD exceptionCode, LPEXCEPTION_POINTERS exceptionInfo ) {
	STACKFRAME64 stackFrame;
	PCONTEXT context;
	SYMBOL_INFO *symbol;
	int count, ret, i, len;
	DWORD64 offset;
	BYTE buffer[sizeof( SYMBOL_INFO ) + 256 - 1];
	IMAGEHLP_MODULE64 moduleInfo;
	char path[MAX_PATH];
	char execdir[MAX_PATH];
	char *p;
	HMODULE helpModule, shellModule;
	SYSTEMTIME systemTime;
	static const char monthNames[12][4] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
		"Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
	OSVERSIONINFO	vinfo;

#ifndef DEDICATED_ONLY
	Win_Shutdown();
#endif

	ret = MessageBox( NULL, APPLICATION " has encountered an unhandled "
		"exception and needs to be terminated.\n"
		"Would you like to generate a crash report?",
		"Unhandled Exception",
		MB_ICONERROR | MB_YESNO
#ifdef DEDICATED_ONLY
		| MB_SERVICE_NOTIFICATION
#endif
		);
	if( ret == IDNO ) {
		return EXCEPTION_CONTINUE_SEARCH;
	}

	helpModule = LoadLibrary( "dbghelp.dll" );
	if( !helpModule ) {
		return EXCEPTION_CONTINUE_SEARCH;
	}

#define GPA( x, y )															\
	do {																	\
		p ## y = ( x )GetProcAddress( helpModule, #y );						\
		if( !p ## y ) {														\
			return EXCEPTION_CONTINUE_SEARCH;								\
		}																	\
	} while( 0 )

	GPA( SETSYMOPTIONS, SymSetOptions );
	GPA( SYMGETMODULEINFO64, SymGetModuleInfo64 );
	GPA( SYMCLEANUP, SymCleanup );
	GPA( SYMINITIALIZE, SymInitialize );
	GPA( ENUMERATELOADEDMODULES64, EnumerateLoadedModules64 );
	GPA( STACKWALK64, StackWalk64 );
	GPA( SYMFROMADDR, SymFromAddr );
	GPA( SYMFUNCTIONTABLEACCESS64, SymFunctionTableAccess64 );
	GPA( SYMGETMODULEBASE64, SymGetModuleBase64 );

	pSymSetOptions( SYMOPT_LOAD_ANYTHING|SYMOPT_DEBUG|SYMOPT_FAIL_CRITICAL_ERRORS );
	processHandle = GetCurrentProcess();
	threadHandle = GetCurrentThread();

	GetModuleFileName( NULL, execdir, sizeof( execdir ) - 1 );
	execdir[sizeof( execdir ) - 1] = 0;
	p = strrchr( execdir, '\\' );
	if( !p ) {
        return EXCEPTION_CONTINUE_SEARCH;
    }

    *p = 0;
    len = p - execdir;
    if( len + 24 >= MAX_PATH ) {
        return EXCEPTION_CONTINUE_SEARCH;
    }
	
    memcpy( path, execdir, len );
    memcpy( path + len, "\\Q2PRO_CrashReportXX.txt", 25 );
	for( i = 0; i < 100; i++ ) {
		path[len+18] = '0' + i / 10;
		path[len+19] = '0' + i % 10;
		if( !Sys_GetPathInfo( path, NULL ) ) {
			break;
		}
	}
	crashReport = fopen( path, "w" );
	if( !crashReport ) {
		return EXCEPTION_CONTINUE_SEARCH;
	}

	pSymInitialize( processHandle, execdir, TRUE );

	GetSystemTime( &systemTime );
	fprintf( crashReport, "Crash report generated %s %u %u, %02u:%02u:%02u UTC\n",
		monthNames[(systemTime.wMonth - 1) % 12], systemTime.wDay, systemTime.wYear,
		systemTime.wHour, systemTime.wMinute, systemTime.wSecond );
	fprintf( crashReport, "by " APPLICATION " " VERSION ", built " __DATE__", " __TIME__ "\n" );

	vinfo.dwOSVersionInfoSize = sizeof( vinfo );
	if( GetVersionEx( &vinfo ) ) {
		fprintf( crashReport, "\nWindows version: %u.%u (build %u) %s\n",
			vinfo.dwMajorVersion, vinfo.dwMinorVersion, vinfo.dwBuildNumber, vinfo.szCSDVersion );
	}

	strcpy( moduleName, "unknown" );

	context = exceptionInfo->ContextRecord;

	fprintf( crashReport, "\nLoaded modules:\n" );
	pEnumerateLoadedModules64( processHandle, EnumModulesCallback,
#ifdef _WIN64
		( PVOID )context->Rip
#else
		( PVOID )context->Eip
#endif
	);

	fprintf( crashReport, "\nException information:\n" );
	fprintf( crashReport, "Code: %08x\n", exceptionCode );
	fprintf( crashReport, "Address: %p (%s)\n",
#ifdef _WIN64
		context->Rip,
#else
		context->Eip,
#endif
		moduleName );

	fprintf( crashReport, "\nThread context:\n" );
#ifdef _WIN64
	fprintf( crashReport, "RIP: %p RBP: %p RSP: %p\n",
		context->Rip, context->Rbp, context->Rsp );
	fprintf( crashReport, "RAX: %p RBX: %p RCX: %p\n",
		context->Rax, context->Rbx, context->Rcx );
	fprintf( crashReport, "RDX: %p RSI: %p RDI: %p\n",
		context->Rdx, context->Rsi, context->Rdi );
#else
	fprintf( crashReport, "EIP: %p EBP: %p ESP: %p\n",
		context->Eip, context->Ebp, context->Esp );
	fprintf( crashReport, "EAX: %p EBX: %p ECX: %p\n",
		context->Eax, context->Ebx, context->Ecx );
	fprintf( crashReport, "EDX: %p ESI: %p EDI: %p\n",
		context->Edx, context->Esi, context->Edi );
#endif

	memset( &stackFrame, 0, sizeof( stackFrame ) );
#ifdef _WIN64
	stackFrame.AddrPC.Offset = context->Rip;
	stackFrame.AddrFrame.Offset = context->Rbp;
	stackFrame.AddrStack.Offset = context->Rsp;
#else
	stackFrame.AddrPC.Offset = context->Eip;
	stackFrame.AddrFrame.Offset = context->Ebp;
	stackFrame.AddrStack.Offset = context->Esp;
#endif
	stackFrame.AddrPC.Mode = AddrModeFlat;
	stackFrame.AddrFrame.Mode = AddrModeFlat;
	stackFrame.AddrStack.Mode = AddrModeFlat;	

	fprintf( crashReport, "\nStack trace:\n" );
	count = 0;
	symbol = ( SYMBOL_INFO * )buffer;
	symbol->SizeOfStruct = sizeof( SYMBOL_INFO );
	symbol->MaxNameLen = 256;
	while( pStackWalk64(
#ifdef _WIN64
		IMAGE_FILE_MACHINE_AMD64,
#else
		IMAGE_FILE_MACHINE_I386,
#endif
		processHandle,
		threadHandle,
		&stackFrame,
		context,
		NULL,
		pSymFunctionTableAccess64,
		pSymGetModuleBase64,
		NULL ) )
	{
		fprintf( crashReport, "%d: %p %p %p %p ",
			count,
			stackFrame.Params[0],
			stackFrame.Params[1],
			stackFrame.Params[2],
			stackFrame.Params[3] );

		moduleInfo.SizeOfStruct = sizeof( moduleInfo );
		if( pSymGetModuleInfo64( processHandle, stackFrame.AddrPC.Offset, &moduleInfo ) ) {
			if( moduleInfo.SymType != SymNone && moduleInfo.SymType != SymExport &&
				pSymFromAddr( processHandle, stackFrame.AddrPC.Offset, &offset, symbol ) )
			{
				fprintf( crashReport, "%s!%s+%#x\n", 
					moduleInfo.ModuleName,
					symbol->Name, offset );
			} else {
				fprintf( crashReport, "%s!%#x\n",
					moduleInfo.ModuleName,
					stackFrame.AddrPC.Offset );
			}
		} else {
			fprintf( crashReport, "%#x\n",
				stackFrame.AddrPC.Offset );
		}
		count++;
	}

	fclose( crashReport );

	shellModule = LoadLibrary( "shell32.dll" );
	if( shellModule ) {
		pShellExecute = ( SHELLEXECUTE )GetProcAddress( shellModule, "ShellExecuteA" );
		if( pShellExecute ) {
			pShellExecute( NULL, "open", path, NULL, execdir, SW_SHOW );
		}
	}

	pSymCleanup( processHandle );

	ExitProcess( 1 );
	return EXCEPTION_CONTINUE_SEARCH;
}

#if 0
EXCEPTION_DISPOSITION _ExceptionHandler(
	EXCEPTION_RECORD *ExceptionRecord,
	void *EstablisherFrame,
	CONTEXT *ContextRecord,
	void *DispatcherContext )
{
	return ExceptionContinueSearch;
}

#ifndef __GNUC__
#define __try1( handler )	__asm { \
	__asm push handler \
	__asm push fs:[0] \
	__asm mov fs:0, esp \
}
#define __except1	__asm { \
	__asm mov eax, [esp] \
	__asm mov fs:[0], eax \
	__asm add esp, 8 \
}
#endif
#endif

#endif /* USE_DBGHELP */

#if ( _MSC_VER >= 1400 )
static void msvcrt_sucks( const wchar_t *expr, const wchar_t *func, const wchar_t *file, unsigned int line, uintptr_t unused ) {
}
#endif

static int Sys_Main( int argc, char **argv ) {
#ifdef DEDICATED_ONLY
	if( !GetModuleFileName( NULL, currentDirectory, sizeof( currentDirectory ) - 1 ) ) {
		return 1;
	}
	currentDirectory[sizeof( currentDirectory ) - 1] = 0;
	{
		char *p = strrchr( currentDirectory, '\\' );
		if( p ) {
			*p = 0;
		}
		if( !SetCurrentDirectory( currentDirectory ) ) {
			return 1;
		}
	}
#else
	if( !GetCurrentDirectory( sizeof( currentDirectory ) - 1, currentDirectory ) ) {
		return 1;
	}
	currentDirectory[sizeof( currentDirectory ) - 1] = 0;
#endif

#if USE_DBGHELP
#ifdef _MSC_VER
	__try {
#else
	__try1( Sys_ExceptionHandler );
#endif
#endif /* USE_DBGHELP */

#if ( _MSC_VER >= 1400 )
	// no, please, don't let strftime kill the whole fucking
	// process just because it does not conform to C99 :((
	_set_invalid_parameter_handler( msvcrt_sucks );
#endif

	Qcommon_Init( argc, argv );

	// main program loop
	while( !shouldExit ) {
		Qcommon_Frame();
	}

	Com_Quit();

#if USE_DBGHELP
#ifdef _MSC_VER
	} __except( Sys_ExceptionHandler( GetExceptionCode(), GetExceptionInformation() ) ) {
		return 1;
	}
#else
	__except1;
#endif
#endif /* USE_DBGHELP */

	// may get here when our service stops
    return 0;
}



#ifdef DEDICATED_ONLY

static char	    **sys_argv;
static int		sys_argc;

static VOID WINAPI ServiceHandler( DWORD fdwControl ) {
	if( fdwControl == SERVICE_CONTROL_STOP ) {
		shouldExit = qtrue;
	}
}

static VOID WINAPI ServiceMain( DWORD argc, LPTSTR *argv ) {
	SERVICE_STATUS	status;

	statusHandle = RegisterServiceCtrlHandler( APPLICATION, ServiceHandler );
	if( !statusHandle ) {
		return;
	}

	memset( &status, 0, sizeof( status ) );
	status.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
	status.dwCurrentState = SERVICE_RUNNING;
	status.dwControlsAccepted = SERVICE_ACCEPT_STOP;
	SetServiceStatus( statusHandle, &status );

	Sys_Main( sys_argc, sys_argv );

	status.dwCurrentState = SERVICE_STOPPED;
	status.dwControlsAccepted = 0;
	SetServiceStatus( statusHandle, &status );
}

static SERVICE_TABLE_ENTRY serviceTable[] = {
	{ APPLICATION, ServiceMain },
	{ NULL, NULL }
};

/*
==================
main

==================
*/
int QDECL main( int argc, char **argv ) {
	int i;

	hGlobalInstance = GetModuleHandle( NULL );

	for( i = 1; i < argc; i++ ) {
		if( !strcmp( argv[i], "-service" ) ) {
			argv[i] = NULL;
			sys_argc = argc;
			sys_argv = argv;
			if( StartServiceCtrlDispatcher( serviceTable ) ) {
				return 0;
			}
			if( GetLastError() == ERROR_FAILED_SERVICE_CONTROLLER_CONNECT ) {
				break; // fall back to normal server startup
			}
			return 1;
		}
	}
	
	return Sys_Main( argc, argv );
}

#else // DEDICATED_ONLY

#define MAX_LINE_TOKENS	128

static char	    *sys_argv[MAX_LINE_TOKENS];
static int		sys_argc;

/*
===============
Sys_ParseCommandLine

===============
*/
static void Sys_ParseCommandLine( char *line ) {
	sys_argc = 1;
    sys_argv[0] = APPLICATION;
	while( *line ) {
		while( *line && *line <= 32 ) {
            line++;
        }
        if( *line == 0 ) {
            break;
        }
		sys_argv[sys_argc++] = line;
		while( *line > 32 ) {
            line++;
        }
        if( *line == 0 ) {
            break;
        }
		*line = 0;
		if( sys_argc == MAX_LINE_TOKENS ) {
			break;
		}
        line++;
	}
}

/*
==================
WinMain

==================
*/
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow ) {
	// previous instances do not exist in Win32
	if( hPrevInstance ) {
		return 1;
	}

	hGlobalInstance = hInstance;
	Sys_ParseCommandLine( lpCmdLine );
	return Sys_Main( sys_argc, sys_argv );
}

#endif // !DEDICATED_ONLY