/*
 * binit.c
 *	Initialize contents of a block file
 *
 * Puts blanks with "\ <spaces> $USER" on first line of each block.
 */
#include <std.h>
#include <stdio.h>
#include <string.h>
#include "defs.h"

static char buf1[BLKCOLS], buf2[BLKCOLS], *name;
static FILE *fp;

/*
 * put_block()
 *	Write out a single Forth block
 */
static void
put_block(void)
{
	int x, y;

	/*
	 * Write out the source block range and its shadow
	 */
	for (x = 0; x < SCRBLK; ++x) {
		(void)fwrite(buf1, sizeof(buf1), 1, fp);
		for (y = 0; y < BLKROWS-1; ++y) {
			(void)fwrite(buf2, sizeof(buf2), 1, fp);
		}
	}

	/*
	 * Blank out trailing bytes
	 */
	for (x = 0; x < BLKRESID; ++x) {
		(void)fputc(' ', fp);
	}
}

int
main(int argc, char **argv)
{
	int x, count;

	/*
	 * Get filename and number of blocks
	 */
	if (argc != 3) {
		fprintf(stderr, "Usage is: %s <file> <blocks>\n", argv[0]);
		exit(1);
	}
	if ((fp = fopen(argv[1], "r+")) == NULL) {
		perror(argv[1]);
		exit(1);
	}
	count = atoi(argv[2]);
	if (count < 1) {
		fprintf(stderr, "Bad count: %s\n", argv[2]);
		exit(1);
	}

	/*
	 * Get name of user, for tagging blocksw
	 */
	name = getenv("USER");
	if (!name) {
		name = getenv("LOGNAME");
		if (!name) {
			fprintf(stderr, "Please set $USER\n");
			exit(1);
		}
	}

	/*
	 * Fill buffers with spaces
	 */
	for (x = 0; x < sizeof(buf1); ++x) {
		buf1[x] = buf2[x] = ' ';
	}

	/*
	 * Put signature in first line
	 */
	buf1[0] = '\\';
	bcopy(name, buf1 + (BLKCOLS-11), strlen(name));

	/*
	 * Put out Forth blocks for the required count
	 */
	for (x = 0; x < count; ++x) {
		put_block();
	}

	fclose(fp);
	return(0);
}
