/* \file MatlabMatrixToPetscMatrix.cpp
 * \brief: convert a sparse or dense matlab matrix to a serial Petsc matrix:
 */


#ifdef HAVE_CONFIG_H
	#include "config.h"
#else
#error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
#endif


#ifdef _SERIAL_

/*Petsc includes: */
#include "petscmat.h"
#include "petscvec.h"
#include "petscksp.h"

/*Matlab includes: */
#include "mex.h"

#include "../../../shared/shared.h"

int MatlabMatrixToPetscMatrix(Mat* pmatrix,int* pmatrix_rows,int* pmatrix_cols,const mxArray* mxmatrix){

	int rows, cols;
	double* mxmatrix_ptr=NULL;
	int ierr;
	int i,j;

	/*output: */
	Mat matrix=NULL;

	/*matlab indices: */
	mwIndex*    ir=NULL;
	mwIndex*    jc=NULL;
	double* pr=NULL;
	int     count;
	int     nnz;
	int     nz;

	/*petsc indices: */
	int* idxm=NULL;
	int* idxn=NULL;
	
	/*Ok, first check if we are dealing with a sparse or full matrix: */
	if (mxIsSparse(mxmatrix)){

		/*Dealing with sparse matrix: recover size first: */
		mxmatrix_ptr=(double*)mxGetPr(mxmatrix);
		rows=mxGetM(mxmatrix);
		cols=mxGetN(mxmatrix);
		nnz=mxGetNzmax(mxmatrix);
		nz=(int)((double)nnz/(double)rows);

		ierr=MatCreateSeqAIJ(PETSC_COMM_SELF,rows,cols,nz,PETSC_NULL,&matrix);CHKERRQ(ierr);

		/*Now, get ir,jc and pr: */
		pr=mxGetPr(mxmatrix);
		ir=mxGetIr(mxmatrix);
		jc=mxGetJc(mxmatrix);

		/*Now, start inserting data into sparse matrix: */
		count=0;
		for(i=0;i<cols;i++){
			for(j=0;j<(jc[i+1]-jc[i]);j++){
				MatSetValue(matrix,ir[count],i,pr[count],INSERT_VALUES);
				count++;
			}
		}

	}
	else{


		/*Dealing with dense matrix: recover pointer and size: */
		mxmatrix_ptr=(double*)mxGetPr(mxmatrix);
		rows=mxGetM(mxmatrix);
		cols=mxGetN(mxmatrix);

		#ifdef _DEBUG_
		for(i=0;i<rows;i++){
			for(j=0;j<cols;j++){
				printf("%g ",*(mxmatrix_ptr+cols*j+i));
			}
			printf("\n");
		}
		#endif

		/*Create serial matrix: */
		ierr=MatCreateSeqDense(PETSC_COMM_SELF,rows,cols,NULL,&matrix);CHKERRQ(ierr);

		/*Insert mxmatrix_ptr values into petsc matrix: */
		idxm=(int*)xmalloc(rows*sizeof(int));
		idxn=(int*)xmalloc(cols*sizeof(int));

		for(i=0;i<rows;i++)idxm[i]=i;
		for(i=0;i<cols;i++)idxn[i]=i;

		ierr=MatSetOption(matrix,MAT_COLUMN_ORIENTED); CHKERRQ(ierr);//matlab is col-oriented.
		ierr=MatSetValues(matrix,rows,idxm,cols,idxn,mxmatrix_ptr,INSERT_VALUES); CHKERRQ(ierr);

	}

	/*Assemble matrix: */
	MatAssemblyBegin(matrix,MAT_FINAL_ASSEMBLY); 
	MatAssemblyEnd(matrix,MAT_FINAL_ASSEMBLY);


	/*Assign output pointer: */
	*pmatrix=matrix;
	*pmatrix_rows=rows;
	*pmatrix_cols=cols;

	return 1;
}
#endif
