#ifndef XPKMASTER_SUBLIBS_C
#define XPKMASTER_SUBLIBS_C

/* Routinesheader

	Name:		sublibs.c
	Main:		xpkmaster
	Versionstring:	$VER: sublibs.c 1.3 (26.03.1998)
	Author:		SDI
	Distribution:	Freeware
	Description:	Handling of xpksublibraries

 1.0   09.10.96 : first real version
 1.1   19.12.97 : a bit code cleanup
 1.2   09.01.98 : included idfromname from util.c
 1.3   26.03.98 : a little bug fix, internal toupper function
*/

#include <proto/exec.h>
#include <proto/xpksub.h>
#include <exec/types.h>
#include <dos/dos.h>
#include "xpkmaster.h"
#include "texts.h"
#include "version.h"

/************************* open sublib from ID ***************************/
XPK_ALLINONE struct Library *opensub(struct XpkBuffer *xbuf, ULONG ID)
{
  struct Library *XpkSubBase;
  UBYTE libname[SUBLIBNAME_SIZE];

  /* Do nothing if we already have what we want */
  if((xbuf->xb_SubBase) && (xbuf->xb_SubID == ID))
    return xbuf->xb_SubBase;

  closesub(xbuf);

  xbuf->xb_SubID = ID;
  sprintf(libname, SUBLIBNAME_STRING, &xbuf->xb_SubID);

  if(!(xbuf->xb_SubBase = XpkSubBase = OpenLibrary(libname, 0)))
    xbuf->xb_Result = XPKERR_MISSINGLIB;
  else if((xbuf->xb_SubInfo = XpksPackerInfo())->xi_MasterVersion > VERSION)
  {
    xbuf->xb_Result = XPKERR_OLDMASTLIB;
    closesub(xbuf);
  }
  return xbuf->xb_SubBase;
}

/*********************** close any open sub-library *********************/
XPK_ALLINONE void closesub(struct XpkBuffer *xbuf)
{
  if(xbuf->xb_SubBase)
  {
#ifdef DEBUG
    DebugRunTime("closesub: closing lib %.4s", &xbuf->xb_SubID);
#endif
    CloseLibrary(xbuf->xb_SubBase);
    xbuf->xb_SubBase = 0;
  }
}

/********************** get ID number from string ***********************/

static UBYTE xpkupper(UBYTE c)
{
  if(c >= 'a' && c <= 'z')
    c -= 'a'-'A';
  return c;
}

XPK_ALLINONE ULONG idfromname(STRPTR name)
{
  ULONG i, j=0;

  for(i = 4; i; i--)
  {
    j <<= 8;
    j += xpkupper(*(name++));
  }

  return j;
}

#endif /* XPKMASTER_SUBLIBS_C */
