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

// TODO Matrix-Funktionen implementieren

// Matrix erzeugen
Matrix createMatrix(unsigned int rows, unsigned int cols)
{
    Matrix matrix;
    matrix.buffer = NULL;
    matrix.rows = 0;
    matrix.cols = 0;
    

    // Wenn die Dimensionen gültig sind, Speicher reservieren
    if (rows > 0 && cols > 0) 
    {
        matrix.buffer = (MatrixType *)malloc(rows * cols * sizeof(MatrixType));
        if (matrix.buffer != NULL)
        {
            matrix.rows = rows;
            matrix.cols = cols;
        }
    }
    return matrix;
}

// Matrix Speicher freigeben
void clearMatrix(Matrix *matrix)
{
    if (matrix->buffer != NULL)
    {
        free(matrix->buffer);
        matrix->buffer = NULL;
    }
    matrix->rows = 0;
    matrix->cols = 0;
}

// Wert setzen
void setMatrixAt(MatrixType value, Matrix matrix, unsigned int rowIdx, unsigned int colIdx)
{
    if (rowIdx < matrix.rows && colIdx < matrix.cols)
    {
        matrix.buffer[rowIdx * matrix.cols + colIdx] = value;
    }
}

// Wert auslesen
MatrixType getMatrixAt(const Matrix matrix, unsigned int rowIdx, unsigned int colIdx)
{
    if (rowIdx < matrix.rows && colIdx < matrix.cols)
    {
        return matrix.buffer[rowIdx * matrix.cols + colIdx];
    }
    return 0; // Fallback
}

// Matrizen addieren
Matrix add(const Matrix m1, const Matrix m2)
{
    if (m1.rows != m2.rows || m1.cols != m2.cols)
    {
        return createMatrix(0, 0); // Falls Matrix-Dimensionen nicht passen
    }

    Matrix result = createMatrix(m1.rows, m1.cols);
    if (result.buffer == NULL) return result;

    for (unsigned int r = 0; r < m1.rows; r++)
    {
        for (unsigned int c = 0; c < m1.cols; c++)
        {
            result.buffer[r * m1.cols + c] =
                getMatrixAt(m1, r, c) + getMatrixAt(m2, r, c);
        }
    }
    return result;
}

// Matrizen multiplizieren
Matrix multiply(const Matrix m1, const Matrix m2)
{
    if (m1.cols != m2.rows)
    {
        return createMatrix(0, 0); // Falls Matrix-Dimensionen nicht passen
    }

    Matrix result = createMatrix(m1.rows, m2.cols);
    if (result.buffer == NULL) return result;

    for (unsigned int r = 0; r < m1.rows; r++)
    {
        for (unsigned int c = 0; c < m2.cols; c++)
        {
            MatrixType sum = 0;
            for (unsigned int k = 0; k < m1.cols; k++)
            {
                sum += getMatrixAt(m1, r, k) * getMatrixAt(m2, k, c);
            }
            result.buffer[r * m2.cols + c] = sum;
        }
    }

    return result;
}