#include <stdio.h>
#define progname "mean"

short asize ;    /* pic dimensions */
long area;
char header=1;

FILE *fp = NULL;            /* input 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;
    default:
      error("unknown flag");
      break;
    }
    --argc;argv++;
  }
 
  if (argc<2)
    error("missing arguments");
  if((fp = fopen(*argv,"r")) == NULL)
    error("can't access input file");

  printf("mean grey-level = %3d\n",mean());
  fclose(fp);
}
 
long mean()
{
long i,total;
  if(header) asize=(getc(fp)&0377);
  area=asize*asize;
  for (i=0,total=0; i<area; i++)
    total += (getc(fp)&0377);
  return(total/area);
}

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