]> git.itanic.dy.fi Git - sdl-planets/blobdiff - main.c
main.c: Use getopt_long() for reading cmd line arguments
[sdl-planets] / main.c
diff --git a/main.c b/main.c
index eb1b127c14058c2c3a5cce379d51c17134826d06..b42f2345d5404ae0e54cc579d6ae4bc39a006f6c 100644 (file)
--- a/main.c
+++ b/main.c
@@ -2,6 +2,7 @@
 #include <unistd.h>
 #include <stdio.h>
 #include <time.h>
+#include <getopt.h>
 
 #include "random.h"
 #include "planet.h"
@@ -322,6 +323,16 @@ int main(int argc, char *argv[])
        int planets = 100, xres = 800, yres = 600;
        double total_mass = 50000;
        double range = 500;
+       int optind = 0, c;
+       static struct option long_options[] = {
+               { .val = 'x', .name = "xres", .has_arg = 1, },
+               { .val = 'y', .name = "yres", .has_arg = 1, },
+               { .val = 'p', .name = "planets", .has_arg = 1 },
+               { .val = 'm', .name = "total-mass", .has_arg = 1 },
+               { .val = 'r', .name = "range", .has_arg = 1 },
+               {},
+       };
+       char short_options[] = "x:y:p:m:r:";
 
        if (SDL_Init(SDL_INIT_VIDEO) != 0) {
                fprintf(stderr, "Unable to initialize SDL: %s\n",
@@ -331,18 +342,33 @@ int main(int argc, char *argv[])
        }
        atexit(SDL_Quit);
 
-       if (argc >= 2)
-               planets = atoi(argv[1]);
+       while (1) {
+               c = getopt_long(argc, argv, short_options, long_options,
+                               &optind);
+
+               if (c == -1)
+                       break;
 
-       if (planets < 1)
-               planets = 1;
+               printf("%c: %s\n", c, optarg);
+
+               switch (c) {
+               case 'x':
+                       xres = atoi(optarg);
+                       break;
 
+               case 'y':
+                       yres = atoi(optarg);
+                       break;
 
-       if (argc >= 3)
-               total_mass = atof(argv[2]);
+               case 'p':
+                       planets = atoi(optarg);
+                       break;
 
-       if (argc >= 4)
-               range = atof(argv[3]);
+               case 'r':
+                       range = atoi(optarg);
+                       break;
+               }
+       }
 
        screen = SDL_SetVideoMode(xres, yres, 32, flags);
        if (screen == NULL) {