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