#!/bin/bash

# This script iterates through all .mcool files in the current directory
# and runs the 'cooler balance' command on each of them, up to 10 in parallel.

# Define the blacklist file path
BLACKLIST_FILE="/net/projects/hic-atlas/atlas-v2/blacklist.bed"

# Define the number of processes for each cooler command
NUM_PROCESSES_PER_COOLER=4

# Define the resolution
RESOLUTION="50000"

# Define the maximum number of parallel jobs
MAX_PARALLEL_JOBS=10

# Check if the blacklist file exists
if [ ! -f "$BLACKLIST_FILE" ]; then
    echo "Error: Blacklist file not found at $BLACKLIST_FILE"
    exit 1
fi

# Initialize a counter for active jobs
active_jobs=0

# Create an array of files to process
files_to_process=(*.mcool)

echo "Starting parallel processing of .mcool files..."

for mcool_file in "${files_to_process[@]}"; do
    # Check if the file exists and is a regular file
    if [ -f "$mcool_file" ]; then
        # Construct the command
        command_to_run="cooler balance --mad-max 0 --blacklist \"$BLACKLIST_FILE\" -p $NUM_PROCESSES_PER_COOLER --force \"$mcool_file::/resolutions/$RESOLUTION\""

        # Run the command in the background
        ( # Start a subshell for each command to group output and error handling
            eval "$command_to_run"
            if [ $? -eq 0 ]; then
                echo "SUCCESS: $mcool_file (Resolution: $RESOLUTION)"
            else
                echo "ERROR: $mcool_file (Resolution: $RESOLUTION) - Check logs/output for details."
            fi
        ) & # Run the subshell in the background

        # Increment active jobs counter
        ((active_jobs++))

        # If the maximum number of parallel jobs is reached, wait for one to finish
        if [ "$active_jobs" -ge "$MAX_PARALLEL_JOBS" ]; then
            wait -n # Waits for the next job to terminate
            ((active_jobs--))
        fi
    else
        # This case might not be reached if *.mcool only matches files,
        # but it's good practice if the glob could match other things.
        echo "Skipping $mcool_file, not a regular file."
    fi
done

# Wait for all remaining background jobs to complete
wait

echo "All .mcool files processed."
