"SS_AutoCal_CP: Automatic Calibration of Pulse Widths and CP Using CP Detection "

"      This macro requires the Solids sequence tancpx.c and the setup macro     "
"      tancpx, the parameter file Settancpx.par and BioPack macros BPsvf,       "
"      BPpage, BPsetparams, and BPgetdate.  The optional parameter MASdev stores"
"      the allowed spin rate deviation and BPplot stores the plottting status   "
"      'plot','on' or 'file'. BPplotdir specifies a full path directory when    "
"      BPplot='file'.  The directory is automatically set to ~/vnmrsys/AutoTripRes."
"      BPpresent='y' does a BioPack setup using setup macros and automatically  "
"      communicates with the HC and HN parameter groups in the probe file.  For "
"      BioPack, initial calibrations come from HC and HN. For any other value of"
"      BPpresent (i.e. ''), setup parameters are derived from Settancpx.par and "
"      initial calibrations must be set in the appropriate parameter group HCa, "
"      HCO, HNai and HNam. BPplotmode='ph' displays and saves phased data.  Any "
"      other value of BPplotmode (i.e. 'av' or '') displays and saves absolute  "
"      value data, with the exception of the last signal-to-noise spectrum. The "
"      probe file must use or contain the parameters of the template            "
"      SS_AutoCal_probe.template.                                               "

"      The manual files SSpreface_Ca, SSpreface_CO, SSpreface_Nai, SSpreface_Nam"
"      should be present in manuals.                                            "

"      This macro calls SS_1_CP, SS_2_CP, SS_3_CP and SS_4_CP in sequence       "
"      Current regions: ('13C','alpha') peptide alpha region (HCa)              "
"                       ('13C','carbonyl') peptide carbonyl region (HCO)        "
"                       ('15N','amide') peptide amide region (HNai)             "
"                       ('15N','amine') amino acid amine region (HNam)          "
                                                 "
"      For operation with BPpresent='y', if BioPack is not installed, the macros"
"      tancpx_HC, tancpx_HN are required.  These macros use BioPack macros      "
"      BPrtppar, BPgetpars, BPfixup, BPcheckprobefile BP_SS_update_from_probefile"
"      and BP_SS_getsrate.  The parameters BPinstall and BPsolids must be created"
"      manually and set to BPinstall=1 and BPsolids='y'. These parameters would "
"      otherwise be created by a Solids BioPack installation. Parameter files   "
"      tancpx_C13.par and tancpx_N15.par must be present in parlib.             "

"      George Gray, Dave Rice 08/28/09.                                         "

//Check the Syntax or Get Region from n1. 

