#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <fcntl.h>
#include <signal.h>
#include <dbx_mess.h>


static char prefix[] = "/tmp/tube";                
#define CONTROL_SIZE (sizeof(dbx_message))
#define WRITE_SIZE 200
#define READ_SIZE 200
#define MAX_NAME_SIZE 200

static int od,id;
static int cd;

static void handler_tstp(int sig)
{
  close(cd);
  close(od);
  close(id);
  exit(1);
}

main(int argc,char **argv)
{
  printf("DBXYAFL multi-console input-output program version 1.004\n");
  if (argc != 2)
  {  
    printf("error: 1 argument required\n");
  }
  else
  {
    main_loop(argv[1]);
  }
}

main_loop(char *name)
{
  char pipe_name1[MAX_NAME_SIZE],pipe_name2[MAX_NAME_SIZE];
  char pipe_name3[MAX_NAME_SIZE];
  char write_buffer[WRITE_SIZE];
  char read_buffer[READ_SIZE];
  dbx_message control_buffer;
  int count, n;
  assert(name != NULL);
  strcpy(pipe_name3, prefix);
  strcat(pipe_name3, name);

/*  sprintf(pipe_name3, "/home/bernard/pipe3"); */

  printf("opening control tube %s\n", pipe_name3);
  cd = open(pipe_name3, O_RDONLY); /* control channel */
  if (cd == -1)
  {
    printf("cannot open control pipe %s \n", pipe_name3);
    exit(EXIT_FAILURE);
  }
  count = read(cd, &control_buffer, CONTROL_SIZE);
/*
  while (count <= 0) 
  {
    printf("waiting for the application start\n");
    sleep(1);
    count = read(cd, &control_buffer, CONTROL_SIZE);
  }
*/
  if (count != CONTROL_SIZE)
  {
    printf("control error\n");
    close(cd);
  }
  else
  {
    strcpy(pipe_name1, prefix);
    strcat(pipe_name1, control_buffer.name);
    printf("opening output tube %s\n", pipe_name1);
    od = open(pipe_name1, O_RDONLY); /* debugger output channel */
    if (od == -1)
    {
      printf("cannot open output pipe %s \n", pipe_name1);
      exit(EXIT_FAILURE);
    }
    n = read(cd, &control_buffer, CONTROL_SIZE);
    if (n != CONTROL_SIZE)
    {
      printf("read error \n");
      exit(EXIT_FAILURE);
    }
    strcpy(pipe_name2, prefix);
    strcat(pipe_name2, control_buffer.name);
    printf("opening input tube %s\n", pipe_name2);
    id = open(pipe_name2, O_WRONLY); /* debugger input channel */
    if (id == -1)
    {
      printf("cannot open input pipe %s \n", pipe_name2);
      exit(EXIT_FAILURE);
    }
    #ifdef SIGINT
      signal(SIGINT, SIG_IGN);
    #endif
    #ifdef SIGTSTP
      signal(SIGTSTP, handler_tstp);
    #endif
    while (read(cd, &control_buffer, CONTROL_SIZE))
    {
      if (n != CONTROL_SIZE)
      {
        printf("read error \n");
        exit(EXIT_FAILURE);
      }
      if (control_buffer.command)
      {
        read(od, write_buffer, control_buffer.length);
        write(1, write_buffer, control_buffer.length);
      }
      else
      {
        gets(read_buffer);
        write(id, read_buffer, strlen(read_buffer)+1);      /* ??? */
      }
    }  
    close(cd);
    close(od);
    close(id);
  }
} 

