/* @(#)make.c	1.67 01/12/09 Copyright 1985, 87, 88, 91, 1995-2001 J. Schilling */
#ifndef lint
static	char sccsid[] =
	"@(#)make.c	1.67 01/12/09 Copyright 1985, 87, 88, 91, 1995-2001 J. Schilling";
#endif
/*
 *	Make program
 *
 *	Copyright (c) 1985, 87, 88, 91, 1995-2001 by J. Schilling
 */
/*
 * 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, 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; see the file COPYING.  If not, write to
 * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#include <mconfig.h>
#include <stdio.h>
#include <standard.h>
#include <getargs.h>
#include "make.h"
#	include	<errno.h>
#include <stdxlib.h>
#include <strdefs.h>
#include <unixstd.h>
#include <timedefs.h>
#include <waitdefs.h>
#include <signal.h>

#include <dirdefs.h>
#include <maxpath.h>
#include <getcwd.h>
#include <schily.h>

char	make_version[] = "1.2a15";

#ifdef	_FASCII
LOCAL	void	setup_env	__PR((void));
#endif
EXPORT	void	usage		__PR((int exitcode));
LOCAL	int	addmakefile	__PR((char *name));
LOCAL	void	read_defs	__PR((void));
LOCAL	void	read_makefiles	__PR((void));
EXPORT	void	setup_dotvars	__PR((void));
LOCAL	void	setup_vars	__PR((void));
LOCAL	void	setup_MAKE	__PR((char* name));
EXPORT	char*	searchtype	__PR((int mode));
LOCAL	void	printdirs	__PR((void));
LOCAL	int	addcommandline	__PR((char *  name));
LOCAL	void	read_cmdline	__PR((void));
EXPORT	void	doexport	__PR((char *));
LOCAL	void	read_environ	__PR((void));
EXPORT	int	main		__PR((int ac, char ** av));
LOCAL	void	check_old_makefiles __PR((void));
LOCAL	void	getmakeflags	__PR((void));
LOCAL	void	read_makemacs	__PR((void));
LOCAL	char*	nextmakemac	__PR((char *s));
LOCAL	void	read_mac	__PR((char *mf));
LOCAL	void	setmakeflags	__PR((void));
LOCAL	char*	stripmacros	__PR((char *macbase, char *new));
LOCAL	void	setmakeenv	__PR((char *envbase, char *envp));
EXPORT	int	docmd		__PR((char * cmd, obj_t * obj));
EXPORT	BOOL	move_tgt	__PR((obj_t * from));
LOCAL	int	copy_file	__PR((char * from, char * objname));
EXPORT	BOOL	touch_file	__PR((char * name));
LOCAL	date_t	gcurtime	__PR((void));
LOCAL	date_t	gnewtime	__PR((void));
EXPORT	date_t	gftime		__PR((char * file));
LOCAL	BOOL	isdir		__PR((char * file));
EXPORT	long	gfileid		__PR((char * file));
EXPORT	char*	prtime		__PR((date_t  date));
LOCAL	void	handler		__PR((int signo));
EXPORT	char	*curwdir	__PR((void));
LOCAL	char*	getdefaultsfile	__PR((void));
#ifndef	HAVE_PUTENV
EXPORT	int	putenv		__PR((const char *new));
#endif

BOOL	posixmode	= FALSE;	/* We found a .POSIX target	*/
BOOL	Eflag		= FALSE;	/* Environment overrides vars	*/
BOOL	Iflag		= FALSE;	/* Ignore errors		*/
BOOL	Kflag		= FALSE;	/* Ignore errors ????		*/
BOOL	Nflag		= FALSE;	/* Only show what to do		*/
BOOL	Qflag		= FALSE;	/* If up to date exit (0)	*/
BOOL	Rflag		= FALSE;	/* Turn off internal rules	*/
BOOL	Sflag		= FALSE;	/* Be silent			*/
BOOL	Tflag		= FALSE;	/* Touch objects		*/
int	Debug		= 0;		/* Print reason for rebuild	*/
int	XDebug		= 0;		/* Print extended debug info	*/
BOOL	Prdep		= FALSE;	/* Print include dependency	*/
BOOL	Probj		= FALSE;	/* Print object tree		*/
BOOL	Print		= FALSE;	/* Print macro/target definitions*/
int	Dmake		= 0;		/* Display makefile		*/
BOOL	help		= FALSE;	/* Show Usage			*/
BOOL	pversion	= FALSE;	/* Show version string		*/
BOOL	NoWarn		= FALSE;	/* No warnings			*/
BOOL	DoWarn		= FALSE;	/* Print extra warnings		*/
char	Makeflags[]	= "MAKEFLAGS";
char	Make_Flags[]	= "MAKE_FLAGS";
char	Make_Macs[]	= "MAKE_MACS";
char	Envdefs[]	= "Environment defs";
char	Makedefs[]	= "Internal Makefile";
char	Ldefaults[]	= "defaults.smk";
#ifdef	SVR4
char	Defaults[]	= "/opt/schily/lib/defaults.smk";
#else
char	Defaults[]	= "/usr/bert/lib/defaults.smk";
#endif
#define	MAKEFILECOUNT	32		/* Max number of Makefiles	*/
char	SMakefile[]	= "SMakefile";	/* smake's default Makefile	*/
char	Makefile[]	= "Makefile";	/* Primary default Makefile	*/
char	makefile[]	= "makefile";	/* Secondary default Makefile	*/
char   *MakeFileNames[MAKEFILECOUNT] = {/* To hold all Makefilenames	*/
#define	MF_IDX_IMPICIT	0
		Makedefs,		/* Implicit rules		*/
#define	MF_IDX_ENVIRON	1
		Envdefs,		/* Environment strings		*/
#define	MF_IDX_DEFAULT	2
		Makefile		/* Default make file		*/
};
#define	MF_IDX_BASE	MF_IDX_DEFAULT
int	Mfilecount	= 2;		/* Current Makefile index	*/
int	Mfiles	= 2;			/* Number of Makefiles found+2	*/
#define	CMDLINECOUNT	64		/* Max number of Cmdline Macros	*/
char	CmdLMac[]	= "Command Line Macro"; /* Makefile Name for ..	*/
char	*CmdLDefs[CMDLINECOUNT];	/* To hold all Cmdline Macros	*/
int	Cmdlinecount;			/* Number of Cmdline Macros	*/
char	*MFCmdline;			/* Pointer to Cmdl. Macs fr. env*/

int	Mflags;

