#define  _USEOLDEXEC_ 1
#include <exec/types.h>
#include <exec/nodes.h>
#include <exec/memory.h>
#include <exec/resident.h>
#include <exec/libraries.h>
#include <exec/execbase.h>
#include <libraries/dos.h>
#include <proto/exec.h>
#include <proto/dos.h>
#include <string.h>

#include "fakefreeanim.h"

#define ONE_GLOBAL_SECTION

/* Prototypes */
ULONG __saveds __asm _LibExpunge( register __a6 struct FFAnimLibrary *libbase );
ULONG __saveds __asm _LibInit( register __a0 APTR seglist,
                                register __d0 struct FFAnimLibrary *libbase );
int __saveds __asm __UserLibInit(register __a6 struct FFAnimLibrary *libbase );
void __saveds __asm __UserLibCleanup(register __a6 struct FFAnimLibrary *libbase);
VOID __saveds LIBStopFakeAnim( VOID );

typedef LONG (*ffPFL)();   /* pointer to function returning 32-bit int        */

/* library initialization table, used for AUTOINIT libraries                */
struct InitTable {
        ULONG        *it_DataSize;       /* library data space size         */
        ffPFL        *it_FuncTable;      /* table of entry points           */
        APTR         it_DataInit;        /* table of data initializers      */
        ffPFL        it_InitFunc;        /* initialization function to run  */
};


/* symbols generated by blink */
extern char __far _LibID[];             /* ID string                        */
extern char __far _LibName[];           /* Name string                      */
extern char __far RESLEN;               /* size of init data                */
extern long __far NEWDATAL;             /* size of global data              */
extern long __far NUMJMPS;              /* number of jmp vectors to copy    */
extern ffPFL _LibFuncTab[];             /* ff function table                */
extern long __far _LibVersion;          /* Version of library               */
extern long __far _LibRevision;         /* Revision of library              */
#define FFVERSION ((long)&_LibVersion)
#define FFREVISION ((long)&_LibRevision)
#define DATAWORDS ((long)&NEWDATAL)     /* magic to get right tpye of reloc */ 
#define SIZEJMPTAB ((long)libbase->ff_origbase->ff_numjmps)
                                        /* size in bytes of jmp table       */

/* From libent.o, needed to determine where data is loaded by loadseg       */
extern long far _Libmergeddata; 

#define FFLIBRARYSIZE ((sizeof(struct FFAnimLibrary) +3) & ~3)



struct InitTable __far _LibInitTab =  {
        (long *)(&RESLEN+FFLIBRARYSIZE),
        _LibFuncTab,
        NULL,                        /* will initialize ff own data */
        _LibInit,
};

__saveds __asm
ULONG _LibInit( register __a0 APTR seglist,
        register __d0 struct FFAnimLibrary *libbase )
{
#ifdef ONE_GLOBAL_SECTION	// [
    long *reloc;
#endif				// ]
    long *sdata;
    char *ddata;
    long nrelocs;

      
    libbase->ff_SegList = (ULONG) seglist;

    /* init. library structure (since I don't do automatic data init.) */
    libbase->ff_Lib.lib_Node.ln_Type = NT_LIBRARY;
    libbase->ff_Lib.lib_Node.ln_Name =  _LibName;
    libbase->ff_Lib.lib_Flags = LIBF_SUMUSED | LIBF_CHANGED;
    libbase->ff_Lib.lib_Version = FFVERSION;
    libbase->ff_Lib.lib_Revision = FFREVISION;
    libbase->ff_Lib.lib_IdString = (APTR) _LibID;
#ifndef ONE_GLOBAL_SECTION	// [
    libbase->ff_relocs = NULL;
    libbase->ff_origbase = libbase;
#if 1	// [
    libbase->ff_numjmps = (long)&NUMJMPS;
#else	// ][
    sdata = (long *)_LibInitTab.it_FuncTable;

    libbase->ff_numjmps = 0;
    while (*sdata != -1)
    {
      libbase->ff_numjmps += 6;
      sdata++;
    }
#endif	// ]

#endif				// ]

     /* Start of copy of global data after structure */
    ddata = (char *)libbase + FFLIBRARYSIZE; 

    sdata = (long *)&_Libmergeddata; /* where loadseg loaded the data */
    memcpy(ddata, (void *)sdata, DATAWORDS*4);

    /* perform relocs if we want one global section for all programs */
    /* that have this lib open. If we want a global section for each */
    /* open, copy the relocs, and do them on each open call.         */
    sdata = sdata + DATAWORDS;
    nrelocs = *sdata;
#ifdef ONE_GLOBAL_SECTION	// [
    sdata++;
    while (nrelocs > 0)
    {
       reloc = (long *)((long)ddata + *sdata++);
       *reloc += (long)ddata;
       nrelocs--;
    }

#ifdef	OUTT	// [    
    if (__UserLibInit(libbase) != 0)
       return NULL; /* abort if user init failed */
#endif		// ]

#else				// ][
    if (nrelocs) 
    {
      if ((libbase->ff_relocs = AllocMem((nrelocs * 4) + 4, MEMF_PUBLIC)) == NULL)
        return 0;
      memcpy((void *)libbase->ff_relocs, (void *)sdata, (nrelocs * 4) + 4);
    }
#endif				// ]

    return ( (ULONG) libbase );
}

