~swag/armagetronad/0.2.9-sty+ct+ap-fork

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
1674
1675
1676
1677
1678
1679
1680
/*

*************************************************************************

ArmageTron -- Just another Tron Lightcycle Game in 3D.
Copyright (C) 2000  Manuel Moos (manuel@moosnet.de)

**************************************************************************

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 "config.h"
#include <fstream>
#include <iomanip>
#include <iostream>
#include "tConfiguration.h"
#include <stdlib.h>
#include <ctype.h>
#include <string>
#include <sstream>
#include "tString.h"
#include "tToDo.h"
#include "tConsole.h"
#include "tDirectories.h"
#include "tLocale.h"
#include "tRecorder.h"
#include "tCommandLine.h"
#include "tResourceManager.h"
#include "tError.h"

#include <vector>
#include <string.h>

#ifndef WIN32
#include <signal.h>
#endif

/***********************************************************************
 * The new Configuration interface, currently not completely implemented
 */

#ifndef NEW_CONFIGURATION_NO_COMPILE

// Use this function to register your own configuration directive
//   returns true if it was successful, false if not
//   should return true even if it didn't register the new directive because
//       it was already there
bool tConfiguration::registerDirective(string newDirective, string defValue) {
    // THIS IS A STUB
}

// Use this function to set a configuration directive from a string
bool tConfiguration::setDirective(string oldDirective, string newValue) {
    // THIS IS A STUB
}

// Use this function to set a configuration directive from an int
bool tConfiguration::setDirective(string oldDirective, int newValue) {
    // THIS IS A STUB
}

// Use this function to set a configuration directive from a float
bool tConfiguration::setDirective(string oldDirective, double newValue) {
    // THIS IS A STUB
}

// Use this function to set a configuration directive from a bool
bool tConfiguration::setDirective(string oldDirective, bool newValue) {
    // THIS IS A STUB
}

// Use this function to get a configuration directive as a string
const string& tConfiguration::getDirective(string oldDirective) {
    // THIS IS A STUB
}

// Use this function to get a configuration directive as an int
const int& tConfiguration::getDirectiveI(string oldDirective) {
    // THIS IS A STUB
}

// Use this function to get a configuration directive as a double
const double& tConfiguration::getDirectiveF(string oldDirective) {
    // THIS IS A STUB
}

// Use this function to get a configuration directive as a bool
const bool& tConfiguration::getDirectiveB(string oldDirective) {
    // THIS IS A STUB
}

// Use this function to load a file
//  You *MUST* pass it a complete path from the root directory!
//  Returns TRUE if it can open the file and load at least some of it
//  Returns FALSE if complete failure.
bool tConfiguration::LoadFile(string filename) {
    // THIS IS A STUB
}

// Use this function to save current configuration to files
//   Returns TRUE on success, FALSE on failure
bool tConfiguration::SaveFile() {
    // THIS IS A STUB
}

// This function is used internally to actually set each directive
bool tConfiguration::_setDirective(string oldDirective, tConfigurationItem& newItem) {
    // THIS IS A STUB
}

// This function registers basic configuration directives
//  Create a new configuration directive by going to this function and
//  putting the appropriate line, then just use it in the game
//  It registers global defaults, but not object-specific defaults
void tConfiguration::_registerDefaults() {
    // THIS IS A STUB
}

tConfiguration* tConfiguration::_instance = 0;

const tConfiguration* tConfiguration::GetConfiguration() {
    if(_instance = 0) {
        _instance = new tConfiguration;
    }

    return _instance;
}

#endif
/*
 * The old stuff follows
 ************************************************************************/

bool           tConfItemBase::printChange=true;
bool           tConfItemBase::printErrors=true;

//Stolen from 0.4. Allows you to toggle boolean commands.
static void st_ToggleConfigItem( std::istream & s )
{
    tString name;
    s >> name;

    if ( name.Size() == 0 )
    {
        con << tOutput( "$toggle_usage_error" );
        return;
    }

    tConfItemBase *base = tConfItemBase::FindConfigItem2( name );

    if ( !base )
    {
        con << tOutput( "$config_command_unknown", name );
        return;
    }

    tConfItem< bool > *confItem = dynamic_cast< tConfItem< bool > * >( base );
    if ( confItem && confItem->Writable() )
    {
        confItem->SetVal( !*confItem->GetTarget() );
    }
    else
    {
        con << tOutput( "$toggle_invalid_config_item", name );
    }
}

static tConfItemFunc toggleConfItemFunc( "TOGGLE", st_ToggleConfigItem );


//! @param newLevel         the new access level to set over the course of the lifetime of this object
//! @param allowElevation   only if set to true, getting higher access rights is possible. Use with extreme care.
tCurrentAccessLevel::tCurrentAccessLevel( tAccessLevel newLevel, bool allowElevation )
{
    // prevent elevation
    if ( !allowElevation && newLevel < currentLevel_ )
    {
        // you probably want to know when this happens in the debugger
        st_Breakpoint();
        newLevel = currentLevel_;
    }

    lastLevel_ = currentLevel_;
    currentLevel_ = newLevel;
}


tCurrentAccessLevel::tCurrentAccessLevel()
{
    lastLevel_ = currentLevel_;
}

tCurrentAccessLevel::~tCurrentAccessLevel()
{
    currentLevel_ = lastLevel_;
}

//! returns the current access level
tAccessLevel tCurrentAccessLevel::GetAccessLevel()
{
    tASSERT( currentLevel_ != tAccessLevel_Invalid );
    return currentLevel_;
}

// returns the name of an access level
tString tCurrentAccessLevel::GetName( tAccessLevel level )
{
    std::ostringstream s;
    s << "$config_accesslevel_" << level;
    return tString( tOutput( s.str().c_str() ) );
}

tAccessLevel tCurrentAccessLevel::currentLevel_ = tAccessLevel_Invalid; //!< the current access level

