/*
  vector.c
  Ruby/GSL: Ruby extension library for GSL (GNU Scientific Library)
    (C) Copyright 2001-2004 by Yoshiki Tsunesada
        Modified by Seiya Nishizawa        14/Apr/2004

  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_complex.h"
#ifdef HAVE_NARRAY_H
#include "rb_gsl_with_narray.h"
#endif

static VALUE rb_gsl_vector_inner_product(int argc, VALUE *argv, VALUE obj);
static VALUE rb_gsl_vector_product_to_m(int argc, VALUE *argv, VALUE obj);

VALUE rb_ary_to_gv(VALUE klass, VALUE ary);

VALUE rb_gsl_vector_new(int argc, VALUE *argv, VALUE klass)
{
  gsl_vector *v = NULL, *vtmp = NULL;
  size_t n;
  int i, beg, en;
#ifdef HAVE_NARRAY_H
  VALUE ary2;
#endif
  switch (argc) {
  case 1:
#ifdef HAVE_NARRAY_H
    if (NA_IsNArray(argv[0])) {
      n = NA_TOTAL(argv[0]);
      v = gsl_vector_alloc(n);
      if (v == NULL) rb_raise(rb_eNoMemError, "gsl_vector_alloc failed");
      ary2 = na_change_type(argv[0], NA_DFLOAT);
      memcpy(v->data, NA_PTR_TYPE(ary2,double*), n*sizeof(double));
      return Data_Wrap_Struct(cgsl_vector, 0, gsl_vector_free, v);
    }
#endif
    switch (TYPE(argv[0])) {
    case T_FIXNUM:
      CHECK_FIXNUM(argv[0]);
      n = FIX2INT(argv[0]);
      v = gsl_vector_calloc(n);
      if (v == NULL) rb_raise(rb_eNoMemError, "gsl_vector_alloc failed");
      break;
    case T_BIGNUM:
      rb_raise(rb_eRangeError, "vector index is limited within the range of Fixnum.");
      break;
    case T_FLOAT:
      v = gsl_vector_alloc(1);
      gsl_vector_set(v, 0, NUM2DBL(argv[0]));
      break;
    case T_ARRAY: 
      v = make_cvector_from_rarrays(argv[0]);
      break;
    default:
      if (CLASS_OF(argv[0]) == rb_cRange) {
	beg = NUM2INT(rb_ivar_get(argv[0], rb_gsl_id_beg));
	en = NUM2INT(rb_ivar_get(argv[0], rb_gsl_id_end));
	if (RTEST(rb_ivar_get(argv[0], rb_gsl_id_excl)))
	  n = en - beg;
	else
	  n = en - beg + 1;
	v = gsl_vector_alloc(n);
	for (i = 0; i < n; i++) gsl_vector_set(v, i, beg + i);
	return Data_Wrap_Struct(cgsl_vector, 0, gsl_vector_free, v);
      } else if (VECTOR_P(argv[0])) {
	Data_Get_Struct(argv[0], gsl_vector, vtmp);
	v = gsl_vector_alloc(vtmp->size);
	for (i = 0; i < vtmp->size; i++) 
	  gsl_vector_set(v, i, gsl_vector_get(vtmp, i));
	return Data_Wrap_Struct(CLASS_OF(argv[0]), 0, gsl_vector_free, v);
      } else {
	rb_raise(rb_eTypeError, 
		 "wrong argument type %s", rb_class2name(CLASS_OF(argv[0])));
      }
      break;
    }
    break;
  default:
    v = gsl_vector_alloc(argc);
    if (v == NULL) rb_raise(rb_eNoMemError, "gsl_vector_alloc failed");
    for (i = 0; i < argc; i++) {
      Need_Float(argv[i]);
      gsl_vector_set(v, i, NUM2DBL(argv[i]));
    }
    break;
  }
  return Data_Wrap_Struct(klass, 0, gsl_vector_free, v);
}

static VALUE rb_gsl_vector_calloc(VALUE klass, VALUE nn)
{
  gsl_vector *v = NULL;
  CHECK_FIXNUM(nn);
  v = gsl_vector_calloc(FIX2INT(nn));
  if (v == NULL) rb_raise(rb_eNoMemError, "gsl_vector_calloc failed");
  return Data_Wrap_Struct(klass, 0, gsl_vector_free, v);
}

static VALUE rb_gsl_vector_size(VALUE obj)
{
  gsl_vector *v = NULL;
  Data_Get_Struct(obj, gsl_vector, v);
  return INT2FIX(v->size);
}

static VALUE rb_gsl_vector_stride(VALUE obj)
{
  gsl_vector *v = NULL;
  Data_Get_Struct(obj, gsl_vector, v);
  return INT2FIX(v->stride);
}

static VALUE rb_gsl_vector_set_stride(VALUE obj, VALUE s)
{
  gsl_vector *v = NULL;
  CHECK_FIXNUM(s);
  Data_Get_Struct(obj, gsl_vector, v);
  v->stride = FIX2INT(s);
  return obj;
}

static VALUE rb_gsl_vector_owner(VALUE obj)
{
  gsl_vector *v = NULL;
  Data_Get_Struct(obj, gsl_vector, v);
  return INT2FIX(v->owner);
}

static VALUE rb_gsl_vector_get(VALUE obj, VALUE ii)
{
  gsl_vector *v = NULL;
  CHECK_FIXNUM(ii);
  Data_Get_Struct(obj, gsl_vector, v);
  return rb_float_new(gsl_vector_get(v, FIX2INT(ii)));
}

static VALUE rb_gsl_vector_set(VALUE obj, VALUE ii, VALUE xx)
{
  gsl_vector *v = NULL;
  Data_Get_Struct(obj, gsl_vector, v);
  gsl_vector_set(v, FIX2INT(ii), NUM2DBL(xx));
  return obj;
}

static VALUE rb_gsl_vector_set_all(VALUE obj, VALUE xx)
{
  gsl_vector *v = NULL;
  Need_Float(xx);
  Data_Get_Struct(obj, gsl_vector, v);
  gsl_vector_set_all(v, NUM2DBL(xx));
  return obj;
}

static VALUE rb_gsl_vector_set_zero(VALUE obj)
{
  gsl_vector *v = NULL;
  Data_Get_Struct(obj, gsl_vector, v);
  gsl_vector_set_zero(v);
  return obj;
}

static VALUE rb_gsl_vector_set_basis(VALUE obj, VALUE ii)
{
  gsl_vector *v = NULL;
  CHECK_FIXNUM(ii);
  Data_Get_Struct(obj, gsl_vector, v);
  gsl_vector_set_basis(v, FIX2INT(ii));
  return obj;
}

static VALUE rb_gsl_vector_each(VALUE obj)
{
  gsl_vector *v = NULL;
  int i;
  Data_Get_Struct(obj, gsl_vector, v);
  for (i = 0; i < v->size; i++) {
    rb_yield(rb_float_new(gsl_vector_get(v, i)));
  }
  return obj;
}

static VALUE rb_gsl_vector_each_index(VALUE obj)
{
  gsl_vector *v = NULL;
  int i;
  Data_Get_Struct(obj, gsl_vector, v);
  for (i = 0; i < v->size; i++) rb_yield(INT2FIX(i));
  return obj;
}

static VALUE rb_gsl_vector_print(VALUE obj)
{
  gsl_vector *v = NULL;
  int i;
  Data_Get_Struct(obj, gsl_vector, v);
  printf("[ ");
  if (VECTOR_COL_P(obj)) {
    for (i = 0; i < v->size; i++) {
      if (i == 0) printf("%4.3e ", gsl_vector_get(v, i));
      else printf("  %4.3e ", gsl_vector_get(v, i));
      if (i != v->size-1) printf("\n");
    }
  } else {
    for (i = 0; i < v->size; i++) printf("%4.3e ", gsl_vector_get(v, i));
  }
  printf("]\n");
  return obj;
}

static VALUE rb_gsl_vector_subvector(int argc, VALUE *argv, VALUE obj)
{
  gsl_vector *v = NULL;
  gsl_vector_view *vv = NULL;
  size_t offset, n;
  Data_Get_Struct(obj, gsl_vector, v);
  switch (argc) {
  case 0:
    offset = 0;
    n = v->size;
    break;
  case 1:
    CHECK_FIXNUM(argv[0]);
    offset = 0;
    n = FIX2INT(argv[0]);
    break;
  case 2:
    CHECK_FIXNUM(argv[0]);
    CHECK_FIXNUM(argv[1]);
    offset = FIX2INT(argv[0]);
    n = FIX2INT(argv[1]);
    break;
  default:
    rb_raise(rb_eArgError, "wrong number of arguments (%d for 0, 1 or 2)", argc);
    break;
  }
  vv = gsl_vector_view_alloc();
  *vv = gsl_vector_subvector(v, offset, n);
  if (VECTOR_COL_P(obj))
    return Data_Wrap_Struct(cgsl_vector_col_view, 0, gsl_vector_view_free, vv);
  else
    return Data_Wrap_Struct(cgsl_vector_view, 0, gsl_vector_view_free, vv);
}

static VALUE rb_gsl_vector_subvector_with_stride(VALUE obj, VALUE o, VALUE s, VALUE nn)
{
  gsl_vector *v = NULL;
  gsl_vector_view *vv = NULL;
  size_t offset, stride, n;
  CHECK_FIXNUM(o);
  CHECK_FIXNUM(s);
  CHECK_FIXNUM(nn);
  offset = FIX2INT(o);
  stride = FIX2INT(s);
  n = FIX2INT(nn);
  Data_Get_Struct(obj, gsl_vector, v);
  vv = gsl_vector_view_alloc();
  *vv = gsl_vector_subvector_with_stride(v, offset, stride, n);
  if (VECTOR_COL_P(obj))
      return Data_Wrap_Struct(cgsl_vector_col_view, 0, gsl_vector_view_free, vv);
  else
    return Data_Wrap_Struct(cgsl_vector_view, 0, gsl_vector_view_free, vv);
}

static VALUE rb_gsl_vector_to_a(VALUE obj)
{
  gsl_vector *v = NULL;
  int i;
  VALUE ary;
  Data_Get_Struct(obj, gsl_vector, v);
  ary = rb_ary_new2(v->size);
  for (i = 0; i < v->size; i++) {
    rb_ary_store(ary, i, rb_float_new(gsl_vector_get(v, i)));
  }
  return ary;
}

/* module function */
static VALUE rb_gsl_vector_memcpy(VALUE obj, VALUE dest, VALUE src)
{
  gsl_vector *vdest = NULL, *vsrc = NULL;
  CHECK_VECTOR(dest);
  CHECK_VECTOR(src);
  Data_Get_Struct(dest, gsl_vector, vdest);
  Data_Get_Struct(src, gsl_vector, vsrc);
  gsl_vector_memcpy(vdest, vsrc);
  return dest;
}

