#include <stdio.h>
#include <getopt.h>
#include <unistd.h>
#include <stdlib.h>
#include <stddef.h>
#include <libwr/switch_hw.h>
#include "fpga_io.h"
#include <libwr/softpll.h>
#include <libwr/util.h>

/*******************/

int print_help(char *prgname)
{
	fprintf(stderr, "Use: %s [-l <ps>]"
			" \n", prgname);

	return 0;
}

int set_ext_pps_latency(char *prgname, int latency)
{
	static struct spll_stats *spll_stats_p;
	spll_stats_p = create_map(FPGA_SPLL_STAT,
				  sizeof(*spll_stats_p));
	
	if (!spll_stats_p){
		fprintf(stderr, "%s: unable to mmap\n", prgname);
		return 1;
	}

	/* check magic number in SPLL stat memory */
	if (spll_stats_p->magic != SPLL_MAGIC) {
		/* wrong magic */
		fprintf(stderr, "%s: Wrong SPLL magic number\n", prgname);
		return 1;
	}
	
	if (spll_stats_p->ver >= 4 ) {
		fprintf(stderr, "%s: Set external PPS latency to %d ps\n", prgname, latency);
		spll_stats_p->ext_pps_latency_ps = latency;
	} else {
		fprintf(stderr, "Err spll stats version is %d\n", spll_stats_p->ver);
	}
	return 0;
}

int main(int argc, char *argv[])
{
	char *prgname = argv[0];
	int c;
	int ret;

	while ((c = getopt(argc, argv, "hl:")) != -1) {
			switch (c) {
			case 'h':
				print_help(prgname);
				ret = 1;
				break;
			case 'l':
				ret= set_ext_pps_latency(prgname, atoi(optarg));
				break;
			default:
				print_help(prgname);
				exit(1);
			}
		}

	return ret;
}