Sona 0.50 Source

Sona 0.50/tools/mml2sona/main.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "main.h"
#include "stream.h"
#include "mml.h"
#include "sona.h"

int main(int argc, char **argv)
{
   int errored = 0;
   
   // Parse arguments
   int allow_options = 1;
   int show_help = 0;
   int show_version = 0;
   
   const char *in_filename = NULL;
   const char *out_filename = NULL;
   int too_many_filenames = 0;
   
   for (int i = 1; i < argc; i++) {
      const char *arg = argv[i];
      
      // Options?
      if (arg[0] == '-' && allow_options) {
         // No more options allowed
         if (strcmp(arg, "--") == 0) {
            allow_options = 0;
         }
         
         // Show program help
         else if (strcmp(arg, "-h") == 0 ||
                  strcmp(arg, "--help") == 0) {
            show_help = 1;
         }
         
         // Show program version
         else if (strcmp(arg, "-v") == 0 ||
                  strcmp(arg, "--version") == 0) {
            show_version = 1;
         }
         
         // Invalid option
         else {
            errored = 1;
            fprintf(stderr, ERRORMSG_BADOPTION, arg);
         }
      }
      
      // Filenames?
      else if (in_filename == NULL)
         in_filename = arg;
      else if (out_filename == NULL)
         out_filename = arg;
      else if (!too_many_filenames) {
         fputs(ERRORMSG_TOOMANYFILES, stderr);
         too_many_filenames = 1;
         errored = 1;
      }
   }
   
   // If anything went wrong with the command line quit now
   if (errored) return EXIT_FAILURE;
   
   // If no arguments are passed, assume that the user is trying to remember
   // how to use this tool. Show the usage without wasting time showing the
   // list of options.
   if (argc == 1) {
      fprintf(stderr, "Usage: %s <input.mml> <output.sona>\n", argv[0]);
      return EXIT_SUCCESS;
   }
   
   // Show help?
   if (show_help) {
      fprintf(stderr, "Usage: %s <input.mml> <output.sona>\n"
                      "Options:\n"
                      "   -h --help      show help\n"
                      "   -v --version   show version\n"
                      "   --             no more options\n",
                      argv[0]);
      return EXIT_SUCCESS;
   }
   
   // Show program version?
   if (show_version) {
      puts(PROGRAM_VER);
      return EXIT_SUCCESS;
   }
   
   // Missing filenames?
   if (in_filename == NULL) {
      fputs(ERRORMSG_NOINPUT, stderr);
      return EXIT_FAILURE;
   }
   else if (out_filename == NULL) {
      fputs(ERRORMSG_NOOUTPUT, stderr);
      return EXIT_FAILURE;
   }
   
   // Process the song data
   Stream *stream = load_mml(in_filename);
   if (stream == NULL)
      return EXIT_FAILURE;
   sort_stream(stream);
   if (save_sona(out_filename, stream))
      return EXIT_FAILURE;
   
   // Done
   return EXIT_SUCCESS;
}