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