/* copy.c - copy entry or screen to a file
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <ctype.h>
#include "terminal.h"
#include "viewfile.h"

extern int menuview_abort;


#define RF_COPY_PROMPT	"[\035BE\035b]:Entry  " \
			"[\035BS\035b]:Screen  " \
			"[\035BQ\035b]:Quit"
#define RF_COPYOVR_PROMPT	"File Exists.  "\
			"[\035BO\035b]:Overwrite  "\
			"[\035BA\035b]:Append  "\
			"[\035BQ\035b]:Quit"


/* Copy an entry or the current screen to the editing file from the current
 * file.
 */
void rf_entry_copy(rf_data_t data)
{
	char buf[512];
	FILE *fptr;
	char *dir;
	long s, e;
	char *m;
	char *a;
	int c;

	dir = getenv("MVIEW_DIR");
	if (!dir) {
		dir = getenv("MVIEW_EDIT_TMP");
		if (!dir) {		    /* no fixed editing file */
			rf_wipe_footer(data);
			t_goto(0, t_rows - 1);
			t_centre("\035R *** MVIEW_DIR not set *** \035r");
			sleep(1);
			rf_wipe_footer(data);
			rf_footer(data);
			return;
		}
		strncpy(buf, dir, 511);
		buf[511] = 0;
	} else {
		strncpy(buf, dir, 500);
		buf[500] = 0;
		strcat(buf, "/edit");
	}

	rf_redraw = 1;

	do {
		if (rf_redraw) {
			rf_wipe_footer(data);
			t_goto(0, t_rows - 1);
			t_centre(RF_COPY_PROMPT);
			rf_redraw = 0;
		}
		c = toupper(t_getchar(1));
		if (menuview_abort)
			c = 'Q';
		if (c == 12)
			rf_redraw = 1;
	} while ((c != 'E') && (c != 'S') && (c != 'Q'));

	s = -1;
	e = 0;

	switch (c) {
	case 'E':
		s = data->ldb_entry->current_line;
		c = rf_scan_entries(data, &s, "[\035BY\035b]:Copy  "
				    "[\035BQ\035b]:Quit", "Y", 0, 0);
		if (c == 'Q')
			s = -1;

		if (s >= 0) {
			for (e = s + 1; (e < data->num_lines)
			     && (data->line_pos[e].type !=
				 MFILE_LINE_DATESTAMP); e++);
		}
		break;
	case 'S':
		e = data->ldb_entry->current_line;
		s = e - (t_rows - 1);
		if (s < 0)
			s = 0;
		if (e < 0)
			e = 0;
		break;
	default:
		break;
	}

	m = "w";

	if (s >= 0) {
		fptr = fopen(buf, "r");
		if (fptr) {
			fclose(fptr);
			rf_redraw = 1;

			do {
				if (rf_redraw) {
					rf_wipe_footer(data);
					t_goto(0, t_rows - 1);
					t_centre(RF_COPYOVR_PROMPT);
					rf_redraw = 0;
				}
				c = toupper(t_getchar(1));
				if (c == 12)
					rf_redraw = 1;
			} while ((c != 'O') && (c != 'A') && (c != 'Q'));

			if (c == 'Q')
				m = 0;
			else if (c == 'O')
				m = "w";
			else if (c == 'A')
				m = "a";
		}

		if ((m) && (fptr = fopen(buf, m))) {
			while (s < e) {
				rf_read_line(data, s);
				if ((data->flags & MENU_STATUS_ANONYMOUS)
				    && (data->line_pos[s].type ==
					MFILE_LINE_FROM)) {
					a = strrchr(data->linebuf, '(');
					if (a)
						*a = 0;
				}
				fprintf(fptr, "%s\n", data->linebuf);
				s++;
			}
			fclose(fptr);
		}
	}

	rf_wipe_footer(data);
	rf_footer(data);
}

/* EOF */
