#!/bin/bash

cat Candidate_list.txt | while read file motif gene
do
    echo "Processing: FILE=${file}  MOTIF=${motif}  GENE=${gene}"

    # 输出文件名更安全
    out="${file}_${gene}.txt"
    peak="${file}_${gene}_peak.txt"

    # 路径检查：是否存在 motif 文件
    motif_file="${file}/homerResults/${motif}.motif"
    if [[ ! -f "$motif_file" ]]; then
        echo "WARNING: Motif file missing: $motif_file"
        continue
    fi

    # 运行 findMotifsGenome.pl
    findMotifsGenome.pl ${file}.txt mm10 ${file} \
        -size given \
        -find "$motif_file" > "$out"

    # 生成唯一 peak list
    cut -f1 "$out" | sed '1d' | sort -u > "$peak"

    echo "Output → $out"
    echo "Peak list → $peak"
    echo "----------------------------------------"

done