/* method */
static VALUE rb_gsl_vector_clone(VALUE obj)
{
  gsl_vector *v = NULL, *vnew = NULL;
  Data_Get_Struct(obj, gsl_vector, v);
  vnew = gsl_vector_alloc(v->size);
  if (vnew == NULL) rb_raise(rb_eNoMemError, "gsl_vector_alloc failed");
  gsl_vector_memcpy(vnew, v);
  if (VECTOR_ROW_P(obj))
    return Data_Wrap_Struct(cgsl_vector, 0, gsl_vector_free, vnew);
  else
    return Data_Wrap_Struct(cgsl_vector_col, 0, gsl_vector_free, vnew);
}

/* module function */
static VALUE rb_gsl_vector_swap(VALUE obj, VALUE vv, VALUE ww)
{
  gsl_vector *v = NULL, *w = NULL;
  CHECK_VECTOR(vv);
  CHECK_VECTOR(ww);
  Data_Get_Struct(vv, gsl_vector, v);
  Data_Get_Struct(ww, gsl_vector, w);
  gsl_vector_swap(w, v);
  return obj;
}

static VALUE rb_gsl_vector_swap_elements(VALUE obj, VALUE i, VALUE j)
{
  gsl_vector *v = NULL;
  CHECK_FIXNUM(i);
  CHECK_FIXNUM(j);
  Data_Get_Struct(obj, gsl_vector, v);
  gsl_vector_swap_elements(v, FIX2INT(i), FIX2INT(j));
  return obj;
}

