/**********************************************************************
 
	Copyright (C) 2003 Hirohisa MORI <joshua@nichibun.ac.jp>
 
	This program is free software; you can redistribute it 
	and/or modify it under the terms of the GLOBALBASE 
	Library General Public License (G-LGPL) as published by 

	http://www.globalbase.org/
 
	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.

**********************************************************************/



#include	<stdio.h>
#include	"xl.h"
#include	"pri_level.h"
#include	"rcache.h"
#include	"memory_debug.h"
#include	"gbview.h"
#include	"win_flame.h"
#include	"cosmos.h"
#include	"init.h"
#include	"save_global.h"
#include	"ex_utils.h"
#include	"http.h"
#include	"HTMLDB.h"
#include	"matrix.h"

#include	"v/v.h"
#include	"v/vobj_utils.h"

void v_loop_init();
void main_task();
void stop_loop();
void quit_task();


void
v_loop_init()
{
XL_INTERPRETER * xli;
	xli = new_xl_interpreter();
	xli->a_type = XLA_SELF;
	setup_i(xli);
}

void
main_task()
{
XL_INTERPRETER * xli;
	xli = new_xl_interpreter();
	xli->a_type = XLA_SELF;
	setup_i(xli);

	loading_file(0, l_string(std_cm,"local"), 1);

//		if ( view_agent_switch == 0 )
//			start_gbview();

	call_window_function("main-window");

}



void stop_loop()
{
  for ( ; ; )
    sleep_sec(1);
}


int
_main(int argc,char ** argv)
{
/*
GBVIEW_FLAME * gf;
GBVIEW_STATUS sts;
*/

	if ( argc < 2 ) {
		fprintf(stderr,"too few argment\n");
		exit(1);
	}
	if ( strcmp(argv[1],"v") == 0 ) {
		init_sg();

		view_init(argc,argv);
		init_ex_language(gblisp_top_env1);

		vobject_init_gb(&argc, &argv);
		init_vobj_function_gb();
		
		vobject_quit_callback = client_quit;
/*
		gf = wf_new_gf();
		wf_init_status(&sts);
		sts.flags = SF_RADAR;
		wf_set_status(gf,&sts);
*/
		init_http_server();
		init_polling_class(gblisp_top_env0);
		init_html_db();



		set_rcache_dir_path(
			l_string(std_cm,get_preference_path()),
			l_string(std_cm,"cache"));
		enable_rcache(RCF_ALL);

		open_control_port();

		create_task(main_task,0,PRI_FETCH);

		end_sg();
/*
		wf_init_status(&sts);
		sts.flags = SF_STATUS;
		sts.status = GVFS_ACTIVE;
		wf_set_status(gf,&sts);
*/
		event_task();
	}
	else if ( strcmp(argv[1],"i") == 0 ||
		  strcmp(argv[1],"o") == 0 ) {
		if ( argc < 3 ) {
			fprintf(stderr,"too few argment\n");
			exit(1);
		}
		ipc_init(argc,argv);
		ipc_system(argc,argv);
	}
	else {
		fprintf(stderr,"invalid argment %s\n",
			argv[1]);
		exit(1);
	}
	exit(0);
	return 0;
}

int
client_quit()
{
static int quit_flag = 0;
	if ( quit_flag )
		return 1;
	quit_flag = 1;
	create_task(quit_task,0,PRI_QUIT);
	return 0;	// stop vobject_quit
}


void
quit_task()
{
int vobject_quit();
XL_INTERPRETER * xli;

	xli = new_xl_interpreter();
	xli->a_type = XLA_SELF;
	setup_i(xli);

	rcache_stop();
	disable_rcache();
	close_all_matrix();
	vobject_quit();
}


