/** Filter blastp output based on coverage and identity percentage
/**/

process REMOVE_SUPERCONTIGS_CHLOROPLASTS_AND_MITOCHONDRIA {
    input:
    path proteome
    path blastp
    output:
    path 'blastp_no_supercontigs_chloroplast_nor_mitochondria.tsv'
    script:
    """
    awk -f "${baseDir}/scripts/black_gene_list.awk" "${proteome}" > 'blacklist.list'
    if [ ! -s 'blacklist.list' ]; then
        cp "${blastp}" 'blastp_no_supercontigs_chloroplast_nor_mitochondria.tsv'
    else
        awk -f "${baseDir}/scripts/filter_blastp_sequence_id_remove.awk" 'blacklist.list' "${blastp}" > 'blastp_no_supercontigs_chloroplast_nor_mitochondria.tsv'
    fi
    """
}

process REMOVE_LOOPS {

    input:
    path blastp

    output:
    path 'noloops.blastp.tsv'

    script:

    """
    awk 'BEGIN { FS=OFS="\t" }  \$1 != \$2 { print \$0 }' "${blastp}" > 'noloops.blastp.tsv'
    """
}

process ADD_GENE_ID_AND_PROTEIN_LENGTHS {

    input:
    path blastp
    path protein_length

    output:
    path 'joined.blastp.tsv'

    script:
    """
    LANG=en_EN sort -t \$'\t' -k 1 "${blastp}" > blastp_s
    LANG=en_EN sort -t \$'\t' -k 1 "${protein_length}" > protein_length_s
    LANG=en_EN join -1 1 -2 1 -t \$'\t' blastp_s protein_length_s > join1.tsv
    LANG=en_EN sort -t \$'\t' -k 2 join1.tsv > join1.tsv_s
    LANG=en_EN join -1 2 -2 1 -t \$'\t' join1.tsv_s protein_length_s > joined.blastp.tsv
    """

}

process FILTER_COVERAGE_IDENTITY_BLASTP {

    input:
    path blastp
    val min_coverage
    val min_identity

    output:
    path 'filtered.blastp.tsv'

    script:
    """
    awk -f "${baseDir}/scripts/filter_blastp.awk" \
        -v min_coverage="${min_coverage}" \
        -v min_identity="${min_identity}" \
        "${blastp}" > 'filtered.blastp.tsv'
    """
}

workflow FILTER_BLASTP {
    take:
    blastp
    proteome
    protein_length
    min_coverage
    min_identity

    main:
    REMOVE_SUPERCONTIGS_CHLOROPLASTS_AND_MITOCHONDRIA(proteome, blastp)
    REMOVE_LOOPS(REMOVE_SUPERCONTIGS_CHLOROPLASTS_AND_MITOCHONDRIA.out)
    ADD_GENE_ID_AND_PROTEIN_LENGTHS(REMOVE_LOOPS.out, protein_length)
    FILTER_COVERAGE_IDENTITY_BLASTP(ADD_GENE_ID_AND_PROTEIN_LENGTHS.out, min_identity, min_coverage)

    emit:
    blastp=FILTER_COVERAGE_IDENTITY_BLASTP.out
}
