#include </usr/local/MATLAB/R2014b/extern/include/mat.h>
#include <armadillo>
#include <string>
#include <iostream>
using namespace std;
using namespace arma;

class matReader{
	MATFile	*pFile;

public:
	matReader(string const& filename){
		pFile = matOpen(filename.c_str(),"r");
		if(pFile==NULL)
			std::cout<<"fail to open file "<<filename<<endl;;
	}
	void	read(mat & m,const string &varName){
		//matlab 默认是列存储，而armadillo库中的mat也是列存储
		mxArray *pArray = matGetVariable(pFile,varName.c_str());
		double	*pTmp = (double*)mxGetData(pArray);
		m.resize(mxGetM(pArray),mxGetN(pArray));
		for (size_t col = 0; col < m.n_cols; col++)
			for (size_t row = 0; row < m.n_rows; row++)
				m(row, col) = pTmp[col*m.n_rows+row];

		//mxFree(pArray);
	}
	void	read(vector<mat> &c, const string &varVame)
	{
		mxArray* pArray = matGetVariable(pFile,varVame.c_str());
		int	n_fold = mxGetM(pArray);
		vector<mat>	cells(n_fold);
		for (size_t i = 0; i < n_fold; i++){		
			mxArray* pCell = mxGetCell_730(pArray, i);
			cells[i].resize(mxGetM(pCell), mxGetN(pCell));
			double	*pTmp = (double*)mxGetData(pCell);
			for (size_t col = 0; col < cells[i].n_cols; col++)
				for (size_t row = 0; row < cells[i].n_rows; row++)
					cells[i](row, col) = pTmp[col*cells[i].n_rows + row];
		}
		c.swap(cells);
	}
};