LONG __saveds __asm
_LibOpen( register __a6 struct FFAnimLibrary *libbase )
{
#ifndef ONE_GLOBAL_SECTION	// [
    struct ExecBase *SysBase = *(struct ExecBase **)4;
    char *newlib;
    long *sdata, *ddata, *reloc;
    long nrelocs;
#endif				// ]

    /* mark us as having another customer */
    libbase->ff_Lib.lib_OpenCnt++;

    /* clear delayed expunges (standard procedure)                */
    libbase->ff_Lib.lib_Flags &= ~LIBF_DELEXP;

#ifndef ONE_GLOBAL_SECTION	// [
    /* Allocate new lib base */
    newlib = AllocMem((long)(FFLIBRARYSIZE + 
                             ((long)&RESLEN) + SIZEJMPTAB), 
                             MEMF_PUBLIC|MEMF_CLEAR);

    if (newlib == NULL) goto error;
        
    /* copy over data */
    memcpy(newlib, (char *)libbase - SIZEJMPTAB, 
           (long)(FFLIBRARYSIZE + DATAWORDS*4 + SIZEJMPTAB));
    
    libbase = (struct FFAnimLibrary *)(newlib+SIZEJMPTAB);
    libbase->ff_relocs = NULL;
    
    /* perform relocs */       
    ddata = (long *)((char *)libbase + FFLIBRARYSIZE); 
    sdata = libbase->ff_origbase->ff_relocs;
    if (sdata)
    {
       nrelocs = *sdata++;
       while (nrelocs > 0)
       {
          reloc = (long *)((long)ddata + *sdata++);
          *reloc += (long)ddata;
          nrelocs--;
       }
    }
              
    if (__UserLibInit(libbase) != 0)
    {
       FreeMem(newlib, (long)(FFLIBRARYSIZE + 
                             ((long)&RESLEN) + SIZEJMPTAB));
error:
       libbase->ff_Lib.lib_OpenCnt--;
       return NULL; /* abort if user init failed */
    }
    
    /* now we need to flush the cache because we copied the jmp table */
    if (SysBase->LibNode.lib_Version >= 36) 
      CacheClearU();

#else				// ][
    if (__UserLibInit(libbase) != 0)
       return NULL; /* abort if user init failed */

#endif				// ]

    return ( (LONG) libbase );
}

ULONG __saveds __asm
_LibClose( register __a6 struct FFAnimLibrary *libbase )
{
    ULONG retval = 0;
    
#ifndef ONE_GLOBAL_SECTION	// [
    struct FFAnimLibrary *origbase;
    if (libbase != libbase->ff_origbase)
    {
       __UserLibCleanup(libbase);
       origbase = libbase->ff_origbase;
       FreeMem((char *)libbase-SIZEJMPTAB, 
               (long)(FFLIBRARYSIZE + ((long)&RESLEN)+SIZEJMPTAB));
       libbase = origbase;
    }

#else				// ][
     __UserLibCleanup(libbase);

#endif				// ]

    LIBStopFakeAnim();

    if (( --libbase->ff_Lib.lib_OpenCnt == 0 ) &&
                        ( libbase->ff_Lib.lib_Flags & LIBF_DELEXP ))
    {
        /* no more people have me open,
         * and I have a delayed expunge pending
         */
         retval = _LibExpunge( libbase ); /* return segment list        */
    }

    return (retval);
}

ULONG __saveds __asm
_LibExpunge( register __a6 struct FFAnimLibrary *libbase )
{
    ULONG seglist = 0;
    LONG  libsize;

#ifndef ONE_GLOBAL_SECTION	// [
    libbase = libbase->ff_origbase;
#endif				// ]

    libbase->ff_Lib.lib_Flags |= LIBF_DELEXP;
    if ( libbase->ff_Lib.lib_OpenCnt == 0 )
    {
        /* really expunge: remove libbase and freemem        */
#ifndef ONE_GLOBAL_SECTION	// [
        if (libbase->ff_relocs)
           FreeMem(libbase->ff_relocs, (*libbase->ff_relocs * 4) + 4);
#else				// ][

#ifdef	OUTT	// [

        __UserLibCleanup(libbase);

#endif		// ]

#endif				// ]
        seglist = libbase->ff_SegList;

        Remove( (struct Node *) libbase);

        libsize = libbase->ff_Lib.lib_NegSize + libbase->ff_Lib.lib_PosSize;
        FreeMem( (char *) libbase - libbase->ff_Lib.lib_NegSize,(LONG) libsize );
    }

    /* return NULL or real seglist                                */
    return ( (ULONG) seglist );
}

