/*
  common.c
  Ruby/GSL: Ruby extension library for GSL (GNU Scientific Library)
    (C) Copyright 2001-2004 by Yoshiki Tsunesada

  Ruby/GSL is free software: you can redistribute it and/or modify it
  under the terms of the GNU General Public License.
  This library is distributed in the hope that it will be useful, but
  WITHOUT ANY WARRANTY.
*/

#include "rb_gsl_array.h"
#include "rb_gsl_histogram.h"
#include <string.h>

FILE* rb_gsl_open_writefile(VALUE io, int *flag)
{
  OpenFile *fptr = NULL;
  FILE *fp = NULL;
  switch (TYPE(io)) {
  case T_STRING:
    fp = fopen(RSTRING(io)->ptr, "w");
    if (fp == NULL) rb_raise(rb_eIOError, "Cannot open file %s\n", STR2CSTR(io));
    *flag = 1;
    break;
  case T_FILE:
    GetOpenFile(io, fptr);
    rb_io_check_writable(fptr);
    fp = GetWriteFile(fptr);
    *flag = 0;
    break;
  default:
    rb_raise(rb_eTypeError, "argv 1 String or File expected");
  }
  return fp;
}

FILE* rb_gsl_open_readfile(VALUE io, int *flag)
{
  OpenFile *fptr = NULL;
  FILE *fp = NULL;
  switch (TYPE(io)) {
  case T_STRING:
    fp = fopen(RSTRING(io)->ptr, "r");
    if (fp == NULL) rb_raise(rb_eIOError, "Cannot open file %s\n", STR2CSTR(io));
    *flag = 1;
    break;
  case T_FILE:
    GetOpenFile(io, fptr);
    rb_io_check_readable(fptr);
    fp = fptr->f;
    *flag = 0;
    break;
  default:
    rb_raise(rb_eTypeError, "argv 1 String or File expected");
  }
  return fp;
}


VALUE rb_gsl_obj_read_only(int argc, VALUE *argv, VALUE obj)
{
  rb_raise(rb_eRuntimeError, "Read only object");
}

int str_tail_grep(char *s0, char *s1)
{
  int len0, len1;
  char *p = NULL;
  len0 = strlen(s0);
  len1 = strlen(s1);
  p = s0 + len0 - len1;
  return strcmp(p, s1);
}

