/*
 * Code to initialise the VMarray. 
 * 
 * 1) Open an empty disk file.
 * 2) Initialise a structure holding a pointer to the free list, and
 *    the file handle.
 * 3) Initialise the free list with the special dummy entry containing a
 *    pointer to the end of the file, and a maximum size of zero.
 */

#include "vm.h"

struct VM_Construct *
VM_Open(char *VM_Filename) {
   BPTR VM_File ;
   struct VM_Construct *VM_C ;
   struct VM_FreeList *VM_F ;

   VM_File = TOpen(VM_Filename,MODE_NEWFILE) ;
   if (!VM_File) 
      return NULL ;

   VM_C = (struct VM_Construct *)
          TMemAlloc( sizeof(struct VM_Construct), MEMF_PUBLIC) ;
   if (!VM_C) {
      FreeTrackedItem((void *)VM_File) ;
      return NULL ;
      }

   VM_C->VM_File = VM_File ;
   VM_C->VM_FileName = VM_Filename ;
   VM_C->VM_Length = 0 ;

   VM_F = (struct VM_FreeList *)
          TMemAlloc( sizeof(struct VM_FreeList), MEMF_PUBLIC) ;
   if (!VM_F) {
      FreeTrackedItem((void *)VM_File) ;
      FreeTrackedItem(VM_C) ;
      return NULL ;
      }

   VM_F->VM_Next = NULL ;
   VM_F->VM_Offset = 0 ;
   VM_F->VM_Length = 0 ;

   VM_C->VM_FreeList = VM_F ;
   VM_C->VM_NumLocks = 0 ;
   NewList((struct List *) &(VM_C->VM_LockList)) ;

   return VM_C ;
   }

ULONG
VM_Close(struct VM_Construct *VM_C) {

   ULONG Err ;

   if (VM_C) {
      if (VM_C->VM_NumLocks) {
	 Err = VM_FlushLockList(VM_C) ;
	 if (Err)
	    return -1 ;
         }

      VM_FlushFreeList(&(VM_C->VM_FreeList)) ;
      FreeTrackedItem((void *)VM_C->VM_File) ;
      DeleteFile(VM_C->VM_FileName) ;
      VM_C->VM_File = NULL ;
      FreeTrackedItem(VM_C) ;
      }
   }
