#include <time.h>
#include <string.h>
#include <stddef.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

#define stringl  250
#define bufsize 2048

int debug = 0;


void chomp(char *s) {
  while(*s && *s != '\n' && *s != '\r') 
    s++;
  *s = 0;
}

void set_debug(int i)
{
  debug = i;
  return;
}

int main ()
{
  
  setbuf(stdout,NULL);
  double rc, rorg;
  struct timespec tdel, trem;
  time_t curtime;
  struct tm *loctime;
  const char delimiters[] = " :\t";
  const char delimnul[] = "";
  char readstring[bufsize], setupstring[bufsize];
  char *token;
  char *cp;
  char c;
  int n;
  int delay=1;
  static char scannerstring[stringl] = "";
  char timebuffer[stringl];
  int er, sockfd, newsockfd, portno, clilen, icount;
  char buffer[bufsize];
  short chid, iaddr, ichannel, i;
  struct sockaddr_in serv_addr, cli_addr;
  sockfd = socket (AF_INET, SOCK_STREAM, 0);
  if (sockfd < 0)
    error ("ERROR opening socket");
  bzero ((char *) &serv_addr, sizeof (serv_addr));
  portno = 12345;               /* atoi (argv[1]); */
  serv_addr.sin_family = AF_INET;
  serv_addr.sin_addr.s_addr = INADDR_ANY;
  serv_addr.sin_port = htons (portno);
  if (bind (sockfd, (struct sockaddr *) &serv_addr, sizeof (serv_addr)) < 0)
    error ("ERROR on binding");
  listen (sockfd, 25);
  clilen = sizeof (cli_addr);

  do
    {
      newsockfd = accept (sockfd, (struct sockaddr *) &cli_addr, &clilen);
      if (debug)
        {
          curtime = time(0);
          printf(ctime(&curtime));
          printf ("count %d fd %d \n", icount++, newsockfd);
        }
      if (newsockfd < 0)
        error ("ERROR on accept");
      bzero (buffer, bufsize);
      n = read (newsockfd, buffer, bufsize - 1);
      if (debug)
        {
          printf ("%s length: %d \n", buffer, strlen (buffer));
        }
      if (n < 0)
        error ("ERROR reading from socket");

      cp = strdup (buffer);     /* Make writable copy.  */
      chomp(cp);   /* Only work with part up to first newline (if any) */
      token = strtok (cp, delimiters);
      c = toupper (token[0]);
      token = strtok (NULL, delimiters);
      if (token)
        {
          iaddr = atoi (token);
          if (debug)
            {
              printf ("%c %d %s  \n", c, iaddr, token);
            }
        }
      if (iaddr>0 || c == 'I' || c == 'Q'  || c == 'D' || c == 'T') 
        { 
          switch (c)
            {
              
            case 'D':
              if (debug)
                {
                  debug = 0;
                  sprintf(readstring,  "Debug off\n"); 
                }
              else
                {
                  debug = 1;
                  sprintf(readstring,  "Debug on\n"); 
                }
              set_debug(debug);
              n = write (newsockfd, readstring, strlen (readstring));
              break;

            case 'T':
              if (token != NULL)
                {
                  delay = atoi(token);
                }
              sprintf(readstring,  "GPIB delay set to %i ms",delay); 
              if (debug)
                printf("%s\n",readstring);
              n = write (newsockfd, readstring, strlen (readstring));
              break;

            case 'I':
              sprintf(readstring,  "Updating channel configurations...\n"); 
              n = write (newsockfd, readstring, strlen (readstring));
              break;
              
            case 'K':
              token = strtok (NULL, delimiters);
              /*              token = strtok (NULL, delimnul);*/
              chid = 0;
              if (token != NULL)
                {
                  chid = atoi(token);
                }
              rc=-32768;
              rorg=-32768;
	      curtime = time (NULL);
	      loctime = localtime (&curtime);
	      strftime (timebuffer, stringl, "%Y:%m:%d:%H:%M:%S", loctime);
	      sprintf(readstring,  "%s %d  %d:%d DUMMY_CHANNEL %f %f\n", timebuffer, curtime, iaddr, chid, rorg, rc);
	      n = write (newsockfd, readstring, strlen (readstring),0);
	      break;
            }
        }
      if (debug)
        {
          printf ("shutting down newsocket %d\n", shutdown (newsockfd, 2));
        }
      close (newsockfd);
    }
  while (c != 'Q');
  printf ("shutting down %d\n", shutdown (sockfd, 2));
  return 0;
}
