aboutsummaryrefslogtreecommitdiff
path: root/src/parsec_server/con_main_sv.cpp
blob: 4de93318d102f2c589fc6af9e92562d42ac1d838 (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
/*
 * PARSEC - Server Console Main Module
 *
 * $Author: uberlinuxguy $ - $Date: 2004/09/26 03:43:47 $
 *
 * Orginally written by:
 *   Copyright (c) Clemens Beer        <cbx@parsec.org>   2001
 *   Copyright (c) Markus Hadwiger     <msh@parsec.org>   1996-2000
 *
 *  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
 */ 

// C library
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// compilation flags/debug support
#include "config.h"
#include "debug.h"

// general definitions
#include "general.h"
#include "gd_heads.h"
#include "objstruc.h"

// global externals
#include "globals.h"

// subsystem headers
#include "inp_defs_sv.h"
//#include "vid_defs.h"

// drawing subsystem
//#include "d_bmap.h"
//#include "d_font.h"

// local module header
#include "con_main_sv.h"

// proprietary module headers
#include "con_act_sv.h"
#include "con_arg.h"
#include "con_aux_sv.h"
#include "con_com_sv.h"
//#include "con_conf.h"
#include "con_ext_sv.h"
#include "con_info_sv.h"
#include "con_int_sv.h"
//#include "con_kmap.h"
#include "con_list_sv.h"
//#include "con_rc.h"
#include "con_std_sv.h"
#include "con_tab.h"
#include "con_vald.h"
//#include "e_color.h"
//#include "e_demo.h"
//#include "e_draw.h"
#include "net_limits.h"
#include "net_defs.h"
#include "e_gameserver.h"
//#include "g_supp.h"
//#include "h_cockpt.h"
//#include "h_strmap.h"
#include "inp_main_sv.h"
#include "keycodes.h"
//#include "m_main.h"
#include "sys_path.h"
#include "sys_swap.h"

// CURSES library -------------------------------------------------------------
#ifdef USE_CURSES
	#ifdef SYSTEM_WIN32_UNUSED
		#pragma comment( lib, "curses.lib" )
	#endif // SYSTEM_WIN32_UNUSED
#endif // USE_CURSES

// flags
#define PROCESS_STARTUP_SCRIPT				// execute startup (boot) script
#define FORCE_CONSOLE_LOGIN					// have to login to exec commands
#define LOSE_KEYBOARD_FOCUS_ON_SLIDEUP		// console loses focus on slide up
#define CONSOLE_OUTPUT_WORKAROUND


// echo commands in startup script
#define ECHO_STARTUP_SCRIPT			TRUE	// echo+history for startup script

// speed of console sliding
#define CONSOLE_SLIDE_SPEED 		3		// less is faster

// miscellaneous defines
#define CONSOLE_MIN_ENTER_LENGTH	4		// lower bound for entry area
#define CURSOR_BLINK_SPEED			0x100	// in reference frames
#define CONSOLE_CAPTION_HEIGHT		2		// caption plus one empty line
#define CONSOLE_MAX_BACK_LINES		128		// number of lines to scroll back


// macros can be disabled to prevent overriding of internal commands
static int disable_macros			= FALSE;

// flag whether script compilation in progress
PUBLIC int compile_script			= FALSE;

// filepointer for compilation output
PUBLIC FILE *compile_fp				= NULL;

// echo commands executed from file (script)
PUBLIC int EchoExternalCommands		= FALSE;

// enter script commands into history list
PUBLIC int HistoryForBatchEntry		= TRUE;

// startup script file names (normal boot/demo boot)
PUBLIC char boot_script_name[]		= "boot_sv" CON_FILE_EXTENSION;
PUBLIC char boot_script_master_name[]		= "boot_ms" CON_FILE_EXTENSION;
static char demo_script_name[]		= "demo_sv" CON_FILE_EXTENSION;

// various string constants
PUBLIC char con_prompt[]			= "::";
PUBLIC char ok_prompt[] 			= "ok.";
PUBLIC char press_space[]			= "- press space -";
PUBLIC char too_many_args[] 		= "too many arguments.";
PUBLIC char arg_missing[]			= "argument missing.";
PUBLIC char invalid_arg[]			= "invalid argument.";
PUBLIC char range_error[]			= "range error.";
PUBLIC char unknown_command[]		= "unknown command: \"%s\"";
PUBLIC char unknown_script[]		= "unknown command script.";
PUBLIC char cmd_not_compilable[]	= "command cannot be compiled.";
PUBLIC char line_separator[]		= "----------------------------------";
static char console_login_passwd[]	= "argument.";
static char recursive_compilation[]	= "recursive compilation... rather not.";
static char compile_open_failed[]	= "cannot open output file.";

PUBLIC int	press_space_curs_x		= strlen( press_space ) - PROMPT_SIZE;

static char console_caption[]		= "parsec command console";
static char console_ready[] 		= "console ready...";

static char auxflag_array_name[]	= ".aux";
static char auxdata_array_name[]	= ".auxd";

static char insert_cursor[]			= "_";	// will be a underline cursor
static char overwrite_cursor[]		= "^";	// will be a block cursor

static char console_lock_done[]		= "console is now locked.";
static char console_unlock_done[]	= "console is now unlocked.";
static char console_is_locked[]		= "console locked.";

// generic string paste area
#define PASTE_STR_LEN 255
static char paste_str[ PASTE_STR_LEN + 1 ];

#if ( PASTE_STR_LEN < MAX_CONSOLE_LINE_LENGTH )
	#error "CON_MAIN::paste_str too short!"
#endif

// console geometry
PRIVATE int console_frameofs_x = 4;
PRIVATE int console_frameofs_y = 0;
PRIVATE int console_frame_left = 8;
PRIVATE int console_frame_top  = 5;

// current console contents
PUBLIC char con_lines[ NUM_CONSOLE_LINES ][ MAX_CONSOLE_LINE_LENGTH + 1 ];

// temporary line from which actual drawing will be done
static char draw_line[ MAX_CONSOLE_LINE_LENGTH + 1 ];

// temporary line for current command (from console input line or file)
static char command_line[ MAX_CONSOLE_LINE_LENGTH + 1 ];

// history buffer (most recent commands history)
static char history_list[ NUM_HISTORY_LINES ][ MAX_CONSOLE_LINE_LENGTH + 1 ];

static int history_add	= 0;	// new entry will be placed here
static int history_scan = 0;	// current scroll position in list

static int insert_mode	= TRUE;	// default mode: insert

PUBLIC int con_back_view= 0;	// number of lines to view back in console

PUBLIC int con_content	= 1;	// valid lines in console buffer
PUBLIC int con_bottom	= 0;	// current line in console buffer (0..)

static int last_con_content;	// old state
static int last_con_bottom;		// (used in lists to overwrite space prompt)

static int cursor_state = CURSOR_BLINK_SPEED;
PUBLIC int cursor_x		= 0;	// current cursor position (0==behind prompt)

static int edit_ofs_x	= 0;	// x offset for viewing the edit line
static int edit_max_x	= MAX_CONSOLE_LINE_LENGTH - PROMPT_SIZE;

int  con_in_talk_mode	= FALSE;
int  con_talk_line		= 0;	// line just below separator in talk mode
char talk_escape_char	= '/';	// escape char for command input in talk mode

int con_non_interactive	= 0;	// CON_AddMessage() instead of CON_AddLine()

int con_logged_in		= 1;	// user logged in
int con_login_mode		= 0;	// login mode (must not display console input)
int con_no_login_check	= 0;	// used by keymapped commands

int ConsoleEnterLength	= 23;	// length of console line (excl. prompt+cursor)
int ConsoleTextX		= 3;	// x-pos of console in char-multiples
int ConsoleTextY		= 7;	// y-pos of console in char-multiples

// execute init only once
int console_init_done	= FALSE;

// scratchpad for path with current working directory prepended
static char curworkdir_path[ PATH_MAX + 1 ];


// CURSES library -------------------------------------------------------------
//
#ifdef USE_CURSES
	WINDOW* g_curses_in_win  = NULL;
	WINDOW* g_curses_out_win = NULL;
#endif // USE_CURSES


// completely erase (fill with zero-bytes) all console lines ------------------
//
void ClearConScreen()
{
	// clear all lines and make them valid
	memset( con_lines, 0, sizeof( con_lines ) );
	con_content = NUM_CONSOLE_LINES;

	// reset back-viewing
	con_back_view = 0;
}


// completely erase (fill with zero-bytes) an entire console line -------------
//
void EraseConLine( int line )
{
	ASSERT( ( line >= 0 ) && ( line < NUM_CONSOLE_LINES ) );
	memset( con_lines[ line ], 0, MAX_CONSOLE_LINE_LENGTH + 1 );
	wclear( g_curses_in_win );
	cursor_x = 0;
}


// fill current line with separator chars -------------------------------------
//
void CreateSeparatorLine( int line )
{
	ASSERT( ( line >= 0 ) && ( line < NUM_CONSOLE_LINES ) );
	memset( con_lines[ line ], '-', MAX_CONSOLE_LINE_LENGTH );
	con_lines[ line ][ MAX_CONSOLE_LINE_LENGTH ] = 0;
}


// return path with current workdir prepended if it starts with "./" ----------
//
char *SubstCurWorkDir( char *path )
{
	ASSERT( path != NULL );

	//NOTE:
	// a copy of the path is returned even if it
	// has not been altered to achieve the exact
	// same semantics as in case of modification.

	//NOTE:
	// this function recognizes ".:" as alternative specifier for
	// the workdir in order to allow MacOS path specifications in
	// console script paths.

	if ( ( strncmp( path, "./", 2 ) == 0 ) ||
		 ( strncmp( path, ".:", 2 ) == 0 ) ) {

		if ( AUX_FORCE_WORKDIR_TO_CURRENT ) {

			// just skip first two chars
			strncpy( curworkdir_path, path + 2, PATH_MAX );
			curworkdir_path[ PATH_MAX ] = 0;

		} else {

			// substitute current working directory for "."
			strcpy( curworkdir_path, CurWorkDir );
			int cwdlen = strlen( CurWorkDir );
			strncpy( curworkdir_path + cwdlen, path + 1, PATH_MAX - cwdlen );
			curworkdir_path[ PATH_MAX ] = 0;
		}

	} else {

		// just copy over unmodified path
		strncpy( curworkdir_path, path, PATH_MAX );
		curworkdir_path[ PATH_MAX ] = 0;
	}

	// convert path to system format
	path = SYSs_ProcessPathString( curworkdir_path );
	if ( path != curworkdir_path ) {
		strncpy( curworkdir_path, path, PATH_MAX );
		curworkdir_path[ PATH_MAX ] = 0;
	}

	// strip path if flag set
	char *substpath = curworkdir_path;
	if ( AUX_FORCE_FILEPATH_TO_CURRENT )
		substpath = SYSs_StripPath( curworkdir_path );

	return substpath;
}


// exec startup script (usually boot.con, but also boot scripts of mods) ------
//
void ExecStartupScript( int echo )
{
	// exec startup command script
	char *startupscript = NULL;

	// start normal or mod boot scripts
	if ( mod_numnames > 0 ) {

		ASSERT( mod_names[ 0 ] != NULL );

		// if mod doesn't override our own packages, execute our boot.con too
		if ( !mod_override ) {
			//startupscript = PlayDemo ? demo_script_name : boot_script_name;
			if(TheServer->GetServerIsMaster()){
				startupscript = boot_script_master_name;
			} else {
				startupscript = boot_script_name;
			}
			ExecConsoleFile( startupscript, echo );
		}

		// afterwards, exec <modname>/boot.con for each registered mod
		for ( int curmod = 0; curmod < mod_numnames; curmod++ ) {

			ASSERT( mod_names[ curmod ] != NULL );
			startupscript = (char *) ALLOCMEM(
				strlen( mod_names[ curmod ] ) + 1 + strlen( boot_script_name ) );
			if ( startupscript == NULL ) {
				OUTOFMEM( 0 );
			}
			strcpy( startupscript, mod_names[ curmod ] );
			strcat( startupscript, "/" );
			strcat( startupscript, boot_script_name );

			// must be done to ensure the file can be found independently of
			// whether it is read from a package or from a real directory
			char *path = SYSs_ProcessPathString( startupscript );

			ExecConsoleFile( path, echo );

			FREEMEM( startupscript );
			startupscript = NULL;
		}

	} else {

		// if no mod is active, we just exec boot.con
		//startupscript = PlayDemo ? demo_script_name : boot_script_name;
		if(TheServer->GetServerIsMaster()){
			startupscript = boot_script_master_name;
		} else {
			startupscript = boot_script_name;
		}
		ExecConsoleFile( startupscript, echo );
	}
}

// init CURSES windows --------------------------------------------------------
//
void CON_InitCurses()
{
#ifdef USE_CURSES

	initscr();
	cbreak();
	//echo();


	// create input window
	g_curses_in_win  = newwin( 1,  COLS, LINES - 1, 0 );
	//wattrset( g_curses_in_win, A_REVERSE );
	keypad( g_curses_in_win, TRUE );
	nodelay( g_curses_in_win, TRUE );
	
	// create output window ( -1 to ensure we do not overwrite the input window )
	g_curses_out_win = newwin( LINES - 1, COLS, 0, 0  );
	nodelay( g_curses_out_win, TRUE );

	// scrolling is ok
	scrollok( g_curses_in_win, TRUE );
	scrollok( g_curses_out_win, TRUE );

	//slk_init( 1 );
	/*slk_set(1, "Insert", 0);
	slk_set(2, "Quit", 0);
	slk_set(3, "Add", 0);
	slk_set(4, "Delete", 0);
	slk_set(5, "Undo", 0);
	slk_set(6, "Search", 0);
	slk_set(7, "Replace", 0);
	slk_set(8, "Save", 0);
	slk_refresh();
	*/


#endif // USE_CURSES
}


// kill all CURSES windows and related stuff ----------------------------------
//
void CON_KillCurses()
{
#ifdef USE_CURSES
	nocbreak();
	echo();
	endwin();
#endif // USE_CURSES
}


// init memory needed for console ---------------------------------------------
//
void CON_InitConsole()
{
	ASSERT( !console_init_done );

	if ( !console_init_done ) {
        int lid;
		// erase console contents
		for ( lid = 0; lid < NUM_CONSOLE_LINES; lid++ ) {
			memset( con_lines[ lid ], 0, MAX_CONSOLE_LINE_LENGTH + 1 );
		}

		// erase history buffer
		for ( lid = 0; lid < NUM_HISTORY_LINES; lid++ ) {
			history_list[ lid ][ 0 ] = '\0';
		}

		// insert startup message into top line
		strcpy( con_lines[ 0 ], console_ready );

		// make startup message valid
		con_content = 1;
		con_bottom  = 0;

		EraseConLine( con_bottom );
		strcpy( con_lines[ con_bottom ], con_prompt );

#ifdef PROCESS_STARTUP_SCRIPT

		// there's no reason to run the external scripts when we are only
		// running in master server mode.
		if(!TheServer->GetServerIsMaster()) {
			// build list of external commands
			BuildExternalCommandList();

			// exec boot.con (also for registered mods)
			ExecStartupScript( ECHO_STARTUP_SCRIPT );
		}
#endif // PROCESS_STARTUP_SCRIPT

		//CAVEAT:
		// this has to stay last, because CON_EXT::ExecConsoleFile()
		// uses it to determine whether it has been called from here.
		console_init_done = TRUE;
	}
}


// make sure no demo is playing when console is inited/reinited/killed --------
//
PRIVATE
void KillDemoReplay()
{
//FIXME: needed on server ?

/*	// make sure we call demo stop instead of full clear
	int oldclearflag = AUX_DISABLE_CLEARDEMO_ON_REPSTOP;
	AUX_DISABLE_CLEARDEMO_ON_REPSTOP = 1;

	// make sure no demo is playing
	//DEMO_StopReplay();

	// restore previous flag state
	AUX_DISABLE_CLEARDEMO_ON_REPSTOP = oldclearflag;
*/
}


// (re)init file pointers used by console -------------------------------------
//
void InitConsoleFileHandling()
{
	// make sure no demo is playing
	KillDemoReplay();

	if ( log_commands ) {
		fclose( log_fp );
		log_commands = 0;
	}

	if ( RecordingActive ) {
		fclose( RecordingFp );
		RecordingActive = 0;
		RemoteRecSessionId++;
	}
}


// kill resources used by console ---------------------------------------------
//
void CON_KillConsole()
{
	if ( console_init_done ) {
		console_init_done = FALSE;

		InitConsoleFileHandling();
	}
}


// flush keyboard buffer for console ------------------------------------------
//
void FlushConsoleBuffer()
{
	dword *pos;

	while ( *( pos = &KeybBuffer->Data + KeybBuffer->ReadPos ) ) {
		KeybBuffer->ReadPos = ( KeybBuffer->ReadPos + 1 ) % KEYB_BUFF_SIZ;
		*pos = 0;
	}
}


// add new message to console (preserve current input) ------------------------
//
PUBLIC
void CON_AddMessage( const char *text )
{
	ASSERT( text != NULL );

	// normal message output
	MSGOUT( text );
}


// flag whether next CON_AddLine() should overwrite the current line ----------
//
static int skip_next_nl = FALSE;


// add new line to console ----------------------------------------------------
//
PUBLIC
void CON_AddLine( const char *text )
{
	ASSERT( text != NULL );

	// normal text output
	MSGOUT( text );
}


// add line feed in console ---------------------------------------------------
//
PUBLIC
void CON_AddLineFeed()
{
	// force line feed
	skip_next_nl = FALSE;
	CON_AddLine( con_prompt );
}


// set flag to disable next line feed in CON_AddLine() ------------------------
//
PUBLIC
void CON_DisableLineFeed()
{
	// set flag
	skip_next_nl = TRUE;
}


// set flag to not eat next line feed in CON_AddLine() ------------------------
//
PUBLIC
void CON_EnableLineFeed()
{
	// clear flag
	skip_next_nl = FALSE;
}


// delete current console line ------------------------------------------------
//
PUBLIC
void CON_DelLine()
{
	EraseConLine( con_bottom );
}


// return pointer to current console line -------------------------------------
//
PUBLIC
char *CON_GetLine()
{
	return con_lines[ con_bottom ];
}


// print prompt for list continuation -----------------------------------------
//
PUBLIC
void CON_ListCtdPrompt()
{
	CON_AddLine( press_space );

	// ensure proper view alignment
	edit_ofs_x = ( cursor_x > ConsoleEnterLength ) ? ( cursor_x - ConsoleEnterLength ) : 0;
}


// print prompt after list has ended ------------------------------------------
//
PUBLIC
void CON_ListEndPrompt()
{
	await_keypress = FALSE;
	com_cont_func  = NULL;

	if ( con_in_talk_mode ) {

		// restore talkmode prompt
		CON_AddLineFeed();
		CreateSeparatorLine( con_bottom );
		CON_AddLineFeed();
		con_talk_line = con_bottom;

	} else {

		// restore standard prompt
		CON_AddLine( con_prompt );
	}
}


// check geometric extents of console window ----------------------------------
//
void CheckConExtents()
{
	ASSERT( FALSE );
}


// check commands with single integer argument/query --------------------------
//
PRIVATE
int ExecGetSetInteger( const char *scan )
{
	ASSERT( scan != NULL );

	ConsoleHeight -= 2;

	for ( int icom = 0; icom < num_int_commands; icom++ ) {

		ASSERT( int_commands[ icom ].command != NULL );
		ASSERT( int_commands[ icom ].intref != NULL );

		// need fetch function for int vars that need to be
		// made current before they contain the correct value
		if(strncmp(scan, int_commands[ icom ].command, strlen(int_commands[ icom ].command)) ==0) {
			if ( int_commands[ icom ].fetch != NULL )
				*int_commands[ icom ].intref = (*int_commands[ icom ].fetch)();

			if ( CheckSetIntArgBounded( int_print_base, scan,
									(char *) int_commands[ icom ].command,
									int_commands[ icom ].intref,
									int_commands[ icom ].bmin,
									int_commands[ icom ].bmax,
									int_commands[ icom ].realize ) ) {
				ConsoleHeight += 2;
				return TRUE;
			}
		}
	}

	ConsoleHeight += 2;

	return FALSE;
}


// temporary storage in which user can alter their name -----------------------
//
static char temp_playername[ MAX_PLAYER_NAME + 1 ];


// exec command with a single optional parameter ------------------------------
//
PRIVATE
void ExecGetSetCommand( char *command )
{
	ASSERT( command != NULL );

	// split off first token (command specifier)
	char *scan = strtok( command, " " );

	// check different commands
	if ( scan != NULL ) {

		if ( ExecGetSetInteger( scan ) ) {
		} else if ( CheckSetObjTypeProperty( int_print_base, scan ) ) {
		} else if ( CheckSetObjClassProperty( int_print_base, scan ) ) {
		} else if ( CheckSetObjInstanceProperty( int_print_base, scan ) ) {
		} else if ( CheckTypeInfo( scan ) ) {
		} else if ( CheckClassInfo( scan ) ) {
		} else if ( CheckInstanceInfo( scan ) ) {
/*		} else if ( CheckKeyMappingEcho( scan ) ) {
		} else if ( CheckKeyMappingSilent( scan ) ) {
		*/} else if ( CheckSetIntArray( int_print_base, scan, auxflag_array_name, AuxEnabling, MAX_SV_ARRAY_SIZE ) ) {
		} else {
			// printout the command that could not be found
			char szBuffer[ 512 ];
			sprintf( szBuffer, unknown_command, scan );
			CON_AddLine( szBuffer );
		}
	} else {

		CON_AddLine( ok_prompt );
	}
}


// key table for compile command ----------------------------------------------
//
key_value_s compile_key_value[] = {

	{ "title",		NULL,	KEYVALFLAG_PARENTHESIZE		},
	{ "desc",		NULL,	KEYVALFLAG_PARENTHESIZE		},
	{ "author",		NULL,	KEYVALFLAG_PARENTHESIZE		},

	{ NULL,			NULL,	KEYVALFLAG_NONE				},
};

enum {

	KEY_COMPILE_TITLE,
	KEY_COMPILE_DESC,
	KEY_COMPILE_AUTHOR
};


// write demo header if at least one info field specified ---------------------
//
PRIVATE
void WriteDemoHeader( char *title, char *desc, char *author )
{
	if ( ( title == NULL ) && ( desc == NULL ) && ( author == NULL ) ) {
		return;
	}

	ASSERT( strlen( DEM_SIGNATURE ) == 6 );

	DemHeader hdr;
	strcpy( hdr.signature, DEM_SIGNATURE );
	hdr.version = REQUIRED_DEM_VERSION;

	dword headersize = sizeof( DemHeader );

	headersize += ( title  != NULL ) ? strlen( title )  + 2 : 0;
	headersize += ( desc   != NULL ) ? strlen( desc )   + 2 : 0;
	headersize += ( author != NULL ) ? strlen( author ) + 2 : 0;

	hdr.headersize = headersize;

	SYS_SwapDemHeader( &hdr );

	// write fixed-size part of header
	fwrite( &hdr, sizeof( hdr ), 1, compile_fp );

	// write title
	byte demokey = 0;
	if ( title != NULL ) {
		demokey = DEMO_KEY_TITLE;
		fwrite( &demokey, sizeof( demokey ), 1, compile_fp );
		fwrite( title, strlen( title ) + 1, 1, compile_fp );
	}

	// write description
	if ( desc != NULL ) {
		demokey = DEMO_KEY_DESCRIPTION;
		fwrite( &demokey, sizeof( demokey ), 1, compile_fp );
		fwrite( desc, strlen( desc ) + 1, 1, compile_fp );
	}

	// write author
	if ( author != NULL ) {
		demokey = DEMO_KEY_AUTHOR;
		fwrite( &demokey, sizeof( demokey ), 1, compile_fp );
		fwrite( author, strlen( author ) + 1, 1, compile_fp );
	}
}


// check compile command and compile script if valid --------------------------
//
PRIVATE
void CompileCommand( char *command )
{
	ASSERT( command != NULL );

	// check for compile command in script to compile
	if ( compile_script ) {
		CON_AddLine( recursive_compilation );
		return;
	}

	// skip command string
	command += CMLEN( CM_COMPILE );

	// check if there is a space between command and argument
	if ( ( *command != ' ' ) && ( *command != 0 ) ) {

		// printout the command that could not be found
		char szBuffer[ 512 ];
		sprintf( szBuffer, unknown_command, command );
		CON_AddLine( szBuffer );

		return;
	}

	// split off argument (name of command script)
	char *scan = strtok( command, " " );
	if ( scan == NULL ) {
		CON_AddLine( arg_missing );
		return;
	}

	// scan out all values to keys
	if ( !ScanKeyValuePairs( compile_key_value, NULL ) )
		return;

	// get demo information strings (not mandatory, might be NULL)
	char *title  = compile_key_value[ KEY_COMPILE_TITLE ].value;
	char *desc   = compile_key_value[ KEY_COMPILE_DESC ].value;
	char *author = compile_key_value[ KEY_COMPILE_AUTHOR ].value;

	// check if command name is valid
	int extcom = CheckExternalCommand( scan );

	if ( extcom > 0 ) {

		// open output file
		strcpy( paste_str, scan );
		strcat( paste_str, CON_FILE_COMPILED_EXTENSION );
		compile_fp = fopen( paste_str, "wb" );

		if ( compile_fp != NULL ) {

			// write header if at least one info field specified
			WriteDemoHeader( title, desc, author );

			// compile script
			compile_script = TRUE;
			CallExternalCommand( extcom - 1, FALSE );
			compile_script = FALSE;

			// close output file
			if ( compile_fp != NULL ) {
				// if no error occurred write eof marker and close file
				int endmarker = 0;
				fwrite( &endmarker, sizeof( endmarker ), 1, compile_fp );
				fclose( compile_fp );
			}

		} else {
			// filepointer for output invalid
			CON_AddLine( compile_open_failed );
		}

	} else {
		// name of script is not in internal table
		CON_AddLine( unknown_script );
	}
}


// execute command that cannot be compiled ------------------------------------
//
void ExecNonCompilableCommand( char *command )
{
	ASSERT( command != NULL );

	//NOTE:
	// this function is mainly used by ExecConsoleCommand().
	// apart from that it is only used by AcExecCommandString()
	// to execute a command supplied as string in a demo.

	// this is first in order to allow user overriding
	// of all non-compilable commands
	if ( CheckCmdsUserDefined( command ) ) {

	// check commands having no parameters
	} else if ( CheckCmdsNoParam( command ) ) {

	// check commands that do their own parameter parsing
	} else if ( CheckCmdsCustomString( command ) ) {

	} else {

		ExecGetSetCommand( command );
	}
}


// add console line to history list -------------------------------------------
//
INLINE
void AddLineToHistory( char *command )
{
	ASSERT( command != NULL );
	ASSERT( strlen( command ) <= MAX_CONSOLE_LINE_LENGTH );

	// store command in current history position, advance in
	// list, and clear history scrolling
	strcpy( history_list[ history_add ], command );
	history_add  = ( history_add + 1 ) & NUM_HISTORY_LINES_MASK;
	history_scan = history_add;

	// clear next two positions in history ring-buffer
	// (this has to be done in order to make scrolling
	// in both directions work properly)
	// this is where entries start to get reused if there
	// is not enough space in the history list
	*( history_list[ history_add ] ) = 0;
	*( history_list[ ( history_add + 1 ) & NUM_HISTORY_LINES_MASK ] ) = 0;
}


// check for console login state and login/logout commands --------------------
//
PRIVATE
int CheckConsoleLogin( char *command )
{
	ASSERT( command != NULL );

	// used by keymapped commands
	if ( con_no_login_check ) {
		return TRUE;
	}

	// avoid preempting startup script
	if ( console_init_done ) {

		if ( con_login_mode ) {
			con_login_mode = 0;

			// check for password
			if ( strcmp( command, console_login_passwd ) == 0 ) {
				con_logged_in = 1;
				CON_AddLine( console_unlock_done );
			}
			// erase password to prevent it from being displayed
			for ( int spos = 0; spos < ConsoleEnterLength; spos++ ) {
				if ( command[ spos ] == 0 )
					break;
				command[ spos ] = '*';
			}
			return FALSE;
		}

		if ( con_logged_in ) {

			if ( strcmp( command, CMSTR( CM_LOGOUT ) ) == 0 ) {
				con_logged_in = 0;
				CON_AddLine( console_lock_done );
				return FALSE;
			}

		} else {

			if ( strcmp( command, CMSTR( CM_LOGIN ) ) == 0 ) {
				con_login_mode = 1;
				return FALSE;
			}

			CON_AddLine( console_is_locked );
			return FALSE;
		}
	}

	return TRUE;
}


// exec console command (this is the main command dispatcher) -----------------
//
void ExecConsoleCommand( char *command, int echo )
{
	//NOTE:
	// this function may be called recursively from within
	// functions called by CON_EXT::CallExternalCommand()
	// to allow execution of command scripts.

	ASSERT( command != NULL );
	ASSERT( ( echo == FALSE ) || ( echo == TRUE ) );

#ifdef FORCE_CONSOLE_LOGIN

	// check login state and login/logout commands
	if ( !CheckConsoleLogin( command ) ) {
		return;
	}

#endif // FORCE_CONSOLE_LOGIN

	// fetch console line as command
	strncpy( command_line, command, MAX_CONSOLE_LINE_LENGTH );
	command_line[ MAX_CONSOLE_LINE_LENGTH ] = 0;
	command = command_line;

	// eat leading whitespace
	for ( ; *command; command++ ) {
		if ( *command != ' ' ) {
			break;
		}
	}

	// early out for empty lines
	if ( *command == 0 ) {
		if ( echo ) {
			CON_AddLine( ok_prompt );
		}
		return;
	}

	if ( echo ) {
		// add command to history list only if echo is on
		AddLineToHistory( command );
	}

	// temp for extcom id
	int extcom;

	if ( strcmp( command, CMSTR( CM_NOMACROS ) ) == 0 ) {

		// disable calls to CallExternalCommand()
		disable_macros = TRUE;

	} else if ( strcmp( command, CMSTR( CM_ENABLEMACROS ) ) == 0 ) {

		// enable calls to CallExternalCommand()
		disable_macros = FALSE;

	} else if ( strncmp( command, CMSTR( CM_COMPILE ), CMLEN( CM_COMPILE ) ) == 0 ) {

		CompileCommand( command );

	} else if ( strncmp( command, ACMSTR( ACM_SIGNATURE ), ACMLEN( ACM_SIGNATURE ) ) == 0 ) {

		// check/exec commands with "ac." prefix
		ActionCommand( command );

	} else if ( !disable_macros && ( extcom = CheckExternalCommand( command ) ) ) {

		// execute command script
		CallExternalCommand( extcom - 1, echo ? EchoExternalCommands : FALSE );

	} else if ( !compile_script ) {

		// check/exec all other commands
		ExecNonCompilableCommand( command );

	} else {

		// error if compilation in progress and non-compilable command found
		CON_AddLine( cmd_not_compilable );
	}
}


// handle console input in talk mode ------------------------------------------
//
PRIVATE
void HandleTalkMode()
{
	if ( con_in_talk_mode ) {

		if ( con_lines[ con_bottom ][ PROMPT_SIZE ] == talk_escape_char ) {

			// remove '/' escape char from input
			strcpy( paste_str, con_lines[ con_bottom ] + PROMPT_SIZE + 1 );

		} else {

			// prepend "say " to input
			strcpy( paste_str, CMSTR( CM_SAY ) );
			paste_str[ CMLEN( CM_SAY ) ] = ' ';
			strncpy( paste_str + CMLEN( CM_SAY ) + 1,
					 con_lines[ con_bottom ] + PROMPT_SIZE,
					 MAX_CONSOLE_LINE_LENGTH - PROMPT_SIZE - CMLEN( CM_SAY ) - 1 );
			paste_str[ MAX_CONSOLE_LINE_LENGTH - PROMPT_SIZE ] = 0;
		}

		// set bottom to line just below separator in order to
		// overwrite previous output. the current input is also
		// copied into this line
		con_bottom = con_talk_line;
		strcpy( con_lines[ con_bottom ] + PROMPT_SIZE, paste_str );

		// ensure the input line gets overwritten by the first console
		// output the command produces. if the command outputs nothing
		// the terminating prompt will overwrite the former input line
		CON_DisableLineFeed();
	}
}


// <enter> key pressed in console ---------------------------------------------
//
PRIVATE
void EnterConsoleCommand()
{
	// handle input in talkmode
	HandleTalkMode();

	// output command
	CON_AddLine( con_lines[ con_bottom ] );

	// insert command into script if currently open
	if ( !InsertCommandLog( con_lines[ con_bottom ] + PROMPT_SIZE ) ) {

		// execute current linecontent
		ExecConsoleCommand( con_lines[ con_bottom ] + PROMPT_SIZE, TRUE );

		if ( await_keypress ) {
			// listcommand: print listmode prompt
			CON_ListCtdPrompt();
		} else {
			// normal command: print standard prompt
			//CON_AddLine( con_prompt );
		}

	} else {

		// command was not executed, but only
		// written to an output script

		if ( HistoryForBatchEntry )
			AddLineToHistory( con_lines[ con_bottom ] + PROMPT_SIZE );
		//CON_AddLine( con_prompt );
	}

	EraseConLine( con_bottom );
	strcpy( con_lines[ con_bottom ], con_prompt );
}


// fetch history list entry into current console line -------------------------
//
PRIVATE
void FetchHistoryEntry( int entryid )
{
	EraseConLine( con_bottom );
	strcpy( con_lines[ con_bottom ], con_prompt );

	if ( con_in_talk_mode ) {

		// handle talkmode
		if ( ( strncmp( history_list[ entryid ], CMSTR( CM_SAY ), CMLEN( CM_SAY ) ) == 0 ) &&
			 ( history_list[ entryid ][ CMLEN( CM_SAY ) ] == ' ' ) ) {

			// strip "say " in order to produce correct talkmode input
			strcpy( con_lines[ con_bottom ] + PROMPT_SIZE, history_list[ entryid ] + CMLEN( CM_SAY ) + 1 );

		} else {

			// prepend '/' escape char in order to produce correct talkmode input
			con_lines[ con_bottom ][ PROMPT_SIZE ] = talk_escape_char;
			strncpy( con_lines[ con_bottom ] + PROMPT_SIZE + 1,
					 history_list[ entryid ],
					 MAX_CONSOLE_LINE_LENGTH - PROMPT_SIZE - 1 );
			con_lines[ con_bottom ][ MAX_CONSOLE_LINE_LENGTH ] = 0;
		}

	} else {

		// use history line as is
		strcpy( con_lines[ con_bottom ] + PROMPT_SIZE, history_list[ entryid ] );
	}

	// set cursor behind end of command
	cursor_x = strlen( con_lines[ con_bottom ] + PROMPT_SIZE );

	// ensure proper view alignment
	edit_ofs_x = ( cursor_x > ConsoleEnterLength ) ?
		( cursor_x - ConsoleEnterLength ) : 0;
}


// check input for console window ---------------------------------------------
//
PRIVATE
bool_t CheckConsoleInput()
{
	// scan keyboardbuffer and process key-presses sequentially
	dword *pos;
	bool_t console_input_done = false;
	while ( *( pos = &KeybBuffer->Data + KeybBuffer->ReadPos ) ) {

		int curlinelen = strlen( con_lines[ con_bottom ] + PROMPT_SIZE );

		if ( await_keypress && com_cont_func ) {

			// <space> or <enter> continues listing
			if ( ( *pos == CKC_SPACE ) || ( *pos == CKC_ENTER ) ) {

				EraseConLine( con_bottom );
				strcpy( con_lines[ con_bottom ], con_prompt );
				// ensure wait prompt gets overwritten
			    con_bottom  = last_con_bottom;
			    con_content = last_con_content;
				cursor_x    = 0;
				com_cont_func();

			// <escape> returns to command prompt immediately
			} else if ( *pos == CKC_ESCAPE ) {

				await_keypress = FALSE;
				com_cont_func  = NULL;
				if ( con_in_talk_mode ) {
					// restore talkmode prompt
					CreateSeparatorLine( con_bottom );
					CON_AddLineFeed();
					con_talk_line = con_bottom;
				} else {
					// restore standard prompt
					EraseConLine( con_bottom );
					strcpy( con_lines[ con_bottom ], con_prompt );
				}
				cursor_x = 0;
			}

		} else if ( *pos & CKC_CTRL_MASK ) {

			// control keys (CKC_xx)
			switch ( *pos ) {

			// <escape>: erase entire command line
			case CKC_ESCAPE:
				EraseConLine( con_bottom );
				strcpy( con_lines[ con_bottom ], con_prompt );
				history_scan  = history_add;
				cursor_x      = 0;
				con_back_view = 0;
				break;

			// <cursor-up>: scroll one line up in history buffer
			case CKC_CURSORUP:
				if ( !con_logged_in )
					break;
				if ( *( history_list[ ( history_scan - 1 ) & NUM_HISTORY_LINES_MASK ] ) != 0 ) {
					history_scan = ( history_scan - 1 ) & NUM_HISTORY_LINES_MASK;
					FetchHistoryEntry( history_scan );
				}
				break;

			// <cursor-down>: scroll one line down in history buffer
			case CKC_CURSORDOWN:
				if ( !con_logged_in )
					break;
				if ( *( history_list[ ( history_scan + 1 ) & NUM_HISTORY_LINES_MASK ] ) != 0 ) {
					history_scan = ( history_scan + 1 ) & NUM_HISTORY_LINES_MASK;
					FetchHistoryEntry( history_scan );
				}
				break;

			// <cursor-left>: set cursor one position left
			case CKC_CURSORLEFT:
				if ( cursor_x > 0 )
					cursor_x--;
				break;

			// <cursor-right>: set cursor one position right
			case CKC_CURSORRIGHT:
				if ( cursor_x < curlinelen )
					cursor_x++;
				break;

			// <shift + cursor-up>: view one line backward
			case CKC_CURSORUP_SHIFTED:
				if ( !con_logged_in || con_in_talk_mode )
					break;
				if ( con_back_view < CONSOLE_MAX_BACK_LINES )
					con_back_view++;
				break;

			// <shift + cursor-down>: view one line forward
			case CKC_CURSORDOWN_SHIFTED:
				if ( !con_logged_in || con_in_talk_mode )
					break;
				if ( con_back_view > 0 )
					con_back_view--;
				break;

			// <shift + cursor-left>: set cursor one word to the left
			case CKC_CURSORLEFT_SHIFTED:
				while ( ( cursor_x > 0 ) &&
						!isalnum( con_lines[ con_bottom ][ PROMPT_SIZE + cursor_x - 1 ] ) )
					cursor_x--;
				while ( ( cursor_x > 0 ) &&
						isalnum( con_lines[ con_bottom ][ PROMPT_SIZE + cursor_x - 1 ] ) )
					cursor_x--;
				break;

			// <shift + cursor-right>: set cursor one word to the right
			case CKC_CURSORRIGHT_SHIFTED:
				while ( ( cursor_x < curlinelen ) &&
						isalnum( con_lines[ con_bottom ][ PROMPT_SIZE + cursor_x ] ) )
					cursor_x++;
				while ( ( cursor_x < curlinelen ) &&
						!isalnum( con_lines[ con_bottom ][ PROMPT_SIZE + cursor_x ] ) )
					cursor_x++;
				break;

			// <home>: set cursor to first column
			case CKC_HOME:
				cursor_x = 0;
				break;

			// <end>: set cursor behind last column
			case CKC_END:
				cursor_x = curlinelen;
				break;

			// <page-up>: view one page backward
			case CKC_PAGEUP:
				if ( !con_logged_in || con_in_talk_mode )
					break;
				if ( cur_vis_conlines <= 0 )
					break;
				if ( con_back_view < CONSOLE_MAX_BACK_LINES )
					con_back_view += cur_vis_conlines;
				if ( con_back_view > CONSOLE_MAX_BACK_LINES )
					con_back_view = CONSOLE_MAX_BACK_LINES;
				break;

			// <page-down>: view one page forward
			case CKC_PAGEDOWN:
				if ( !con_logged_in || con_in_talk_mode )
					break;
				if ( cur_vis_conlines <= 0 )
					break;
				if ( con_back_view > 0 )
					con_back_view -= cur_vis_conlines;
				if ( con_back_view < 0 )
					con_back_view = 0;
				break;

			// <insert>: toggle insert mode
			case CKC_INSERT:
				insert_mode = !insert_mode;
				break;

			// <del>: delete and shift left
			case CKC_DELETE:
				if ( cursor_x < curlinelen ) {
					strcpy( paste_str, con_lines[ con_bottom ] + PROMPT_SIZE + cursor_x + 1 );
					strcpy( con_lines[ con_bottom ] + PROMPT_SIZE + cursor_x, paste_str );
				}
				break;

			// <tab>: find completion for current input
			case CKC_TAB:
				if ( !con_logged_in )
					break;
				CompleteCommand();
				break;

			// <enter>: execute current line
			case CKC_ENTER:
				EnterConsoleCommand();
				break;

			// <backspace>: step left and shift righthand side left
			case CKC_BACKSPACE:
				if ( cursor_x > 0 ) {
					if ( cursor_x == curlinelen ) {
						cursor_x--;
						con_lines[ con_bottom ][ PROMPT_SIZE + cursor_x ] = 0;
					} else {
						cursor_x--;
						strcpy( paste_str, con_lines[ con_bottom ] + PROMPT_SIZE + cursor_x + 1 );
						strcpy( con_lines[ con_bottom ] + PROMPT_SIZE + cursor_x, paste_str );
					}
				}
				break;
			}

		} else {

			// typeable characters
			if ( ( ConsoleASCIIValid[ *pos & CON_ASCII_MASK ] ) &&
				 ( cursor_x < edit_max_x ) ) {
				if ( insert_mode && ( cursor_x < curlinelen ) ) {
					if ( curlinelen < edit_max_x ) {
						strcpy( paste_str, con_lines[ con_bottom ] + PROMPT_SIZE + cursor_x );
						strcpy( con_lines[ con_bottom ] + PROMPT_SIZE + cursor_x + 1, paste_str );
						con_lines[ con_bottom ][ PROMPT_SIZE + cursor_x++ ] = (byte)*pos;
					}
				} else {
					con_lines[ con_bottom ][ PROMPT_SIZE + cursor_x++ ] = (byte)*pos;
				}
			}
		}

		// advance one position in circular keybuffer
		KeybBuffer->ReadPos = ( KeybBuffer->ReadPos + 1 ) % KEYB_BUFF_SIZ;
		*pos = 0;

		console_input_done = true;
	}

	return console_input_done;
}


// type for writestring function pointer --------------------------------------
//
typedef void (*WSFP)( ... );

//NOTE:
// this declaration is in global scope because of the extern "C".
// only gcc needs the otherwise redundant curly braces, however.



// process quicksay console input and draw it ---------------------------------
//
int QuicksayConsole()
{
/*	// check whether main console has turned quicksay off
	if ( !KeybFlags->ConEnabled || !KeybFlags->ConActive ) {
		return FALSE;
	}

	dword *pos;
	dword readpos = KeybBuffer->ReadPos;

	// scan console input buffer for ESCAPE or ENTER which
	// should turn off quicksay mode again
	while ( *( pos = &KeybBuffer->Data + readpos ) ) {

		if ( *pos == CKC_ESCAPE || *pos == CKC_ENTER ) {
			SetQuicksayConsole( FALSE );
		}

		readpos = ( readpos + 1 ) % KEYB_BUFF_SIZ;
	}

	// use standard input handling
	CheckConsoleInput();

	// ensure proper edit line viewing window
	if ( cursor_x < edit_ofs_x ) {
		edit_ofs_x = cursor_x;
	} else if ( cursor_x > edit_ofs_x + ConsoleEnterLength ) {
		edit_ofs_x = cursor_x - ConsoleEnterLength;
	}

	// determine whether translucency should be used
	int translucent = VID_TRANSLUCENCY_SUPPORTED;

	D_SetWStrContext( CharsetInfo[ HUD_CHARSETNO ].charsetpointer,
					  CharsetInfo[ HUD_CHARSETNO ].geompointer,
					  NULL,
					  CharsetInfo[ HUD_CHARSETNO ].width,
					  CharsetInfo[ HUD_CHARSETNO ].height );

	// write text translucent only for color depths below 32 bit per pixel
	WSFP wsfp = translucent ? (WSFP) &D_WriteTrString : (WSFP) &D_WriteString;

	// determine chars to draw
	if ( edit_ofs_x == 0 ) {
		memcpy( draw_line, con_lines[ con_bottom ], ConsoleEnterLength + PROMPT_SIZE );
		draw_line[ ConsoleEnterLength + PROMPT_SIZE ] = 0;
	} else {
		memcpy( draw_line, con_lines[ con_bottom ], PROMPT_SIZE );
		draw_line[ PROMPT_SIZE - 1 ] = '<';
		memcpy( draw_line + PROMPT_SIZE, con_lines[ con_bottom ] + PROMPT_SIZE + edit_ofs_x, ConsoleEnterLength );
		draw_line[ ConsoleEnterLength + PROMPT_SIZE ] = 0;
	}

	int xpos = ConsoleTextX * CharsetInfo[ HUD_CHARSETNO ].width + console_frameofs_x;
	int ypos = 130;

	// draw background bar
	int barwidth  = ( ConsoleEnterLength + PROMPT_SIZE + 1 ) * CharsetInfo[ HUD_CHARSETNO ].width + 6;
	int barheight = CharsetInfo[ HUD_CHARSETNO ].height + 4;
	D_DrawTrRect( xpos - 3, ypos - 2, barwidth, barheight, TRTAB_PANELBACK );

	// draw line contents
	wsfp( draw_line, xpos, ypos, TRTAB_PANELTEXT );

	// maintain blinking of cursor if not done by main console
	if ( ConsoleSliding == 0 ) {
		cursor_state += CurScreenRefFrames;
	}

	// draw cursor
	if ( cursor_state & CURSOR_BLINK_SPEED ) {

		xpos  = ConsoleTextX + cursor_x - edit_ofs_x + PROMPT_SIZE;
		xpos *= CharsetInfo[ HUD_CHARSETNO ].width;
		xpos += console_frameofs_x;

		char *cursorstr = insert_mode ? insert_cursor : overwrite_cursor;
		wsfp( cursorstr, xpos, ypos, TRTAB_PANELTEXT );
	}

	// allow caller to check for disabling
	return KeybFlags->ConActive;
	*/

	return FALSE;
}


// draw console window --------------------------------------------------------
//
PRIVATE
void DrawConsole( bool_t bClear )
{
	//NOTE: in order to minimize screen flicker, we only clear the inputline, 
	//      if the previous contents was longers
	if ( bClear )
		wclear( g_curses_in_win );

	mvwprintw( g_curses_in_win, 0, 0, con_lines[ con_bottom ] );
	wmove( g_curses_in_win, 0, cursor_x + PROMPT_SIZE );
	wrefresh( g_curses_in_win );
}


// main console function: process keyboard input and draw console window ------
//
PUBLIC
void CON_ConsoleMain()
{
	static bool_t init_prompt_drawn = false;

	// set number of currently visible console lines
	// (negative values allowed!)
	cur_vis_conlines = ConsoleHeight;

	unsigned int len_before = strlen( con_lines[ con_bottom ] );

	// process console keyboard input
	if ( CheckConsoleInput() || !init_prompt_drawn ) {

		init_prompt_drawn = true;
		// draw console
		DrawConsole( len_before > strlen( con_lines[ con_bottom ] ) );
	}
}