--- cache.c.orig	Mon Dec 29 15:33:42 2003
+++ cache.c	Fri Jan 23 13:21:33 2004
@@ -34,9 +34,10 @@
  *      Internal Constants
  *
  ***********************************************************************/
-#define FTRNUM_START        100
-#define MINIMUM_FREE_SPACE  1024768
-#define MAX_DATA_SIZE       64000
+#define FTRNUM_START           100
+#define MINIMUM_FREE_SPACE     1024768
+#define MAX_DATA_SIZE          64000
+#define STORAGE_HEAP_LOCATION  0,1
 
 static const Char cacheDBName[] = "Plkr-Cache";
 
@@ -58,6 +59,7 @@
 static Err GetCacheNode( CacheType type, Int32 refID, CacheNode** refNode );
 static void RemoveCacheNodeRecord( CacheNode* node );
 static void RemoveCacheNode( CacheNode* node );
+static UInt32 StorageHeapFree ( void );
 
 
 /***********************************************************************
@@ -170,6 +172,12 @@
 {
     CacheNode* node;
 
+    while ( StorageHeapFree() < MINIMUM_FREE_SPACE && ListSize ( cache ) > 0 )
+        RemoveCacheNode( ListFirst( cache ) );
+
+    if ( StorageHeapFree() < MINIMUM_FREE_SPACE )
+        return errNone;
+
     node = SafeMemPtrNew( sizeof *node );
     MemSet( node, sizeof *node, 0 );
 
@@ -307,3 +315,22 @@
     if ( dbID != 0 )
         DmDeleteDatabase( cardNo, dbID );
 }
+
+
+
+static UInt32 StorageHeapFree ( void )
+{
+    UInt16  heapID;
+    UInt32  total;
+    UInt32  free;
+    UInt32  maxsize;
+
+    heapID  = MemHeapID( STORAGE_HEAP_LOCATION );
+    total   = MemHeapSize( heapID );
+    MemHeapFreeBytes( heapID, &free, &maxsize );
+    MSG( _( "Cache storage heap: %ld total, %ld used, %ld avail\n",
+            total, total - free, maxsize ) );
+
+    return free;
+}
+
