package thermocouple

import (
	"th7/data/thermocouple"
)

const (
	S_MAX_C  = 1768.1
	S_MIN_C  = -50.0
	S_MAX_UV = 18693.0
	S_MIN_UV = -235.0
)

func s_c_to_uv(c float64) (float64, error) {

	if c < S_MIN_C || c > S_MAX_C {
		return 0, thermocouple.ErrC
	}

	var c0, c1, c2, c3, c4, c5, c6, c7, c8, E float64

	if c < 1064.18 {
		c0 = 0.0
		c1 = 5.40313308631
		c2 = 1.25934289740e-2
		c3 = -2.32477968689e-5
		c4 = 3.22028823036e-8
		c5 = -3.31465196389e-11
		c6 = 2.55744251786e-14
		c7 = -1.25068871393e-17
		c8 = 2.71443176145e-21
	} else if c < 1664.5 {
		c0 = 1.32900445085e3
		c1 = 3.34509311344
		c2 = 6.45805192818e-3
		c3 = -1.64856259209e-6
		c4 = 1.29989605174e-11
		c5 = 0.0
		c6 = 0.0
		c7 = 0.0
		c8 = 0.0
	} else {
		c0 = 1.46628232636e5
		c1 = -2.58430516752e2
		c2 = 1.63693574641e-1
		c3 = -3.30439046987e-5
		c4 = -9.43223690612e-12
		c5 = 0.0
		c6 = 0.0
		c7 = 0.0
		c8 = 0.0
	}

	E = c0 + c*(c1+c*(c2+c*(c2+c*(c3+c*(c4+c*(c5+c*(c6+c*(c7+c*(c8)))))))))
	return E, nil
}

func s_uv_to_c(uv float64) (float64, error) {

	if uv < S_MIN_UV || uv > S_MAX_UV {
		return 0, thermocouple.ErrUV
	}

	var c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, T float64

	if uv < 1874.0 {
		c0 = 0.0
		c1 = 1.84949460e-1
		c2 = -8.00504062e-5
		c3 = 1.02237430e-7
		c4 = -1.52248592e-10
		c5 = 1.88821343e-13
		c6 = -1.59085941e-16
		c7 = 8.23027890e-20
		c8 = -2.34181944e-23
		c9 = 2.79786260e-27
	} else if uv < 11950.0 {
		c0 = 1.291507177e1
		c1 = 1.466298863e-1
		c2 = -1.534713402e-5
		c3 = 3.145945973e-9
		c4 = -4.163257839e-13
		c5 = 3.187963771e-17
		c6 = -1.291637500e-21
		c7 = 2.183475087e-26
		c8 = -1.447379511e-31
		c9 = 8.211272125e-36
	} else if uv < 17536.0 {
		c0 = -8.087801117e1
		c1 = 1.621573104e-1
		c2 = -8.536869453e-6
		c3 = 4.719686453e-10
		c4 = -1.441693666e-14
		c5 = 2.081618890e-19
		c6 = 0.0
		c7 = 0.0
		c8 = 0.0
		c9 = 0.0
	} else {
		c0 = 5.333875126e4
		c1 = -1.235892298e1
		c2 = 1.092657613e-3
		c3 = -4.265693686e-8
		c4 = 6.247205420e-13
		c5 = 0.0
		c6 = 0.0
		c7 = 0.0
		c8 = 0.0
		c9 = 0.0
	}

	T = c0 + uv*(c1+uv*(c2+uv*(c3+uv*(c4+uv*(c5+uv*(c6+uv*(c7+uv*(c8+uv*(c9)))))))))
	return T, nil
}