static VALUE rb_gsl_vector_reverse(VALUE obj)
{
  gsl_vector *v = NULL;
  Data_Get_Struct(obj, gsl_vector, v);
  gsl_vector_reverse(v);
  return obj;
}

static VALUE rb_gsl_vector_reverse2(VALUE obj)
{
  gsl_vector *v = NULL, *vnew = NULL;
  Data_Get_Struct(obj, gsl_vector, v);
  vnew = gsl_vector_alloc(v->size);
  if (vnew == NULL) rb_raise(rb_eNoMemError, "gsl_vector_alloc failed");
  gsl_vector_memcpy(vnew, v);
  gsl_vector_reverse(vnew);
  if (VECTOR_ROW_P(obj)) 
    return Data_Wrap_Struct(cgsl_vector, 0, gsl_vector_free, vnew);
  else
    return Data_Wrap_Struct(cgsl_vector_col, 0, gsl_vector_free, vnew);
}

enum {
  GSL_VECTOR_ADD,
  GSL_VECTOR_ADD2,
  GSL_VECTOR_SUB,
  GSL_VECTOR_SUB2,
  GSL_VECTOR_MUL,
  GSL_VECTOR_MUL2,
  GSL_VECTOR_DIV,
  GSL_VECTOR_DIV2,
};

static VALUE rb_gsl_vector_arithmetics(int flag, VALUE obj, VALUE bb) 
{
  gsl_vector *v = NULL, *vnew = NULL, *b = NULL;
  gsl_vector_complex *cvnew = NULL, *cb = NULL;
  gsl_complex *c = NULL;
  Data_Get_Struct(obj, gsl_vector, v);
  switch (TYPE(bb)) {
  case T_FLOAT:
  case T_FIXNUM:
  case T_BIGNUM:
    switch (flag) {
    case GSL_VECTOR_ADD:
      vnew = make_vector_clone(v);
      gsl_vector_add_constant(vnew, NUM2DBL(bb));
      break;
    case GSL_VECTOR_ADD2:
      gsl_vector_add_constant(v, NUM2DBL(bb));
      return obj;
      break;
    case GSL_VECTOR_SUB:
      vnew = make_vector_clone(v);
      gsl_vector_add_constant(vnew, -NUM2DBL(bb));
      break;
    case GSL_VECTOR_SUB2:
      gsl_vector_add_constant(v, -NUM2DBL(bb));
      return obj;
      break;
    case GSL_VECTOR_MUL:
      vnew = make_vector_clone(v);
      gsl_vector_scale(vnew, NUM2DBL(bb));
      break;
    case GSL_VECTOR_MUL2:
      gsl_vector_scale(v, NUM2DBL(bb));
      return obj;
      break;
    case GSL_VECTOR_DIV:
      vnew = make_vector_clone(v);
      gsl_vector_scale(vnew, 1.0/NUM2DBL(bb));
      break;
    case GSL_VECTOR_DIV2:
      gsl_vector_scale(v, 1.0/NUM2DBL(bb));
      return obj;
      break;
    }
    return Data_Wrap_Struct(VECTOR_ROW_COL(obj), 0, gsl_vector_free, vnew);
    break;
  default:
    if (VECTOR_P(bb)) {
      Data_Get_Struct(bb, gsl_vector, b);
      switch (flag) {
      case GSL_VECTOR_ADD:
	vnew = make_vector_clone(v);
	gsl_vector_add(vnew, b);
	break;
      case GSL_VECTOR_ADD2:
	gsl_vector_add(v, b);
	return obj;
	break;
      case GSL_VECTOR_SUB:
	vnew = make_vector_clone(v);
	gsl_vector_sub(vnew, b);
	break;
      case GSL_VECTOR_SUB2:
	gsl_vector_sub(v, b);
	return obj;
	break;
      case GSL_VECTOR_MUL:
	vnew = make_vector_clone(v);
	gsl_vector_mul(vnew, b);
	break;
      case GSL_VECTOR_MUL2:
	gsl_vector_mul(v, b);
	return obj;
	break;
      case GSL_VECTOR_DIV:
	vnew = make_vector_clone(v);
	gsl_vector_div(vnew, b);
	break;
      case GSL_VECTOR_DIV2:
	gsl_vector_div(v, b);
	return obj;
	break;
      }
      return Data_Wrap_Struct(VECTOR_ROW_COL(obj), 0, gsl_vector_free, vnew);
    } else if (VECTOR_COMPLEX_P(bb)) {
      Data_Get_Struct(bb, gsl_vector_complex, cb);
      cvnew = vector_to_complex(v);
      switch (flag) {
      case GSL_VECTOR_ADD:
      case GSL_VECTOR_ADD2:
	gsl_vector_complex_add(cvnew, cb);
	break;
      case GSL_VECTOR_SUB:
      case GSL_VECTOR_SUB2:
	gsl_vector_complex_sub(cvnew, cb);
	break;
      case GSL_VECTOR_MUL:
      case GSL_VECTOR_MUL2:
	gsl_vector_complex_mul(cvnew, cb);
	break;
      case GSL_VECTOR_DIV:
      case GSL_VECTOR_DIV2:
	gsl_vector_complex_div(cvnew, cb);
	break;
      }
      if (VECTOR_ROW_P(obj))
	return Data_Wrap_Struct(cgsl_vector_complex, 0, gsl_vector_complex_free, cvnew);
      else
	return Data_Wrap_Struct(cgsl_vector_complex_col, 0, gsl_vector_complex_free, cvnew);
    } else if (COMPLEX_P(bb)) {
      Data_Get_Struct(bb, gsl_complex, c);
      cvnew = vector_to_complex(v);
      switch (flag) {
      case GSL_VECTOR_ADD:
      case GSL_VECTOR_ADD2:
	gsl_vector_complex_add_constant(cvnew, *c);
	break;
      case GSL_VECTOR_SUB:
      case GSL_VECTOR_SUB2:
	gsl_vector_complex_add_constant(cvnew, gsl_complex_negative(*c));
	break;
      case GSL_VECTOR_MUL:
      case GSL_VECTOR_MUL2:
	gsl_vector_complex_scale(cvnew, *c);
	break;
      case GSL_VECTOR_DIV:
      case GSL_VECTOR_DIV2:
	gsl_vector_complex_scale(cvnew, gsl_complex_inverse(*c));
	break;
      }
      if (VECTOR_ROW_P(obj)) 
	return Data_Wrap_Struct(cgsl_vector_complex, 0, gsl_vector_complex_free, cvnew);
      else
	return Data_Wrap_Struct(cgsl_vector_complex_col, 0, gsl_vector_complex_free, cvnew);
    } else {
      rb_raise(rb_eTypeError, "wrong type argument %s", rb_class2name(CLASS_OF(bb)));
    }
    break;
  }
  /* never reach here */
  return Qnil;
}

