/*
 * machdep_bsd.c
 *
 * BSD dependencies
 *
 * In here, we do command line parsing, getting time of day, and
 * other things that BSD is nice for.
 *
 */

#include <stdio.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/file.h>
#include "X/box.h"
#include "defs.h"

machdep_init(argc, argv)
	int	argc;
	char	**argv;
{
	extern	FILE *rootfile();
	extern	char *rindex();
	extern	char *progname;
	extern	int interactive;
	extern	int sweeps;
	extern	char fileroot[];
	extern	char loadfile[];
	extern	char onlyfile[];
	extern	char cmdfile[];
	extern	int extract;
	extern	int testall;
	extern	int only;
	extern	int *onlys;
	extern	int numtotal;
	extern	int dispout;
	extern	long seed;
	extern	FILE *cmdfp;
	extern	FILE *onlyfp;
	extern	FILE *loadfp;
	extern	int no_cmd;
	extern	int ndtokens;
	extern	int box;
	extern	int disphid;
	extern	int array;
	char	*bp;
	register int i;
	int	nread;

	progname = argv[0];
	if ((bp = rindex(argv[0], '/')) != 0)
		progname = bp+1;
	time(&seed);
	argvec(argc, argv);
	srandom(seed);
	exp_init();
	if (argc == 1 || fileroot[0] == 0)
		interactive++;
	if (testall > 0 && sweeps == 0 && fileroot[0] != 0)
		sweeps = -1;
	if (sweeps == 0 && extract == 0)
		interactive++;
	/*
	 * save the command (but we need a fileroot for this)
	 */
	if (no_cmd == 0 && fileroot[0]) {
		cmdfp = rootfile(cmdfile, "cmd", "a");
		for (i = 1; i < argc; i++)
			fprintf(cmdfp, "%s ", argv[i]);
		fprintf(cmdfp, "\n");
		fflush(cmdfp);
	}
	/*
	 * if we have a fileroot, set up our filenames and configure
	 * the network; otherwise, we'll have to wait until we're
	 * in the command loop.  setup() does a lot of stuff and calls
	 * a number of other routines.
	 */
	if (fileroot[0] != 0)
		setup(fileroot);
	if ((testall > 0) && (sweeps == -1))
		sweeps = ndtokens;
	/*
	 * open up box stream (must follow setup())
	 */
	if (box) {
		if (dispout == 1) {
			box_create(BOX_OUT);
		} else if (disphid == 1) {
			box_create(BOX_HID);
		}
	}
	/*
	 * if a loadfile is specified read it in
	 */
	if (loadfile[0] != 0) {
		if (array == 0)
			loadweights1(loadfile);
		if (array == 1)
			loadweights2(loadfile);
	}
	if (only == 1) {
		if (array != 1){
			perror("ERROR: .only requires -a");
			exit(1);
		}
		onlyfp = rootfile(onlyfile, "only", "r");
		nread = 0;
		for (i = 0; i < numtotal; i++){
			nread += fscanf(onlyfp, "%d", (onlys+i));
		}
		if (nread != numtotal)
			inputerr(onlyfile, "only data");
	}
	sigsetup();
}
