package thermocouple

import (
	"th7/data/thermocouple"
)

const (
	R_MAX_C  = 1768.0
	R_MIN_C  = -50.0
	R_MAX_UV = 21103.0
	R_MIN_UV = -226.0
)

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

	if c < R_MIN_C || c > R_MAX_C {
		return 0, thermocouple.ErrC
	}

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

	if c < 1064.18 {
		c0 = 0.0
		c1 = 5.28961729765
		c2 = 1.39166589782e-2
		c3 = -2.38855693017e-5
		c4 = 3.56916001063e-8
		c5 = -4.62347666298e-11
		c6 = 5.00777441034e-14
		c7 = -3.73105886191e-17
		c8 = 1.57716482367e-20
		c9 = -2.81038625251e-24
	} else if c < 1664.5 {
		c0 = 2.95157925316e3
		c1 = -2.52061251332
		c2 = 1.59564501865e-2
		c3 = -7.64085947576e-6
		c4 = 2.05305291024e-9
		c5 = -2.93359668173e-13
		c6 = 0.0
		c7 = 0.0
		c8 = 0.0
		c9 = 0.0
	} else {
		c0 = 1.52232118209e5
		c1 = -2.68819888545e2
		c2 = 1.71280280471e-1
		c3 = -3.45895706453e-5
		c4 = -9.34633971046e-12
		c5 = 0.0
		c6 = 0.0
		c7 = 0.0
		c8 = 0.0
		c9 = 0.0
	}

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

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

	if uv < R_MIN_UV || uv > R_MAX_UV {
		return 0, thermocouple.ErrUV
	}

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

	if uv < 1923.0 {
		c0 = 0.0
		c1 = 1.8891380e-1
		c2 = -9.3835290e-5
		c3 = 1.3068619e-7
		c4 = -2.2703580e-10
		c5 = 3.5145659e-13
		c6 = -3.8953900e-16
		c7 = 2.8239471e-19
		c8 = -1.2607281e-22
		c9 = 3.1353611e-26
		c10 = -3.3187769e-30
	} else if uv < 13228.0 {
		c0 = 1.334584505e1
		c1 = 1.472644573e-1
		c2 = -1.844024844e-5
		c3 = 4.031129726e-9
		c4 = -6.249428360e-13
		c5 = 6.468412046e-17
		c6 = -4.458750426e-21
		c7 = 1.994710146e-25
		c8 = -5.313401790e-30
		c9 = 6.481976217e-35
		c10 = 0.0
	} else if uv < 19739.0 {
		c0 = -8.199599416e1
		c1 = 1.553962042e-1
		c2 = -8.342197663e-6
		c3 = 4.279433549e-10
		c4 = -1.191577910e-14
		c5 = 1.492290091e-19
		c6 = 0.0
		c7 = 0.0
		c8 = 0.0
		c9 = 0.0
		c10 = 0.0
	} else {
		c0 = 3.406177836e4
		c1 = -7.023729171
		c2 = 5.582903813e-4
		c3 = -1.952394635e-8
		c4 = 2.560740231e-13
		c5 = 0.0
		c6 = 0.0
		c7 = 0.0
		c8 = 0.0
		c9 = 0.0
		c10 = 0.0
	}

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