/* iffar - IFF CAT archiver delete functions

   By Karl Lehenbauer, version 1.2, release date 5/9/88.
   This code is released to the public domain.
   See the README file for more information.

*/

#include <exec/types.h>
#include <exec/memory.h>
#include <stdio.h>
#include <fcntl.h>
#include "assert.h"
#include "iff.h"

extern ULONG nextchunk();

int delete_entries(archive_name,fnames,nfiles)
char *archive_name;
char *fnames[];
int nfiles;
{
	int old_archive_fd, new_archive_fd;
	ULONG cat_type, chunkid, innerchunkid, subtype;
	long chunksize, innerchunksize, filesize;
	char textbuf[128], old_archive_name[128];
	int i, delete_file, file_bytes;

	extern int verbose;

	/* rename the archive to its old name concatenated with ".old"
	 */
	sprintf(old_archive_name,"%s.old",archive_name);
	unlink(old_archive_name);
	rename(archive_name,old_archive_name);

	if ((old_archive_fd = OpenCAT(old_archive_name,&cat_type,&filesize)) == -1)
	{
		fprintf(stderr,"Can't open archive '%s'\n",old_archive_name);
		return(0);
	}

	if ((new_archive_fd = create_archive(archive_name,ID_MISC)) < 0)
		return(0);

	while ((chunkid = nextCATchunk(old_archive_fd,&subtype,&textbuf[0],&chunksize,&filesize)) != 0L)
	{
		/* if the chunk type isn't FORM, CAT or LIST, copy it across 
		 * without looking at it */
		 if (chunkid != ID_FORM && chunkid != ID_CAT && chunkid != ID_LIST)
		 {
		 	if (!WriteChunkHeader(new_archive_fd,chunkid,chunksize))
				return(0);
			copychunkbytes(old_archive_fd,new_archive_fd,chunksize,&filesize);
		}

		/* search to see if this chunk's name is one specified in fnames,
		 * an array of pointer to char strings */

		delete_file = 0;
		for (i = 0; i < nfiles; i++)
		{
			if (!strnicmp(fnames[i],textbuf, 128))
			{
				delete_file = 1;
				break;
			}
		}
		/* if we did decide to delete it, skip it */
		if (delete_file)
		{
			if (verbose)
				fprintf(stderr,"deleting %s\n",textbuf);

				if (!skipchunk(old_archive_fd,chunksize,&filesize))
				{
					fprintf(stderr,"delete: skipchunk failed\n");
					return(0);
				}
		}
		else	/* we want to copy it */
		{
			if (!WriteCATentry(new_archive_fd,textbuf,chunkid,subtype,chunksize))
				return(0);

			copychunkbytes(old_archive_fd,new_archive_fd,chunksize,&filesize);
		}
	}

	/* write the right length in for the header */
	rewrite_archive_header(new_archive_fd);

	/* close the old and new archive files and return success */
	close(old_archive_fd);
	close(new_archive_fd);
	return(1);
}

/* end of extract.c */

