target_reads=10000000
genome_sizes="hg38.25_chromsome.sizes"


bam_file="test_merged.sorted.bam"
bedgraph_file="test_merged.sorted.bedGraph"
norm_bedgraph_file="test_10M.bedgraph"
bigwig_file="test_10M.bigWig"

    if [[ ! -f "$bam_file" ]]; then
        echo "BAM file $bam_file does not exist. Skipping."
        continue
    fi

    if [[ ! -f "$bedgraph_file" ]]; then
        echo "BedGraph file $bedgraph_file does not exist. Skipping."
        continue
    fi

    mapped_reads=$(samtools view -c -F 4 "$bam_file")
    echo "Total number of mapped reads for $base_name: $mapped_reads"

    if ((mapped_reads == 0)); then
        echo "No mapped reads found for $base_name. Skipping normalization."
        continue
    fi

    factor=$(bc <<< "scale=6; $target_reads / $mapped_reads")

    awk -v factor="$factor" '{$4 *= factor; print}' "$bedgraph_file" > "$norm_bedgraph_file"

    bedGraphToBigWig "$norm_bedgraph_file" "$genome_sizes" "$bigwig_file"

    echo "Tissue $base_name successfully converted to bigWig."

done