tAccessLevelSetter::tAccessLevelSetter( tConfItemBase & item, tAccessLevel level )
{
#ifdef KRAWALL_SERVER
    item.requiredLevel = level;
#endif
}

static std::map< tString, tConfItemBase * > * st_confMap = 0;
tConfItemBase::tConfItemMap & tConfItemBase::ConfItemMap()
{
    if (!st_confMap)
        st_confMap = tNEW( tConfItemMap );
    return *st_confMap;
}

tConfItemBase::tConfItemMap const & tConfItemBase::GetConfItemMap()
{
    return ConfItemMap();
}

static bool st_preventCasacl = false;

tCasaclPreventer::tCasaclPreventer( bool prevent )
{
    previous_ = st_preventCasacl;
    st_preventCasacl = prevent;
}

tCasaclPreventer::~tCasaclPreventer()
{
    st_preventCasacl = previous_;
}

//! returns whether we're currently in an RINCLUDE file
bool tCasaclPreventer::InRInclude()
{
    return st_preventCasacl;
}

// changes the access level of a configuration item
class tConfItemLevel: public tConfItemBase
{
public:
    tConfItemLevel()
    : tConfItemBase( "ACCESS_LEVEL" )
    {
        requiredLevel = tAccessLevel_Owner;
    }

    virtual void ReadVal(std::istream &s)
    {
        // read name and access level
        tString name;
        s >> name;

        int levelInt;
        s >> levelInt;
        tAccessLevel level = static_cast< tAccessLevel >( levelInt );

        if ( s.fail() )
        {
            if(printErrors)
            {
                con << tOutput( "$access_level_usage" );
            }
            return;
        }

        // make name uppercase:
        tToUpper( name );

        // find the item
        tConfItemMap & confmap = ConfItemMap();
        tConfItemMap::iterator iter = confmap.find( name );
        if ( iter != confmap.end() )
        {
            // and change the level
            tConfItemBase * ci = (*iter).second;

            if( ci->requiredLevel < tCurrentAccessLevel::GetAccessLevel() )
            {
                con << tOutput( "$access_level_nochange_now",
                                name,
                                tCurrentAccessLevel::GetName( ci->requiredLevel ),
                                tCurrentAccessLevel::GetName( tCurrentAccessLevel::GetAccessLevel() ) );
            }
            else if( level < tCurrentAccessLevel::GetAccessLevel() )
            {
                con << tOutput( "$access_level_nochange_later",
                                name,
                                tCurrentAccessLevel::GetName( level ),
                                tCurrentAccessLevel::GetName( tCurrentAccessLevel::GetAccessLevel() ) );
            }
            else if ( ci->requiredLevel != level )
            {
                if(printChange)
                {
                    con << tOutput( "$access_level_change", name, tCurrentAccessLevel::GetName( ci->requiredLevel ) , tCurrentAccessLevel::GetName( level ) );
                }
                ci->requiredLevel = level;
            }
        }
        else if(printErrors)
        {
            con << tOutput( "$config_command_unknown", name );
        }
    }

    virtual void WriteVal(std::ostream &s)
    {
        tASSERT(0);
    }

    virtual void FetchVal(tString &val){};

    virtual bool Writable(){
        return false;
    }

    virtual bool Save(){
        return false;
    }

    // CAN this be saved at all?
    virtual bool CanSave(){
        return false;
    }
};

static tConfItemLevel st_confLevel;

#ifdef KRAWALL_SERVER

static char const *st_casacl = "CASACL";

//! casacl (Check And Set ACcess Level) command: elevates the access level for the context of the current configuration file
class tCasacl: tConfItemBase
{
public:
    tCasacl()
    : tConfItemBase( st_casacl )
    {
        requiredLevel = tAccessLevel_Program;
    }

    virtual void ReadVal( std::istream & s )
    {
        int required_int = 0, elevated_int = 20;

        // read required and elevated access levels
        s >> required_int;
        s >> elevated_int;

        tAccessLevel elevated = static_cast< tAccessLevel >( elevated_int );
        tAccessLevel required = static_cast< tAccessLevel >( required_int );

        if ( s.fail() )
        {
            con << tOutput( "$casacl_usage" );
            throw tAbortLoading( st_casacl );
        }
        else if ( tCurrentAccessLevel::GetAccessLevel() > required )
        {
            con << tOutput( "$access_level_error",
                            "CASACL",
                            tCurrentAccessLevel::GetName( required ),
                            tCurrentAccessLevel::GetName( tCurrentAccessLevel::GetAccessLevel() )
                );
            throw tAbortLoading( st_casacl );
        }
        else if ( st_preventCasacl )
        {
            con << tOutput( "$casacl_not_allowed" );
            throw tAbortLoading( st_casacl );
        }
        else
        {
            tString().ReadLine(s); // prevent commands following this one without a newline
            tCurrentAccessLevel::currentLevel_ = elevated;
        }
    }

    virtual void WriteVal(std::ostream &s)
    {
        tASSERT(0);
    }

    virtual void FetchVal(tString &val){};

    virtual bool Writable(){
        return false;
    }

    virtual bool Save(){
        return false;
    }

    // CAN this be saved at all?
    virtual bool CanSave(){
        return false;
    }
};

static tCasacl st_sudo;

#endif

bool st_FirstUse=true;
static tConfItem<bool> fu("FIRST_USE",st_FirstUse);
//static tConfItem<bool> fu("FIRST_USE","help_first_use",st_FirstUse);


tAbortLoading::tAbortLoading( char const * command )
: command_( command )
{
}

tString tAbortLoading::DoGetName() const
{
    return tString(tOutput( "$abort_loading_name"));
}

tString tAbortLoading::DoGetDescription() const
{
    return tString(tOutput( "$abort_loading_description", command_ ));
}

tConfItemBase::tConfItemBase(const char *t)
        :id(-1),title(t),
