#include <stdlib.h>

#include <dlg/resman.h>

#include <link/io.h>

#include <proto/exec.h>

extern   struct   List  ResourceList;

extern   struct   Node       *IFindName(struct List *, char *);


struct AreaNode    *FindTheArea(struct RMMessage *,UBYTE);
void                RemoveArea(struct RMMessage *);
BOOL                LockInQueue(struct List *);


struct AreaNode *FindTheArea(struct RMMessage *message,UBYTE cflag)
{
   struct AreaNode *area;
   struct List *lst;
   char name[8];

   lst=&ResourceList;

   ASPrintf(NULL,name,"%c%.5ld",(message->flags&FILELOCK)?'F':'M',(signed short)message->area);

   if(area=(struct AreaNode *)IFindName(lst,name)) return(area);

   if(!cflag) return(NULL);

   area=(struct AreaNode *)malloc(sizeof(struct AreaNode));

   area->area=message->area;

   area->mn.users=0;
   area->mn.type=0;
   area->mn.node.ln_Type=(message->flags&FILELOCK)?NODE_FAREA:NODE_MAREA;
   area->mn.node.ln_Name=(char *)malloc(8);
   ASPrintf(NULL,area->mn.node.ln_Name,"%.5s",name);

   NewList(&(area->mn.locklist));
   NewList(&(area->mn.activelocks));

   AddTail(lst,(struct Node *)area);

   return(area);
}

void RemoveArea(struct RMMessage *message)
{
   struct List *lst;
   struct AreaNode *area;
   char name[6];

   lst=&ResourceList;

   ASPrintf(NULL,name,"%c%.5ld",(message->flags&FILELOCK)?'F':'M',(signed short)message->area);

   if(area=(struct AreaNode *)IFindName(lst,name))
   {
      Remove((struct Node *)area);
      free(area->mn.node.ln_Name);
      free(area);
   }
}

BOOL LockInQueue(struct List *locklist)
{
   struct AreaLock *al;
   struct Node *nd;

   nd=locklist->lh_Head;

   while(nd->ln_Succ)
   {
      al=(struct AreaLock *)nd;

      if(!(al->type&QUICKLOCK)) return(TRUE);

      nd=nd->ln_Succ;
   }

   return(FALSE);
}


