#!/usr/bin/env python3


import urllib.request
from io import StringIO
import lxml.etree as ET
import re
import xraylib as xrl

xrl.SetErrorMessages(0)

lbl_url = "http://nucleardata.nuclear.lu.se/toi/nuclide.asp?iZA="

nuclide_codes = sorted(("260055", "940238", "960244", "480109", "530125", "950241", "640153", "270057", "560133", "550137"))

with open("../../src/xraylib-radionuclides-internal.h", "w") as output_int, open("../../include/xraylib-radionuclides.h", "w") as output_header:


    header_begin = '''/*
Copyright (c) 2014-2018, 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 nuclides.pl
 * Modify at your own risk...
 */


#ifndef XRAYLIB_RADIO_NUCLIDES_H
#define XRAYLIB_RADIO_NUCLIDES_H

#include "xraylib-error.h"

/* 
 * name: a string containing the mass number (A), followed by the chemical element (e.g. 55Fe)
 * Z: atomic number of the radionuclide
 * A: mass number of the radionuclide
 * N: number of neutrons of the radionuclide
 * Z_xray: atomic number of the nuclide after decay, and which should be used in calculating the energy of the emitted X-ray lines
 * nXrays: number of emitted characteristic X-rays
 * XrayLines: array of *_LINE macros, identifying the emitted X-rays
 * XrayIntensities: array of photons per disintegration, one value per emitted X-ray
 * nGammas: number of emitted gamma-rays
 * GammaEnergies: array of emitted gamma-ray energies
 * GammaIntensities: array of emitted gamma-ray photons per disintegration
 */

struct radioNuclideData{
	char *name;
	int Z;
	int A;
	int N;
	int Z_xray;
	int nXrays;
	int *XrayLines;
	double *XrayIntensities;
	int nGammas;
	double *GammaEnergies;
	double *GammaIntensities;
};


/*
 *
 * Returns a pointer to a newly allocated struct containing
 * the requested radionuclide on success, or NULL when the radionuclide 
 * was not found in the list. The radionuclide is requested by providing
 * its name as argument to the function. For a list of available names,
 * use GetRadioNuclideList.
 *
 * The returned struct should be freed after usage with FreeRadioNuclideData.
 *
 */
XRL_EXTERN
struct radioNuclideData *GetRadioNuclideDataByName(const char radioNuclideString[], xrl_error **error);

/*
 *
 * Returns a pointer to a newly allocated struct containing
 * the requested radionuclide on success, or NULL when the radionuclide
 * was not found in the list. The radionuclide is requested by providing
 * its index in the internal table to the function. Typically this would
 * be done using the RADIO_NUCLIDE_* macros in this file.
 *
 * The returned struct should be freed after usage with FreeRadioNuclideData.
 *
 */
XRL_EXTERN
struct radioNuclideData *GetRadioNuclideDataByIndex(int radioNuclideIndex, xrl_error **error);

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

/*
 *
 * Deallocates a pointer to a radioNuclideData struct completely.
 * It is recommended to set the pointer to NULL after calling this function.
 *
 */
XRL_EXTERN
void FreeRadioNuclideData(struct radioNuclideData *radioNuclideData);

'''

    output_header.write(header_begin)

    header_begin2 = '''/*
Copyright (c) 2014-2018, 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 nuclides.pl
 * Modify at your own risk...
 */

#include "xraylib.h"
#include "xraylib-error-private.h"

'''
    output_int.write(header_begin2)


    nuclideData = []

    for nuclideIndex, nuclide_code in enumerate(nuclide_codes):
        print(nuclide_code)
        url = lbl_url + nuclide_code
        print("url: {}".format(url))

        try:
            response = urllib.request.urlopen(url)
            html = response.read().decode("utf-8")

            # fix html file
            html = re.sub(r"(<\/FONT>\r\n)<\/FONT>", r"\1", html)
            html = re.sub(r"(Tables:<\/A>)<\/FONT>", r"\1", html)
            html = re.sub(r"(ENSDF data:<\/A>)<\/FONT>", r"\1", html)
            html = re.sub(r"(Java applets:<\/A>)<\/FONT>", r"\1", html)
            html = re.sub(r"(TORI Data \(1999\))(<\/font>)(<\/I>)", r"\1\3\2", html)
            html = re.sub(r"(<\/B>)(<\/FONT>)(<P>)", r"\2\1\3", html)
            html = re.sub(r"&nbsp;<I>.+<\/I>&nbsp;", "", html)
            html = re.sub(r"&nbsp;<i>.+<\/i>&nbsp;", "", html)
            html = re.sub(r"/&nbsp;", "", html)
            html = re.sub(r"(<TD>)<\d.+(<\/TD>)", r"\1\2", html)

            parser = ET.HTMLParser()
            tree = ET.parse(StringIO(html), parser)

            xpath_Z = "/html/body/center/table/tr[3]/td[2]/center/table[1]/caption/table/tr[2]/th[1]/font/text()";
            xpath_A = "/html/body/center/table/tr[3]/td[2]/center/table[1]/caption/table/tr[1]/th[1]/font/text()";
            xpath_N = "/html/body/center/table/tr[3]/td[2]/center/table[1]/caption/table/tr[2]/th[2]/font/text()";

            nuclideDataSingle = dict()

            Z = tree.xpath(xpath_Z)[0]
            A = tree.xpath(xpath_A)[0]
            N = tree.xpath(xpath_N)[0]
            print("Z: {}".format(Z))
            print("A: {}".format(A))
            print("N: {}".format(N))

            nuclideDataSingle['Z'] = Z
            nuclideDataSingle['A'] = A
            nuclideDataSingle['N'] = N
            nuclideDataSingle['name'] = "{}{}".format(A, xrl.AtomicNumberToSymbol(int(Z)))

            ##gamma stuff
            xpath_gamma = "/html/body/center/table/tr[3]/td[2]/center/table[3]/tr[position() >= 4 and position() < count(/html/body/center/table/tr[3]/td[2]/center/table[3]/tr)]"
            gamma_nodes = tree.xpath(xpath_gamma)

            print("gamma nodes number: {}".format(len(gamma_nodes)))

            gamma_energies = []
            gamma_intensities = []

            for node in gamma_nodes:
                try:
                    gamma_intensity = node.xpath("td[2]/text()")[0]
                    gamma_intensity = float(gamma_intensity)
                    gamma_energies.append(node.xpath("td[1]/text()")[0].strip())
                    gamma_intensities.append("{:g}".format(gamma_intensity / 100.0))
                except Exception:
                    pass

            nuclideDataSingle['nGammas'] = len(gamma_energies)
            nuclideDataSingle['gammaEnergies'] = gamma_energies
            nuclideDataSingle['gammaIntensities'] = gamma_intensities
            print("nGammas: {}".format(nuclideDataSingle['nGammas']))


            ##X-rays
            xpath_xray= "/html/body/center/table/tr[3]/td[2]/center/table[4]/tr[position() >= 4 and position() <= count(/html/body/center/table/tr[3]/td[2]/center/table[4]/tr)]"
            xray_nodes = tree.xpath(xpath_xray)

            print("xray nodes number: {}".format(len(xray_nodes)))

            xray_lines = []
            xray_intensities = []

            # extract X-ray element
            Z_xray = xray_nodes[0].xpath("td[3]/text()")[0][0:2]
            if not Z_xray[1].isalpha() or not Z_xray[1].islower():
                Z_xray = Z_xray[0]
            print("Z_xray: {}".format(Z_xray))
            nuclideDataSingle['Z_xray'] = xrl.SymbolToAtomicNumber(Z_xray)

            for node in xray_nodes:
                xray_intensity = node.xpath("td[2]/text()")[0]
                line = node.xpath("td[3]/text()")[0]
                line = line.replace(Z_xray, "")
                line_major = line.upper()
                line_minor = node.xpath("td[3]/sub/*/text()")[0].upper()
                try:
                    line_micro = node.xpath("td[3]/sub/text()")[0].upper()
                except IndexError:
                    line_micro = ""
                line = line_major + line_minor + line_micro + "_LINE"
                line = line.strip()
                print("line: {}".format(line))
                try:
                    xray_intensity = float(xray_intensity)
                    xray_energy = xrl.LineEnergy(nuclideDataSingle['Z_xray'], getattr(xrl, line))
                    if xray_energy == 0.0:
                        raise Exception("LineEnergy not found for {} {}", nuclideDataSingle['Z_xray'], line)
                    print("Energies: {}  {}".format(node.xpath("td[1]/text()")[0], xray_energy))
                    xray_intensities.append("{:g}".format(xray_intensity/100.0))
                    xray_lines.append(line)
                except Exception as e:
                    print("Exception: " + str(e))

            nuclideDataSingle['nXrays'] = len(xray_intensities)
            print("nXrays: {}".format(nuclideDataSingle['nXrays']))
            nuclideDataSingle['xrayIntensities'] = xray_intensities
            nuclideDataSingle['xrayLines'] = xray_lines

            output_header.write("#define RADIO_NUCLIDE_{} {}\n".format(nuclideDataSingle['name'].upper(), nuclideIndex))
            nuclideData.append(nuclideDataSingle)
        except Exception as e:
            print(e)
            raise


    output_int.write("static const int nNuclideDataList = {};\n".format(len(nuclideData)))

    for i, nd in enumerate(nuclideData):
        output_int.write("static int __NuclideDataList_XrayLines_{}[] = {{{}}};\n".format(i, ", ".join(nd['xrayLines'])))
        output_int.write("static double __NuclideDataList_XrayIntensities_{}[] = {{{}}};\n".format(i, ", ".join(nd['xrayIntensities'])))
        output_int.write("static double __NuclideDataList_GammaEnergies_{}[] = {{{}}};\n".format(i, ", ".join(nd['gammaEnergies'])))
        output_int.write("static double __NuclideDataList_GammaIntensities_{}[] = {{{}}};\n".format(i, ", ".join(nd['gammaIntensities'])))

    output_int.write("static const struct radioNuclideData nuclideDataList[] = {\n")
    ls = ["{{\"{}\" ,{}, {}, {}, {}, {}, __NuclideDataList_XrayLines_{}, __NuclideDataList_XrayIntensities_{}, {}, __NuclideDataList_GammaEnergies_{}, __NuclideDataList_GammaIntensities_{}}}".format( \
        nd['name'], \
	nd['Z'], \
        nd['A'], \
        nd['N'], \
        nd['Z_xray'], \
        nd['nXrays'], \
        i, \
        i, \
        nd['nGammas'], \
        i, \
        i) for i, nd in enumerate(nuclideData)]
    output_int.write(",\n".join(ls) + "\n")

    output_int.write("};\n")

    output_header.write("\n#endif\n")


