#include <stdio.h>
#include <string.h>
#include <getopt.h>
#include <sprog.h>
#include <serial.h>
#include <lpc.h>

struct option sprog_options[] = {
  {"port", required_argument, NULL, 'p'},
  {"family", required_argument, NULL, 'f'},
  {"baud", required_argument, NULL, 'b'},
  {"version", no_argument, NULL, 'v'},
  {"help", no_argument, NULL, 'h'},
  {NULL, 0, NULL, 0}
};

void usage(const char *name);
void print_version(void);
  

int main(int argc, char *argv[]) {
  const struct sprog_family *fam;
  int opt;
  int option_index;
  int baud;
  char port[128];
  port[0] = 0;
  fam = NULL;
  
  while((opt = getopt_long(argc, argv, "p:b:f:h", sprog_options, &option_index))!=-1) {
    switch(opt) {
      case 'p':
	strncpy(port, optarg, sizeof(port));
	break;
      case 'f':
	if(strcmp(optarg, "lpc")==0)
	  fam = &lpc_family;
	else
	  sprog_error("Family '%s' not recognized\n", optarg);
	break;
      case 'b':
	if(sscanf(optarg, "%d", &baud)!=1) {
	  sprog_error("Invalid value for baud rate: '%s'\n", optarg);
	  return 1;
	}
	break;
      case 'v':
	print_version();
	return 0;
	break;
      case 'h':
	usage(argv[0]);
	return 0;
	break;
      default:
	usage(argv[0]);
	return 1;
    }
  }
  
  if(!port[0]) {
    sprog_error("Serial port not specified!\n");
    usage(argv[0]);
    return 1;
  }
  
  if(!fam) {
    sprog_error("Family not specified!\n");
    usage(argv[0]);
    return 1;
  }
  
  sprog_communicate(fam, port, baud);
  
  return 0;
  
}

void usage(const char *name) {
  printf("%s -p <port> -f <family> [options]\n", name);
  printf("Following options are supported:\n");
  printf("  -p <port>, --port <port>		specify the serial port, eg. /dev/ttyS0\n");
  printf("  -f <family>, --family <family>	specify the microcontroller family, eg. lpc\n");
  printf("  -b <baud>, --baud <baud>		specify the baud rate\n");
  printf("  -h, --help				display this help\n");
  printf("  --version				print version and exit\n");
}

void print_version(void) {
  printf("SProg v%s (built on " __DATE__ ")\n", sprog_version);
}