/* ex4.cpp
 * Peter Webb, Aug. 1995
 * Example 4 from the documentation: Error handling
 */

#include <stdio.h>
#include <setjmp.h>
#include "matlab.h"

static double data[] = {  1, 2, 3, 4, 5, 6 };

/* Setjmp/longjmp buffer */
static jmp_buf env;

void ErrorHandler(const char *msg)
{
    mlfPrintf("%s\n", msg);
    longjmp(env, -1);
}

main()
{
    /* Create two matrices */

    Matrix *mat0 = mxCreateFull(2, 3, 0);
    Matrix *mat1 = mxCreateFull(3, 2, 0);
    Matrix *mat2 = 0;
    
    if (setjmp(env) == 0)
    {
	/* Set the error handler */

	mlfSetErrorHandler(ErrorHandler);

	/* This is an illegal operation: mat0 and mat1 do not have the
	 * same dimension
	 */
	mat2 = mlfPlus(mat0, mat1);
	mlfPrintMatrix(mat2);

	mxFreeMatrix(mat0);
	mxFreeMatrix(mat1);
    }
    else
    {
        /* mlfPrintHandler */
        mlfPrintf("Caught a Math Library error! Recovering!\n");
	mxFreeMatrix(mat0);
	mxFreeMatrix(mat1);
    }
    exit(0);
}

