/*
    LIB - a librarian for compatible OBJ/LIB files
    Copyright (C) 1995,1996  Steffen Kaiser

    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.
*/
/* $RCSfile: FOREACH.C $
   $Locker: ska $	$Name: v3_2 $	$State: Rel $

	ForEach file cmd [{arg}] [%] [{arg}]

	Reads the file line-by-line and calls cmd via system() with the first
	single '%' replaced by the line. If there is no '%', the line will
	be appended

*/

#include <stdio.h>

#ifndef lint
static char rcsid[] = 
	"$Id: FOREACH.C 3.3 1999/02/17 05:18:08 ska Rel ska $";
#endif


main(int argc, char **argv)
{	FILE *f;
	char preBuf[128], postBuf[128], readBuf[2048], runBuf[3092], *p;

	if(argc < 3) {
		printf("ForEach - Invokes a command for each line of a file\nUseage: %s file cmd [{arg}]\n", argv[0]);
		puts("If one arg is a single '%', this sign is replaced by the line\notherwise, the read line is appended.");
		exit(30);
	}
	if(!(f = fopen(argv[1], "rt"))) {
		printf("Cannot open %s\n", argv[1]);
		exit(31);
	}
	*preBuf = *postBuf = 0;
	argv = &argv[1];
	while(*++argv)
		if(memcmp(*argv, "%", 2)
		 && memcmp(*argv, "%%", 3)
		 && memcmp(*argv, "%%%", 4)) {
			strcat(preBuf, *argv);
			strcat(preBuf, " ");
		}
	else break;
	if(*argv) while(*++argv) {
		strcat(postBuf, " ");
		strcat(postBuf, *argv);
	}
	while(fgets(readBuf, sizeof(readBuf), f)) {
		p = strchr(readBuf, '\0');
		while(p >= readBuf && isspace(*--p));
		p[1] = 0;
		p = readBuf - 1;
		while(isspace(*++p));
		if(*p) {
			concat(runBuf, preBuf, p, postBuf);
			if(strlen(runBuf) > 100) puts("Command line too long -- ignored");
			else system(runBuf);
		}
	}
	fclose(f);
}
