#include <stdio.h>
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#ifdef HAVE_FNMATCH_H
#include <fnmatch.h>
#endif

#ifdef HAVE_CAML_MLVALUES_H
#include <caml/mlvalues.h>
#endif
#ifdef HAVE_CAML_MEMORY_H
#include <caml/memory.h>
#endif
#ifdef HAVE_CAML_ALLOC_H
#include <caml/alloc.h>
#endif
#ifdef HAVE_CAML_CUSTOM_H
#include <caml/custom.h>
#endif

value ocamlpkgsrc_fnmatch (value pattern, value string, value options)
{
	CAMLparam3 (pattern, string, options);
	CAMLlocal1 (optptr);
	int flags = 0;

	optptr = options;
	while (Is_block (optptr))
	{
		switch (Int_val (Field (optptr, 0)))
		{
			case 0: flags |= FNM_NOESCAPE; break; 
			case 1: flags |= FNM_PATHNAME; break;
			case 2: flags |= FNM_PERIOD; break;
			default: fprintf (stderr, "Unknown %d\n", Int_val (Field (optptr, 0)));
		}
		optptr = Field (optptr, 1);
	}

	if (fnmatch (String_val (pattern), String_val (string), flags) == 0)
		CAMLreturn (Val_true);
	else
		CAMLreturn (Val_false);
}