changed(false){

    tConfItemMap & confmap = ConfItemMap();
    if ( confmap.find( title ) != confmap.end() )
        tERR_ERROR_INT("Two tConfItems with the same name " << t << "!");

    // compose help name
    tString helpname;
    helpname << title << "_help";
    tToLower( helpname );

    const_cast<tOutput&>(help).AddLocale(helpname);

    confmap[title] = this;

    requiredLevel = tAccessLevel_Admin;
    setLevel      = tAccessLevel_Owner;
}

tConfItemBase::tConfItemBase(const char *t, const tOutput& h)
        :id(-1),title(t), help(h),
changed(false){

    tConfItemMap & confmap = ConfItemMap();
    if ( confmap.find( title ) != confmap.end() )
        tERR_ERROR_INT("Two tConfItems with the same name " << t << "!");

    confmap[title] = this;

    requiredLevel = tAccessLevel_Admin;
    setLevel      = tAccessLevel_Owner;
}

tConfItemBase::~tConfItemBase()
{
    tConfItemMap & confmap = ConfItemMap();
    confmap.erase(title);
    if ( confmap.size() == 0 )
    {
        delete st_confMap;
        st_confMap = 0;
    }
}

void tConfItemBase::ExportAll(){
    SaveAll(std::cout, true);
}

void tConfItemBase::SaveAll(std::ostream &s, bool all){
    tConfItemMap & confmap = ConfItemMap();
    for(tConfItemMap::iterator iter = confmap.begin(); iter != confmap.end() ; ++iter)
    {
        tConfItemBase * ci = (*iter).second;
        if ((!all && ci->Save())||(all && ci->CanSave())){
            s << ci->title << " ";
            ci->WriteVal(s);
            s << "\n";
        }
    }
}

int tConfItemBase::EatWhitespace(std::istream &s){
    int c=' ';

    while(isblank(c) &&
            c!='\n'    &&
            s.good()  &&
            !s.eof())
        c=s.get();

    if( s.good() )
    {
        s.putback(c);
    }

    return c;
}

void tConfItemBase::LoadLine(std::istream &s){
    if(!s.eof() && s.good()){
        tString name;
        s >> name;

        // make name uppercase:
        tToUpper( name );

        bool found=false;

        if (name[0]=='#'){ // comment. ignore rest of line
            char c=' ';
            while(c!='\n' && s.good() && !s.eof()) c=s.get();
            found=true;
        }

        if (strlen(name)==0) // ignore empty lines
            found=true;

        tConfItemMap & confmap = ConfItemMap();
        tConfItemMap::iterator iter = confmap.find( name );
        if ( iter != confmap.end() )
        {
            tConfItemBase * ci = (*iter).second;

            bool cb=ci->changed;
            ci->changed=false;

#ifdef DEBUG
            con << "Current level: " << tCurrentAccessLevel::GetAccessLevel() << "\n";
            con << "Required level: " << ci->requiredLevel << "\n";
#endif

            if ( ci->requiredLevel >= tCurrentAccessLevel::GetAccessLevel() )
            {
                ci->setLevel = tCurrentAccessLevel::GetAccessLevel();

                ci->ReadVal(s);
                if (ci->changed)
                {
                    ci->WasChanged();
                }
                else
                {
                    ci->changed=cb;
                }
            }
            else
            {
                tString discard;
                discard.ReadLine(s);

                con << tOutput( "$access_level_error",
                                name,
                                tCurrentAccessLevel::GetName( ci->requiredLevel ),
                                tCurrentAccessLevel::GetName( tCurrentAccessLevel::GetAccessLevel() )
                    );
                return;
            }

            found=true;
        }

        if (!found){
            // eat rest of input line
            tString rest;
            rest.ReadLine( s );

            if (printErrors)
            {
                tOutput o;
                o.SetTemplateParameter(1, name);
                o << "$config_command_unknown";
                con << o;

                if (printChange)
                {
                    int sim_maxlen=-1;

                    for(tConfItemMap::iterator iter = confmap.begin(); iter != confmap.end() ; ++iter)
                    {
                        tConfItemBase * ci = (*iter).second;
                        if (strstr(ci->title,name) &&
                                static_cast<int>(strlen(ci->title)) > sim_maxlen)
                            sim_maxlen=strlen(ci->title);
                    }

                    if (sim_maxlen>0 && printChange ){
                        int len = name.Len()-1;
                        int printMax = 1 + 3 * len * len * len;
                        con << tOutput("$config_command_other");
                        for(tConfItemMap::iterator iter = confmap.begin(); iter != confmap.end() ; ++iter)
                        {
                            tConfItemBase * ci = (*iter).second;
                            if (strstr(ci->title,name))
                            {
                                tString help ( ci->help );
                                if ( --printMax > 0 )
                                {
                                    tString mess;
                                    mess << ci->title;
                                    mess.SetPos( sim_maxlen+2, false );
                                    mess << "(";
                                    mess << help;
                                    mess << ")\n";
                                    con << mess;
                                }
                            }
                        }
                        if (printMax <= 0 )
                            con << tOutput("$config_command_more");
                    }
                }
                else
                {
                    con << '\n';
                }
            }
        }
    }

    //  std::cout << line << " lines read.\n";
}

//Stolen from 0.4. Needed for "TOGGLE" function. 
tConfItemBase *tConfItemBase::FindConfigItem2(tString const &name) {
    tConfItemMap & confmap = ConfItemMap();
    tConfItemMap::iterator iter = confmap.find( name.ToUpper() );
    if ( iter != confmap.end() ) {
        return iter->second;
    } else {
        return 0;
    }
}

tString tConfItemBase::FindConfigItem(tString name)
{
    tConfItemMap & confmap = ConfItemMap();
    for(tConfItemMap::iterator iter = confmap.begin(); iter != confmap.end() ; ++iter)
    {
        tConfItemBase * ci = (*iter).second;
        tString command;
        command << ci->title.ToLower();
        if (command.Contains(name.ToLower()))
        {
            if (command.StartsWith(name.ToLower()))
            {
                return ci->title;
            }
        }
    }
    return tString("");
}

