/******************************************************************************
*									      *
*	(C) 1993 by K. Ballueder					      *
*									      *
*	Please feel free to contact me:					      *
*		kballued@charon.physik.uni-osnabrueck.de		      *
*		kballued@jupiter.rz.uni-osnabrueck.de			      *
*									      *
******************************************************************************/
/*
**	zfopen: open compressed file for readonly mode
*/

#include <stdio.h>
#include <limits.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "zfopen.h"

FILE * zfopen(char *filename, char *type)
{
	FILE 	*stream;
	char 	z_filename[PATH_MAX],
		t_filename[PATH_MAX] = "",
		commandstring[PATH_MAX];

	/* try uncompressed file first */
	if((stream = fopen(filename, type)) != NULL)
		return stream;
		
	/* try gzipped file */
	strcpy(z_filename,filename);
	strcat(z_filename,ZFO_SUFFIX1);
	if((stream = fopen(z_filename, "rb")) == NULL)
	{	/* try compressed file */
		strcpy(z_filename, filename);
		strcat(z_filename, ZFO_SUFFIX2);
		if((stream = fopen(z_filename, "rb")) == NULL)
			return NULL;
	}
	/* Ok, now decompress it, first close it again */
	fclose(stream);
	tmpnam(t_filename);	
	if((stream = fopen(t_filename, "wb")) == NULL)
			return NULL;
	strcpy(commandstring, ZFO_PROG);
	strcat(commandstring," < ");
	strcat(commandstring,z_filename);
	strcat(commandstring," > ");
	strcat(commandstring,t_filename);
	/* ok, let's do it */
	fclose(stream);
	system(commandstring);

	if((stream = fopen(t_filename, type)) == NULL)
			return NULL;
	unlink(t_filename);
	return stream;
}
