// cpsHspinal - Calibrate pwHspinal and phHspinal in a double array 
//              using decoupling during a Spin Echo, using 
//              Tancpxhahnecho. Process the double array to obtain 
//              maximum intensity. 

//              Argument 1 = 'setup'
//              Argument 2 = 'init' sets aHtppm = aHspinal = aH90.
//                            and pwHspinal = 165 degree fli[p angle. 
//                            else use exisiting values. 
//              Argument 3 is the region number with a defaul of 1. 


//==================
// The SETUP macro
//==================

if (($#>0) and ($1='setup')) then

// Read Macro Arguments

   if ($# < 2) then $2 = 'init' endif 
   if ($# < 3) then $3 = 1 endif

// Set Sequence and Read Modules 
   
   parammodule('setsampleglobals')
   Settancpx
   Tancpxhahnecho
   parammodule('updatesampleglobals')
   parammodule('studydir')
   $ret = 0 $reg = '' $tnuc = '' $dnuc = '' 
   parammodule('setacqregion',$3):$ret,$reg,$tnuc,$dnuc
   parammodule('errorcheck',$ret,$3,'setacqregion')
   $ret2 = 0
   parammodule('setacqdisplay',$3,''):$ret2
   parammodule('errorcheck',$ret2,$3,'setacqdisplay')
   $ret3 = 0
   parammodule('setsample1D',1):$ret3
   parammodule('infocheck',$ret3,1,'setsample1D','sample')

// Obtain Standard CP and Decoupling Parameters from Probe File

   probeparamgroup('getlocal',$reg,$dnuc,'HX','srate'):srate
   probeparamgroup('get',$reg,$dnuc,'HX','ch','sh','to','fr',
                                         'aH','b','d','t','of')
   probeparamgroup('get','hp'+$reg,$dnuc,'90H','a','pw')
   probeparamgroup('get',$reg,$tnuc,'90X','a','pw')
   probeparamgroup('get',$reg,$tnuc,'HX','aX')
   probeparamgroup('get',$reg,$dnuc,'tppmH','a','pw','ph')
   probeparamgroup('get',$reg,$dnuc,'spinalH','a','pw','ph')
   Hseq='spinal'

// Calibrate setddrtc for CP

   exists('ddrpm','parameter'):$e
   if ($e < 0.5) then
      create('ddrpm','string')
      ddrpm='r'
   endif   
   rof2=rd-0.6 alfa=ad

// Setup the Hard Spin Echo

   probeparamgroup('getlocal',$reg,$tnuc,'','pwX180'):$pwX180 
   pwXecho = $pwX180
   aXecho = aX90  

// Initialize the Spinal Amplitude and Pulse Width

   if ($2 = 'init') then 
      aHspinal = aH90
      pwHspinal = 2.0*pwH90*165.0/180.0
   endif 
   $aHspinal_sp = aHspinal
   $pwHspinal_sp = pwHspinal

// Setup an Array of phHspinal and pwHspinal

   $pwHspinal_sp=0.2*trunc($pwHspinal_sp/0.2 + 0.5)
   $pwHspinal_min=$pwHspinal_sp - 0.6

   array('phHspinal',12,2,2)
   array('pwHspinal',10,$pwHspinal_min,0.2)
   array = 'phHspinal,pwHspinal'

// Set Automatic Linebroadening 

   fn=16*np lb = 2.0*sw/(3.14159*np) sb = at/2.0 sbs=0.0 sbs='n' lb=0

// Linear Prediction

   parlp
   proc = 'ft'
  
// Set the Auto Display to Absolute Value

   $macroname = $0 + '(\'maxamp\',100)'
   wnt='vp=0 sb=\'y\' wft setref av ' + $macroname + ' noislm(1.0) dssh'

// Set Macro-Specific Processing and Plotting 

   wexp = 'chempackQ'
   $arg3 = '' format($3,1,0):$arg3
   execprocess = $0 + '(\'process\',\'' + $2 + '\',' + $arg3 + ')'
   execplot = ''
   clear(2)
   write('line3','%s Setup is Complete\n',$0)
   return
endif

//===========================
// Macro-Specific Processing
//===========================

if (($# > 0) and ($1 = 'process')) then 

// Read Macro Arguments

   if ($# < 2) then $2 = 'init' endif 
   if ($# < 3) then $3 = 1 endif

// Set the Region

   $ret = 0 $reg = '' $tnuc = '' $dnuc = '' 
   parammodule('setacqlabel',1):$ret,$reg,$tnuc,$dnuc

// Analyze the Double Array of pwHspinal and phHspinal

   $bestone=1 $bestone1=1 $bestone2=1
   $counter=1 $counter1=1 $counter2=1 $best=0
   lb = 2.0*sw/(3.14159*np) sb = at/2.0 sbs=0.0 sbs='n'
   fn=16*np vp=0 av wft
   $size_pwHspinal=size('pwHspinal')
   repeat
      select($counter)
      $counter1=trunc(($counter-1)/$size_pwHspinal) + 1
      $counter2=($counter-1)%$size_pwHspinal + 1
      peak:$ht
      if ($ht>$best) then $best=$ht $bestone=$counter $bestone1=$counter1 $bestone2=$counter2 endif
      $counter=$counter+1
   until ($counter>arraydim)

// Select the Best Values of pwHspinal and phHspinal

   $phHspinal=phHspinal[$bestone1]
   $pwHspinal=pwHspinal[$bestone2]

// Update pwHspinal and phHspinal

   probeparamgroup('setlocal',$reg,$dnuc,'','phHspinal',$phHspinal)
   probeparamgroup('setlocal',$reg,$dnuc,'','pwHspinal',$pwHspinal)
endif

//===========================
// Macro-Specific Plotting
//===========================

if (($# > 0) and ($1 = 'plot')) then 
   wc = 50 sc = 50
   plot1d
   return  
endif 

//==================================
// Begin AutoCalibration Utilities
//==================================

//--------------------
// The maxamp function
//--------------------

if (($# > 0) and ($1 = 'maxamp')) then
   select(celem) 
   if (celem=1) then 
      vsadj($2) 
   endif
   peak:$ht
   if ($ht>$2) then 
      vsadj($2) 
   endif 
   return    
endif  

//--------------------------
// The  minmaxfit function
//--------------------------

if (($# > 0) and ($1 = 'minmaxfit')) then 

   $bestone=$2
   $lim=2
   if ($#>3) then $lim=$4 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','$2 = %f',$2)

// 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=$2 and $remainder=0.0 

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