/** LISTING BEGIN **/
// writes the list of all commands and their help to config_all.cfg in the var directory
void tConfItemBase::WriteAllToFile()
{
    tConfItemMap & confmap = ConfItemMap();
    int sim_maxlen = -1;

    for(tConfItemMap::iterator iter = confmap.begin(); iter != confmap.end() ; ++iter)
    {
        tConfItemBase * ci = (*iter).second;
        if (static_cast<int>(strlen(ci->title)) > sim_maxlen)
            sim_maxlen = strlen(ci->title);
    }

    std::ofstream w;
    if ( tDirectories::Var().Open(w, "config_all.cfg"))
    {
        /*w << "{| border=\"2\" cellspacing=\"0\" cellpadding=\"4\" rules=\"all\" style=\"margin:1em 1em 1em 0; border:solid 1px #AAAAAA; border-collapse:collapse; background-color:#F9F9F9; font-size:95%; empty-cells:show;\"\n";
        w << "!Command\n";
        w << "!Default\n";
        w << "!Meaning\n";
        w << "|-\n";
        */
        for(tConfItemMap::iterator iter = confmap.begin(); iter != confmap.end() ; ++iter)
        {
            tConfItemBase * ci = (*iter).second;
            tString help ( ci->help );

            tString mess, value;

            //  fetch the value set for this setting.
            ci->FetchVal(value);

            mess << ci->title << " ";

            mess.SetPos( sim_maxlen+2, false );
            mess << value << " ";
            mess << " # ";
            mess << help;
            mess << "\n";

            w << mess;
            /*w << "| " << ci->title << " || " << value << " || " << help << "\n";
            w << "|-\n";*/
        }
        //w << "|}\n";
    }
    w.close();
}

static void sg_ListAllCommands(std::istream &s)
{
    tConfItemBase::WriteAllToFile();
}
static tConfItemFunc sg_ListAllCommandsConf("LIST_ALL_COMMANDS", &sg_ListAllCommands);

/** LISTING END **/

/** LISTING ACCESS_LEVEL BEGIN **/
// writes the list of all commands and their help to config_all_levels.cfg in the var directory
void tConfItemBase::WriteAllLevelsToFile()
{
    tConfItemMap & confmap = ConfItemMap();
    int sim_maxlen = -1;

    for(tConfItemMap::iterator iter = confmap.begin(); iter != confmap.end() ; ++iter)
    {
        tConfItemBase * ci = (*iter).second;
        if (static_cast<int>(strlen(ci->title)) > sim_maxlen)
            sim_maxlen = strlen(ci->title);
    }

    std::ofstream w;
    if ( tDirectories::Var().Open(w, "config_all_levels.cfg"))
    {
        for(tConfItemMap::iterator iter = confmap.begin(); iter != confmap.end() ; ++iter)
        {
            tConfItemBase * ci = (*iter).second;
            tString help ( ci->help );

            tString mess;

            mess << "ACCESS_LEVEL ";
            mess << ci->title << " ";

            //mess.SetPos( sim_maxlen+2, false );
            mess << ci->requiredLevel;
            mess.SetPos( sim_maxlen+5, false );
            mess << " # ";
            mess << help;
            mess << "\n";

            w << mess;
        }
    }
    w.close();
}

static void sg_ListAllCommandsLevels(std::istream &s)
{
    tConfItemBase::WriteAllLevelsToFile();
}
static tConfItemFunc sg_ListAllCommandsLevelsConf("LIST_ALL_COMMANDS_LEVELS", &sg_ListAllCommandsLevels);

/** LISTING ACCESS_LEVEL END **/

/** SET ALL ACCESS_LEVEL BEGIN **/
void tConfItemBase::SetAllAccessLevel(int newLevel)
{
    tConfItemMap & confmap = ConfItemMap();
    tAccessLevel level = static_cast< tAccessLevel >( newLevel );

    for(tConfItemMap::iterator iter = confmap.begin(); iter != confmap.end() ; ++iter)
    {
        tConfItemBase * ci = (*iter).second;
        ci->requiredLevel = level;
    }

    tString message;
    message << "All access levels of commands have been changed to " << tCurrentAccessLevel::GetName(level) << "!\n";
    con << message;
}

static void st_SetCommandsAccessLevel(std::istream &s)
{
    tString levelStr;
    s >> levelStr;

    int newLevel = atoi(levelStr);
    tConfItemBase::SetAllAccessLevel(newLevel);
}
static tConfItemFunc st_SetCommandsAccessLevelConf("SET_COMMANDS_ACCESSLEVEL", &st_SetCommandsAccessLevel);
/** SET ALL ACCESS_LEVEL END **/

void tConfItemBase::WriteChangedToFile()
{
    tConfItemMap & confmap = ConfItemMap();
    int sim_maxlen = -1;

    for(tConfItemMap::iterator iter = confmap.begin(); iter != confmap.end() ; ++iter)
    {
        tConfItemBase * ci = (*iter).second;
        if (static_cast<int>(strlen(ci->title)) > sim_maxlen)
            sim_maxlen = strlen(ci->title);
    }

    std::ofstream w;
    if ( tDirectories::Var().Open(w, "config_changed.cfg"))
    {
        for(tConfItemMap::iterator iter = confmap.begin(); iter != confmap.end() ; ++iter)
        {
            tConfItemBase * ci = (*iter).second;
            if (!ci->changed) continue;

            tString help ( ci->help );

            tString mess, value;

            //  fetch the value set for this setting.
            ci->FetchVal(value);

            mess << ci->title << " ";

            mess.SetPos( sim_maxlen+2, false );
            mess << value << " ";
            mess << " # ";
            mess << help;
            mess << "\n";

            w << mess;
        }
    }
    w.close();
}

