/** Run the workflow for all species in the csv table */

include { GUNZIP as GUNZIP_1 } from "./modules/gunzip.nf"
include { GUNZIP as GUNZIP_2 } from "./modules/gunzip.nf"
include { FILTER_FASTA } from "./modules/filter_fasta.nf"
include { FILTER_BLASTP } from "./modules/filter_blastp.nf"
include { CLUSTERING } from "./modules/clustering.nf"
include { TAGs } from "./modules/tags.nf"



process CSV_ROW {
    publishDir "results/", mode: 'copy'
    input:
    val(species)
    path(proteome)
    path(tags)
    path(families)
    output:
    path "${species}.csv"
    script:
    """
    nb_tag0=\$(tail -n +2  "${tags}"| awk 'BEGIN { max = 0 } { if (\$3 != "-" && \$3 > max) max = \$3 } END { print max }')
    nb_tag1=\$(tail -n +2  "${tags}"| awk 'BEGIN { max = 0 } { if (\$4 != "-" && \$4 > max) max = \$4 } END { print max }')
    nb_tag_genes0=\$(tail -n +2 "${tags}" | awk 'BEGIN {count = 0} \$3 != "-" { count += 1 } END { print count }' )
    nb_tag_genes1=\$(tail -n +2 "${tags}" | awk 'BEGIN {count = 0} \$4 != "-" { count += 1 } END { print count }' )
    nb_families=\$(tail -1 "${families}" | awk '{ print \$2 }')
    nb_genes_largest_family=\$(awk '\$2 != "-" { count[\$2] += 1} END { max_count=0; for (tag in count) { if (count[tag] > max_count) max_count = count[tag] } print max_count}' "${families}")
    nb_genes_largest_tag0=\$(tail -n +2 "${tags}" | awk '\$3 != "-" { count[\$3] += 1} END { max_count=0; for (tag in count) { if (count[tag] > max_count) max_count = count[tag] } print max_count}')
    nb_duplicates=\$(cat "${families}" | wc -l)
    nb_genes=\$(awk '/^>/ { print \$4 }' "${proteome}" | sort | uniq | wc -l)
    nb_singletons=\$((nb_genes - nb_duplicates + 1))
    echo "${species},\${nb_genes},\${nb_duplicates},\${nb_singletons},\${nb_families},\${nb_genes_largest_family},\${nb_tag0},\${nb_tag1},\${nb_tag_genes0},\${nb_tag_genes1},\${nb_genes_largest_tag0}" > "${species}.csv"
    """
}



workflow {
    proteome = file(params.proteome)
    gff3 = file(params.gff3)
    blastp = file(params.blastp)

    GUNZIP_1(proteome)
    GUNZIP_2(gff3)
    FILTER_FASTA(GUNZIP_1.out)
    FILTER_BLASTP(blastp, GUNZIP_1.out, FILTER_FASTA.out.lengths, params.min_coverage, params.min_identity)
    CLUSTERING(FILTER_BLASTP.out.blastp)
    TAGs(CLUSTERING.out, GUNZIP_2.out)
    CSV_ROW(params.species, GUNZIP_1.out, TAGs.out, CLUSTERING.out)
}
