#define PROGNAME "pattern"
#include <stdio.h>

#define XMAX 512 /* max pic size */
short xsize=128;   /* pic file size */
short base=0; 
short xb;
FILE *fq = NULL; /* pointer to output file */

#define BSIZE 4
char buf1[BSIZE]={ 0, 8, 2,10};
char buf2[BSIZE]={12, 4,14, 6};
char buf3[BSIZE]={ 3,11, 1, 9};
char buf4[BSIZE]={15, 7,13, 5};


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

  while((argc>0)&&(*argv[0] == '-'))
  {
    switch((*argv)[1]) {
    case 'x':
      sscanf(*argv+2,"%hd",&xsize);
      if(xsize<0) error("bad size");
      break;
    case 'b':
      sscanf(*argv+2,"%hd",&base);
      if(base<0||(255-15)<base) error("bad base");
      break;
    default:
      error("bad option");
      break;
    }
    argc--;
    argv++;
  }


  if (argc!=2)
    error("arg count");

  if((fq=fopen(*argv++,"w"))==NULL)
    error("can't open ouput file");

  if(base!=0)
    offsetbufs();
  makepic();
  fclose(fq);
}

offsetbufs()
{
short i;
char *bp1,*bp2,*bp3,*bp4;
  for(i=0,bp1=buf1,bp2=buf2,bp3=buf3,bp4=buf4;i<BSIZE;i++) {
    *bp1++ = ((*bp1)&0377) + base;
    *bp2++ = ((*bp2)&0377) + base;
    *bp3++ = ((*bp3)&0377) + base;
    *bp4++ = ((*bp4)&0377) + base;
  }
}

write_line(bp)
char *bp;
{
register short i;
char *obp;
  for(i=0,obp=bp;i<xb;bp=obp,i++) {
     putc(*bp++,fq);
     putc(*bp++,fq);
     putc(*bp++,fq);
     putc(*bp  ,fq);
  }
}


makepic()
{
short i;

  if(xsize<256) putc(xsize,fq); /*header*/
  xb=xsize/BSIZE;

  for(i=0;i<xb;i++) {
    write_line(buf1);
    write_line(buf2);
    write_line(buf3);
    write_line(buf4);
  }
}

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