#include <setjmp.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>

#include "csv.h"

bool
processFile(const char *filename)
{
	FILE *in;

	if ( (in = fopen(filename, "r")) == NULL ) {
		return false;
	}

	csv_t csv;
	csv_init(&csv);

	while ( csv_read(&csv, in) ) {
		const size_t nf = csv_nfields(&csv);
		(void) nf;
		// ...
	}
	csv_cleanup(&csv);

	fclose(in);
	return true;
}

bool
processFile_options(const char *filename)
{
	FILE *in;

	if ( (in = fopen(filename, "r")) == NULL ) {
		return false;
	}

	csv_options_t csv_options   = csv_default_options;
	csv_options.field_delimiter = '"';
	csv_options.field_separator = ',';

	csv_t csv;
	csv_init_opt(&csv, &csv_options);

	while ( csv_read(&csv, in) ) {
		const size_t nf = csv_nfields(&csv);
		(void) nf;
		// ...
	}
	csv_cleanup(&csv);

	fclose(in);
	return true;
}

static void
csvErrorHandler(csv_err_t err, void *cb_arg)
{
	longjmp(*((jmp_buf *) cb_arg), err);
}

bool
processFile_error(const char *filename)
{
	FILE *in;

	if ( (in = fopen(filename, "r")) == NULL ) {
		return false;
	}

	csv_options_t csv_options   = csv_default_options;
	csv_options.field_delimiter = '"';
	csv_options.field_separator = ',';

	jmp_buf env;
	csv_options.cb_error     = csvErrorHandler;
	csv_options.cb_error_arg = &env;

	csv_t csv;
	csv_init_opt(&csv, &csv_options);

	switch ( setjmp(env) ) {
	case CSV_ERR_OK:
		while ( csv_read(&csv, in) ) {
			const size_t nf = csv_nfields(&csv);
			(void) nf;
			// ...
		}
		break;

	case CSV_ERR_OUT_OF_MEMORY:
		csv_cleanup(&csv);
		break;

	case CSV_ERR_OUT_OF_RANGE:
		csv_cleanup(&csv);
		break;

	case CSV_ERR_IO_READ:
		csv_cleanup(&csv);
		break;

	case CSV_ERR_IO_WRITE:
		csv_cleanup(&csv);
		break;
	}

	fclose(in);
	return true;
}

int
main(void)
{
	return EXIT_SUCCESS;
}
