#!/bin/bash


#launch job in parralel
MAX_JOBS=$(( $(nproc) -4 ))   # Maximum parallel jobs
SEMAPHORE="job_semaphore"

# Create a named pipe (FIFO) for job control
mkfifo $SEMAPHORE
exec 3<> $SEMAPHORE
rm $SEMAPHORE

# Pre-fill the semaphore with tokens equal to MAX_JOBS
for ((i=0; i<MAX_JOBS; i++)); do
    echo "" >&3
done


for section in {0..20}; do
    read -u 3  # Wait for an available slot
    {
        root -l -q "./ToffHighRes.C($section,0.0)" 
        echo "" >&3  # Release the slot
    } & 
done

wait

exec 3>&- #close semaphore 

wait 

root -l -q "./MergeToff.C()"
