/*
 * File: search.c
 * Auth: Eric Harlow
 */
#include <gtk/gtk.h>
#include "notepad.h"
#include "dialog.h"
#include <string.h>

#include <locale.h>
#include <libintl.h>
#define _(STRING) gettext(STRING)


int LookForString (gchar *szHaystack, const gchar *find_string, int nStart);


/*
 * FindFunction
 *
 * Looks for the string in the notepad.
 */
gboolean FindFunction (const gchar *find_string, gpointer data)
{
	int nIndex;
	GtkWidget *text = GetTextWidget ();
	char *szHaystack;   

	/* --- Get the text from the widget --- */
	szHaystack = GetText ();

	/* --- Get cursor position --- */
	nIndex = GTK_EDITABLE (text)->selection_end_pos;

	/* --- Find the string --- */
	nIndex = LookForString (szHaystack, find_string, nIndex);

	if(nIndex >= 0)
	{
		/* --- Move the cursor to a position --- */
		gtk_text_set_point (GTK_TEXT (text), nIndex);

		/* --- These two lines will force the widget to --- */
		/*     scroll to the position where the text is. --- */
		gtk_text_insert (GTK_TEXT (text), NULL, NULL, NULL, " ", 1);
		gtk_text_backward_delete (GTK_TEXT (text), 1);

		/* --- Select the field found. --- */
		gtk_editable_select_region (GTK_EDITABLE (text), 
									nIndex, nIndex + strlen (find_string));

	}
	else
	{
		ShowMessage (_("Find..."), _("Not found.  Reached the end of the file."));
	}

	/* --- Release memory. --- */
	g_free (szHaystack);

	return TRUE;
}



/*
 * LookForString
 *
 * Search for a string (find_string) in a larger 
 * string (szHaystack) starting at a given position (nStart)
 * in the large string.
 *
 * This is referred to as the brute force algorithm.
 */
int LookForString (gchar *szHaystack, const gchar *find_string, int nStart)
{
	int nHaystackLength;
	int nNeedleLength;
	int nPos;

	/* --- Get the length of the strings. --- */
	nHaystackLength = strlen (szHaystack);
	nNeedleLength = strlen (find_string);

	/* --- Check each string --- */
	for(nPos = nStart; nPos < nHaystackLength; nPos++)
	{
		/* --- Did we find it here? --- */
		if(strncmp (&szHaystack[nPos], find_string, nNeedleLength) == 0)
		{
			/* --- yes, return index --- */
			return(nPos);
		}
	}

	/* Didn't find string, return -1 --- */
	return(-1);
}






/*
 * menu_Find
 * 
 * Find a string in the editor
 */
void menu_Find (GtkWidget *widget, gpointer data)
{
	FindStringDialog (_("Find text:"), FindFunction, data);
}
