/* 
 * Ming/Ruby
 * $Id: util.c,v 1.4 2002/06/11 17:49:54 daisu-ik Exp $
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2.1 of the License, or (at your option) any later version.
 *
 *  This library 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
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include <string.h>
#include <ctype.h>
#include "ruby.h"
#include <ming.h>
#include "ming_ruby.h"

int safe_tolower(c)
	 int c;
{
  if(isupper(c))
	return tolower(c);
  else
	return(c);
}

int strncmp_ignore_case(s1, s2, n)
	 const char *s1, *s2;
	 size_t n;
{
  int c1, c2, result = 0;
  size_t i;

  for(i = 0; i < n; i++) {
	if (s1[i] == '\0') {
	  if (s2[i] == '\0') {
		result = 0;
		break;
	  } else {
		result = -1;
		break;
	  }
	} else if (s2[i] == '\0') {
	  result = 1;
	  break;
	}

	c1 = safe_tolower(s1[i]);
	c2 = safe_tolower(s2[i]);

	if (c1 > c2) {
	  result = 1;
	  break;
	} else if (c1 < c2){
	  result = -1;
	  break;
	}
  }

  return result;
}

FILE *search_file(path, name, mode)
	 VALUE path;
	 char *name, *mode;
{
  VALUE item;
  char *dir, delimiter[] = "/", *filename;
  size_t i, len, dir_len, total_len;
  FILE *fp = NULL;

  len = strlen(name);

  fp = fopen(name, mode);
  if (fp != NULL)
	return fp;
  
  for(i = 0; i < RARRAY(path)->len; i++) {
	item = RARRAY(path)->ptr[i];
	dir = STR2CSTR(item);
	dir_len = RSTRING(item)->len;

	if(strncmp(&dir[dir_len - 1], delimiter, 1) != 0) {
	  total_len = dir_len + len + 2;
	  filename = ALLOC_N(char, dir_len + len + 2);
	  snprintf(filename, total_len, "%s%s%s", dir, delimiter, name);
	} else {
	  total_len = dir_len + len + 1;
	  filename = ALLOC_N(char, total_len);
	  snprintf(filename, total_len, "%s%s", dir, name);
	}

	fp = fopen(filename, mode);

	if (fp != NULL)
	  return fp;
  }

  return fp;
}

int init_references(table)
     struct References *table;
{
  table->size = 0;
  table->item = NULL;

  return 0;
}

int regist_references(table, src)
     struct References *table;
     VALUE src;
{
  unsigned long n;

  n = table->size;

  if(n == 0) {
    table->item = ALLOC(VALUE);
  } else {
    REALLOC_N(table->item, VALUE, n + 1);
  }

  table->item[n] = src;
  table->size++;

  return 0;
}
	 
int mark_references(table)
     struct References *table;
{
  unsigned long i;
  VALUE *p = table->item;

  for(i = 0; i < table->size; i++){ 
    rb_gc_mark(*p);
    p++;
  }

  return 0;
}
