// system headers
#include <stdio.h>
#include <stdlib.h>

// global VeriFinger SDK headers
#include <NCore.h>
#include <NTypes.h>
#include <NImages.h>
#include <FncMatcher.h>

char title[] = "Fingerprint verification tutorial, Version 6.0.0.0, Copyright (C) 2008 Neurotechnology\n";

int usage()
{
	printf("usage:\n");
	printf("\tVerification <template> <template>\n");
	printf("\n");
	printf("\t<template> - file name of extracted features.\n");
	printf("\n\nExample:\n");
	printf("\tVerification template1.bin template2.bin\n");

	return 1;
}

static void printMatchDetails(FncmMatchDetails *matchDetails)
{
	printf("Matching score: ");
	if (matchDetails)
	{
		printf("%d", matchDetails->Score);
	}
	else
	{
		printf("0");
	}
	printf("\n");
}

int main(int argc, char **argv)
{
	NResult res = 0;
	FILE * f1;
	FILE * f2;


	char * template1 = NULL;
	long template1Size = 0;
	char * template2 = NULL;
	long template2Size = 0;
	FncmMatchDetails * matchDetails = NULL;
	int score;

	HFncMatcher matcher = NULL;

	printf(title);
	if (argc < 2)
	{
		return usage();
	}

	f1 = fopen(argv[1], "rb");
	if (f1 != NULL)
	{
		fseek(f1, 0, SEEK_END);
		template1Size = ftell(f1);
		fseek(f1, 0, SEEK_SET);

		template1 = malloc(template1Size);
		if (template1 == NULL)
		{
			printf("Not enough memory.\n");
			fclose(f1);
			res = -1;
			goto exception_1;
		}
		fread(template1, 1, template1Size, f1);

		fclose(f1);
	}
	else
	{
		printf("Can't open file %s", argv[1]);
        res = -1;
		goto exception_1;
	}

	f2 = fopen(argv[2], "rb");
	if (f2 != NULL)
	{
		fseek(f2, 0, SEEK_END);
		template2Size = ftell(f2);
		fseek(f2, 0, SEEK_SET);

		template2 = malloc(template2Size);
		if (template2 == NULL)
		{
			printf("Not enough memory.\n");
			fclose(f2);
			res = -1;
			goto exception_2;
		}
		fread(template2, 1, template2Size, f2);

		fclose(f2);
	}
	else
	{
		printf("Can't open file %s", argv[2]);
        res = -1;
		goto exception_2;
	}

	res = FncmCreate(&matcher);
	if (res != N_OK)
	{
		printf("Failed to create matcher. Error %d\n", res);
		goto exception_3;
	}

	res = FncmVerify(matcher, template1, template1Size, template2, template2Size, &matchDetails, &score);
	if (res != N_OK)
	{
		printf("Failed to match templates. Error %d\n", res);
		goto exception_4;
	}

	printf("Score = %d\n", score);
	if (score > 0)
	{
		printf ("Templates matched\n");
		printMatchDetails(matchDetails);
	}
	else
	{
		printf ("Templates not matched\n");
	}

exception_4:
	if (matcher != NULL)
		FncmFree(matcher);
exception_3:
	if (template2) free(template2);
exception_2:
	if (template1) free(template1);
exception_1:
	return res;
}
