/*
 *  xbmf by Davide Libenzi (XMail Broken Mailers Filter)
 *  Copyright (C) 2006  Davide Libenzi
 *
 *  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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 *  Davide Libenzi <davidel@xmailserver.org>
 *
 */

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



static void usage(char const *prg) {

	fprintf(stderr, "use: %s [-z CHNUM] filepath\n", prg);
}

int main(int ac, char **av) {
	int n, zrep = ' ';
	size_t i, size, bmod;
	long off;
	FILE *fp;
	char buf[2048];

	for (n = 1; n < ac; n++) {
		if (strcmp(av[n], "-z") == 0) {
			if (++n < ac)
				zrep = atoi(av[n]);
		} else
			break;
	}
	if (n == ac) {
		usage(av[0]);
		return 0;
	}
	if ((fp = fopen(av[n], "r+b")) == NULL) {
		perror(av[n]);
		return 0;
	}
	size = 0;
	do {
		off = ftell(fp);
		if ((size = fread(buf, 1, sizeof(buf), fp)) > 0) {
			for (i = bmod = 0; i < size; i++)
				if (buf[i] == 0)
					buf[i] = (char) zrep, bmod++;
			if (bmod) {
				fseek(fp, off, SEEK_SET);
				if (fwrite(buf, 1, size, fp) != size) {
					perror(av[n]);
					fclose(fp);
					return 3;
				}
				fseek(fp, off + size, SEEK_SET);
			}
		}
	} while (size == sizeof(buf));
	if (size > 0 && buf[size - 1] != '\n') {
		fseek(fp, 0, SEEK_END);
		fputs("\r\n", fp);
	}
	fclose(fp);

	return 0;
}