char	*ObjDir;		/* .OBJDIR: pathname Target destination dir */
int	ObjSearch	= SALL;	/* .OBJSEARCH: searchtype for explicit rules*/
list_t	*SearchList;		/* .SEARCHLIST: list of src/obj dir pairs   */
list_t	*Suffixes;		/* .SUFFIXES: list of suffixes (POSIX)      */
BOOL	SSuffrules;
obj_t	*Init;			/* .INIT: command to execute at startup	    */
obj_t	*Done;			/* .DONE: command do execute on success	    */
obj_t	*Failed;		/* .FAILED: command to execute on failure   */
obj_t	*IncludeFailed;		/* .INCLUDE_FAILED: cmd to exec if missing  */
obj_t	*Deflt;			/* .DEFAULT: command to execute if no rule  */
obj_t	*Precious;		/* .PRECIOUS: list of targets not to remove */
obj_t	*curtarget;		/* current target of actually running cmd   */
date_t	curtime;		/* Current time				    */
date_t	newtime;		/* Special time newer than all		    */

#define	MINSECS		60
#define	HOURSECS	(MINSECS*60)
#define	DAYSECS		(HOURSECS*24)
#define	MONTHSECS	(DAYSECS*30)
#define	YEARSECS	(DAYSECS*365)

char	Nullstr[]	= "";
char	slash[]		= PATH_DELIM_STR;

LOCAL	BOOL	xpatrules;	/* Have non local pattern rules	in Makefile */
EXPORT	int	xssrules;	/* Have non local simple suffix rules	    */

#ifdef	_FASCII				/* Mark Williams C		*/
char	*_stksize	= (char *) 8192;

/*
 * Old and probably outdated setup that was needed in 1986 to make
 * 'smake' run on a ATARI ST using the Marc Williams C development tools.
 */
LOCAL void
setup_env()
{
	register char	*ep;
	extern	 char	*getenv();

	if ((ep = getenv("PATH")) == (char *) NULL || *ep == '\0')
		putenv("PATH=.bin,,\\bin,\\lib");

	if ((ep = getenv("SUFF")) == (char *) NULL || *ep == '\0')
		putenv("SUFF=,.prg,.tos,.ttp");

	if ((ep = getenv("LIBPATH")) == (char *) NULL || *ep == '\0')
		putenv("LIBPATH=\\lib,\\bin");

	if ((ep = getenv("TMPDIR")) == (char *) NULL || *ep == '\0')
		putenv("TMPDIR=\\tmp");

	if ((ep = getenv("INCDIR")) == (char *) NULL || *ep == '\0')
		putenv("INCDIR=\\include");
}
#endif

EXPORT void
usage(exitcode)
	int	exitcode;
{
	error("Usage:	smake [options] [file1...filen]\n");
	error("Options:\n");
	error("	-e	Environment overrides variables in Makefile.\n");
	error("	-i	Ignore errors.\n");
	error("	-k	Ignore errors (not implemented).\n");
	error("	-n	Don't make - only say what to do.\n");
	error("	-p	Print all macro and target definitions.\n");
	error("	-q	Question mode. Exit code is 0 if target is up to date.\n");
	error("	-r	Turn off internal rules.\n");
	error("	-s	Be silent.\n");
	error("	-t	Touch Objects instead of executing defined commands.\n");
	error("	-w	Don't print warning Messages.\n");
	error("	-W	Print extra (debug) warning Messages.\n");
	error("	-D	Display Makefiles as read in.\n");
	error("	-DD	Display Makefiles/Rules as read in.\n");
	error("	-d	Print reason why a target has to be rebuilt.\n");
	error("	-dd	Debug dependency check.\n");
	error("	-xM	Print include dependency.\n");
	error("	-xd	Print extended debug info.\n");
	error("	-probj	Print object tree.\n");
	error("	-help	Print this help.\n");
	error("	-version Print version number.\n");
	error("	-posix	Force POSIX behaviour.\n");
	error("	mf=makefilename | -f makefilename\n");
	exit(exitcode);
}

/*
 * Add a new makefile to the list of makefiles.
 * Called by getargs() if a -f option was found.
 */
LOCAL int
addmakefile(name)
	char	*name;
{
	if (Mfiles >= MAKEFILECOUNT) {
		errmsgno(EX_BAD, "Too many Makefiles.\n");
		return (BADFLAG);
	}
	MakeFileNames[Mfiles++] = name;
	return (1);
}

/*
 * Read the default rules - either compiled in or from file.
 */
LOCAL void
read_defs()
{
		char	*deflts;
	extern	char	implicit_rules[];/* Default rules compiled into make */

	Dmake--;
	Mfilecount = 0;

	if (gftime(Ldefaults) != 0) {
		MakeFileNames[0] = Ldefaults;
		readfile(Ldefaults, TRUE);
#ifdef	DEFAULTS_PATH				/* This is the install path */
	} else if (gftime(DEFAULTS_PATH) != 0) {
		MakeFileNames[0] = DEFAULTS_PATH;
		readfile(DEFAULTS_PATH, TRUE);
#endif
	} else if (gftime(Defaults) != 0) {
		MakeFileNames[0] = Defaults;
		readfile(Defaults, TRUE);
	} else if ((deflts = getdefaultsfile()) != NULL) {
		MakeFileNames[0] = deflts;
		readfile(deflts, TRUE);
	} else {
		readstring(implicit_rules, Makedefs);
	}
	Dmake++;
}

/*
 * Read in all external makefiles. Use either the names from command line
 * or look for the default names "Makefile" and "makefile".
 */
LOCAL void
read_makefiles()
{
	patr_t	*oPatrules = Patrules;
	patr_t	**opattail = pattail;

	Patrules = 0;
	pattail = &Patrules;
	xssrules = 0;

	Mfilecount = 2;
	if (Mfiles == 2) {
		/*
		 * First look for "SMakefile",
		 * then for "Makefile", then for "makefile"
		 */
		if (gftime(SMakefile) != 0) {		/* "SMakefile" */
			Mfiles++;
			MakeFileNames[2] = SMakefile;
		} else if (gftime(Makefile) != 0) {	/* "Makefile" */
			Mfiles++;
			MakeFileNames[2] = Makefile;
		} else if (gftime(makefile) != 0) {	/* "makefile" */
			Mfiles++;
			MakeFileNames[2] = makefile;
		}
	}
	while (Mfilecount < Mfiles) {
		readfile(MakeFileNames[Mfilecount], TRUE);
		Mfilecount++;
	}

	/*
	 * Check for external pattern rule definitions.
	 */
	xpatrules = Patrules != NULL;
	/*
	 * The pattern rules which are defined in the external makefiles
	 * must superseede the pattern rules from the internal rules.
	 * Concat the pattern rules found in internal rules to the end of
	 * the patern rules list from external makefiles.
	 */
	*pattail = oPatrules;
	pattail = opattail;
}

/*
 * Setup special variables.
 *
 * NOTE: Must be reentrant because it may be called more than once
 *	 if the "include" directive is used.
 *	 As there is (currently) no way to delete an object
 *	 it is OK not to do anything special if objlook() returns NULL.
 */