static VALUE rb_gsl_vector_add(VALUE obj, VALUE b)
{
  return rb_gsl_vector_arithmetics(GSL_VECTOR_ADD, obj, b);
}

static VALUE rb_gsl_vector_add2(VALUE obj, VALUE b)
{
  return rb_gsl_vector_arithmetics(GSL_VECTOR_ADD2, obj, b);
}

static VALUE rb_gsl_vector_sub(VALUE obj, VALUE b)
{
  return rb_gsl_vector_arithmetics(GSL_VECTOR_SUB, obj, b);
}

static VALUE rb_gsl_vector_sub2(VALUE obj, VALUE b)
{
  return rb_gsl_vector_arithmetics(GSL_VECTOR_SUB2, obj, b);
}

static VALUE rb_gsl_vector_mul(VALUE obj, VALUE b)
{
  VALUE argv[2];
  if (VECTOR_ROW_P(obj) && VECTOR_COL_P(b)) {
    argv[0] = obj;
    argv[1] = b;
    return rb_gsl_vector_inner_product(2, argv, CLASS_OF(obj));
  }
  if (VECTOR_COL_P(obj) && VECTOR_ROW_P(b)) {
    argv[0] = obj;
    argv[1] = b;
    return rb_gsl_vector_product_to_m(2, argv, CLASS_OF(obj));
  }
  return rb_gsl_vector_arithmetics(GSL_VECTOR_MUL, obj, b);
}

static VALUE rb_gsl_vector_mul2(VALUE obj, VALUE b)
{
  return rb_gsl_vector_arithmetics(GSL_VECTOR_MUL2, obj, b);
}

static VALUE rb_gsl_vector_div(VALUE obj, VALUE b)
{
  return rb_gsl_vector_arithmetics(GSL_VECTOR_DIV, obj, b);
}

static VALUE rb_gsl_vector_div2(VALUE obj, VALUE b)
{
  return rb_gsl_vector_arithmetics(GSL_VECTOR_DIV2, obj, b);
}

static VALUE rb_gsl_vector_scale(VALUE obj, VALUE x)
{
  return rb_gsl_vector_arithmetics(GSL_VECTOR_MUL, obj, x);
}

static VALUE rb_gsl_vector_scale2(VALUE obj, VALUE x)
{
  return rb_gsl_vector_arithmetics(GSL_VECTOR_MUL2, obj, x);
}

static VALUE rb_gsl_vector_add_constant(VALUE obj, VALUE x)
{
  return rb_gsl_vector_arithmetics(GSL_VECTOR_ADD, obj, x);
}

static VALUE rb_gsl_vector_add_constant2(VALUE obj, VALUE x)
{
  return rb_gsl_vector_arithmetics(GSL_VECTOR_ADD2, obj, x);
}

static VALUE rb_gsl_vector_max(VALUE obj)
{
  gsl_vector *v = NULL;
  Data_Get_Struct(obj, gsl_vector, v);
  return rb_float_new(gsl_vector_max(v));
}

static VALUE rb_gsl_vector_min(VALUE obj)
{
  gsl_vector *v = NULL;
  Data_Get_Struct(obj, gsl_vector, v);
  return rb_float_new(gsl_vector_min(v));
}

static VALUE rb_gsl_vector_minmax(VALUE obj)
{
  gsl_vector *v = NULL;
  double min, max;
  Data_Get_Struct(obj, gsl_vector, v);
  gsl_vector_minmax(v, &min, &max);
  return rb_ary_new3(2, rb_float_new(min), rb_float_new(max));
}

static VALUE rb_gsl_vector_max_index(VALUE obj)
{
  gsl_vector *v = NULL;
  Data_Get_Struct(obj, gsl_vector, v);
  return INT2FIX(gsl_vector_max_index(v));
}

static VALUE rb_gsl_vector_min_index(VALUE obj)
{
  gsl_vector *v = NULL;
  Data_Get_Struct(obj, gsl_vector, v);
  return INT2FIX(gsl_vector_min_index(v));
}

