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

#include <dlg/resman.h>

#include <link/io.h>

#include <proto/dlg.h>
#include <proto/exec.h>

#include <pragmas/dlg.h>

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


extern   struct   List        LangList;
extern   struct   Library    *DLGBase;

struct LangNode  *RMLoadLang(char *);
BOOL              FreeLang(struct LangNode *);


/// RMLoadLang
struct LangNode *RMLoadLang(char *name)
{
   char   filename[64];
   char  *mem;
   ULONG  size;
   ULONG  adr;
   struct LangNode   *tn;
   struct LangStruct *ls;
   short  count;

   if (tn = (struct LangNode *)IFindName(&LangList,name))
   {
      tn->opencount++;
      return(tn);
   }

   ASPrintf(NULL, filename, "DLGCONFIG:Languages/%.20s.dat", name);
   if (FileSize(filename, &size)==-1)  return(NULL);
   if (!size)                          return(NULL);

   tn = (struct LangNode *)malloc(sizeof(struct LangNode));
   if (!tn)  return(NULL);

   tn->opencount    =   1;
   ls               = &(tn->ls);
   tn->node.ln_Name = ls->name;
   strcpy(ls->name, name);

   mem = malloc(size);

   if (!mem)
   {
      free(tn);
      return(NULL);
   }

   GetFirstStruct(filename, mem, size);
   movmem(mem, &(ls->numstrings), 2);

   ls->strings = (char **)((long)mem + 2L);
   adr         = (long)mem + (long)(ls->numstrings)*4L+2L;

   for(count=0; count < ls->numstrings; count++)
   ls->strings[count] = (char *)((long)(ls->strings[count])+adr);

   AddTail(&LangList, (struct Node *)tn);
   return(tn);
}
//-

/// FreeLang
BOOL FreeLang(struct LangNode *ln)
{
   struct LangStruct *ls;

   if(ln->opencount > 1)
   {
      ln->opencount = ln->opencount - 1;
      return(FALSE);
   }

   ln->opencount = ln->opencount - 1;

   ls = &(ln->ls);
   free((char *)((long)ls->strings - 2));

   if (IFindName(&LangList,ln->node.ln_Name))
   Remove((struct Node *)ln);

   return(TRUE);
}
//-
