/*  filo -- manipulate a `rolodex'-like database
 *  Copyright (C) 1994 David Deaven, Jennifer Corkill
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program; if not, write to the Free Software
 *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 * $Id: scan.c,v 1.2 1995/10/26 19:25:28 deaven Exp $
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "dmd/memory.h"
#include "filo.h"

/* Each of these functions returns a newly-allocated string
 * containing the relevant part of the address, or NULL if
 * it isn't there.
 */

static char *buffer;
static int bp, buffersize = 0;

static void copytobuffer(char *s, int start, int end)
{
	int new = bp + end - start + 1;
	if(new > buffersize) {
	  buffersize = new;
	  buffer = myrealloc(buffer, buffersize * sizeof(char));
	}
	while(start <= end) buffer[bp++] = s[start++];
}

/* The address is just all of the non-comment lines.
 */
char *scan_address(char *s)
{
	int e;
	bp = 0;

	while(*s != '\0')
	{
	  switch(*s) {
	    case '#':
	    case '%':
	      while(*s != '\0' && *s != '\n') ++s;
	    case '\n':
	      break;
	    default:
	      for(e = 0; s[e] != '\0' && s[e] != '\n'; ++e);
	      copytobuffer(s, 0, e);
	      s += e;
	      break;
	  }
	  if(*s == '\0') break;
	  ++s;
	}
	buffer[bp] = '\0';

	return mystrdup(buffer);
}

/* Scan for a `keyword = XXX' or `keyword: XXX' kind of field
 * within a comment line.
 */
char *scan_keyword(char *s, char *keyword)
{
	char c, *r;
	int e;
	while((s = strstr(s, keyword)) != NULL)
	{
	  s += strlen(keyword);

	  /* Check if we are in a comment line.
	   */
	  for(r = s; *r != '\n' && *r != '\0'; --r);
	  while(isspace(r[1])) ++r;
	  if(r[1] != '%' && r[1] != '#') continue;

	  while(*s != '\0' && *s != '\n' && *s != '=' && *s != ':') ++s;
	  if(*s == '\0' || *s == '\n') continue;
	  ++s;

	  while(isspace(*s) && *s != '\n') ++s;
	  if(*s == '\n') continue;

	  for(e = 0; s[e] != '\0' && s[e] != '\n'; ++e);
	  c = s[e]; s[e] = '\0';
	  r = mystrdup(s);
	  s[e] = c;
	  return r;
	}
	return NULL;
}
