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