/*------------------------------------------------------------------------------*
 * File Name: Passing2DArray.c 													*
 * Creation: 																	*
 * Purpose: Example on passing a 2D Array/matrix to a NAG function				*
 * Copyright (c) OriginLab Corp. 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010	*
 * All Rights Reserved															*
 * 																				*
 * Modification Log:															*
 *------------------------------------------------------------------------------*/
 
////////////////////////////////////////////////////////////////////////////////////
#include <Origin.h>
#include <OC_nag8.h>	// Header file for NAG library
// Note: The above header file does not include all the NAG library header files
// More header files can be added from the Origin C\System\NAG8 subfolder, such as:
#include <NAG8\nagf07.h>


////////////////////////////////////////////////////////////////////////////////////
// This example calls two NAG functiosn to compute the inverse of a real matrix
// It is assumed that the function is called with matrix object active, where the
// matrix object is type double and it is a square matrix
int test_nag3()
{

	// Point to active matrix object
	MatrixLayer matLy = Project.ActiveLayer();
	if( !matLy ) return 1;
	Matrix MatData(matLy, -1);
	if( !MatData ) return 2;
	
	// Check to see if it is a square matrix
	int nRows, nCols;
	nRows = MatData.GetNumRows();
	nCols = MatData.GetNumCols();	
	if( nRows != nCols ) return 3;
			
	vector<int> ipiv;
	ipiv.SetSize(nCols);
	int pda = nCols;
	Nag_OrderType order = Nag_RowMajor;
	NagError nagerror;
	
	// Create a new matrix page/object for holding the inverse
	MatrixPage matPgInverse;
	matPgInverse.Create("Origin");
	MatrixLayer matLyInverse = matPgInverse.Layers(0);
	Matrix MatInverse(matLyInverse, 0);
	// Copy data into this result matrix object for passing to NAG functions
	MatInverse = MatData;
	
	// Factorize the matrix
	nag_dgetrf(order, nCols, nCols, MatInverse, pda, ipiv, &nagerror);
	if (nagerror.code != NE_NOERROR)
	{
		printf("Error from f07adc.\n%s\n", nagerror.message);
		matPgInverse.Destroy();
		return 4;
	}
	
	// Compute inverse of matrix
	nag_dgetri(order, nCols, MatInverse, pda, ipiv, &nagerror);
	if (nagerror.code != NE_NOERROR)
	{
		printf("Error from f07ajc.\n%s\n", nagerror.message);
		matPgInverse.Destroy();
		return 5;
	}
	
	// Create another new matrix to hold product of data and result matrices
	MatrixPage matPgProduct;
	matPgProduct.Create("Origin");
	MatrixLayer matLyProduct = matPgProduct.Layers(0);
	Matrix MatProduct(matLyProduct, 0);
	// Compute product
	MatProduct = MatData * MatInverse;
	
	return 0;
}
