#!/bin/bash

# This script will take the TADMAP output and convert it to a bed4 file
infile_geneset='TADMap_geneset_mm.csv'
infile_TAD_coordinates='TADMap_scaffold_mm.bed'
outfile='TADMap_geneset_mm.bed'
tmp_gene_name='gene_name.tmp'

echo $infile_geneset
echo $infile_TAD_coordinates
echo $outfile
echo $tmp_gene_name

# extract all the gene names from the TADMap_geneset_mm.csv file 2nd columns in format of "gene_name_1|ensembl_id_1|MGI_id_1;gene_name_2|ensembl_id_2|MGI_id_2;...;gene_name_n|ensembl_id_n|MGI_id_n"
awk '{
    n = split($0, entries, ";") # Split the line by semicolon
    gene_names = ""
    for (i = 1; i <= n; i++) {
        split(entries[i], parts, "|") # Split each entry by pipe
        if (gene_names == "") {
            gene_names = parts[1] # Add the gene name
        } else {
            gene_names = gene_names "," parts[1] # Append with comma
        }
    }
    if (gene_names == "") {
        gene_names = "NA"
    }
    print gene_names
}
' <(cut -f2 -d',' $infile_geneset|tail -n+2) > $tmp_gene_name

paste -d' ' <(cat $infile_TAD_coordinates) $tmp_gene_name > $outfile
rm $tmp_gene_name
# add column 5 with 0s (score) and column 6 with . (strand) tab-separated
#awk 'BEGIN{OFS="\t"}{print $0,0,"."}' $outfile > ${outfile}.bed

#sort -k1,1 -k2,2n $outfile > ${outfile}.sorted
#bedToBigBed ${outfile_bed}.sorted $chr_size $outfile

