/*******************************************************************************
 *
 * ALBERTA:  an Adaptive multi Level finite element toolbox  using
 *           Bisectioning refinement and Error control by Residual
 *           Techniques
 *
 * www.alberta-fem.de
 *
 * file:     cmdline.c
 *
 * description: helper function for parsing command-line parameters
 * for a typical ALBERTA application program.
 *
 ******************************************************************************
 *
 * this file's author(s):
 *            Claus-Justus Heine
 *            Abteilung fuer Angewandte Mathematik
 *            Albert-Ludwigs-Universitaet Freiburg
 *            Hermann-Herder-Str. 10
 *            79104 Freiburg
 *            Germany
 *            Claus.Heine@Mathematik.Uni-Freiburg.DE
 *
 * (c) by C.-J. Heine (2004(?)-2007)
 *
 ******************************************************************************/

#include "alberta-demo.h"

#include <getopt.h>

/*******************************************************************************
 * helper function for command-line provided parameters
 ******************************************************************************/

void parse_parameters(int argc, char *argv[], const char *init_file)
{
  struct option long_options[] = {
    {"init-file", required_argument, NULL, 'i'},
    {"parameters", required_argument, NULL, 'p'},
    {"help", no_argument, NULL, 'h'},
    {NULL, 0, NULL, '\0'}
  };
  int option_index = 0;
  int c;
  char *params = NULL;

  /* first of all, init parameters of the init file */
  do {
    c = getopt_long(argc, argv, "i:p:h", long_options, &option_index);
    switch (c) {
    case 'h':
	 printf("Usage: %s [-h] [-i INITFILE] [-p PARAMETERS]\n"
		"[--help] [--init-file=INITFILE] [--parameters=PARAMETERS]\n",
		argv[0]);
	 exit(0);
	 break;
    case 'i':
	 init_file = optarg;
	 break;
    case 'p':
	 params = optarg;
	 break;
    }
  } while (c != -1);


  init_parameters(0, init_file);
  if (params) {
       char *param, *value;
       do {
	    param = strtok(params, "'");
	    params = NULL;
	    if (param) {
		 TEST_EXIT((value = strchr(param, '=')) != NULL,
			   "Command-line specified parameters are garbled, "
			   "not '=' sign found.\n");
		 *value++ = '\0';
		 ADD_PARAMETER(0, param, value);
	    }
       } while (param);
  }
}