static VALUE rb_gsl_vector_minmax_index(VALUE obj)
{
  gsl_vector *v = NULL;
  size_t imin, imax;
  Data_Get_Struct(obj, gsl_vector, v);
  gsl_vector_minmax_index(v, &imin, &imax);
  return rb_ary_new3(2, INT2FIX(imin), INT2FIX(imax));
}

static VALUE rb_gsl_vector_isnull(VALUE obj)
{
  gsl_vector *v = NULL;
  Data_Get_Struct(obj, gsl_vector, v);
  return INT2FIX(gsl_vector_isnull(v));
}

static VALUE rb_gsl_vector_isnull2(VALUE obj)
{
  gsl_vector *v = NULL;
  Data_Get_Struct(obj, gsl_vector, v);
  if (gsl_vector_isnull(v)) return Qtrue;
  else return Qfalse;
}

VALUE rb_ary_to_gv0(VALUE ary)
{
  gsl_vector *v = NULL;
  int i;
  size_t size;
  size = RARRAY(ary)->len;
  v = gsl_vector_alloc(size);
  if (v == NULL) rb_raise(rb_eNoMemError, "gsl_vector_alloc failed");
  for (i = 0; i < size; i++) {
    gsl_vector_set(v, i, NUM2DBL(rb_ary_entry(ary, i)));
  }
  return Data_Wrap_Struct(cgsl_vector, 0, gsl_vector_free, v);
}

VALUE rb_ary_to_gv(VALUE klass, VALUE ary)
{
  gsl_vector *v = NULL;
  int i;
  size_t size;
  size = RARRAY(ary)->len;
  v = gsl_vector_alloc(size);
  if (v == NULL) rb_raise(rb_eNoMemError, "gsl_vector_alloc failed");
  for (i = 0; i < size; i++) {
    gsl_vector_set(v, i, NUM2DBL(rb_ary_entry(ary, i)));
  }
  return Data_Wrap_Struct(cgsl_vector, 0, gsl_vector_free, v);
}

VALUE rb_gsl_range_to_gv(VALUE obj)
{
  int beg, en, n, i;
  gsl_vector *v = NULL;
  beg = NUM2INT(rb_ivar_get(obj, rb_gsl_id_beg));
  en = NUM2INT(rb_ivar_get(obj, rb_gsl_id_end));
  if (RTEST(rb_ivar_get(obj, rb_gsl_id_excl)))
    n = en - beg;
  else
    n = en - beg + 1;
  v = gsl_vector_alloc(n);
  for (i = 0; i < n; i++) gsl_vector_set(v, i, beg + i);
  return Data_Wrap_Struct(cgsl_vector, 0, gsl_vector_free, v);
}

static VALUE rb_gsl_vector_fwrite(VALUE obj, VALUE io)
{
  gsl_vector *h = NULL;
  FILE *f = NULL;
  int status, flag = 0;
  Data_Get_Struct(obj, gsl_vector, h);
  f = rb_gsl_open_writefile(io, &flag);
  status = gsl_vector_fwrite(f, h);
  if (flag == 1) fclose(f);
  return INT2FIX(status);
}

static VALUE rb_gsl_vector_fread(VALUE obj, VALUE io)
{
  gsl_vector *h = NULL;
  FILE *f = NULL;
  int status, flag = 0;
  Data_Get_Struct(obj, gsl_vector, h);
  f = rb_gsl_open_readfile(io, &flag);
  status = gsl_vector_fread(f, h);
  if (flag == 1) fclose(f);
  return INT2FIX(status);
}

static VALUE rb_gsl_vector_fprintf(int argc, VALUE *argv, VALUE obj)
{
  gsl_vector *h = NULL;
  FILE *fp = NULL;
  int status, flag = 0;
  if (argc != 1 && argc != 2) {
    rb_raise(rb_eArgError, "wrong number of arguments (%d for 1 or 2)", argc);
  }
  Data_Get_Struct(obj, gsl_vector, h);
  fp = rb_gsl_open_writefile(argv[0], &flag);
  if (argc == 2) {
    if (TYPE(argv[1]) == T_STRING)
      status = gsl_vector_fprintf(fp, h, STR2CSTR(argv[1]));
    else
      rb_raise(rb_eTypeError, "argv 2 String expected");
  } else {
    status = gsl_vector_fprintf(fp, h, "%g");
  }
  if (flag == 1) fclose(fp);
  return INT2FIX(status);
}

static VALUE rb_gsl_vector_printf(int argc, VALUE *argv, VALUE obj)
{
  gsl_vector *h = NULL;
  int status;
  Data_Get_Struct(obj, gsl_vector, h);
  if (argc == 1) {
    if (TYPE(argv[0]) != T_STRING) 
      rb_raise(rb_eTypeError, "String expected");
    else
      status = gsl_vector_fprintf(stdout, h, STR2CSTR(argv[0]));
  } else {
    status = gsl_vector_fprintf(stdout, h, "%g");
  }
  return INT2FIX(status);
}

static VALUE rb_gsl_vector_fscanf(VALUE obj, VALUE io)
{
  gsl_vector *h = NULL;
  FILE *fp = NULL;
  int status, flag = 0;
  Data_Get_Struct(obj, gsl_vector, h);
  fp = rb_gsl_open_readfile(io, &flag);
  status = gsl_vector_fscanf(fp, h);
  if (flag == 1) fclose(fp);
  return INT2FIX(status);
}

