/*
 *   Pure Data Packet system implementation: setup code
 *   Copyright (c) by Tom Schouten <tom@zwizwa.be>
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program; if not, write to the Free Software
 *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 */

#include <stdio.h>
#include <pf/config.h>
#include <pf/stream.h>
#include <pf/list.h>
#include <pf/forth.h>
#include <pf/string.h>


/* all symbols are C style */
#ifdef __cplusplus
extern "C"
{
#endif

/* module setup declarations (all C-style) */

/* pf system / internal stuff */
void pf_debug_setup(void);
void pf_list_setup(void);
void pf_forth_setup(void);
pf_error_t pf_forth_library_setup(pf_list_t *args);
//pf_error_t pf_forth_user_setup(void);
void pf_symbol_setup(void);
void pf_type_setup(void);
void pf_packet_setup(void);
void pf_string_setup(void);
void pf_image_setup(void);
void pf_hash_setup(void);


void forth_vm_debug(void);


static int nb_inits = 0;

// FIXME: add cleanup to detect memory leaks
// this would require module unloading too..

/* library setup routine */
pf_error_t pf_init(int argc, char **argv){
    

    /* check for multiple inits */
    if (nb_inits++) {
	pf_post("libpf: already initialized %d", nb_inits);
	PF_ASSERT(0 && "already initialized");
	return e_idle;
    }
    else{
	//pf_post("libpf: initializing");
    }


    /* setup pf system */

    /* boot kernel */
    pf_debug_setup();    // setup debugging
    pf_symbol_setup();   // symbol object
    pf_list_setup();     // list+atom objects
    pf_hash_setup();     // pointer (int) hash object
    pf_type_setup();     // packet type handling
    pf_packet_setup();   // packet memory management
    pf_string_setup();   // pf string type
    pf_forth_setup();       // forth vm core 
    pf_image_setup();    // pf image type


    pf_list_t *arg_list = pf_list_new();
    while ((--argc) != -1){
	pf_list_push_packet(arg_list, pf_packet_stringf("%s", argv[argc]));
    }
    
    /* run forth extension code */
    return pf_forth_library_setup(arg_list);

    /* run user rc script */
    //return pf_forth_user_setup();


}

#ifdef __cplusplus
}
#endif
