/* L-31 MCS 572 Mon 31 Mar 2014 : matmatmul0.c
 * This file contains basic code to multiply two 0/1 matrices,
 * used to compare the performance with GPUs.
 * At the command line the user must give three dimensions: n, m, and p.
 * The program generates a random n-by-m 0/1 matrix A,
 * a random m-by-p 0/1 matrix B, and then computes the product.
 * In this version, a matrix is stores as one dimensional array. */

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

void randomMatrix ( int n, int m, float *x )
/* 
 * Fills up the n-by-m matrix x with random
 * values of zeroes and ones. */
{
   int i,j,r;
   float *p = x;
   for(i=0; i<n; i++)
      for(j=0; j<m; j++)
      {
         r = rand() % 2;
         *(p++) = (float) r;
      }
}

void writeMatrix ( int n, int m, float *x )
/*
 * Writes the n-by-m matrix x to screen. */
{
   int i,j;
   float *p = x;
   for(i=0; i<n; i++,printf("\n"))
      for(j=0; j<m; j++)
         printf(" %d", (int)*(p++));
}

void matrixMultiply
 ( int n, int m, int p, float *A, float *B, float *C )
/*
 * Multiplies the n-by-m matrix A 
 * with the m-by-p matrix B into the matrix C. */
{
   int i,k,rowC,colC;
   for(i=0; i<n*p; i++)
   {
      C[i] = 0.0;
      rowC = i/p;
      colC = i%p;
      float *pA = &A[rowC*m];
      float *pB = &B[colC];
      for(k=0; k<m; k++)
      {
         pB = &B[colC+k*p];
         C[i] += (*(pA++))*(*pB);
      }
   }
}

int main ( int argc, char*argv[] )
{
   if(argc < 5)
   {
      printf("call with 4 arguments :\n");
      printf("dimensions n, m, p, and mode (0 or 1)\n");
   }
   else
   {
      int n = atoi(argv[1]);    /* number of rows of A */
      int m = atoi(argv[2]);    /* number of columns of A */
                                /* and number of rows of B */
      int p = atoi(argv[3]);    /* number of columns of B */
      int mode = atoi(argv[4]); /* 0 no output, 1 show output */
      srand(time(0));
      float *A = (float*)calloc(n*m,sizeof(float));
      float *B = (float*)calloc(m*p,sizeof(float));
      float *C = (float*)calloc(n*p,sizeof(float));
      randomMatrix(n,m,A);
      randomMatrix(m,p,B);
      if(mode == 1) 
      {
         printf("a random %d-by-%d 0/1 matrix A :\n",n,m);
         writeMatrix(n,m,A);
         printf("a random %d-by-%d 0/1 matrix B :\n",m,p);
         writeMatrix(m,p,B);
      }
      matrixMultiply(n,m,p,A,B,C);
      if(mode == 1)
      {
         printf("the resulting %d-by-%d matrix C :\n",n,p);
         writeMatrix(n,p,C);
      }
   }
   return 0;
}