EXPORT void
setup_dotvars()
{
	obj_t	*obj;
	list_t	*l;
	char	*name;

	obj = objlook(".OBJDIR", FALSE);
	if (obj != NULL && obj->o_type != ':')	/* Must be a special target */
		obj = NULL;

	if (obj != NULL) {
		if (obj->o_list && (ObjDir = obj->o_list->l_obj->o_name)) {
			if (gfileid(ObjDir) == gfileid(".")) {
				/*
				 * Do not allow moving targets to themselves.
				 */
				ObjDir = NULL;
			}
		}
	}
	/*
	 * Create special variable $O -> ObjDir
	 */
	define_var("O", ObjDir ? ObjDir : ".");

	obj = objlook(".OBJSEARCH", FALSE);
	if (obj != NULL && obj->o_type != ':')	/* Must be a special target */
		obj = NULL;
	if (obj != NULL) {
		if ((l = obj->o_list) != NULL) {
			name = l->l_obj->o_name;
			if (streql("src", name)) {
				ObjSearch = SSRC;
			} else if (streql("obj", name)) {
				ObjSearch = SOBJ;
			} else if (streql("all", name)) {
				ObjSearch = SALL;
			} else {
				/*
				 * This is the default.
				 */
				ObjSearch = SALL;
			}
		}
	}

	obj = objlook(".SEARCHLIST", FALSE);
	if (obj != NULL && obj->o_type != ':')	/* Must be a special target */
		obj = NULL;
	if (obj != NULL) {
		SearchList = obj->o_list;
	} else if ((obj = objlook("VPATH", FALSE)) != NULL && obj->o_type == '=') {
		SearchList = cvtvpath(obj->o_list);
	}

	if (objlook(".IGNORE", FALSE))
		Iflag = TRUE;
	if (objlook(".SILENT", FALSE))
		Sflag = TRUE;

	Init = objlook(".INIT", FALSE);
	Done = objlook(".DONE", FALSE);
	Failed = objlook(".FAILED", FALSE);
	IncludeFailed = objlook(".INCLUDE_FAILED", FALSE);
	if (IncludeFailed != NULL && IncludeFailed->o_cmd == NULL)
		IncludeFailed = NULL;
	Deflt = objlook(".DEFAULT", FALSE);
	Precious = objlook(".PRECIOUS", FALSE);

	if (objlook(".POSIX", FALSE))
		posixmode = TRUE;
	obj = objlook(".SUFFIXES", FALSE);
	if (obj != NULL && obj->o_type != ':')	/* Must be a special target */
		obj = NULL;
	if (obj != NULL)
		Suffixes = obj->o_list;
	if (Debug > 1 && Suffixes != (list_t *) NULL) {
		register list_t *p;

		error(".SUFFIXES :\t");
		for (p = Suffixes; p; p = p->l_next)
			error("%s ", p->l_obj->o_name);
		error("\n");
	}
	SSuffrules = check_ssufftab();
}

/*
 * Set up some known special macros.
 */
LOCAL void
setup_vars()
{
	define_var("$", "$");			/* Really needed ? */
	define_var("MAKE_NAME", "smake");	/* Needed to identify syntax */
	define_var("MAKE_VERSION", make_version);/* Version dependant files? */
}

/*
 * Set up the special macro $(MAKE).
 * If we were called with an absolute PATH or without any '/', use argv[0],
 * else compute the absolute PATH by prepending working dir to argv[0].
 */
LOCAL void
setup_MAKE(name)
	char	*name;
{
	char	wd[MAXPATHNAME + 1];
	int	len;

	/*
	 * If argv[0] starts with a slash or contains
	 * no slash, it is useful as $(MAKE).
	 */
	if (name[0] == SLASH || strchr(name, SLASH) == NULL) {
		define_var("MAKE", name);
	} else {
		/*
		 * Compute abs pathname for $(MAKE)
		 */
		strncpy(wd, curwdir(), sizeof(wd));
		wd[sizeof(wd)-1] = '\0';
		len = strlen(wd);
		if ((strlen(name) + len + 2) < sizeof(wd)) {
			strcat(wd, "/");
			strcat(wd, name);
		}
		define_var("MAKE", wd);
	}
}

/*
 * Transfer object search types into human readable names.
 */
EXPORT char *
searchtype(mode)
	int	mode;
{
	if (mode == SSRC)
		return ("src");
	if (mode == SOBJ)
		return ("obj");
	if (mode == SALL)
		return ("all");
	return ("invalid Object search mode");
}

/*
 * Print some 'smake' special macros:
 * .OBJDIR, .SEARCHLIST and .OBJSEARCH
 */
LOCAL void
printdirs()
{
	if (ObjDir != NULL)
		error(".OBJDIR :\t%s\n", ObjDir);

	error(".OBJSEARCH :\t%s\n", searchtype(ObjSearch));

	if (SearchList != (list_t *) NULL) {
		register list_t *p;
			error(".SEARCHLIST :\t");
		for (p = SearchList; p; p = p->l_next)
			error("%s ", p->l_obj->o_name);
		error("\n");
	}
}

/*
 * Add a command line macro to our list.
 * This is called by getargs().
 */
LOCAL int
addcommandline(name)
	char	*name;
{
	if (Debug > 1)
		error("got_it: %s\n", name);

/* UNIX make: ":;=$\n\t"	*/

	if (!strchr(name, '='))
		return (NOTAFILE);/* Tell getargs that this may be a flag */
	if (Cmdlinecount >= CMDLINECOUNT) {
		errmsgno(EX_BAD, "Too many Commandline Macros.\n");
		return (BADFLAG);
	}
	CmdLDefs[Cmdlinecount++] = name;
	return (1);
}

/*
 * Read in and parse all command line macro definitions from list.
 */
LOCAL void
read_cmdline()
{
	register int	i;

	MakeFileNames[Mfilecount] = CmdLMac;

	Mflags |= F_READONLY;
	for (i = 0; i < Cmdlinecount; i++) {
		readstring(CmdLDefs[i], CmdLMac);
		putenv(CmdLDefs[i]);
	}
	Mflags &= ~F_READONLY;
	Mfilecount++;
}

/*
 * Export a macro into the environment.
 * This is mainly done by the "export" directive inside a makefile.
 */
EXPORT void
doexport(oname)
	char	*oname;
{
	obj_t	*obj;
	list_t	*l;
	char	*name;
	int	len;

	obj = objlook(oname, FALSE);
	if (obj != NULL && obj->o_type != '=')	/* Must be a macro type target */
		obj = NULL;
	if (obj != NULL) {
		if ((l = obj->o_list) != NULL) {
			len = strlen(oname)+2;
			while (l && l->l_obj->o_name) {
				len += strlen(l->l_obj->o_name)+1;
				l = l->l_next;
			}
			name = malloc(len);
			if (name == NULL)
				comerr("Cannot alloc memory for env.\n");
			name[0] = '\0';
			l = obj->o_list;
			strcat(name, oname);
			strcat(name, "=");
			while (l && l->l_obj->o_name) {
				strcat(name, l->l_obj->o_name);
				strcat(name, " ");
				l = l->l_next;
			}
			putenv(name);
		}
	}
}

