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