/***************************************************************************
 *   copyright           : (C) 2005 by Hendrik Sattler                     *
 *   mail                : post@hendrik-sattler.de                         *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/

#include "apoconv.h"

#include <helper.h>
#include <locale.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define PROGRAM_NAME "apoconv"
#define PROGRAM_VERSION  "0.0.2"
#include <disclaimer.h>

#define SYNTAX "Usage: apoconv {-m <main file> [-s] | -V <version> <apofile...>}"
int main (int argc, char** argv) {
  struct apo_main_info info;
  str_list_t* temp;
  int show_only = 0;
  int i = 1;

  if (argc <= 1) {
    print_proginfo(PROGRAM_NAME,PROGRAM_VERSION);
    print_disclaimer();
    fprintf(stderr,"%s\n",SYNTAX);
    exit(EXIT_FAILURE);
  }

  //setting locale of this program
  setlocale(LC_ALL,"");

  while (argv[i] && argv[i][0] == '-') {
    switch (argv[i++][1]) {
    case 'm':
      if (argc-i) {
	apo_main_info_init(&info);
	apo_main_decode(argv[i],&info);
	++i;
	continue;
      }
      break;
    case 's':
      show_only = 1;
      continue;
    case 'V':
      if (argc-i) {
	info.version = atoi(argv[i]);
	for (++i; i < argc && argv[i][0] != '-'; ++i)
	  info.files = str_list_append(info.files,str_list_create(argv[i]));
	continue;
      }
      break;
    default:
      break;
    }
    print_proginfo(PROGRAM_NAME,PROGRAM_VERSION);
    print_disclaimer();
    fprintf(stderr,"%s\n",SYNTAX);
    exit(EXIT_FAILURE);
  }

  if (!info.version) exit(EXIT_FAILURE);

  if (show_only) {
    fprintf(stderr,"The following files are probably version %d:\n",info.version);
    while (info.files != NULL) {
      temp = info.files;
      info.files = info.files->next;
      printf("%s\n",temp->data);
      str_list_destroy(temp);
    }
  } else {
    apo_data_decode(&info);
  }
  exit(EXIT_SUCCESS);
}
