/* $Id: cleanup.c,v 1.1 1993/11/17 12:21:51 too Exp $
 *
 * Copyright (c) 1993 AmiTCP/IP Group <amitcp-group@hut.fi>
 *
 * Created: Wed Nov 10 13:48:06 1993 too
 * Last modified: Wed Nov 17 14:19:14 1993 too
 */
{
  {
    int i;
    int subcount;
    
    for (i = 0, subcount = 0; i < nfds; i++) {
      struct ApplPort * applport = applarray[i];
      if (applport->ap_Pw) {
	ReplyPkt(applport->ap_Pw->pw_Packet, 0, 0);
	FreeMem(applport->ap_Pw, sizeof (struct PendingWrites));
      }
      if (applport->ap_Packet)
	switch (applport->ap_Packet->dp_Type) {
	case ACTION_FINDINPUT:
	case ACTION_FINDOUTPUT: /* listening and holding Open() packet */
	case ACTION_FINDUPDATE:
	  ReplyPkt(applport->ap_Packet, DOSFALSE, ERROR_NO_MORE_ENTRIES);
	  FreeMem(applport, sizeof (struct ApplPort));
	  subcount++;
	  break;
	case ACTION_WAIT_CHAR:
	  Abort_Timeout(&applport->ap_Tr);
	  /* FALL THROUGH... */
	default: /* perhaps only ACTION_READ */
	  ReplyPkt(applport->ap_Packet, 0, 0);
	}
    }
    nfds -= subcount;
  }
  For_Each_List_Item_CacheNext(&freeappllist, void *, item,
			       FreeMem(item,
				       sizeof (struct ApplPort)); );
  For_Each_List_Item_CacheNext(&freewritelist, void *, item,
			       FreeMem(item,
				       sizeof (struct PendingWrites)); );
  sigmask = myportflag | applportflag;
  while(nfds > 0) {
    ULONG smask = Wait(sigmask);
    if (smask & myportflag) {
      struct Message * msg;
      /*
       * New Open() packets. Reply w/ FALSE immediately.
       */
      while((msg = GetMsg(mymsgport)) != NULL)
	ReplyPkt(msgToPkt(msg), DOSFALSE, ERROR_NO_MORE_ENTRIES);
    }
    if (smask & applportflag) {
      /*
       * Packets to ports of applications. Handle Close() packets.
       */
      while(applcbcur != applcbpos) {
	struct Message * msg;
	struct ApplPort * applport;

	applport = directIndex(struct ApplPort *, applcbbuf, applcbcur);
	applcbcur += sizeof (struct ApplPort *);
	applcbcur &= 0x3f * sizeof (struct ApplPort *);

	if ((msg = GetMsg(&applport->ap_AMP.amp_Msgport)) != NULL) {
	  struct DosPacket * packet = msgToPkt(msg);

	  DP("pktType: %ld", packet->dp_Type);
	  switch(packet->dp_Type) {
	  case ACTION_END:
	    if (--applport->ap_OpenCnt == 0) {
	      FreeMem(applport, sizeof (struct ApplPort));
	      nfds--;
	    }
	    ReplyPkt(packet, DOSTRUE, 0);
	    break;
	  default:
	    ReplyPkt(packet, DOSFALSE, ERROR_NO_MORE_ENTRIES);
	    break;
	  }
	}
      }
    }
  }
  mydev->dol_Task = 0; /* ATOMIC */
  /*
   * Check if there is still some Open() packets.
   */
  {
    struct Message * msg;
    while((msg = GetMsg(mymsgport)) != NULL)
      ReplyPkt(msgToPkt(msg), DOSFALSE, ERROR_NO_MORE_ENTRIES);
  }
}
