/* --------------------
	vmail -- find.c

	Searching titles for strings.

	Copyright (C) J. Zobel, University of Melbourne, October 1987.
-------------------- */

#include "defs.h"

static char str[LEN] = "^.*";

/* --------------------
	Get string for searching, either forwards (forwards = true) or backwards
	(forwards = false).  Then scan mail headers using regex().
-------------------- */
void
search(forwards)
	int		forwards;
{
	char	s1[LEN], *s2, *re_comp();
	int		i;
	bool	found = false;
	folder	f;
	item	m;

	get_string((forwards) ? "/" : "?", s1);
	if((i = strlen(s1)) > 0) {
			/* new search string */
		strcpy(str+3, s1);
		str[i+=3] = '.', str[++i] = '*', str[++i] = '\0';
	} else if(strlen(str+3) == 0) {
		addstatus("", false);
		return;
	}
	if((s2 = re_comp(str)) != (char *) NULL) {
		addstatus(s2, false);
		return;
	}
	addstatus("searching ...", false);
	if(forwards)
		for(i=y+1, f=curflr, m=curmail->next ; ! found && m != curmail ; ) {
			if(m == (item) NULL) {
				f = f->next; NEXT_VALID(f);
				if(f == (folder) NULL) {
					f = folders;
					NEXT_VALID(f);
				}
				m = f->mail;
				i = FIRST;
			}
			if(! (found = re_exec(m->title)))
				m = m->next, i++;
		}
	else
		for(i=y-1, f=curflr, m=curmail->prev ; ! found && m != curmail ; ) {
			if(m == (item) NULL) {
				f = f->prev; PREV_VALID(f);
				if(f == (folder) NULL) {
						/* find last folder */
					for(f=folders ; f->next != (folder) NULL ; f=f->next)
						;
					PREV_VALID(f);
				}
					/* find last mail item with count */
				for(i=FIRST, m=f->mail ; m->next != (item) NULL ; i++,m=m->next)
					;
			}
			if(! (found = re_exec(m->title)))
				m = m->prev, i--;
		}
	curmail = m, y = i;
	if(f != curflr) {
		curflr = f;
		display_page();
	} else if(! found)	/* come back to current folder (known to be valid) */
		addstatus("pattern not found", true);
	else
		addstatus("", false);
}
