proc ihelium3_chebychev {coef z} {
# coef: Zu Zl a0 a1 a2 ...
  set a2_n [lassign $coef zu zl a0 a1]
  set x [expr (($z - $zl) - ($zu - $z)) / double($zu - $zl)]
  set tn_2 1
  set tn_1 $x
  set y [expr $a0 * 0.5 + $a1 * $x]
  lappend conv $y
  foreach an $a2_n {
    set tn [expr 2 * $x * $tn_1 - $tn_2]
    set y [expr $y + $an * $tn]
    lappend conv $y
    set tn_2 $tn_1
    set tn_1 $tn
  }
#  clientput "zl=$zl zu=$zu z=$z x=$x $conv"
  return $y
}

proc ihelium3_calib {sensorno} {
  upvar #0 ihelium3_$sensorno cal

  set fil [open calcurves/#CMP${sensorno}Coefftable.dat]
  foreach B {0 0.2 0.4 0.6 0.8 1 2 3 4 5 6 7} {
    set cal($B) [gets $fil]
  }
  close $fil
  
  set fil [open calcurves/#CMP${sensorno}HT_Coeff.dat]
  set c [list]
  while {[gets $fil line] >= 0} {
    if {[string index $line 0] ne "#"} {
      lappend c [string trim $line]
    }
  }
  close $fil
  set cal(HT) $c
}

proc ihelium3_res2temp {sensorno B R} {
  upvar #0 ihelium3_$sensorno cal
  
  set r [expr log10($R)]
#  clientput r=$r
  if {$r < [lindex $cal(0) 1]} {
    set t [ihelium3_chebychev $cal(HT) $r]
  } else {
    set B [expr abs($B)]
    if {$B >= 7} {
      set B0 6
      set B1 7
      set w 1
    } else {
      if {$B >= 1} {
        set B0 [expr int($B)]
        set B1 [expr $B0 + 1]
      } else {
        set B0 [format %g [expr int($B * 5) * 0.2]]
        set B1 [format %g [expr $B0 + 0.2]]
      }
      set w [expr (sqrt($B) - sqrt($B0)) / (sqrt($B1) - sqrt($B0))]
    }
    set t0 [ihelium3_chebychev $cal($B0) $r]
    set t1 [ihelium3_chebychev $cal($B1) $r]
    set t [expr (1 - $w) * $t0 + $w * $t1]
  }
  return [expr pow(10, $t)]
}

proc ihelium3_tab {sensorno r} {
  foreach B {0 0.2 0.4 0.6 0.8 1 2 3 4 5 6 7} {
    set T [list $B]
    foreach R $r {
      set tt [ihelium3_res2temp $sensorno $B $R]
      if {$tt < 0.4} {
        break
      }
      lappend T $tt
    }
    clientput $T
  }
}
