/* -*- Mode: C; c-file-style: "gnu" -*-
   sockin.c -- native methods for the socket input stream.
   Created: Chris Toshok <toshok@hungry.com>, 3-Feb-98
 */
/*
  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) 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 <errno.h>

#ifdef HAVE_UNISTD_H
#  include <unistd.h>
#endif
#ifdef HAVE_IO_H
#  include <io.h>
#endif

JNIEXPORT jint JNICALL
Java_java_net_SocketInputStream_socketRead(JNIEnv *env,
					   jobject obj,
					   jbyteArray bytes,
					   jint off,
					   jint len)
{
  HungryEnv *henv = HVM_ThreadGetEnv();
  jclass sockin_class = (*env)->FindClass(env, "java/net/SocketInputStream");
  jclass sockimpl_class = (*env)->FindClass(env, "java/net/SocketImpl");
  jclass fdesc_class = (*env)->FindClass(env, "java/io/FileDescriptor");
  jfieldID sockimpl_field = (*env)->GetFieldID(env, sockin_class, "impl", "Ljava/net/SocketImpl;");
  jfieldID fdesc_field = (*env)->GetFieldID(env, sockimpl_class, "fd", "Ljava/io/FileDescriptor;");
  jfieldID fd_field = (*env)->GetFieldID(env, fdesc_class, "fd", "I");
  jobject sockimpl;
  jobject fdesc;
  int fd;
  jbyte *byte_buf;
  int ret_val;

  sockimpl = (*env)->GetObjectField(env, obj, sockimpl_field);
  fdesc = (*env)->GetObjectField(env, sockimpl, fdesc_field);
  fd = (*env)->GetIntField(env, fdesc, fd_field);

  byte_buf = (*env)->GetByteArrayElements(env, bytes, NULL);

  ret_val = read(fd, byte_buf + off, len);

  if (ret_val == -1)
    { 
      HVM_ExceptionThrow(henv, "java/io/IOException", "socket read failed.");
    }
  
  (*env)->ReleaseByteArrayElements(env, bytes, byte_buf, 0);

  return ret_val;
}

JNIEXPORT void JNICALL
Java_java_net_SocketInputStream_init(JNIEnv *env,
				     jclass cls)
{
  /* anything needed here? */
}
