#include "MatlabWriter.h"
#include "Matrix.h"
#include <matio.h>
#include <utility>

MatlabWriter::MatlabWriter(const std::string& aFileName)
    : mFileName(aFileName)
{
    mMat = Mat_CreateVer(mFileName.c_str(),nullptr, MAT_FT_MAT5);
}

MatlabWriter::~MatlabWriter()
{
    Mat_Close(mMat);
}

void MatlabWriter::setMatrix(const Aurora::Matrix& aMatrixs, const std::string& aName)
{
    mMatrixs.insert(std::pair<std::string, Aurora::Matrix>(aName, aMatrixs));
}

void MatlabWriter::write()
{
    for(auto i= mMatrixs.begin(); i!=mMatrixs.end(); ++i)
    {
        Aurora::Matrix matrix = i->second;
        std::string name = i->first;
        int dimsSize = matrix.getDims();
        size_t dims[3] ={(size_t)matrix.getDimSize(0),(size_t)matrix.getDimSize(1), (size_t)matrix.getDimSize(2)};
        matvar_t* var =  Mat_VarCreate(name.c_str(),MAT_C_SINGLE,MAT_T_SINGLE,dimsSize,dims,matrix.getData(),0);
        Mat_VarWrite(mMat,var,MAT_COMPRESSION_NONE);
        Mat_VarFree(var);
    }
}
