/**********************************************************************
 * ti library's routine for doing a general search
 *
 * $Author: brlewis $
 * $Source: /mit/techinfodev/src/libti/RCS/search.c,v $
 * $Header: /mit/techinfodev/src/libti/RCS/search.c,v 3.3 1995/04/10 20:21:57 brlewis Exp $
 *
 * Copyright 1993 by the Massachusetts Institute of Technology.
 *
 * For copying and distribution information, please see the file
 * <mit-copyright.h>.
 **********************************************************************/

#include <mit-copyright.h>

#ifndef lint
static char rcsid_ti_search_c[] = "$Header: /mit/techinfodev/src/libti/RCS/search.c,v 3.3 1995/04/10 20:21:57 brlewis Exp $";
#endif /* lint */

#include <errno.h>
#include <string.h>
#include <ctype.h>
#include <ti/memory.h>
#include <ti/ti.h>

/**********************************************************************
 * ti_search(TI *tp, ti_menu **mp, char *title,
 *           char *search_data, long search_top, ti_trn_t search_type)
 *	caller should have opened tp
 *	search_type should be one of TI_TFIND, TI_TCHGD_SINCE,
 *		TI_TFULL_TXTI_TSEARCH, TI_TSOURCE_SRCH
 *
 * - searches from node "top" for matches of "keyword"
 * - creates menu with "title" given
 * - returns error code
 **********************************************************************/

long
ti_search(
	  TI *tp,
	  ti_menu **mp,
	  char *title,
	  char *search_data,
	  long search_top,
	  ti_trn_t search_type)
{
  char newquery[1024];

  /* initialize new menu */
  TI_MEM(*mp = New(ti_menu));
  memset(*mp, 0, sizeof(ti_menu));

  /* form query */
  if (search_type == TI_TCHGD_SINCE)
    sprintf(newquery, "%c:%ld:%s", (char)search_type, search_top,
	    ti_date_convert(search_data));
  else
    {
      if (search_top) sprintf(newquery, "%c:%.1000s:%d", (char)search_type,
		       search_data, search_top);
      else sprintf(newquery, "%c:%.1000s", (char)search_type, search_data);
    }
  TI_MEM((*mp)->query = newstring(newquery)); /* XXX small leak */
  strcpy((*mp)->query, newquery);

  /* insert title */
  TI_MEM((*mp)->title = newstring(title)); /* XXX */
  strcpy((*mp)->title, title);

  /* success */
  (*mp)->type = TI_MSCH;
  tp->links++;
  (*mp)->tp=tp;
  return(0L);
}

char *
ti_date_convert(date)
     char *date;
{
  static char retval[64];
  register char *tmp1, *tmp2;

  for(tmp1= date, tmp2= retval;
      *tmp1;
      tmp1++, tmp2++)
    {
      if (!isdigit(*tmp1)) *tmp2 = ':';
      else *tmp2 = *tmp1;
    }
  *tmp2 = '\0';
  return(retval);
}
