import math


def statistics_to_tex(
    all_stats, labels, filename=None, quantity_name="$\\langle E_L\\rangle$"
):
    """
    Produce LaTeX table from statistics produced from ``compute_statistics_for_series``.
    """

    digs = max([abs(int(math.floor(math.log10(stats["sem"])))) for stats in all_stats])

    tex = f"""\\begin{{tabular}}{{lS[table-format=1.%d]*2{{S[table-format=1.%d]}}*2{{S[table-format=1.1]}}}}
\\toprule
\\addlinespace
& {{%s}} & {{CI$^{{95}}_-$}} & {{CI$^{{95}}_+$}} & {{Std}} & {{Var}} \\\\
\\addlinespace
\\midrule
\\addlinespace
\\addlinespace
    """ % (
        digs + 2,
        digs,
        quantity_name,
    )

    for stats, label in zip(all_stats, labels):
        stats = stats.copy()
        stats["ci-"], stats["ci+"] = stats.pop("CI")

        tex += label + " & "

        significant_digits = abs(int(math.floor(math.log10(stats["sem"]))))
        tex += "{0:.{2}f}({1:.0f}) & ".format(
            stats["mean"], stats["sem"] * 10 ** significant_digits, significant_digits
        )
        tex += "{0:.{1}f} & ".format(stats["ci-"], significant_digits)
        tex += "{0:.{1}f} & ".format(stats["ci+"], significant_digits)
        tex += "\\num{{{0:.1e}}} & ".format(stats["std"])
        tex += "\\num{{{0:.1e}}}".format(stats["var"])

        tex += "\\\\\n"

    tex += "\\addlinespace\\addlinespace\\bottomrule\n\\end{tabular}"

    if filename is not None:
        with open(filename, "w") as f:
            f.write(tex)

    return tex