#define PROGNAME "noise"
#include <stdio.h>
#include <math.h>

short header=1;/* set if pic file contains a header char */
short xsize;   /* pic file size                          */
long area ;    /* pic file area                          */
FILE *fp=NULL,*fp1 = NULL; /* pointer to pic files */
FILE *fq = NULL; /* pointer to output file */


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

  while((argc>0)&&(*argv[0] == '-'))
  {
    switch((*argv)[1]) {
    case 'x':
      sscanf(argv+2,"%hd",&xsize);
      header=(!header);
      break;
    default:
      error("bad option");
      break;
    }
    argc--;
    argv++;
  }

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

  fprintf(stderr,"opening input file : %s\n",*argv);
  if((fp=fopen(*argv++,"r"))==NULL)
    error("can't open file");
  argc--;

  fprintf(stderr,"opening input file : %s\n",*argv);
  if((fp1=fopen(*argv++,"r"))==NULL)
    error("can't open file");
  argc--;

  compute();
  fclose(fp);
  fclose(fp1);
}

compute()
{
short xsize1;
long total;
double rt;

  if(header) {
    xsize = getc(fp)&0377;
    xsize1 = getc(fp1)&0377;
    if(xsize!=xsize1)
      error("inconsistent file headers");
  }
  area = xsize*xsize;
  total = accumulate();
  rt = sqrt((double) total);
  fprintf(stderr,"total square difs = %ld, rooted = %f, rooted&meaned= %f\n"
                 ,total,rt,rt/area);
}

long accumulate()
{
register long i,acc;
register int d;

  for(i=0,acc=0;i++<area; ) {
    d = ((getc(fp))&0377) - ((getc(fp1))&0377);
    acc+=(d*d);
/*    fprintf(stderr,"%4d %3d\n",i,d); */
  }
  return(acc);
}

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