if ($#<2) then 
   write('error','Format: SS_AutoCal_CP(\'nucleus\',\'region\')')
   abort
endif
if (($2='alpha')or($2='carbonyl')or($2='amide')or($2='amine')) then
   n1=$2 
endif
$2=n1 n1=''
 
if (($2<>'alpha')and($2<>'carbonyl')and($2<>'amide')and($2<>'amine')) then
   write('error','Region = \'alpha\',\'carbonyl\',\'amide\' or \'amine\'')
   abort
endif

//Check to see if Plotting is Requested and There is a Plotter

exists('BPplot','parameter','global'):$e
if ($e>0.5) then 
   if ((BPplot='plot')or(BPplot='on')or(BPplot='file')) then
      if (plotter='') then
         banner('Plotting is Requested but no Plotter is Defined')
         write('line3','Plotting is Requested but no Plotter is Defined')
         return      
      else
         banner('Plotting is On')         
         write('line3','Plotting is On and Output is %s',BPplot)
      endif
   else
      banner('Plotting is Off')
      write('line3','Plotting is Off')
   endif
else
   create('BPplot','string','global')
   BPplot=''
   banner('Plotting is Off')
   write('line3','Plotting is Off')
endif

// Create BPsample if it does not exist

exists('BPsample','parameter','global'):$e
if ($e<0.5) then 
   create('BPsample','string','global')
   BPsample=''
endif

// Create BPregion if it does not exist

exists('BPregion','parameter','global'):$e
if ($e<0.5) then 
   create('BPregion','string','global')
   BPregion=''
endif
if ($1='C13') then 
   BPregion = $2
endif

// Create BPcopy if it does not exist

exists('BPcopy','parameter','global'):$e
if ($e<0.5) then 
   create('BPcopy','real','global')
   BPcopy=0
endif

// Create BPchain if it does not exist

exists('BPchain','parameter','global'):$e
if ($e<0.5) then 
   create('BPchain','string','global')
   BPchain=''
endif

// Initialize the Workspace for Solids

$sysparfile=systemdir+'/parlib/Settancpx.par'
$parfile=userdir+'/parlib/Settancpx.par'
exists($sysparfile,'file'):$e
if ($e>0.5) then
   rtp($sysparfile)
else
   exists($parfile,'file'):$e
   if ($e>0.5) then
      rtp($parfile)
   else
      banner('Solids Sequences Not Installed')
      abort
   endif
endif

// Add Linear Prediction

proc='lp'
parlp
lpalg = 'lpfft'
lpopt = 'b'
lpfilt = 8
lpnupts=256
strtlp = 5
lpext=4
strtext=4

// Get the Current Spin Rate with an Average of 10

banner('Measuring Spinning Rate and Stability')
$count=1 srate=0
repeat
   $index=''
   if ($count<10) then
      format($count,1,0):$index
   else
      format($count,2,0):$index
   endif
   $dest=curexp+'/stat'+$index
   shell('showstat > ',$dest):$dummy
 
   lookup('file',$dest,'currently', 'at:','read'):$masrate,$ret 
   if $ret then
      format($masrate,5,0):srate[$count]
   endif
   echo($masrate)
   shell('sleep 1')
   $count=$count+1
until ($count>10)

averag(srate[1],srate[2],srate[3],srate[4],srate[5],srate[6],
       srate[7],srate[8],srate[9],srate[10]):$avgsrate,$dev
echo($avgsrate,$dev)

// Format and Write Spin Rate as Text

$avsrate='' $devsrate=''
$avgsrate=trunc(($avgsrate+0.5)*10000)/10000
$dev=trunc($dev*10)/10
format($avgsrate,5,0):$avsrate
format($dev,3,1):$devsrate
$string1='Average MAS Rate = '+$avsrate+' Hz'
$string2='Standard Deviation of MAS Rate = '+$devsrate+' Hz'
write('line3','MAS Rate = %5.0f Hz. Standard Deviation = %2.0f Hz',$avgsrate,$dev)
$percentdev=100*($dev/$avgsrate)
$percentdev=trunc(1000*$percentdev)/1000

$avgsrate=trunc($avgsrate + 0.5)

//Check the Spin Rate 

if ($avgsrate<500) then 
   $message='MAS Spin Rate Measurement is Less Than 500 Hz - Aborting'
   banner($message)
   return
endif 

// Check the Spin Rate Deviation Relative to Limit

exists('MASdev','parameter','global'):$e
if ($e=1) then
   if ($percentdev>MASdev) then
      $u='' $v='' format($dev,2,1):$u format(MASdev*$avgsrate/100.0,2,1):$v
      $x='' $y='' format($percentdev,2,3):$x format(MASdev,2,4):$y
      $message='MAS Rate Stability of '+$x+' percent ('+$u+' Hz) exceeds User-Defined Stability of '+$y+' percent ('+$v+' Hz) - Aborting'
      banner($message)
      return
   endif
endif

// Remove Files Generated by the Spin Rate Measurement

$count=1
repeat
   $index=''
   if ($count<10) then
      format($count,1,0):$index
   else
      format($count,2,0):$index
   endif
   $dest=curexp+'/stat'+$index
   rm($dest)
   $count=$count+1
until ($count>10)

// Set the Date

$date=''
BPgetdate:$date

// Create AutoTripRes Directory

cd(userdir)
exists('AutoTripRes','file'):$e
if ($e>0.5) then
   exists('BioPack.dir/backups','directory'):$e
   if not($e) then
      shell('mkdir -p BioPack.dir/backups'):$dum
   endif
   mv('AutoTripRes','BioPack.dir/backups/AutoTripRes_'+$date)
endif
mkdir('AutoTripRes')

// Create and Set BPplotdir

exists('BPplotdir','parameter','global'):$e
if ($e<0.5) then 
   create('BPplotdir','string','global')
endif
BPplotdir=userdir + '/AutoTripRes'

// Create BPplotmode if it does not exist

exists('BPplotmode','parameter','global'):$e
if ($e<0.5) then 
   create('BPplotmode','string','global')
   BPplotmode=''
endif

// Create a Log File

$file='Log_'+$1+'_'+$2
cd(userdir)
exists('AutoTripRes','file'):$e
if ($e=1) then
   cd('AutoTripRes')
   write('reset',$file)
   write('file',$file,'CP %s %s Calibration on %s',$1,$2,$date)
   write('line3','CP %s %s Calibration on %s',$1,$2,$date)
   write('file',$file,'Temperature = %6.1fC, Spin Rate = %6.0fHz',temp,srate)
   write('line3','Temperature = %6.1fC, Spin Rate = %6.0fHz',temp,srate)
endif

// Get Current Temperature

$tpwr=tpwr $tof=tof $pw=pw  "memorize current settings"
$vtset=''
shell('showstat > ',curexp+'/stat'):$dummy
lookup('file',curexp+'/stat','VT','active:','read'):$vtset,$ret
delete(curexp+'/stat')
if $ret then
   format($vtset,0,1):$temp
endif

// Check for BPplot

exists('BPplot','parameter','global'):$e
if ($e>0.5) then 
   if ((BPplot='plot')or(BPplot='on')) then
      printon
      if (($1='C13')and($2='alpha')) then  man('SSpreface_Ca_CP')  endif
      if (($1='C13')and($2='carbonyl')) then  man('SSpreface_CO_CP')  endif
      if (($1='N15') and($2='amide')) then  man('SSpreface_Nai_CP') endif
      if (($1='C13')and($2='amine')) then  man('SSpreface_Nam_CP') endif
      printoff
   endif
endif

// Get the Calibrated Lock Frequency

getparam('lockfreq','Probe'):$lockfreq
setvalue('lockfreq',$lockfreq,'systemglobal')
getparam('solvent','Probe'):$solvent
setvalue('solvent',$solvent)

//Create BPpresent if it Does Not Exist

exists('BPpresent','parameter','global'):$e
if ($e<0.5) then 
   create('BPpresent','string','global')
   BPpresent=''
endif

// Get Parameters for the Resonance to be Calibrated

if (BPpresent='y') then 
//   banner('BioPack Software not Available, Continue Using SolidsPack')
//   write('line3','BioPack Software not Available, Continue Using SolidsPack')
   BPpresent='y'
endif

if (BPpresent<>'y') then
   tancpx
   if ($1='C13') then
      tn='C13' dn='H1' dn2='N15' ampmode='dppp'
      getsolidsprobedata('tn') getsolidsprobedata('dn') getsolidsprobedata('dn2')
      ad=4.0 rd=4.0 ddrtc=8.0 lp=0 d1=2.0 nt=1 ss=2 bs=4
      sw=100000.0 at=0.01 fn=16.0*np sb=at/2.0 sb='n' sbs='n' lb=50 gain=30  
      ofHX=0.0 shHX='t' 
      if ($2='alpha') then
         setref setoffset('C13',60):tof tof=0.1*trunc(tof/0.1 + 0.5) sp=35p wp=50p setref
         getparam('pwHspinal_HCa','H1'):pwHspinal
         getparam('aHspinal_HCa','H1'):aHspinal
         getparam('phHspinal_HCa','H1'):phHspinal
         getparam('pwH90_hpHCa','H1'):pwH90
         getparam('aH90_hpHCa','H1'):aH90
         getparam('aHhx_HCa','H1'):aHhx
         getparam('bHX_HCa','H1'):bHX
         getparam('dHX_HCa','H1'):dHX
         getparam('pwX90_HCa','C13'):pwX90
         getparam('aX90_HCa','C13'):aX90
         getparam('aXhx_HCa','C13'):aXhx
         getparam('tHX_HCa','H1'):tHX
      elseif ($2='carbonyl') then 
         setref setoffset('C13',175):tof tof=0.1*trunc(tof/0.1 + 0.5) sp=165p wp=20p setref
         getparam('pwHspinal_HCO','H1'):pwHspinal
         getparam('aHspinal_HCO','H1'):aHspinal
         getparam('phHspinal_HCO','H1'):phHspinal
         getparam('pwH90_hpHCO','H1'):pwH90
         getparam('aH90_hpHCO','H1'):aH90
         getparam('aHhx_HCO','H1'):aHhx
         getparam('bHX_HCO','H1'):bHX
         getparam('dHX_HCO','H1'):dHX
         getparam('pwX90_HCO','C13'):pwX90
         getparam('aX90_HCO','C13'):aX90
         getparam('aXhx_HCO','C13'):aXhx
         getparam('tHX_HCO','H1'):tHX
      else
         banner('Calibration Nucleus and Region Not Found')
         abort
      endif
   elseif ($1='N15') then   
      tn='N15' dn='H1' dn2='C13' ampmode='dppp'
      getsolidsprobedata('tn') getsolidsprobedata('dn') getsolidsprobedata('dn2')
      ad=4.0 rd=16.0 ddrtc=20.0 lp=0 d1=2.0 nt=1 ss=2 bs=4
      sw=50000.0 at=0.01 fn=16.0*np sb=at/2.0 sb='n' sbs='n' lb=50 gain=30 
      ofHX=0.0 shHX='t' 
      if ($2='amide') then
         setref setoffset('N15',115):tof tof=0.1*trunc(tof/0.1 + 0.5) sp=90p wp=50p setref
         getparam('pwHspinal_HNai','H1'):pwHspinal
         getparam('aHspinal_HNai','H1'):aHspinal
         getparam('phHspinal_HNai','H1'):phHspinal
         getparam('pwH90_hpHNai','H1'):pwH90
         getparam('aH90_hpHNai','H1'):aH90
         getparam('aHhx_HNai','H1'):aHhx
         getparam('bHX_HNai','H1'):bHX
         getparam('dHX_HNai','H1'):dHX
         getparam('pwX90_HNai','N15'):pwX90
         getparam('aX90_HNai','N15'):aX90
         getparam('aXhx_HNai','N15'):aXhx
         getparam('tHX_HNai','H1'):tHX
      elseif ($2='amine') then 
         setref setoffset('N15',35):tof tof=0.1*trunc(tof/0.1 + 0.5) sp=15p wp=40p setref
         getparam('pwHspinal_HNam','H1'):pwHspinal
         getparam('aHspinal_HNam','H1'):aHspinal
         getparam('phHspinal_HNam','H1'):phHspinal
         getparam('pwH90_hpHNam','H1'):pwH90
         getparam('aH90_hpHNam','H1'):aH90
         getparam('aHhx_HNam','H1'):aHhx
         getparam('bHX_HNam','H1'):bHX
         getparam('dHX_HNam','H1'):dHX
         getparam('pwX90_HNam','N15'):pwX90
         getparam('aX90_HNam','N15'):aX90
         getparam('aXhx_HNam','N15'):aXhx
         getparam('tHX_HNam','H1'):tHX
      else
         banner('Calibration Nucleus and Region Not Found')
         abort
      endif
   endif
   cdc ai 
else 
   if ($1='C13') then
      tancpx_HC   
      if ($2='alpha') then
         setref setoffset('C13',60):tof tof=0.1*trunc(tof/0.1 + 0.5) sp=45p wp=30p setref
      elseif ($2='carbonyl') then 
         setref setoffset('C13',175):tof tof=0.1*trunc(tof/0.1 + 0.5) sp=165p wp=20p setref
      endif
      ad=4.0 rd=4.0 ddrtc=8.0 lp=0 d1=2.0 nt=1 ss=2 bs=4
      sw=100000.0 at=0.01 fn=16.0*np sb=at/2.0 sb='n' sbs='n' lb=50 gain=30  
      ofHX=0.0 shHX='t' 
   elseif ($1='N15') then
      tancpx_HN  
      if ($2='amide') then
         setref setoffset('N15',115):tof tof=0.1*trunc(tof/0.1 + 0.5) sp=90p wp=50p setref
      elseif ($2='amine') then 
         setref setoffset('N15',35):tof tof=0.1*trunc(tof/0.1 + 0.5) sp=15p wp=40p setref       
      endif     
      ad=4.0 rd=16.0 ddrtc=20.0 lp=0 d1=2.0 nt=1 ss=2 bs=4
      sw=50000.0 at=0.01 fn=16.0*np sb=at/2.0 sb='n' sbs='n' lb=50 gain=30 
      ofHX=0.0 shHX='t' 
   endif
   cdc ai
endif

// Establish the Remaining Ramp Parameters

chHX='fr' frHX='dec' toHX='obs' 

// Obtain aH90_mp and pwH90_mp from the Probe File 

if (BPpresent<>'y') then  
   if (($1='C13')and($2='alpha')) then
      getparam('aH90_mpHCa','H1'):aH90   
      getparam('pwH90_mpHCa','H1'):$pwH90_mp
   elseif (($1='C13')and($2='carbonyl')) then 
      getparam('aH90_mpHCO','H1'):aH90
      getparam('pwH90_mpHCO','H1'):$pwH90_mp
   elseif (($1='N15')and($2='amide')) then 
      getparam('aH90_mpHNai','H1'):aH90
      getparam('pwH90_mpHNai','H1'):$pwH90_mp
   elseif (($1='N15')and($2='amine')) then
      getparam('aH90_mpHNam','H1'):aH90
      getparam('pwH90_mpHNam','H1'):$pwH90_mp
   else
      banner('Calibration Nucleus and Region Not Found')
      abort
   endif
else 
   if (($1='C13')and($2='alpha')) then
      getparam('aH90_mpHC','H1'):aH90   
      getparam('pwH90_mpHC','H1'):$pwH90_mp
   elseif (($1='C13')and($2='carbonyl')) then 
      getparam('aH90_mpHC','H1'):aH90
      getparam('pwH90_mpHC','H1'):$pwH90_mp
   elseif (($1='N15')and($2='amide')) then 
      getparam('aH90_mpHN','H1'):aH90
      getparam('pwH90_mpHN','H1'):$pwH90_mp
   elseif (($1='N15')and($2='amine')) then
      getparam('aH90_mpHN','H1'):aH90
      getparam('pwH90_mpHN','H1'):$pwH90_mp
   else
      banner('Calibration Nucleus and Region Not Found')
      abort
   endif
endif 

// Set TPPM from SPINAl, use SPINAL - save MAS Info

aHtppm=aHspinal pwHtppm=pwHspinal phHtppm=pwHspinal
n1=$string1 n2=$string2 n3=$2
srate=$avgsrate temp=$temp

// Set Up the Medium-Power 1H Nutation Array

$pwH90step=$pwH90_mp/10.0

// Set the Auto Display to ph or av

if (BPplotmode='ph') then 
   wnt='vp=50 sb=\'n\' wft setref ph SS_AutoCal_aph0(\'array\'):$ok if ($ok<>1) then sb=\'y\' wft av endif SS_AutoCal_maxamp(50) noislm(0.5) dssh'
else 
   wnt='vp=0 sb=\'y\' wft setref av SS_AutoCal_maxamp(100) noislm(1.0) dssh'
endif 
text('1H Nutation Experiment at\\Medium Power')
if (($1='C13')and($2='alpha')) then atext('for C13-alpha') endif
if (($1='C13')and($2='carbonyl')) then atext('for C13-carbonyl') endif
if (($1='N15')and($2='amide')) then atext('for N15-amide') endif
if (($1='N15')and($2='amine')) then atext('for N15-amine') endif
atext(n1) atext(n2)
array('pwH90',50,$pwH90step,$pwH90step)
wexp='SS_1_CP(\''+ $1 +'\',\'' + $2 + '\')'
au 

