#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>

#include <erroutines.h>


int
WH_sock(int sock, char *hostname, int port, 
	char *query, int maxlines, int timeout)
{
  char log_str[256];
  FILE *sfi;
  FILE *sfo;
  struct sockaddr_in sin;
  struct hostent *hp;
  int ch;
  int s;
  
  sprintf(log_str, "would perform query >%s< to %s:%d  \n"
	  "limits: line %d tmout %d and print on socket %d\n",
	  query,hostname,port, maxlines,timeout,sock );
  log_inst_print(log_str);
  
  if ( (hp = gethostbyname(hostname)) == NULL) {
    return WH_BADHOST;
  }

  s = socket(AF_INET, SOCK_STREAM, 0);
  if (s < 0) {
    return WH_SOCKET;
  }
  
  bzero((caddr_t)&sin, sizeof (sin));
  sin.sin_family = hp->h_addrtype;
  if (bind(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
    close(s);
    return WH_BIND;
  }
  bcopy(hp->h_addr, (char *)&sin.sin_addr, hp->h_length);
  sin.sin_port=port;

  if (connect(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
    close(s);
    return WH_CONNECT;
  }

#if 1
  sfi = fdopen(s, "r");
  sfo = fdopen(s, "w");
  if (sfi == NULL || sfo == NULL) {
    (void)close(s);
    return WH_OPEN;
  }

  fprintf(sfo, "%s\r\n", query);
  fflush(sfo);

  while ((ch = getc(sfi)) != EOF) {
    int ret = SK_putc(sock,ch);
  }

  fclose(sfo);
  fclose(sfi);
#else
  SK_puts(s, query);
  SK_puts(s, "\r\n");

  while( (ch = SK_getc(s)) != EOF ) {
    SK_putc(sock,ch);
  }
#endif
  close(s);
}

