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

# $Log: not supported by cvs2svn $
# Revision 1.20  2008/06/02 22:01:34  emery
# Replace executable "replace" with replaceText. The old "replace" conflicts
# with new linux and solaris utilities.
#
# Revision 1.19  2006/04/13 19:49:26  soliday
# Changed the tolerance of the SR corrector setpoints back the what they
# were before I changed them last week.
#
# Revision 1.18  2006/04/07 16:09:51  soliday
# Changed the tolerance of the SR corrector setpoints.
#
# Revision 1.17  2005/12/21 20:04:22  shang
# added making mt corrector request file according to the status.
#
# Revision 1.16  2005/12/19 23:25:18  shang
# added making corrector setpoints and checking added and removed PVs.
#
# Revision 1.15  2005/08/08 19:38:26  emery
# Removed recent addition of *.RateP and *.FactorP PVs to the widlcard
# match of IDBM request file. These PVs will be incorporated
# into SR.req through SROrbitSetPt.req and its template.
#
# Revision 1.14  2005/08/04 17:24:48  emery
# Fixed a problem importing *ID*RateP PVs from IDBM.req.
#
# Revision 1.13  2004/06/09 16:32:11  emery
# Added to comments.
#
# Revision 1.12  2003/09/26 15:59:57  emery
# Added comments explaining the contents of the SR.req.set* files
#
# Revision 1.11  2003/03/22 03:40:54  emery
# Renamed tmp files so that they are more easily identifiable.
#
# Revision 1.10  2003/03/22 02:32:49  emery
# In creating file with cerenkov PV, added the removal of
# ioc_name column.
#
# Revision 1.9  2003/01/21 15:02:52  emery
# Moved procedure makeCerenkovFile earlier and changed
# the location of the | command.
#
# Revision 1.8  2002/10/02 19:05:42  shang
# replaced burtrb by obtaining pvs from iocRecName.sdds
#
# Revision 1.7  2002/06/18 18:08:14  borland
# Now retains ID*Gap PVs (gap readbacks).
#
# Revision 1.6  2002/06/17 20:27:52  borland
# Use the IsProtected and IsReadOnly values from the IDBM.req file instead of
# overwriting them.
#
# Revision 1.5  2002/06/17 20:09:07  borland
# Selects GapReturn as well as GapSet PVs for IDs.
#
# Revision 1.4  2002/06/10 22:16:55  borland
# Added SR.req.set12 to list of files to be combined.
#
# Revision 1.3  2002/05/22 17:23:56  emery
# Added regeneration of SR.req.set9, the cerenkov detector setup.
#
# Revision 1.2  2000/10/31 00:10:59  emery
# Use makeIDBMreqFile instead of makeIDBMFile
#
# Revision 1.1  2000/10/27 02:09:26  emery
# First installation.
#

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 recordFile /home/helios/oagData/pvdata/iocRecNamesOAG.sdds
set rootname SR
set usage {usage: makeSRReqFile [-output <filename> | -install 1]}
set output ""
set install 0
set args $argv
if {[APSStrictParseArguments {output install}] || \
      (![string length $output] && !$install) || \
      ([string length $output] && $install)} {
    puts stderr "Error for $argv0 in [pwd]: $usage"
    exit 1
}
if [file exist $rootname.req] {
    set lastFile [file readlink $rootname.req]
} else {
    set lastFile ""
}
if !$install {
    if [file exists $output] {
        puts stderr "Error for $argv0 in [pwd]: $output exists"
        exit 1
    }
} else {
    if ![string length $lastFile] {
        set lastFile $rootname.req-0000
    }
    set output [APSNextGenerationedName -name $lastFile -separator - -newFile 1]
}
#make MT corrector request file
proc makeMTCorReqFile {args} {
    set output ""
    APSParseArguments {output}
    set tmpfile /tmp/[APSTmpString]
    set MTstatus /home/helios/oagData/sr/HCorrectorStatus/config.sdds
    set recordFile /home/helios/oagData/pvdata/iocRecNamesOAG.sdds
    if [catch {exec sddsprocess $MTstatus -pipe=out \
                 -match=col,DeviceName=*:MT  \
                 -filter=col,Nonexistent,0,0 \
                 | sddsconvert -pipe=in $tmpfile.MTCorr -retain=col,DeviceName} result] {
        return -code error "makeMTCorReqFile: $result"
    }
    set extensionList {:CurrentAI :CurrentAO :RateDividerAO :StatusCALC}
    set toleranceList {0.1 1.0e-3 0.0 0.0}
    set readList {y n n y}
    set protectList {n n y n}
    foreach ext $extensionList tol $toleranceList read $readList protect $protectList {
        if [catch {exec sddsprocess $tmpfile.MTCorr $tmpfile.MTCorr$ext \
                     -edit=col,ControlName,DeviceName,ei/$ext/ \
                     -print=col,ControlType,pv \
                     -print=col,Category,SteeringPS \
                     -print=col,IsNumerical,y,type=character \
                     -define=col,Tolerance,$tol \
                     -print=col,Beamline,SR \
                     -print=col,OpsIntervention,n,type=character \
                     -print=col,IsReadOnly,$read,type=character \
                     -print=col,IsProtected,$protect,type=character } result] {
            return -code error "makeMTCorReqFile: $result"
        }
        lappend fileList $tmpfile.MTCorr$ext
    }
    if [catch {eval exec sddscombine $fileList -merge -pipe=out \
                 | sddsprocess -pipe \
                 -edit=col,rec_name,ControlName,S?/./D \
                 | sddssort -column=rec_name -pipe \
                 | sddsxref -reuse -nowarnings -pipe $recordFile -match=rec_name \
                 | sddsconvert -pipe -delete=col,rec_name,ioc_name,DeviceName \
                 | sddssort -pipe=in -numericHigh -col=ControlName -unique $output \
             } result] {
        return -code error "makeMTCorReqFile: $result"
    }
    eval file delete -force $fileList
    file delete -force $tmpfile.MTCorr
}