static VALUE rb_gsl_vector_matrix_view(int argc, VALUE *argv, VALUE obj)
{
  gsl_vector *v = NULL;
  gsl_matrix_view *mv = NULL;
  Data_Get_Struct(obj, gsl_vector, v);
  switch (argc) {
  case 2:
    mv = gsl_matrix_view_alloc();
    *mv = gsl_matrix_view_vector(v, FIX2INT(argv[0]), FIX2INT(argv[1]));
    break;
  case 3:
    mv = gsl_matrix_view_alloc();
    *mv = gsl_matrix_view_vector_with_tda(v, FIX2INT(argv[0]), FIX2INT(argv[1]), 
				 FIX2INT(argv[2]));
    break;
  default:
    rb_raise(rb_eArgError, "wrong number of arguments (%d for 2 or 3)", argc);
    break;
  }
  return Data_Wrap_Struct(cgsl_matrix_view, 0, gsl_matrix_view_free, mv);
}

static VALUE rb_gsl_vector_matrix_view_with_tda(VALUE obj, VALUE nn1, VALUE nn2,
						VALUE tda)
{
  gsl_vector *v = NULL;
  gsl_matrix_view *mv = NULL;
  Data_Get_Struct(obj, gsl_vector, v);
  mv = gsl_matrix_view_alloc();
  *mv = gsl_matrix_view_vector_with_tda(v, FIX2INT(nn1), FIX2INT(nn2), FIX2INT(tda));
  return Data_Wrap_Struct(cgsl_matrix_view, 0, gsl_matrix_view_free, mv);
}

gsl_vector_view* gsl_vector_view_alloc()
{
  gsl_vector_view *vv = NULL;
  vv = ALLOC(gsl_vector_view);
  if (vv == NULL) rb_raise(rb_eNoMemError, "malloc failed");
  vv->vector.owner = 0;
  return vv;
}

void gsl_vector_view_free(gsl_vector_view * vv)
{
  free((gsl_vector_view *) vv);
}

static VALUE rb_gsl_vector_to_complex(VALUE obj)
{
  gsl_vector *v = NULL;
  gsl_vector_complex *cv = NULL;
  gsl_complex z;
  size_t i;
  double x;
  Data_Get_Struct(obj, gsl_vector, v);
  cv = gsl_vector_complex_alloc(v->size);
  for (i = 0; i < v->size; i++) {
    x = gsl_vector_get(v, i);
    z.dat[0] = x;
    z.dat[1] = 0.0;
    gsl_vector_complex_set(cv, i, z);
  }
  if (VECTOR_ROW_P(obj))
    return Data_Wrap_Struct(cgsl_vector_complex, 0, gsl_vector_complex_free, cv);
  else
    return Data_Wrap_Struct(cgsl_vector_complex_col, 0, gsl_vector_complex_free, cv);
}

static VALUE rb_gsl_vector_trans(VALUE obj)
{
  gsl_vector *v = NULL, *vnew = NULL;
  Data_Get_Struct(obj, gsl_vector, v);
  vnew = make_vector_clone(v);
  if (VECTOR_ROW_P(obj))
    return Data_Wrap_Struct(cgsl_vector_col, 0, gsl_vector_free, vnew);
  else if (VECTOR_COL_P(obj))
    return Data_Wrap_Struct(cgsl_vector, 0, gsl_vector_free, vnew);
  else rb_raise(rb_eTypeError, "wrong type");
}

static VALUE rb_gsl_vector_trans2(VALUE obj)
{
  if (CLASS_OF(obj) == cgsl_vector) RBASIC(obj)->klass = cgsl_vector_col;
  else if (CLASS_OF(obj) == cgsl_vector_col) RBASIC(obj)->klass = cgsl_vector;
  else {
    rb_raise(rb_eRuntimeError, "method trans! for %s is forbidden",
	     rb_class2name(CLASS_OF(obj)));
  }
  return obj;
}

static VALUE rb_gsl_vector_coerce(VALUE obj, VALUE other)
{
  gsl_vector *v = NULL, *vnew = NULL;
  gsl_vector_complex *cv = NULL;
  gsl_complex *c = NULL;
  VALUE vv;
  Data_Get_Struct(obj, gsl_vector, v);
  switch (TYPE(other)) {
  case T_FLOAT:
  case T_FIXNUM:
  case T_BIGNUM:
    vnew = gsl_vector_alloc(v->size);
    if (vnew == NULL) rb_raise(rb_eNoMemError, "gsl_vector_alloc failed");
    gsl_vector_set_all(vnew, NUM2DBL(other));
    vv = Data_Wrap_Struct(VECTOR_ROW_COL(obj), 0, gsl_vector_free, vnew);
    return rb_ary_new3(2, vv, obj);
    break;
  default:
    if (COMPLEX_P(other)) {
      Data_Get_Struct(other, gsl_complex, c);
      cv = gsl_vector_complex_alloc(v->size);
      if (cv == NULL) rb_raise(rb_eNoMemError, "gsl_vector_alloc failed");
      gsl_vector_complex_set_all(cv, *c);
      if (VECTOR_ROW_P(obj)) 
	vv = Data_Wrap_Struct(cgsl_vector_complex, 0, gsl_vector_complex_free, cv);
      else
	vv = Data_Wrap_Struct(cgsl_vector_complex_col, 0, gsl_vector_complex_free, cv);
      return rb_ary_new3(2, vv, obj);
    } else if (VECTOR_COMPLEX_P(other)) {
      cv = vector_to_complex(v);
      if (VECTOR_ROW_P(obj)) 
	vv = Data_Wrap_Struct(cgsl_vector_complex, 0, gsl_vector_complex_free, cv);
      else
	vv = Data_Wrap_Struct(cgsl_vector_complex_col, 0, gsl_vector_complex_free, cv);
      return rb_ary_new3(2, other, vv);
    } else {
      rb_raise(rb_eTypeError, "cannot coerced");
    }
    break;
  }
}

