#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <netinet/in.h>
#include <netdb.h>
#include <signal.h>
#include <curses.h>

#define PORT	47350	// Replace with your port number

/* talk.c - 10 points
 *   When called with no arguments it should act as a server, awaiting a
 *   client connection.  When one arrives it should begin the talk session.
 *   If called with two arguments it connects to the server.
 * 
 * Compile with: gcc -o talk talk.c -lcurses
 */
void initcurses(void) {
  initscr();
  meta(stdscr,TRUE);
  cbreak();
  noecho();
  intrflush(stdscr, FALSE);
  clear();
  refresh();
}

void cleanup(int s) {
  move(LINES, 0);
  refresh();
  echo();
  nocbreak();
  endwin();
  exit(0);
}

// Setup the socket as a server, bound to any interface, bound to the port
// defined above.  This function waits for a connection, then returns the
// newly connected socket.
int server(void) {
  struct sockaddr_in server;
  int sock, them, r;

  // Create an internet stream socket (optionally set socket option to reuse
  // the address, set descriptor 




  
  // setup socket address:



  // Bind socket:



  // Begin listening for connections:



  // Accept a connection (them) and return it:



  return them;
}

// Sets up a client socket, to connect to the machine at host / port:
int client(char *host, char *port) {
  struct sockaddr_in server;
  struct hostent *he;
  int sock;
  
  // Create an internet stream socket:


  
  // Setup the servers address:



  
  // Connect to the server:



  return sock;
}

int main(int argc, char *argv[])
{
  struct sigaction sa;
  WINDOW *top, *bot;
  int sock, i, r, rows, ch;
  char c;
  fd_set rfds, sfds;
  int highfd = 0;

  // Install a sigaction to call "cleanup" when a signal is received:



  initcurses();
  rows = (LINES - LINES%2)/2;
  top = newwin(rows, COLS, 0, 0);
  scrollok(top, 1);
  for(i=0; i < COLS; i++) mvaddch(rows, i, '-');
  bot = newwin(rows, COLS, rows+1, 0);
  scrollok(bot, 1);
  refresh();

  if (argc >= 3) {
    sock = client(argv[1], argv[2]);
  } else {
    sock = server();
  }

  // Setup the permanent fd_set "sfds":

  
  
  
  for(;;) {
    // Re-initialize fd set: copy sfds to rfds:


    // perform select:

    
    // Check socket, if input available:
    //   read a single character.
    //   put it on the top window, i.e.:
/*
      if (c == '\b') {
	// This simulates a destructive backspace character:
	waddch(top, '\b');
	waddch(top, ' ');
      }
      waddch(top, (char)c);
      wrefresh(top);
*/




    // Check stdin, if input available:
    //   read a single character
    //   put it on the bottom window
    //   write it on the socket:

    
    
    
    
    
    
    

    
    
  }
  cleanup(0);
  return 0;
}
