#include <stdio.h>
#include <stdlib.h>
#include <getopt.h>
#include <string.h>
#include <timecode/timecode.h>

/* test sample
 * 08:17:00:23  1352017021.063243775
 */

Timecode tc;

static struct option const long_options[] =
{
	{"help", no_argument, 0, 'h'},
	{"format", required_argument, 0, 'F'},
	{"fps", required_argument, 0, 'f'},
	{"version", no_argument, 0, 'V'},
	{NULL, 0, NULL, 0}
};

static void usage (int status) {
  printf ("time2sec - parse timecode to seconds or unixtime.\n\n");
  printf ("Usage: time2sec [ OPTIONS ] timecode\n\n");
  printf ("Options:\n\
  -f, --fps <num>[/den]      set framerate (default 1000/1)\n\
  -h, --help                 display this help and exit\n\
  -V, --version              print version information and exit\n\
\n");
  printf ("\n\
...\n\
\n\
...\n\
\n");
  printf ("Report bugs to Robin Gareus <robin@gareus.org>\n"
          "Website and manual: <https://github.com/x42/timecode-utils>\n"
	  );
  exit (status);
}

static int decode_switches (int argc, char **argv) {
  int c;

  while ((c = getopt_long (argc, argv,
			   "f:"	/* fps */
			   "h"	/* help */
			   "V",	/* version */
			   long_options, (int *) 0)) != EOF)
    {
      switch (c) {

	case 'f':
		timecode_parse_framerate(&tc.r, optarg, 0);
	break;

	case 'V':
	  printf ("time2sec version %s\n\n", VERSION);
	  printf ("Copyright (C) GPL 2012 Robin Gareus <robin@gareus.org>\n");
	  exit (0);

	case 'h':
	  usage (0);

	default:
	  usage (EXIT_FAILURE);
	}
    }

  return optind;
}

int main (int argc, char **argv) {
	timecode_copy_rate(&tc, TCFPSMS);
	timecode_reset_unixtime(&tc);

	int i = decode_switches(argc, argv);
	if (i >= argc) usage (EXIT_FAILURE);

	timecode_parse_time(&tc.t, &tc.r, argv[i]);

	double tcsec = timecode_to_sec(&tc.t, &tc.r);

	printf("%lf\n", tcsec);
	return 0;
}
