#include "config.h"

#include "xml/from-txt.h"
#include "xml/pathnode.h"
#include "xml/listnode.h"
#include "xml/dumpnode.h"
#include "xml/addsnode.h"
#include "xml/gerror.h"
#include <stdlib.h>
#include <string.h>

#ifdef HAVE_LIBPCRE
#include <pcre.h>

#define ___ {
#define ____ }

typedef struct
{
    pcre*        regex;
    const gchar* markup;
    int          ovector[33];
}
 Data;
void func (xml_GNode* node, gpointer data)
{
    Data* use = data;
    if (node->off == node->end) return;
    if (! node->text) return;

    ___ int rc; int off = node->off;
 again:
    /* plus we can use lookbehind assertions for the substring: uhm, GOOD ? */
    rc = pcre_exec (use->regex, 0, node->text->str, node->end, off, 
		    0, use->ovector, 33);
    if (rc < 0) return;

    if (rc) 
    
{
	/* g_printerr ("[%i..%i]", use->ovector[0], use->ovector[1]); */
	xml_tree_add2 (node, use->markup, use->ovector[0], use->ovector[1]);
	/* g_print ("'"); xml_tree_to_xml_file (node, 0); g_print ("'\n"); */
	off = use->ovector[1];
	goto again;
    }
____; }
int
main (int argc, char** argv)
{
    xml_g_set_prgname(argv[0]); 

    if (argc < 4)
    
{
	g_printerr ("> %s filename xpath regex [markup] [options]\n"
		    "\t walk the tree looking for nodes matching the xpath\n"
		    "\t specification - even in an abbreviated form it\n"
		    "\t can match a number of nodes. On each substring the\n"
		    "\t given perl-regex will be run and any result area\n"
		    "\t will be marked with that markup.\n"
		    "\t the default markup is Q\n",
		    g_get_prgname());
	return 1;
    }
___ gchar *filename = 0; const gchar *xpath = 0, *regex = 0, *markup = 0, *styleflag = "";
{   int i ; for (i=1; i < argc ; i++) 
{
	if (argv[i][0] == '-') 
{ styleflag = argv[i]; continue; }
if (! filename)
{ filename = argv[i]; continue; }
if (! xpath)
{ xpath = argv[i]; continue; }
if (! regex)
{ regex = argv[i]; continue; }
if (! markup)
{ markup = argv[i]; continue; }
g_warning ("extra argument on commandline, ignored: %s", argv[i]); }
}
if (! markup) markup = "Q"; ___ xml_GNode* tree; GError* error = 0; tree = xml_g_markup_parse_file (0, filename, &error); if (error) xml_g_show_error (&error, "after parsing file:\n\t'%s'", filename); ___ int style = xml_path_CANON; if (strstr (styleflag, "-match")) style = xml_path_MATCH; if (strstr (styleflag, "-strict")) style = xml_path_STRICT; if (strstr (styleflag, "-canon")) style = xml_path_CANON; ___ auto const char* errmsg; int erridx; pcre* compiled = pcre_compile (regex, 0, &errmsg, &erridx, 0); if (! compiled) g_error ("errornous regex: %s\n", errmsg); ___ auto Data data =
{ compiled, markup }
; xml_path_node_foreach (tree, xpath, func, &data); /* and print the result */ xml_tree_node_to_xml_file (tree, 0); return 0; ____;____;____;____;____; }
#else
int main (int argc, char** argv)
{
    g_error ("%s: no pcre lib was found during configure", argv[0]);
    return 63;
}
#endif
/* 
   Local variables:
   c-file-style: "stroustrup"
   End:
 */