void tConfItemBase::DownloadSettings_Go(nMessage &m)
{
    //  download the config if this is a client
    if (sn_GetNetState() == nCLIENT)
    {
        tString m_title;
        m >> m_title;
        if ((m_title == "DOWNLOAD_BEGIN") && m.End())
        {
            con << "Downloading config from server...\n";

            //  truncate the file for fresh settings
            std::ofstream o;
            if ( tDirectories::Var().Open(o, "server_settings.cfg", std::ios::trunc) ) {}
            o.close();
            return;
        }
        else if ((m_title == "DOWNLOAD_END") && m.End())
        {
            con << "Download complete!\n";
            return;
        }
        tString m_value;
        m >> m_value;

        std::ofstream o;
        if (tDirectories::Var().Open(o, "server_settings.cfg", std::ios::app))
        {
            o << m_title << " " << m_value << "\n";
        }
        o.close();
    }
}

static nDescriptor downloadSettings(61,tConfItemBase::DownloadSettings_Go, "download settings");

void tConfItemBase::DownloadSettings_To(int peer)
{
    //  transfer the settings to the requested client
    //  Client ID must be greater than 0 for it to work
    if ((sn_GetNetState() == nSERVER) && (peer > 0))
    {
        {
            nMessage *m=new nMessage(downloadSettings);
            *m << tString("DOWNLOAD_BEGIN");
            m->Send(peer);
        }

        tConfItemMap & confmap = ConfItemMap();
        for(tConfItemMap::iterator iter = confmap.begin(); iter != confmap.end() ; ++iter)
        {
            tConfItemBase * item = (*iter).second;
            if (item && item->CanSave())
            {
                nMessage *m=new nMessage(downloadSettings);
                *m << item->title;

                tString value;
                item->FetchVal(value);
                *m << value;

                m->Send(peer);
            }
        }

        {
            nMessage *m=new nMessage(downloadSettings);
            *m << tString("DOWNLOAD_END");
            m->Send(peer);
        }
    }
}

tString configFileDownload("");
void tConfItemBase::DownloadConfig_Go(nMessage &m)
{
    //  download the config if this is a client
    if (sn_GetNetState() == nCLIENT)
    {
        tString c_line;
        m >> c_line;
        if ((c_line == "DOWNLOAD_BEGIN") && !m.End())
        {
            m >> configFileDownload;
            con << "Downloading \"" << configFileDownload << "\" from server...\n";

            //  truncate the file for fresh settings
            std::ofstream o;
            tString configFile;
            configFile << "public/" << configFileDownload;
            if ( tDirectories::Config().Open(o, configFile, std::ios::trunc) ) {}
            o.close();
            return;
        }
        else if ((c_line == "DOWNLOAD_END") && m.End())
        {
            con << "Download complete!\n";
            configFileDownload = "";
            return;
        }

        if (configFileDownload == "") return;

        std::ofstream o;
        tString configFile;
        configFile << "public/" << configFileDownload;
        if (tDirectories::Config().Open(o, configFile, std::ios::app))
        {
            o << c_line << "\n";
        }
        o.close();
    }
}

static nDescriptor downloadConfigs(62,tConfItemBase::DownloadConfig_Go, "download config");

bool st_downloadConfigProcess = false;
void tConfItemBase::DownloadConfig_To(tString file, int peer)
{
    //  don't process if its under process
    if (st_downloadConfigProcess) return;
    st_downloadConfigProcess = true;

    // refuse to load illegal paths
    if( !tPath::IsValidPath( file ) )
        return;

    nMessage *m = NULL;

    std::ifstream i;
    tString configFile;
    configFile << "public/" << file;

    //  transfer the settings from config to the client
    //  Client ID must be greater than 0 for it to work
    if ((sn_GetNetState() == nSERVER) && (peer > 0) && tDirectories::Config().Open(i, configFile))
    {
        m = new nMessage(downloadConfigs);
        *m << tString("DOWNLOAD_BEGIN");
        *m << file;
        m->Send(peer);

        std::istream &s(i);
        int i = 0;
        while (!s.eof() && s.good())
        {
            tString line;
            line.ReadLine(s);

            m = new nMessage(downloadConfigs);
            *m << line;
            m->Send(peer);

            i++;
        }

        m = new nMessage(downloadConfigs);
        *m << tString("DOWNLOAD_END");
        m->Send(peer);
    }
    i.close();

    st_downloadConfigProcess = false;
}


int tConfItemBase::AccessLevel(std::istream &s){
    if(!s.eof() && s.good()){
        tString name;
        s >> name;
        // make name uppercase:
        tToUpper( name );
        tConfItemMap & confmap = ConfItemMap();
        tConfItemMap::iterator iter = confmap.find( name );
        if ( iter != confmap.end() )
        {
            tConfItemBase * ci = (*iter).second;
            return ci->requiredLevel;
        }
    }
    return -1;

}

static char const * recordingSection = "CONFIG";

/*
bool LoadAllHelper(std::istream * s)
{
    tString line;

    // read line from recording
    if ( s || !tRecorder::Playback( recordingSection, line ) )
    {
        // return on failure
        if (!s)
            return false;

        // read line from stream
        line.ReadLine( *s );

        // write line to recording
        tRecorder::Record( recordingSection, line );
    }
    line << '\n';

    // process line
    std::stringstream str(static_cast< char const * >( line ) );
    tConfItemBase::LoadLine(str);

    return true;
}
*/

