
/*
 * Copyright (C) 1990 by Jay Konigsberg. mail: jak@sactoh0
 *
 * Permission to use, copy, modify, and distribute this  software  and  its
 * documentation is hereby  granted,  provided  that  the  above  copyright
 * notice appear in all copies  and that  both  the  copyright  notice  and
 * this permission notice appear in supporting documentation. This software
 * is provided "as is" without express or implied  warranty.  However,  the
 * author retains all Copyright priviliges and rights  to  renumeration  if
 * this software is sold.
 */

/*
 * savefile - save the text buffer to a file.
 */

#include "simped.h"

void savefile(editfile, newfile, fd, text, count)
char	*editfile;
int	*newfile;
FILE	*fd;
char	**text;
int	count;
{
FILE	*fopen();

int	fclose(),
	fprintf(),
	printf(),
	fputs(),
	puts(),
	unlink(),
	cleanup();

char	*getline();

int	textinx,		/* index for the text buffer */
	text_entered=0,		/* was something entered */
	ch=0;			/* characters read in */

char	buffer[LINELEN+2];	/* buffer for filename entry */

puts("");
if (! editfile)
    {
    for(;;)
	{
	fputs("\nPlease enter a filename: ", stdout);
	if (getline(buffer, &text_entered, stdin, '\0', TRUE))
	    {
	    puts("Too many characters.");
	    return;
	    }
	if( ! text_entered ) /* a return by itself was entered */
	    return;
	buffer[strlen(buffer)-1]='\0';
	editfile = buffer;
	if ( (fd=fopen(editfile, "r")) == NULL)
	    {
	    break;
	    }
	printf("%s: file exists! return to exit.\n", editfile);
	}
    fclose(fd);
    if( (fd=fopen(editfile, "w")) == NULL )
	{
	fprintf(stderr,"Can't open %s, probably an illegal filename",editfile);
	return;
	}
    }

if ( ! *newfile )
    {
    fclose(fd);
    if( (fd=fopen(editfile, "w")) == NULL )
	{
	fprintf(stderr,"fopen for write failed.\n");
	cleanup(2);
	}
    }
else
    {
    rewind(fd);
    }
for (textinx=0; textinx < count; ++textinx)
    {
    ch += strlen(text[textinx]);
    fputs(text[textinx], fd);
    }
if (ch > 0)
    {
    printf("\n%s: written, %d lines, %d characters\n", editfile, count, ch);
    }
else
    {
    if ( unlink(editfile) == -1 )
	{
	fprintf(stderr,"unlink failed: error=%d", errno);
	}
    else
	{
	puts("Empty file - no action");
	}
    }
cleanup(0);
}