/*
 * Read in and parse all environment vars to make them make macros.
 */
LOCAL void
read_environ()
{
	register char	**env;
	extern	char	**environ;
	char *ev;
	char *p;

	Dmake -= 2;
	Mfilecount = 1;

/*	MakeFileNames[Mfilecount++] = Envdefs;*/

	if (Eflag)
		Mflags |= F_READONLY;
	mfname = Envdefs; 
	for (env = environ; *env; env++) {
		ev = *env;
		p = strchr(ev, EQUAL);
		if (p == NULL)
			continue;
		*p = '\0';
		define_var(ev, &p[1]);
		*p = EQUAL;
	}
	mfname = NULL; 
	Mflags &= ~F_READONLY;

	Dmake += 2;
}


EXPORT int
main(ac, av)
	int	ac;
	char	*av[];
{
	static	int	failures = 0;
		int	i;
		int	cac = ac;
		char	* const *cav = av;
	static	char	options[] = "help,version,posix,e,i,k,n,p,q,r,s,t,w,W,d+,D+,xM,xd+,probj,mf&,f&,&";

	save_args(ac, av);
getpid();
getpgrp();

#ifdef	_FASCII			/* Mark Williams C	*/
	stderr->_ff &= ~_FSTBUF;/* setbuf was called ???*/

	setup_env();
#endif
	getmakeflags();

	cac--; cav++;
	if (getallargs(&cac, &cav, options, &help, &pversion, &posixmode,
			&Eflag, &Iflag, &Kflag, &Nflag, &Print,
			&Qflag, &Rflag, &Sflag, &Tflag,
			&NoWarn, &DoWarn,
			&Debug, &Dmake, &Prdep, &XDebug, &Probj,
			addmakefile, NULL,
			addmakefile, NULL,
			addcommandline, NULL) < 0) {
		errmsgno(EX_BAD, "Bad flag: %s.\n", cav[0]);
		usage(EX_BAD);
	}
	if (help)
		usage(0);
	if (pversion) {
		printf("Smake release %s (%s-%s-%s) Copyright (C) 1985, 87, 88, 91, 1995-2001 Jörg Schilling\n",
				make_version,
				HOST_CPU, HOST_VENDOR, HOST_OS);
		exit(0);
	}
	setmakeflags();
	if (Qflag) {
		Sflag = TRUE;
		Nflag = TRUE;
	}
	if (Debug > 0)
		error("MAKEFLAGS value: '%s'\n", getenv(Makeflags));

	/*
	 * XXX Reihenfolge bei UNIX make beachten!!!
	 */
	if (signal(SIGINT, SIG_IGN) != SIG_IGN)
		signal(SIGINT, handler);
	if (signal(SIGQUIT, SIG_IGN) != SIG_IGN)
		signal(SIGQUIT, handler);
	if (signal(SIGHUP, SIG_IGN) != SIG_IGN)
		signal(SIGHUP, handler);
	if (signal(SIGTERM, SIG_IGN) != SIG_IGN)
		signal(SIGTERM, handler);
	curtime = gcurtime();
	newtime = gnewtime();

	initchars();
	initgbuf(NAMEMAX);
i = Mfilecount;
Mfilecount = 0;

	/*
	 * The functions read_cmdline() and read_makemacs() are setting
	 * the F_READONLY flag in all objects. The function read_environ()
	 * sets F_READONLY if the -e option was specified.
	 * This differs from the description in POSIX for 'make' but it
	 * is the only way to allow 'include' directives to work as expected.
	 * For the same reason, we are reading the macros in the opposite
	 * order as described in POSIX.
	 */
	read_cmdline();		/* First read cmd line args		*/
	read_makemacs();	/* then the inherited cmd line args	*/
Mfilecount = i;
	if (!Rflag)
		read_defs();
	setup_MAKE(av[0]);
	setup_vars();
	setup_arch();
	read_environ();		/* Sets F_READONLY if -e flag is present*/

	/*
	 * Clear default target, then look again in makefiles
	 */
	default_tgt = NULL;
	read_makefiles();

	/*
	 * Let all objects created later seem to bee in
	 * last Makefile or in implicit rules if no 
	 * Makefile is present.
	 */
	Mfilecount = Mfiles - 1;
	if (Mfilecount < 2)
		Mfilecount = 0;

	setup_dotvars();
	if (!Rflag)
		check_old_makefiles();

	if (Probj)		/* -probj Flag				*/
		printtree();
	if (Print) {		/* -p Flag				*/
		prtree();
		exit(0);	/* XXX Really exit() here for make -p -f /dev/null ??? */
				/* XXX Posix requires make -p -f /dev/null 2>/dev/null */
				/* XXX to print the internal macros	*/
	}
	if (Debug > 1)
		printdirs();	/* .OBJDIR .OBJSEARCH .SEARCHLIST	*/

	makeincs();		/* Re-make included files */
	omake(Init, TRUE);
	cac = ac;
	cav = av;
	cac--; cav++;
	for (i = 0; getfiles(&cac, &cav, options); cac--, cav++, i++)
		if (!domake(cav[0]))
			failures++;

	if (i == 0 && !domake((char *) NULL))
		failures++;
	if (failures && Failed) {
		omake(Failed, TRUE);
	} else {
		omake(Done, TRUE);
	}
#ifdef	DEBUG
	prmem();
#endif
	if (failures > 0)
		exit(1);
	exit(0);
	return (0);		/* keep lint happy :-) */
}

/*
 * Check for old makefile systems without patten matching rules.
 *
 * Old makefile systems only define simple suffix rules. Now that newer smake
 * releases support POSIX suffix rules, the makefile system will only work
 * if the makefile system uses pattern matchg rules.
 * We may remove this function in 2005.
 */
LOCAL void
check_old_makefiles()
{
	obj_t	*o;

	if (Suffixes == NULL)	/* No/Empty .SUFFIXES, no compat probelems */
		return;
	if (xssrules == 0)	/* Makefile did not define simple suff rule*/
		return;
	if (xpatrules)		/* New makefiles define pattern rules 	   */
		return;

	/*
	 * All makefiles from the Schily (SING) makefile system define
	 * _UNIQ=.XxZzy-
	 */
	if ((o = objlook("_UNIQ", FALSE)) == NULL)
		return;
	if (!streql(".XxZzy-", o->o_list->l_obj->o_name))
		return;
	
	errmsgno(EX_BAD, "Warning: this project uses an old version of the makefile system.\n");
	comerrno(EX_BAD, "Update the makefiles or call 'smake -r'.\n");
}