// test if a line should enter the recording; check if the line contains one of the passed
// substrings. The array of substrings is supposed to be zero terminated.
static bool s_Veto( tString line_in, std::vector< tString > const & vetos )
{
    // make name uppercase:
    tToUpper( line_in );

    // eat whitespace at the beginning
    char const * test = line_in;
    while( isblank(*test) )
        test++;

    // skip "LAST_"
    tString line( test );
    if ( line.StartsWith( "LAST_" ) )
        line = tString( static_cast< char const * >(line) + 5 );

    // iterate throug vetoed config items and test each one
    for ( std::vector< tString >::const_iterator iter = vetos.begin(); iter != vetos.end(); ++iter )
    {
        tString const & veto = *iter;

        if ( line.StartsWith( veto ) )
        {
#ifdef DEBUG_X
            if ( !line.StartsWith( "INCLUDE" ) && tRecorder::IsRunning() )
            {
                con << "Veto on config line: " << line << "\n";
            }
#endif

            return true;
        }
    }

    return false;
}

// test if a line should be read from a recording
// sound and video mode settings shold not
static std::vector< tString > st_Stringify( char const * vetos[] )
{
    std::vector< tString > ret;

    char const * * v = vetos;
    while ( *v )
    {
        ret.push_back( tString( *v ) );
        ++v;
    }

    return ret;
}

static bool s_VetoPlayback( tString const & line )
{
    static char const * vetos_char[]=
        { "USE_DISPLAYLISTS", "CHECK_ERRORS", "ZDEPTH",
          "COLORDEPTH", "FULLSCREEN ", "ARMAGETRON_LAST_WINDOWSIZE",
          "ARMAGETRON_WINDOWSIZE", "ARMAGETRON_LAST_SCREENMODE",
          "ARMAGETRON_SCREENMODE", "CUSTOM_SCREEN", "SOUND",
          "PASSWORD", "ADMIN_PASS",
          "ZTRICK", "MOUSE_GRAB", "PNG_SCREENSHOT", // "WHITE_SPARKS", "SPARKS",
          "KEEP_WINDOW_ACTIVE", "TEXTURE_MODE", "TEXTURES_HI", "LAG_O_METER", "INFINITY_PLANE",
          "SKY_WOBBLE", "LOWER_SKY", "UPPER_SKY", "DITHER", "HIGH_RIM", "FLOOR_DETAIL",
          "FLOOR_MIRROR", "SHOW_FPS", "TEXT_OUT", "SMOOTH_SHADING", "ALPHA_BLEND",
          "PERSP_CORRECT", "POLY_ANTIALIAS", "LINE_ANTIALIAS", "FAST_FORWARD_MAXSTEP",
          "DEBUG_GNUPLOT", "FLOOR_", "MOVIEPACK_", "RIM_WALL_",
          0 };

    static std::vector< tString > vetos = st_Stringify( vetos_char );

    // delegate
    return s_Veto( line, vetos );
}

// test if a line should enter the recording
// passwords should not.
static bool s_VetoRecording( tString const & line )
{
    static char const * vetos_char[]=
        { "#", "PASSWORD", "ADMIN_PASS", "LOCAL_USER", "LOCAL_TEAM",
          0 };

    static std::vector< tString > vetos = st_Stringify( vetos_char );

    // delegate
    return s_Veto( line, vetos ) || s_VetoPlayback( line );
}


//! @param s        stream to read from
//! @param record   set to true if the configuration is to be recorded and played back. That's usually only required if s is a file stream.
void tConfItemBase::LoadAll(std::istream &s, bool record ){
    tCurrentAccessLevel levelResetter;

    try{

    while(!s.eof() && s.good())
    {
        tString line;

        // read line from stream
        line.ReadLine( s );

        /// concatenate lines ending in a backslash
        while ( line.Len() > 1 && line[line.Len()-2] == '\\' && s.good() && !s.eof() )
        {
            line[line.Len()-2] = '\0';

            // unless it is a double backslash
            if ( line.Len() > 2 && line[line.Len()-3] == '\\' )
            {
                break;
            }

            line.SetLen( line.Len()-1 );
            tString rest;
            rest.ReadLine( s );
            line << rest;
        }

        if ( line.Len() <= 1 )
            continue;

        // write line to recording
        if ( record && !s_VetoRecording( line ) )
        {
            // don't record supid admins' instant chat logins
            static tString instantChat("INSTANT_CHAT_STRING");
            if ( line.StartsWith( instantChat ) && strstr( line, "/login" ) )
            {
                tString newLine = line.SubStr( 0, strstr( line, "/login" ) - (char const *)line );
                newLine += "/login NONE";
                if ( line[strlen(line)-1] == '\\' )
                    newLine += '\\';
                tRecorder::Record( recordingSection, newLine );
            }
            else
                tRecorder::Record( recordingSection, line );
        }

        //        std::cout << line << '\n';

        // process line
        // line << '\n';
        if ( !record || !tRecorder::IsPlayingBack() || s_VetoPlayback( line ) )
        {
            std::stringstream str(static_cast< char const * >( line ) );
            tConfItemBase::LoadLine(str);
            // std::cout << line << '\n';
        }
    }
    }
    catch( tAbortLoading const & e )
    {
        // loading was aborted
        con << e.GetDescription() << "\n";
    }
}

void tConfItemBase::DocAll(std::ostream &s){
    tConfItemMap & confmap = ConfItemMap();
    for(tConfItemMap::iterator iter = confmap.begin(); iter != confmap.end() ; ++iter)
    {
        tConfItemBase * ci = (*iter).second;

        tString help ( ci->help );
        if ( help != "UNDOCUMENTED" )
        {
            tString line;
            line << ci->title;
            line.SetPos( 30, false );
            line << help;
            s << line << '\n';
        }
    }
}

//! @param s        stream to read from
//! @param record   set to true if the configuration is to be recorded and played back. That's usually only required if s is a file stream, so it defaults to true here.
void tConfItemBase::LoadAll(std::ifstream &s, bool record )
{
    std::istream &ss(s);
    LoadAll( ss, record );
}


