/* matrixop.c - Define some basic matrix operations 
 *
 * Jerod Weinman
 * 21 May 2008
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "matrix.h"
#include "matrixop.h"

/* Check the dimensions of three matrices for the sum C=A+B 
 *
 * Returns -1 if there is a dimension mismatch, and zero otherwise. */
int mtxCheckAddDim(const struct matrix_t *a, const struct matrix_t *b, 
                        const struct matrix_t *c)
{
     
     if (a->rows != b->rows || a->rows != c->rows  ||
         a->cols != b->cols || a->cols != c->cols ) {
          return -1;
     }
     
     return 0;

}


/* Matrix addition C = A + B
 *
 * Preconditions:
 *   Matrix parameters a,b and c all have the same dimension
 *
 * Postconditions:
 *   The resulting matrix sum is stored in parameter c
 *   Return value of 0 indicates successful completion of the addition
 */
int mtxAdd( const struct matrix_t *a, const struct matrix_t *b, 
                   struct matrix_t *c)
{
     /* Make sure these matrices are "addable" */
     int res = mtxCheckAddDim(a,b,c);

     if (res<0) {
          fprintf(stderr,"Dimension mismatch for matrix add.\n");
          return res;
     }
     
     int m = a->rows;        /* Dimensions of input matrices */
     int n = a->cols;

     MTX_TYPE *pa, *pb, *pc; /* Pointers to matrix data */

     /* Initialize pointers to beginning of data */
     pa = a->data;
     pb = b->data;
     pc = c->data;

     /* Iterate over every entry in the matrices */
     int i,j;
     for (i=0 ; i<m ; i++)
          for (j=0 ; j<n ; j++, pa++,pb++,pc++)
               *pc = *pa + *pb;


     /* Indicate successful completion */
     return 0;
}
