/*
 * t4exit.cpp --
 *
 *	Implementation of the T4Graph exit handler procedure and the
 *	T4Graph interpreter registry. This code ensures that when an
 *	interpreter is destroyed, if the interpreter has the last
 *	live reference to a storage, that storage will get closed.
 *
 *	Authors: Jacob Levy and Jean-Claude Wippler.
 *		 jyl@best.com	jcw@equi4.com
 *
 * Copyright (c) 2000-2003, JYL Software Inc.
 * 
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 * 
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE, EVEN IF
 * JYL SOFTWARE INC. IS MADE AWARE OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "t4graphrep.h"

/*
 * Forward declaration of the exit handler:
 */

static void	ExitProc(ClientData);

/*
 * Set up a T4Graph exit handler so that all storages available in all
 * interpreters get closed and potentially committed on exit.
 *
 * This procedure can be safely called multiple times and it will not
 * do anything the second and subsequent times it is called.
 */

void
T4Graph_SetupExitHandler()
{
	
    /*
     * If this call is setting up the storage registry, then also
     * set up the exit handler.
     */

    if (T4Graph_InitStorageRegistry()) {
	Tcl_CreateExitHandler(ExitProc, NULL);
    }
}

/*
 * The exit handler: this procedure iterates over the interpreter
 * registry and calls the interpreter delete procedure. Then, it
 * destroys the interpreter registry.
 */

static void
ExitProc(ClientData ignored)
{
    Tcl_HashSearch search;
    T4Storage *sp;

    /*
     * Iterate over all registered storages and forcefully close them.
     * Because the destructor unregisters the storage, we have to restart
     * the search for each iteration.
     */

    for (sp = T4Graph_FirstStorage(&search);
	 sp != NULL;
	 sp = T4Graph_FirstStorage(&search)) {
	delete sp;
    }

    /*
     * Destroy the storage registry.
     */

    T4Graph_DestroyStorageRegistry();
}
