#!/usr/bin/env perl
#
#
#

use strict;
use warnings;
use WWW::Curl::Easy;
use XML::LibXML;

my $nist_url = "http://physics.nist.gov/cgi-bin/Star/compos.pl?matno=";

my $curl = WWW::Curl::Easy->new;

#goto compounds;

open (OUTPUT, ">", "../densities.dat");
for (my $i = 1 ; $i <= 98 ; $i++) {

	my $url = sprintf("%s%03i.html", $nist_url, $i);
	print "URL: ".$url."\n";

	#use curl to download the files
	$curl->setopt(CURLOPT_URL, $url);
	my $html_file;

	$curl->setopt(CURLOPT_WRITEDATA, \$html_file);
	my $rv = $curl->perform;
	if ($rv != 0) {
		printf "Curl error for file %s: %s\n", $url, $curl->getinfo(CURLINFO_HTTP_CODE);
		exit 1;
	}

	
	#work with html_file
	my $dom = XML::LibXML->load_html(string => $html_file, recover => 1, suppress_errors => 1);
	my $xpc = XML::LibXML::XPathContext->new($dom);
	my $density = $xpc->findvalue("//body/center/table/tr[1]/td[2]");

	#printf "Density element %i is %f g/cm3\n", $i, $density;
	printf OUTPUT "%i\t%f\n", $i, $density;

} 
close OUTPUT;

compounds:


open (OUTPUT_INT, ">", "../../src/xraylib-nist-compounds-internal.h");
open (OUTPUT_HEADER, ">", "../../include/xraylib-nist-compounds.h");

my $header_begin = <<'HEADER';
/*
Copyright (c) 2013, Tom Schoonjans
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
    * The names of the contributors may not be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY Tom Schoonjans ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Tom Schoonjans BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

/*
 * This file was automatically generated by nist-compounds.pl
 * Modify at your own risk...
 */



#include "xraylib-parser.h"


#ifndef XRAYLIB_NIST_COMPOUNDS_H
#define XRAYLIB_NIST_COMPOUNDS_H


struct compoundDataNIST {
	char *name;
        int nElements;
        int *Elements;
        double *massFractions;
        double density;
};


/*
 *
 * Returns a pointer to a newly allocated struct containing
 * the requested compound on success, or NULL when the compound
 * was not found in the list. The compound is requested by providing
 * its name as argument to the function. For a list of available names,
 * use GetCompoundDataNISTList.
 *
 * The returned struct should be freed after usage with FreeCompoundDataNIST.
 *
 */
struct compoundDataNIST *GetCompoundDataNISTByName(const char compoundString[]);

/*
 *
 * Returns a pointer to a newly allocated struct containing
 * the requested compound on success, or NULL when the compound
 * was not found in the list. The compound is requested by providing
 * its index in the internal table to the function. Typically this would
 * be done using the NIST_COMPOUND_* macros in this file.
 *
 * The returned struct should be freed after usage with FreeCompoundDataNIST.
 *
 */
struct compoundDataNIST *GetCompoundDataNISTByIndex(int compoundIndex);

/*
 *
 * Returns a NULL-terminated array of strings of all the compounds in the
 * internal table. If nCompounds is not NULL, it shall receive the number 
 * of compounds.
 *
 * The returned array should be freed firstly by using xrlFree to deallocate
 * all individual strings, and subsequently by using xrlFree to deallocate the array
 *
 */
char **GetCompoundDataNISTList(int *nCompounds);

/*
 *
 * Deallocates a pointer to a compoundDataNIST struct completely.
 * It is recommended to set the pointer to NULL after calling this function.
 *
 */
void FreeCompoundDataNIST(struct compoundDataNIST *compoundData);

HEADER

print OUTPUT_HEADER $header_begin;

my $header_begin2 = <<'EOF2';
/*
Copyright (c) 2013, Tom Schoonjans
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
    * The names of the contributors may not be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY Tom Schoonjans ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Tom Schoonjans BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

/*
 * This file was automatically generated by nist-compounds.pl
 * Modify at your own risk...
 */

