/*
 * The author of this software is Eric Grosse.  Copyright (c) 1993 by AT&T.
 * Permission to use, copy, modify, and distribute this software for any
 * purpose without fee is hereby granted, provided that this entire notice
 * is included in all copies of any software which is or includes a copy
 * or modification of this software and in all copies of the supporting
 * documentation for such software.
 * THIS SOFTWARE IS BEING PROVIDED "AS IS", WITHOUT ANY EXPRESS OR IMPLIED
 * WARRANTY.  IN PARTICULAR, NEITHER THE AUTHORS NOR AT&T MAKE ANY
 * REPRESENTATION OR WARRANTY OF ANY KIND CONCERNING THE MERCHANTABILITY
 * OF THIS SOFTWARE OR ITS FITNESS FOR ANY PARTICULAR PURPOSE.
 */

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include "suffix.h"

void *
Malloc(size_t n)
{
	void *p;
	if (!(p = malloc((size_t)n))){
		fprintf(stderr,"unable to allocate %d bytes\n",n);
		exit(1);
	}
	return p;
}

int
read_suffix(char *file, Suffix **ps)
{
	FILE *f;
	char line[1024];
	unsigned char *r;
	Suffix *s;

	*ps = 0;
	if((f = fopen(file,"r"))==NULL) /* master presumably doesn't follow our scheme */
		return(1);
	while(fgets(line,sizeof(line),f)!=NULL){
		if(line[0]!='.') continue;   /* must be a comment */
		for(r = (unsigned char*)line; *r && !isspace(*r); r++){}
		s = (Suffix*)Malloc(sizeof(*s));
		s->size = r-(unsigned char*)line;
		s->dotsuf = (char*)Malloc((s->size+1)*sizeof(char));
		strncpy(s->dotsuf,line,s->size);
		s->dotsuf[s->size] = 0;
		*ps = s;
		ps = &s->next;
		*ps = 0;
	}
	fclose(f);
	return(0);
}

int
need_compr(char *basename, Suffix *s)
{
	int n = strlen(basename);
	for(; s; s = s->next)
		if( n>=s->size && strcmp(basename+n-s->size,s->dotsuf)==0 )
			return(0);
	return(1);
}

#ifdef STANDALONE
int
main(int argc, char **argv)
{
	int aflag = 0;
	char name[2001], *newline;
	Suffix *suffixlist;
	if(strcmp(argv[1],"-a")==0){
		aflag++; argv++; argc--;
	}
	if(argc!=2){
		fprintf(stderr,"usage: %s suffixlist < filelist > Zfilelist\n",argv[0]);
		exit(1);
	}
	if(read_suffix(argv[1],&suffixlist))
		exit(1);	/* uncompressed==1 */
	while(fgets(name,sizeof(name),stdin)!=NULL){
		newline = name+(strlen(name)-1);
		if(*newline=='\n') *newline = 0;
		if(need_compr(name,suffixlist))
			printf("%s.Z\n",name);
		else if(aflag)
			printf("%s\n",name);
	}
	exit(0);
}
#endif