
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include <dos/dos.h>
#include <clib/dos_protos.h>
#include <clib/exec_protos.h>

#include <clib/AMarquee_protos.h>

#include <pragmas/AMarquee_pragmas.h>

#define UNLESS(x) if (!(x))

struct Library * AMarqueeBase = NULL;
struct QSession * session     = NULL;

void CleanExit(void)
{
  if (session)      QFreeSession(session);       /* This MUST be done before we close the library! */
  if (AMarqueeBase) CloseLibrary(AMarqueeBase);
  printf("All done.\n");
}

/* Main program--simply increments our counter using a stream. */
int main(int argc, char ** argv)
{
  char * connectTo, * progName;
  int port = 2957;
  int count = 0;
  
  atexit(CleanExit);
    
  printf("StreamGen: This program continually updates an integer on the server.\n");
  printf("           It uses QStreamOp(), so anyone subscribing to streamcount\n");
  printf("           should see a monotonously increasing stream of integers.\n");

  if (argc < 2) 
  {
    printf("Usage:  StreamGen hostname [myname]\n");
    exit(RETURN_WARN);
  }
  connectTo = argv[1] ? argv[1] : "localhost";
  progName  = argv[2] ? argv[2] : "streamgen";

  if ((AMarqueeBase = OpenLibrary("amarquee.library",37L)) == NULL)
  {
    printf("Couldn't open amarquee.library v37!\n");
    exit(RETURN_ERROR);
  }
  printf("Connecting to %s:%i...\n",connectTo, port);
  if ((session = QNewSession(connectTo, port, progName)) == NULL)
  {
    printf("Couldn't connect to server %s:%i\n",connectTo, port);
    CloseLibrary(AMarqueeBase);
    exit(RETURN_WARN);
  }
  printf("StreamGen connected to server %s:%i\n",connectTo, port);

  /* Setup */
  while(1)
  {
    struct QMessage * msg;
    
    printf("Streaming %i...\r",count); fflush(stdout);
    UNLESS(QStreamOp(session, "streamcount", &count, sizeof(count)))
    {
      printf("QStreamOp() (even) failed, aborting!\n");
      break;    
    } 
    count++;
    UNLESS(QGo(session, 0L))
    {
      printf("QGo() failed, aborting!\n");
      break;
    }    
    Delay(10);
    
    /* Check for any error messages */
    while(msg = (struct QMessage *)GetMsg(session->qMsgPort))
    {
      int stat = msg->qm_Status;
      
      FreeQMessage(session, msg);
      if (stat != QERROR_NO_ERROR)
      {
        printf("Received an error message, closing the connection\n");
        exit(RETURN_ERROR);
      }
    }
  }
  /* CleanExit called here via the atexit() feature */
}