# make Steering Accumulator request file
proc makeSteeringAccumulatorFile {args} {
    set output ""
    APSParseArguments {output}
    set tmpfile /tmp/[APSTmpString]
    set recordFile /home/helios/oagData/pvdata/iocRecNamesOAG.sdds
    for {set sector 1} {$sector < 36} {incr sector} {
        if [catch {exec replaceText SR.req.set14.template $tmpfile.sector$sector \
                     -orig=<sector> -replace=$sector \
                 } result] {
            return -code error "makeCerenkovFile: $result"
        }
        lappend fileList $tmpfile.sector$sector
    }
    if [catch {eval exec sddscombine $fileList -merge -pipe=out \
                 | sddsprocess -pipe  \
                 -edit=col,rec_name,ControlName,S?/./D \
                 | sddssort -column=rec_name -pipe \
                 | sddsxref -reuse -nowarnings -pipe $recordFile -match=rec_name \
                 | sddsconvert -pipe -delete=col,rec_name,ioc_name \
                 | sddssort -pipe=in -column=ControlName -numeric -unique $output \
             } result] {
        return -code error "makeCerenkovFile: $result"
    }
    eval file delete $fileList
    return
}
proc makeCerenkovFile {args} {
    set output ""
    APSParseArguments {output}
    set tmpfile /tmp/[APSTmpString]
    set sectorList [exec sdds2stream -col=Sector \
                      /home/helios/oagData/sr/cerenkov/sectors.sdds]
    set recordFile /home/helios/oagData/pvdata/iocRecNamesOAG.sdds
    foreach sector $sectorList {
        if [catch {exec replaceText SR.req.set9.template $tmpfile.sector$sector \
                     -orig=<sector> -replace=$sector \
                 } result] {
            return -code error "makeCerenkovFile: $result"
        }
        lappend fileList $tmpfile.sector$sector
    }
    if [catch {eval exec sddscombine $fileList -merge -pipe=out \
                 | sddsprocess -pipe  \
                 -edit=col,rec_name,ControlName,S?/./D \
                 | sddssort -column=rec_name -pipe \
                 | sddsxref -reuse -nowarnings -pipe $recordFile -match=rec_name \
                 | sddsconvert -pipe -delete=col,rec_name,ioc_name \
                 | sddssort -pipe=in -column=ControlName -numeric -unique $output \
             } result] {
        return -code error "makeCerenkovFile: $result"
    }
    eval file delete $fileList
    return
}

set tmpfile /tmp/[APSTmpString]
# make a new IDBM request file 
set IDBM $tmpfile.IDBM
if [catch {exec makeIDBMreqFile -mode SR -install 0 -output $IDBM} result] {
    puts stderr "Error for $argv0 in [pwd]: $result"
    exit 1
}
# extract data from IDBM file (gap settings and *ID*RateP) to add to this file
if [catch {exec sddsprocess $IDBM -pipe=out \
         -match=column,ControlName=ID*GapSet*,ControlName=*GapReturn*,|,ControlName=*Gap,|,ControlName=ID*CurrentReturn,|,ControlName=ID*Select,| \
             | sddsconvert -pipe -dele=column,Category,Beamline,OpsIntervention \
             | sddsprocess -pipe=in $tmpfile.IDBM1 \
             -print=column,Category,ID -print=column,Beamline,SR \
             -print=column,OpsIntervention,n,type=character} result] {
    puts stderr "Error for $argv0 in [pwd]: $result"
    exit 1
}

# make a new SROrbitSetPt.req file for use by this script
set orbitSetPt $tmpfile.orbitSetPt
if [catch {exec makeOrbitSetPtReqFile -output $orbitSetPt -mode SR} result] {
    puts stderr "Error for $argv0 in [pwd]: $result"
    exit 1
}
#remove RateP and OffsetP pv from SR.req
if [catch {exec sddsprocess $orbitSetPt $orbitSetPt.1 -match=col,ControlName=*RateP,! \
	       -match=col,ControlName=*OffsetP,! \
	  -match=col,ControlName=*FactorP,!  } result] {
    puts stderr "Error for $argv0 in [pwd]: $result"
    exit 1	
}
exec mv $orbitSetPt.1 $orbitSetPt

