"SS_AutoCal_DP: Automatic Calibration of Pulse Widths and CP Using Onepulse     "
"               Followed by a CP Match,                                         "

"      This macro requires the Solids sequences tancpx.c and onepul.c, the      " 
"      setup macros tancpx and onepul, 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' or 'on'. The optional BPplotdir specifies a  "
"      directory when BPplot='file'.  The probe file must use the template      " 
"      SS_AutoCal_probe.template. 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 HC, or HN.                "
"      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_HC and SSpreface_HN, should be present in the "
"      manuals directory.                                                       "

"      This macro calls SS_1_DP, SS_2_DP, SS_3_DP and SS_4_DP in sequence       "
"      Current regions: ('13C','adam') adamantane CH at 38.3ppm (HC)            "
"                       ('15N','amino') amino acid amino region (HN)            "

"      For operation with BPpresent='y', if BioPack is not installed, the macros"
"      onepul_HC and onepul_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 1. These parameters would otherwise be       "
"      created by a Solids BioPack installation. Parameter files tancpx_C13 and "
"      tancpx_N15 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_DP(\'nucleus\',\'region\')')
   abort
endif
if (($2='adam')or($2='amino')) then
   n1=$2 
endif
$2=n1 n1=''
if (($2<>'adam')and($2<>'amino')) then
   write('error','Region = \'adam\' or \'amino\'')
   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($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
      
// 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
   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

// 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')

// Set BPplotdir if it Exists

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

// 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 in the AutoTripRes Directory

$file='Log_'+$1+'_'+$2
cd(userdir)
exists('AutoTripRes','file'):$e
if ($e=1) then
   cd('AutoTripRes')
   write('reset',$file)
   write('file',$file,'DP %s %s Calibration on %s',$1,$2,$date)
   write('line3','DP %s %s Calibration on %s',$1,$2,$date)
   write('file',$file,'Temperature = %6.1fC, Spin Rate = %fHz',temp,srate)
   write('line3','Temperature = %6.1fC, Spin Rate = %fHz',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='adam')) then  man('SSpreface_adam_DP') endif
      if (($1='N15')and($2='amine')) then  man('SSpreface_am_DP') endif
      printoff
   endif
endif

//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

write('line3','wp = %f\n',wp)
if (BPpresent<>'y') then
   onepul
   if (($1='C13')and($2='adam')) then
      tn='H1' dn='C13' dn2='N15' ampmode='pdpp'
      getsolidsprobedata('tn') getsolidsprobedata('dn') getsolidsprobedata('dn2')
      setref setoffset('H1',2.0):tof tof=0.1*trunc(tof/0.1 + 0.5) sp=-8p wp=20p dof=0.0 setref 
   elseif (($1='N15')and($2='amino')) then
      tn='H1' dn='N15' dn2='C13' ampmode='pdpp'
      getsolidsprobedata('tn') getsolidsprobedata('dn') getsolidsprobedata('dn2')
      setref setoffset('H1',5.0):tof tof=0.1*trunc(tof/0.1 + 0.5) sp=-5p wp=20p dof=0.0 setref 
   else
      banner('Calibration Nucleus and Region Not Found')
      abort
   endif
else
   if (($1='C13')and($2='adam')) then
      onepulH1_HC
      setref setoffset('H1',2.0):tof tof=0.1*trunc(tof/0.1 + 0.5) sp=-8p wp=20p dof=0.0 setref 
   elseif (($1='N15')and($2='amino')) then
      onepulH1_HN
      setref setoffset('H1',5.0):tof tof=0.1*trunc(tof/0.1 + 0.5) sp=-5p wp=20p dof=0.0 setref 
   else
      banner('Calibration Nucleus and Region Not Found')
      abort
   endif
endif    
cdc ai
write('line3','2wp = %f\n',wp)

ad=2.0 rd=2.0 ddrtc=4.0 lp=0 d1=3.0 nt=1 ss=1 bs=1
sw=100000.0 at=0.003 fn=16.0*np sb=at/2.0 sb='y' sbs='n' lb=0 gain=30  
dpwr=0 aH90=0.0 pwH90=0.0 aHspinal=0.0 phHspinal=0.0 pwHspinal=8.0 Hseq='spinal'

// Get Medium Power Calibrations 

if (($1='C13')and($2='adam')) then
   getparam('aH90_mpHC','H1'):$aH90_mp
   getparam('pwH90_mpHC','H1'):$pwH90_mp
elseif (($1='N15')and($2='amino')) then
   getparam('aH90_mpHN','H1'):$aH90_mp
   getparam('pwH90_mpHN','H1'):$pwH90_mp
else
   banner('Calibration Nucleus and Region Not Found')
   abort
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

aX90=$aH90_mp
$pwX90step=$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 select(r1) 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='adam')) then atext('for C13-adam') endif 
if (($1='N15')and($2='amino')) then atext('for N15-amino') endif
atext(n1) atext(n2)
array('pwX90',50,$pwX90step,$pwX90step)
wexp='SS_1_DP(\''+ $1 +'\',\'' + $2 + '\')'

// Setup for Offset Correction 

exists('autooffsetflag','parameter'):$e
if ($e<0.5) then 
   create('autooffsetflag')
endif
autooffsetflag=2
au
