/* Copyright (c) 1991-2002 Doshita Lab. Speech Group, Kyoto University */
/* Copyright (c) 2000-2002 Speech and Acoustics Processing Lab., NAIST */
/*   All rights reserved   */

/* rdwt.c --- lowlevel functions for TCP/IP inter-process communication */

/* rd() and wt() should be used in both end of communication */

/* $Id: rdwt.c,v 1.4 2002/09/11 22:01:50 ri Exp $ */

#include <sent/stddefs.h>
#include <sent/tcpip.h>

/* buffer size */
#define		BUFSZ	4096


/* read in data from stream for a specified length */
/* data format: length(4)->data(length)->length(4)->data(length)->... */
int
rd(  int   fd,			/* file descpritor */
     char *data,		/* pointer to buffer */
     int  *len,			/* received length in bytes (return value) */
     int   maxlen)		/* maximum length of data[] in bytes */
{
  int count=0;
  int tmpbytes, tmplen;
  
  if ((tmpbytes=read(fd,(char *)len,sizeof(int))) != sizeof(int)) {
    /*j_printerr( "failed to read num\n");*/
    return(-1);
  }
  if (*len > maxlen) {
    j_printerr( "transfer data length exceeded: %d (>%d)\n",
	    len, maxlen);
    return(-1);
  }
  while (count<(*len)){

    tmplen = (*len) - count;
    if (tmplen > BUFSZ) tmplen = BUFSZ;
    if ((tmpbytes = read(fd,data+count,tmplen)) < 0) {
      j_printerr( "failed to read data at %d / %d\n",count, len);
      return(count);
    }
    count += tmpbytes;
  }
  return(count);
}

/* write data to stream for a specified length */
/* data format: length(4)->data(length)->length(4)->data(length)->... */
int
wt(
   int  fd,			/* file descpritor */
   char *data,			/* pointer to buffer */
   int   len)			/* length of data in bytes */
{
  int	tmpbytes;

  /* len == 0 means end of segment ack */
  if ((tmpbytes=write(fd,(char *)&len,sizeof(int))) != sizeof(int)) {
    /*j_printerr( "failed to write num\n");*/
    return(-1);
  }
  if (len > 0) {
    if ((tmpbytes=write(fd,data,len)) < 0) {
      j_printerr( "failed to write data (%d bytes)\n",len);
      return(-1);
    }
  } else {
    tmpbytes = 0;
  }
  return(tmpbytes);
}