/* 2.Aug.2004 */
static VALUE rb_gsl_vector_inner_product(int argc, VALUE *argv, VALUE obj)
{
  gsl_vector *v = NULL, *v2 = NULL;
  double prod = 0.0;
  int i;
  switch (TYPE(obj)) {
  case T_MODULE:
  case T_CLASS:
  case T_OBJECT:
    if (argc != 2) rb_raise(rb_eArgError, "wrong number of arguments (%d for 2)",
			    argc);
    if (!VECTOR_ROW_P(argv[0]))
      rb_raise(rb_eTypeError, "wrong argument type %s (GSL::Vector expected)",
	       rb_class2name(CLASS_OF(argv[0])));
    if (!VECTOR_COL_P(argv[1]))
      rb_raise(rb_eTypeError, "wrong argument type %s (GSL::Vector::Col expected)",
	       rb_class2name(CLASS_OF(argv[1])));
    Data_Get_Struct(argv[0], gsl_vector, v);
    Data_Get_Struct(argv[1], gsl_vector, v2);
    break;
  default:
    if (argc != 1) rb_raise(rb_eArgError, "wrong number of arguments (%d for 1)",
			    argc);
    if (!VECTOR_ROW_P(obj))
      rb_raise(rb_eTypeError, "wrong argument type %s (GSL::Vector expected)",
	       rb_class2name(CLASS_OF(obj)));
    if (!VECTOR_COL_P(argv[0]))
      rb_raise(rb_eTypeError, "wrong argument type %s (GSL::Vector::Col expected)",
	       rb_class2name(CLASS_OF(argv[0])));
    Data_Get_Struct(obj, gsl_vector, v);
    Data_Get_Struct(argv[0], gsl_vector, v2);
    break;
  }
  if (v->size != v2->size) rb_raise(rb_eRangeError, "vector lengths do not match");
  for (i = 0; i < v->size; i++) prod += gsl_vector_get(v, i)*gsl_vector_get(v2, i);
  return rb_float_new(prod);
}

static VALUE rb_gsl_vector_product_to_m(int argc, VALUE *argv, VALUE obj)
{
  gsl_vector *v = NULL, *v2 = NULL;
  gsl_matrix *m = NULL;
  int i, j;
  switch (TYPE(obj)) {
  case T_MODULE:
  case T_CLASS:
  case T_OBJECT:
    if (argc != 2) rb_raise(rb_eArgError, "wrong number of arguments (%d for 2)",
			    argc);
    if (!VECTOR_COL_P(argv[0]))
      rb_raise(rb_eTypeError, "wrong argument type %s (GSL::Vector::Col expected)",
	       rb_class2name(CLASS_OF(argv[0])));
    if (!VECTOR_ROW_P(argv[1]))
      rb_raise(rb_eTypeError, "wrong argument type %s (GSL::Vector expected)",
	       rb_class2name(CLASS_OF(argv[1])));
    Data_Get_Struct(argv[0], gsl_vector, v);
    Data_Get_Struct(argv[1], gsl_vector, v2);
    break;
  default:
    if (argc != 1) rb_raise(rb_eArgError, "wrong number of arguments (%d for 1)",
			    argc);
    if (!VECTOR_COL_P(obj))
      rb_raise(rb_eTypeError, "wrong argument type %s (GSL::Vector::Col expected)",
	       rb_class2name(CLASS_OF(obj)));
    if (!VECTOR_ROW_P(argv[0]))
      rb_raise(rb_eTypeError, "wrong argument type %s (GSL::Vector expected)",
	       rb_class2name(CLASS_OF(argv[0])));
    Data_Get_Struct(obj, gsl_vector, v);
    Data_Get_Struct(argv[0], gsl_vector, v2);
    break;
  }
  m = gsl_matrix_alloc(v->size, v2->size);
  for (i = 0; i < v->size; i++) {
    for (j = 0; j < v2->size; j++) {
      gsl_matrix_set(m, i, j, gsl_vector_get(v, i)*gsl_vector_get(v2, j));
    }
  }
  return Data_Wrap_Struct(cgsl_matrix, 0, gsl_matrix_free, m);
}

