/**************************
 * Owen Sullivan
 * CPSC 2310 Fall 2022
 * Username: opsulli
 * Instructor: Dr. Yvon Feaster
**************************/

#include "functions.h"

int **readFile(FILE *fp, int *size) {
    
    fscanf(fp, "%d", size);

    int num = *size;
    int index = 0;
    
    // Fixed malloc call using sizeof(int *) instead of sizeof(int)
    int **mat = (int **)malloc(num * sizeof(int *));
    
    for (index = 0; index < num; index++)
        mat[index] = (int *)malloc(num * sizeof(int)); 

    int row = 0; 
    int col = 0;
    for (; row < num; row++) {
        
        // Fixed for loops by setting col equal to 0 at the start of each loop
        for (col = 0; col < num; col++) {
            
            fscanf(fp, "%d", &mat[row][col]);
        
        }
    
    }
    
    return mat;

}

void printMatrix(int **mat, int num) {
    
    int row = 0; 
    int col = 0;
    for (row = 0; row < num; row++) {
        
        for (col = 0; col < num; col++) {
            
            printf("%.2d\t", mat[row][col]);
        
        }
        printf("\n");
    
    }
    
}

bool isLeftDiagonal(int row, int col) {

    // Ternary operator to check if row and col are the same
    return (row == col) ? true : false;

}

bool isRightDiagonal(int size, int row, int col) {

    // Ternary operator to check if row is equal to the difference between
    // size (minus 1 since row/col indexes are 0 but size is index 1) and col
    return (row == (size - 1) - col) ? true : false;

}

int calculateVal(int **mat, int size) {

    int total = 0;

    for (int row = 0; row < size; row++) {

        for (int col = 0; col < size; col++) {

            // Check that current matrix value isn't a diagnonal
            if (!isLeftDiagonal(row, col)
                && !isRightDiagonal(size, row, col)) {

                    // Add current matrix value to total
                    total = total + mat[row][col];

            }

        }

    }

    return total;

}