#define I_ERRNO
#define I_SYS
#define I_SOCKET
#include "includes.h"

#include "client.h"
#include <signal.h>

#define MAXREDIR 32
/* improved version - does multiple redirs  -ot */

int display_num = 9;
int debug = 0;

char *remote_port[MAXREDIR];

int rd_connect_server(int n) {
  int s;
  
  if ((s = connect_server(0)) <0) {
    perror("Couldn't open term");
    close(s);
    return -1;
  }

  if (send_command(s, C_PORT, 0, "%s", remote_port[n])< 0) {
    return -1;
  }

  send_command(s, C_DUMB, 1, 0);
  return s;
}

void check_usage(int n) {
  if ( n < 2 )
    {
      fprintf ( stderr, "Usage: redir [options] {<localport> <[host:]remoteport>}\n" );
      exit(1);
    }
}

void main(int argc, char *argv[]) {
  int s;
  int first, i;
  int svs[MAXREDIR];
  signal(SIGPIPE, SIG_IGN);
  first = client_options(argc, argv,"",NULL);
  setbuf(stderr, 0);
	check_usage(argc-first);

	for (i = 0; i < MAXREDIR && first < argc;first += 2) {
		check_usage(argc - first);
		fprintf(stderr, "Redirecting %s to %s\n", argv[first], argv[first+1] );
    remote_port[i] = argv[first+1];
    
    /* Bind the local socket we are going */
    /* to listen on.  */
    s = bind_tcp(atoi(argv[first]));
    if (s < 0) {
      fprintf(stderr, "Port is already bound or some such error. s = %d\n", s);
    }
    else {
      svs[i++] = s;
    }
  }
  do_connect(i, svs, rd_connect_server);
}