/*
 * Read in and parse the makeflags we got from the MAKEFLAGS= environment var.
 */
LOCAL void
getmakeflags()
{
	char	*mf = getenv(Makeflags);

	if (!mf || *mf == '\0')	/* No MAKEFLAGS= or empty MAKEFLAGS=	*/
		return;

	if (*mf != '-') {	/* Only macros if does not start with '-'*/
		char *p = nextmakemac(mf);

		/*
		 * Be gracious to non POSIX make programs like 'GNUmake' which
		 * may have "e -- MAKE=smake" in the MAKEFLAGS environment.
		 */
		if (p == NULL || strchr(mf, '=') < p) {
			MFCmdline = mf;
			goto out;	/* Allow debug prints */
		}
	}

	while (*mf) {
		switch (*mf) {

		case ' ':
			break;		/* Ignore blanks */

		case '-':		/* look for " -- " separator */
			if (mf[1] == '-') {
				if (mf[2] != ' ')
					return;
				MFCmdline = &mf[3];
				goto out;/* Allow debug prints */
			}
			break;		/* Ignore single '-' */

		case 'D':		/* Display makefile */
			Dmake++;
			break;

		case 'd':		/* Debug */
			Debug++;
			break;

		case 'X':		/* XDebug */
			XDebug++;
			break;

		case 'e':		/* Environment overrides vars */
			Eflag = TRUE;
			break;

		case 'i':		/* Ignore errors */
			Iflag = TRUE;
			break;

		case 'k':		/* Ignore errors  ???? */
			Kflag = TRUE;
			break;

		case 'n':		/* Do not exec any commands */
			Nflag = TRUE;
			break;

		case 'p':		/* Print macros/targets */
			Print = TRUE;
			break;

		case 'q':		/* Question */
			Qflag = TRUE;
			break;

		case 'r':		/* Turn off internal Rules */
			Rflag = TRUE;
			break;

		case 's':		/* Silent */
			Sflag = TRUE;
			break;

		case 't':		/* Touch */
			Tflag = TRUE;
			break;

		case 'W':		/* Extra Warnings */
			DoWarn = TRUE;
			break;

		case 'w':		/* No Warnings */
			NoWarn = TRUE;
			break;

		case 'Z':		/* Print includes */
			Prdep = TRUE;
			break;
		}
		mf++;
	}
out:
	if (Debug > 0)
		error("Read MAKEFLAGS:  '%s'\n", getenv(Makeflags));
}

/*
 * Parse a list of macro=value command line macros from the
 * MAKEFLAGS= environment and set up the macro in the make tree.
 */
LOCAL void
read_makemacs()
{
	register char	*mf = MFCmdline;
	register char	*p;

	if (mf == NULL)
		return;
	while (*mf) {
		p = nextmakemac(mf);
		if (p == NULL) {	/* No other macro def follows */
			read_mac(mf);
			return;
		} else {		/* Need to temporarily null terminate */
			*p = '\0';
			read_mac(mf);
			*p = ' ';
			mf = &p[1];
		}
	}
}

/*
 * Find next un-escaped blank (' ') which is a separator
 * for a list of macro=value items.
 */
LOCAL char *
nextmakemac(s)
	char	*s;
{
	while (*s) {
		if (*s == '\\') {	/* escaped character	*/
			if (*++s == '\0')
				return (NULL);
		} else if (*s == ' ') {	/* un-escaped space	*/
			return (s);
		}
		s++;
	}
	return (NULL);
}

/*
 * Remove the escapes that have been introduced before the name=value
 * lists are put together into the MAKEFLAGS= environment.
 * Then parse the result as a string.
 */
LOCAL void
read_mac(mf)
	char	*mf;
{
	char	macdef[NAMEMAX*2+1];
	char	*p;

	p = macdef;
	while (*mf) {
		if (p >= &macdef[NAMEMAX*2])
			break;
		/*
		 * Only remove those escape sequences, that we created.
		 * This is "\\" and "\ ".
		 */
		if (mf[0] == '\\' && (mf[1] == '\\' || mf[1] == ' '))
			mf++;
		*p++ = *mf++;
	}
	*p = '\0';
	Mflags |= F_READONLY;
	readstring(macdef, Envdefs);
	Mflags &= ~F_READONLY;
}

/*
 * Prepare the MAKEFLAGS= environment for export.
 */
LOCAL void
setmakeflags()
{
		/*
		 * MAKEFLAGS=-	12 bytes incl '\0'
		 * 3 x 8 bytes=	24 bytes
		 * 11 flags	11 bytes
		 * '-- '	 3 bytes
		 * =====================
		 *		50 bytes
		 */
#define	MAKEENV_SIZE_STATIC	64
static	char	makeenv[MAKEENV_SIZE_STATIC];
	char	*p;
	int	i;

	p = strcatl(makeenv, Makeflags, NULL);
	*p++ = '=';
	*p++ = '-';		/* Posix make includes '-'     */
				/* "MAKEFLAGS=-" 12 incl. '\0' */

	i = Dmake;		/* Display makefile */
	if (i > 8)
		i = 8;
	while (--i >= 0)
		*p++ = 'D';

	i = Debug;		/* Debug */
	if (i > 8)
		i = 8;
	while (--i >= 0)
		*p++ = 'd';

	i = XDebug;		/* XDebug */
	if (i > 8)
		i = 8;
	while (--i >= 0)
		*p++ = 'X';

	if (Eflag)		/* Environment overrides vars */
		*p++ = 'e';
	if (Iflag)		/* Ignore errors */
		*p++ = 'i';
	if (Kflag)		/* Ignore errors  ??? */
		*p++ = 'k';
	if (Nflag)		/* Do not exec any commands */
		*p++ = 'n';
	if (Print)		/* Print macros/targets */
		*p++ = 'p';
	if (Qflag)		/* Question */
		*p++ = 'q';
	if (Rflag)		/* Turn off internal Rules */
		*p++ = 'r';
	if (Sflag)		/* Silent */
		*p++ = 's';
	if (Tflag)		/* Touch */
		*p++ = 't';
	if (DoWarn)		/* Extra Warnings */
		*p++ = 'W';
	if (NoWarn)		/* No Warnings */
		*p++ = 'w';
	if (Prdep)		/* Print includes */
		*p++ = 'Z';

	if (p - makeenv == 11)	/* Empty flags, remove '-' */
		--p;
	*p = '\0';
	define_var(Make_Flags, &makeenv[10]);
	doexport(Make_Flags);
	setmakeenv(makeenv, p);
}

/*
 * Strip out macro defs inherited from MAKELAGS, that will be overwritten
 * by command line macro defs.
 * Return new write poiner at end of string.
 */