//! @param s        file stream to be used for reading later
//! @param filename name of the file to open
//! @param path     whether to look in var directory
//! @return success flag
bool tConfItemBase::OpenFile( std::ifstream & s, tString const & filename, SearchPath path )
{
    bool ret = ( ( path & Config ) && tDirectories::Config().Open(s, filename ) ) || ( ( path & Var ) && st_StringEndsWith(filename, ".cfg") && tDirectories::Var().Open(s, filename ) );

    static char const * section = "INCLUDE_VOTE";
    tRecorder::Playback( section, ret );
    tRecorder::Record( section, ret );

    return ret;
}

//! @param s        file to read from
void tConfItemBase::ReadFile( std::ifstream & s )
{
    if ( !tRecorder::IsPlayingBack() )
    {
        tConfItemBase::LoadAll(s, true );
    }
    else
    {
        tConfItemBase::LoadPlayback();
    }
}

/*
  void tConfItemBase::ReadVal(std::istream &s);
  void tConfItemBase::WriteVal(std::istream &s);
*/

/*
tString configfile(){
	tString f;
	//#ifndef WIN32
	//  f << static_cast<const char *>(getenv("HOME"));
	//  f << st_LogDir <<
	//  f << "/.ArmageTronrc";
	//#else
		const tPath& vpath = tDirectories::Var();
		for ( int prio = vpath.MaxPriority(); prio>=0; --prio )
		{
			tString path = vpath.Path( prio );
			prio = -1;

	f << st_LogDir << "/user.cfg";
	//#endif
	return f;
}
*/

bool tConfItemBase::LoadPlayback( bool print )
{
    if ( !tRecorder::IsPlayingBack() )
        return false;

    // read line from recording
    tString line;
    while ( tRecorder::Playback( recordingSection, line ) )
    {
        tRecorder::Record( recordingSection, line );
        if ( !s_VetoPlayback( line ) )
        {
            // process line
            if ( print ) con << "Playback input : " << line << '\n';
            std::stringstream str(static_cast< char const * >( line ) );
            tConfItemBase::LoadLine(str);
        }
    }

    return true;
}

static bool Load( const tPath& path, const char* filename )
{
    // read from file
    if ( !filename )
    {
        return false;
    }

    std::ifstream s;
    if ( path.Open( s, filename ) )
    {
        tConfItemBase::LoadAll( s, true );
        return true;
    }
    else
    {
        return false;
    }
}

// flag indicating whether settings were read from a playback
static bool st_settingsFromRecording = false;

#ifdef DEDICATED
tString extraConfig("NONE");

class tExtraConfigCommandLineAnalyzer: public tCommandLineAnalyzer
{
private:
    virtual bool DoAnalyze( tCommandLineParser & parser )
    {
        return parser.GetOption(extraConfig, "--extraconfig", "-e");
    }

    virtual void DoHelp( std::ostream & s )
    {                                      //
        s << "-e, --extraconfig            : open an extra configuration file after\n"
        << "                               settings_dedicated.cfg\n";
    }
};

static tExtraConfigCommandLineAnalyzer s_extraAnalyzer;
#endif

static void st_InstallSigHupHandler();

static tString st_customConfigLine = tString("");
static tSettingItem<tString> st_customConfigLineConf("CUSTOM_CONFIGS", st_customConfigLine);

//  CUSTOM_CONFIGS config1.cfg;config2.cfg;
void st_LoadCustomConfigs()
{
    if (st_customConfigLine.Filter() != "")
    {
        tArray<tString> configs = st_customConfigLine.Split(";");
        if (configs.Len() > 0)
        {
            for(int i = 0; i < configs.Len(); i++)
            {
                tString config = configs[i];

                Load(tDirectories::Config(), config);
                Load(tDirectories::Var(), config);
                Load(tDirectories::Resource(), config);
            }
        }
    }
}
static void st_LoadCustomConfigsStr(std::istream &s)
{
    st_LoadCustomConfigs();
}
static tConfItemFunc st_LoadCustomConfigsConf("LOAD_CUSTOM_CONFIGS", &st_LoadCustomConfigsStr);

void st_LoadConfig( bool printChange )
{
    // default include files are executed at owner level
    tCurrentAccessLevel level( tAccessLevel_Owner, true );

    st_InstallSigHupHandler();

    const tPath& var = tDirectories::Var();
    const tPath& config = tDirectories::Config();
    const tPath& data = tDirectories::Data();

    tConfItemBase::printChange=printChange;
#ifdef DEDICATED
    tConfItemBase::printErrors=false;
#endif
    {
        Load( var, "user.cfg" );
    }
    tConfItemBase::printErrors=true;

    Load( config, "settings.cfg" );
#ifdef DEDICATED
    Load( config, "settings_dedicated.cfg" );
    if( extraConfig != "NONE" ) Load( config, extraConfig );
#else
    if (st_FirstUse)
    {
        Load( config, "default.cfg" );
    }

    Load( config, "settings_client.cfg" );
#endif

    Load( data, "moviepack/settings.cfg" );

    Load( config, "autoexec.cfg" );
    Load( var, "autoexec.cfg" );

    st_LoadCustomConfigs();

    // load configuration from playback
    tConfItemBase::LoadPlayback();
    st_settingsFromRecording = tRecorder::IsPlayingBack();

    tConfItemBase::printChange=true;
}

static void st_ReLoadConfig(std::istream &s)
{
    st_LoadConfig(false);
}
static tConfItemFunc st_ReLoadConfigConf("RELOAD_CONFIG", &st_ReLoadConfig);
static tAccessLevelSetter st_ReLoadConfigConfLevel( st_ReLoadConfigConf, tAccessLevel_Moderator );

static bool st_UserCfgSave = true;
static tConfItem<bool> st_UserCfgSaveConf("CFG_USER_SAVE", st_UserCfgSave);

void st_SaveConfig()
{
    // don't save while playing back
    if ( st_settingsFromRecording )
    {
        return;
    }

    std::ofstream s;
    if ( tDirectories::Var().Open( s, "user.cfg", std::ios::out, true ) )
    {
        if (st_UserCfgSave)
            tConfItemBase::SaveAll(s);
    }
    else
    {
        tOutput o("$config_file_write_error");
        con << o;
        std::cerr << o;
    }
}

