]> git.mxchange.org Git - flightgear.git/blob - src/Main/options.cxx
Code cleanups, code updates and fix at least on (possible) devide-by-zero
[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 fgOptMetar( const char *arg )
1101 {
1102     // The given METAR string cannot be effective without disabling
1103     // real weather fetching.
1104     fgSetBool("/environment/realwx/enabled", false);
1105     // The user-supplied METAR string
1106     fgSetString("/environment/metar/data", arg);
1107
1108     return FG_OPTIONS_OK;
1109 }
1110
1111 static int
1112 fgOptRandomWind( const char *arg )
1113 {
1114     double min_hdg = sg_random() * 360.0;
1115     double max_hdg = min_hdg + (20 - sqrt(sg_random() * 400));
1116     double speed = sg_random() * sg_random() * 40;
1117     double gust = speed + (10 - sqrt(sg_random() * 100));
1118     Environment::Presets::WindSingleton::instance()->preset(min_hdg, max_hdg, speed, gust);
1119     return FG_OPTIONS_OK;
1120 }
1121
1122 static int
1123 fgOptWind( const char *arg )
1124 {
1125     double min_hdg = 0.0, max_hdg = 0.0, speed = 0.0, gust = 0.0;
1126     if (!parse_wind( arg, &min_hdg, &max_hdg, &speed, &gust)) {
1127         SG_LOG( SG_GENERAL, SG_ALERT, "bad wind value " << arg );
1128         return FG_OPTIONS_ERROR;
1129     }
1130     Environment::Presets::WindSingleton::instance()->preset(min_hdg, max_hdg, speed, gust);
1131     return FG_OPTIONS_OK;
1132 }
1133
1134 static int
1135 fgOptTurbulence( const char *arg )
1136 {
1137     Environment::Presets::TurbulenceSingleton::instance()->preset( atof(arg) );
1138     return FG_OPTIONS_OK;
1139 }
1140
1141 static int
1142 fgOptCeiling( const char *arg )
1143 {
1144     double elevation, thickness;
1145     string spec = arg;
1146     string::size_type pos = spec.find(':');
1147     if (pos == string::npos) {
1148         elevation = atof(spec.c_str());
1149         thickness = 2000;
1150     } else {
1151         elevation = atof(spec.substr(0, pos).c_str());
1152         thickness = atof(spec.substr(pos + 1).c_str());
1153     }
1154     Environment::Presets::CeilingSingleton::instance()->preset( elevation, thickness );
1155     return FG_OPTIONS_OK;
1156 }
1157
1158 static int
1159 fgOptWp( const char *arg )
1160 {
1161     string_list *waypoints = globals->get_initial_waypoints();
1162     if (!waypoints) {
1163         waypoints = new string_list;
1164         globals->set_initial_waypoints(waypoints);
1165     }
1166     waypoints->push_back(arg);
1167     return FG_OPTIONS_OK;
1168 }
1169
1170 static int
1171 fgOptConfig( const char *arg )
1172 {
1173     string file = arg;
1174     try {
1175         readProperties(file, globals->get_props());
1176     } catch (const sg_exception &e) {
1177         string message = "Error loading config file: ";
1178         message += e.getFormattedMessage() + e.getOrigin();
1179         SG_LOG(SG_INPUT, SG_ALERT, message);
1180         return FG_OPTIONS_ERROR;
1181     }
1182     return FG_OPTIONS_OK;
1183 }
1184
1185 static bool
1186 parse_colon (const string &s, double * val1, double * val2)
1187 {
1188     string::size_type pos = s.find(':');
1189     if (pos == string::npos) {
1190         *val2 = atof(s);
1191         return false;
1192     } else {
1193         *val1 = atof(s.substr(0, pos).c_str());
1194         *val2 = atof(s.substr(pos+1).c_str());
1195         return true;
1196     }
1197 }
1198
1199
1200 static int
1201 fgOptFailure( const char * arg )
1202 {
1203     string a = arg;
1204     if (a == "pitot") {
1205         fgSetBool("/systems/pitot/serviceable", false);
1206     } else if (a == "static") {
1207         fgSetBool("/systems/static/serviceable", false);
1208     } else if (a == "vacuum") {
1209         fgSetBool("/systems/vacuum/serviceable", false);
1210     } else if (a == "electrical") {
1211         fgSetBool("/systems/electrical/serviceable", false);
1212     } else {
1213         SG_LOG(SG_INPUT, SG_ALERT, "Unknown failure mode: " << a);
1214         return FG_OPTIONS_ERROR;
1215     }
1216
1217     return FG_OPTIONS_OK;
1218 }
1219
1220
1221 static int
1222 fgOptNAV1( const char * arg )
1223 {
1224     double radial, freq;
1225     if (parse_colon(arg, &radial, &freq))
1226         fgSetDouble("/instrumentation/nav[0]/radials/selected-deg", radial);
1227     fgSetDouble("/instrumentation/nav[0]/frequencies/selected-mhz", freq);
1228     return FG_OPTIONS_OK;
1229 }
1230
1231 static int
1232 fgOptNAV2( const char * arg )
1233 {
1234     double radial, freq;
1235     if (parse_colon(arg, &radial, &freq))
1236         fgSetDouble("/instrumentation/nav[1]/radials/selected-deg", radial);
1237     fgSetDouble("/instrumentation/nav[1]/frequencies/selected-mhz", freq);
1238     return FG_OPTIONS_OK;
1239 }
1240
1241 static int
1242 fgOptADF1( const char * arg )
1243 {
1244     double rot, freq;
1245     if (parse_colon(arg, &rot, &freq))
1246         fgSetDouble("/instrumentation/adf[0]/rotation-deg", rot);
1247     fgSetDouble("/instrumentation/adf[0]/frequencies/selected-khz", freq);
1248     return FG_OPTIONS_OK;
1249 }
1250
1251 static int
1252 fgOptADF2( const char * arg )
1253 {
1254     double rot, freq;
1255     if (parse_colon(arg, &rot, &freq))
1256         fgSetDouble("/instrumentation/adf[1]/rotation-deg", rot);
1257     fgSetDouble("/instrumentation/adf[1]/frequencies/selected-khz", freq);
1258     return FG_OPTIONS_OK;
1259 }
1260
1261 static int
1262 fgOptDME( const char *arg )
1263 {
1264     string opt = arg;
1265     if (opt == "nav1") {
1266         fgSetInt("/instrumentation/dme/switch-position", 1);
1267         fgSetString("/instrumentation/dme/frequencies/source",
1268                     "/instrumentation/nav[0]/frequencies/selected-mhz");
1269     } else if (opt == "nav2") {
1270         fgSetInt("/instrumentation/dme/switch-position", 3);
1271         fgSetString("/instrumentation/dme/frequencies/source",
1272                     "/instrumentation/nav[1]/frequencies/selected-mhz");
1273     } else {
1274         double frequency = atof(arg);
1275         if (frequency==0.0)
1276         {
1277             SG_LOG(SG_INPUT, SG_ALERT, "Invalid DME frequency: '" << arg << "'.");
1278             return FG_OPTIONS_ERROR;
1279         }
1280         fgSetInt("/instrumentation/dme/switch-position", 2);
1281         fgSetString("/instrumentation/dme/frequencies/source",
1282                     "/instrumentation/dme/frequencies/selected-mhz");
1283         fgSetDouble("/instrumentation/dme/frequencies/selected-mhz", frequency);
1284     }
1285     return FG_OPTIONS_OK;
1286 }
1287
1288 static int
1289 fgOptLivery( const char *arg )
1290 {
1291     string opt = arg;
1292     string livery_path = "livery/" + opt;
1293     fgSetString("/sim/model/texture-path", livery_path.c_str() );
1294     return FG_OPTIONS_OK;
1295 }
1296
1297 static int
1298 fgOptScenario( const char *arg )
1299 {
1300     SGPropertyNode_ptr ai_node = fgGetNode( "/sim/ai", true );
1301     vector<SGPropertyNode_ptr> scenarii = ai_node->getChildren( "scenario" );
1302     int index = -1;
1303     for ( size_t i = 0; i < scenarii.size(); ++i ) {
1304         int ind = scenarii[i]->getIndex();
1305         if ( index < ind ) {
1306             index = ind;
1307         }
1308     }
1309     SGPropertyNode_ptr scenario = ai_node->getNode( "scenario", index + 1, true );
1310     scenario->setStringValue( arg );
1311     return FG_OPTIONS_OK;
1312 }
1313
1314 static int
1315 fgOptRunway( const char *arg )
1316 {
1317     fgSetString("/sim/presets/runway", arg );
1318     fgSetBool("/sim/presets/runway-requested", true );
1319     return FG_OPTIONS_OK;
1320 }
1321
1322 static int
1323 fgOptParking( const char *arg )
1324 {
1325     cerr << "Processing argument " << arg << endl;
1326     fgSetString("/sim/presets/parking", arg );
1327     fgSetBool  ("/sim/presets/parking-requested", true );
1328     return FG_OPTIONS_OK;
1329 }
1330
1331 static int
1332 fgOptVersion( const char *arg )
1333 {
1334     cerr << "FlightGear version: " << FLIGHTGEAR_VERSION << endl;
1335     cerr << "Revision: " << REVISION << endl;
1336     cerr << "Build-Id: " << HUDSON_BUILD_ID << endl;
1337     cerr << "FG_ROOT=" << globals->get_fg_root() << endl;
1338     cerr << "FG_HOME=" << globals->get_fg_home() << endl;
1339     cerr << "FG_SCENERY=";
1340
1341     int didsome = 0;
1342     string_list scn = globals->get_fg_scenery();
1343     for (string_list::const_iterator it = scn.begin(); it != scn.end(); it++)
1344     {
1345         if (didsome) cerr << ":";
1346         didsome++;
1347         cerr << *it;
1348     }
1349     cerr << endl;
1350     cerr << "SimGear version: " << SG_STRINGIZE(SIMGEAR_VERSION) << endl;
1351     cerr << "OSG version: " << osgGetVersion() << endl;
1352     cerr << "PLIB version: " << PLIB_VERSION << endl;
1353     return FG_OPTIONS_EXIT;
1354 }
1355
1356 static int
1357 fgOptCallSign(const char * arg)
1358 {
1359     int i;
1360     char callsign[11];
1361     strncpy(callsign,arg,10);
1362     callsign[10]=0;
1363     for (i=0;callsign[i];i++)
1364     {
1365         char c = callsign[i];
1366         if (c >= 'A' && c <= 'Z') continue;
1367         if (c >= 'a' && c <= 'z') continue;
1368         if (c >= '0' && c <= '9') continue;
1369         if (c == '-' || c == '_') continue;
1370         // convert any other illegal characters
1371         callsign[i]='-';
1372     }
1373     fgSetString("sim/multiplay/callsign", callsign );
1374     return FG_OPTIONS_OK;
1375 }
1376
1377 static int
1378 fgOptIgnoreAutosave(const char* arg)
1379 {
1380     fgSetBool("/sim/startup/ignore-autosave", true);
1381     // don't overwrite autosave on exit
1382     fgSetBool("/sim/startup/save-on-exit", false);
1383     return FG_OPTIONS_OK;
1384 }
1385
1386 static int
1387 fgOptEnableFreeze(const char* arg)
1388 {
1389     fgSetBool("/sim/freeze/master", true);
1390     fgSetBool("/sim/freeze/clock", true);
1391     return FG_OPTIONS_OK;
1392 }
1393
1394 static int
1395 fgOptDisableFreeze(const char* arg)
1396 {
1397     fgSetBool("/sim/freeze/master", false);
1398     fgSetBool("/sim/freeze/clock", false);
1399     return FG_OPTIONS_OK;
1400 }
1401
1402 // Set a property for the --prop: option. Syntax: --prop:[<type>:]<name>=<value>
1403 // <type> can be "double" etc. but also only the first letter "d".
1404 // Examples:  --prop:alpha=1  --prop:bool:beta=true  --prop:d:gamma=0.123
1405 static int
1406 fgOptSetProperty(const char* raw)
1407 {
1408   string arg(raw);
1409   string::size_type pos = arg.find('=');
1410   if (pos == arg.npos || pos == 0 || pos + 1 == arg.size())
1411     return FG_OPTIONS_ERROR;
1412   
1413   string name = arg.substr(0, pos);
1414   string value = arg.substr(pos + 1);
1415   string type;
1416   pos = name.find(':');
1417   
1418   if (pos != name.npos && pos != 0 && pos + 1 != name.size()) {
1419     type = name.substr(0, pos);
1420     name = name.substr(pos + 1);
1421   }
1422   SGPropertyNode *n = fgGetNode(name.c_str(), true);
1423   
1424   bool writable = n->getAttribute(SGPropertyNode::WRITE);
1425   if (!writable)
1426     n->setAttribute(SGPropertyNode::WRITE, true);
1427   
1428   bool ret = false;
1429   if (type.empty())
1430     ret = n->setUnspecifiedValue(value.c_str());
1431   else if (type == "s" || type == "string")
1432     ret = n->setStringValue(value.c_str());
1433   else if (type == "d" || type == "double")
1434     ret = n->setDoubleValue(strtod(value.c_str(), 0));
1435   else if (type == "f" || type == "float")
1436     ret = n->setFloatValue(atof(value.c_str()));
1437   else if (type == "l" || type == "long")
1438     ret =  n->setLongValue(strtol(value.c_str(), 0, 0));
1439   else if (type == "i" || type == "int")
1440     ret =  n->setIntValue(atoi(value.c_str()));
1441   else if (type == "b" || type == "bool")
1442     ret =  n->setBoolValue(value == "true" || atoi(value.c_str()) != 0);
1443   
1444   if (!writable)
1445     n->setAttribute(SGPropertyNode::WRITE, false);
1446   return ret ? FG_OPTIONS_OK : FG_OPTIONS_ERROR;
1447 }
1448
1449 static int
1450 fgOptLoadTape(const char* arg)
1451 {
1452   // load a flight recorder tape but wait until the fdm is initialized
1453   class DelayedTapeLoader : SGPropertyChangeListener {
1454   public:
1455     DelayedTapeLoader( const char * tape ) :
1456       _tape(tape)
1457     {
1458       SGPropertyNode_ptr n = fgGetNode("/sim/signals/fdm-initialized", true);
1459       n->addChangeListener( this );
1460     }
1461
1462     virtual ~ DelayedTapeLoader() {}
1463
1464     virtual void valueChanged(SGPropertyNode * node)
1465     {
1466       node->removeChangeListener( this );
1467
1468       // tell the replay subsystem to load the tape
1469       FGReplay* replay = (FGReplay*) globals->get_subsystem("replay");
1470       SGPropertyNode_ptr arg = new SGPropertyNode();
1471       arg->setStringValue("tape", _tape );
1472       arg->setBoolValue( "same-aircraft", 0 );
1473       replay->loadTape(arg);
1474
1475       delete this; // commence suicide
1476     }
1477   private:
1478     std::string _tape;
1479
1480   };
1481
1482   new DelayedTapeLoader(arg);
1483   return FG_OPTIONS_OK;
1484 }
1485
1486
1487
1488 /*
1489    option       has_param type        property         b_param s_param  func
1490
1491 where:
1492  option    : name of the option
1493  has_param : option is --name=value if true or --name if false
1494  type      : OPTION_BOOL    - property is a boolean
1495              OPTION_STRING  - property is a string
1496              OPTION_DOUBLE  - property is a double
1497              OPTION_INT     - property is an integer
1498              OPTION_CHANNEL - name of option is the name of a channel
1499              OPTION_FUNC    - the option trigger a function
1500  b_param   : if type==OPTION_BOOL,
1501              value set to the property (has_param is false for boolean)
1502  s_param   : if type==OPTION_STRING,
1503              value set to the property if has_param is false
1504  func      : function called if type==OPTION_FUNC. if has_param is true,
1505              the value is passed to the function as a string, otherwise,
1506              s_param is passed.
1507
1508     For OPTION_DOUBLE and OPTION_INT, the parameter value is converted into a
1509     double or an integer and set to the property.
1510
1511     For OPTION_CHANNEL, add_channel is called with the parameter value as the
1512     argument.
1513 */
1514
1515 enum OptionType { OPTION_BOOL = 0, OPTION_STRING, OPTION_DOUBLE, OPTION_INT, OPTION_CHANNEL, OPTION_FUNC, OPTION_IGNORE };
1516 const int OPTION_MULTI = 1 << 17;
1517
1518 struct OptionDesc {
1519     const char *option;
1520     bool has_param;
1521     int type;
1522     const char *property;
1523     bool b_param;
1524     const char *s_param;
1525     int (*func)( const char * );
1526     } fgOptionArray[] = {
1527
1528     {"language",                     true,  OPTION_IGNORE, "", false, "", 0 },
1529         {"console",                      false, OPTION_IGNORE,   "", false, "", 0 },
1530     {"launcher",                     false, OPTION_IGNORE,   "", false, "", 0 },
1531     {"disable-rembrandt",            false, OPTION_BOOL,   "/sim/rendering/rembrandt/enabled", false, "", 0 },
1532     {"enable-rembrandt",             false, OPTION_BOOL,   "/sim/rendering/rembrandt/enabled", true, "", 0 },
1533     {"renderer",                     true,  OPTION_STRING, "/sim/rendering/rembrandt/renderer", false, "", 0 },
1534     {"disable-splash-screen",        false, OPTION_BOOL,   "/sim/startup/splash-screen", false, "", 0 },
1535     {"enable-splash-screen",         false, OPTION_BOOL,   "/sim/startup/splash-screen", true, "", 0 },
1536     {"disable-mouse-pointer",        false, OPTION_STRING, "/sim/startup/mouse-pointer", false, "disabled", 0 },
1537     {"enable-mouse-pointer",         false, OPTION_STRING, "/sim/startup/mouse-pointer", false, "enabled", 0 },
1538     {"disable-random-objects",       false, OPTION_BOOL,   "/sim/rendering/random-objects", false, "", 0 },
1539     {"enable-random-objects",        false, OPTION_BOOL,   "/sim/rendering/random-objects", true, "", 0 },
1540     {"disable-random-vegetation",    false, OPTION_BOOL,   "/sim/rendering/random-vegetation", false, "", 0 },
1541     {"enable-random-vegetation",     false, OPTION_BOOL,   "/sim/rendering/random-vegetation", true, "", 0 },
1542     {"disable-random-buildings",     false, OPTION_BOOL,   "/sim/rendering/random-buildings", false, "", 0 },
1543     {"enable-random-buildings",      false, OPTION_BOOL,   "/sim/rendering/random-buildings", true, "", 0 },
1544     {"disable-real-weather-fetch",   false, OPTION_BOOL,   "/environment/realwx/enabled", false, "", 0 },
1545     {"enable-real-weather-fetch",    false, OPTION_BOOL,   "/environment/realwx/enabled", true,  "", 0 },
1546     {"metar",                        true,  OPTION_FUNC,   "", false, "", fgOptMetar },
1547     {"disable-ai-models",            false, OPTION_BOOL,   "/sim/ai/enabled", false, "", 0 },
1548     {"enable-ai-models",             false, OPTION_BOOL,   "/sim/ai/enabled", true, "", 0 },
1549     {"disable-ai-traffic",           false, OPTION_BOOL,   "/sim/traffic-manager/enabled", false, "", 0 },
1550     {"enable-ai-traffic",            false, OPTION_BOOL,   "/sim/traffic-manager/enabled", true,  "", 0 },
1551     {"disable-freeze",               false, OPTION_FUNC,   "", false, "", fgOptDisableFreeze },
1552     {"enable-freeze",                false, OPTION_FUNC,   "", true, "", fgOptEnableFreeze },
1553     {"disable-fuel-freeze",          false, OPTION_BOOL,   "/sim/freeze/fuel", false, "", 0 },
1554     {"enable-fuel-freeze",           false, OPTION_BOOL,   "/sim/freeze/fuel", true, "", 0 },
1555     {"disable-clock-freeze",         false, OPTION_BOOL,   "/sim/freeze/clock", false, "", 0 },
1556     {"enable-clock-freeze",          false, OPTION_BOOL,   "/sim/freeze/clock", true, "", 0 },
1557     {"disable-hud-3d",               false, OPTION_BOOL,   "/sim/hud/enable3d[1]", false, "", 0 },
1558     {"enable-hud-3d",                false, OPTION_BOOL,   "/sim/hud/enable3d[1]", true, "", 0 },
1559     {"disable-anti-alias-hud",       false, OPTION_BOOL,   "/sim/hud/color/antialiased", false, "", 0 },
1560     {"enable-anti-alias-hud",        false, OPTION_BOOL,   "/sim/hud/color/antialiased", true, "", 0 },
1561     {"disable-auto-coordination",    false, OPTION_BOOL,   "/controls/flight/auto-coordination", false, "", 0 },
1562     {"enable-auto-coordination",     false, OPTION_BOOL,   "/controls/flight/auto-coordination", true, "", 0 },
1563     {"browser-app",                  true,  OPTION_STRING, "/sim/startup/browser-app", false, "", 0 },
1564     {"disable-hud",                  false, OPTION_BOOL,   "/sim/hud/visibility[1]", false, "", 0 },
1565     {"enable-hud",                   false, OPTION_BOOL,   "/sim/hud/visibility[1]", true, "", 0 },
1566     {"disable-panel",                false, OPTION_BOOL,   "/sim/panel/visibility", false, "", 0 },
1567     {"enable-panel",                 false, OPTION_BOOL,   "/sim/panel/visibility", true, "", 0 },
1568     {"disable-sound",                false, OPTION_BOOL,   "/sim/sound/working", false, "", 0 },
1569     {"enable-sound",                 false, OPTION_BOOL,   "/sim/sound/working", true, "", 0 },
1570     {"sound-device",                 true,  OPTION_STRING, "/sim/sound/device-name", false, "", 0 },
1571     {"airport",                      true,  OPTION_STRING, "/sim/presets/airport-id", false, "", 0 },
1572     {"runway",                       true,  OPTION_FUNC,   "", false, "", fgOptRunway },
1573     {"vor",                          true,  OPTION_FUNC,   "", false, "", fgOptVOR },
1574     {"vor-frequency",                true,  OPTION_DOUBLE, "/sim/presets/vor-freq", false, "", fgOptVOR },
1575     {"ndb",                          true,  OPTION_FUNC,   "", false, "", fgOptNDB },
1576     {"ndb-frequency",                true,  OPTION_DOUBLE, "/sim/presets/ndb-freq", false, "", fgOptVOR },
1577     {"carrier",                      true,  OPTION_FUNC,   "", false, "", fgOptCarrier },
1578     {"parkpos",                      true,  OPTION_FUNC,   "", false, "", fgOptParkpos },
1579     {"fix",                          true,  OPTION_FUNC,   "", false, "", fgOptFIX },
1580     {"offset-distance",              true,  OPTION_DOUBLE, "/sim/presets/offset-distance-nm", false, "", 0 },
1581     {"offset-azimuth",               true,  OPTION_DOUBLE, "/sim/presets/offset-azimuth-deg", false, "", 0 },
1582     {"lon",                          true,  OPTION_FUNC,   "", false, "", fgOptLon },
1583     {"lat",                          true,  OPTION_FUNC,   "", false, "", fgOptLat },
1584     {"altitude",                     true,  OPTION_FUNC,   "", false, "", fgOptAltitude },
1585     {"uBody",                        true,  OPTION_FUNC,   "", false, "", fgOptUBody },
1586     {"vBody",                        true,  OPTION_FUNC,   "", false, "", fgOptVBody },
1587     {"wBody",                        true,  OPTION_FUNC,   "", false, "", fgOptWBody },
1588     {"vNorth",                       true,  OPTION_FUNC,   "", false, "", fgOptVNorth },
1589     {"vEast",                        true,  OPTION_FUNC,   "", false, "", fgOptVEast },
1590     {"vDown",                        true,  OPTION_FUNC,   "", false, "", fgOptVDown },
1591     {"vc",                           true,  OPTION_FUNC,   "", false, "", fgOptVc },
1592     {"mach",                         true,  OPTION_FUNC,   "", false, "", fgOptMach },
1593     {"heading",                      true,  OPTION_DOUBLE, "/sim/presets/heading-deg", false, "", 0 },
1594     {"roll",                         true,  OPTION_DOUBLE, "/sim/presets/roll-deg", false, "", 0 },
1595     {"pitch",                        true,  OPTION_DOUBLE, "/sim/presets/pitch-deg", false, "", 0 },
1596     {"glideslope",                   true,  OPTION_DOUBLE, "/sim/presets/glideslope-deg", false, "", 0 },
1597     {"roc",                          true,  OPTION_FUNC,   "", false, "", fgOptRoc },
1598     {"fg-root",                      true,  OPTION_IGNORE,   "", false, "", 0 },
1599     {"fg-scenery",                   true,  OPTION_FUNC | OPTION_MULTI,   "", false, "", fgOptFgScenery },
1600     {"fg-aircraft",                  true,  OPTION_IGNORE | OPTION_MULTI,   "", false, "", 0 },
1601     {"fdm",                          true,  OPTION_STRING, "/sim/flight-model", false, "", 0 },
1602     {"aero",                         true,  OPTION_STRING, "/sim/aero", false, "", 0 },
1603     {"aircraft-dir",                 true,  OPTION_IGNORE,   "", false, "", 0 },
1604     {"model-hz",                     true,  OPTION_INT,    "/sim/model-hz", false, "", 0 },
1605     {"max-fps",                      true,  OPTION_DOUBLE, "/sim/frame-rate-throttle-hz", false, "", 0 },
1606     {"speed",                        true,  OPTION_DOUBLE, "/sim/speed-up", false, "", 0 },
1607     {"trim",                         false, OPTION_BOOL,   "/sim/presets/trim", true, "", 0 },
1608     {"notrim",                       false, OPTION_BOOL,   "/sim/presets/trim", false, "", 0 },
1609     {"on-ground",                    false, OPTION_BOOL,   "/sim/presets/onground", true, "", 0 },
1610     {"in-air",                       false, OPTION_BOOL,   "/sim/presets/onground", false, "", 0 },
1611     {"fog-disable",                  false, OPTION_STRING, "/sim/rendering/fog", false, "disabled", 0 },
1612     {"fog-fastest",                  false, OPTION_STRING, "/sim/rendering/fog", false, "fastest", 0 },
1613     {"fog-nicest",                   false, OPTION_STRING, "/sim/rendering/fog", false, "nicest", 0 },
1614     {"disable-horizon-effect",       false, OPTION_BOOL,   "/sim/rendering/horizon-effect", false, "", 0 },
1615     {"enable-horizon-effect",        false, OPTION_BOOL,   "/sim/rendering/horizon-effect", true, "", 0 },
1616     {"disable-enhanced-lighting",    false, OPTION_BOOL,   "/sim/rendering/enhanced-lighting", false, "", 0 },
1617     {"enable-enhanced-lighting",     false, OPTION_BOOL,   "/sim/rendering/enhanced-lighting", true, "", 0 },
1618     {"disable-distance-attenuation", false, OPTION_BOOL,   "/sim/rendering/distance-attenuation", false, "", 0 },
1619     {"enable-distance-attenuation",  false, OPTION_BOOL,   "/sim/rendering/distance-attenuation", true, "", 0 },
1620     {"disable-specular-highlight",   false, OPTION_BOOL,   "/sim/rendering/specular-highlight", false, "", 0 },
1621     {"enable-specular-highlight",    false, OPTION_BOOL,   "/sim/rendering/specular-highlight", true, "", 0 },
1622     {"disable-clouds",               false, OPTION_BOOL,   "/environment/clouds/status", false, "", 0 },
1623     {"enable-clouds",                false, OPTION_BOOL,   "/environment/clouds/status", true, "", 0 },
1624     {"disable-clouds3d",             false, OPTION_BOOL,   "/sim/rendering/clouds3d-enable", false, "", 0 },
1625     {"enable-clouds3d",              false, OPTION_BOOL,   "/sim/rendering/clouds3d-enable", true, "", 0 },
1626     {"fov",                          true,  OPTION_FUNC,   "", false, "", fgOptFov },
1627     {"aspect-ratio-multiplier",      true,  OPTION_DOUBLE, "/sim/current-view/aspect-ratio-multiplier", false, "", 0 },
1628     {"disable-fullscreen",           false, OPTION_BOOL,   "/sim/startup/fullscreen", false, "", 0 },
1629     {"enable-fullscreen",            false, OPTION_BOOL,   "/sim/startup/fullscreen", true, "", 0 },
1630     {"disable-save-on-exit",         false, OPTION_BOOL,   "/sim/startup/save-on-exit", false, "", 0 },
1631     {"enable-save-on-exit",          false, OPTION_BOOL,   "/sim/startup/save-on-exit", true, "", 0 },
1632     {"read-only",                    false, OPTION_BOOL,   "/sim/fghome-readonly", true, "", 0 },
1633     {"ignore-autosave",              false, OPTION_FUNC,   "", false, "", fgOptIgnoreAutosave },
1634     {"restore-defaults",             false, OPTION_BOOL,   "/sim/startup/restore-defaults", true, "", 0 },
1635     {"shading-flat",                 false, OPTION_BOOL,   "/sim/rendering/shading", false, "", 0 },
1636     {"shading-smooth",               false, OPTION_BOOL,   "/sim/rendering/shading", true, "", 0 },
1637     {"texture-filtering",            false, OPTION_INT,    "/sim/rendering/filtering", 1, "", 0 },
1638     {"disable-wireframe",            false, OPTION_BOOL,   "/sim/rendering/wireframe", false, "", 0 },
1639     {"enable-wireframe",             false, OPTION_BOOL,   "/sim/rendering/wireframe", true, "", 0 },
1640     {"materials-file",               true,  OPTION_STRING, "/sim/rendering/materials-file", false, "", 0 },
1641     {"disable-terrasync",            false, OPTION_BOOL,   "/sim/terrasync/enabled", false, "", 0 },
1642     {"enable-terrasync",             false, OPTION_BOOL,   "/sim/terrasync/enabled", true, "", 0 },
1643     {"terrasync-dir",                true,  OPTION_FUNC,   "", false, "", fgOptTerrasyncDir },
1644     {"download-dir",                 true,  OPTION_STRING, "/sim/paths/download-dir", false, "", 0 },
1645     {"geometry",                     true,  OPTION_FUNC,   "", false, "", fgOptGeometry },
1646     {"bpp",                          true,  OPTION_FUNC,   "", false, "", fgOptBpp },
1647     {"units-feet",                   false, OPTION_STRING, "/sim/startup/units", false, "feet", 0 },
1648     {"units-meters",                 false, OPTION_STRING, "/sim/startup/units", false, "meters", 0 },
1649     {"timeofday",                    true,  OPTION_STRING, "/sim/startup/time-offset-type", false, "noon", 0 },
1650     {"season",                       true,  OPTION_STRING, "/sim/startup/season", false, "summer", 0 },
1651     {"time-offset",                  true,  OPTION_FUNC,   "", false, "", fgOptTimeOffset },
1652     {"time-match-real",              false, OPTION_STRING, "/sim/startup/time-offset-type", false, "system-offset", 0 },
1653     {"time-match-local",             false, OPTION_STRING, "/sim/startup/time-offset-type", false, "latitude-offset", 0 },
1654     {"start-date-sys",               true,  OPTION_FUNC,   "", false, "", fgOptStartDateSys },
1655     {"start-date-lat",               true,  OPTION_FUNC,   "", false, "", fgOptStartDateLat },
1656     {"start-date-gmt",               true,  OPTION_FUNC,   "", false, "", fgOptStartDateGmt },
1657     {"hud-tris",                     false, OPTION_STRING, "/sim/hud/frame-stat-type", false, "tris", 0 },
1658     {"hud-culled",                   false, OPTION_STRING, "/sim/hud/frame-stat-type", false, "culled", 0 },
1659     {"atcsim",                       true,  OPTION_CHANNEL, "", false, "dummy", 0 },
1660     {"atlas",                        true,  OPTION_CHANNEL | OPTION_MULTI, "", false, "", 0 },
1661     {"httpd",                        true,  OPTION_FUNC   , "", false, "", fgOptHttpd },
1662     {"jpg-httpd",                    true,  OPTION_FUNC,    "", false, "", fgOptJpgHttpd },
1663     {"native",                       true,  OPTION_CHANNEL | OPTION_MULTI, "", false, "", 0 },
1664     {"native-ctrls",                 true,  OPTION_CHANNEL | OPTION_MULTI, "", false, "", 0 },
1665     {"native-fdm",                   true,  OPTION_CHANNEL | OPTION_MULTI, "", false, "", 0 },
1666     {"native-gui",                   true,  OPTION_CHANNEL | OPTION_MULTI, "", false, "", 0 },
1667     {"opengc",                       true,  OPTION_CHANNEL | OPTION_MULTI, "", false, "", 0 },
1668     {"AV400",                        true,  OPTION_CHANNEL | OPTION_MULTI, "", false, "", 0 },
1669     {"AV400Sim",                     true,  OPTION_CHANNEL | OPTION_MULTI, "", false, "", 0 },
1670     {"AV400WSimA",                   true,  OPTION_CHANNEL | OPTION_MULTI, "", false, "", 0 },
1671     {"AV400WSimB",                   true,  OPTION_CHANNEL | OPTION_MULTI, "", false, "", 0 },
1672     {"garmin",                       true,  OPTION_CHANNEL | OPTION_MULTI, "", false, "", 0 },
1673     {"igc",                          true,  OPTION_CHANNEL | OPTION_MULTI, "", false, "", 0 },
1674     {"nmea",                         true,  OPTION_CHANNEL | OPTION_MULTI, "", false, "", 0 },
1675     {"generic",                      true,  OPTION_CHANNEL | OPTION_MULTI, "", false, "", 0 },
1676     {"props",                        true,  OPTION_CHANNEL | OPTION_MULTI, "", false, "", 0 },
1677     {"telnet",                       true,  OPTION_CHANNEL | OPTION_MULTI, "", false, "", 0 },
1678     {"pve",                          true,  OPTION_CHANNEL, "", false, "", 0 },
1679     {"ray",                          true,  OPTION_CHANNEL, "", false, "", 0 },
1680     {"rul",                          true,  OPTION_CHANNEL, "", false, "", 0 },
1681     {"joyclient",                    true,  OPTION_CHANNEL, "", false, "", 0 },
1682     {"jsclient",                     true,  OPTION_CHANNEL, "", false, "", 0 },
1683     {"proxy",                        true,  OPTION_FUNC,    "", false, "", fgSetupProxy },
1684     {"callsign",                     true,  OPTION_FUNC,    "", false, "", fgOptCallSign},
1685     {"multiplay",                    true,  OPTION_CHANNEL | OPTION_MULTI, "", false, "", 0 },
1686 #if FG_HAVE_HLA
1687     {"hla",                          true,  OPTION_CHANNEL, "", false, "", 0 },
1688     {"hla-local",                    true,  OPTION_CHANNEL, "", false, "", 0 },
1689 #endif
1690     {"trace-read",                   true,  OPTION_FUNC | OPTION_MULTI,   "", false, "", fgOptTraceRead },
1691     {"trace-write",                  true,  OPTION_FUNC | OPTION_MULTI,   "", false, "", fgOptTraceWrite },
1692     {"log-level",                    true,  OPTION_FUNC,   "", false, "", fgOptLogLevel },
1693     {"log-class",                    true,  OPTION_FUNC,   "", false, "", fgOptLogClasses },
1694     {"view-offset",                  true,  OPTION_FUNC | OPTION_MULTI,   "", false, "", fgOptViewOffset },
1695     {"visibility",                   true,  OPTION_FUNC,   "", false, "", fgOptVisibilityMeters },
1696     {"visibility-miles",             true,  OPTION_FUNC,   "", false, "", fgOptVisibilityMiles },
1697     {"random-wind",                  false, OPTION_FUNC,   "", false, "", fgOptRandomWind },
1698     {"wind",                         true,  OPTION_FUNC | OPTION_MULTI,   "", false, "", fgOptWind },
1699     {"turbulence",                   true,  OPTION_FUNC,   "", false, "", fgOptTurbulence },
1700     {"ceiling",                      true,  OPTION_FUNC,   "", false, "", fgOptCeiling },
1701     {"wp",                           true,  OPTION_FUNC | OPTION_MULTI,   "", false, "", fgOptWp },
1702     {"flight-plan",                  true,  OPTION_STRING,   "/autopilot/route-manager/file-path", false, "", NULL },
1703     {"config",                       true,  OPTION_FUNC | OPTION_MULTI,   "", false, "", fgOptConfig },
1704     {"aircraft",                     true,  OPTION_STRING, "/sim/aircraft", false, "", 0 },
1705     {"vehicle",                      true,  OPTION_STRING, "/sim/aircraft", false, "", 0 },
1706     {"failure",                      true,  OPTION_FUNC | OPTION_MULTI,   "", false, "", fgOptFailure },
1707 #ifdef ENABLE_IAX
1708     {"enable-fgcom",                 false, OPTION_BOOL,   "/sim/fgcom/enabled", true, "", 0 },
1709     {"disable-fgcom",                false, OPTION_BOOL,   "/sim/fgcom/enabled", false, "", 0 },
1710 #endif
1711     {"com1",                         true,  OPTION_DOUBLE, "/instrumentation/comm[0]/frequencies/selected-mhz", false, "", 0 },
1712     {"com2",                         true,  OPTION_DOUBLE, "/instrumentation/comm[1]/frequencies/selected-mhz", false, "", 0 },
1713     {"nav1",                         true,  OPTION_FUNC,   "", false, "", fgOptNAV1 },
1714     {"nav2",                         true,  OPTION_FUNC,   "", false, "", fgOptNAV2 },
1715     {"adf", /*legacy*/               true,  OPTION_FUNC,   "", false, "", fgOptADF1 },
1716     {"adf1",                         true,  OPTION_FUNC,   "", false, "", fgOptADF1 },
1717     {"adf2",                         true,  OPTION_FUNC,   "", false, "", fgOptADF2 },
1718     {"dme",                          true,  OPTION_FUNC,   "", false, "", fgOptDME },
1719     {"min-status",                   true,  OPTION_STRING,  "/sim/aircraft-min-status", false, "all", 0 },
1720     {"livery",                       true,  OPTION_FUNC,   "", false, "", fgOptLivery },
1721     {"ai-scenario",                  true,  OPTION_FUNC | OPTION_MULTI,   "", false, "", fgOptScenario },
1722     {"parking-id",                   true,  OPTION_FUNC,   "", false, "", fgOptParking  },
1723     {"version",                      false, OPTION_FUNC,   "", false, "", fgOptVersion },
1724     {"enable-fpe",                   false, OPTION_IGNORE,   "", false, "", 0},
1725     {"fgviewer",                     false, OPTION_IGNORE,   "", false, "", 0},
1726     {"no-default-config",            false, OPTION_IGNORE, "", false, "", 0},
1727     {"prop",                         true,  OPTION_FUNC | OPTION_MULTI,   "", false, "", fgOptSetProperty},
1728     {"load-tape",                    true,  OPTION_FUNC,   "", false, "", fgOptLoadTape },
1729     {0}
1730 };
1731
1732
1733 namespace flightgear
1734 {
1735
1736 /**
1737  * internal storage of a value->option binding
1738  */
1739 class OptionValue 
1740 {
1741 public:
1742   OptionValue(OptionDesc* d, const string& v) :
1743     desc(d), value(v)
1744   {;}
1745   
1746   OptionDesc* desc;
1747   string value;
1748 };
1749
1750 typedef std::vector<OptionValue> OptionValueVec;
1751 typedef std::map<string, OptionDesc*> OptionDescDict;
1752   
1753 class Options::OptionsPrivate
1754 {
1755 public:
1756   
1757   OptionValueVec::const_iterator findValue(const string& key) const
1758   {
1759     OptionValueVec::const_iterator it = values.begin();
1760     for (; it != values.end(); ++it) {
1761       if (!it->desc) {
1762         continue; // ignore markers
1763       }
1764       
1765       if (it->desc->option == key) {
1766         return it;
1767       }
1768     } // of set values iteration
1769     
1770     return it; // not found
1771   }
1772
1773     OptionValueVec::iterator findValue(const string& key)
1774     {
1775         OptionValueVec::iterator it = values.begin();
1776         for (; it != values.end(); ++it) {
1777             if (!it->desc) {
1778                 continue; // ignore markers
1779             }
1780
1781             if (it->desc->option == key) {
1782                 return it;
1783             }
1784         } // of set values iteration
1785         
1786         return it; // not found
1787     }
1788   
1789   OptionDesc* findOption(const string& key) const
1790   {
1791     OptionDescDict::const_iterator it = options.find(key);
1792     if (it == options.end()) {
1793       return NULL;
1794     }
1795     
1796     return it->second;
1797   }
1798   
1799   int processOption(OptionDesc* desc, const string& arg_value)
1800   {
1801     if (!desc) {
1802       return FG_OPTIONS_OK; // tolerate marker options
1803     }
1804     
1805     switch ( desc->type & 0xffff ) {
1806       case OPTION_BOOL:
1807         fgSetBool( desc->property, desc->b_param );
1808         break;
1809       case OPTION_STRING:
1810         if ( desc->has_param && !arg_value.empty() ) {
1811           fgSetString( desc->property, arg_value.c_str() );
1812         } else if ( !desc->has_param && arg_value.empty() ) {
1813           fgSetString( desc->property, desc->s_param );
1814         } else if ( desc->has_param ) {
1815           SG_LOG( SG_GENERAL, SG_ALERT, "Option '" << desc->option << "' needs a parameter" );
1816           return FG_OPTIONS_ERROR;
1817         } else {
1818           SG_LOG( SG_GENERAL, SG_ALERT, "Option '" << desc->option << "' does not have a parameter" );
1819           return FG_OPTIONS_ERROR;
1820         }
1821         break;
1822       case OPTION_DOUBLE:
1823         if ( !arg_value.empty() ) {
1824           fgSetDouble( desc->property, atof( arg_value ) );
1825         } else {
1826           SG_LOG( SG_GENERAL, SG_ALERT, "Option '" << desc->option << "' needs a parameter" );
1827           return FG_OPTIONS_ERROR;
1828         }
1829         break;
1830       case OPTION_INT:
1831         if ( !arg_value.empty() ) {
1832           fgSetInt( desc->property, atoi( arg_value ) );
1833         } else {
1834           SG_LOG( SG_GENERAL, SG_ALERT, "Option '" << desc->option << "' needs a parameter" );
1835           return FG_OPTIONS_ERROR;
1836         }
1837         break;
1838       case OPTION_CHANNEL:
1839         // XXX return value of add_channel should be checked?
1840         if ( desc->has_param && !arg_value.empty() ) {
1841           add_channel( desc->option, arg_value );
1842         } else if ( !desc->has_param && arg_value.empty() ) {
1843           add_channel( desc->option, desc->s_param );
1844         } else if ( desc->has_param ) {
1845           SG_LOG( SG_GENERAL, SG_ALERT, "Option '" << desc->option << "' needs a parameter" );
1846           return FG_OPTIONS_ERROR;
1847         } else {
1848           SG_LOG( SG_GENERAL, SG_ALERT, "Option '" << desc->option << "' does not have a parameter" );
1849           return FG_OPTIONS_ERROR;
1850         }
1851         break;
1852       case OPTION_FUNC:
1853         if ( desc->has_param && !arg_value.empty() ) {
1854           return desc->func( arg_value.c_str() );
1855         } else if ( !desc->has_param && arg_value.empty() ) {
1856           return desc->func( desc->s_param );
1857         } else if ( desc->has_param ) {
1858           SG_LOG( SG_GENERAL, SG_ALERT, "Option '" << desc->option << "' needs a parameter" );
1859           return FG_OPTIONS_ERROR;
1860         } else {
1861           SG_LOG( SG_GENERAL, SG_ALERT, "Option '" << desc->option << "' does not have a parameter" );
1862           return FG_OPTIONS_ERROR;
1863         }
1864         break;
1865         
1866       case OPTION_IGNORE:
1867         break;
1868     }
1869     
1870     return FG_OPTIONS_OK;
1871   }
1872     
1873   /**
1874    * insert a marker value into the values vector. This is necessary
1875    * when processing options, to ensure the correct ordering, where we scan
1876    * for marker values in reverse, and then forwards within each group.
1877    */
1878   void insertGroupMarker()
1879   {
1880     values.push_back(OptionValue(NULL, "-"));
1881   }
1882   
1883   /**
1884    * given a current iterator into the values, find the preceding group marker,
1885    * or return the beginning of the value vector.
1886    */
1887   OptionValueVec::const_iterator rfindGroup(OptionValueVec::const_iterator pos) const
1888   {
1889     while (--pos != values.begin()) {
1890       if (pos->desc == NULL) {
1891         return pos; // found a marker, we're done
1892       }
1893     }
1894     
1895     return pos;
1896   }
1897   
1898   bool showHelp,
1899     verbose,
1900     showAircraft,
1901     shouldLoadDefaultConfig;
1902     
1903   OptionDescDict options;
1904   OptionValueVec values;
1905   simgear::PathList propertyFiles;
1906 };
1907   
1908 Options* Options::sharedInstance()
1909 {
1910   if (shared_instance == NULL) {
1911     shared_instance = new Options;
1912   }
1913   
1914   return shared_instance;
1915 }
1916   
1917 Options::Options() :
1918   p(new OptionsPrivate())
1919 {
1920   p->showHelp = false;
1921   p->verbose = false;
1922   p->showAircraft = false;
1923   p->shouldLoadDefaultConfig = true;
1924   
1925 // build option map
1926   OptionDesc *desc = &fgOptionArray[ 0 ];
1927   while ( desc->option != 0 ) {
1928     p->options[ desc->option ] = desc;
1929     ++desc;
1930   }
1931 }
1932   
1933 Options::~Options()
1934 {
1935 }
1936   
1937 void Options::init(int argc, char **argv, const SGPath& appDataPath)
1938 {
1939 // first, process the command line
1940   bool inOptions = true;
1941   for (int i=1; i<argc; ++i) {
1942     if (inOptions && (argv[i][0] == '-')) {
1943       if (strcmp(argv[i], "--") == 0) { // end of options delimiter
1944         inOptions = true;
1945         continue;
1946       }
1947       
1948       int result = parseOption(argv[i]);
1949       processArgResult(result);
1950     } else {
1951     // XML properties file
1952       SGPath f(argv[i]);
1953       if (!f.exists()) {
1954         SG_LOG(SG_GENERAL, SG_ALERT, "config file not found:" << f.str());
1955       } else {
1956         p->propertyFiles.push_back(f);
1957       }
1958     }
1959   } // of arguments iteration
1960   p->insertGroupMarker(); // command line is one group
1961   
1962   // establish log-level before anything else - otherwise it is not possible
1963   // to show extra (debug/info/warning) messages for the start-up phase.
1964   fgOptLogLevel(valueForOption("log-level", "alert").c_str());
1965
1966   if (!p->shouldLoadDefaultConfig) {
1967     setupRoot(argc, argv);
1968     return;
1969   }
1970   
1971 // then config files
1972   SGPath config;
1973   std::string homedir;
1974   if (getenv("HOME")) {
1975     homedir = getenv("HOME");
1976   }
1977     
1978   if( !homedir.empty() && !hostname.empty() ) {
1979     // Check for ~/.fgfsrc.hostname
1980     config.set(homedir);
1981     config.append(".fgfsrc");
1982     config.concat( "." );
1983     config.concat( hostname );
1984     readConfig(config);
1985   }
1986   
1987 // Check for ~/.fgfsrc
1988   if( !homedir.empty() ) {
1989     config.set(homedir);
1990     config.append(".fgfsrc");
1991     readConfig(config);
1992   }
1993   
1994 // check for a config file in app data
1995   SGPath appDataConfig(appDataPath);
1996   appDataConfig.append("fgfsrc");
1997   if (appDataConfig.exists()) {
1998     readConfig(appDataConfig);
1999   }
2000   
2001 // setup FG_ROOT
2002   setupRoot(argc, argv);
2003   
2004 // system.fgfsrc is disabled, as we no longer allow anything in fgdata to set
2005 // fg-root/fg-home/fg-aircraft and hence control what files Nasal can access
2006   std::string name_for_error = homedir.empty() ? appDataConfig.str() : config.str();
2007   if( ! hostname.empty() ) {
2008     config.set(globals->get_fg_root());
2009     config.append( "system.fgfsrc" );
2010     config.concat( "." );
2011     config.concat( hostname );
2012     if (config.exists()) {
2013       flightgear::fatalMessageBox("Unsupported configuration",
2014         "You have a " + config.str() + " file, which is no longer processed for security reasons",
2015         "If you created this file intentionally, please move it to " + name_for_error);
2016     }
2017   }
2018
2019   config.set(globals->get_fg_root());
2020   config.append( "system.fgfsrc" );
2021   if (config.exists()) {
2022     flightgear::fatalMessageBox("Unsupported configuration",
2023       "You have a " + config.str() + " file, which is no longer processed for security reasons",
2024       "If you created this file intentionally, please move it to " + name_for_error);
2025   }
2026 }
2027
2028 void Options::initPaths()
2029 {
2030     BOOST_FOREACH(const string& paths, valuesForOption("fg-aircraft")) {
2031         globals->append_aircraft_paths(paths);
2032     }
2033
2034     const char* envp = ::getenv("FG_AIRCRAFT");
2035     if (envp) {
2036         globals->append_aircraft_paths(envp);
2037     }
2038
2039 }
2040
2041 void Options::initAircraft()
2042 {
2043   string aircraft;
2044   if (isOptionSet("aircraft")) {
2045     aircraft = valueForOption("aircraft");
2046   } else if (isOptionSet("vehicle")) {
2047     aircraft = valueForOption("vehicle");
2048   }
2049     
2050   if (!aircraft.empty()) {
2051     SG_LOG(SG_INPUT, SG_INFO, "aircraft = " << aircraft );
2052     fgSetString("/sim/aircraft", aircraft.c_str() );
2053   } else {
2054     SG_LOG(SG_INPUT, SG_INFO, "No user specified aircraft, using default" );
2055   }
2056     
2057   if (p->showAircraft) {
2058         vector<SGPath> path_list;
2059
2060     fgOptLogLevel( "alert" );
2061
2062     // First place to check is the 'Aircraft' sub-directory in $FG_ROOT
2063
2064         path_list.push_back( SGPath( globals->get_fg_root() ) );
2065         path_list.back().append("Aircraft");
2066
2067     // Additionally, aircraft may also be found in user-defined places
2068         // (via $FG_AIRCRAFT or with the '--fg-aircraft' option)
2069
2070         string_list aircraft_paths = globals->get_aircraft_paths();
2071         for (string_list::iterator it = aircraft_paths.begin();
2072                  it != aircraft_paths.end(); ++it)
2073           path_list.push_back( SGPath(*it));
2074
2075     fgShowAircraft(path_list);
2076     exit(0);
2077   }
2078   
2079   if (isOptionSet("aircraft-dir")) {
2080     SGPath aircraftDirPath(valueForOption("aircraft-dir"));
2081
2082     // Set this now, so it's available in FindAndCacheAircraft. Use realpath()
2083     // as in FGGlobals::append_aircraft_path(), otherwise fgValidatePath()
2084     // will deny access to resources under this path if one of its components
2085     // is a symlink (which is not a problem, since it was given as is by the
2086     // user---this is very different from a symlink *under* the aircraft dir
2087     // or a scenery dir).
2088     fgSetString("/sim/aircraft-dir", aircraftDirPath.realpath().c_str());
2089   }
2090 }
2091   
2092 void Options::processArgResult(int result)
2093 {
2094   if ((result == FG_OPTIONS_HELP) || (result == FG_OPTIONS_ERROR))
2095     p->showHelp = true;
2096   else if (result == FG_OPTIONS_VERBOSE_HELP)
2097     p->verbose = true;
2098   else if (result == FG_OPTIONS_SHOW_AIRCRAFT) {
2099     p->showAircraft = true;
2100   } else if (result == FG_OPTIONS_NO_DEFAULT_CONFIG) {
2101     p->shouldLoadDefaultConfig = false;
2102   } else if (result == FG_OPTIONS_SHOW_SOUND_DEVICES) {
2103     SGSoundMgr smgr;
2104     
2105     smgr.init();
2106     string vendor = smgr.get_vendor();
2107     string renderer = smgr.get_renderer();
2108     cout << renderer << " provided by " << vendor << endl;
2109     cout << endl << "No. Device" << endl;
2110     
2111     vector <const char*>devices = smgr.get_available_devices();
2112     for (vector <const char*>::size_type i=0; i<devices.size(); i++) {
2113       cout << i << ".  \"" << devices[i] << "\"" << endl;
2114     }
2115     devices.clear();
2116     smgr.stop();
2117     exit(0);
2118   } else if (result == FG_OPTIONS_EXIT) {
2119     exit(0);
2120   }
2121 }
2122   
2123 void Options::readConfig(const SGPath& path)
2124 {
2125   sg_gzifstream in( path.str() );
2126   if ( !in.is_open() ) {
2127     return;
2128   }
2129   
2130   SG_LOG( SG_GENERAL, SG_INFO, "Processing config file: " << path.str() );
2131   
2132   in >> skipcomment;
2133   while ( ! in.eof() ) {
2134     string line;
2135     getline( in, line, '\n' );
2136     
2137     // catch extraneous (DOS) line ending character
2138     int i;
2139     for (i = line.length(); i > 0; i--)
2140       if (line[i - 1] > 32)
2141         break;
2142     line = line.substr( 0, i );
2143     
2144     if ( parseOption( line ) == FG_OPTIONS_ERROR ) {
2145       cerr << endl << "Config file parse error: " << path.str() << " '"
2146       << line << "'" << endl;
2147             p->showHelp = true;
2148     }
2149     in >> skipcomment;
2150   }
2151
2152   p->insertGroupMarker(); // each config file is a group
2153 }
2154   
2155 int Options::parseOption(const string& s)
2156 {
2157   if ((s == "--help") || (s=="-h")) {
2158     return FG_OPTIONS_HELP;
2159   } else if ( (s == "--verbose") || (s == "-v") ) {
2160     // verbose help/usage request
2161     return FG_OPTIONS_VERBOSE_HELP;
2162   } else if ((s == "--console") || (s == "-c")) {
2163           simgear::requestConsole();
2164           return FG_OPTIONS_OK;
2165   } else if (s.find("-psn") == 0) {
2166     // on Mac, when launched from the GUI, we are passed the ProcessSerialNumber
2167     // as an argument (and no others). Silently ignore the argument here.
2168     return FG_OPTIONS_OK;
2169   } else if ( s.find( "--show-aircraft") == 0) {
2170     return(FG_OPTIONS_SHOW_AIRCRAFT);
2171   } else if ( s.find( "--show-sound-devices") == 0) {
2172     return(FG_OPTIONS_SHOW_SOUND_DEVICES);
2173   } else if ( s.find( "--no-default-config") == 0) {
2174     return FG_OPTIONS_NO_DEFAULT_CONFIG;
2175   } else if ( s.find( "--prop:") == 0) {
2176     // property setting has a slightly different syntax, so fudge things
2177     OptionDesc* desc = p->findOption("prop");
2178     if (s.find("=", 7) == string::npos) { // no equals token
2179       SG_LOG(SG_GENERAL, SG_ALERT, "malformed property option:" << s);
2180       return FG_OPTIONS_ERROR;
2181     }
2182     
2183     p->values.push_back(OptionValue(desc, s.substr(7)));
2184     return FG_OPTIONS_OK;
2185   } else if ( s.find( "--" ) == 0 ) {
2186     size_t eqPos = s.find( '=' );
2187     string key, value;
2188     if (eqPos == string::npos) {
2189       key = s.substr(2);
2190     } else {
2191       key = s.substr( 2, eqPos - 2 );
2192       value = s.substr( eqPos + 1);
2193     }
2194     
2195     return addOption(key, value);
2196   } else {
2197       flightgear::modalMessageBox("Unknown option", "Unknown command-line option: " + s);
2198     return FG_OPTIONS_ERROR;
2199   }
2200 }
2201   
2202 int Options::addOption(const string &key, const string &value)
2203 {
2204   OptionDesc* desc = p->findOption(key);
2205   if (!desc) {
2206     flightgear::modalMessageBox("Unknown option", "Unknown command-line option: " + key);
2207     return FG_OPTIONS_ERROR;
2208   }
2209   
2210   if (!(desc->type & OPTION_MULTI)) {
2211     OptionValueVec::const_iterator it = p->findValue(key);
2212     if (it != p->values.end()) {
2213       SG_LOG(SG_GENERAL, SG_WARN, "multiple values forbidden for option:" << key << ", ignoring:" << value);
2214       return FG_OPTIONS_OK;
2215     }
2216   }
2217   
2218   p->values.push_back(OptionValue(desc, value));
2219   return FG_OPTIONS_OK;
2220 }
2221
2222 int Options::setOption(const string &key, const string &value)
2223 {
2224     OptionDesc* desc = p->findOption(key);
2225     if (!desc) {
2226         flightgear::modalMessageBox("Unknown option", "Unknown command-line option: " + key);
2227         return FG_OPTIONS_ERROR;
2228     }
2229
2230     if (!(desc->type & OPTION_MULTI)) {
2231         OptionValueVec::iterator it = p->findValue(key);
2232         if (it != p->values.end()) {
2233             // remove existing valye
2234             p->values.erase(it);
2235         }
2236     }
2237     
2238     p->values.push_back(OptionValue(desc, value));
2239     return FG_OPTIONS_OK;
2240 }
2241
2242 void Options::clearOption(const std::string& key)
2243 {
2244     OptionValueVec::iterator it = p->findValue(key);
2245     for (; it != p->values.end(); it = p->findValue(key)) {
2246         p->values.erase(it);
2247     }
2248 }
2249
2250 bool Options::isOptionSet(const string &key) const
2251 {
2252   OptionValueVec::const_iterator it = p->findValue(key);
2253   return (it != p->values.end());
2254 }
2255   
2256 string Options::valueForOption(const string& key, const string& defValue) const
2257 {
2258   OptionValueVec::const_iterator it = p->findValue(key);
2259   if (it == p->values.end()) {
2260     return defValue;
2261   }
2262   
2263   return it->value;
2264 }
2265
2266 string_list Options::valuesForOption(const std::string& key) const
2267 {
2268   string_list result;
2269   OptionValueVec::const_iterator it = p->values.begin();
2270   for (; it != p->values.end(); ++it) {
2271     if (!it->desc) {
2272       continue; // ignore marker values
2273     }
2274     
2275     if (it->desc->option == key) {
2276       result.push_back(it->value);
2277     }
2278   }
2279   
2280   return result;
2281 }
2282
2283 string defaultDownloadDir()
2284 {
2285 #if defined(SG_WINDOWS)
2286     SGPath p(SGPath::documents());
2287     p.append("FlightGear");
2288 #else
2289     SGPath p(globals->get_fg_home());
2290 #endif
2291     return p.str();
2292 }
2293
2294 OptionResult Options::processOptions()
2295 {
2296   // establish locale before showing help (this selects the default locale,
2297   // when no explicit option was set)
2298   globals->get_locale()->selectLanguage(valueForOption("language").c_str());
2299
2300   // now FG_ROOT is setup, process various command line options that bail us
2301   // out quickly, but rely on aircraft / root settings
2302   if (p->showHelp) {
2303     showUsage();
2304       return FG_OPTIONS_EXIT;
2305   }
2306   
2307   // processing order is complicated. We must process groups LIFO, but the
2308   // values *within* each group in FIFO order, to retain consistency with
2309   // older versions of FG, and existing user configs.
2310   // in practice this means system.fgfsrc must be *processed* before
2311   // .fgfsrc, which must be processed before the command line args, and so on.
2312   OptionValueVec::const_iterator groupEnd = p->values.end();
2313
2314   while (groupEnd != p->values.begin()) {
2315     OptionValueVec::const_iterator groupBegin = p->rfindGroup(groupEnd);
2316   // run over the group in FIFO order
2317     OptionValueVec::const_iterator it;
2318     for (it = groupBegin; it != groupEnd; ++it) {      
2319       int result = p->processOption(it->desc, it->value);
2320       switch(result)
2321       {
2322           case FG_OPTIONS_ERROR:
2323               showUsage();
2324               return FG_OPTIONS_ERROR;
2325               
2326           case FG_OPTIONS_EXIT:
2327               return FG_OPTIONS_EXIT;
2328               
2329           default:
2330               break;
2331       }
2332         if (it->desc) {
2333             SG_LOG(SG_GENERAL, SG_INFO, "\toption:" << it->desc->option << " = " << it->value);
2334         }
2335     }
2336     
2337     groupEnd = groupBegin;
2338   }
2339
2340   BOOST_FOREACH(const SGPath& file, p->propertyFiles) {
2341     SG_LOG(SG_GENERAL, SG_INFO,
2342            "Reading command-line property file " << file.str());
2343           readProperties(file.str(), globals->get_props());
2344   }
2345
2346 // now options are process, do supplemental fixup
2347   const char *envp = ::getenv( "FG_SCENERY" );
2348   if (envp) {
2349     globals->append_fg_scenery(envp, true);
2350   }
2351
2352 // download dir fix-up
2353     string downloadDir = simgear::strutils::strip(fgGetString("/sim/paths/download-dir"));
2354     if (downloadDir.empty()) {
2355         downloadDir = defaultDownloadDir();
2356         SG_LOG(SG_GENERAL, SG_INFO, "Using default download dir: " << downloadDir);
2357     } else {
2358         simgear::Dir d(downloadDir);
2359         if (!d.exists()) {
2360             SG_LOG(SG_GENERAL, SG_INFO, "Creating requested download dir: " << downloadDir);
2361             d.create(0755);
2362         }
2363     }
2364
2365 // terrasync directory fixup
2366     string terrasyncDir = simgear::strutils::strip(fgGetString("/sim/terrasync/scenery-dir"));
2367   if (terrasyncDir.empty()) {
2368       SGPath p(downloadDir);
2369       p.append("TerraSync");
2370       terrasyncDir = p.str();
2371
2372       simgear::Dir d(terrasyncDir);
2373       if (!d.exists()) {
2374           d.create(0755);
2375       }
2376
2377           SG_LOG(SG_GENERAL, SG_INFO, "Using default TerraSync: " << terrasyncDir);
2378       fgSetString("/sim/terrasync/scenery-dir", p.str());
2379   } else {
2380       SG_LOG(SG_GENERAL, SG_INFO, "Using explicit TerraSync dir: " << terrasyncDir);
2381   }
2382
2383     // check if we setup a scenery path so far
2384     bool addFGDataScenery = globals->get_fg_scenery().empty();
2385
2386     // always add the terrasync location, regardless of whether terrasync
2387     // is enabled or not. This allows us to toggle terrasync on/off at
2388     // runtime and have things work as expected
2389     const string_list& scenery_paths(globals->get_fg_scenery());
2390     if (std::find(scenery_paths.begin(), scenery_paths.end(), terrasyncDir) == scenery_paths.end()) {
2391         // terrasync dir is not in the scenery paths, add it
2392         globals->append_fg_scenery(terrasyncDir);
2393     }
2394
2395     if (addFGDataScenery) {
2396         // no scenery paths set at all, use the data in FG_ROOT
2397         // ensure this path is added last
2398         SGPath root(globals->get_fg_root());
2399         root.append("Scenery");
2400         globals->append_fg_scenery(root.str());
2401     }
2402
2403   return FG_OPTIONS_OK;
2404 }
2405   
2406 void Options::showUsage() const
2407 {
2408   fgOptLogLevel( "alert" );
2409   
2410   FGLocale *locale = globals->get_locale();
2411   SGPropertyNode options_root;
2412   
2413   simgear::requestConsole(); // ensure console is shown on Windows
2414   cout << endl;
2415
2416   try {
2417     fgLoadProps("options.xml", &options_root);
2418   } catch (const sg_exception &) {
2419     cout << "Unable to read the help file." << endl;
2420     cout << "Make sure the file options.xml is located in the FlightGear base directory," << endl;
2421     cout << "and the location of the base directory is specified by setting $FG_ROOT or" << endl;
2422     cout << "by adding --fg-root=path as a program argument." << endl;
2423     
2424     exit(-1);
2425   }
2426
2427   SGPropertyNode *options = options_root.getNode("options");
2428   if (!options) {
2429     SG_LOG( SG_GENERAL, SG_ALERT,
2430            "Error reading options.xml: <options> directive not found." );
2431     exit(-1);
2432   }
2433
2434   if (!locale->loadResource("options"))
2435   {
2436       cout << "Unable to read the language resource." << endl;
2437       exit(-1);
2438   }
2439
2440   const char* usage = locale->getLocalizedString(options->getStringValue("usage"), "options");
2441   if (usage) {
2442     cout << usage << endl;
2443   }
2444   
2445   vector<SGPropertyNode_ptr>section = options->getChildren("section");
2446   for (unsigned int j = 0; j < section.size(); j++) {
2447     string msg = "";
2448     
2449     vector<SGPropertyNode_ptr>option = section[j]->getChildren("option");
2450     for (unsigned int k = 0; k < option.size(); k++) {
2451       
2452       SGPropertyNode *name = option[k]->getNode("name");
2453       SGPropertyNode *short_name = option[k]->getNode("short");
2454       SGPropertyNode *key = option[k]->getNode("key");
2455       SGPropertyNode *arg = option[k]->getNode("arg");
2456       bool brief = option[k]->getNode("brief") != 0;
2457       
2458       if ((brief || p->verbose) && name) {
2459         string tmp = name->getStringValue();
2460         
2461         if (key){
2462           tmp.append(":");
2463           tmp.append(key->getStringValue());
2464         }
2465         if (arg) {
2466           tmp.append("=");
2467           tmp.append(arg->getStringValue());
2468         }
2469         if (short_name) {
2470           tmp.append(", -");
2471           tmp.append(short_name->getStringValue());
2472         }
2473         
2474         if (tmp.size() <= 25) {
2475           msg+= "   --";
2476           msg += tmp;
2477           msg.append( 27-tmp.size(), ' ');
2478         } else {
2479           msg += "\n   --";
2480           msg += tmp + '\n';
2481           msg.append(32, ' ');
2482         }
2483         // There may be more than one <description> tag associated
2484         // with one option
2485         
2486         vector<SGPropertyNode_ptr> desc;
2487         desc = option[k]->getChildren("description");
2488         if (! desc.empty()) {
2489           for ( unsigned int l = 0; l < desc.size(); l++) {
2490             string t = desc[l]->getStringValue();
2491
2492             // There may be more than one translation line.
2493             vector<SGPropertyNode_ptr>trans_desc = locale->getLocalizedStrings(t.c_str(),"options");
2494             for ( unsigned int m = 0; m < trans_desc.size(); m++ ) {
2495               string t_str = trans_desc[m]->getStringValue();
2496               
2497               if ((m > 0) || ((l > 0) && m == 0)) {
2498                 msg.append( 32, ' ');
2499               }
2500               
2501               // If the string is too large to fit on the screen,
2502               // then split it up in several pieces.
2503               
2504               while ( t_str.size() > 47 ) {
2505                 
2506                 string::size_type m = t_str.rfind(' ', 47);
2507                 msg += t_str.substr(0, m) + '\n';
2508                 msg.append( 32, ' ');
2509                 
2510                 t_str.erase(t_str.begin(), t_str.begin() + m + 1);
2511               }
2512               msg += t_str + '\n';
2513             }
2514           }
2515         }
2516       }
2517     }
2518     
2519     const char* name = locale->getLocalizedString(section[j]->getStringValue("name"),"options");
2520     if (!msg.empty() && name) {
2521       cout << endl << name << ":" << endl;
2522       cout << msg;
2523       msg.erase();
2524     }
2525   }
2526   
2527   if ( !p->verbose ) {
2528     const char* verbose_help = locale->getLocalizedString(options->getStringValue("verbose-help"),"options");
2529     if (verbose_help)
2530         cout << endl << verbose_help << endl;
2531   }
2532 #ifdef _MSC_VER
2533   std::cout << "Hit a key to continue..." << std::endl;
2534   std::cin.get();
2535 #endif
2536 }
2537   
2538 #if defined(__CYGWIN__)
2539 string Options::platformDefaultRoot() const
2540 {
2541   return "../data";
2542 }
2543
2544 #elif defined(SG_WINDOWS)
2545 string Options::platformDefaultRoot() const
2546 {
2547   return "..\\data";
2548 }
2549 #elif defined(SG_MAC)
2550 // platformDefaultRoot defined in CocoaHelpers.mm
2551 #else
2552 string Options::platformDefaultRoot() const
2553 {
2554   return PKGLIBDIR;
2555 }
2556 #endif
2557   
2558 void Options::setupRoot(int argc, char **argv)
2559 {
2560     string root;
2561     bool usingDefaultRoot = false;
2562
2563   if (isOptionSet("fg-root")) {
2564     root = valueForOption("fg-root"); // easy!
2565     SG_LOG(SG_GENERAL, SG_INFO, "set from command-line argument: fg_root = " << root );
2566   } else {
2567   // Next check if fg-root is set as an env variable
2568     char *envp = ::getenv( "FG_ROOT" );
2569     if ( envp != NULL ) {
2570       root = envp;
2571       SG_LOG(SG_GENERAL, SG_INFO, "set from FG_ROOT env var: fg_root = " << root );
2572     } else {
2573 #if defined(HAVE_QT)
2574         flightgear::initApp(argc, argv);
2575         root = SetupRootDialog::restoreUserSelectedRoot();
2576 #endif
2577         if (root.empty()) {
2578             usingDefaultRoot = true;
2579             root = platformDefaultRoot();
2580             SG_LOG(SG_GENERAL, SG_INFO, "platform default fg_root = " << root );
2581         } else {
2582             SG_LOG(SG_GENERAL, SG_INFO, "Qt launcher set fg_root = " << root );
2583         }
2584     }
2585   } 
2586   
2587   globals->set_fg_root(root);
2588     static char required_version[] = FLIGHTGEAR_VERSION;
2589     string base_version = fgBasePackageVersion(root);
2590
2591 #if defined(HAVE_QT)
2592     // note we never end up here if restoring a user selected root via
2593     // the Qt GUI, since that code pre-validates the path. But if we're using
2594     // a command-line, env-var or default root this check can fail and
2595     // we still want to use the GUI in that case
2596     if (base_version != required_version) {
2597         flightgear::initApp(argc, argv);
2598         SetupRootDialog::runDialog(usingDefaultRoot);
2599     }
2600 #else
2601     // validate it
2602     if (base_version.empty()) {
2603         flightgear::fatalMessageBox("Base package not found",
2604                                     "Required data files not found, check your installation.",
2605                                     "Looking for base-package files at: '" + root + "'");
2606
2607         exit(-1);
2608     }
2609     
2610     if (base_version != required_version) {
2611       flightgear::fatalMessageBox("Base package version mismatch",
2612                                   "Version check failed: please check your installation.",
2613                                   "Found data files for version '" + base_version +
2614                                   "' at '" + globals->get_fg_root() + "', version '"
2615                                   + required_version + "' is required.");
2616
2617     exit(-1);
2618   }
2619 #endif
2620 }
2621   
2622 bool Options::shouldLoadDefaultConfig() const
2623 {
2624   return p->shouldLoadDefaultConfig;
2625 }
2626
2627 bool Options::checkForArg(int argc, char* argv[], const char* checkArg)
2628 {
2629     for (int i = 0; i < argc; ++i) {
2630         char* arg = argv[i];
2631         if (arg == 0) {
2632             continue;
2633         }
2634
2635         if (*arg != '-') { // we only care about args with a leading hypen
2636             continue;
2637         }
2638
2639         arg++;
2640         if (*arg == '-') { // skip double hypens
2641             arg++;
2642         }
2643
2644         if (strcmp(arg, checkArg) == 0) {
2645             return true;
2646         }
2647     }
2648     
2649     return false;
2650 }
2651     
2652 } // of namespace flightgear
2653