/*
  Public domain 							
  Compile with gcc `xml2-config --cflags --libs` -o xmlparser xmlparser.c
*/

#include <stdio.h>
#include <stdlib.h>
#include <libxml/parser.h>

#if defined(LIBXML_TREE_ENABLED) && defined(LIBXML_OUTPUT_ENABLED)
int
main(int argc, char *argv[])
{
	xmlDocPtr doc;
	xmlChar *xmlbuf;
	int bufsize, i, indentspaces=1;
	xmlChar *ptr;

	if (argc != 2 && argc != 3) {
		fprintf(stderr, "Usage: %s <xmlfile> [number of indent spaces in multiples of 2 (default 1x)]\n",argv[0]);
		exit(EXIT_FAILURE);
	}
	if (argc == 3)
		indentspaces = atoi(argv[2]);

	doc = xmlReadFile(argv[1], NULL, 0);
	if (doc == NULL) {
		perror(argv[1]);
		exit(EXIT_FAILURE);
	}

	xmlDocDumpFormatMemory(doc, &xmlbuf, &bufsize, 1);

	if (indentspaces == 1)
		printf((char *) xmlbuf);
	else {
		for (ptr=xmlbuf ; ptr < xmlbuf + bufsize; ptr++) {
			fputc((int) *ptr, stdout);
			if ((char) *ptr == '\n') {
				ptr++;
				while ((char) *ptr == ' ' && ptr < xmlbuf + bufsize) {
					for (i = 0 ; i < indentspaces; i++)
						fputc((int) ' ', stdout);
					ptr++;
				}
				ptr--;
			}
		}

	}

	xmlFree(xmlbuf);
	xmlFreeDoc(doc);

	xmlCleanupParser();

	exit(EXIT_SUCCESS);
}

#else

int
main(void)
{
	fprintf(stderr, "Your libxml2 installation needs to be compiled with tree and output support for this tool to work\nAborting.\n");
	exit(EXIT_FAILURE);
}

#endif
