// ddiff/dpatch - manipulate differences between debian packages.
// Copyright 2000 Tom Rothamel <tom-ddiff@onegeek.org>
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  

#include <stdio.h>
#include <string.h>
#include <malloc.h>
#include <unistd.h>
#include "genfile.h"

#define debug(x, y...) fprintf(stderr, "gfstdio %d: " x "\n", getpid() , ## y) /**/
/* #define debug(x, y...) /**/

// This is an implementation of a GFILE that uses a regular stdio stream
// as it's base. This is used to get a file open so that GARCHIVES can be
// created from it.

struct StdioGF : public GFILE {
	FILE *f;
	char *fn;
	
	char *gets(char *, int);
	size_t read(void *, size_t, size_t);
	void seek(long);
	void skip(long);
	long tell();
	GFILE *dup();
	
	~StdioGF();
};


GFILE *open_gfstdio(char *fn) {
	FILE *f;
	StdioGF *sgf;
	
	f = fopen(fn, "r");
	if (!f) return NULL;

	sgf = new StdioGF;
	sgf->f = f;
	sgf->fn = strdup(fn);
	return sgf;
}

char *StdioGF::gets(char *s, int l) {
	return fgets(s, l, f);
}

size_t StdioGF::read(void *s, size_t size, size_t nmemb) {
	int rv;
	
	rv = fread(s, size, nmemb, f);
	return rv;
}

void StdioGF::seek(long off) {
	fseek(f, off, SEEK_SET);
}

void StdioGF::skip(long off) {
	fseek(f, off, SEEK_CUR);
}

long StdioGF::tell() {
	return ftell(f);
}

GFILE *StdioGF::dup() {
	return open_gfstdio(fn);
}

StdioGF::~StdioGF() {
	fclose(f);
	free(fn);
}
