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