// SS_AutoCal_minmaxfit - Interpolate a minimum/maximum of the peak 
// height using 2*$3+1 arrayed spectra around a selected spectrum, $1. 
// Expect a minimum ($2='min') or a maximum ($2='max'). If such 
// exists return a new best element, $bestone and an interpolated 
// fraction between $bestone and $bestone+1. Otherwise return 
// $bestone=$1.     

// if $#<3 Measure +/-2 Peaks Around $bestone
$bestone=$1
$lim=2
if ($#>2) then $lim=$3 endif

// Prepare 'analyze.inp'

$file=curexp+'/analyze.inp'
exists($file,'file'):$a
if ($a>0.5) then 
   write('reset',$file) 
endif

format((2*$lim+1),2,0):$sizes

write('file',$file,'AMPLITUDE')
write('file',$file,'INTENSITY')
write('file',$file,'%12s%13s%7s%7s\n','1',$sizes,'linear','linear')
format((2*$lim+1),2,0):$sizes
write('file',$file,'%8s%5s','NEXT',$sizes)
write('file',$file,'1')

$step=$bestone-$lim
repeat
   select($step)
   peak:$ht
   write('file',$file,'%14.1f%12.2f',$step,$ht)
   $step=$step+1
until ($step>$bestone+$lim)

// 'poly2 Analysis with 'expfit'

analyze('expfit','regression','poly2')
$file=curexp+'/analyze.out'
lookup('file',$file)
lookup('seek','NEXT','skip', '2','read','4'):$a0s,$a1s,$a2s
format($a0s,8,4):$a0
format($a1s,8,4):$a1
format($a2s,8,4):$a2
$inf=-$a1/(2.0*$a2)
$infval=$a0+$a1*$inf+$a2*$inf*$inf

// Mean Value from 'poly0' 

analyze('expfit','regression','poly0')
lookup('file',$file)
lookup('seek','NEXT','skip', '2','read','4'):$a0s,$a1s,$a2s
format($a0s,8,4):$a0
$mean=$a0
write('line3','$inf=%f $infval=%f $mean=%f',$inf,$infval,$mean)
write('line3','$1 = %f',$1)

// Min ($minmax<0) or Max ($minmax>0) or none ($minmax=0)

$minmax=0 $ret=0.0
if (($bestone-$lim)<$inf)and($inf<($bestone+$lim)) then 
   $ret=$inf
   if ($infval<$mean) then 
      $minmax=-1
   else
      $minmax=1
   endif
endif

write('line3','$xmin = %f $ret = %f $xmax = %f $minmax=%f',$bestone-$lim,$ret,$bestone+$lim,$minmax)

// Return the new $bestone and a Fraction After $bestone,
// else Return $bestone=$1 and $remainder=0.0 

$remainder=0 
if (($2='min')and($minmax<0)) then 
   $bestone=trunc($ret) 
   $remainder=$ret-$bestone
endif
if (($2='max')and($minmax>0)) then 
   $bestone=trunc($ret) 
   $remainder=$ret-$bestone
endif
if ($minmax=0) then
   $bestone=$1 
   $remainder=0.0
endif
write('line3','$bestone=%f',$bestone)
return($bestone,$remainder)