LOCAL char *
stripmacros(macbase, new)
	char	*macbase;
	char	*new;
{
	char	*p = strchr(new, '=');
	char	*p2;

	if (p == NULL)				/* Paranoia */
		return (macbase + strlen(macbase));

	do {
		p2 = nextmakemac(macbase);	/* Find next macro delim */

		if (strncmp(macbase, new, p - new) == 0) {
			/*
			 * Got a match, need to remove this entry.
			 */
			if (p2 == NULL) {	/* This is the only, zap out */
				*macbase = '\0';
			} else {		/* Copy rest over current */
				strcpy(macbase, &p2[1]);
			}
		} else if (p2) {		/* Continue with next extry */
			macbase = &p2[1];
		}
	} while (p2);
	return (macbase + strlen(macbase));
}

/*
 * Add the actual command line macro definitions to the MAKEFLAGS= string
 * and then putenv() the result.
 */
LOCAL void
setmakeenv(envbase, envp)
	char	*envbase;
	char	*envp;
{
	register int	i;
	register int	l;
	register int	len = 0;
	register char	*p;
	register char	*macbase;

	if (Cmdlinecount == 0 && (MFCmdline == 0 || *MFCmdline == '\0')) {
		/*
		 * No command line macros and no inherited command line
		 * macros from MAKEFLAGS, so just call putenv() and return.
		 */
		putenv(envbase);
		return;
	}

	if ((envp - envbase) > 10) {	/* envbase[] is currently not empty */
		strcpy(envp, " -- ");	/* we need a separator to the flags */

		envp += 4;
		*envp = '\0';
	}
	if (MFCmdline)			/* Add one for '\0' or ' ' at end */
		len = strlen(MFCmdline) + 1;

	for (i = 0; i < Cmdlinecount; i++) {
		p = CmdLDefs[i];
		while (*p) {
			if (*p == '\\' || *p == ' ')
				len++;
			len++;
			p++;
		}
		len += 1;		/* Add one for '\0' or ' ' at end */
	}

	l = strlen(envbase) + len + 1;	/* Add one (see stripmacro comment) */
	if (l > MAKEENV_SIZE_STATIC) {
		p = malloc(l);
		strcpy(p, envbase);
		envp = p + (envp - envbase);
		envbase = p;
	}

	macbase = envp;
	if (MFCmdline) {
		for (p=MFCmdline; *p;)
			*envp++ = *p++;
		*envp++ = ' ';
	}
	*envp = '\0';

	for (i = 0; i < Cmdlinecount; i++) {
		p = CmdLDefs[i];
		envp = stripmacros(macbase, p);
		while (*p) {
			if (*p == '\\' || *p == ' ')
				*envp++ = '\\';
			*envp++ = *p++;
		}
		*envp++ = ' ';
		*envp = '\0';	/* Needed for stripmacros */
	}			/* But overshoots by one  */
	*--envp = '\0';
	putenv(envbase);
	define_var(Make_Macs, macbase);
	doexport(Make_Macs);
}

#define	iswhite(c)	((c) == ' ' || (c) == '\t')

#if	defined(__linux__) || defined(__linux)
/*
 * Needed to handle the Linux bash signal bug.
 */
int	lpid;
#endif

/*
 * Execute or print a command line.
 * Return exit code from command line.
 */
EXPORT int
docmd(cmd, obj)
	register char	*cmd;
	obj_t		*obj;
{
	int	code;
	int	pid = 0;
	int	retries;
	int	Exit;
	int	Silent = Sflag;
	int	NoError = Iflag;
	int	NoExec = Nflag;
	BOOL	foundplus = FALSE;

	while (iswhite(*cmd))
		cmd++;
/*
 * '-' Ignore error, '@' Silent, '+' Always execute
 * '?' No command dependency checking, '!' Force command dependency checking
 */
	for (code = 0; code < 5 &&
	     (*cmd == '@' || *cmd == '-' || *cmd == '+' ||
			*cmd == '?' || *cmd == '!');
							code++, cmd++) {
		if (*cmd == '@')
			Silent = TRUE;
		if (*cmd == '-')
			NoError = TRUE;
		if (*cmd == '+') {
			NoExec = FALSE;
			foundplus = TRUE;
		}
		if (*cmd == '?') {
			;		/* XXX To be defined !!! */
		}
		if (*cmd == '!') {
			;		/* XXX To be defined !!! */
		}
	}
	if (foundplus)
		Silent = FALSE;

	if (!Silent || NoExec || Debug > 0) {
/*		error("...%s\n", cmd);*/
		printf("%s%s\n", posixmode?"\t":"...", cmd);	/* POSIX !!! */
	}
	if (NoExec && !found_make)
		return (0);

	curtarget = obj;
#if	defined(IS_UNIX) || defined(JOS)	/* XXX else system() ??? */
	/*
	 *  Do several tries to fork child to allow working on loaded systems.
	 */
	for (retries = 0; retries < 10; retries++) {
		pid = fork();
		if (pid >= 0)
			break;
		sleep(1L);		/* Wait for resources to become free.*/
	}
	if (pid < 0)
		comerr("Can't fork.\n");

	if (pid == 0) {		/* Child process: do the work. */
		/*
		 * We used to call /bin/sh -ce 'cmd' but we get problems on QNX
		 * and UNIX-98 requests that the command shall be called as in
		 * system() which means /bin/sh -c 'cmd'.
		 */
		execl("/bin/sh", "sh", "-c", cmd, 0);
		comerr("Can't exec /bin/sh.\n");
	}
#if	defined(__linux__) || defined(__linux)
	/*
	 * Needed to handle the Linux bash signal bug.
	 */
	lpid = pid;
#endif

	/* Parent process: wait for child. */
	if ((code = wait((WAIT_T *)&Exit)) != pid)
		comerrno(Exit, "code %d waiting for /bin/sh.\n", geterrno());
#else	/* IS_UNIX || JOS */
	Exit = system(cmd);
#endif
	curtarget = (obj_t *)NULL;
	if (Exit && Debug > 0)
		errmsgno(Exit>>8, "Code %d from command line.\n", Exit>>8);
	if (NoError)
		return (0);
	return (Exit);
}

#ifdef	tos
#		include "osbind.h"
#endif

/*
 * Move a target file to ObjDir.
 */
