
if (params.diachromatic_use_java_8) {
    java_path = params.java_8_path
}
else {
    java_path = "java"
}


// Path to Diachromatic.jar
params.diachromatic_dir = "${baseDir}/bin/java"
diachromatic_path = params.diachromatic_dir
params.fastq_dir = "${params.data_dir}/${params.sra_run}"

hic_truncated_name = "${params.sra_run}-HiC.truncated_R"

process COPY_CONTAINER_CONFIG {

    output:
    stdout emit: msg_ch

    script:
    """
    [ ! -d "${HOME}/.ncbi" ] && mkdir ${HOME}/.ncbi
    [ ! -f "${HOME}/.ncbi/user-settings.mkfg" ] && \
    cp ${baseDir}/bin/user-settings.mkfg ${HOME}/.ncbi/ && \
    echo using copied ${HOME}/.ncbi/user-settings.mkfg || \
    echo using local ${HOME}/.ncbi/user-settings.mkfg
    """
}

process PREPARE_SRA {

    publishDir "${params.data_dir}/${params.sra_run}", mode: 'copy', enabled: params.save_intermediate

    container "quay.io/hdc-workflows/sratools:main"

    input:
    val config_type_msg

    output:
    path "${params.sra_run}/${params.sra_run}.sra" optional params.skip_prefetch_sra
    tuple val(params.sra_run), path("${params.sra_run}_{1,2}.fastq"), emit: fastq_ch

    script:
    if (!params.skip_prefetch_sra) {
        """
        echo ${config_type_msg}
        prefetch ${params.sra_run} -O ./. --max-size u
        fasterq-dump -f ./${params.sra_run}
        """
    } else {
        """
        echo ${config_type_msg}
        fasterq-dump -f ${params.data_dir}/${params.sra_run}/${params.sra_run}
        """
    }
}

process DIACHROMATIC_TRUNCATE {

    publishDir "${params.data_dir}/diachromatic", mode: 'copy', enabled: params.save_intermediate

    input:
    tuple val(id), path(fastq)

    output:
    tuple val(params.sra_run), path("${hic_truncated_name}{1,2}.fastq.gz"), emit: truncated_ch
    """
    ${java_path} -jar "${diachromatic_path}"/Diachromatic.jar truncate -q ${fastq[0]} -r ${fastq[1]} -e ${params.REnzyme} -x ${params.sra_run}-HiC -o ./.
    """
}
