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

// TODO Matrix-Funktionen implementieren

Matrix createMatrix(unsigned int rows, unsigned int cols)
{   
    if (rows ==0 || cols ==0){ // check if dimensions are valid
     Matrix empty = {.rows =0, .cols=0, .buffer =NULL}; //return empty matrix if invalid
     return empty;
    }
    MatrixType *buffer = malloc(rows * cols* sizeof(MatrixType)); //allocate memory
    if (buffer == NULL){ //check if memory allocation succeeded
        Matrix empty = {.rows =0, .cols=0, .buffer =NULL}; //return empty matrix if out of memory 
        return empty;
    }
    Matrix result ={.rows = rows, .cols = cols, .buffer = buffer}; // create and return matrix
    return result;
        
    
    
}

void clearMatrix(Matrix *matrix)
{ free(matrix-> buffer); // free the buffer memory
  matrix -> buffer = NULL; // set all members to NUll
  matrix -> rows =0;
  matrix -> cols =0;
    
}

void setMatrixAt(MatrixType value, Matrix matrix, unsigned int rowIdx, unsigned int colIdx)
{   if (rowIdx >= matrix.rows || colIdx >= matrix.cols){ // check if indices are valid 
    return; // do nothing if out of bounds
}
    unsigned int index = rowIdx * matrix.cols + colIdx; // calculate index using row-major formula
    matrix.buffer[index] = value ; // set value at that index
    
}

MatrixType getMatrixAt(const Matrix matrix, unsigned int rowIdx, unsigned int colIdx)
{  if (rowIdx >= matrix.rows || colIdx >= matrix.cols){  //check if indices are valid
    return UNDEFINED_MATRIX_VALUE;
}

unsigned int index = rowIdx * matrix.cols + colIdx; //calculate index using row-major formula
return matrix.buffer [index]; // return the value at that index
    
}

Matrix add(const Matrix matrix1, const Matrix matrix2)
{
    
}

Matrix multiply(const Matrix matrix1, const Matrix matrix2)
{
    
}