#include "c:stdio.h"
#define progname "mondrian"
#define MAXSIZE 256 /* max. image size */
#define MAXAREA MAXSIZE*MAXSIZE
char pic[MAXAREA];
FILE *fq=NULL;
short xsize=256;
int area = 256*256;
char header=0;
char rflag =0;
char mon_file_name[10] = "mon.256";
char ill_file_name[10] = "ill.256";

main(argc,argv)
char **argv;
{

  argv++;
  while ((argc>1)&&((*argv)[0] == '-'))
  {

    switch((*argv)[1]) {
    case 'r': 
      rflag=1;
      break;
    default:
      error("unknown flag");
      break;
    }
    --argc;argv++;
  }

  if(rflag){
    strcpy(mon_file_name,"monr.256");
    strcpy(ill_file_name,"illr.256");
  }

  if((fq=fopen(mon_file_name,"w")) == NULL)
    error("can't write mondrian  file ");

  make_mondrain();
  write_pic(fq);
  fclose(fq);

  if((fq=fopen(ill_file_name,"w")) == NULL)
    error("can't write illuminated mondrain file ");

  illuminate();
  write_pic(fq);
  fclose(fq);
}

illuminate()
{
long xsize_2 = xsize*2;
long xsize_4 = xsize*4;
long xsize_8 = xsize*8;
long xsize_10 = xsize*10;
long l;
short i,j;
char *picp;

  for(j=0,picp=pic;j<xsize;j++)
    for(i=0;i<xsize;i++,picp++) {
       l = (*picp);
       l= l&0377;
       if(rflag)       l=l*(xsize_4 -i-j);
       else            l=l*(xsize_8 +i+j);
       l=l/xsize_10;
       *picp = l;
    }
}

outofpic(x) {   return((x<0) || (x>=xsize));   }

rectangle(x,y,breadth,height,grey_level)
short x,y,breadth,height;
char grey_level;
{
short i,j;
char *picp;

  if(outofpic(x))    error("bad x value");
  if(outofpic(y))    error("bad y value");
  if(outofpic(x+breadth))  error("bad breadth value");
  if(outofpic(y+height))  error("bad height value");

  picp=pic+x+xsize*y;
  for(j=0;j<height;j++,picp+=(xsize-breadth))
    for(i=0;i<breadth;i++)
      *picp++ =grey_level ;
}

write_pic(fq)
FILE *fq;
{
  char *picp;
  int i;

  if(header) putc(xsize,fq);
  for(i=0,picp=pic;i<area;i++)
    putc(*picp++,fq);
}


error(s)
char *s;
{
  fprintf(stderr,"%s: %s\n",progname,s);
  exit(1);
}

#define Lgrey 255
#define MLgrey 205
#define Mgrey 154
#define MDgrey 103
#define Dgrey 52
#define Bgrey 5

make_mondrain()
{
rectangle(0,0,MAXSIZE/2,MAXSIZE-1,MLgrey); /*e*/
rectangle(MAXSIZE/2,0,MAXSIZE/2-1,MAXSIZE-1,Dgrey); /*e*/
}
