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

#define XMAX 512 /* max pic size */
short xsize=16;   /* pic file size */
short hi=255;   /* high grey-level */
short lo=0;   /* low grey-level */
FILE *fq = NULL; /* pointer to output file */
char rflag=0; /* set if making a ramp */
char line[XMAX]; /* line buffer */


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 'h':
      sscanf(*argv+2,"%hd",&hi);
      if(hi<0||255<hi) error("bad hi");
      break;
    case 'l':
      sscanf(*argv+2,"%hd",&lo);
      if(lo<0||255<lo) error("bad lo");
      break;
    case 'r':
      rflag=1;
      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");

  makepic();
  fclose(fq);
}

write_line()
{
short i;
char *p;

  for(i=0,p=line;i<xsize;i++)
     putc(*p++,fq);
}

make_step()
{
short i,xsize_2=xsize/2;
char *p;

  for(i=0,p=line;i<xsize_2;i++)    *p++=lo;
  for(;i<xsize;i++)                *p++=hi;
}

make_ramp()
{
float grad=(hi-lo)/(((float)xsize)-1.0);
float acc;
short i;
char *p;

  for(i=0,p=line,acc=0.0;i<xsize;i++,acc+=grad)
    *p++ =( (char) lo + acc);
}

make_line()
{
  if(rflag) make_ramp();
  else      make_step();
}

makepic()
{
short i;

  if(xsize<256) putc(xsize,fq); /*header*/
  make_line();
  for(i=0;i<xsize;i++)
    write_line();
}

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