#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "paulslib.h"
#include "bitmaplib.h"

#define n 6

// nxy is the image width and height = 3^n
#define nxy 729

int main(int argc,char **argv)
{
   int i,j,k;
   int **b = NULL;
   int sum;
   BITMAP4 *image,white={255,255,255,0},black={0,0,0,0};
   char fname[64];
   FILE *fptr;

   /* Form the matrix */
   b = malloc((nxy+1)*sizeof(int *));
   for (i=0;i<nxy+1;i++)
      b[i] = malloc((n+1)*sizeof(int));
   for (i=0;i<nxy+1;i++) {
      k = 1;
      for (j=0;j<n+1;j++) {
         b[i][j] = (i/k % 3) % 2;
         k *= 3;
      }
   }


   /* Create the image */
   image = Create_Bitmap(nxy,nxy);
   Erase_Bitmap(image,nxy,nxy,white);

   /* Draw the cells of the carpet */
   for (i=0;i<nxy;i++) {
      for (j=0;j<nxy;j++) {
         sum = 0;
         for (k=0;k<n+1;k++)
            sum += b[i][k]*b[j][k];
         if (sum > 0)
            Draw_Pixel(image,nxy,nxy,i,j,black);
      }
   }

   /* Write the image */
   sprintf(fname,"hadamard.tga");
   if ((fptr = fopen(fname,"w")) == NULL) {
      fprintf(stderr,"Unable to open bitmap file\n");
      exit(0);
   }
   Write_Bitmap(fptr,image,nxy,nxy,12);
   fclose(fptr);

   exit(0);
}

