#!/usr/bin/env python3
#
#    JKS - Measurement database system
#    Copyright (C) 2026  Christoph Lehner (christoph.lehner@ur.de, https://github.com/lehner/jks)
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License along
#    with this program; if not, write to the Free Software Foundation, Inc.,
#    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Print the elements of a constant tag one per line, for shell loops:
#   for lam in $(jks_values db.jks lambda); do ...; done
# Integral values are printed without decimal point, others as the shortest
# decimal that reads back to the same double.
#
import jks, sys, os, math, numpy as np

if len(sys.argv) != 3:
    print("%s database.jks tag" % sys.argv[0])
    sys.exit(0)

db, tag = sys.argv[1], sys.argv[2]
res = jks.resamples(db)
if tag not in res.set:
    print("ERROR: %s not in %s" % (tag, db))
    sys.exit(1)

jk = res.get(tag)
orig = np.atleast_1d(np.asarray(jk.orig, dtype=np.float64)).ravel()
blocks = np.asarray(jk.blocks, dtype=np.float64).reshape(len(jk.blocks), len(orig))
if not np.all(np.isfinite(orig)):
    print("ERROR: %s has non-finite values" % tag)
    sys.exit(1)
if not np.all(blocks == orig):
    print("ERROR: %s fluctuates over the blocks; loop values must be constant" % tag)
    sys.exit(1)

for x in orig:
    x = float(x)
    print(str(int(x)) if x.is_integer() and abs(x) < 2**53 else repr(x))
