#include "paramObj.h"
#include "parseObj.h"
#include "paramParser.h"
#include <string>
#include <cstdlib>       // for atof

void printHelp(const char* caller="") {
  string usg="\nUsage: " + (string)caller + " [options]\n";
  printf(usg.c_str());
  printf("Options:\n");
  printf("     --help             print this help and quit\n");
  printf(" -f  --file  filename   read options from file 'filename'\n");
  printf(" -a          v1 [v2]    calculate v1+v2 and print the result\n");
  printf("                        if only v1 is used, v2 shall be zero\n\n");
}

void initParser(paramParser* pp) {
  // remark: pp must be 'new'ed already!
  if (pp == NULL) return;
  pp->setParamChar("-");                     // set character for options
  pp->setFileHeaderLine("** MiniAdder **");  // headerline for files
  pp->addParam("--help");                    // add 'help'-option: zero values
  pp->addParam("-f", "--file", 1);           // add 'file'-option: 1 value
  pp->addParam("-a", 1, 2);                  // add 'add'-option: 1 or 2 values
}

int action(int argc, char** argv, paramParser* pp) {
  parseObj* pa;


  pp->parseCommandLine(argc, argv);

  pa = pp->getOption();

  // no options? print help!
  if (pp->size() < 1) {
    printHelp(argv[0]);
    return 0;
  }
  if (pp->size() == 1) {
    if ( (pa->isOption("--help") > 0) && pa->processable() ) {
      printHelp(argv[0]);
      return 0;
    }
  }

  // traverse options
  while (pa != NULL) {
    if ( (pa->isOption("-f", "--file") > 0) && pa->processable() ) {
      try{
        pp->parseFile(pa->getValue(0), pa);
      }
      catch(char* p) {
        printf("Error in option file \%s!\n", p);
      }
    }
    if ( (pa->isOption("-a") > 0) && pa->processable() ) {
      float v1, v2;
      int nop = pa->size();
      switch (nop) {
        case 1: v2 = 0; v1 = atof(pa->getValue(0).c_str()); break;
        case 2: v2 = atof(pa->getValue(1).c_str());
                v1 = atof(pa->getValue(0).c_str()); break;
        default: v2 = 0; v1 = 0;
      }
      printf("%f + %f = %f\n", v1, v2, v1+v2);
    }
    pa = pp->getNextOption();
  }
  return 0;
}

int main(int argc, char** argv) {
  paramParser* p = new paramParser();
  initParser(p);
  action(argc, argv, p);
  delete p;

  return 0;
}
