/* Collection of code snippets by Arne Vajhøj */
/* (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <iccdef.h>
#include <descrip.h>
#include <starlet.h>

static char outmsg[10000] = "";

static void handler(unsigned int evttyp, unsigned int con, unsigned int datlen, char *dat,
                    unsigned int p5, unsigned int p6, char *p7)
{
   long stat;
   struct _ios_icc rec_iosb, tra_iosb;
   char inmsg[1000];
   if(evttyp == ICC$C_EV_CONNECT)
   {
      printf("connect from user %s (pid %08X)\n", p7, p6);
      stat = sys$icc_accept(con, 0, 0, 0, 0);
      if((stat & 1) == 0) printf("sys$icc_accept stat = %d\n", stat);
      stat = sys$icc_receivew(con, &rec_iosb, 0, 0, inmsg, sizeof(inmsg));
      if((stat & 1) == 0) printf("sys$icc_receivew stat = %d\n", stat);
      if((rec_iosb.ios_icc$w_status & 1) == 0) printf("sys$icc_receivew iosb = %d\n", rec_iosb.ios_icc$w_status);
      inmsg[rec_iosb.ios_icc$l_rcv_len] = 0;
      if(strlen(outmsg) > 0) strcat(outmsg, "\r\n");
      strcat(outmsg, inmsg);
      stat = sys$icc_transmitw(con, &tra_iosb, 0, 0, outmsg, strlen(outmsg));
      if((stat & 1) == 0) printf("sys$icc_transmitw stat = %d\n", stat);
      if((tra_iosb.ios_icc$w_status & 1) == 0) printf("sys$icc_receivew iosb = %d\n", tra_iosb.ios_icc$w_status);
    }
   else if(evttyp == ICC$C_EV_DISCONNECT)
   {
      printf("disconnect\n");
   }
}

int main(int argc, char *argv[])
{
   long appid;
   long stat;
   char dummy[2];
   $DESCRIPTOR(APPID, "MYCHANNEL");
   /* open association (listener) */
   stat = sys$icc_open_assoc(&appid, &APPID, 0, 0, handler, handler, 0, 0, 0);
   if((stat & 1) == 0) printf("sys$icc_open_assoc stat = %d\n", stat);
   /* wait for user input */
   printf("Press enter to exit");
   fgets(dummy, sizeof(dummy), stdin);
   /* close association (listener) */
   stat = sys$icc_close_assoc(appid);
   if((stat & 1) == 0) printf("sys$icc_close_assoc stat = %d\n", stat);
   return 0;
}
