
#include <stdio.h>

#define BUFSIZE 1024
#define NODESIZE (BUFSIZE*10)

struct node {
	struct node *next;
	char buf[NODESIZE];
}

main(argc, argv)
int argc;
char **argv;
{
	char stash[BUFSIZE];
	int n, f, lsize;
	struct node *head, *last, *malloc();

	head = last = malloc(sizeof (struct node));
	head->next = NULL;
	lsize = 0;

	while ((n = read(0, stash, BUFSIZE)) > 0) {
		if (lsize+n > NODESIZE) {
			int t = NODESIZE - lsize;
			strncpy(&last->buf[lsize], stash, t);
			if ((last->next = malloc(sizeof(struct node))) == NULL) {
				printf("stash: not enough memory\n");
				exit(1);
			}
			last = last->next;
			strncpy(last->buf, &stash[t], n-t);
			lsize = n-t;
		} else {
			strncpy(&last->buf[lsize], stash, n);
			lsize += n;
		}
	}
	if (argc < 2)
		f = 1;
	else if ((f = creat(argv[1], 0666)) < 0) {
		perror(argv[1]);
		exit (1);
	}
	for (; head->next != NULL; head = head->next)
		write(f, head->buf, NODESIZE);
	write(f, head->buf, lsize);
	exit (0);
}

