#ifdef HAVE_STDLIB_H
#include <stdlib.h>
#endif
#include <stdio.h>
#include <malloc.h>
#include "yagi.h"


/* The authors of the book 'Numerical Recipes in C' were kind enough
to make the utility routines in the files 'nrutil.c' and 'nrutil.h'
public domain. Hence I can include both without any problems */


#define NR_END 1
#define FREE_ARG char*

#ifndef size_t         /* gcc needs this */
#define size_t int
#endif

char *string(long nl,long nh)
{
	char *v;

	v=(char *)malloc((unsigned) (nh-nl+1)*sizeof(char));
	if (!v) nrerror("allocation failure in string()");
	return v-nl;
}

void free_string(char *v, long nl, long nh)
/* free a string allocated with string() */
{
	/* free((FREE_ARG) (v+nl-NR_END)); */
	free((FREE_ARG) (v+nl));
}

struct FCOMPLEX **FCOMPLEXmatrix(long nrl, long nrh, long ncl, long nch)
/* allocate a FCOMPLEX matrix with subscript range m[nrl..nrh][ncl..nch] */
{
	long i, nrow=nrh-nrl+1,ncol=nch-ncl+1;
	struct FCOMPLEX **m;

	/* allocate pointers to rows */
	m=(struct FCOMPLEX **) malloc((size_t)((nrow+NR_END)*sizeof(struct
	FCOMPLEX*)));
	if (!m) nrerror("allocation failure 1 in matrix()");
	m += NR_END;
	m -= nrl;

	/* allocate rows and set pointers to them */
	m[nrl]=(struct FCOMPLEX *) malloc((size_t)((nrow*ncol+NR_END)*sizeof(struct FCOMPLEX)));
	if (!m[nrl]) nrerror("allocation failure 2 in matrix()");
	m[nrl] += NR_END;
	m[nrl] -= ncl;

	for(i=nrl+1;i<=nrh;i++) m[i]=m[i-1]+ncol;

	/* return pointer to array of pointers to rows */
	return m;
}

struct element_data *element_data_vector(long nl, long nh)
/* allocate an element_data vector with subscript range v[nl..nh] */
{
	struct element_data *v;

	v=(struct element_data  *)malloc((size_t) ((nh-nl+1+NR_END)*sizeof(struct element_data)));
	if (!v) nrerror("allocation failure in element_data_vector()");
	return v-nl+NR_END;
}

struct FCOMPLEX *FCOMPLEXvector(long nl, long nh)
/* allocate a FCOMPLEX vector with subscript range v[nl..nh] */
{
	struct FCOMPLEX *v;

	v=(struct FCOMPLEX *)malloc((size_t) ((nh-nl+1+NR_END)*sizeof(struct FCOMPLEX)));
	if (!v) nrerror("allocation failure in FCOMPLEXvector()");
	return v-nl+NR_END;
}

void free_FCOMPLEXmatrix(struct FCOMPLEX **m, long nrl, long nrh, long ncl, long nch)
{
        free((FREE_ARG) (m[nrl]+ncl-NR_END));
        free((FREE_ARG) (m+nrl-NR_END));
}

void free_FCOMPLEXvector( struct FCOMPLEX *v, long nl, long nh)
{
        free((FREE_ARG) (v+nl-NR_END));

}

void free_element_data_vector( struct element_data *v, long nl, long nh)
{
        free((FREE_ARG) (v+nl-NR_END));

}