set corrSetPt $tmpfile.corrSetPt
if [catch {exec makeCorSetPtReqFile -output $corrSetPt -mode SR} result] {
    puts stderr "Error for $argv0 in [pwd]: $result"
    exit 1
}
#make MT Corrector request file
if [catch {makeMTCorReqFile -output $tmpfile.mt} result] {
    puts stderr "Error for $argv0 in [pwd]: $result"
    exit
}
#make BPLD request file
set bpldFile $tmpfile.bpld
if [catch {exec makeBPLDreqFile -output $bpldFile -mode SR} result] {
    puts stderr "Error for $argv0 in [pwd]: $result"
    exit 1
}

if [catch {makeCerenkovFile -output SR.req.set9} result] {
    puts stderr "Error for $argv0 in [pwd]: $result"
    exit 1
}

if [catch {makeSteeringAccumulatorFile -output SR.req.set14} result] {
    puts stderr "Error for $argv0 in [pwd]: $result"
    exit 1
}

# files            content
# SR.req.set1      magnets, timing, rf brief, scrapers, some diagnostics
# SR.req.set1-0032 magnets, timing, rf brief, scrapers, some diagnostics but no corrector setpoints
# the command for creating SR.req.set1-0032 is
# sddsselect SR.req.set1-0030 SRCorSetpts.req -match=ControlName -invert SR.req.set1-0032
# SR.req-set1-0033 magnets, timing, rf brief, scrapers, some diagnostics but no 
#                  corrector setpoints and  no MT correctors, the command for creating
#                  SR.req-set1-0033 is
#                  sddsprocess SR.req.set1-0032 SR.req.set1-0033 -match=col,ControlName=*:MT:*,!
# SR.req.set2      magnets readback offsets.
# SR.req.set3      magnets tolerance
# SR.req.set4      SBM redaback data (NMR, transductors)
# SR.req.set5      beam lifetime calculated and chromaticity based on sextupoles and lattice model
# SR.req.set6      magnets drive limits (hi)
# SR.req.set7      magnets drive limits (hi)
# SR.req.set8      BPLD trip limits. Not used anymore. Use makeBPLDreqFile.
# SR.req.set9      Cerenkov data
# SR.req.set10     Video (image) data
# SR.req.set11     Include in RMS bpms
# the file below is reqmoved. ID11 is no longer a wiggler, These PVs no longer exists.
# SR.req.set12     ID11 FF data            
# SR.req.set13     S35 Pinhole Camera
# SR.req.set14     Steering accumulator PVs

if [catch {eval exec sddscombine $tmpfile.corrSetPt $tmpfile.mt SR.req.set1 \
             SR.req.set2 SR.req.set3 \
             SR.req.set4 SR.req.set5 SR.req.set6 SR.req.set7 $bpldFile \
             SR.req.set9 SR.req.set10 SR.req.set11  SR.req.set13 SR.req.set14 \
             $tmpfile.IDBM1 $tmpfile.orbitSetPt SCU1.req SCU6.req HSCU.req \
             $output.tmp -merge -overWrite \
         } result] {
    puts stderr "Error for $argv0 in [pwd]: $result"
    exit 1
}

#  Make sure there is only one instance of each name
# I don't know what the the column Row is used for.
if [catch {exec sddsprocess $output.tmp -pipe=out \
             -edit=col,rec_name,ControlName,S?/./D \
             | sddssort -pipe -col=rec_name \
             | sddsxref -reuse -nowarnings -pipe $recordFile -match=rec_name \
             | sddsconvert -pipe -delete=col,rec_name,ioc_name \
             | sddssort -pipe=in $output -unique \
             -col=Category -column=ControlName -numericHigh  \
         } result] {
    puts stderr "Error for $argv0 in [pwd]: $result"
    exit 1
}
catch {file delete -force -- $output.tmp}

if [string length $lastFile] {
    puts "New file: [exec sdds2stream -rows $output]"
    puts "Last file: [exec sdds2stream -rows $lastFile]"
    exec sddsselect $output $lastFile -match=ControlName -invert $rootname.added 
    exec sddsselect $lastFile $output -match=ControlName -invert $rootname.removed 
    puts "PVs added ($rootname.added): [exec sdds2stream -rows $rootname.added]"
    puts "PVs removed ($rootname.removed): [exec sdds2stream -rows $rootname.removed]"
}
if $install {
    if [file exists ${rootname}.req] {
        if [catch {file delete ${rootname}.req} result] {
            puts stderr "Error for $argv0 in [pwd]: $result"
            exit 1  
        }
    }
    catch {exec chmod -w $rootname.req}
    if [catch {exec ln -s $output ${rootname}.req} result] {
        puts stderr "Error for $argv0 in [pwd]: $result"
        exit 1
    }
    if [catch {APSMakeSCRCategoryFiles -input ${rootname}.req} result] {
        puts stderr "Error for $argv0 in [pwd]: $result"
        exit 1
    }
}