EXPORT BOOL
move_tgt(from)
	register obj_t	*from;
{
	date_t	fromtime;
	int	code;
	char	objname[NAMEMAX*2];

	/*
	 * Move only if:
	 *	objdir to corresponding srcdir exists
	 *	target is known in Makefile
	 */
	if ((ObjDir == NULL && from->o_level == OBJLEVEL) ||
						from->o_level < OBJLEVEL)
		return (TRUE);

	fromtime = gftime(from->o_name);
	if (fromtime == 0)		/* Nothing to move found */
		return (TRUE);

	if (strchr(from->o_name, SLASH))/* Only move from current directory */
		return (TRUE);

	if (Debug > 3) error("move: from->o_level: %d\n", from->o_level);
	if (!build_path(from->o_level, from->o_name, objname))
		return (FALSE);
	if (!Sflag || Nflag)
		error("...move %s %s\n", from->o_name, objname);
	if (Nflag)
		return (TRUE);

	if (gfileid(from->o_name) == gfileid(objname)) {
		errmsgno(EX_BAD, "Will not move '%s' to itself.\n",
							from->o_name);
		return (TRUE);
	}
#	ifdef	tos
	unlink(objname);
	if ((code = Frename(0, from->o_name, objname)) < 0) {
		if (code == EXDEV) {
			code = copy_file(from->o_name, objname);
			if (unlink(from->o_name) < 0)
				errmsg("Can't remove old name '%s'.\n",
								from->o_name);
		} else {
			errmsgno(-code, "Can't rename '%s' to '%s'.\n",
						from->o_name, objname);
		}
	}
	if (code < 0)
		return (FALSE);
#	else
#ifdef	HAVE_RENAME
	if ((code = rename(from->o_name, objname)) < 0) {
		if (geterrno() == EXDEV) {
			code = copy_file(from->o_name, objname);
		} else {
			errmsg("Can't rename '%s' to '%s'.\n",
						from->o_name, objname);
		}
	}
	if (code < 0)
		return (FALSE);
#else
	unlink(objname);
	if ((code = link(from->o_name, objname)) < 0) {
		if (geterrno() == EXDEV) {
			code = copy_file(from->o_name, objname);
		} else {
			errmsg("Can't add name '%s' to '%s'.\n",
						objname, from->o_name);
		}
	}
	if (code < 0)
		return (FALSE);
	if (unlink(from->o_name) < 0)
		errmsg("Can't remove old name '%s'.\n", from->o_name);
#endif	/* HAVE_RENAME */
#endif
	return (TRUE);
}

/*
 * Copy File if we cannot rename the file.
 */
#ifdef	tos
LOCAL int
copy_file(from, objname)
	char	*from;
	char	*objname;
{
	int	fin;
	int	fout;
	int	cnt = -1;

	if ((fin = open(from, 0)) < 0)
		errmsg("Can't open '%s'.\n", from);
	else {
		if ((fout = creat(objname, 0666)) < 0)
			errmsg("Can't create '%s'.\n", objname);
		else {
			while ((cnt = read(fin, gbuf, gbufsize)) > 0)
				if (write(fout, gbuf, cnt) != cnt) {
					errmsg("Write error on '%s'.\n",
								objname);
					cnt = -1;
					break;
				}
			close(fout);
		}
		close(fin);
	}
	return (cnt);
}
#else
LOCAL int
copy_file(from, objname)
	char	*from;
	char	*objname;
{
	FILE	*fin;
	FILE	*fout;
	int	cnt = -1;

	if ((fin = fileopen(from, "rub")) == 0)
		errmsg("Can't open '%s'.\n", from);
	else {
		if ((fout = fileopen(objname, "wtcub")) == 0)
			errmsg("Can't create '%s'.\n", objname);
		else {
			while ((cnt = fileread(fin, gbuf, gbufsize)) > 0)
				filewrite(fout, gbuf, cnt);
			fclose(fout);
		}
		fclose(fin);
	}
	return (cnt);
}
#endif

/*
 * This function behaves similar to the UNIX 'touch' command.
 */
EXPORT BOOL
touch_file(name)
	char	*name;
{
	FILE	*f;
	char	objname[NAMEMAX*2];
	char	c;

	sprintf(objname, "%s%c%s", ObjDir, SLASH, filename(name));
	if (!gftime(objname))
		sprintf(objname, name);
	if (!Sflag) error("...touch %s\n", objname);
	if (Nflag) return (TRUE);
	if ((f = fileopen(objname, "rwcub")) != (FILE *)NULL) {
		c = getc(f);
		fileseek(f, (off_t)0);
		putc(c, f);
		fclose(f);
		return (TRUE);
	}
	return (FALSE);
}

#	include <statdefs.h>
#	define	STATBUF		struct stat

/*
 * Get current time.
 */
LOCAL date_t
gcurtime()
{
	return ((date_t) time((time_t *) 0));
}

/*
 * Get a time that is in the future (as far as possible).
 */
LOCAL date_t
gnewtime()
{
	time_t	t = curtime;
	time_t	a = YEARSECS;
	int	i = 0;

	while ((a * 2) > a) {
		a *= 2;
		if (++i > 100)
			break;
	}
	i = 0;
	while (a > 0) {
		while ((t + a) > t) {
			t += a;
			if (++i > 100)
				break;
		}
		if (i > 1000)
			break;
		a /= 2;
	}
	while (t == NOTIME || t == BADTIME || t == RECURSETIME)
		t--;
/*printf("i: %d, %lu, %lx, %s\n", i, t, t, prtime(-3));*/
	return (t);
}

/*
 * Get the time of last modification for a file.
 * Cannot call it gmtime()
 */
EXPORT date_t
gftime(file)
	char	*file;
{
	STATBUF	stbuf;
	char	this_time[32];
	char	cur_time[32];

	stbuf.st_mtime = 0;
	if (stat(file, &stbuf) < 0) {
		/*
		 * GNU libc.6 destroys st_mtime
		 */
		stbuf.st_mtime = 0;
	}

	if (Debug > 3)
		error("gftime(%s) = %s\n", file, prtime(stbuf.st_mtime));

	if (stbuf.st_mtime > (curtime +5)) {
		date_t	xcurtime;

		xcurtime = gcurtime();
		if (stbuf.st_mtime <= (xcurtime +5)) {
			curtime = xcurtime;
			return (stbuf.st_mtime);
		}
		strncpy(this_time, prtime(stbuf.st_mtime), sizeof(this_time));
		this_time[sizeof(this_time)-1] = '\0';
		strncpy(cur_time, prtime(curtime), sizeof(cur_time));
		cur_time[sizeof(cur_time)-1] = '\0';
		errmsgno(EX_BAD,
			"Warning: '%s' has modification time in the future (%s > %s).\n",
			file, this_time, cur_time);
	}
	return (stbuf.st_mtime);
}

/*
 * Check if file is a directory.
 */
LOCAL BOOL
isdir(file)
	char	*file;
{
	STATBUF	stbuf;

	if (stat(file, &stbuf) < 0)
		return (TRUE);
	if ((stbuf.st_mode&S_IFMT) == S_IFDIR)
		return (TRUE);
	return (FALSE);
}

/*
 * Get a unique number for a file to prevent moving targets to themselves.
 * XXX inode number is now long !!!
 */
