/* search.c - search backwards or forwards
 */

#include <string.h>
#include <ctype.h>
#include "mstring.h"
#include "terminal.h"
#include "viewfile.h"


/* [/] - prompt for a string to search for, and search for it.
 */
void rf_search(rf_data_t data)
{
	char found = 0;
	long lines = 0;
	char *p;
	char *q;
	int a;

	rf_wipe_footer(data);

	do {
		a = t_input("Search : ", data->search_buf,
			    sizeof(data->search_buf) - 1);
	} while (a == 1);

	rf_wipe_footer(data);
	rf_footer(data);

	if (data->search_buf[0] == 0)
		return;

	while ((data->ldb_entry->current_line < data->num_lines)
	       && (!found)) {

		rf_read_line(data, data->ldb_entry->current_line);
		mstripattr(data->linebuf);

		if (data->line_pos[data->ldb_entry->current_line].type
		    == MFILE_LINE_FROM) {
			if (data->flags & MENU_STATUS_ANONYMOUS) {
				p = strrchr(data->linebuf, '(');
				if (p)
					*p = 0;	/* preserve anonymity */
			}
		}

		data->ldb_entry->current_line++;
		lines++;

		if ((lines % 10) == 0)
			t_bored(1);

		p = data->linebuf;

		do {
			q = p;
			p = strchr(q, tolower(data->search_buf[0]));
			if (!p)
				p = strchr(q,
					   toupper(data->search_buf[0]));
			if (p) {
				if (strncasecmp
				    (p, data->search_buf,
				     strlen(data->search_buf)) == 0)
					found = 1;
				else
					p++;
			}
		} while ((p) && (!found));

	}

	t_bored(0);

	if (lines < t_rows) {
		data->ldb_entry->current_line -= lines;
		rf_scroll_forward(data, lines);
	} else {
		rf_redraw_screen(data);
	}
}


/* [\] - prompt for a string to search for, and search for it backwards.
 */
void rf_search_backwards(rf_data_t data)
{
	char found = 0;
	long lines = 0;
	char *p;
	char *q;
	int a;

	rf_wipe_footer(data);

	do {
		a = t_input("Search backwards : ", data->search_buf,
			    sizeof(data->search_buf) - 1);
	} while (a == 1);

	rf_wipe_footer(data);
	rf_footer(data);

	if (data->search_buf[0] == 0)
		return;

	while ((data->ldb_entry->current_line > 0) && (!found)) {
		data->ldb_entry->current_line--;
		lines++;

		rf_read_line(data, data->ldb_entry->current_line - 1);
		mstripattr(data->linebuf);

		if (data->line_pos[data->ldb_entry->current_line - 1].type
		    == MFILE_LINE_FROM) {
			if (data->flags & MENU_STATUS_ANONYMOUS) {
				p = strrchr(data->linebuf, '(');
				if (p)
					*p = 0;	/* preserve anonymity */
			}
		}

		if ((lines % 10) == 0)
			t_bored(1);

		p = data->linebuf;

		do {
			q = p;
			p = strchr(q, tolower(data->search_buf[0]));
			if (!p)
				p = strchr(q,
					   toupper(data->search_buf[0]));
			if (p) {
				if (strncasecmp
				    (p, data->search_buf,
				     strlen(data->search_buf)) == 0)
					found = 1;
				else
					p++;
			}
		} while ((p) && (!found));

	}

	t_bored(0);

	if (data->ldb_entry->current_line < 0)
		data->ldb_entry->current_line = 0;

	if (lines < t_rows) {
		data->ldb_entry->current_line += lines;
		rf_scroll_back(data, lines);
	} else {
		rf_redraw_screen(data);
	}
}

/* EOF */