void Init_gsl_vector()
{
  rb_define_singleton_method(cgsl_vector, "new", rb_gsl_vector_new, -1);
  rb_define_singleton_method(cgsl_vector, "[]", rb_gsl_vector_new, -1);
  rb_define_singleton_method(cgsl_vector, "alloc", rb_gsl_vector_new, -1);
  rb_define_singleton_method(cgsl_vector, "calloc", rb_gsl_vector_calloc, 1);

  rb_define_method(cgsl_vector, "size", rb_gsl_vector_size, 0);
  rb_define_method(cgsl_vector, "stride", rb_gsl_vector_stride, 0);
  rb_define_method(cgsl_vector, "set_stride", rb_gsl_vector_set_stride, 1);
  rb_define_alias(cgsl_vector, "stride=", "set_stride");
  rb_define_method(cgsl_vector, "owner", rb_gsl_vector_owner, 0);
  rb_define_method(cgsl_vector, "get", rb_gsl_vector_get, 1);
  rb_define_method(cgsl_vector, "set", rb_gsl_vector_set, 2); 
  rb_define_alias(cgsl_vector, "[]", "get");
  rb_define_alias(cgsl_vector, "[]=", "set");
  rb_define_method(cgsl_vector, "set_all", rb_gsl_vector_set_all, 1);
  rb_define_method(cgsl_vector, "set_zero", rb_gsl_vector_set_zero, 0);

  rb_define_method(cgsl_vector, "set_basis", rb_gsl_vector_set_basis, 1);
  rb_define_method(cgsl_vector, "each", rb_gsl_vector_each, 0);
  rb_define_method(cgsl_vector, "each_index", rb_gsl_vector_each_index, 0);
  rb_define_method(cgsl_vector, "print", rb_gsl_vector_print, 0);
  rb_define_method(cgsl_vector, "inspect", rb_gsl_vector_print, 0);
  rb_define_method(cgsl_vector, "subvector", rb_gsl_vector_subvector, -1);
  rb_define_alias(cgsl_vector, "view", "subvector");
  rb_define_method(cgsl_vector, "subvector_with_stride", rb_gsl_vector_subvector_with_stride, 3);

  rb_define_method(cgsl_vector, "to_a", rb_gsl_vector_to_a, 0);
  rb_define_singleton_method(cgsl_vector, "memcpy", rb_gsl_vector_memcpy, 2);
  rb_define_method(cgsl_vector, "clone", rb_gsl_vector_clone, 0);
  rb_define_singleton_method(cgsl_vector, "swap", rb_gsl_vector_swap, 2);
  rb_define_method(cgsl_vector, "swap_elements", rb_gsl_vector_swap_elements, 2);
  rb_define_method(cgsl_vector, "reverse!", rb_gsl_vector_reverse, 0);
  rb_define_method(cgsl_vector, "reverse", rb_gsl_vector_reverse2, 0);

  rb_define_method(cgsl_vector, "add", rb_gsl_vector_add, 1);
  rb_define_alias(cgsl_vector, "+", "add");
  rb_define_method(cgsl_vector, "add!", rb_gsl_vector_add2, 1);
  rb_define_alias(cgsl_vector, "+=", "add!");
  rb_define_method(cgsl_vector, "sub", rb_gsl_vector_sub, 1);
  rb_define_alias(cgsl_vector, "-", "sub");
  rb_define_method(cgsl_vector, "sub!", rb_gsl_vector_sub2, 1);
  rb_define_alias(cgsl_vector, "-=", "sub!");
  rb_define_method(cgsl_vector, "mul", rb_gsl_vector_mul, 1);
  rb_define_alias(cgsl_vector, "*", "mul");
  rb_define_method(cgsl_vector, "mul!", rb_gsl_vector_mul2, 1);
  rb_define_alias(cgsl_vector, "*=", "mul!");
  rb_define_method(cgsl_vector, "div", rb_gsl_vector_div, 1);
  rb_define_alias(cgsl_vector, "/", "div");
  rb_define_method(cgsl_vector, "div!", rb_gsl_vector_div2, 1);
  rb_define_alias(cgsl_vector, "/=", "div!");
  rb_define_method(cgsl_vector, "scale", rb_gsl_vector_scale, 1);
  rb_define_method(cgsl_vector, "scale!", rb_gsl_vector_scale2, 1);
  rb_define_method(cgsl_vector, "add_constant", rb_gsl_vector_add_constant, 1);
  rb_define_alias(cgsl_vector, "add_const", "add_constant");
  rb_define_method(cgsl_vector, "add_constant!", rb_gsl_vector_add_constant2, 1);
  rb_define_alias(cgsl_vector, "add_const!", "add_constant!");

  rb_define_method(cgsl_vector, "max", rb_gsl_vector_max, 0);
  rb_define_method(cgsl_vector, "min", rb_gsl_vector_min, 0);
  rb_define_method(cgsl_vector, "minmax", rb_gsl_vector_minmax, 0);
  rb_define_method(cgsl_vector, "max_index", rb_gsl_vector_max_index, 0);
  rb_define_method(cgsl_vector, "min_index", rb_gsl_vector_min_index, 0);
  rb_define_method(cgsl_vector, "minmax_index", rb_gsl_vector_minmax_index, 0);
  rb_define_method(cgsl_vector, "isnull", rb_gsl_vector_isnull, 0);
  rb_define_method(cgsl_vector, "isnull?", rb_gsl_vector_isnull2, 0);

  rb_define_method(cgsl_vector, "fwrite", rb_gsl_vector_fwrite, 1);
  rb_define_method(cgsl_vector, "fread", rb_gsl_vector_fread, 1);
  rb_define_method(cgsl_vector, "fprintf", rb_gsl_vector_fprintf, -1);
  rb_define_method(cgsl_vector, "printf", rb_gsl_vector_printf, -1);
  rb_define_method(cgsl_vector, "fscanf", rb_gsl_vector_fscanf, 1);

  rb_define_method(cgsl_vector, "matrix_view", rb_gsl_vector_matrix_view, -1);
  rb_define_method(cgsl_vector, "matrix_view_with_tda", rb_gsl_vector_matrix_view_with_tda, 2);

  rb_define_method(cgsl_vector, "to_complex", rb_gsl_vector_to_complex, 0);

  rb_define_method(cgsl_vector, "trans", rb_gsl_vector_trans, 0);
  rb_define_alias(cgsl_vector, "transpose", "trans");
  rb_define_alias(cgsl_vector, "col", "trans");
  rb_define_alias(cgsl_vector_col, "row", "trans");

  rb_define_method(cgsl_vector, "trans!", rb_gsl_vector_trans2, 0);
  rb_define_alias(cgsl_vector, "transpose!", "trans!");
  rb_define_alias(cgsl_vector, "col!", "trans!");
  rb_define_alias(cgsl_vector_col, "row!", "trans!");

  /*****/

  rb_define_method(cgsl_vector, "coerce", rb_gsl_vector_coerce, 1);

  /*****/

  rb_undef_method(cgsl_vector_view_ro, "set");
  rb_undef_method(cgsl_vector_view_ro, "[]=");

  /* 2.Aug.2004 */
  rb_define_singleton_method(cgsl_vector, "inner_product", rb_gsl_vector_inner_product, -1);
  rb_define_singleton_method(cgsl_vector, "dot", rb_gsl_vector_inner_product, -1);
  rb_define_method(cgsl_vector, "inner_product", rb_gsl_vector_inner_product, -1);
  rb_define_alias(cgsl_vector, "dot", "inner_product");

  /*****/
  rb_define_method(rb_cArray, "to_gv", rb_ary_to_gv0, 0);
  rb_define_method(rb_cRange, "to_gv", rb_gsl_range_to_gv, 0);
  rb_define_singleton_method(cgsl_vector, "ary_to_gv", rb_ary_to_gv, 1);

}

