/*
 * parse filename. return a linked list containing all the parsed
 * statements if successful, NULL if some error occurred. the
 * function automatically logs all errors
 */
section_t *parse (const char *filename)
{
   scan_t sc;
   section_t *section;
   int result;

   if ((section = (section_t *) mem_alloc (sizeof (section_t))) == NULL)
	 {
		log_printf (LOG_ERROR,"Out of memory\n");
		return (NULL);
	 }

   section->n = 0;
   section->name = NULL;
   section->stmt = NULL;
   section->child = NULL;

   log_printf (LOG_VERBOSE,"Opening configuration file: %s\n",filename);
   if (scan_open (&sc,filename) < 0)
	 {
		mem_free (section);
		return (NULL);
	 }

   result = parse_section (&section,&sc,NULL);
   if (result == FIN) log_printf (LOG_VERBOSE,"Successfully parsed configuration file\n");

   scan_close (&sc);
   log_printf (LOG_VERBOSE,"Closed configuration file\n");

   if (result == ERR) parse_destroy (&section);

   return (section);
}
/*
 * free all memory occupied by the specified parse structure
 */
void parse_destroy (section_t **section)
{
   if (section != NULL && *section != NULL)
	 {
		int i;

		if ((*section)->name != NULL) mem_free ((*section)->name);

		if ((*section)->stmt != NULL)
		  {
			 stmt_t *tmp,*prev = (*section)->stmt;

			 do
			   {
				  tmp = (*section)->stmt->next;
				  stmt_destroy (&(*section)->stmt);
				  (*section)->stmt = tmp;
			   }
			 while (prev != (*section)->stmt);

			 (*section)->stmt = NULL;
		  }

		for (i = 0; i < (*section)->n; i++)
		  if ((*section)->child[i] != NULL)
			parse_destroy (&(*section)->child[i]);

		if ((*section)->n) mem_free ((*section)->child);
		mem_free (*section);

		*section = NULL;
	 }
}
int html_parser::parse_init()
{

    outer_ = recode_new_outer(true);

    page_ = (char *) malloc(max_page_len + 1);
    buffer_conv_ = (char *) malloc(max_page_len + 1);

    title_ = (char *) malloc(max_title_len + 1);
    content_ = (char *) malloc(max_content_len + 1);
    links_ = (link_t *) malloc(sizeof(link_t) * (max_links_num + 1));


    tree_ = new html_tree(max_page_len + 1);

    if (page_ == NULL || title_ == NULL || buffer_conv_ == NULL ||
        content_ == NULL || links_ == NULL || tree_ == NULL)
        goto fail;

    page_[0] = '\0';
    content_[0] = '\0';
    title_[0] = '\0';

    buffer_conv_len_ = max_page_len + 1;

    return 0;

  fail:
    parse_destroy();
    return -1;
}
int main ()
{
   section_t *section;

   mem_open (NULL);
   log_open (NULL,LOG_NOISY,LOG_HAVE_COLORS | LOG_PRINT_FUNCTION);
   atexit (mem_close);
   atexit (log_close);

   if ((section = parse ("TEST.conf")) == NULL)
	 exit (EXIT_FAILURE);

   dump_sections (0,section);
   parse_destroy (&section);

   exit (EXIT_SUCCESS);
}
html_parser::~html_parser()
{

    parse_destroy();

}