#include <stdio.h>
#include <math.h>
#define progname "logar"

#define TMAX 256
char log_table[TMAX];  /* log conversion look up table */
short asize ;    /* pic dimensions */
short header=1;/* set if pic file contains a header char */
char dflag = 0;
     

FILE *fp, *fq = NULL;            /* input,output picture channels */
 
main(argc,argv)
char **argv;
{

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

    switch((*argv)[1]) {
    case 'x':
      sscanf(*argv+2,"%hd",&asize);
      if(asize<0) error("picture size");
      header=0;
      break;
    case 'd':
      dflag=1;
      break;
    default:
      error("unknown flag");
      break;
    }
    --argc;argv++;
  }
 
  if (argc<3)
    error("missing arguments");
  else
  {
    if((fp = fopen(*argv++,"r")) == NULL)
      error("can't access input file");
    --argc;

    if((fq = fopen(*argv,"w")) == NULL)
      error("can't access output file");
  }
  make_log_table();
  convert_pic();
  fclose(fp);
  fclose(fq);
}
 


make_log_table()
{
double CONST = 32.0/log((double) 2.0);
register char *p;
register short i;

    log_table[0]=0;
    for(i=1,p=log_table+1;i<TMAX;i++) 
      *p++ = ( (char) (log((double) i)*CONST));

  if(dflag)
    for(i=0,p=log_table;i<TMAX;i++) 
      fprintf(stderr,"%3d    %d\n",i,(*p++)&0377);
}

error(s)
char *s;
{
  fprintf(stderr,"%s: %s\n",progname,s);
  exit(1);
}
 
convert_pic()
{
long i,area;
  if (header)
     asize=getc(fp)&0377;
  if (asize<0)   error("array size out of range");
  area = asize*asize;

  if(header||asize<256)   putc(asize,fq);
  for (i=0;i<area;i++)
     putc( log_table[getc(fp)&0377] , fq);
}
