#!/usr/bin/env nextflow

save_enabled = params.save_intermediate

use_docker_container = params.singularity_use_docker_container

if (workflow.containerEngine == 'docker') {
    re_path = "/repex_tarean/seqclust"
    reformat_path = "reformat.sh"
}
else if (workflow.containerEngine == 'singularity') {
    re_path = "seqclust"
    reformat_path = "reformat.sh"
}
else {
    re_path = params.re_seqclust_path
    reformat_path = params.bbmap_reformat_path
}

process FORMAT_READS {
    publishDir "${params.data_dir}/processed_reads", mode: 'copy', enabled: save_enabled

    if (workflow.containerEngine == 'singularity' && !use_docker_container) {
        container "https://depot.galaxyproject.org/singularity/bbmap:38.93--he522d1c_0"
    } else {
        container "quay.io/biocontainers/bbmap:38.93--he522d1c_0"
    }

    input:
    tuple val(sample_id), path(reads)

    output:
    path "${sample_id}_interleaved.fq" , emit: processed_reads_fq_ch

    script:
    """
    ${reformat_path} in1=${reads[0]} in2=${reads[1]} out=${sample_id}_interleaved.fq trimreaddescription=t requirebothbad=f minlength=100 forcetrimleft=8 forcetrimmod=-1 addslash spaceslash=f samplereadstarget=250000
    """

}

process SEQTK_SEQ {
    publishDir "${params.data_dir}/processed_reads", mode: 'copy', enabled: save_enabled

    if (workflow.containerEngine == 'singularity' && !use_docker_container) {
        container "https://depot.galaxyproject.org/singularity/seqtk:1.3--h5bf99c6_3"
    } else {
        container "quay.io/biocontainers/seqtk:1.3--h5bf99c6_3"
    }

    input:
    path interleaved_fq

    output:
    path "${params.sra_run}_interleaved.fa" , emit: processed_reads_fa_ch

    script:
    """
    seqtk seq -A ${interleaved_fq} > ${params.sra_run}_interleaved.fa
    #seqtk rename interleaved.fa > renamed.fa
    """
}

process RUN_RE {
    //assign reads to the clusters as annotated by RepeatExplorer
    publishDir "${params.data_dir}/RE_output", mode: 'copy', enabled: save_enabled

    if (workflow.containerEngine == 'singularity' && !use_docker_container) {
        container "shub://repeatexplorer/repex_tarean:latest"
    } else {
        container "kavonrtep/repeatexplorer:2.3.8"
    }

    input:
    path interleaved_fa

    output:
    path "${params.RE_run}/seqclust/clustering/hitsort.cls", emit: hitsort_cls
    path "${params.RE_run}/CLUSTER_TABLE.csv", emit: clTABLE
    path "${params.RE_run}/contigs.fasta", emit: contigs_fasta
    path "${params.RE_run}/TAREAN_consensus_rank_?.fasta"

    script:
    //check whether the automatic filtering is a way to go (are the reads omitted when clusters are being defined, or are they not assigned to any clusters at all? )
    """
    ${re_path} -p --cpu=3 --keep_names --automatic_filtering --mincl ${params.clustering_threshold} ${interleaved_fa} -v ${params.RE_run}
    """
}
