#!/bin/bash

# Check for input argument
if [ "$#" -ne 2 ]; then
    echo "Usage: $0 <input.bigBed> <output.bedGraph>"
    exit 1
fi

# Input and output files
INPUT_BIGBED="$1"
OUTPUT_BEDGRAPH="$2"

# Temporary files
TEMP_BED="temp.bed"
FILTERED_BEDGRAPH="temp_filtered.bedGraph"
SORTED_BEDGRAPH="temp_sorted.bedGraph"
WINDOW_OUTPUT="temp_window.bedGraph"

# Path to UCSC bigBedToBed tool
BIGBEDTOBED="./bigBedToBed"

# Check if bigBedToBed is available
if ! command -v $BIGBEDTOBED &> /dev/null; then
    echo "Error: bigBedToBed tool not found. Please install it or add it to your PATH."
    exit 1
fi

# Step 1: Convert bigBed to BED
echo "Converting bigBed to BED..."
$BIGBEDTOBED "$INPUT_BIGBED" "$TEMP_BED"

# Step 2: Filter uncovered sites and convert to BedGraph format
echo "Filtering uncovered sites and creating BedGraph format..."
awk 'BEGIN{OFS="\t"} $5 > 0 {print $1, $2, $3, $11}' "$TEMP_BED" > "$FILTERED_BEDGRAPH"

# Step 3: Sort the BedGraph file
echo "Sorting BedGraph file..."
sort -k1,1 -k2,2n "$FILTERED_BEDGRAPH" > "$SORTED_BEDGRAPH"

# Step 4: Compute signal in sliding windows and filter out empty positions
echo "Computing signal in sliding windows (5kb) and filtering out empty positions..."
GENOME_FILE="hg38.sorted.genome"
bedtools makewindows -g "$GENOME_FILE" -w 5000 -s 5000 | \
bedtools map -a stdin -b "$SORTED_BEDGRAPH" -c 4 -o mean | \
awk '$4 != "."' > "$WINDOW_OUTPUT"

# Step 5: Output final BedGraph file
echo "Saving final BedGraph file to $OUTPUT_BEDGRAPH..."
mv "$WINDOW_OUTPUT" "$OUTPUT_BEDGRAPH"

# Cleanup temporary files
rm -f "$TEMP_BED" "$FILTERED_BEDGRAPH" "$SORTED_BEDGRAPH"

echo "Processing complete. Final file: $OUTPUT_BEDGRAPH"

