/**********************************************************************
 
	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	"stream.h"
#include	"xl2pdb_p.h"
#include	"avt.h"

extern CODE_INDEX *code_index;
extern AVT_NODE * pdb_same_name_avt;
char info_file[INFO_FILENAME_SIZE];

STREAM *
open_info_file(int argc,char ** argv)
{
int i;
STREAM *fd;
	for ( i = 0 ; i < argc ; i ++ )
		if ( strcmp(argv[i],"/") == 0 )
			break;
	if ( i == argc )
		fd = 0;
	else {
		i ++;
		if ( i == argc )
			fd = 0;
	 	else {
			strcpy(info_file,argv[i]);
			for ( i = strlen(info_file)-1 ; i >= 0 ; i -- ) {
				if ( info_file[i] == '.' )
					break;
				if ( info_file[i] == '/' )
					break;
			}
			if ( i <= 0 || info_file[i] != '.' )
				i = strlen(info_file);
			strcpy(&info_file[i],".inf");
			fd = s_open_file(info_file,
				O_RDWR|O_CREAT|O_TRUNC,0644);
			if ( fd < 0 ) {
				fprintf(stderr,"cannot open the file\n");
				perror(info_file);
				exit(1);
			}
		}
	}
	return fd;
}

int
info_func(AVT_NODE * a,STREAM ** fd)
{
PDB_POLYGON2D * p, * pp;
unsigned int fofs;
XL_SEXP * sym;
char buf[32];
unsigned int code;
	pp = p = a->data;
	code = p->code/NO_PITCH;
	code_index[code].fofs = s_seek_file(*fd,0,SEEK_CUR);
	sprintf(buf,"%i",p->code/NO_PITCH);
	for ( ; p ; p = p->samename ) {
		if ( p->info ) {
			sym = car(p->info);
			set_attribute(sym,
				l_string(std_cm,"code"),
				l_string(std_cm,buf));
			print_sexp(*fd,p->info,PF_LISP);
			s_printf(*fd,"\n");
			s_flush(*fd);
			code_index[code].minrect = pp->minrect;
			return 0;
		}
	}
	s_printf(*fd,
		"([information code=\"%i\" name=\"%s\" scheme=\"null\"])\n",
		code*NO_PITCH,
		n_string(std_cm,pp->name),
		n_string(std_cm,pp->subname));

	s_flush(*fd);
	code_index[code].minrect = pp->minrect;
	return 0;
}

void
output_info(int argc,char ** argv)
{
STREAM * fd;

	fd = open_info_file(argc,argv);
	avt_trace_from_small(pdb_same_name_avt,info_func,&fd);
	s_printf(fd,"(end-of-information-file)\n");
	s_close(fd);
}
