"SS_AutoCal_DCP: Calibration of Amide DCP with C-carbonyl and C-alpha           "
  
"      This macro requires the Solids sequences tancpx.c, tancpxflip.c and      "
"      dcptan.c, the setup macros tancpx, tancpxflip and dcptan, 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. For BPpresent='' the workspace  "
"      is intialized with Settancpx.par. For both modes, BPpresent='y' or '',   "
"      initial calibrations come from the appropriate parameter group HCa, HCO, "
"      and HNai. For 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.                                               "

"      This macro calls SS_1_DCP, SS_2_DCP and SS_3_DCP in sequence.            "
"      Current regions: ('13C','alpha') peptide alpha region (HCa)              "
"                       ('13C','carbonyl') peptide carbonyl region (HCO)        "

"      For 15N the region('15N','amide') peptide amide region (HNai) is assumed "

"      For operation with BPpresent='y', if BioPack is not installed, the macros"
"      tancpx_HCa, tancpx_HCO, tancpx_HNai and tancpx_HNam 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
   
// Initialize the Workspace for Solids

$sysparfile=systemdir+'/parlib/Settancpx.par'
$parfile=userdir+'/parlib/Settancpx.par'
exists($parfile,'file'):$e
if ($e>0.5) then
   rtp($parfile)
else
   exists($sysparfile,'file'):$e
   if ($e>0.5) then
      rtp($sysparfile)
   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

// Create BPregion if it does not exist

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

// 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 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=1) 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,'CP1 %s %s Calibration on %s',$1,$2,$date)
   write('line3','CP1 %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_DCP')  endif
      if (($1='C13')and($2='carbonyl')) then  man('SSpreface_CO_DCP')  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 13C 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 
   tancpxt1rho 
   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 sp=45p wp=30p 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 sp= 165p wp=20p setref
      getparam('pwHspinal_HCO','H1'):pwHspinal
      getparam('aHspinal_HCO','H1'):aHspinal
      getparam('phHspinal_HCO','H1'):phHspinal
      getparam('pwH90_hp_HCO','H1'):pwH90
      getparam('aH90_hp_HCO','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
   cdc ai 
else
   if ($2='alpha') then
      tancpxt1rho_Ca
   elseif ($2='carbonyl') then
      tancpxt1rho_CO 
   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' 
   cdc ai
endif

// Establish the Remaining Ramp Parameters

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

// Obtain aH90_hp, aX90 and pwX90 from the Probe File 

if (($1='C13')and($2='alpha')) then
   getparam('aX90_HCa','C13'):$aX90_sp
   getparam('pwX90_HCa','C13'):$pwX90_sp
   getparam('aH90_hpHCa','H1'):$aH90_hp
elseif (($1='C13')and($2='carbonyl')) then
   getparam('aX90_HCO','C13'):$aX90_sp
   getparam('pwX90_HCO','C13'):$pwX90_sp
   getparam('aH90_hpHCO','H1'):$aH90_hp
else
   banner('Calibration Nucleus and Region Not Found')
   abort
endif

// Set TPPM from SPINAl - save MAS Info

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

// Setup the 13C Spinlock Array based on the Medium-Power $B1 0.0 to +3.0*srate

$B1=1.0e6/(4.0*$pwX90_sp) 
$aXlockmax=$aX90_sp*(3.0*srate)/$B1
if ($aXlockmax>$aX90_sp) then $aXlockmax=$aX90_sp endif
$stepsize=trunc((($aXlockmax-120)/40) + 0.5)
array('aXlock',41,120,$stepsize) 
aHlock=$aH90_hp
tlock=3000

// Set the Auto Display to ph or av

if (BPplotmode='ph') then 
   wnt='vp=0 sb=\'n\' wft setref ph SS_AutoCal_aph0(\'array\'):$ok if ($ok<>1) then sb=\'y\' wft av endif SS_AutoCal_maxamp(100) noislm(1.0) dssh'
else 
   wnt='vp=0 sb=\'y\' wft setref av SS_AutoCal_maxamp(100) noislm(1.0) dssh'
endif 
text('13C T1rho Spinlock Array')
if (($1='C13')and($2='alpha')) then atext('for C13-alpha') endif
if (($1='C13')and($2='carbonyl')) then atext('for C13-carbonyl') endif
atext(n1) atext(n2)
wexp='SS_1_DCP(\''+ $1 +'\',\'' + $2 + '\')'
au


