#include <stdlib.h>
#include <string.h>
#include "matrix.h"

// TODO Matrix-Funktionen implementieren

#define EMPTY_CHAR 0


Matrix createMatrix(unsigned int rows, unsigned int cols)        
{
  Matrix matrix;
  matrix.rows = rows;
  matrix.cols = cols;
  matrix.data = EMPTY_CHAR;

  if(rows > 0 && cols > 0) 
  {
    matrix.data = (MatrixType*) calloc(rows * cols, sizeof(MatrixType));
  }
  return matrix;
}

void clearMatrix(Matrix *matrix)
{
  if(matrix && matrix->data)
  {
    free(matrix->data);
    matrix->data = EMPTY_CHAR;
    matrix->rows = 0;
    matrix->cols = 0;
  }
  
}

void setMatrixAt(MatrixType value, Matrix *matrix, unsigned int rowIdx, unsigned int colIdx)
{
  if(matrix && matrix->data && rowIdx < matrix->rows && colIdx < matrix->cols)
  {
    matrix->data[rowIdx * matrix->cols + colIdx] = value;
  }
    
}

MatrixType getMatrixAt(const Matrix matrix, unsigned int rowIdx, unsigned int colIdx)
{
  if(matrix.data && rowIdx < matrix.rows && colIdx < matrix.cols)
  {
    return matrix.data[rowIdx * matrix.cols + colIdx];
  }
  return UNDEFINED_MATRIX_VALUE;
}

Matrix add(const Matrix matrix1, const Matrix matrix2)
{
  if(matrix1.rows != matrix2.rows || matrix1.cols != matrix2.cols)
  {
    return createMatrix(0,0);
  }
  Matrix result = createMatrix(matrix1.rows, matrix1.cols);
  for(unsigned int i = 0; i < result.rows; ++i)
  {
    for(unsigned int j = 0; j < result.cols; ++j)
    {
      MatrixType val = getMatrixAt(matrix1, i, j) + getMatrixAt(matrix2, i, j);
      setMatrixAt(val, &result, i, j);
    }
  }
  return result;

}

Matrix multiply(const Matrix matrix1, const Matrix matrix2)
{
  if(matrix1.cols != matrix2.rows)
  {
    return createMatrix(0, 0);
  }
  Matrix result = createMatrix(matrix1.rows, matrix2.cols);
  for(unsigned int i = 0; i < result.rows; ++i)
  {
    for(unsigned int j = 0; j < result.cols; ++j)
    {
      MatrixType sum = 0;
      for(unsigned int k = 0; k < matrix1.cols; ++k)
      {
        sum += getMatrixAt(matrix1, i, k) * getMatrixAt(matrix2, k, j);
      }
      setMatrixAt(sum, &result, i, j);
    }
  }
  return result;
    
}


//Vergleich der MatrixReihen/Zeilen
   // if((sizeof(matrix1) / sizeof(matrix1[0])) == sizeof(matrix2) / sizeof(matrix2[0]))
 //   {
   //     if(sizeof(matrix1[0]) / sizeof(matrix1[0][0]) == sizeof(matrix2[0] / sizeof(matrix2[0][0])))
 //       {
            


  //      }
 //}