int taskid ;
int control, socket ;

int display, file ;

void task_output(int handle; string data)
{
  string send ;

  /*write_raw(file, data) ;*/
  data_to_socket(socket, data) ;

  send="\0300FF00-> " ;
  string_cat(send, data) ;
  text_to_display(display, 0, send, "") ;
}

void task_died(int handle)
{
  text_to_display(display, 0, "\03FF0000The task has died", "") ;
  data_to_socket(socket, "\0d\0aThe task has died\0d\0a") ;
  close_socket(socket) ;
  socket=-1 ;
  quit() ;
}

void display_close_request(int display)
{
  if (socket >= 0)
  {
    data_to_socket(socket, "\0d\0aThe script is being killed from console\0d\0a") ;
  }
  quit() ;
}

void socket_connected(int handle; int new)
{
  text_to_display(display, 0, "Connected", "") ;
  if (handle=socket)
  {
    close_socket(handle) ;
    text_to_display(display, 0, "Set", "") ;
    socket=new ;
    define_socket_to_raw(new) ;
    taskid=start_task("GOS", 640, 0) ;
  }
}

void socket_closed(int handle)
{
  socket=-1 ;
  text_to_display(display, 0, "\0300FF00The remote end has closed the socket", "") ;
}

void data_from_socket(int handle; string data; int size)
{
  if (handle=socket)
  {
    int n, size ;
    string send ;

    size=string_len(data) ;
    for (n=0; n < size; n=n+1 ;)
    {
      if (string_char(data, n) != 10)
      {
        set_string_char(send, string_len(send), string_char(data, n)) ;
      }
    }
    text_to_display(display, 0, send, "") ;
    data_to_task(taskid, send) ;
  }
}

void main()
{
  int port ;

  init("RawServer", "Server for testing clients", "Sham Gardner", "0.00 (December 1997)", 0) ;

  display=open_display(80, 20, 100, "wop") ;

  port=23 ;
  socket=create_listening_socket(port) ;
  if (socket >= 0)
  {
    text_to_display(display, 0, "Successfully bound port 23", "") ;
  }
  else
  {
    port=0 ;
    socket=create_listening_socket(port) ;
    if (socket >= 0)
    {
      string info ;

      info="Unable to bind port 1234, using port " ;
      string_cat(info, int_to_string(port)) ;
      string_cat(info, " instead.") ;
      text_to_display(display, 0, info, "") ;
    }
    else
    {
      report_error("Unable to bind any port, exiting.") ;
      quit() ;
    }
  }
}
