#include <stdio.h>
#include <opencv2/core/core_c.h>

#define vars "ABCDEF" 
#define DIM 6
int main( int argc, char** argv )
{

  float data[DIM*DIM]={4,3,2,1,1,2,
                       1,2,3,4,4,3,
                       8,1,2,8,8,2,
                       5,3,6,9,9,6,
                       9,8,1,2,4,5,
                       5,6,1,2,7,8};
  CvMat mat;
  cvInitMatHeader(&mat,DIM,DIM,CV_32FC1,&data);
  CvMat *res=cvCreateMat(DIM,1,CV_32FC1);
  CvMat *right=cvCreateMat(DIM,1,CV_32FC1);
  cvSet(right,cvScalarAll(3)); 

  cvSolve(&mat,right,res);

  printf("Matrix roots by gaussian decomp.\n");
  for(int i=0;i<DIM;i++)
      printf("%c = %f\n",vars[i],cvGet2D(res,i,0).val[0]);

  float tmp=0;
  for(int i=0;i<DIM;i++)
    tmp+=data[i]*cvGet2D(res,i,0).val[0]; 

  printf("Accuracy check, result must be 3\nresult=%f\n",tmp);

  cvReleaseMat(&res);
  cvReleaseMat(&right);

  printf("Find Inverse matrix by gaussian decomp\nMultiply source and inverse matrix must be identity matrix.\n"); 
  
  CvMat *inv=cvCreateMat(DIM,DIM,CV_32FC1);
  res=cvCreateMat(DIM,DIM,CV_32FC1);

  cvInvert(&mat,inv);
  cvMatMulAdd(&mat,inv,NULL,res);

  for(int i=0;i<DIM;i++)
    for(int j=0;j<DIM;j++)
      printf("%d%s",cvRound(cvGet2D(res,i,j).val[0]),((j+1)%DIM==0?"\n":" "));

  cvReleaseMat(&inv);
  cvReleaseMat(&res);

	return EXIT_SUCCESS;
}
