/**
* Copyright 1981-2012 ECMWF.
*
* This software is licensed under the terms of the Apache Licence 
* Version 2.0 which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
*
* In applying this licence, ECMWF does not waive the privileges and immunities 
* granted to it by virtue of its status as an intergovernmental organisation 
* nor does it submit to any jurisdiction.
*/

#ifdef FORTRAN_NO_UNDERSCORE
#define IINSERT iinsert
#define RINSERT rinsert
#define DINSERT dinsert
#define IXTRACT ixtract
#define RXTRACT rxtract
#define DXTRACT dxtract
#define RMOVEN  rmoven
#define JLOC    jloc
#else
#define IINSERT iinsert_
#define RINSERT rinsert_
#define DINSERT dinsert_
#define IXTRACT ixtract_
#define RXTRACT rxtract_
#define DXTRACT dxtract_
#define RMOVEN  rmoven_
#define JLOC    jloc_
#endif

#include <memory.h>
#include "common/fortint.h"

fortint IXTRACT(JPointer * array, fortint * index) {
fortint * p = (fortint *) *array;
/*
// Extracts a Fortran integer from an array.
// Note that the array pointer is given by reference.
*/
  return (fortint) p[(*index)-1];
}

fortreal RXTRACT(RPointer * array, fortint * index) {
fortreal * p = (fortreal *) *array;
/*
// Extracts a Fortran real from an array.
// Note that the array pointer is given by reference.
*/

  return (fortreal) p[(*index)-1];
}

void DXTRACT(void * target, void ** array, fortint * index) {
/*
// Extracts a Fortran REAL*8 from an array of doubles.
// Note that the array pointer is given by reference.
*/
unsigned char * p = (unsigned char*)(*array) + ((*index)-1)*8;

  memmove(target, p, 8);
  return;
}

void IINSERT(JPointer * array, fortint * index, fortint * value) {
fortint * p = (fortint *) *array;
/*
// Inserts a Fortran integer into an array.
// Note that the array pointer is given by reference.
*/
  p[(*index)-1] = *value;
  return;
}

void RINSERT(RPointer * array, fortint * index, fortreal * value) {
fortreal * p = (fortreal *) *array;
/*
// Inserts a Fortran real into an array.
// Note that the array pointer is given by reference.
*/
  p[(*index)-1] = *value;
  return;
}

void DINSERT(void ** array, fortint * index, void * value) {
/*
// Inserts a Fortran single into a (double) array.
// Note that the array pointer is given by reference.
*/
unsigned char * p = (unsigned char*)(*array) + ((*index)-1)*8;

  memmove(p,value,8);
  return;
}

void RMOVEN(RPointer * target, RPointer * source, fortint * number) {
fortreal * Target = (fortreal *) *target;
fortreal * Source = (fortreal *) *source;
size_t N = (*number) * sizeof(fortreal);
/*
// Moves Fortran reals from one array to another.
// Note that the array pointers are given by reference.
*/
  memmove(Target, Source, N);
}

RPointer JLOC(RPointer array) {
/*
// Emulates the Fortran %LOC function
*/
  return array;
}
