/**********************************************************************
 * ti library's get-message routine
 *
 * $Author: brlewis $
 * $Source: /afs/net.mit.edu/project/net_dev/brlewis/src/lib/RCS/_ti_recvmsg.c,v $
 * $Header: /afs/net.mit.edu/project/net_dev/brlewis/src/lib/RCS/_ti_recvmsg.c,v 0.1 92/03/12 15:26:53 brlewis Exp $
 *
 * Copyright 1991 by the Massachusetts Institute of Technology.
 *
 * For copying and distribution information, please see the file
 * <mit-copyright.h>.
 **********************************************************************/
#include <mit-copyright.h>

#ifndef lint
static char rcsid__ti_recvmsg_c[] = "$Header: /afs/net.mit.edu/project/net_dev/brlewis/src/lib/RCS/_ti_recvmsg.c,v 0.1 92/03/12 15:26:53 brlewis Exp $";
#endif /* lint */

#include <errno.h>
#include <ti/ti.h>

/**********************************************************************
 * _ti_recvmsg(TI_H hti, LPSTR buf, int bufsize)
 *
 * - reads message from hti's sock into buf (bufsize chars)
 * - returns error code
 **********************************************************************/

/* jms 7/9/92 -- windows-izing completed, pending approval. */
/* i/o needs a bit of work */

long
_ti_recvmsg(hti, buf, bufsize)
     TI_H hti;
     LPSTR buf;
     int bufsize;
{
  register int red=1;
  int total=0;
  long code;
  TI_LP lpti;

  lpti = (TI_LP)TI_DEREFERENCE(hti);

  while(bufsize > 0 && red > 0)
    {
      red = read(lpti->sock, buf, bufsize);
      if (red < 0) CLEANUP_AND_RETURN((long)errno)
      buf += red;
      bufsize -= red;
      total += red;
      if (total >= TI_EOM_LEN)
	if (!strncmp(buf-TI_EOM_LEN, TI_EOM, TI_EOM_LEN))
	  {
	    /* end of message has been read */
	    *(buf-TI_EOM_LEN) = '\0';	/* remove EOM from message */
	    total -= TI_EOM_LEN;
	    break;
	  }
    }

  if (red < 0)
    {
      *ti_context = '\0';
      CLEANUP_AND_RETURN((long) errno)
    }
  if (!bufsize)
    {
      *ti_context = '\0';
      CLEANUP_AND_RETURN(TI_ERR_TOOLONG)
    }
  code = 0L;

CLEANUP:
  TI_REMOVE_DEREFERENCE(hti, lpti);
  return(code);
}
