/* poorteln.c (emx+gcc) */

#include <stdio.h>
#include <stdlib.h>
#include <process.h>
#include <string.h>
#include <io.h>
#include <unistd.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include "easysock.h"

static void copy (int from, int to)
{
  int nread, nwritten;
  char *p;
  static char buf[4096];

  while ((nread = read (from, buf, sizeof (buf))) > 0)
    {
      p = buf;
      while (nread > 0)
        {
          nwritten = write (to, p, nread);
          if (nwritten < 0)
            break;
          nread -= nwritten;
          p += nwritten;
        }
    }
}


static void read_socket (void *arg)
{
  copy (*(int *)arg, STDOUT_FILENO);
  exit (1);
}


static void write_socket (void *arg)
{
  copy (STDIN_FILENO, *(int *)arg);
  exit (1);
}


int main (int argc, char *argv[])
{
  struct sockaddr_in in_local, in_server;
  int s_server, port, i;

  if (argc != 3)
    {
      fputs ("Usage: poorteln <host> <port>\n", stderr);
      return 1;
    }

  es_parse_host (&in_server, argv[1]);
  es_parse_port (&port, argv[2]);

  in_server.sin_port = port;

  es_socket (&s_server);
  es_reuse (s_server);
  es_bind_any (s_server);
  es_getsockname (&in_local, s_server);

  printf ("Socket handle:         %d\n", s_server);
  printf ("TCP/IP socket handle:  %d\n", _getsockhandle (s_server));
  printf ("Local port number:     %d\n", ntohs (in_local.sin_port));

  es_connect (s_server, &in_server);

  i = 0;
  if (ioctl (s_server, FIONBIO, (char *)&i) != 0)
    perror ("ioctl(FIONBIO)");

  setmode (STDIN_FILENO, O_BINARY);
  setmode (STDOUT_FILENO, O_BINARY);

  _beginthread (write_socket, 0, 0x8000, &s_server);
  read_socket (&s_server);

  close (s_server);
  return 0;
}
