---------------------------------------------------------------------------
-- Embedded Library Registration Stub
-- 
-- Written by Iriel <iriel@vigilance-committee.org>
--
-- Version 0.1 - 2006-03-05
---------------------------------------------------------------------------
-- To use this for your own AddOns, copy this file and then edit only the
-- section at the bottom with the appropriate library name(s).
---------------------------------------------------------------------------
local stub = {};

-- Instance replacement method, replace contents of old with that of new
function stub:ReplaceInstance(old, new)
   for k,v in pairs(old) do old[k]=nil; end
   for k,v in pairs(new) do old[k]=v; end
end

-- Get a new copy of the stub
function stub:NewStub()
  local newStub = {};
  self:ReplaceInstance(newStub, self);
  newStub.lastVersion = '';
  newStub.versions = {};
  return newStub;
end

-- Get instance version
function stub:GetInstance(version)
   if (not version) then version = self.lastVersion; end
   local versionData = self.versions[version];
   if (not versionData) then
      message("Cannot find library instance with version '" 
              .. version .. "'");
      return;
   end
   return versionData.instance;
end

-- Register new instance
function stub:Register(newInstance)
   local version,minor = newInstance:GetLibraryVersion();
   self.lastVersion = version;
   local versionData = self.versions[version];
   if (not versionData) then
      -- This one is new!
      versionData = { instance = newInstance,
         minor = minor,
         old = {} 
      };
      self.versions[version] = versionData;
      newInstance:LibActivate(self);
      return newInstance;
   end
   if (minor <= versionData.minor) then
      -- This one is already obsolete
      if (newInstance.LibDiscard) then
         newInstance:LibDiscard();
      end
      return versionData.instance;
   end
   -- This is an update
   local oldInstance = versionData.instance;
   local oldList = versionData.old;
   versionData.instance = newInstance;
   versionData.minor = minor;
   local skipCopy = newInstance:LibActivate(self, oldInstance, oldList);
   table.insert(oldList, oldInstance);
   if (not skipCopy) then
      for i, old in ipairs(oldList) do
         self:ReplaceInstance(old, newInstance);
      end
   end
   return newInstance;
end

----------------------------------------------------------------------------
-- PUT LIBRARY INSTANCES HERE
--
-- if (not LibName) then LibName = stub:NewStub(); end
-- Follow all with stub = nil

-- Set up IrielVirtualFrames (IrielPrototype-2-dev/617)
if (not IrielVirtualFrames) then IrielVirtualFrames = stub:NewStub(); end

-- Release stub to gc
stub = nil;
