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