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