/* -*- Mode: C; c-file-style: "gnu" -*-
   double.c -- native methods for java/lang/Double.
   Created: Chris Toshok <toshok@hungry.com>, 28-Jul-1997
 */
/*
  This file is part of Japhar, the GNU Virtual Machine for Java Bytecodes.
  Japhar is a project of The Hungry Programmers, GNU, and OryxSoft.

  Copyright (C) 1997, 1998, 1999 The Hungry Programmers

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Library General Public
  License as published by the Free Software Foundation; either
  version 2 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
  Library General Public License for more details.

  You should have received a copy of the GNU Library 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
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "jniint.h"

#include <stdlib.h>
#include <string.h>

extern PRLogModuleInfo *nativeLm;

JNIEXPORT jlong JNICALL
Java_java_lang_Double_doubleToLongBits(JNIEnv *env,
				       jclass cls,
				       jdouble value)
{
  jvalue jval;

  jval.d = value;

  /* The q formatter is a BSD code.  I know of no ANSI equvalent */
  PR_LOG(nativeLm, PR_LOG_DEBUG, ("Double.doubleToLongBits(%f) = 0x%16qx;\n",
				  value, jval.j));

  return jval.j;
}

JNIEXPORT jdouble JNICALL
Java_java_lang_Double_longBitsToDouble(JNIEnv *env,
				       jclass cls,
				       jlong bits)
{
  jvalue value;

  value.j = bits;

  PR_LOG(nativeLm, PR_LOG_DEBUG, ("Double.longBitsToDouble(0x%16qx) = %f;\n",
				  bits, value.d));

  return value.d;
}

/* JDK1.1 */
JNIEXPORT jdouble JNICALL
Java_java_lang_Double_valueOf0(JNIEnv *env,
			       jclass cls,
			       jstring string)
{
  HungryEnv *henv = HVM_ThreadGetEnv();
  double d;
  const jbyte *string_chars;
  jint string_length;
  char *str;

  if (NULL == string)
    {
      HVM_ExceptionThrow(henv, "java/lang/NullPointerException", NULL);
      return 0.0; /* Must return something... */
    }

  string_chars = (*env)->GetStringUTFChars(env, string, NULL);
  string_length = (*env)->GetStringUTFLength(env, string) + 1;
  str = (char*)malloc(string_length * sizeof(char));
  
  strncpy(str, (char*)string_chars, string_length);

  (*env)->ReleaseStringUTFChars(env, string, string_chars);

  d = atof(str);

  free(str);

  return (jdouble)d;
}