#include <xraylib-nist-compounds.h>

EOF2

print OUTPUT_INT $header_begin2;

my $compoundIndex = 0;

my @compoundData;

for (my $i = 99 ; $i <= 278 ; $i++) {
	my $url = sprintf("%s%03i.html", $nist_url, $i);
	print "URL: ".$url."\n";

	#use curl to download the files
	$curl->setopt(CURLOPT_URL, $url);
	my $html_file;

	$curl->setopt(CURLOPT_WRITEDATA, \$html_file);
	my $rv = $curl->perform;
	if ($rv != 0) {
		printf "Curl error for file %s: %s\n", $url, $curl->getinfo(CURLINFO_HTTP_CODE);
		exit 1;
	}

	#fix html file
	$html_file =~ s/(<form action=\"\/cgi-bin\/Star\/compos.pl\" method=GET>)\n(<center>)/$2\n$1/gm;
	$html_file =~ s/<a\n/\n/g;
	$html_file =~ s/<script.+<\/script>//g;

	#print $html_file;

	#work with html_file
	#my $dom = XML::LibXML->load_html(string => $html_file, recover => 1, suppress_errors => 1);
	my $dom = XML::LibXML->load_html(string => $html_file);
	my $xpc = XML::LibXML::XPathContext->new($dom);

	my $searchstring = sprintf "//body/center/form/select/option[\@value='%03i']", $i;
	#print $searchstring;

	my %compoundDataSingle;

	my $name = $xpc->findvalue($searchstring, $dom);
	my $density = $xpc->findvalue("//body/center/table[1]/tr[1]/td[2]", $dom);

	$compoundDataSingle{name} = $name;
	$compoundDataSingle{density} = $density;

	my @nodes = $xpc->findnodes("//body/center/table[2]/tr[\@align='right']", $dom);

	$compoundDataSingle{nElements} = scalar(@nodes);

	my @Elements;
	my @massFractions;

	for my $node (@nodes) {
		push @Elements, $xpc->find("td[1]", $node);
		push @massFractions, $xpc->find("td[2]", $node);
	}

	$compoundDataSingle{Elements} = \@Elements;
	$compoundDataSingle{massFractions} = \@massFractions;

	#macro
	my $macro = uc($name);
	$macro =~ s/, /_/g;
	$macro =~ s/ /_/g;
	$macro =~ s/-/_/g;
	$macro =~ s/\(//g;
	$macro =~ s/\)//g;
	$macro =~ s/,//g;
	$macro =~ s/\///g;

	printf OUTPUT_HEADER "#define NIST_COMPOUND_%s %i\n", $macro, $compoundIndex++;

	push @compoundData, \%compoundDataSingle;
}


printf OUTPUT_INT "static const int nCompoundDataNISTList = %i;\n", $compoundIndex;


for (my $i = 0 ; $i < scalar(@compoundData) ; $i++) {
	printf OUTPUT_INT "static int __CompoundDataNISTList_Elements_%i[] = {%s};\n",$i, join(", ",@{$compoundData[$i]->{Elements}});
	printf OUTPUT_INT "static double __CompoundDataNISTList_massFractions_%i[] = {%s};\n",$i, join(", ",@{$compoundData[$i]->{massFractions}});
}

printf OUTPUT_INT "static const struct compoundDataNIST compoundDataNISTList[] = {\n";
for (my $i = 0 ; $i < scalar(@compoundData) ; $i++) {
	printf OUTPUT_INT "{\"%s\" ,%i, __CompoundDataNISTList_Elements_%i, __CompoundDataNISTList_massFractions_%i, %f}",
		$compoundData[$i]->{name}, $compoundData[$i]->{nElements}, $i, $i, $compoundData[$i]->{density};
	if ($i ne scalar(@compoundData) -1) {
		printf OUTPUT_INT ",\n";
	}
	else {
		printf OUTPUT_INT "\n";
	}
}
printf OUTPUT_INT "};\n";

printf OUTPUT_HEADER "\n#endif\n";

close OUTPUT_INT;
close OUTPUT_HEADER;


