]> git.mxchange.org Git - flightgear.git/blob - src/Main/options.cxx
ee3b3aafaf1367676b4b355bb33eb63dc32ef636
[flightgear.git] / src / Main / options.cxx
1 // options.cxx -- class to handle command line options
2 //
3 // Written by Curtis Olson, started April 1998.
4 //
5 // Copyright (C) 1998  Curtis L. Olson  - http://www.flightgear.org/~curt
6 //
7 // This program is free software; you can redistribute it and/or
8 // modify it under the terms of the GNU General Public License as
9 // published by the Free Software Foundation; either version 2 of the
10 // License, or (at your option) any later version.
11 //
12 // This program is distributed in the hope that it will be useful, but
13 // WITHOUT ANY WARRANTY; without even the implied warranty of
14 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 // General Public License for more details.
16 //
17 // You should have received a copy of the GNU General Public License
18 // along with this program; if not, write to the Free Software
19 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
20 //
21 // $Id$
22
23
24 #ifdef HAVE_CONFIG_H
25 #  include <config.h>
26 #endif
27
28 #include <simgear/compiler.h>
29 #include <simgear/structure/exception.hxx>
30 #include <simgear/debug/logstream.hxx>
31 #include <simgear/timing/sg_time.hxx>
32 #include <simgear/misc/sg_dir.hxx>
33
34 #include <boost/foreach.hpp>
35
36 #include <cmath>        // rint()
37 #include <stdio.h>
38 #include <stdlib.h>     // atof(), atoi()
39 #include <string.h>     // strcmp()
40 #include <algorithm>
41
42 #include <iostream>
43 #include <string>
44 #include <sstream>
45
46 #include <simgear/math/sg_random.h>
47 #include <simgear/props/props_io.hxx>
48 #include <simgear/misc/sgstream.hxx>
49 #include <simgear/misc/sg_path.hxx>
50 #include <simgear/scene/material/mat.hxx>
51 #include <simgear/sound/soundmgr_openal.hxx>
52 #include <simgear/misc/strutils.hxx>
53 #include <Autopilot/route_mgr.hxx>
54 #include <Aircraft/replay.hxx>
55
56 #include <GUI/gui.h>
57 #include <GUI/MessageBox.hxx>
58 #if defined(HAVE_QT)
59 #include <GUI/QtLauncher.hxx>
60 #include <GUI/SetupRootDialog.hxx>
61 #endif
62
63 #include <Main/locale.hxx>
64 #include "globals.hxx"
65 #include "fg_init.hxx"
66 #include "fg_props.hxx"
67 #include "options.hxx"
68 #include "util.hxx"
69 #include "main.hxx"
70 #include "locale.hxx"
71 #include <Viewer/viewer.hxx>
72 #include <Viewer/viewmgr.hxx>
73 #include <Environment/presets.hxx>
74 #include <Network/http/httpd.hxx>
75 #include "AircraftDirVisitorBase.hxx"
76
77 #include <osg/Version>
78 #include <Include/version.h>
79 #include <simgear/version.h>
80
81 using std::string;
82 using std::sort;
83 using std::cout;
84 using std::cerr;
85 using std::endl;
86 using std::vector;
87 using std::cin;
88
89 using namespace flightgear;
90
91 #define NEW_DEFAULT_MODEL_HZ 120
92
93 static flightgear::Options* shared_instance = NULL;
94
95 static double
96 atof( const string& str )
97 {
98     return ::atof( str.c_str() );
99 }
100
101 static int
102 atoi( const string& str )
103 {
104     return ::atoi( str.c_str() );
105 }
106
107 static int fgSetupProxy( const char *arg );
108
109 /**
110  * Set a few fail-safe default property values.
111  *
112  * These should all be set in $FG_ROOT/preferences.xml, but just
113  * in case, we provide some initial sane values here. This method
114  * should be invoked *before* reading any init files.
115  */
116 void fgSetDefaults ()
117 {
118
119                                 // Position (deliberately out of range)
120     fgSetDouble("/position/longitude-deg", 9999.0);
121     fgSetDouble("/position/latitude-deg", 9999.0);
122     fgSetDouble("/position/altitude-ft", -9999.0);
123
124                                 // Orientation
125     fgSetDouble("/orientation/heading-deg", 9999.0);
126     fgSetDouble("/orientation/roll-deg", 0.0);
127     fgSetDouble("/orientation/pitch-deg", 0.424);
128
129                                 // Velocities
130     fgSetDouble("/velocities/uBody-fps", 0.0);
131     fgSetDouble("/velocities/vBody-fps", 0.0);
132     fgSetDouble("/velocities/wBody-fps", 0.0);
133     fgSetDouble("/velocities/speed-north-fps", 0.0);
134     fgSetDouble("/velocities/speed-east-fps", 0.0);
135     fgSetDouble("/velocities/speed-down-fps", 0.0);
136     fgSetDouble("/velocities/airspeed-kt", 0.0);
137     fgSetDouble("/velocities/mach", 0.0);
138
139                                 // Presets
140     fgSetDouble("/sim/presets/longitude-deg", 9999.0);
141     fgSetDouble("/sim/presets/latitude-deg", 9999.0);
142     fgSetDouble("/sim/presets/altitude-ft", -9999.0);
143
144     fgSetDouble("/sim/presets/heading-deg", 9999.0);
145     fgSetDouble("/sim/presets/roll-deg", 0.0);
146     fgSetDouble("/sim/presets/pitch-deg", 0.424);
147
148     fgSetString("/sim/presets/speed-set", "knots");
149     fgSetDouble("/sim/presets/airspeed-kt", 0.0);
150     fgSetDouble("/sim/presets/mach", 0.0);
151     fgSetDouble("/sim/presets/uBody-fps", 0.0);
152     fgSetDouble("/sim/presets/vBody-fps", 0.0);
153     fgSetDouble("/sim/presets/wBody-fps", 0.0);
154     fgSetDouble("/sim/presets/speed-north-fps", 0.0);
155     fgSetDouble("/sim/presets/speed-east-fps", 0.0);
156     fgSetDouble("/sim/presets/speed-down-fps", 0.0);
157
158     fgSetBool("/sim/presets/onground", true);
159     fgSetBool("/sim/presets/trim", false);
160
161                                 // Miscellaneous
162     fgSetBool("/sim/startup/splash-screen", true);
163     // we want mouse-pointer to have an undefined value if nothing is
164     // specified so we can do the right thing for voodoo-1/2 cards.
165     // fgSetString("/sim/startup/mouse-pointer", "disabled");
166     fgSetBool("/controls/flight/auto-coordination", false);
167     fgSetString("/sim/logging/priority", "alert");
168
169                                 // Features
170     fgSetBool("/sim/hud/color/antialiased", false);
171     fgSetBool("/sim/hud/enable3d[1]", true);
172     fgSetBool("/sim/hud/visibility[1]", false);
173     fgSetBool("/sim/panel/visibility", true);
174     fgSetBool("/sim/sound/enabled", true);
175     fgSetBool("/sim/sound/working", true);
176     fgSetBool("/sim/fgcom/enabled", false);
177
178                                 // Flight Model options
179     fgSetString("/sim/flight-model", "jsb");
180     fgSetString("/sim/aero", "c172");
181     fgSetInt("/sim/model-hz", NEW_DEFAULT_MODEL_HZ);
182     fgSetDouble("/sim/speed-up", 1.0);
183
184                                 // Rendering options
185     fgSetString("/sim/rendering/fog", "nicest");
186     fgSetBool("/environment/clouds/status", true);
187     fgSetBool("/sim/startup/fullscreen", false);
188     fgSetBool("/sim/rendering/shading", true);
189     fgTie( "/sim/rendering/filtering", SGGetTextureFilter, SGSetTextureFilter, false);
190     fgSetInt("/sim/rendering/filtering", 1);
191     fgSetBool("/sim/rendering/wireframe", false);
192     fgSetBool("/sim/rendering/horizon-effect", false);
193     fgSetBool("/sim/rendering/enhanced-lighting", false);
194     fgSetBool("/sim/rendering/distance-attenuation", false);
195     fgSetBool("/sim/rendering/specular-highlight", true);
196     fgSetString("/sim/rendering/materials-file", "materials.xml");
197     fgSetInt("/sim/startup/xsize", 1024);
198     fgSetInt("/sim/startup/ysize", 768);
199     fgSetInt("/sim/rendering/bits-per-pixel", 32);
200     fgSetString("/sim/view-mode", "pilot");
201     fgSetDouble("/sim/current-view/heading-offset-deg", 0);
202
203                                 // HUD options
204     fgSetString("/sim/startup/units", "feet");
205     fgSetString("/sim/hud/frame-stat-type", "tris");
206
207                                 // Time options
208     fgSetInt("/sim/startup/time-offset", 0);
209     fgSetString("/sim/startup/time-offset-type", "system-offset");
210     fgSetLong("/sim/time/cur-time-override", 0);
211
212                                 // Freeze options
213     fgSetBool("/sim/freeze/master", false);
214     fgSetBool("/sim/freeze/position", false);
215     fgSetBool("/sim/freeze/clock", false);
216     fgSetBool("/sim/freeze/fuel", false);
217
218     fgSetString("/sim/multiplay/callsign", "callsign");
219     fgSetString("/sim/multiplay/rxhost", "");
220     fgSetString("/sim/multiplay/txhost", "");
221     fgSetInt("/sim/multiplay/rxport", 0);
222     fgSetInt("/sim/multiplay/txport", 0);
223     
224     SGPropertyNode* v = globals->get_props()->getNode("/sim/version", true);
225     v->setValueReadOnly("flightgear", FLIGHTGEAR_VERSION);
226     v->setValueReadOnly("simgear", SG_STRINGIZE(SIMGEAR_VERSION));
227     v->setValueReadOnly("openscenegraph", osgGetVersion());
228     v->setValueReadOnly("openscenegraph-thread-safe-reference-counting",
229                          osg::Referenced::getThreadSafeReferenceCounting());
230     v->setValueReadOnly("revision", REVISION);
231     v->setValueReadOnly("build-number", HUDSON_BUILD_NUMBER);
232     v->setValueReadOnly("build-id", HUDSON_BUILD_ID);
233     v->setValueReadOnly("hla-support", bool(FG_HAVE_HLA));
234
235     char* envp = ::getenv( "http_proxy" );
236     if( envp != NULL )
237       fgSetupProxy( envp );
238 }
239
240 ///////////////////////////////////////////////////////////////////////////////
241 // helper object to implement the --show-aircraft command.
242 // resides here so we can share the fgFindAircraftInDir template above,
243 // and hence ensure this command lists exectly the same aircraft as the normal
244 // loading path.
245 class ShowAircraft : public AircraftDirVistorBase
246 {
247 public:
248     ShowAircraft()
249     {
250         _minStatus = getNumMaturity(fgGetString("/sim/aircraft-min-status", "all"));
251     }
252     
253     
254     void show(const SGPath& path)
255     {
256         visitDir(path, 0);
257         
258         simgear::requestConsole(); // ensure console is shown on Windows
259         
260         std::sort(_aircraft.begin(), _aircraft.end(), ciLessLibC());
261         cout << "Available aircraft:" << endl;
262         for ( unsigned int i = 0; i < _aircraft.size(); i++ ) {
263             cout << _aircraft[i] << endl;
264         }
265     }
266     
267 private:
268     virtual VisitResult visit(const SGPath& path)
269     {
270         SGPropertyNode root;
271         try {
272             readProperties(path.str(), &root);
273         } catch (sg_exception& ) {
274             return VISIT_CONTINUE;
275         }
276         
277         int maturity = 0;
278         string descStr("   ");
279         descStr += path.file();
280         // trim common suffix from file names
281         int nPos = descStr.rfind("-set.xml");
282         if (nPos == (int)(descStr.size() - 8)) {
283             descStr.resize(nPos);
284         }
285         
286         SGPropertyNode *node = root.getNode("sim");
287         if (node) {
288             SGPropertyNode* desc = node->getNode("description");
289             // if a status tag is found, read it in
290             if (node->hasValue("status")) {
291                 maturity = getNumMaturity(node->getStringValue("status"));
292             }
293             
294             if (desc) {
295                 if (descStr.size() <= 27+3) {
296                     descStr.append(29+3-descStr.size(), ' ');
297                 } else {
298                     descStr += '\n';
299                     descStr.append( 32, ' ');
300                 }
301                 descStr += desc->getStringValue();
302             }
303         } // of have 'sim' node
304         
305         if (maturity >= _minStatus) {
306             _aircraft.push_back(descStr);
307         }
308         
309         return VISIT_CONTINUE;
310     }
311     
312     
313     int getNumMaturity(const char * str)
314     {
315         // changes should also be reflected in $FG_ROOT/data/options.xml &
316         // $FG_ROOT/data/Translations/string-default.xml
317         const char* levels[] = {"alpha","beta","early-production","production"};
318         
319         if (!strcmp(str, "all")) {
320             return 0;
321         }
322         
323         for (size_t i=0; i<(sizeof(levels)/sizeof(levels[0]));i++)
324             if (strcmp(str,levels[i])==0)
325                 return i;
326         
327         return 0;
328     }
329     
330     // recommended in Meyers, Effective STL when internationalization and embedded
331     // NULLs aren't an issue.  Much faster than the STL or Boost lex versions.
332     struct ciLessLibC : public std::binary_function<string, string, bool>
333     {
334         bool operator()(const std::string &lhs, const std::string &rhs) const
335         {
336             return strcasecmp(lhs.c_str(), rhs.c_str()) < 0 ? 1 : 0;
337         }
338     };
339     
340     int _minStatus;
341     string_list _aircraft;
342 };
343
344 /*
345  * Search in the current directory, and in on directory deeper
346  * for <aircraft>-set.xml configuration files and show the aircaft name
347  * and the contents of the<description> tag in a sorted manner.
348  *
349  * @parampath the directory to search for configuration files
350  */
351 void fgShowAircraft(const SGPath &path)
352 {
353     ShowAircraft s;
354     s.show(path);
355     
356 #ifdef _MSC_VER
357     cout << "Hit a key to continue..." << endl;
358     std::cin.get();
359 #endif
360 }
361
362
363 static bool
364 parse_wind (const string &wind, double * min_hdg, double * max_hdg,
365             double * speed, double * gust)
366 {
367   string::size_type pos = wind.find('@');
368   if (pos == string::npos)
369     return false;
370   string dir = wind.substr(0, pos);
371   string spd = wind.substr(pos+1);
372   pos = dir.find(':');
373   if (pos == string::npos) {
374     *min_hdg = *max_hdg = atof(dir.c_str());
375   } else {
376     *min_hdg = atof(dir.substr(0,pos).c_str());
377     *max_hdg = atof(dir.substr(pos+1).c_str());
378   }
379   pos = spd.find(':');
380   if (pos == string::npos) {
381     *speed = *gust = atof(spd.c_str());
382   } else {
383     *speed = atof(spd.substr(0,pos).c_str());
384     *gust = atof(spd.substr(pos+1).c_str());
385   }
386   return true;
387 }
388
389 static bool
390 parseIntValue(char** ppParserPos, int* pValue,int min, int max, const char* field, const char* argument)
391 {
392     if ( !strlen(*ppParserPos) )
393         return true;
394
395     char num[256];
396     int i = 0;
397
398     while ( isdigit((*ppParserPos)[0]) && (i<255) )
399     {
400         num[i] = (*ppParserPos)[0];
401         (*ppParserPos)++;
402         i++;
403     }
404     num[i] = '\0';
405
406     switch ((*ppParserPos)[0])
407     {
408         case 0:
409             break;
410         case ':':
411             (*ppParserPos)++;
412             break;
413         default:
414             SG_LOG(SG_GENERAL, SG_ALERT, "Illegal character in time string for " << field << ": '" <<
415                     (*ppParserPos)[0] << "'.");
416             // invalid field - skip rest of string to avoid further errors
417             while ((*ppParserPos)[0])
418                 (*ppParserPos)++;
419             return false;
420     }
421
422     if (i<=0)
423         return true;
424
425     int value = atoi(num);
426     if ((value < min)||(value > max))
427     {
428         SG_LOG(SG_GENERAL, SG_ALERT, "Invalid " << field << " in '" << argument <<
429                "'. Valid range is " << min << "-" << max << ".");
430         return false;
431     }
432     else
433     {
434         *pValue = value;
435         return true;
436     }
437 }
438
439 // parse a time string ([+/-]%f[:%f[:%f]]) into hours
440 static double
441 parse_time(const string& time_in) {
442     char *time_str, num[256];
443     double hours, minutes, seconds;
444     double result = 0.0;
445     int sign = 1;
446     int i;
447
448     time_str = (char *)time_in.c_str();
449
450     // printf("parse_time(): %s\n", time_str);
451
452     // check for sign
453     if ( strlen(time_str) ) {
454         if ( time_str[0] == '+' ) {
455             sign = 1;
456             time_str++;
457         } else if ( time_str[0] == '-' ) {
458             sign = -1;
459             time_str++;
460         }
461     }
462     // printf("sign = %d\n", sign);
463
464     // get hours
465     if ( strlen(time_str) ) {
466         i = 0;
467         while ( (time_str[0] != ':') && (time_str[0] != '\0') ) {
468             num[i] = time_str[0];
469             time_str++;
470             i++;
471         }
472         if ( time_str[0] == ':' ) {
473             time_str++;
474         }
475         num[i] = '\0';
476         hours = atof(num);
477         // printf("hours = %.2lf\n", hours);
478
479         result += hours;
480     }
481
482     // get minutes
483     if ( strlen(time_str) ) {
484         i = 0;
485         while ( (time_str[0] != ':') && (time_str[0] != '\0') ) {
486             num[i] = time_str[0];
487             time_str++;
488             i++;
489         }
490         if ( time_str[0] == ':' ) {
491             time_str++;
492         }
493         num[i] = '\0';
494         minutes = atof(num);
495         // printf("minutes = %.2lf\n", minutes);
496
497         result += minutes / 60.0;
498     }
499
500     // get seconds
501     if ( strlen(time_str) ) {
502         i = 0;
503         while ( (time_str[0] != ':') && (time_str[0] != '\0') ) {
504             num[i] = time_str[0];
505             time_str++;
506             i++;
507         }
508         num[i] = '\0';
509         seconds = atof(num);
510         // printf("seconds = %.2lf\n", seconds);
511
512         result += seconds / 3600.0;
513     }
514
515     SG_LOG( SG_GENERAL, SG_INFO, " parse_time() = " << sign * result );
516
517     return(sign * result);
518 }
519
520 // parse a date string (yyyy:mm:dd:hh:mm:ss) into a time_t (seconds)
521 static long int
522 parse_date( const string& date, const char* timeType)
523 {
524     struct tm gmt,*pCurrentTime;
525     int year,month,day,hour,minute,second;
526     char *argument, *date_str;
527
528     SGTime CurrentTime;
529     CurrentTime.update(SGGeod(),0,0);
530
531     // FIXME This should obtain system/aircraft/GMT time depending on timeType
532     pCurrentTime = CurrentTime.getGmt();
533
534     // initialize all fields with current time
535     year   = pCurrentTime->tm_year + 1900;
536     month  = pCurrentTime->tm_mon + 1;
537     day    = pCurrentTime->tm_mday;
538     hour   = pCurrentTime->tm_hour;
539     minute = pCurrentTime->tm_min;
540     second = pCurrentTime->tm_sec;
541
542     argument = (char *)date.c_str();
543     date_str = argument;
544
545     // start with parsing year
546     if (!strlen(date_str) ||
547         !parseIntValue(&date_str,&year,0,9999,"year",argument))
548     {
549         return -1;
550     }
551
552     if (year < 1970)
553     {
554         SG_LOG(SG_GENERAL, SG_ALERT, "Invalid year '" << year << "'. Use 1970 or later.");
555         return -1;
556     }
557
558     parseIntValue(&date_str, &month,  1, 12, "month",  argument);
559     parseIntValue(&date_str, &day,    1, 31, "day",    argument);
560     parseIntValue(&date_str, &hour,   0, 23, "hour",   argument);
561     parseIntValue(&date_str, &minute, 0, 59, "minute", argument);
562     parseIntValue(&date_str, &second, 0, 59, "second", argument);
563
564     gmt.tm_sec  = second;
565     gmt.tm_min  = minute;
566     gmt.tm_hour = hour;
567     gmt.tm_mday = day;
568     gmt.tm_mon  = month - 1;
569     gmt.tm_year = year -1900;
570     gmt.tm_isdst = 0; // ignore daylight savings time for the moment
571
572     time_t theTime = sgTimeGetGMT( gmt.tm_year, gmt.tm_mon, gmt.tm_mday,
573                                    gmt.tm_hour, gmt.tm_min, gmt.tm_sec );
574
575     SG_LOG(SG_GENERAL, SG_INFO, "Configuring startup time to " << ctime(&theTime));
576
577     return (theTime);
578 }
579
580
581 // parse angle in the form of [+/-]ddd:mm:ss into degrees
582 static double
583 parse_degree( const string& degree_str) {
584     double result = parse_time( degree_str );
585
586     // printf("Degree = %.4f\n", result);
587
588     return(result);
589 }
590
591
592 // parse time offset string into seconds
593 static long int
594 parse_time_offset( const string& time_str) {
595    long int result;
596
597     // printf("time offset = %s\n", time_str);
598
599 #ifdef HAVE_RINT
600     result = (int)rint(parse_time(time_str) * 3600.0);
601 #else
602     result = (int)(parse_time(time_str) * 3600.0);
603 #endif
604
605     // printf("parse_time_offset(): %d\n", result);
606
607     return( result );
608 }
609
610
611 // Parse --fov=x.xx type option
612 static double
613 parse_fov( const string& arg ) {
614     double fov = atof(arg);
615
616     if ( fov < FG_FOV_MIN ) { fov = FG_FOV_MIN; }
617     if ( fov > FG_FOV_MAX ) { fov = FG_FOV_MAX; }
618
619     fgSetDouble("/sim/view[0]/config/default-field-of-view-deg", fov);
620
621     // printf("parse_fov(): result = %.4f\n", fov);
622
623     return fov;
624 }
625
626
627 // Parse I/O channel option
628 //
629 // Format is "--protocol=medium,direction,hz,medium_options,..."
630 //
631 //   protocol = { native, nmea, garmin, AV400, AV400Sim, fgfs, rul, pve, etc. }
632 //   medium = { serial, socket, file, etc. }
633 //   direction = { in, out, bi }
634 //   hz = number of times to process channel per second (floating
635 //        point values are ok.
636 //
637 // Serial example "--nmea=serial,dir,hz,device,baud" where
638 //
639 //  device = OS device name of serial line to be open()'ed
640 //  baud = {300, 1200, 2400, ..., 230400}
641 //
642 // Socket exacmple "--native=socket,dir,hz,machine,port,style" where
643 //
644 //  machine = machine name or ip address if client (leave empty if server)
645 //  port = port, leave empty to let system choose
646 //  style = tcp or udp
647 //
648 // File example "--garmin=file,dir,hz,filename" where
649 //
650 //  filename = file system file name
651
652 static bool
653 add_channel( const string& type, const string& channel_str ) {
654     // This check is neccessary to prevent fgviewer from segfaulting when given
655     // weird options. (It doesn't run the full initailization)
656     if(!globals->get_channel_options_list())
657     {
658         SG_LOG(SG_GENERAL, SG_ALERT, "Option " << type << "=" << channel_str
659                                      << " ignored.");
660         return false;
661     }
662     SG_LOG(SG_GENERAL, SG_INFO, "Channel string = " << channel_str );
663     globals->get_channel_options_list()->push_back( type + "," + channel_str );
664     return true;
665 }
666
667 static void
668 clearLocation ()
669 {
670     fgSetString("/sim/presets/airport-id", "");
671     fgSetString("/sim/presets/vor-id", "");
672     fgSetString("/sim/presets/ndb-id", "");
673     fgSetString("/sim/presets/carrier", "");
674     fgSetString("/sim/presets/parkpos", "");
675     fgSetString("/sim/presets/fix", "");
676 }
677
678 static int
679 fgOptVOR( const char * arg )
680 {
681     clearLocation();
682     fgSetString("/sim/presets/vor-id", arg);
683     return FG_OPTIONS_OK;
684 }
685
686 static int
687 fgOptNDB( const char * arg )
688 {
689     clearLocation();
690     fgSetString("/sim/presets/ndb-id", arg);
691     return FG_OPTIONS_OK;
692 }
693
694 static int
695 fgOptCarrier( const char * arg )
696 {
697     clearLocation();
698     fgSetString("/sim/presets/carrier", arg);
699     return FG_OPTIONS_OK;
700 }
701
702 static int
703 fgOptParkpos( const char * arg )
704 {
705     fgSetString("/sim/presets/parkpos", arg);
706     return FG_OPTIONS_OK;
707 }
708
709 static int
710 fgOptFIX( const char * arg )
711 {
712     clearLocation();
713     fgSetString("/sim/presets/fix", arg);
714     return FG_OPTIONS_OK;
715 }
716
717 static int
718 fgOptLon( const char *arg )
719 {
720     clearLocation();
721     fgSetDouble("/sim/presets/longitude-deg", parse_degree( arg ));
722     fgSetDouble("/position/longitude-deg", parse_degree( arg ));
723     return FG_OPTIONS_OK;
724 }
725
726 static int
727 fgOptLat( const char *arg )
728 {
729     clearLocation();
730     fgSetDouble("/sim/presets/latitude-deg", parse_degree( arg ));
731     fgSetDouble("/position/latitude-deg", parse_degree( arg ));
732     return FG_OPTIONS_OK;
733 }
734
735 static int
736 fgOptAltitude( const char *arg )
737 {
738     fgSetBool("/sim/presets/onground", false);
739     if ( !strcmp(fgGetString("/sim/startup/units"), "feet") )
740         fgSetDouble("/sim/presets/altitude-ft", atof( arg ));
741     else
742         fgSetDouble("/sim/presets/altitude-ft",
743                     atof( arg ) * SG_METER_TO_FEET);
744     return FG_OPTIONS_OK;
745 }
746
747 static int
748 fgOptUBody( const char *arg )
749 {
750     fgSetString("/sim/presets/speed-set", "UVW");
751     if ( !strcmp(fgGetString("/sim/startup/units"), "feet") )
752         fgSetDouble("/sim/presets/uBody-fps", atof( arg ));
753     else
754         fgSetDouble("/sim/presets/uBody-fps",
755                     atof( arg ) * SG_METER_TO_FEET);
756     return FG_OPTIONS_OK;
757 }
758
759 static int
760 fgOptVBody( const char *arg )
761 {
762     fgSetString("/sim/presets/speed-set", "UVW");
763     if ( !strcmp(fgGetString("/sim/startup/units"), "feet") )
764         fgSetDouble("/sim/presets/vBody-fps", atof( arg ));
765     else
766         fgSetDouble("/sim/presets/vBody-fps",
767                             atof( arg ) * SG_METER_TO_FEET);
768     return FG_OPTIONS_OK;
769 }
770
771 static int
772 fgOptWBody( const char *arg )
773 {
774     fgSetString("/sim/presets/speed-set", "UVW");
775     if ( !strcmp(fgGetString("/sim/startup/units"), "feet") )
776         fgSetDouble("/sim/presets/wBody-fps", atof(arg));
777     else
778         fgSetDouble("/sim/presets/wBody-fps",
779                             atof(arg) * SG_METER_TO_FEET);
780     return FG_OPTIONS_OK;
781 }
782
783 static int
784 fgOptVNorth( const char *arg )
785 {
786     fgSetString("/sim/presets/speed-set", "NED");
787     if ( !strcmp(fgGetString("/sim/startup/units"), "feet") )
788         fgSetDouble("/sim/presets/speed-north-fps", atof( arg ));
789     else
790         fgSetDouble("/sim/presets/speed-north-fps",
791                             atof( arg ) * SG_METER_TO_FEET);
792     return FG_OPTIONS_OK;
793 }
794
795 static int
796 fgOptVEast( const char *arg )
797 {
798     fgSetString("/sim/presets/speed-set", "NED");
799     if ( !strcmp(fgGetString("/sim/startup/units"), "feet") )
800         fgSetDouble("/sim/presets/speed-east-fps", atof(arg));
801     else
802         fgSetDouble("/sim/presets/speed-east-fps",
803                     atof(arg) * SG_METER_TO_FEET);
804     return FG_OPTIONS_OK;
805 }
806
807 static int
808 fgOptVDown( const char *arg )
809 {
810     fgSetString("/sim/presets/speed-set", "NED");
811     if ( !strcmp(fgGetString("/sim/startup/units"), "feet") )
812         fgSetDouble("/sim/presets/speed-down-fps", atof(arg));
813     else
814         fgSetDouble("/sim/presets/speed-down-fps",
815                             atof(arg) * SG_METER_TO_FEET);
816     return FG_OPTIONS_OK;
817 }
818
819 static int
820 fgOptVc( const char *arg )
821 {
822     // fgSetString("/sim/presets/speed-set", "knots");
823     // fgSetDouble("/velocities/airspeed-kt", atof(arg.substr(5)));
824     fgSetString("/sim/presets/speed-set", "knots");
825     fgSetDouble("/sim/presets/airspeed-kt", atof(arg));
826     return FG_OPTIONS_OK;
827 }
828
829 static int
830 fgOptMach( const char *arg )
831 {
832     fgSetString("/sim/presets/speed-set", "mach");
833     fgSetDouble("/sim/presets/mach", atof(arg));
834     return FG_OPTIONS_OK;
835 }
836
837 static int
838 fgOptRoc( const char *arg )
839 {
840     fgSetDouble("/sim/presets/vertical-speed-fps", atof(arg)/60);
841     return FG_OPTIONS_OK;
842 }
843
844 static int
845 fgOptFgScenery( const char *arg )
846 {
847     globals->append_fg_scenery(arg);
848     return FG_OPTIONS_OK;
849 }
850
851 static int
852 fgOptFov( const char *arg )
853 {
854     parse_fov( arg );
855     return FG_OPTIONS_OK;
856 }
857
858 static int
859 fgOptGeometry( const char *arg )
860 {
861     bool geometry_ok = true;
862     int xsize = 0, ysize = 0;
863     string geometry = arg;
864     string::size_type i = geometry.find('x');
865
866     if (i != string::npos) {
867         xsize = atoi(geometry.substr(0, i));
868         ysize = atoi(geometry.substr(i+1));
869     } else {
870         geometry_ok = false;
871     }
872
873     if ( xsize <= 0 || ysize <= 0 ) {
874         xsize = 640;
875         ysize = 480;
876         geometry_ok = false;
877     }
878
879     if ( !geometry_ok ) {
880         SG_LOG( SG_GENERAL, SG_ALERT, "Unknown geometry: " << geometry );
881         SG_LOG( SG_GENERAL, SG_ALERT,
882                 "Setting geometry to " << xsize << 'x' << ysize << '\n');
883     } else {
884         SG_LOG( SG_GENERAL, SG_INFO,
885                 "Setting geometry to " << xsize << 'x' << ysize << '\n');
886         fgSetInt("/sim/startup/xsize", xsize);
887         fgSetInt("/sim/startup/ysize", ysize);
888     }
889     return FG_OPTIONS_OK;
890 }
891
892 static int
893 fgOptBpp( const char *arg )
894 {
895     string bits_per_pix = arg;
896     if ( bits_per_pix == "16" ) {
897         fgSetInt("/sim/rendering/bits-per-pixel", 16);
898     } else if ( bits_per_pix == "24" ) {
899         fgSetInt("/sim/rendering/bits-per-pixel", 24);
900     } else if ( bits_per_pix == "32" ) {
901         fgSetInt("/sim/rendering/bits-per-pixel", 32);
902     } else {
903         SG_LOG(SG_GENERAL, SG_ALERT, "Unsupported bpp " << bits_per_pix);
904     }
905     return FG_OPTIONS_OK;
906 }
907
908 static int
909 fgOptTimeOffset( const char *arg )
910 {
911     fgSetLong("/sim/startup/time-offset",
912                 parse_time_offset( arg ));
913     fgSetString("/sim/startup/time-offset-type", "system-offset");
914     return FG_OPTIONS_OK;
915 }
916
917 static int
918 fgOptStartDateSys( const char *arg )
919 {
920     long int theTime = parse_date( arg, "system" );
921     if (theTime>=0)
922     {
923         fgSetLong("/sim/startup/time-offset",  theTime);
924         fgSetString("/sim/startup/time-offset-type", "system");
925     }
926     return FG_OPTIONS_OK;
927 }
928
929 static int
930 fgOptStartDateLat( const char *arg )
931 {
932     long int theTime = parse_date( arg, "latitude" );
933     if (theTime>=0)
934     {
935         fgSetLong("/sim/startup/time-offset", theTime);
936         fgSetString("/sim/startup/time-offset-type", "latitude");
937     }
938     return FG_OPTIONS_OK;
939 }
940
941 static int
942 fgOptStartDateGmt( const char *arg )
943 {
944     long int theTime = parse_date( arg, "gmt" );
945     if (theTime>=0)
946     {
947         fgSetLong("/sim/startup/time-offset", theTime);
948         fgSetString("/sim/startup/time-offset-type", "gmt");
949     }
950     return FG_OPTIONS_OK;
951 }
952
953 static int
954 fgOptJpgHttpd( const char * arg )
955 {
956   SG_LOG(SG_ALL,SG_ALERT,
957    "the option --jpg-httpd is no longer supported! Please use --httpd instead."
958    " URL for the screenshot within the new httpd is http://YourFgServer:xxxx/screenshot");
959   return FG_OPTIONS_EXIT;
960 }
961
962 static int
963 fgOptHttpd( const char * arg )
964 {
965     // port may be any valid address:port notation
966     // like 127.0.0.1:8080
967     // or just the port 8080
968     string port = simgear::strutils::strip(string(arg));
969     if( port.empty() ) return FG_OPTIONS_ERROR;
970     fgSetString( string(flightgear::http::PROPERTY_ROOT).append("/options/listening-port").c_str(), port );
971     return FG_OPTIONS_OK;
972 }
973
974 static int
975 fgSetupProxy( const char *arg )
976 {
977     string options = simgear::strutils::strip( arg );
978     string host, port, auth;
979     string::size_type pos;
980
981     // this is NURLP - NURLP is not an url parser
982     if( simgear::strutils::starts_with( options, "http://" ) )
983         options = options.substr( 7 );
984     if( simgear::strutils::ends_with( options, "/" ) )
985         options = options.substr( 0, options.length() - 1 );
986
987     host = port = auth = "";
988     if ((pos = options.find("@")) != string::npos)
989         auth = options.substr(0, pos++);
990     else
991         pos = 0;
992
993     host = options.substr(pos, options.size());
994     if ((pos = host.find(":")) != string::npos) {
995         port = host.substr(++pos, host.size());
996         host.erase(--pos, host.size());
997     }
998
999     fgSetString("/sim/presets/proxy/host", host.c_str());
1000     fgSetString("/sim/presets/proxy/port", port.c_str());
1001     fgSetString("/sim/presets/proxy/authentication", auth.c_str());
1002
1003     return FG_OPTIONS_OK;
1004 }
1005
1006 static int
1007 fgOptTraceRead( const char *arg )
1008 {
1009     string name = arg;
1010     SG_LOG(SG_GENERAL, SG_INFO, "Tracing reads for property " << name);
1011     fgGetNode(name.c_str(), true)
1012         ->setAttribute(SGPropertyNode::TRACE_READ, true);
1013     return FG_OPTIONS_OK;
1014 }
1015
1016 static int
1017 fgOptLogLevel( const char *arg )
1018 {
1019     fgSetString("/sim/logging/priority", arg);
1020     setLoggingPriority(arg);
1021
1022     return FG_OPTIONS_OK;
1023 }
1024
1025 static int
1026 fgOptLogClasses( const char *arg )
1027 {
1028     fgSetString("/sim/logging/classes", arg);
1029     setLoggingClasses (arg);
1030
1031     return FG_OPTIONS_OK;
1032 }
1033
1034 static int
1035 fgOptTraceWrite( const char *arg )
1036 {
1037     string name = arg;
1038     SG_LOG(SG_GENERAL, SG_INFO, "Tracing writes for property " << name);
1039     fgGetNode(name.c_str(), true)
1040         ->setAttribute(SGPropertyNode::TRACE_WRITE, true);
1041     return FG_OPTIONS_OK;
1042 }
1043
1044 static int
1045 fgOptViewOffset( const char *arg )
1046 {
1047     // $$$ begin - added VS Renganathan, 14 Oct 2K
1048     // for multi-window outside window imagery
1049     string woffset = arg;
1050     double default_view_offset = 0.0;
1051     if ( woffset == "LEFT" ) {
1052             default_view_offset = SGD_PI * 0.25;
1053     } else if ( woffset == "RIGHT" ) {
1054         default_view_offset = SGD_PI * 1.75;
1055     } else if ( woffset == "CENTER" ) {
1056         default_view_offset = 0.00;
1057     } else {
1058         default_view_offset = atof( woffset.c_str() ) * SGD_DEGREES_TO_RADIANS;
1059     }
1060     /* apparently not used (CLO, 11 Jun 2002)
1061         FGViewer *pilot_view =
1062             (FGViewer *)globals->get_viewmgr()->get_view( 0 ); */
1063     // this will work without calls to the viewer...
1064     fgSetDouble( "/sim/current-view/heading-offset-deg",
1065                     default_view_offset  * SGD_RADIANS_TO_DEGREES );
1066     // $$$ end - added VS Renganathan, 14 Oct 2K
1067     return FG_OPTIONS_OK;
1068 }
1069
1070 static int
1071 fgOptVisibilityMeters( const char *arg )
1072 {
1073     Environment::Presets::VisibilitySingleton::instance()->preset( atof( arg ) );
1074     return FG_OPTIONS_OK;
1075 }
1076
1077 static int
1078 fgOptVisibilityMiles( const char *arg )
1079 {
1080     Environment::Presets::VisibilitySingleton::instance()->preset( atof( arg ) * 5280.0 * SG_FEET_TO_METER );
1081     return FG_OPTIONS_OK;
1082 }
1083
1084 static int
1085 fgOptRandomWind( const char *arg )
1086 {
1087     double min_hdg = sg_random() * 360.0;
1088     double max_hdg = min_hdg + (20 - sqrt(sg_random() * 400));
1089     double speed = sg_random() * sg_random() * 40;
1090     double gust = speed + (10 - sqrt(sg_random() * 100));
1091     Environment::Presets::WindSingleton::instance()->preset(min_hdg, max_hdg, speed, gust);
1092     return FG_OPTIONS_OK;
1093 }
1094
1095 static int
1096 fgOptWind( const char *arg )
1097 {
1098     double min_hdg = 0.0, max_hdg = 0.0, speed = 0.0, gust = 0.0;
1099     if (!parse_wind( arg, &min_hdg, &max_hdg, &speed, &gust)) {
1100         SG_LOG( SG_GENERAL, SG_ALERT, "bad wind value " << arg );
1101         return FG_OPTIONS_ERROR;
1102     }
1103     Environment::Presets::WindSingleton::instance()->preset(min_hdg, max_hdg, speed, gust);
1104     return FG_OPTIONS_OK;
1105 }
1106
1107 static int
1108 fgOptTurbulence( const char *arg )
1109 {
1110     Environment::Presets::TurbulenceSingleton::instance()->preset( atof(arg) );
1111     return FG_OPTIONS_OK;
1112 }
1113
1114 static int
1115 fgOptCeiling( const char *arg )
1116 {
1117     double elevation, thickness;
1118     string spec = arg;
1119     string::size_type pos = spec.find(':');
1120     if (pos == string::npos) {
1121         elevation = atof(spec.c_str());
1122         thickness = 2000;
1123     } else {
1124         elevation = atof(spec.substr(0, pos).c_str());
1125         thickness = atof(spec.substr(pos + 1).c_str());
1126     }
1127     Environment::Presets::CeilingSingleton::instance()->preset( elevation, thickness );
1128     return FG_OPTIONS_OK;
1129 }
1130
1131 static int
1132 fgOptWp( const char *arg )
1133 {
1134     string_list *waypoints = globals->get_initial_waypoints();
1135     if (!waypoints) {
1136         waypoints = new string_list;
1137         globals->set_initial_waypoints(waypoints);
1138     }
1139     waypoints->push_back(arg);
1140     return FG_OPTIONS_OK;
1141 }
1142
1143 static int
1144 fgOptConfig( const char *arg )
1145 {
1146     string file = arg;
1147     try {
1148         readProperties(file, globals->get_props());
1149     } catch (const sg_exception &e) {
1150         string message = "Error loading config file: ";
1151         message += e.getFormattedMessage() + e.getOrigin();
1152         SG_LOG(SG_INPUT, SG_ALERT, message);
1153         return FG_OPTIONS_ERROR;
1154     }
1155     return FG_OPTIONS_OK;
1156 }
1157
1158 static bool
1159 parse_colon (const string &s, double * val1, double * val2)
1160 {
1161     string::size_type pos = s.find(':');
1162     if (pos == string::npos) {
1163         *val2 = atof(s);
1164         return false;
1165     } else {
1166         *val1 = atof(s.substr(0, pos).c_str());
1167         *val2 = atof(s.substr(pos+1).c_str());
1168         return true;
1169     }
1170 }
1171
1172
1173 static int
1174 fgOptFailure( const char * arg )
1175 {
1176     string a = arg;
1177     if (a == "pitot") {
1178         fgSetBool("/systems/pitot/serviceable", false);
1179     } else if (a == "static") {
1180         fgSetBool("/systems/static/serviceable", false);
1181     } else if (a == "vacuum") {
1182         fgSetBool("/systems/vacuum/serviceable", false);
1183     } else if (a == "electrical") {
1184         fgSetBool("/systems/electrical/serviceable", false);
1185     } else {
1186         SG_LOG(SG_INPUT, SG_ALERT, "Unknown failure mode: " << a);
1187         return FG_OPTIONS_ERROR;
1188     }
1189
1190     return FG_OPTIONS_OK;
1191 }
1192
1193
1194 static int
1195 fgOptNAV1( const char * arg )
1196 {
1197     double radial, freq;
1198     if (parse_colon(arg, &radial, &freq))
1199         fgSetDouble("/instrumentation/nav[0]/radials/selected-deg", radial);
1200     fgSetDouble("/instrumentation/nav[0]/frequencies/selected-mhz", freq);
1201     return FG_OPTIONS_OK;
1202 }
1203
1204 static int
1205 fgOptNAV2( const char * arg )
1206 {
1207     double radial, freq;
1208     if (parse_colon(arg, &radial, &freq))
1209         fgSetDouble("/instrumentation/nav[1]/radials/selected-deg", radial);
1210     fgSetDouble("/instrumentation/nav[1]/frequencies/selected-mhz", freq);
1211     return FG_OPTIONS_OK;
1212 }
1213
1214 static int
1215 fgOptADF1( const char * arg )
1216 {
1217     double rot, freq;
1218     if (parse_colon(arg, &rot, &freq))
1219         fgSetDouble("/instrumentation/adf[0]/rotation-deg", rot);
1220     fgSetDouble("/instrumentation/adf[0]/frequencies/selected-khz", freq);
1221     return FG_OPTIONS_OK;
1222 }
1223
1224 static int
1225 fgOptADF2( const char * arg )
1226 {
1227     double rot, freq;
1228     if (parse_colon(arg, &rot, &freq))
1229         fgSetDouble("/instrumentation/adf[1]/rotation-deg", rot);
1230     fgSetDouble("/instrumentation/adf[1]/frequencies/selected-khz", freq);
1231     return FG_OPTIONS_OK;
1232 }
1233
1234 static int
1235 fgOptDME( const char *arg )
1236 {
1237     string opt = arg;
1238     if (opt == "nav1") {
1239         fgSetInt("/instrumentation/dme/switch-position", 1);
1240         fgSetString("/instrumentation/dme/frequencies/source",
1241                     "/instrumentation/nav[0]/frequencies/selected-mhz");
1242     } else if (opt == "nav2") {
1243         fgSetInt("/instrumentation/dme/switch-position", 3);
1244         fgSetString("/instrumentation/dme/frequencies/source",
1245                     "/instrumentation/nav[1]/frequencies/selected-mhz");
1246     } else {
1247         double frequency = atof(arg);
1248         if (frequency==0.0)
1249         {
1250             SG_LOG(SG_INPUT, SG_ALERT, "Invalid DME frequency: '" << arg << "'.");
1251             return FG_OPTIONS_ERROR;
1252         }
1253         fgSetInt("/instrumentation/dme/switch-position", 2);
1254         fgSetString("/instrumentation/dme/frequencies/source",
1255                     "/instrumentation/dme/frequencies/selected-mhz");
1256         fgSetDouble("/instrumentation/dme/frequencies/selected-mhz", frequency);
1257     }
1258     return FG_OPTIONS_OK;
1259 }
1260
1261 static int
1262 fgOptLivery( const char *arg )
1263 {
1264     string opt = arg;
1265     string livery_path = "livery/" + opt;
1266     fgSetString("/sim/model/texture-path", livery_path.c_str() );
1267     return FG_OPTIONS_OK;
1268 }
1269
1270 static int
1271 fgOptScenario( const char *arg )
1272 {
1273     SGPropertyNode_ptr ai_node = fgGetNode( "/sim/ai", true );
1274     vector<SGPropertyNode_ptr> scenarii = ai_node->getChildren( "scenario" );
1275     int index = -1;
1276     for ( size_t i = 0; i < scenarii.size(); ++i ) {
1277         int ind = scenarii[i]->getIndex();
1278         if ( index < ind ) {
1279             index = ind;
1280         }
1281     }
1282     SGPropertyNode_ptr scenario = ai_node->getNode( "scenario", index + 1, true );
1283     scenario->setStringValue( arg );
1284     return FG_OPTIONS_OK;
1285 }
1286
1287 static int
1288 fgOptRunway( const char *arg )
1289 {
1290     fgSetString("/sim/presets/runway", arg );
1291     fgSetBool("/sim/presets/runway-requested", true );
1292     return FG_OPTIONS_OK;
1293 }
1294
1295 static int
1296 fgOptParking( const char *arg )
1297 {
1298     cerr << "Processing argument " << arg << endl;
1299     fgSetString("/sim/presets/parking", arg );
1300     fgSetBool  ("/sim/presets/parking-requested", true );
1301     return FG_OPTIONS_OK;
1302 }
1303
1304 static int
1305 fgOptVersion( const char *arg )
1306 {
1307     cerr << "FlightGear version: " << FLIGHTGEAR_VERSION << endl;
1308     cerr << "Revision: " << REVISION << endl;
1309     cerr << "Build-Id: " << HUDSON_BUILD_ID << endl;
1310     cerr << "FG_ROOT=" << globals->get_fg_root() << endl;
1311     cerr << "FG_HOME=" << globals->get_fg_home() << endl;
1312     cerr << "FG_SCENERY=";
1313
1314     int didsome = 0;
1315     string_list scn = globals->get_fg_scenery();
1316     for (string_list::const_iterator it = scn.begin(); it != scn.end(); it++)
1317     {
1318         if (didsome) cerr << ":";
1319         didsome++;
1320         cerr << *it;
1321     }
1322     cerr << endl;
1323     cerr << "SimGear version: " << SG_STRINGIZE(SIMGEAR_VERSION) << endl;
1324     cerr << "PLIB version: " << PLIB_VERSION << endl;
1325     return FG_OPTIONS_EXIT;
1326 }
1327
1328 static int
1329 fgOptCallSign(const char * arg)
1330 {
1331     int i;
1332     char callsign[11];
1333     strncpy(callsign,arg,10);
1334     callsign[10]=0;
1335     for (i=0;callsign[i];i++)
1336     {
1337         char c = callsign[i];
1338         if (c >= 'A' && c <= 'Z') continue;
1339         if (c >= 'a' && c <= 'z') continue;
1340         if (c >= '0' && c <= '9') continue;
1341         if (c == '-' || c == '_') continue;
1342         // convert any other illegal characters
1343         callsign[i]='-';
1344     }
1345     fgSetString("sim/multiplay/callsign", callsign );
1346     return FG_OPTIONS_OK;
1347 }
1348
1349 static int
1350 fgOptIgnoreAutosave(const char* arg)
1351 {
1352     fgSetBool("/sim/startup/ignore-autosave", true);
1353     // don't overwrite autosave on exit
1354     fgSetBool("/sim/startup/save-on-exit", false);
1355     return FG_OPTIONS_OK;
1356 }
1357
1358 // Set a property for the --prop: option. Syntax: --prop:[<type>:]<name>=<value>
1359 // <type> can be "double" etc. but also only the first letter "d".
1360 // Examples:  --prop:alpha=1  --prop:bool:beta=true  --prop:d:gamma=0.123
1361 static int
1362 fgOptSetProperty(const char* raw)
1363 {
1364   string arg(raw);
1365   string::size_type pos = arg.find('=');
1366   if (pos == arg.npos || pos == 0 || pos + 1 == arg.size())
1367     return FG_OPTIONS_ERROR;
1368   
1369   string name = arg.substr(0, pos);
1370   string value = arg.substr(pos + 1);
1371   string type;
1372   pos = name.find(':');
1373   
1374   if (pos != name.npos && pos != 0 && pos + 1 != name.size()) {
1375     type = name.substr(0, pos);
1376     name = name.substr(pos + 1);
1377   }
1378   SGPropertyNode *n = fgGetNode(name.c_str(), true);
1379   
1380   bool writable = n->getAttribute(SGPropertyNode::WRITE);
1381   if (!writable)
1382     n->setAttribute(SGPropertyNode::WRITE, true);
1383   
1384   bool ret = false;
1385   if (type.empty())
1386     ret = n->setUnspecifiedValue(value.c_str());
1387   else if (type == "s" || type == "string")
1388     ret = n->setStringValue(value.c_str());
1389   else if (type == "d" || type == "double")
1390     ret = n->setDoubleValue(strtod(value.c_str(), 0));
1391   else if (type == "f" || type == "float")
1392     ret = n->setFloatValue(atof(value.c_str()));
1393   else if (type == "l" || type == "long")
1394     ret =  n->setLongValue(strtol(value.c_str(), 0, 0));
1395   else if (type == "i" || type == "int")
1396     ret =  n->setIntValue(atoi(value.c_str()));
1397   else if (type == "b" || type == "bool")
1398     ret =  n->setBoolValue(value == "true" || atoi(value.c_str()) != 0);
1399   
1400   if (!writable)
1401     n->setAttribute(SGPropertyNode::WRITE, false);
1402   return ret ? FG_OPTIONS_OK : FG_OPTIONS_ERROR;
1403 }
1404
1405 static int
1406 fgOptLoadTape(const char* arg)
1407 {
1408   // load a flight recorder tape but wait until the fdm is initialized
1409   class DelayedTapeLoader : SGPropertyChangeListener {
1410   public:
1411     DelayedTapeLoader( const char * tape ) :
1412       _tape(tape)
1413     {
1414       SGPropertyNode_ptr n = fgGetNode("/sim/signals/fdm-initialized", true);
1415       n->addChangeListener( this );
1416     }
1417
1418     virtual ~ DelayedTapeLoader() {}
1419
1420     virtual void valueChanged(SGPropertyNode * node) 
1421     {
1422       node->removeChangeListener( this );
1423
1424       // tell the replay subsystem to load the tape
1425       FGReplay* replay = (FGReplay*) globals->get_subsystem("replay");
1426       SGPropertyNode_ptr arg = new SGPropertyNode();
1427       arg->setStringValue("tape", _tape );
1428       arg->setBoolValue( "same-aircraft", 0 );
1429       replay->loadTape(arg);
1430
1431       delete this; // commence suicide
1432     }
1433   private:
1434     std::string _tape;
1435
1436   };
1437
1438   new DelayedTapeLoader(arg);
1439   return FG_OPTIONS_OK;
1440 }
1441
1442
1443
1444 /*
1445    option       has_param type        property         b_param s_param  func
1446
1447 where:
1448  option    : name of the option
1449  has_param : option is --name=value if true or --name if false
1450  type      : OPTION_BOOL    - property is a boolean
1451              OPTION_STRING  - property is a string
1452              OPTION_DOUBLE  - property is a double
1453              OPTION_INT     - property is an integer
1454              OPTION_CHANNEL - name of option is the name of a channel
1455              OPTION_FUNC    - the option trigger a function
1456  b_param   : if type==OPTION_BOOL,
1457              value set to the property (has_param is false for boolean)
1458  s_param   : if type==OPTION_STRING,
1459              value set to the property if has_param is false
1460  func      : function called if type==OPTION_FUNC. if has_param is true,
1461              the value is passed to the function as a string, otherwise,
1462              s_param is passed.
1463
1464     For OPTION_DOUBLE and OPTION_INT, the parameter value is converted into a
1465     double or an integer and set to the property.
1466
1467     For OPTION_CHANNEL, add_channel is called with the parameter value as the
1468     argument.
1469 */
1470
1471 enum OptionType { OPTION_BOOL = 0, OPTION_STRING, OPTION_DOUBLE, OPTION_INT, OPTION_CHANNEL, OPTION_FUNC, OPTION_IGNORE };
1472 const int OPTION_MULTI = 1 << 17;
1473
1474 struct OptionDesc {
1475     const char *option;
1476     bool has_param;
1477     int type;
1478     const char *property;
1479     bool b_param;
1480     const char *s_param;
1481     int (*func)( const char * );
1482     } fgOptionArray[] = {
1483
1484     {"language",                     true,  OPTION_IGNORE, "", false, "", 0 },
1485         {"console",                      false, OPTION_IGNORE,   "", false, "", 0 },
1486     {"launcher",                     false, OPTION_IGNORE,   "", false, "", 0 },
1487     {"disable-rembrandt",            false, OPTION_BOOL,   "/sim/rendering/rembrandt/enabled", false, "", 0 },
1488     {"enable-rembrandt",             false, OPTION_BOOL,   "/sim/rendering/rembrandt/enabled", true, "", 0 },
1489     {"renderer",                     true,  OPTION_STRING, "/sim/rendering/rembrandt/renderer", false, "", 0 },
1490     {"disable-splash-screen",        false, OPTION_BOOL,   "/sim/startup/splash-screen", false, "", 0 },
1491     {"enable-splash-screen",         false, OPTION_BOOL,   "/sim/startup/splash-screen", true, "", 0 },
1492     {"disable-mouse-pointer",        false, OPTION_STRING, "/sim/startup/mouse-pointer", false, "disabled", 0 },
1493     {"enable-mouse-pointer",         false, OPTION_STRING, "/sim/startup/mouse-pointer", false, "enabled", 0 },
1494     {"disable-random-objects",       false, OPTION_BOOL,   "/sim/rendering/random-objects", false, "", 0 },
1495     {"enable-random-objects",        false, OPTION_BOOL,   "/sim/rendering/random-objects", true, "", 0 },
1496     {"disable-random-vegetation",    false, OPTION_BOOL,   "/sim/rendering/random-vegetation", false, "", 0 },
1497     {"enable-random-vegetation",     false, OPTION_BOOL,   "/sim/rendering/random-vegetation", true, "", 0 },
1498     {"disable-random-buildings",     false, OPTION_BOOL,   "/sim/rendering/random-buildings", false, "", 0 },
1499     {"enable-random-buildings",      false, OPTION_BOOL,   "/sim/rendering/random-buildings", true, "", 0 },
1500     {"disable-real-weather-fetch",   false, OPTION_BOOL,   "/environment/realwx/enabled", false, "", 0 },
1501     {"enable-real-weather-fetch",    false, OPTION_BOOL,   "/environment/realwx/enabled", true,  "", 0 },
1502     {"metar",                        true,  OPTION_STRING, "/environment/metar/data", false, "", 0 },
1503     {"disable-ai-models",            false, OPTION_BOOL,   "/sim/ai/enabled", false, "", 0 },
1504     {"enable-ai-models",             false, OPTION_BOOL,   "/sim/ai/enabled", true, "", 0 },
1505     {"disable-ai-traffic",           false, OPTION_BOOL,   "/sim/traffic-manager/enabled", false, "", 0 },
1506     {"enable-ai-traffic",            false, OPTION_BOOL,   "/sim/traffic-manager/enabled", true,  "", 0 },
1507     {"disable-freeze",               false, OPTION_BOOL,   "/sim/freeze/master", false, "", 0 },
1508     {"enable-freeze",                false, OPTION_BOOL,   "/sim/freeze/master", true, "", 0 },
1509     {"disable-fuel-freeze",          false, OPTION_BOOL,   "/sim/freeze/fuel", false, "", 0 },
1510     {"enable-fuel-freeze",           false, OPTION_BOOL,   "/sim/freeze/fuel", true, "", 0 },
1511     {"disable-clock-freeze",         false, OPTION_BOOL,   "/sim/freeze/clock", false, "", 0 },
1512     {"enable-clock-freeze",          false, OPTION_BOOL,   "/sim/freeze/clock", true, "", 0 },
1513     {"disable-hud-3d",               false, OPTION_BOOL,   "/sim/hud/enable3d[1]", false, "", 0 },
1514     {"enable-hud-3d",                false, OPTION_BOOL,   "/sim/hud/enable3d[1]", true, "", 0 },
1515     {"disable-anti-alias-hud",       false, OPTION_BOOL,   "/sim/hud/color/antialiased", false, "", 0 },
1516     {"enable-anti-alias-hud",        false, OPTION_BOOL,   "/sim/hud/color/antialiased", true, "", 0 },
1517     {"disable-auto-coordination",    false, OPTION_BOOL,   "/controls/flight/auto-coordination", false, "", 0 },
1518     {"enable-auto-coordination",     false, OPTION_BOOL,   "/controls/flight/auto-coordination", true, "", 0 },
1519     {"browser-app",                  true,  OPTION_STRING, "/sim/startup/browser-app", false, "", 0 },
1520     {"disable-hud",                  false, OPTION_BOOL,   "/sim/hud/visibility[1]", false, "", 0 },
1521     {"enable-hud",                   false, OPTION_BOOL,   "/sim/hud/visibility[1]", true, "", 0 },
1522     {"disable-panel",                false, OPTION_BOOL,   "/sim/panel/visibility", false, "", 0 },
1523     {"enable-panel",                 false, OPTION_BOOL,   "/sim/panel/visibility", true, "", 0 },
1524     {"disable-sound",                false, OPTION_BOOL,   "/sim/sound/working", false, "", 0 },
1525     {"enable-sound",                 false, OPTION_BOOL,   "/sim/sound/working", true, "", 0 },
1526     {"sound-device",                 true,  OPTION_STRING, "/sim/sound/device-name", false, "", 0 },
1527     {"airport",                      true,  OPTION_STRING, "/sim/presets/airport-id", false, "", 0 },
1528     {"runway",                       true,  OPTION_FUNC,   "", false, "", fgOptRunway },
1529     {"vor",                          true,  OPTION_FUNC,   "", false, "", fgOptVOR },
1530     {"vor-frequency",                true,  OPTION_DOUBLE, "/sim/presets/vor-freq", false, "", fgOptVOR },
1531     {"ndb",                          true,  OPTION_FUNC,   "", false, "", fgOptNDB },
1532     {"ndb-frequency",                true,  OPTION_DOUBLE, "/sim/presets/ndb-freq", false, "", fgOptVOR },
1533     {"carrier",                      true,  OPTION_FUNC,   "", false, "", fgOptCarrier },
1534     {"parkpos",                      true,  OPTION_FUNC,   "", false, "", fgOptParkpos },
1535     {"fix",                          true,  OPTION_FUNC,   "", false, "", fgOptFIX },
1536     {"offset-distance",              true,  OPTION_DOUBLE, "/sim/presets/offset-distance-nm", false, "", 0 },
1537     {"offset-azimuth",               true,  OPTION_DOUBLE, "/sim/presets/offset-azimuth-deg", false, "", 0 },
1538     {"lon",                          true,  OPTION_FUNC,   "", false, "", fgOptLon },
1539     {"lat",                          true,  OPTION_FUNC,   "", false, "", fgOptLat },
1540     {"altitude",                     true,  OPTION_FUNC,   "", false, "", fgOptAltitude },
1541     {"uBody",                        true,  OPTION_FUNC,   "", false, "", fgOptUBody },
1542     {"vBody",                        true,  OPTION_FUNC,   "", false, "", fgOptVBody },
1543     {"wBody",                        true,  OPTION_FUNC,   "", false, "", fgOptWBody },
1544     {"vNorth",                       true,  OPTION_FUNC,   "", false, "", fgOptVNorth },
1545     {"vEast",                        true,  OPTION_FUNC,   "", false, "", fgOptVEast },
1546     {"vDown",                        true,  OPTION_FUNC,   "", false, "", fgOptVDown },
1547     {"vc",                           true,  OPTION_FUNC,   "", false, "", fgOptVc },
1548     {"mach",                         true,  OPTION_FUNC,   "", false, "", fgOptMach },
1549     {"heading",                      true,  OPTION_DOUBLE, "/sim/presets/heading-deg", false, "", 0 },
1550     {"roll",                         true,  OPTION_DOUBLE, "/sim/presets/roll-deg", false, "", 0 },
1551     {"pitch",                        true,  OPTION_DOUBLE, "/sim/presets/pitch-deg", false, "", 0 },
1552     {"glideslope",                   true,  OPTION_DOUBLE, "/sim/presets/glideslope-deg", false, "", 0 },
1553     {"roc",                          true,  OPTION_FUNC,   "", false, "", fgOptRoc },
1554     {"fg-root",                      true,  OPTION_IGNORE,   "", false, "", 0 },
1555     {"fg-scenery",                   true,  OPTION_FUNC | OPTION_MULTI,   "", false, "", fgOptFgScenery },
1556     {"fg-aircraft",                  true,  OPTION_IGNORE | OPTION_MULTI,   "", false, "", 0 },
1557     {"fdm",                          true,  OPTION_STRING, "/sim/flight-model", false, "", 0 },
1558     {"aero",                         true,  OPTION_STRING, "/sim/aero", false, "", 0 },
1559     {"aircraft-dir",                 true,  OPTION_IGNORE,   "", false, "", 0 },
1560     {"model-hz",                     true,  OPTION_INT,    "/sim/model-hz", false, "", 0 },
1561     {"max-fps",                      true,  OPTION_DOUBLE, "/sim/frame-rate-throttle-hz", false, "", 0 },
1562     {"speed",                        true,  OPTION_DOUBLE, "/sim/speed-up", false, "", 0 },
1563     {"trim",                         false, OPTION_BOOL,   "/sim/presets/trim", true, "", 0 },
1564     {"notrim",                       false, OPTION_BOOL,   "/sim/presets/trim", false, "", 0 },
1565     {"on-ground",                    false, OPTION_BOOL,   "/sim/presets/onground", true, "", 0 },
1566     {"in-air",                       false, OPTION_BOOL,   "/sim/presets/onground", false, "", 0 },
1567     {"fog-disable",                  false, OPTION_STRING, "/sim/rendering/fog", false, "disabled", 0 },
1568     {"fog-fastest",                  false, OPTION_STRING, "/sim/rendering/fog", false, "fastest", 0 },
1569     {"fog-nicest",                   false, OPTION_STRING, "/sim/rendering/fog", false, "nicest", 0 },
1570     {"disable-horizon-effect",       false, OPTION_BOOL,   "/sim/rendering/horizon-effect", false, "", 0 },
1571     {"enable-horizon-effect",        false, OPTION_BOOL,   "/sim/rendering/horizon-effect", true, "", 0 },
1572     {"disable-enhanced-lighting",    false, OPTION_BOOL,   "/sim/rendering/enhanced-lighting", false, "", 0 },
1573     {"enable-enhanced-lighting",     false, OPTION_BOOL,   "/sim/rendering/enhanced-lighting", true, "", 0 },
1574     {"disable-distance-attenuation", false, OPTION_BOOL,   "/sim/rendering/distance-attenuation", false, "", 0 },
1575     {"enable-distance-attenuation",  false, OPTION_BOOL,   "/sim/rendering/distance-attenuation", true, "", 0 },
1576     {"disable-specular-highlight",   false, OPTION_BOOL,   "/sim/rendering/specular-highlight", false, "", 0 },
1577     {"enable-specular-highlight",    false, OPTION_BOOL,   "/sim/rendering/specular-highlight", true, "", 0 },
1578     {"disable-clouds",               false, OPTION_BOOL,   "/environment/clouds/status", false, "", 0 },
1579     {"enable-clouds",                false, OPTION_BOOL,   "/environment/clouds/status", true, "", 0 },
1580     {"disable-clouds3d",             false, OPTION_BOOL,   "/sim/rendering/clouds3d-enable", false, "", 0 },
1581     {"enable-clouds3d",              false, OPTION_BOOL,   "/sim/rendering/clouds3d-enable", true, "", 0 },
1582     {"fov",                          true,  OPTION_FUNC,   "", false, "", fgOptFov },
1583     {"aspect-ratio-multiplier",      true,  OPTION_DOUBLE, "/sim/current-view/aspect-ratio-multiplier", false, "", 0 },
1584     {"disable-fullscreen",           false, OPTION_BOOL,   "/sim/startup/fullscreen", false, "", 0 },
1585     {"enable-fullscreen",            false, OPTION_BOOL,   "/sim/startup/fullscreen", true, "", 0 },
1586     {"disable-save-on-exit",         false, OPTION_BOOL,   "/sim/startup/save-on-exit", false, "", 0 },
1587     {"enable-save-on-exit",          false, OPTION_BOOL,   "/sim/startup/save-on-exit", true, "", 0 },
1588     {"read-only",                    false, OPTION_BOOL,   "/sim/fghome-readonly", true, "", 0 },
1589     {"ignore-autosave",              false, OPTION_FUNC,   "", false, "", fgOptIgnoreAutosave },
1590     {"restore-defaults",             false, OPTION_BOOL,   "/sim/startup/restore-defaults", true, "", 0 },
1591     {"shading-flat",                 false, OPTION_BOOL,   "/sim/rendering/shading", false, "", 0 },
1592     {"shading-smooth",               false, OPTION_BOOL,   "/sim/rendering/shading", true, "", 0 },
1593     {"texture-filtering",            false, OPTION_INT,    "/sim/rendering/filtering", 1, "", 0 },
1594     {"disable-wireframe",            false, OPTION_BOOL,   "/sim/rendering/wireframe", false, "", 0 },
1595     {"enable-wireframe",             false, OPTION_BOOL,   "/sim/rendering/wireframe", true, "", 0 },
1596     {"materials-file",               true,  OPTION_STRING, "/sim/rendering/materials-file", false, "", 0 },
1597     {"disable-terrasync",            false, OPTION_BOOL,   "/sim/terrasync/enabled", false, "", 0 },
1598     {"enable-terrasync",             false, OPTION_BOOL,   "/sim/terrasync/enabled", true, "", 0 },
1599     {"terrasync-dir",                true,  OPTION_STRING, "/sim/terrasync/scenery-dir", false, "", 0 },
1600     {"geometry",                     true,  OPTION_FUNC,   "", false, "", fgOptGeometry },
1601     {"bpp",                          true,  OPTION_FUNC,   "", false, "", fgOptBpp },
1602     {"units-feet",                   false, OPTION_STRING, "/sim/startup/units", false, "feet", 0 },
1603     {"units-meters",                 false, OPTION_STRING, "/sim/startup/units", false, "meters", 0 },
1604     {"timeofday",                    true,  OPTION_STRING, "/sim/startup/time-offset-type", false, "noon", 0 },
1605     {"season",                       true,  OPTION_STRING, "/sim/startup/season", false, "summer", 0 },
1606     {"time-offset",                  true,  OPTION_FUNC,   "", false, "", fgOptTimeOffset },
1607     {"time-match-real",              false, OPTION_STRING, "/sim/startup/time-offset-type", false, "system-offset", 0 },
1608     {"time-match-local",             false, OPTION_STRING, "/sim/startup/time-offset-type", false, "latitude-offset", 0 },
1609     {"start-date-sys",               true,  OPTION_FUNC,   "", false, "", fgOptStartDateSys },
1610     {"start-date-lat",               true,  OPTION_FUNC,   "", false, "", fgOptStartDateLat },
1611     {"start-date-gmt",               true,  OPTION_FUNC,   "", false, "", fgOptStartDateGmt },
1612     {"hud-tris",                     false, OPTION_STRING, "/sim/hud/frame-stat-type", false, "tris", 0 },
1613     {"hud-culled",                   false, OPTION_STRING, "/sim/hud/frame-stat-type", false, "culled", 0 },
1614     {"atcsim",                       true,  OPTION_CHANNEL, "", false, "dummy", 0 },
1615     {"atlas",                        true,  OPTION_CHANNEL | OPTION_MULTI, "", false, "", 0 },
1616     {"httpd",                        true,  OPTION_FUNC   , "", false, "", fgOptHttpd },
1617     {"jpg-httpd",                    true,  OPTION_FUNC,    "", false, "", fgOptJpgHttpd },
1618     {"native",                       true,  OPTION_CHANNEL | OPTION_MULTI, "", false, "", 0 },
1619     {"native-ctrls",                 true,  OPTION_CHANNEL | OPTION_MULTI, "", false, "", 0 },
1620     {"native-fdm",                   true,  OPTION_CHANNEL | OPTION_MULTI, "", false, "", 0 },
1621     {"native-gui",                   true,  OPTION_CHANNEL | OPTION_MULTI, "", false, "", 0 },
1622     {"opengc",                       true,  OPTION_CHANNEL | OPTION_MULTI, "", false, "", 0 },
1623     {"AV400",                        true,  OPTION_CHANNEL | OPTION_MULTI, "", false, "", 0 },
1624     {"AV400Sim",                     true,  OPTION_CHANNEL | OPTION_MULTI, "", false, "", 0 },
1625     {"AV400WSimA",                   true,  OPTION_CHANNEL | OPTION_MULTI, "", false, "", 0 },
1626     {"AV400WSimB",                   true,  OPTION_CHANNEL | OPTION_MULTI, "", false, "", 0 },
1627     {"garmin",                       true,  OPTION_CHANNEL | OPTION_MULTI, "", false, "", 0 },
1628     {"igc",                          true,  OPTION_CHANNEL | OPTION_MULTI, "", false, "", 0 },
1629     {"nmea",                         true,  OPTION_CHANNEL | OPTION_MULTI, "", false, "", 0 },
1630     {"generic",                      true,  OPTION_CHANNEL | OPTION_MULTI, "", false, "", 0 },
1631     {"props",                        true,  OPTION_CHANNEL | OPTION_MULTI, "", false, "", 0 },
1632     {"telnet",                       true,  OPTION_CHANNEL | OPTION_MULTI, "", false, "", 0 },
1633     {"pve",                          true,  OPTION_CHANNEL, "", false, "", 0 },
1634     {"ray",                          true,  OPTION_CHANNEL, "", false, "", 0 },
1635     {"rul",                          true,  OPTION_CHANNEL, "", false, "", 0 },
1636     {"joyclient",                    true,  OPTION_CHANNEL, "", false, "", 0 },
1637     {"jsclient",                     true,  OPTION_CHANNEL, "", false, "", 0 },
1638     {"proxy",                        true,  OPTION_FUNC,    "", false, "", fgSetupProxy },
1639     {"callsign",                     true,  OPTION_FUNC,    "", false, "", fgOptCallSign},
1640     {"multiplay",                    true,  OPTION_CHANNEL | OPTION_MULTI, "", false, "", 0 },
1641 #if FG_HAVE_HLA
1642     {"hla",                          true,  OPTION_CHANNEL, "", false, "", 0 },
1643     {"hla-local",                    true,  OPTION_CHANNEL, "", false, "", 0 },
1644 #endif
1645     {"trace-read",                   true,  OPTION_FUNC | OPTION_MULTI,   "", false, "", fgOptTraceRead },
1646     {"trace-write",                  true,  OPTION_FUNC | OPTION_MULTI,   "", false, "", fgOptTraceWrite },
1647     {"log-level",                    true,  OPTION_FUNC,   "", false, "", fgOptLogLevel },
1648     {"log-class",                    true,  OPTION_FUNC,   "", false, "", fgOptLogClasses },
1649     {"view-offset",                  true,  OPTION_FUNC | OPTION_MULTI,   "", false, "", fgOptViewOffset },
1650     {"visibility",                   true,  OPTION_FUNC,   "", false, "", fgOptVisibilityMeters },
1651     {"visibility-miles",             true,  OPTION_FUNC,   "", false, "", fgOptVisibilityMiles },
1652     {"random-wind",                  false, OPTION_FUNC,   "", false, "", fgOptRandomWind },
1653     {"wind",                         true,  OPTION_FUNC | OPTION_MULTI,   "", false, "", fgOptWind },
1654     {"turbulence",                   true,  OPTION_FUNC,   "", false, "", fgOptTurbulence },
1655     {"ceiling",                      true,  OPTION_FUNC,   "", false, "", fgOptCeiling },
1656     {"wp",                           true,  OPTION_FUNC | OPTION_MULTI,   "", false, "", fgOptWp },
1657     {"flight-plan",                  true,  OPTION_STRING,   "/autopilot/route-manager/file-path", false, "", NULL },
1658     {"config",                       true,  OPTION_FUNC | OPTION_MULTI,   "", false, "", fgOptConfig },
1659     {"aircraft",                     true,  OPTION_STRING, "/sim/aircraft", false, "", 0 },
1660     {"vehicle",                      true,  OPTION_STRING, "/sim/aircraft", false, "", 0 },
1661     {"failure",                      true,  OPTION_FUNC | OPTION_MULTI,   "", false, "", fgOptFailure },
1662 #ifdef ENABLE_IAX
1663     {"enable-fgcom",                 false, OPTION_BOOL,   "/sim/fgcom/enabled", true, "", 0 },
1664     {"disable-fgcom",                false, OPTION_BOOL,   "/sim/fgcom/enabled", false, "", 0 },
1665 #endif
1666     {"com1",                         true,  OPTION_DOUBLE, "/instrumentation/comm[0]/frequencies/selected-mhz", false, "", 0 },
1667     {"com2",                         true,  OPTION_DOUBLE, "/instrumentation/comm[1]/frequencies/selected-mhz", false, "", 0 },
1668     {"nav1",                         true,  OPTION_FUNC,   "", false, "", fgOptNAV1 },
1669     {"nav2",                         true,  OPTION_FUNC,   "", false, "", fgOptNAV2 },
1670     {"adf", /*legacy*/               true,  OPTION_FUNC,   "", false, "", fgOptADF1 },
1671     {"adf1",                         true,  OPTION_FUNC,   "", false, "", fgOptADF1 },
1672     {"adf2",                         true,  OPTION_FUNC,   "", false, "", fgOptADF2 },
1673     {"dme",                          true,  OPTION_FUNC,   "", false, "", fgOptDME },
1674     {"min-status",                   true,  OPTION_STRING,  "/sim/aircraft-min-status", false, "all", 0 },
1675     {"livery",                       true,  OPTION_FUNC,   "", false, "", fgOptLivery },
1676     {"ai-scenario",                  true,  OPTION_FUNC | OPTION_MULTI,   "", false, "", fgOptScenario },
1677     {"parking-id",                   true,  OPTION_FUNC,   "", false, "", fgOptParking  },
1678     {"version",                      false, OPTION_FUNC,   "", false, "", fgOptVersion },
1679     {"enable-fpe",                   false, OPTION_IGNORE,   "", false, "", 0},
1680     {"fgviewer",                     false, OPTION_IGNORE,   "", false, "", 0},
1681     {"no-default-config",            false, OPTION_IGNORE, "", false, "", 0},
1682     {"prop",                         true,  OPTION_FUNC | OPTION_MULTI,   "", false, "", fgOptSetProperty},
1683     {"load-tape",                    true,  OPTION_FUNC,   "", false, "", fgOptLoadTape },
1684     {0}
1685 };
1686
1687
1688 namespace flightgear
1689 {
1690
1691 /**
1692  * internal storage of a value->option binding
1693  */
1694 class OptionValue 
1695 {
1696 public:
1697   OptionValue(OptionDesc* d, const string& v) :
1698     desc(d), value(v)
1699   {;}
1700   
1701   OptionDesc* desc;
1702   string value;
1703 };
1704
1705 typedef std::vector<OptionValue> OptionValueVec;
1706 typedef std::map<string, OptionDesc*> OptionDescDict;
1707   
1708 class Options::OptionsPrivate
1709 {
1710 public:
1711   
1712   OptionValueVec::const_iterator findValue(const string& key) const
1713   {
1714     OptionValueVec::const_iterator it = values.begin();
1715     for (; it != values.end(); ++it) {
1716       if (!it->desc) {
1717         continue; // ignore markers
1718       }
1719       
1720       if (it->desc->option == key) {
1721         return it;
1722       }
1723     } // of set values iteration
1724     
1725     return it; // not found
1726   }
1727   
1728   OptionDesc* findOption(const string& key) const
1729   {
1730     OptionDescDict::const_iterator it = options.find(key);
1731     if (it == options.end()) {
1732       return NULL;
1733     }
1734     
1735     return it->second;
1736   }
1737   
1738   int processOption(OptionDesc* desc, const string& arg_value)
1739   {
1740     if (!desc) {
1741       return FG_OPTIONS_OK; // tolerate marker options
1742     }
1743     
1744     switch ( desc->type & 0xffff ) {
1745       case OPTION_BOOL:
1746         fgSetBool( desc->property, desc->b_param );
1747         break;
1748       case OPTION_STRING:
1749         if ( desc->has_param && !arg_value.empty() ) {
1750           fgSetString( desc->property, arg_value.c_str() );
1751         } else if ( !desc->has_param && arg_value.empty() ) {
1752           fgSetString( desc->property, desc->s_param );
1753         } else if ( desc->has_param ) {
1754           SG_LOG( SG_GENERAL, SG_ALERT, "Option '" << desc->option << "' needs a parameter" );
1755           return FG_OPTIONS_ERROR;
1756         } else {
1757           SG_LOG( SG_GENERAL, SG_ALERT, "Option '" << desc->option << "' does not have a parameter" );
1758           return FG_OPTIONS_ERROR;
1759         }
1760         break;
1761       case OPTION_DOUBLE:
1762         if ( !arg_value.empty() ) {
1763           fgSetDouble( desc->property, atof( arg_value ) );
1764         } else {
1765           SG_LOG( SG_GENERAL, SG_ALERT, "Option '" << desc->option << "' needs a parameter" );
1766           return FG_OPTIONS_ERROR;
1767         }
1768         break;
1769       case OPTION_INT:
1770         if ( !arg_value.empty() ) {
1771           fgSetInt( desc->property, atoi( arg_value ) );
1772         } else {
1773           SG_LOG( SG_GENERAL, SG_ALERT, "Option '" << desc->option << "' needs a parameter" );
1774           return FG_OPTIONS_ERROR;
1775         }
1776         break;
1777       case OPTION_CHANNEL:
1778         // XXX return value of add_channel should be checked?
1779         if ( desc->has_param && !arg_value.empty() ) {
1780           add_channel( desc->option, arg_value );
1781         } else if ( !desc->has_param && arg_value.empty() ) {
1782           add_channel( desc->option, desc->s_param );
1783         } else if ( desc->has_param ) {
1784           SG_LOG( SG_GENERAL, SG_ALERT, "Option '" << desc->option << "' needs a parameter" );
1785           return FG_OPTIONS_ERROR;
1786         } else {
1787           SG_LOG( SG_GENERAL, SG_ALERT, "Option '" << desc->option << "' does not have a parameter" );
1788           return FG_OPTIONS_ERROR;
1789         }
1790         break;
1791       case OPTION_FUNC:
1792         if ( desc->has_param && !arg_value.empty() ) {
1793           return desc->func( arg_value.c_str() );
1794         } else if ( !desc->has_param && arg_value.empty() ) {
1795           return desc->func( desc->s_param );
1796         } else if ( desc->has_param ) {
1797           SG_LOG( SG_GENERAL, SG_ALERT, "Option '" << desc->option << "' needs a parameter" );
1798           return FG_OPTIONS_ERROR;
1799         } else {
1800           SG_LOG( SG_GENERAL, SG_ALERT, "Option '" << desc->option << "' does not have a parameter" );
1801           return FG_OPTIONS_ERROR;
1802         }
1803         break;
1804         
1805       case OPTION_IGNORE:
1806         break;
1807     }
1808     
1809     return FG_OPTIONS_OK;
1810   }
1811     
1812   /**
1813    * insert a marker value into the values vector. This is necessary
1814    * when processing options, to ensure the correct ordering, where we scan
1815    * for marker values in reverse, and then forwards within each group.
1816    */
1817   void insertGroupMarker()
1818   {
1819     values.push_back(OptionValue(NULL, "-"));
1820   }
1821   
1822   /**
1823    * given a current iterator into the values, find the preceeding group marker,
1824    * or return the beginning of the value vector.
1825    */
1826   OptionValueVec::const_iterator rfindGroup(OptionValueVec::const_iterator pos) const
1827   {
1828     while (--pos != values.begin()) {
1829       if (pos->desc == NULL) {
1830         return pos; // found a marker, we're done
1831       }
1832     }
1833     
1834     return pos;
1835   }
1836   
1837   bool showHelp,
1838     verbose,
1839     showAircraft,
1840     shouldLoadDefaultConfig;
1841     
1842   OptionDescDict options;
1843   OptionValueVec values;
1844   simgear::PathList propertyFiles;
1845 };
1846   
1847 Options* Options::sharedInstance()
1848 {
1849   if (shared_instance == NULL) {
1850     shared_instance = new Options;
1851   }
1852   
1853   return shared_instance;
1854 }
1855   
1856 Options::Options() :
1857   p(new OptionsPrivate())
1858 {
1859   p->showHelp = false;
1860   p->verbose = false;
1861   p->showAircraft = false;
1862   p->shouldLoadDefaultConfig = true;
1863   
1864 // build option map
1865   OptionDesc *desc = &fgOptionArray[ 0 ];
1866   while ( desc->option != 0 ) {
1867     p->options[ desc->option ] = desc;
1868     ++desc;
1869   }
1870 }
1871   
1872 Options::~Options()
1873 {
1874 }
1875   
1876 void Options::init(int argc, char **argv, const SGPath& appDataPath)
1877 {
1878 // first, process the command line
1879   bool inOptions = true;
1880   for (int i=1; i<argc; ++i) {
1881     if (inOptions && (argv[i][0] == '-')) {
1882       if (strcmp(argv[i], "--") == 0) { // end of options delimiter
1883         inOptions = true;
1884         continue;
1885       }
1886       
1887       int result = parseOption(argv[i]);
1888       processArgResult(result);
1889     } else {
1890     // XML properties file
1891       SGPath f(argv[i]);
1892       if (!f.exists()) {
1893         SG_LOG(SG_GENERAL, SG_ALERT, "config file not found:" << f.str());
1894       } else {
1895         p->propertyFiles.push_back(f);
1896       }
1897     }
1898   } // of arguments iteration
1899   p->insertGroupMarker(); // command line is one group
1900   
1901   // establish log-level before anything else - otherwise it is not possible
1902   // to show extra (debug/info/warning) messages for the start-up phase.
1903   fgOptLogLevel(valueForOption("log-level", "alert").c_str());
1904
1905   if (!p->shouldLoadDefaultConfig) {
1906     setupRoot(argc, argv);
1907     return;
1908   }
1909   
1910 // then config files
1911   SGPath config;
1912   std::string homedir;
1913   if (getenv("HOME")) {
1914     homedir = getenv("HOME");
1915   }
1916     
1917   if( !homedir.empty() && !hostname.empty() ) {
1918     // Check for ~/.fgfsrc.hostname
1919     config.set(homedir);
1920     config.append(".fgfsrc");
1921     config.concat( "." );
1922     config.concat( hostname );
1923     readConfig(config);
1924   }
1925   
1926 // Check for ~/.fgfsrc
1927   if( !homedir.empty() ) {
1928     config.set(homedir);
1929     config.append(".fgfsrc");
1930     readConfig(config);
1931   }
1932   
1933 // check for a config file in app data
1934   SGPath appDataConfig(appDataPath);
1935   appDataConfig.append("fgfsrc");
1936   if (appDataConfig.exists()) {
1937     readConfig(appDataConfig);
1938   }
1939   
1940 // setup FG_ROOT
1941   setupRoot(argc, argv);
1942   
1943 // system.fgfsrc is disabled, as we no longer allow anything in fgdata to set
1944 // fg-root/fg-home/fg-aircraft and hence control what files Nasal can access
1945   std::string name_for_error = homedir.empty() ? appDataConfig.str() : config.str();
1946   if( ! hostname.empty() ) {
1947     config.set(globals->get_fg_root());
1948     config.append( "system.fgfsrc" );
1949     config.concat( "." );
1950     config.concat( hostname );
1951     if (config.exists()) {
1952       flightgear::fatalMessageBox("Unsupported configuration",
1953         "You have a " + config.str() + " file, which is no longer processed for security reasons",
1954         "If you created this file intentionally, please move it to " + name_for_error);
1955     }
1956   }
1957
1958   config.set(globals->get_fg_root());
1959   config.append( "system.fgfsrc" );
1960   if (config.exists()) {
1961     flightgear::fatalMessageBox("Unsupported configuration",
1962       "You have a " + config.str() + " file, which is no longer processed for security reasons",
1963       "If you created this file intentionally, please move it to " + name_for_error);
1964   }
1965 }
1966
1967 void Options::initPaths()
1968 {
1969     BOOST_FOREACH(const string& paths, valuesForOption("fg-aircraft")) {
1970         globals->append_aircraft_paths(paths);
1971     }
1972
1973     const char* envp = ::getenv("FG_AIRCRAFT");
1974     if (envp) {
1975         globals->append_aircraft_paths(envp);
1976     }
1977
1978 }
1979
1980 void Options::initAircraft()
1981 {
1982   string aircraft;
1983   if (isOptionSet("aircraft")) {
1984     aircraft = valueForOption("aircraft");
1985   } else if (isOptionSet("vehicle")) {
1986     aircraft = valueForOption("vehicle");
1987   }
1988     
1989   if (!aircraft.empty()) {
1990     SG_LOG(SG_INPUT, SG_INFO, "aircraft = " << aircraft );
1991     fgSetString("/sim/aircraft", aircraft.c_str() );
1992   } else {
1993     SG_LOG(SG_INPUT, SG_INFO, "No user specified aircraft, using default" );
1994   }
1995     
1996   if (p->showAircraft) {
1997     fgOptLogLevel( "alert" );
1998     SGPath path( globals->get_fg_root() );
1999     path.append("Aircraft");
2000     fgShowAircraft(path);
2001     exit(0);
2002   }
2003   
2004   if (isOptionSet("aircraft-dir")) {
2005     // set this now, so it's available in FindAndCacheAircraft
2006     fgSetString("/sim/aircraft-dir", valueForOption("aircraft-dir"));
2007   }
2008 }
2009   
2010 void Options::processArgResult(int result)
2011 {
2012   if ((result == FG_OPTIONS_HELP) || (result == FG_OPTIONS_ERROR))
2013     p->showHelp = true;
2014   else if (result == FG_OPTIONS_VERBOSE_HELP)
2015     p->verbose = true;
2016   else if (result == FG_OPTIONS_SHOW_AIRCRAFT) {
2017     p->showAircraft = true;
2018   } else if (result == FG_OPTIONS_NO_DEFAULT_CONFIG) {
2019     p->shouldLoadDefaultConfig = false;
2020   } else if (result == FG_OPTIONS_SHOW_SOUND_DEVICES) {
2021     SGSoundMgr smgr;
2022     
2023     smgr.init();
2024     string vendor = smgr.get_vendor();
2025     string renderer = smgr.get_renderer();
2026     cout << renderer << " provided by " << vendor << endl;
2027     cout << endl << "No. Device" << endl;
2028     
2029     vector <const char*>devices = smgr.get_available_devices();
2030     for (vector <const char*>::size_type i=0; i<devices.size(); i++) {
2031       cout << i << ".  \"" << devices[i] << "\"" << endl;
2032     }
2033     devices.clear();
2034     smgr.stop();
2035     exit(0);
2036   } else if (result == FG_OPTIONS_EXIT) {
2037     exit(0);
2038   }
2039 }
2040   
2041 void Options::readConfig(const SGPath& path)
2042 {
2043   sg_gzifstream in( path.str() );
2044   if ( !in.is_open() ) {
2045     return;
2046   }
2047   
2048   SG_LOG( SG_GENERAL, SG_INFO, "Processing config file: " << path.str() );
2049   
2050   in >> skipcomment;
2051   while ( ! in.eof() ) {
2052     string line;
2053     getline( in, line, '\n' );
2054     
2055     // catch extraneous (DOS) line ending character
2056     int i;
2057     for (i = line.length(); i > 0; i--)
2058       if (line[i - 1] > 32)
2059         break;
2060     line = line.substr( 0, i );
2061     
2062     if ( parseOption( line ) == FG_OPTIONS_ERROR ) {
2063       cerr << endl << "Config file parse error: " << path.str() << " '"
2064       << line << "'" << endl;
2065             p->showHelp = true;
2066     }
2067     in >> skipcomment;
2068   }
2069
2070   p->insertGroupMarker(); // each config file is a group
2071 }
2072   
2073 int Options::parseOption(const string& s)
2074 {
2075   if ((s == "--help") || (s=="-h")) {
2076     return FG_OPTIONS_HELP;
2077   } else if ( (s == "--verbose") || (s == "-v") ) {
2078     // verbose help/usage request
2079     return FG_OPTIONS_VERBOSE_HELP;
2080   } else if ((s == "--console") || (s == "-c")) {
2081           simgear::requestConsole();
2082           return FG_OPTIONS_OK;
2083   } else if (s.find("-psn") == 0) {
2084     // on Mac, when launched from the GUI, we are passed the ProcessSerialNumber
2085     // as an argument (and no others). Silently ignore the argument here.
2086     return FG_OPTIONS_OK;
2087   } else if ( s.find( "--show-aircraft") == 0) {
2088     return(FG_OPTIONS_SHOW_AIRCRAFT);
2089   } else if ( s.find( "--show-sound-devices") == 0) {
2090     return(FG_OPTIONS_SHOW_SOUND_DEVICES);
2091   } else if ( s.find( "--no-default-config") == 0) {
2092     return FG_OPTIONS_NO_DEFAULT_CONFIG;
2093   } else if ( s.find( "--prop:") == 0) {
2094     // property setting has a slightly different syntax, so fudge things
2095     OptionDesc* desc = p->findOption("prop");
2096     if (s.find("=", 7) == string::npos) { // no equals token
2097       SG_LOG(SG_GENERAL, SG_ALERT, "malformed property option:" << s);
2098       return FG_OPTIONS_ERROR;
2099     }
2100     
2101     p->values.push_back(OptionValue(desc, s.substr(7)));
2102     return FG_OPTIONS_OK;
2103   } else if ( s.find( "--" ) == 0 ) {
2104     size_t eqPos = s.find( '=' );
2105     string key, value;
2106     if (eqPos == string::npos) {
2107       key = s.substr(2);
2108     } else {
2109       key = s.substr( 2, eqPos - 2 );
2110       value = s.substr( eqPos + 1);
2111     }
2112     
2113     return addOption(key, value);
2114   } else {
2115       flightgear::modalMessageBox("Unknown option", "Unknown command-line option: " + s);
2116     return FG_OPTIONS_ERROR;
2117   }
2118 }
2119   
2120 int Options::addOption(const string &key, const string &value)
2121 {
2122   OptionDesc* desc = p->findOption(key);
2123   if (!desc) {
2124     flightgear::modalMessageBox("Unknown option", "Unknown command-line option: " + key);
2125     return FG_OPTIONS_ERROR;
2126   }
2127   
2128   if (!(desc->type & OPTION_MULTI)) {
2129     OptionValueVec::const_iterator it = p->findValue(key);
2130     if (it != p->values.end()) {
2131       SG_LOG(SG_GENERAL, SG_WARN, "multiple values forbidden for option:" << key << ", ignoring:" << value);
2132       return FG_OPTIONS_OK;
2133     }
2134   }
2135   
2136   p->values.push_back(OptionValue(desc, value));
2137   return FG_OPTIONS_OK;
2138 }
2139   
2140 bool Options::isOptionSet(const string &key) const
2141 {
2142   OptionValueVec::const_iterator it = p->findValue(key);
2143   return (it != p->values.end());
2144 }
2145   
2146 string Options::valueForOption(const string& key, const string& defValue) const
2147 {
2148   OptionValueVec::const_iterator it = p->findValue(key);
2149   if (it == p->values.end()) {
2150     return defValue;
2151   }
2152   
2153   return it->value;
2154 }
2155
2156 string_list Options::valuesForOption(const std::string& key) const
2157 {
2158   string_list result;
2159   OptionValueVec::const_iterator it = p->values.begin();
2160   for (; it != p->values.end(); ++it) {
2161     if (!it->desc) {
2162       continue; // ignore marker values
2163     }
2164     
2165     if (it->desc->option == key) {
2166       result.push_back(it->value);
2167     }
2168   }
2169   
2170   return result;
2171 }
2172
2173
2174 static string defaultTerrasyncDir()
2175 {
2176 #if defined(SG_WINDOWS)
2177         SGPath p(SGPath::documents());
2178         p.append("FlightGear");
2179 #else
2180     SGPath p(globals->get_fg_home());
2181 #endif
2182         p.append("TerraSync");
2183         return p.str();
2184 }
2185
2186
2187 OptionResult Options::processOptions()
2188 {
2189   // establish locale before showing help (this selects the default locale,
2190   // when no explicit option was set)
2191   globals->get_locale()->selectLanguage(valueForOption("language").c_str());
2192
2193   // now FG_ROOT is setup, process various command line options that bail us
2194   // out quickly, but rely on aircraft / root settings
2195   if (p->showHelp) {
2196     showUsage();
2197       return FG_OPTIONS_EXIT;
2198   }
2199   
2200   // processing order is complicated. We must process groups LIFO, but the
2201   // values *within* each group in FIFO order, to retain consistency with
2202   // older versions of FG, and existing user configs.
2203   // in practice this means system.fgfsrc must be *processed* before
2204   // .fgfsrc, which must be processed before the command line args, and so on.
2205   OptionValueVec::const_iterator groupEnd = p->values.end();
2206
2207   while (groupEnd != p->values.begin()) {
2208     OptionValueVec::const_iterator groupBegin = p->rfindGroup(groupEnd);
2209   // run over the group in FIFO order
2210     OptionValueVec::const_iterator it;
2211     for (it = groupBegin; it != groupEnd; ++it) {      
2212       int result = p->processOption(it->desc, it->value);
2213       switch(result)
2214       {
2215           case FG_OPTIONS_ERROR:
2216               showUsage();
2217               return FG_OPTIONS_ERROR;
2218               
2219           case FG_OPTIONS_EXIT:
2220               return FG_OPTIONS_EXIT;
2221               
2222           default:
2223               break;
2224       }
2225     }
2226     
2227     groupEnd = groupBegin;
2228   }
2229
2230   BOOST_FOREACH(const SGPath& file, p->propertyFiles) {
2231     SG_LOG(SG_GENERAL, SG_INFO,
2232            "Reading command-line property file " << file.str());
2233           readProperties(file.str(), globals->get_props());
2234   }
2235
2236 // now options are process, do supplemental fixup
2237   const char *envp = ::getenv( "FG_SCENERY" );
2238   if (envp) {
2239     globals->append_fg_scenery(envp);
2240   }
2241     
2242 // terrasync directory fixup
2243     string terrasyncDir = simgear::strutils::strip(fgGetString("/sim/terrasync/scenery-dir"));
2244   if (terrasyncDir.empty()) {
2245           terrasyncDir = defaultTerrasyncDir();
2246           // auto-save it for next time
2247           
2248           SG_LOG(SG_GENERAL, SG_INFO,
2249                   "Using default TerraSync: " << terrasyncDir);
2250       fgSetString("/sim/terrasync/scenery-dir", terrasyncDir);
2251   }
2252
2253   SGPath p(terrasyncDir);
2254
2255   // following is necessary to ensure NavDataCache sees stable scenery paths from
2256   // terrasync. Ensure the Terrain and Objects subdirs exist immediately, rather
2257   // than waiting for the first tiles to be scheduled.
2258   simgear::Dir terrainDir(SGPath(p, "Terrain")),
2259     objectsDir(SGPath(p, "Objects"));
2260   if (!terrainDir.exists()) {
2261       terrainDir.create(0755);
2262   }
2263   
2264   if (!objectsDir.exists()) {
2265       objectsDir.create(0755);
2266   }
2267
2268     // check the above actuall worked
2269     if (!objectsDir.exists() || !terrainDir.exists()) {
2270         std::stringstream ss;
2271         ss << "Scenery download will be disabled. The configured location is '" << terrasyncDir << "'.";
2272         flightgear::modalMessageBox("Invalid scenery download location",
2273                                     "Automatic scenery download is configured to use a location (path) which invalid.",
2274                                     ss.str());
2275         fgSetBool("/sim/terrasync/enabled", false);
2276     }
2277
2278   if (fgGetBool("/sim/terrasync/enabled")) {
2279     const string_list& scenery_paths(globals->get_fg_scenery());
2280     if (std::find(scenery_paths.begin(), scenery_paths.end(), terrasyncDir) == scenery_paths.end()) {
2281       // terrasync dir is not in the scenery paths, add it
2282       globals->append_fg_scenery(terrasyncDir);
2283     }
2284   }
2285   
2286   if (globals->get_fg_scenery().empty()) {
2287     // no scenery paths set *at all*, use the data in FG_ROOT
2288     SGPath root(globals->get_fg_root());
2289     root.append("Scenery");
2290     globals->append_fg_scenery(root.str());
2291   }
2292     
2293   return FG_OPTIONS_OK;
2294 }
2295   
2296 void Options::showUsage() const
2297 {
2298   fgOptLogLevel( "alert" );
2299   
2300   FGLocale *locale = globals->get_locale();
2301   SGPropertyNode options_root;
2302   
2303   simgear::requestConsole(); // ensure console is shown on Windows
2304   cout << endl;
2305
2306   try {
2307     fgLoadProps("options.xml", &options_root);
2308   } catch (const sg_exception &) {
2309     cout << "Unable to read the help file." << endl;
2310     cout << "Make sure the file options.xml is located in the FlightGear base directory," << endl;
2311     cout << "and the location of the base directory is specified by setting $FG_ROOT or" << endl;
2312     cout << "by adding --fg-root=path as a program argument." << endl;
2313     
2314     exit(-1);
2315   }
2316
2317   SGPropertyNode *options = options_root.getNode("options");
2318   if (!options) {
2319     SG_LOG( SG_GENERAL, SG_ALERT,
2320            "Error reading options.xml: <options> directive not found." );
2321     exit(-1);
2322   }
2323
2324   if (!locale->loadResource("options"))
2325   {
2326       cout << "Unable to read the language resource." << endl;
2327       exit(-1);
2328   }
2329
2330   const char* usage = locale->getLocalizedString(options->getStringValue("usage"), "options");
2331   if (usage) {
2332     cout << usage << endl;
2333   }
2334   
2335   vector<SGPropertyNode_ptr>section = options->getChildren("section");
2336   for (unsigned int j = 0; j < section.size(); j++) {
2337     string msg = "";
2338     
2339     vector<SGPropertyNode_ptr>option = section[j]->getChildren("option");
2340     for (unsigned int k = 0; k < option.size(); k++) {
2341       
2342       SGPropertyNode *name = option[k]->getNode("name");
2343       SGPropertyNode *short_name = option[k]->getNode("short");
2344       SGPropertyNode *key = option[k]->getNode("key");
2345       SGPropertyNode *arg = option[k]->getNode("arg");
2346       bool brief = option[k]->getNode("brief") != 0;
2347       
2348       if ((brief || p->verbose) && name) {
2349         string tmp = name->getStringValue();
2350         
2351         if (key){
2352           tmp.append(":");
2353           tmp.append(key->getStringValue());
2354         }
2355         if (arg) {
2356           tmp.append("=");
2357           tmp.append(arg->getStringValue());
2358         }
2359         if (short_name) {
2360           tmp.append(", -");
2361           tmp.append(short_name->getStringValue());
2362         }
2363         
2364         if (tmp.size() <= 25) {
2365           msg+= "   --";
2366           msg += tmp;
2367           msg.append( 27-tmp.size(), ' ');
2368         } else {
2369           msg += "\n   --";
2370           msg += tmp + '\n';
2371           msg.append(32, ' ');
2372         }
2373         // There may be more than one <description> tag associated
2374         // with one option
2375         
2376         vector<SGPropertyNode_ptr> desc;
2377         desc = option[k]->getChildren("description");
2378         if (! desc.empty()) {
2379           for ( unsigned int l = 0; l < desc.size(); l++) {
2380             string t = desc[l]->getStringValue();
2381
2382             // There may be more than one translation line.
2383             vector<SGPropertyNode_ptr>trans_desc = locale->getLocalizedStrings(t.c_str(),"options");
2384             for ( unsigned int m = 0; m < trans_desc.size(); m++ ) {
2385               string t_str = trans_desc[m]->getStringValue();
2386               
2387               if ((m > 0) || ((l > 0) && m == 0)) {
2388                 msg.append( 32, ' ');
2389               }
2390               
2391               // If the string is too large to fit on the screen,
2392               // then split it up in several pieces.
2393               
2394               while ( t_str.size() > 47 ) {
2395                 
2396                 string::size_type m = t_str.rfind(' ', 47);
2397                 msg += t_str.substr(0, m) + '\n';
2398                 msg.append( 32, ' ');
2399                 
2400                 t_str.erase(t_str.begin(), t_str.begin() + m + 1);
2401               }
2402               msg += t_str + '\n';
2403             }
2404           }
2405         }
2406       }
2407     }
2408     
2409     const char* name = locale->getLocalizedString(section[j]->getStringValue("name"),"options");
2410     if (!msg.empty() && name) {
2411       cout << endl << name << ":" << endl;
2412       cout << msg;
2413       msg.erase();
2414     }
2415   }
2416   
2417   if ( !p->verbose ) {
2418     const char* verbose_help = locale->getLocalizedString(options->getStringValue("verbose-help"),"options");
2419     if (verbose_help)
2420         cout << endl << verbose_help << endl;
2421   }
2422 #ifdef _MSC_VER
2423   std::cout << "Hit a key to continue..." << std::endl;
2424   std::cin.get();
2425 #endif
2426 }
2427   
2428 #if defined(__CYGWIN__)
2429 string Options::platformDefaultRoot() const
2430 {
2431   return "../data";
2432 }
2433
2434 #elif defined(SG_WINDOWS)
2435 string Options::platformDefaultRoot() const
2436 {
2437   return "..\\data";
2438 }
2439 #elif defined(SG_MAC)
2440 // platformDefaultRoot defined in CocoaHelpers.mm
2441 #else
2442 string Options::platformDefaultRoot() const
2443 {
2444   return PKGLIBDIR;
2445 }
2446 #endif
2447   
2448 void Options::setupRoot(int argc, char **argv)
2449 {
2450   string root;
2451     bool usingDefaultRoot = false;
2452
2453   if (isOptionSet("fg-root")) {
2454     root = valueForOption("fg-root"); // easy!
2455   } else {
2456   // Next check if fg-root is set as an env variable
2457     char *envp = ::getenv( "FG_ROOT" );
2458     if ( envp != NULL ) {
2459       root = envp;
2460     } else {
2461         usingDefaultRoot = true;
2462       root = platformDefaultRoot();
2463     }
2464   } 
2465   
2466   SG_LOG(SG_GENERAL, SG_INFO, "fg_root = " << root );
2467   globals->set_fg_root(root);
2468     static char required_version[] = FLIGHTGEAR_VERSION;
2469     string base_version = fgBasePackageVersion(root);
2470
2471 #if defined(HAVE_QT)
2472     if (base_version != required_version) {
2473         QtLauncher::initApp(argc, argv);
2474         if (SetupRootDialog::restoreUserSelectedRoot()) {
2475             SG_LOG(SG_GENERAL, SG_INFO, "restored user selected fg_root = " << globals->get_fg_root() );
2476             return;
2477         }
2478
2479         SetupRootDialog dlg(usingDefaultRoot);
2480         dlg.exec();
2481         if (dlg.result() != QDialog::Accepted) {
2482             exit(-1);
2483         }
2484     }
2485 #else
2486     // validate it
2487     if (base_version.empty()) {
2488         flightgear::fatalMessageBox("Base package not found",
2489                                     "Required data files not found, check your installation.",
2490                                     "Looking for base-package files at: '" + root + "'");
2491
2492         exit(-1);
2493     }
2494     
2495     if (base_version != required_version) {
2496       flightgear::fatalMessageBox("Base package version mismatch",
2497                                   "Version check failed: please check your installation.",
2498                                   "Found data files for version '" + base_version +
2499                                   "' at '" + globals->get_fg_root() + "', version '"
2500                                   + required_version + "' is required.");
2501
2502     exit(-1);
2503   }
2504 #endif
2505 }
2506   
2507 bool Options::shouldLoadDefaultConfig() const
2508 {
2509   return p->shouldLoadDefaultConfig;
2510 }
2511
2512 bool Options::checkForArg(int argc, char* argv[], const char* checkArg)
2513 {
2514     for (int i = 0; i < argc; ++i) {
2515         char* arg = argv[i];
2516         if (!strncmp("--", arg, 2) && !strcmp(arg + 2, checkArg)) {
2517             return true;
2518         }
2519         
2520         if ((arg[0] == '-') && !strcmp(arg + 1, checkArg)) {
2521             return true;
2522         }
2523     }
2524     
2525     return false;
2526 }
2527     
2528 } // of namespace flightgear
2529