/*
** common v1.1
**
** Tries to get the common bytes of many files (useful for /etc/magic)
**
** Copyright (c) 9.7.94 by Andreas Ley <Andreas.Ley@rz.uni-karlsruhe.de>
**
** Permission to use, copy, modify, and distribute this software for any
** purpose and without fee is hereby granted, provided that the above
** copyright notice appears in all copies. This software is provided "as is"
** and without any express or implied warranties.
**
** This program has been tested on a HP9000/720 with HP-UX A.08.07
** In this environment, neither lint -u nor gcc -Wall produce any messages.
** If you encounter any errors or need to make any changes to port it
** to another platform, please contact me.
**
** Version history
**
** Version 1.1 - 7.6.2001
**	Added dynamic buffers
**
** Version 1.0 - 9.7.94
**	Initial version
*/

char header[]="common v1.1\n(c) 1994 by Andreas Ley\n";

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/param.h>


unsigned char	*bytes,*buffer;
int		max=-1,maxsize=16*BUFSIZ;


void common(src)
FILE	*src;
{
	int		nmax;

	if (max<0)
		max=fread(bytes,1,maxsize,src);
	else {
		nmax=fread(buffer,1,max,src);
		for (max=0;max<nmax;max++)
			if (buffer[max]!=bytes[max])
				break;
	}
}



void usage(image)
char *image;
{
	(void)fprintf(stderr,"Usage: %s [-h] [-v] [-s bufsize] file1 file2 [file3...]\n",image);
	(void)fprintf(stderr,"-s  specify buffer size (default: %d)\n",maxsize);
	exit(1);
}


main(argc,argv)
int	argc;
char	*argv[];
{
	int		c;
	extern char	*optarg;
	extern int	optind;
	char		error[2*MAXPATHLEN+14];
	FILE		*src;

	while ((c=getopt(argc,argv,"s:vh?")) != EOF)
		switch ((char)c) {
		case 's':
			maxsize=atol(optarg);
			break;
		case 'v':
			(void)fprintf(stderr,header);
			exit(0);
		case 'h':
			(void)fprintf(stderr,header);
		case '?':
			usage(argv[0]);
		}

	if (optind+1>=argc)
			usage(argv[0]);

	if (!(bytes=(unsigned char *)malloc(maxsize))) {
		(void)sprintf(error,"%s: cannot malloc %d bytes",argv[0],maxsize);
		perror(error);
	}
	if (!(buffer=(unsigned char *)malloc(maxsize))) {
		(void)sprintf(error,"%s: cannot malloc another %d bytes",argv[0],maxsize);
		perror(error);
	}

	for (;optind<argc;optind++)
		if (strcmp(argv[optind],"-"))
			if (src=fopen(argv[optind],"r")) {
				common(src);
				(void)fclose(src);
			}
			else {
				(void)sprintf(error,"%s: cannot open %s",argv[0],argv[optind]);
				perror(error);
			}
		else
			common(stdin);

	printf("%she first %d bytes are common in all files.\n",max<maxsize?"T":"At least t",max);

	return(0);
}

