#!/bin/sh  
# \
exec oagtclsh "$0" "$@"

# $Log: not supported by cvs2svn $

set auto_path [linsert $auto_path 0 /usr/local/oag/apps/lib/$env(HOST_ARCH)]
set auto_path [linsert $auto_path 0 /usr/local/oag/lib_patch/$env(HOST_ARCH)]
APSStandardSetup

set usage "usage: makeDataReviewSRBPMFiles"

# make list of sectors which has both P0's working
if [catch {APSSRGetWorkingP0SectorsList} P0List] {
    puts stderr "Error (1) for $argv0 in [pwd]: $result"
    exit 1
}

for {set sector 1} {$sector<41} {incr sector} {
    puts stderr "Working on $sector"
    set filenameAve [format srBPMAve.tmp%02ld $sector]
    set filename    [format srBPMs.tmp%02ld $sector]
    set sectorP1 [expr $sector+1]
    if $sectorP1>40 {
        set sectorP1 1
    }
    set P0Name  S${sector}B:P0
    set P0Name1 S${sectorP1}A:P0
    set extraCmd ""
    if {[lsearch $P0List $P0Name]!=-1 && [lsearch $P0List $P0Name1]==-1} {
        # plot P0's instead of P1's 
        set extraCmd "100%/P1/P0/"
    }
    exec sddsprocess srBPMs.sdds.template $filename \
      -reedit=column,PlotDescription,100%/<sector>/$sector/100%/<sectorP1>/$sectorP1/ \
      -reedit=column,sddsplotOptions,100%/<sector>/$sector/100%/<sectorP1>/$sectorP1/$extraCmd
    exec sddsprocess srBPMAve.sdds.template $filenameAve \
      -reedit=column,PlotDescription,100%/<sector>/$sector/100%/<sectorP1>/$sectorP1/ \
      -reedit=column,sddsplotOptions,100%/<sector>/$sector/100%/<sectorP1>/$sectorP1/$extraCmd
    lappend srBPMAveList $filenameAve
    lappend srBPMsList   $filename
}

foreach group {srBPMAve srBPMs} {
    set nameList [lsort [glob -nocomplain ${group}.sdds-????]]
    set newLink [APSNextGenerationedName -name [lindex $nameList end] \
                   -newFile 1]
    eval exec sddscombine [subst \$${group}List] -merge $newLink
    catch {eval file delete [subst \$${group}List]  $group.sdds}
    exec ln -s $newLink $group.sdds
}
