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

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: setUp324WithGaps -nGaps <number> -gapLength <slots> -guardBunches {0|1} -rootname <string>"
set nGaps -1
set gapLength -1
set guardBunches -1
set rootname ""
set args $argv
if {[APSStrictParseArguments {nGaps gapLength guardBunches rootname}] || \
   [expr $nGaps<0] || [expr $gapLength<0] || [expr $guardBunches<0] || [string length $rootname]==0} {
    puts stderr $usage
    exit 1
}
if {[file exists $rootname.pattern] || [file exists $rootname.putMe]} {
    puts stderr "In use: $rootname"
    exit
}

if [expr $guardBunches!=0] {
    set guardBunches 1
}
if [expr $gapLength%2!=0] {
    puts stderr "gapLength must be even"
    exit 1
}

if [expr 324%$nGaps!=0] {
   puts stderr "nGaps=$nGaps does not divide evenly into 324"
   exit 1
}

for {set n 0} {$n<324} {incr n} {
    set multiplier($n) 1
}

for {set gap 0} {$gap<$nGaps} {incr gap} {
    set limit1 [expr ($gap+1)*324/$nGaps]
    set limit0 [expr $limit1-$gapLength]
    #puts stderr "Blank out: $limit0 -> [expr $limit1-1]"
    for {set slot $limit0} {$slot<$limit1} {incr slot} {
        set multiplier([expr $slot%324]) 0
    }
    set limit1 [expr $limit0]
    set limit0 [expr $limit1-$guardBunches*$gapLength/2]
    #puts stderr "Double: $limit0 -> [expr $limit1-1]"
    for {set slot $limit0} {$slot<$limit1} {incr slot} {
        set multiplier([expr $slot%324]) 2
    }
    set limit0 [expr ($gap+1)*324/$nGaps]
    set limit1 [expr $limit0+$guardBunches*$gapLength/2]
    #puts stderr "Double: $limit0 -> [expr $limit1-1]"
    for {set slot $limit0} {$slot<$limit1} {incr slot} {
        set multiplier([expr $slot%324]) 2
    }
}

set bucketList ""
set multList ""
set count 0
for {set slot 0} {$slot<324} {incr slot} {
    lappend bucketList [expr 4*$slot]
    lappend multList $multiplier($slot)
    if $multiplier($slot) {
        incr count $multiplier($slot)
    }
}

exec sddsmakedataset $rootname.pattern \
  -column=Bucket,type=long -data=[join $bucketList ,] \
  -column=Multiplier,type=long -data=[join $multList ,] 

set pvList Mt:SRinjectNumBunchesAO.VAL
set valueList $count
set offset 0
for {set slot 0} {$slot<324} {incr slot} {
    if $multiplier($slot)!=0 {
        lappend pvList Mt:SRbunch[format %03d $offset].VAL
        lappend valueList [expr $slot*4]
        incr offset
    }
    if $multiplier($slot)==2 {
        lappend pvList Mt:SRbunch[format %03d $offset].VAL
        lappend valueList [expr $slot*4]
        incr offset
    }
}

exec sddsmakedataset $rootname.putMe \
  -column=ControlName,type=string -data=[join $pvList ,] \
  -column=ValueString,type=string -data=[join $valueList ,]