void st_LoadUserConfig()
{
    const tPath& var = tDirectories::Var();
    Load(var, "user.cfg");
}

void st_LoadConfig()
{
    st_LoadConfig( false );
}

static void st_DoHandleSigHup()
{
    con << tOutput("$config_sighup");
    st_SaveConfig();
    st_LoadConfig();
}

static void st_HandleSigHup( int signal )
{
    st_ToDo_Signal( st_DoHandleSigHup );
}

static void st_InstallSigHupHandler()
{
#ifndef WIN32
    static bool installed = false;
    if ( !installed )
    {
        signal( SIGHUP, &st_HandleSigHup );
        installed = true;
    }
#endif
}

void tConfItemLine::ReadVal(std::istream &s){
    tString dummy;
    dummy.ReadLine(s, true);
    if(strcmp(dummy,*target)){
        if (printChange)
        {
            tColoredString oldval;
            oldval << *target << tColoredString::ColorString(1,1,1);
            tColoredString newval;
            newval << dummy << tColoredString::ColorString(1,1,1);
            tOutput o;
            o.SetTemplateParameter(1, title);
            o.SetTemplateParameter(2, oldval);
            o.SetTemplateParameter(3, newval);
            o << "$config_value_changed";
            con << o;
        }
        *target=dummy;
        changed=true;
    }

    *target=dummy;
}


void tConfItemLine::WriteVal(std::ostream &s){
    tConfItem<tString>::WriteVal(s);

    // double trailing backslash so it is read back as a single backslash, not
    // a continued line (HACK: this would actually be the job of the calling function)
    if ( target->Len() >= 2 &&
            target->operator()(target->Len() - 2) == '\\' )
        s << "\\";
}

tConfItemFunc::tConfItemFunc
(const char *title, CONF_FUNC *func)
    :tConfItemBase(title),f(func){}

tConfItemFunc::~tConfItemFunc(){}

void tConfItemFunc::ReadVal(std::istream &s){(*f)(s);}
void tConfItemFunc::WriteVal(std::ostream &){}
void tConfItemFunc::FetchVal(tString &val){}

bool tConfItemFunc::Save(){return false;}

void st_Include( tString const & file )
{
    // refuse to load illegal paths
    if( !tPath::IsValidPath( file ) )
        return;

    if ( !tRecorder::IsPlayingBack() )
    {
        // really load include file
        if ( !file.EndsWith(".cfg") || !Load( tDirectories::Var(), file ) )
        {
            if (!Load( tDirectories::Config(), file ) && tConfItemBase::printErrors )
            {
                con << tOutput( "$config_include_not_found", file );
            }
        }
    }
    else
    {
        // just read configuration, and don't forget to reset the config level
        tCurrentAccessLevel levelResetter;
        tConfItemBase::LoadPlayback();
    }

    // mark section
    char const * section = "INCLUDE_END";
    tRecorder::Record( section );
    tRecorder::PlaybackStrict( section );

}

static void Include(std::istream& s, bool error )
{
    // allow CASACL
    tCasaclPreventer allower(false);

    tString file;
    s >> file;

    // refuse to load illegal paths
    if( !tPath::IsValidPath( file ) )
        return;

    if ( !tRecorder::IsPlayingBack() )
    {
        // really load include file
        if ( !st_StringEndsWith(file, ".cfg") || !Load( tDirectories::Var(), file ) )
        {
            if (!Load( tDirectories::Config(), file ) && error )
            {
                con << tOutput( "$config_include_not_found", file );
            }
        }
    }
    else
    {
        // just read configuration, and don't forget to reset the config level
        tCurrentAccessLevel levelResetter;
        tConfItemBase::LoadPlayback();
    }

    // mark section
    char const * section = "INCLUDE_END";
    tRecorder::Record( section );
    tRecorder::PlaybackStrict( section );

}

static void Include(std::istream& s )
{
    Include( s, true );
}

static void SInclude(std::istream& s )
{
    Include( s, false );
}

static tConfItemFunc s_Include("INCLUDE",  &Include);
static tConfItemFunc s_SInclude("SINCLUDE",  &SInclude);

// obsoleted settings that still are around in some distruted configuration files
static void st_Dummy(std::istream &s){tString rest; rest.ReadLine(s);}
static tConfItemFunc st_DummyMpHack("MOVIEPACK_HACK",&st_Dummy);

#ifdef DEDICATED
// settings missing in the dedicated server
static tConfItemFunc st_Dummy1("ARENA_WALL_SHADOW_NEAR", &st_Dummy);
static tConfItemFunc st_Dummy2("ARENA_WALL_SHADOW_DIST", &st_Dummy);
static tConfItemFunc st_Dummy3("ARENA_WALL_SHADOW_SIDEDIST", &st_Dummy);
static tConfItemFunc st_Dummy4("ARENA_WALL_SHADOW_SIZE", &st_Dummy);
static tConfItemFunc st_Dummy5("BUG_TRANSPARENCY_DEMAND", &st_Dummy);
static tConfItemFunc st_Dummy6("BUG_TRANSPARENCY", &st_Dummy);
static tConfItemFunc st_Dummy7("SHOW_OWN_NAME", &st_Dummy);
static tConfItemFunc st_Dummy8("FADEOUT_NAME_DELAY", &st_Dummy);
static tConfItemFunc st_Dummy9("FLOOR_MIRROR_INT", &st_Dummy);
#endif
#ifndef DEBUG
// settings missing in optimized mode
static tConfItemFunc st_Dummy10("SIMULATE_RECEIVE_PACKET_LOSS", &st_Dummy);
static tConfItemFunc st_Dummy11("SIMULATE_SEND_PACKET_LOSS", &st_Dummy);
#endif