EXPORT long
gfileid(file)
	char	*file;
{
	STATBUF stbuf;
	long	result;

	/*
	 * Setup a unique default. In case stat() will fail.
	 */
	stbuf.st_ino = (short) (int) file;
	stbuf.st_dev = 0;
	if (stat(file, &stbuf) < 0) {
		/*
		 * GNU libc.6 destroys st_mtime
		 * Paranoia .... we fall back here too.
		 */
		stbuf.st_ino = (short) (int) file;
		stbuf.st_dev = 0;
	}
	result = (stbuf.st_dev << 16) | stbuf.st_ino;
	if (Debug > 3)
		error("gfileid: %s %ld\n", file, result);
	return (result);
}

/*
 * Transfer UNIX time stamps into human readable names.
 * Take care of our "special timestamps".
 */
EXPORT char *
prtime(date)
	date_t	date;
{
	char	*s;

	if (date == (date_t)0)
		return ("File does not exist");
	if (date == BADTIME)
		return ("File could not be made");
	if (date == RECURSETIME)
		return ("Recursive dependencies");
	if (date == newtime)
		return ("Younger than any file");

	s = ctime((const time_t *)&date);
	s[strlen(s)-1] = '\0';
	return (s);
}

/*
 * Our general signal handler. Does some needed clean up and includes
 * workarounds for buggy OS like Linux.
 */
LOCAL void
handler(signo)
	int	signo;
{
	char	*name;

	signal(signo, handler);
	errmsgno(EX_BAD, "Got signal %d\n", signo);
	if (!curtarget)
		goto out;

	errmsgno(EX_BAD, "Current target is: %s precious: %d\n",
			curtarget->o_name, isprecious(curtarget));

/*	while(wait(0) >= 0) */
/*		;*/
	/*
	 * Keine Bibliotheken
	 * Kein -t, -q etc.
	 */
	if (isprecious(curtarget))
		goto out;

	name = curtarget->o_name;

	if (isdir(name)) {
		error("*** %s not removed.\n", name);
		goto out;
	}
	if (unlink(name) >= 0) {
		error("*** %s removed.\n", name);
	} else {
		errmsg("*** %s could not be removed.\n", name);
	}
	/*
	 * Test ob ObjDir/name existiert und neuer als vorher ist.
	 */

out:

#if	defined(__linux__) || defined(__linux)
	/*
	 * Linux signal handling is broken. This is caused by a bug in 'bash'.
	 * Bash does jobcontrol even if called as "sh -c 'command'".
	 * This is illegal. Only the foregound (make) process and with some
	 * bash versions the descendant 'make' processes are killed.
	 * The following code tries to kill the others too.
	 */
	signal(signo, SIG_IGN);		/* Make us immune to death ;-)	*/

	/*
	 * First shoot everyone into the foot.
	 */
	kill(lpid, signo);		/* Kill bash that is our child	*/
	kill(-lpid, signo);		/* Kill possible bash children	*/
	kill(-getpgrp(), signo);	/* Kill our process group	*/

	/*
	 * Now shoot everyone into the head.
	 */
	kill(lpid, SIGKILL);		/* Kill bash that is our child	*/
	kill(-lpid, SIGKILL);		/* Kill possible bash children	*/
	kill(-getpgrp(), SIGKILL);	/* Kill our process group	*/
#endif
	exit(signo);
}

/*
 * Return current working directory in an allocated string.
 */
EXPORT	char *
curwdir()
{
	static	char	*wdir;
		char	wd[MAXPATHNAME + 1];

	if (wdir != NULL)
		return (wdir);

	if (getcwd(wd, MAXPATHNAME) == NULL) {
		wd[0] = '/';
		wd[1] = '\0';
	}
	wdir = malloc(strlen(wd)+1);
	if (wdir == NULL)
		comerr("Cannot malloc working dir.\n");
	strcpy(wdir, wd);
	return (wdir);
}

/*
 * Search for the defaults.smk file in the PATH of the user.
 * Assume that the file is ... bin/../lib/defaults.smk
 */
LOCAL char *
getdefaultsfile()
{
	char	*path = getenv("PATH");
	char	pbuf[NAMEMAX];
	char	*nbuf = pbuf;
	char	*np;
	char	*name = "lib/defaults.smk";

	if (path == NULL)
		return (NULL);

	for(;;) {
		np = nbuf;
		while (*path != ':' && *path != '\0'
		    && np < &nbuf[sizeof(pbuf)-sizeof(name)-1])
 				*np++ = *path++;
		*np = '\0';
		while (np > nbuf && np[-1] == '/')
			*--np= '\0';
		if (np >= &nbuf[4] && streql(&np[-4], "/bin"))
			np = &np[-4];
		*np++ = '/';
		*np   = '\0';
		strcpy(np, name);

		if (gftime(nbuf)) {
			np = malloc(strlen(nbuf)+1);
			if (np == NULL)
				return (NULL);
			strcpy(np, nbuf);
			return (np);
		}

		if (*path == '\0')
			break;
		path++;
	}
	return (NULL);
}

#ifndef	HAVE_PUTENV

EXPORT	int	putenv		__PR((const char *new));
LOCAL	int	ev_find		__PR((const char *s));

extern	char 	**environ;	/* The environment array		*/
LOCAL	BOOL	ealloc = FALSE;	/* TRUE if environ is already allocated */

/*
 * Our local putenv implementation for systems that don't have it.
 */
EXPORT int
putenv(new)
	const char	*new;
{
	char 		**newenv;
	register int	idx;

	if ((idx = ev_find(new)) >= 0) {
		/*
		 * An old entry with the same name exists, replace it.
		 */
		environ[idx] = (char *)new;
	} else {
		/*
		 * If idx is < 0, we need to expand environ for the new entry.
		 * In this case -idx is the inverted size of the old environ.
		 */
		idx = -idx + 1;		/* Add space for new entry */
		if (ealloc) {
			/*
			 * environ is allocated, expand with realloc
			 */
			newenv = (char **)realloc(environ, idx*sizeof(char *));
			if (newenv == NULL)
				return (-1);
		} else {
			/*
			 * environ is orig space, copy to malloc'ed space
			 */
			ealloc = TRUE;
			newenv = (char **)malloc(idx*sizeof(char *));
			if (newenv == NULL)
				return (-1);
			(void)movebytes((char *)environ, (char *)newenv,
 						(int)(idx*sizeof(char *)));
		}
		environ = newenv;
		environ[idx-2] = (char *)new;
		environ[idx-1] = NULL;
	}
	return (0);
}

/*
 * Check if arg of form name=value is part of environ.
 * Return index on success and -environ_size if not.
 */
LOCAL int
ev_find(s)
	register const char	*s;
{
	register int		i = 0;
	register const char	*ep;
	register const char	*s2;

	for (i=0; environ[i] != NULL; i++) {
		/*
		 * Find string in environment entry.
		 */
		for (ep = environ[i], s2 = s; *ep == *s2++; ep++) {
			if (*ep == '=')
				return (i);
		}
	}
	return (-(++i));
}
#endif	/* HAVE_PUTENV */
