/*
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Config file for defining DSL2 per module options and publishing paths
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Available keys to override module options:
        ext.args   = Additional arguments appended to command in module.
        ext.args2  = Second set of arguments appended to command in module (multi-tool modules).
        ext.args3  = Third set of arguments appended to command in module (multi-tool modules).
        ext.prefix = File name prefix for output files.
----------------------------------------------------------------------------------------
*/

//
// General configuration options
//

process {
    publishDir = [
        path: { "${params.outdir}/${task.process.tokenize(':')[-1].tokenize('_')[0].toLowerCase()}" },
        mode: params.publish_dir_mode,
        saveAs: { filename -> filename.equals('versions.yml') ? null : filename }
    ]

    withName: 'SAMPLESHEET_CHECK' {
        ext.args   = {
            [
                'samplesheet.valid.csv',
                params.with_control ? "--with_control" : ''
            ].join(' ').trim()
        }
        publishDir = [
            path: { "${params.outdir}/pipeline_info" },
            mode: params.publish_dir_mode,
            saveAs: { filename -> filename.equals('versions.yml') ? null : filename }
        ]
    }

    withName: 'CUSTOM_DUMPSOFTWAREVERSIONS' {
        publishDir = [
            path: { "${params.outdir}/pipeline_info" },
            mode: params.publish_dir_mode,
            pattern: '*_versions.yml'
        ]
    }
}

//
// Genome preparation options
//

process {
    withName: 'GUNZIP_.*' {
        publishDir = [
            path: { "${params.outdir}/genome" },
            mode: params.publish_dir_mode,
            saveAs: { filename -> filename.equals('versions.yml') ? null : filename },
            enabled: params.save_reference
        ]
    }

    withName: 'UNTAR_.*' {
        ext.args2 = '--no-same-owner'
        publishDir = [
            path: { "${params.outdir}/genome/index" },
            mode: params.publish_dir_mode,
            saveAs: { filename -> filename.equals('versions.yml') ? null : filename },
            enabled: params.save_reference
        ]
    }

    withName: 'BWA_INDEX|BOWTIE2_BUILD|STAR_GENOMEGENERATE|CHROMAP_INDEX' {
        publishDir = [
            path: { "${params.outdir}/genome/index" },
            mode: params.publish_dir_mode,
            saveAs: { filename -> filename.equals('versions.yml') ? null : filename },
            enabled: params.save_reference
        ]
    }

    withName: 'GFFREAD' {
        ext.args   = '--keep-exon-attrs -F -T'
        publishDir = [
            path: { "${params.outdir}/genome" },
            mode: params.publish_dir_mode,
            saveAs: { filename -> filename.equals('versions.yml') ? null : filename },
            enabled: params.save_reference
        ]
    }

    withName: 'GTF2BED' {
        publishDir = [
            path: { "${params.outdir}/genome" },
            mode: params.publish_dir_mode,
            saveAs: { filename -> filename.equals('versions.yml') ? null : filename },
            enabled: params.save_reference
        ]
    }

    withName: 'CUSTOM_GETCHROMSIZES' {
        publishDir = [
            path: { "${params.outdir}/genome" },
            mode: params.publish_dir_mode,
            saveAs: { filename -> filename.equals('versions.yml') ? null : filename },
            enabled: params.save_reference
        ]
    }

    withName: 'TSS_EXTRACT' {
        publishDir = [
            path: { "${params.outdir}/genome" },
            mode: params.publish_dir_mode,
            saveAs: { filename -> filename.equals('versions.yml') ? null : filename },
            enabled: params.save_reference
        ]
    }

    withName: 'GENOME_BLACKLIST_REGIONS' {
        publishDir = [
            path: { "${params.outdir}/genome" },
            mode: params.publish_dir_mode,
            saveAs: { filename -> filename.equals('versions.yml') ? null : filename },
            enabled: params.save_reference
        ]
    }

    withName: 'GET_AUTOSOMES' {
        publishDir = [
            path: { "${params.outdir}/genome" },
            mode: params.publish_dir_mode,
            saveAs: { filename -> filename.equals('versions.yml') ? null : filename },
            enabled: params.save_reference
        ]
    }

    withName: 'KHMER_UNIQUEKMERS' {
        publishDir = [ enabled: false ]
    }
}

//
// Read QC and trimming options
//

if (!(params.skip_fastqc || params.skip_qc)) {
    process {
        withName: 'FASTQC' {
            ext.args = '--quiet'
            publishDir = [
                [
                    path: { "${params.outdir}/fastqc" },
                    mode: params.publish_dir_mode,
                    pattern: "*.{html}"
                ],
                [
                    path: { "${params.outdir}/fastqc/zips" },
                    mode: params.publish_dir_mode,
                    pattern: "*.{zip}"
                ]
            ]
        }
    }
}

if (!params.skip_trimming) {
    process {
        withName: 'TRIMGALORE' {
            ext.args   = {
                [
                    '--fastqc',
                    params.trim_nextseq > 0 ? "--nextseq ${params.trim_nextseq}" : '',
                    params.clip_r1 > 0 ? "--clip_r1 ${params.clip_r1}" : '',
                    params.clip_r2 > 0 ? "--clip_r2 ${params.clip_r2}" : '',
                    params.three_prime_clip_r1 > 0 ? "--three_prime_clip_r1 ${params.three_prime_clip_r1}" : '',
                    params.three_prime_clip_r2 > 0 ? "--three_prime_clip_r2 ${params.three_prime_clip_r2}" : ''
                ].join(' ').trim()
            }
            publishDir = [
                [
                    path: { "${params.outdir}/trimgalore/fastqc" },
                    mode: params.publish_dir_mode,
                    pattern: "*.{html}"
                ],
                [
                    path: { "${params.outdir}/trimgalore/fastqc/zips" },
                    mode: params.publish_dir_mode,
                    pattern: "*.{zip}"
                ],
                [
                    path: { "${params.outdir}/trimgalore/logs" },
                    mode: params.publish_dir_mode,
                    pattern: "*.txt"
                ],
                [
                    path: { "${params.outdir}/trimgalore" },
                    mode: params.publish_dir_mode,
                    pattern: "*.fq.gz",
                    enabled: params.save_trimmed
                ]
            ]
        }
    }
}

process {
    withName: 'NFCORE_ATACSEQ:ATACSEQ:.*:BAM_SORT_STATS_SAMTOOLS:SAMTOOLS_SORT' {
        ext.prefix = { "${meta.id}.Lb.sorted" }
        publishDir = [
            path: { "${params.outdir}/${params.aligner}/library" },
            mode: params.publish_dir_mode,
            saveAs: { filename -> filename.equals('versions.yml') ? null : filename },
            enabled: params.save_align_intermeds
        ]
    }

    withName: 'NFCORE_ATACSEQ:ATACSEQ:.*:BAM_SORT_STATS_SAMTOOLS:SAMTOOLS_INDEX' {
        ext.prefix = { "${meta.id}.Lb.sorted" }
        publishDir = [
            path: { "${params.outdir}/${params.aligner}/library" },
            mode: params.publish_dir_mode,
            saveAs: { filename -> filename.equals('versions.yml') ? null : filename },
            enabled: params.save_align_intermeds
        ]
    }

    withName: 'NFCORE_ATACSEQ:ATACSEQ:.*:BAM_SORT_STATS_SAMTOOLS:BAM_STATS_SAMTOOLS:SAMTOOLS_.*' {
        ext.prefix = { "${meta.id}.Lb.sorted.bam" }
        publishDir = [
            path: { "${params.outdir}/${params.aligner}/library/samtools_stats" },
            mode: params.publish_dir_mode,
            saveAs: { filename -> filename.equals('versions.yml') ? null : filename },
            enabled: params.save_align_intermeds
        ]
    }
}

if (params.aligner == 'bwa') {
    process {
        withName: 'BWA_MEM' {
            ext.args   = {
                [
                    '-M',
                    params.bwa_min_score ? " -T ${params.bwa_min_score}" : '',
                    meta.read_group ? "-R ${meta.read_group}": ''
                ].join(' ').trim()
            }
            ext.args2  = '-bhS -F 0x0100 -O BAM'
            ext.prefix = { "${meta.id}.Lb" }
            publishDir = [
                path: { "${params.outdir}/${params.aligner}/library" },
                mode: params.publish_dir_mode,
                saveAs: { filename -> filename.equals('versions.yml') ? null : filename },
                enabled: false
            ]
        }
    }
}

if (params.aligner == 'bowtie2') {
    process {
        withName: 'BOWTIE2_ALIGN' {
            ext.args   = {
                [
                    meta.read_group ? "--rg-id ${meta.id} --rg SM:${meta.id - ~/_T\d+$/} --rg PL:ILLUMINA --rg LB:${meta.id} --rg PU:1" : '',
                    params.seq_center ? "--rg CN:${params.seq_center}" : ''
                ].join(' ').trim()
            }
            ext.prefix = { "${meta.id}.Lb" }
            publishDir = [
                [
                    path: { "${params.outdir}/${params.aligner}/library" },
                    mode: params.publish_dir_mode,
                    saveAs: { filename -> filename.equals('versions.yml') ? null : filename },
                    enabled: false
                ],
                [
                    path: { "${params.outdir}/${params.aligner}/library/unmapped" },
                    mode: params.publish_dir_mode,
                    pattern: '*.fastq.gz',
                    enabled: params.save_unaligned
                ]
            ]
        }
    }
}

if (params.aligner == 'chromap') {
    process {
        withName: 'CHROMAP_INDEX' {
            publishDir = [
                path: { "${params.outdir}/genome/${params.aligner}/index" },
                mode: params.publish_dir_mode,
                saveAs: { filename -> filename.equals('versions.yml') ? null : filename }
            ]
        }

        withName: 'CHROMAP_CHROMAP' {
            ext.args   = '-l 2000 --Tn5-shift --low-mem --SAM'
            ext.prefix = { "${meta.id}.Lb" }
            publishDir = [
                path: { "${params.outdir}/${params.aligner}/library" },
                mode: params.publish_dir_mode,
                saveAs: { filename -> filename.equals('versions.yml') ? null : filename },
                enabled: false
            ]
        }
    }
}

if (params.aligner == 'star') {
    process {
        withName: 'STAR_ALIGN' {
            ext.args   = [
                '--runMode alignReads',
                '--alignIntronMax 1',
                '--alignEndsType EndToEnd',
                '--outSAMtype BAM Unsorted',
                '--readFilesCommand zcat',
                '--runRNGseed 0',
                '--outSAMattributes NH HI AS NM MD',
                params.save_unaligned ? '--outReadsUnmapped Fastx' : ''
            ].join(' ').trim()
            publishDir = [
                [
                    path: { "${params.outdir}/${params.aligner}/library/log" },
                    mode: params.publish_dir_mode,
                    pattern: '*.{out,tab}'
                ],
                [
                    path: { "${params.outdir}/${params.aligner}/library" },
                    mode: params.publish_dir_mode,
                    pattern: '*.bam',
                    enabled: false
                ],
                [
                    path: { "${params.outdir}/${params.aligner}/library/unmapped" },
                    mode: params.publish_dir_mode,
                    pattern: '*.fastq.gz',
                    enabled: params.save_unaligned
                ]
            ]
        }
    }
}

process {
    withName: 'PICARD_MERGESAMFILES_LIBRARY' {
        ext.args   = '--SORT_ORDER coordinate --VALIDATION_STRINGENCY LENIENT --TMP_DIR tmp'
        ext.prefix = { "${meta.id}.mLb.sorted" }
        publishDir = [
            path: { "${params.outdir}/${params.aligner}/merged_library" },
            mode: params.publish_dir_mode,
            pattern: '*.bam',
            enabled: params.save_align_intermeds
        ]
    }

    withName: '.*:MERGED_LIBRARY_MARKDUPLICATES_PICARD:PICARD_MARKDUPLICATES' {
        ext.args   = '--ASSUME_SORTED true --REMOVE_DUPLICATES false --VALIDATION_STRINGENCY LENIENT --TMP_DIR tmp'
        ext.prefix = { "${meta.id}.mLb.mkD.sorted" }
        publishDir = [
            [
                path: { "${params.outdir}/${params.aligner}/merged_library/picard_metrics" },
                mode: params.publish_dir_mode,
                pattern: '*.metrics.txt'
            ],
            [
                path: { "${params.outdir}/${params.aligner}/merged_library" },
                mode: params.publish_dir_mode,
                pattern: '*.bam',
                enabled: params.save_align_intermeds
            ]
        ]
    }

    withName: '.*:MERGED_LIBRARY_MARKDUPLICATES_PICARD:SAMTOOLS_INDEX' {
        publishDir = [
            path: { "${params.outdir}/${params.aligner}/merged_library" },
            mode: params.publish_dir_mode,
            pattern: '*.{bai,csi}',
            enabled: params.save_align_intermeds
        ]
    }

    withName: '.*:MERGED_LIBRARY_MARKDUPLICATES_PICARD:BAM_STATS_SAMTOOLS:.*' {
        ext.prefix = { "${meta.id}.mLb.mkD.sorted.bam" }
        publishDir = [
            path: { "${params.outdir}/${params.aligner}/merged_library/samtools_stats" },
            mode: params.publish_dir_mode,
            pattern: '*.{stats,flagstat,idxstats}'
        ]
    }

    withName: 'BAMTOOLS_FILTER' {
        ext.args   = {
                [
                    meta.single_end ? '-F 0x004' : '-F 0x004 -F 0x0008 -f 0x001',
                    params.keep_dups ? '' : '-F 0x0400',
                    params.keep_multi_map ? '' : '-q 1'
                ].join(' ').trim()
        }
        ext.prefix = { meta.single_end ? "${meta.id}.mLb.clN.sorted" : "${meta.id}.mLb.flT.sorted" }
        publishDir = [
            path: { "${params.outdir}/${params.aligner}/merged_library" },
            mode: params.publish_dir_mode,
            pattern: '*.bam',
            saveAs: { (meta.single_end || params.save_align_intermeds) ? "${it}" : null }
        ]
    }

    withName: '.*:MERGED_LIBRARY_FILTER_BAM:SAMTOOLS_INDEX' {
        ext.prefix = { "${meta.id}.mLb.clN.sorted" }
        publishDir = [
            path: { "${params.outdir}/${params.aligner}/merged_library" },
            mode: params.publish_dir_mode,
            pattern: '*.{bai,csi}'
        ]
    }

    withName: '.*:MERGED_LIBRARY_FILTER_BAM:BAM_STATS_SAMTOOLS:.*' {
        ext.prefix = { "${meta.id}.mLb.clN.sorted.bam" }
        publishDir = [
            path: { "${params.outdir}/${params.aligner}/merged_library/samtools_stats" },
            mode: params.publish_dir_mode,
            pattern: '*.{stats,flagstat,idxstats}'
        ]
    }

    withName: '.*:MERGED_LIBRARY_FILTER_BAM:SAMTOOLS_SORT' {
        ext.args   = '-n'
        ext.prefix = { "${meta.id}.mLb.flT.name_sorted" }
        publishDir = [
            path: { "${params.outdir}/${params.aligner}/merged_library" },
            mode: params.publish_dir_mode,
            pattern: '*.bam',
            enabled: params.save_align_intermeds
        ]
    }

    withName: 'BAM_REMOVE_ORPHANS' {
        ext.args   = '--only_fr_pairs'
        ext.prefix = { "${meta.id}.mLb.clN" }
        publishDir = [
            path: { "${params.outdir}/${params.aligner}/merged_library" },
            mode: params.publish_dir_mode,
            pattern: '*.bam',
            enabled: params.save_align_intermeds
        ]
    }

    withName: '.*:MERGED_LIBRARY_FILTER_BAM:BAM_SORT_STATS_SAMTOOLS:.*' {
        ext.prefix = { "${meta.id}.mLb.clN.sorted" }
        publishDir = [
            path: { "${params.outdir}/${params.aligner}/merged_library" },
            mode: params.publish_dir_mode,
            pattern: "*.{bam,bai}"
        ]
    }

    withName: '.*:MERGED_LIBRARY_FILTER_BAM:BAM_SORT_STATS_SAMTOOLS:BAM_STATS_SAMTOOLS:.*' {
        ext.prefix = { "${meta.id}.mLb.clN.sorted.bam" }
        publishDir = [
            path: { "${params.outdir}/${params.aligner}/merged_library/samtools_stats" },
            mode: params.publish_dir_mode,
            pattern: "*.{stats,flagstat,idxstats}"
        ]
    }

    withName: '.*:MERGED_LIBRARY_BAM_TO_BIGWIG:BEDTOOLS_GENOMECOV' {
        ext.args   = { (meta.single_end && params.fragment_size > 0) ? "-fs ${params.fragment_size}" : '' }
        ext.prefix = { "${meta.id}.mLb.clN" }
        publishDir = [
            [
                path: { "${params.outdir}/${params.aligner}/merged_library/bigwig" },
                mode: params.publish_dir_mode,
                pattern: "*.bigWig"
            ],
            [
                path: { "${params.outdir}/${params.aligner}/merged_library/bigwig/scale" },
                mode: params.publish_dir_mode,
                pattern: "*.txt"
            ]
        ]
    }

    withName: '.*:MERGED_LIBRARY_BAM_TO_BIGWIG:UCSC_BEDGRAPHTOBIGWIG' {
        ext.prefix = { "${meta.id}.mLb.clN" }
        publishDir = [
            path: { "${params.outdir}/${params.aligner}/merged_library/bigwig" },
            mode: params.publish_dir_mode,
            pattern: "*.bigWig"
        ]
    }
}

if (!params.skip_picard_metrics) {
    process {
        withName: 'MERGED_LIBRARY_PICARD_COLLECTMULTIPLEMETRICS' {
            ext.args   = '--VALIDATION_STRINGENCY LENIENT --TMP_DIR tmp'
            ext.prefix = { "${meta.id}.mLb.clN" }
            publishDir = [
                [
                    path: { "${params.outdir}/${params.aligner}/merged_library/picard_metrics" },
                    mode: params.publish_dir_mode,
                    pattern: "*_metrics"
                ],
                [
                    path: { "${params.outdir}/${params.aligner}/merged_library/picard_metrics/pdf" },
                    mode: params.publish_dir_mode,
                    pattern: "*.pdf"
                ]
            ]
        }
    }
}

if (!params.skip_preseq) {
    process {
        withName: 'MERGED_LIBRARY_PRESEQ_LCEXTRAP' {
            ext.args   = '-verbose -bam -seed 1'
            ext.prefix = { "${meta.id}.mLb.mkD" }
            publishDir = [
                path: { "${params.outdir}/${params.aligner}/merged_library/preseq" },
                mode: params.publish_dir_mode,
                saveAs: { filename -> filename.equals('versions.yml') ? null : filename }
            ]
        }
    }
}

if (!params.skip_plot_profile) {
    process {
        withName: 'DEEPTOOLS_COMPUTEMATRIX_SCALE_REGIONS' {
            ext.args   = 'scale-regions --regionBodyLength 1000 --beforeRegionStartLength 3000 --afterRegionStartLength 3000 --missingDataAsZero --skipZeros --smartLabels'
            ext.prefix = { "${meta.id}.mLb.clN.scale_regions" }
            publishDir = [
                path: { "${params.outdir}/${params.aligner}/merged_library/deeptools/plotprofile" },
                mode: params.publish_dir_mode,
                saveAs: { filename -> filename.equals('versions.yml') ? null : filename }
            ]
        }

        withName: 'DEEPTOOLS_COMPUTEMATRIX_REFERENCE_POINT' {
            ext.args   = 'reference-point --missingDataAsZero --skipZeros --smartLabels --upstream 3000 --downstream 3000'
            ext.prefix = { "${meta.id}.mLb.clN.reference_point" }
            publishDir = [
                path: { "${params.outdir}/${params.aligner}/merged_library/deeptools/plotprofile" },
                mode: params.publish_dir_mode,
                saveAs: { filename -> filename.equals('versions.yml') ? null : filename }
            ]
        }

        withName: 'DEEPTOOLS_PLOTPROFILE' {
            ext.prefix = { "${meta.id}.mLb.clN.reference_point" }
            publishDir = [
                path: { "${params.outdir}/${params.aligner}/merged_library/deeptools/plotprofile" },
                mode: params.publish_dir_mode,
                saveAs: { filename -> filename.equals('versions.yml') ? null : filename }
            ]
        }

        withName: 'DEEPTOOLS_PLOTHEATMAP' {
            ext.prefix = { "${meta.id}.mLb.clN.scale_regions" }
            publishDir = [
                path: { "${params.outdir}/${params.aligner}/merged_library/deeptools/plotprofile" },
                mode: params.publish_dir_mode,
                saveAs: { filename -> filename.equals('versions.yml') ? null : filename }
            ]
        }
    }
}

if (!params.skip_plot_fingerprint) {
    process {
        withName: 'MERGED_LIBRARY_DEEPTOOLS_PLOTFINGERPRINT' {
            ext.args   = {
                [
                    '--skipZeros',
                    "--numberOfSamples $params.fingerprint_bins",
                    params.with_control ? "--labels ${meta.id}.mLb.clN $meta.control" : "--labels ${meta.id}.mLb.clN"
                ].join(' ').trim()
            }
            ext.prefix = { "${meta.id}.mLb.clN" }
            publishDir = [
                path: { "${params.outdir}/${params.aligner}/merged_library/deeptools/plotfingerprint" },
                mode: params.publish_dir_mode,
                saveAs: { filename -> filename.equals('versions.yml') ? null : filename }
            ]
        }
    }
}

process {
    withName: '.*:MERGED_LIBRARY_CALL_ANNOTATE_PEAKS:MACS2_CALLPEAK' {
        ext.args   = [
            '--keep-dup all',
            '--nomodel',
            params.narrow_peak      ? '' : "--broad --broad-cutoff ${params.broad_cutoff}",
            params.save_macs_pileup ? '--bdg --SPMR' : '',
            params.macs_pvalue      ? "--pvalue ${params.macs_pvalue}" : '',
            params.macs_fdr         ? "--qvalue ${params.macs_fdr}" : ''
        ].join(' ').trim()
        ext.prefix = { "${meta.id}.mLb.clN" }
        publishDir = [
            path: { "${params.outdir}/${params.aligner}/merged_library/macs2/${params.narrow_peak ? '/narrow_peak' : '/broad_peak'}" },
            mode: params.publish_dir_mode,
            saveAs: { filename -> filename.equals('versions.yml') ? null : filename }
        ]
    }

    withName: '.*:MERGED_LIBRARY_CALL_ANNOTATE_PEAKS:FRIP_SCORE' {
        ext.args   = '-bed -c -f 0.20'
        publishDir = [
            path: { "${params.outdir}/${params.aligner}/merged_library/macs2/${params.narrow_peak ? '/narrow_peak' : '/broad_peak'}/qc" },
            enabled: false
        ]
    }

    withName: '.*:MERGED_LIBRARY_CALL_ANNOTATE_PEAKS:MULTIQC_CUSTOM_PEAKS' {
        ext.prefix = { "${meta.id}.mLb.clN_peaks" }
        publishDir = [
            path: { "${params.outdir}/${params.aligner}/merged_library/macs2/${params.narrow_peak ? '/narrow_peak' : '/broad_peak'}/qc" },
            mode: params.publish_dir_mode,
            saveAs: { filename -> filename.equals('versions.yml') ? null : filename }
        ]
    }
}

if (!params.skip_peak_annotation) {
    process {
        withName: '.*:MERGED_LIBRARY_CALL_ANNOTATE_PEAKS:HOMER_ANNOTATEPEAKS' {
            ext.args   = '-gid'
            ext.prefix = { "${meta.id}.mLb.clN_peaks" }
            publishDir = [
                path: { "${params.outdir}/${params.aligner}/merged_library/macs2/${params.narrow_peak ? '/narrow_peak' : '/broad_peak'}" },
                mode: params.publish_dir_mode,
                saveAs: { filename -> filename.equals('versions.yml') ? null : filename }
            ]
        }
    }

    if (!params.skip_peak_qc) {
        process {
            withName: '.*:MERGED_LIBRARY_CALL_ANNOTATE_PEAKS:PLOT_MACS2_QC' {
                ext.args   = '-o ./ -p macs2_peak.mLb.clN'
                publishDir = [
                    path: { "${params.outdir}/${params.aligner}/merged_library/macs2/${params.narrow_peak ? '/narrow_peak' : '/broad_peak'}/qc" },
                    mode: params.publish_dir_mode,
                    saveAs: { filename -> filename.equals('versions.yml') ? null : filename }
                ]
            }

            withName: '.*:MERGED_LIBRARY_CALL_ANNOTATE_PEAKS:PLOT_HOMER_ANNOTATEPEAKS' {
                ext.args   = '-o ./'
                ext.prefix = 'macs2_annotatePeaks.mLb.clN'
                publishDir = [
                    path: { "${params.outdir}/${params.aligner}/merged_library/macs2/${params.narrow_peak ? '/narrow_peak' : '/broad_peak'}/qc" },
                    mode: params.publish_dir_mode,
                    saveAs: { filename -> filename.equals('versions.yml') ? null : filename }
                ]
            }
        }
    }
}

if (!params.skip_consensus_peaks) {
    process {
        withName: '.*:MERGED_LIBRARY_CONSENSUS_PEAKS:MACS2_CONSENSUS' {
            ext.args   = "--min_replicates ${params.min_reps_consensus}"
            ext.prefix = "consensus_peaks.mLb.clN"
            publishDir = [
                path: { "${params.outdir}/${params.aligner}/merged_library/macs2/${params.narrow_peak ? '/narrow_peak' : '/broad_peak'}/consensus" },
                mode: params.publish_dir_mode,
                saveAs: { filename -> filename.equals('versions.yml') ? null : filename }
            ]
        }

        withName: '.*:MERGED_LIBRARY_CONSENSUS_PEAKS:SUBREAD_FEATURECOUNTS'  {
            ext.args   = '-F SAF -O --fracOverlap 0.2'
            ext.prefix = "consensus_peaks.mLb.clN"
            publishDir = [
                path: { "${params.outdir}/${params.aligner}/merged_library/macs2/${params.narrow_peak ? '/narrow_peak' : '/broad_peak'}/consensus" },
                mode: params.publish_dir_mode,
                saveAs: { filename -> filename.equals('versions.yml') ? null : filename }
            ]
        }
    }

    if (!params.skip_deseq2_qc) {
        process {
            withName: '.*:MERGED_LIBRARY_CONSENSUS_PEAKS:DESEQ2_QC' {
                ext.args   = [
                    '--id_col 1',
                    '--sample_suffix \'.mLb.clN.sorted.bam\'',
                    '--count_col 7',
                    params.deseq2_vst ? '--vst TRUE' : ''
                ].join(' ').trim()
                ext.prefix = { "${meta.id}.mLb.clN" }
                publishDir = [
                    path: { "${params.outdir}/${params.aligner}/merged_library/macs2/${params.narrow_peak ? '/narrow_peak' : '/broad_peak'}/consensus/deseq2" },
                    mode: params.publish_dir_mode,
                    saveAs: { filename -> filename.equals('versions.yml') ? null : filename }
                ]
            }
        }
    }
}

if (!params.skip_peak_annotation) {
    process {
        withName: '.*:MERGED_LIBRARY_CONSENSUS_PEAKS:HOMER_ANNOTATEPEAKS' {
            ext.args   = '-gid'
            ext.prefix = "consensus_peaks.mLb.clN"
            publishDir = [
                path: { "${params.outdir}/${params.aligner}/merged_library/macs2/${params.narrow_peak ? '/narrow_peak' : '/broad_peak'}/consensus" },
                mode: params.publish_dir_mode,
                saveAs: { filename -> filename.equals('versions.yml') ? null : filename }
            ]
        }
    }
}

if (!params.skip_ataqv) {
    process {
        withName: 'MERGED_LIBRARY_ATAQV_ATAQV' {
            ext.args   = '--ignore-read-groups'
            publishDir = [
                path: { "${params.outdir}/${params.aligner}/merged_library/ataqv/${params.narrow_peak ? '/narrow_peak' : '/broad_peak'}" },
                mode: params.publish_dir_mode,
                saveAs: { filename -> filename.equals('versions.yml') ? null : filename }
            ]
        }
        withName: 'MERGED_LIBRARY_ATAQV_MKARV' {
            publishDir = [
                path: { "${params.outdir}/${params.aligner}/merged_library/ataqv/${params.narrow_peak ? '/narrow_peak' : '/broad_peak'}" },
                mode: params.publish_dir_mode,
                saveAs: { filename -> filename.equals('versions.yml') ? null : filename }
            ]
        }
    }
}

if (!params.skip_merge_replicates) {
    process {
        withName: 'PICARD_MERGESAMFILES_REPLICATE' {
            ext.args   = '--SORT_ORDER coordinate --VALIDATION_STRINGENCY LENIENT --TMP_DIR tmp'
            ext.prefix = { "${meta.id}.mRp.sorted" }
            publishDir = [
                path: { "${params.outdir}/${params.aligner}/merged_replicate" },
                mode: params.publish_dir_mode,
                pattern: '*.bam',
                enabled: params.save_align_intermeds
            ]
        }

        withName: '.*:MERGED_REPLICATE_MARKDUPLICATES_PICARD:PICARD_MARKDUPLICATES' {
            ext.args   = '--ASSUME_SORTED true --REMOVE_DUPLICATES true --VALIDATION_STRINGENCY LENIENT --TMP_DIR tmp'
            ext.prefix = { "${meta.id}.mRp.clN.sorted" }
            publishDir = [
                [
                    path: { "${params.outdir}/${params.aligner}/merged_replicate/picard_metrics" },
                    mode: params.publish_dir_mode,
                    pattern: '*.metrics.txt'
                ],
                [
                    path: { "${params.outdir}/${params.aligner}/merged_replicate" },
                    mode: params.publish_dir_mode,
                    pattern: '*.bam',
                ]
            ]
        }

        withName: '.*:MERGED_REPLICATE_MARKDUPLICATES_PICARD:SAMTOOLS_INDEX' {
            publishDir = [
                path: { "${params.outdir}/${params.aligner}/merged_replicate" },
                mode: params.publish_dir_mode,
                pattern: '*.{bai,csi}'
            ]
        }

        withName: '.*:MERGED_REPLICATE_MARKDUPLICATES_PICARD:BAM_STATS_SAMTOOLS:.*' {
            ext.prefix = { "${meta.id}.mRp.clN.sorted.bam" }
            publishDir = [
                path: { "${params.outdir}/${params.aligner}/merged_replicate/samtools_stats" },
                mode: params.publish_dir_mode,
                pattern: '*.{stats,flagstat,idxstats}'
            ]
        }

        withName: '.*:MERGED_REPLICATE_BAM_TO_BIGWIG:BEDTOOLS_GENOMECOV' {
            ext.args   = { (meta.single_end && params.fragment_size > 0) ? "-fs ${params.fragment_size}" : '' }
            ext.prefix = { "${meta.id}.mRp.clN" }
            publishDir = [
                [
                    path: { "${params.outdir}/${params.aligner}/merged_replicate/bigwig" },
                    mode: params.publish_dir_mode,
                    pattern: "*.bigWig"
                ],
                [
                    path: { "${params.outdir}/${params.aligner}/merged_replicate/bigwig/scale" },
                    mode: params.publish_dir_mode,
                    pattern: "*.txt"
                ]
            ]
        }

        withName: '.*:MERGED_REPLICATE_BAM_TO_BIGWIG:UCSC_BEDGRAPHTOBIGWIG' {
            ext.prefix = { "${meta.id}.mRp.clN" }
            publishDir = [
                [
                    path: { "${params.outdir}/${params.aligner}/merged_replicate/bigwig" },
                    mode: params.publish_dir_mode,
                    pattern: "*.bigWig"
                ]
            ]
        }
    }

    process {
        withName: '.*:MERGED_REPLICATE_CALL_ANNOTATE_PEAKS:MACS2_CALLPEAK' {
            ext.args   = [
                '--keep-dup all',
                '--nomodel',
                params.narrow_peak      ? '' : "--broad --broad-cutoff ${params.broad_cutoff}",
                params.save_macs_pileup ? '--bdg --SPMR' : '',
            ].join(' ').trim()
            ext.prefix = { "${meta.id}.mRp.clN" }
            publishDir = [
                path: { "${params.outdir}/${params.aligner}/merged_replicate/macs2/${params.narrow_peak ? '/narrow_peak' : '/broad_peak'}" },
                mode: params.publish_dir_mode,
                saveAs: { filename -> filename.equals('versions.yml') ? null : filename }
            ]
        }

        withName: '.*:MERGED_REPLICATE_CALL_ANNOTATE_PEAKS:FRIP_SCORE' {
            ext.args   = '-bed -c -f 0.20'
            publishDir = [
                path: { "${params.outdir}/${params.aligner}/merged_replicate/macs2/${params.narrow_peak ? '/narrow_peak' : '/broad_peak'}/qc" },
                enabled: false
            ]
        }

        withName: '.*:MERGED_REPLICATE_CALL_ANNOTATE_PEAKS:MULTIQC_CUSTOM_PEAKS' {
            ext.prefix = { "${meta.id}.mRp.clN_peaks" }
            publishDir = [
                path: { "${params.outdir}/${params.aligner}/merged_replicate/macs2/${params.narrow_peak ? '/narrow_peak' : '/broad_peak'}/qc" },
                mode: params.publish_dir_mode,
                saveAs: { filename -> filename.equals('versions.yml') ? null : filename }
            ]
        }
    }

    if (!params.skip_peak_annotation ) {
        process {
            withName: '.*:MERGED_REPLICATE_CALL_ANNOTATE_PEAKS:HOMER_ANNOTATEPEAKS' {
                ext.args   = '-gid'
                ext.prefix = { "${meta.id}.mRp.clN_peaks" }
                publishDir = [
                    path: { "${params.outdir}/${params.aligner}/merged_replicate/macs2/${params.narrow_peak ? '/narrow_peak' : '/broad_peak'}" },
                    mode: params.publish_dir_mode,
                    saveAs: { filename -> filename.equals('versions.yml') ? null : filename }
                ]
            }
        }

        if (!params.skip_peak_qc) {
            process {
                withName: '.*:MERGED_REPLICATE_CALL_ANNOTATE_PEAKS:PLOT_MACS2_QC' {
                    ext.args   = '-o ./ -p macs2_peak.mRp.clN'
                    publishDir = [
                        path: { "${params.outdir}/${params.aligner}/merged_replicate/macs2/${params.narrow_peak ? '/narrow_peak' : '/broad_peak'}/qc" },
                        mode: params.publish_dir_mode,
                        saveAs: { filename -> filename.equals('versions.yml') ? null : filename }
                    ]
                }

                withName: '.*:MERGED_REPLICATE_CALL_ANNOTATE_PEAKS:PLOT_HOMER_ANNOTATEPEAKS' {
                    ext.args   = '-o ./'
                    ext.prefix = 'macs2_annotatePeaks.mRp.clN'
                    publishDir = [
                        path: { "${params.outdir}/${params.aligner}/merged_replicate/macs2/${params.narrow_peak ? '/narrow_peak' : '/broad_peak'}/qc" },
                        mode: params.publish_dir_mode,
                        saveAs: { filename -> filename.equals('versions.yml') ? null : filename }
                    ]
                }
            }
        }
    }

    if (!params.skip_consensus_peaks) {
        process {
            withName: '.*:MERGED_REPLICATE_CONSENSUS_PEAKS:MACS2_CONSENSUS' {
                ext.prefix = "consensus_peaks.mRp.clN"
                publishDir = [
                    path: { "${params.outdir}/${params.aligner}/merged_replicate/macs2/${params.narrow_peak ? '/narrow_peak' : '/broad_peak'}/consensus" },
                    mode: params.publish_dir_mode,
                    saveAs: { filename -> filename.equals('versions.yml') ? null : filename }
                ]
            }

            withName: '.*:MERGED_REPLICATE_CONSENSUS_PEAKS:SUBREAD_FEATURECOUNTS'  {
                ext.args   = '-F SAF -O --fracOverlap 0.2'
                ext.prefix = "consensus_peaks.mRp.clN"
                publishDir = [
                    path: { "${params.outdir}/${params.aligner}/merged_replicate/macs2/${params.narrow_peak ? '/narrow_peak' : '/broad_peak'}/consensus" },
                    mode: params.publish_dir_mode,
                    saveAs: { filename -> filename.equals('versions.yml') ? null : filename }
                ]
            }
        }

        if (!params.skip_deseq2_qc) {
            process {
                withName: '.*:MERGED_REPLICATE_CONSENSUS_PEAKS:DESEQ2_QC' {
                    ext.args   = [
                        '--id_col 1',
                        '--sample_suffix \'.mLb.clN.sorted.bam\'',
                        '--count_col 7',
                        params.deseq2_vst ? '--vst TRUE' : ''
                    ].join(' ').trim()
                    ext.prefix = { "${meta.id}.mRp.clN" }
                    publishDir = [
                        path: { "${params.outdir}/${params.aligner}/merged_replicate/macs2/${params.narrow_peak ? '/narrow_peak' : '/broad_peak'}/consensus/deseq2" },
                        mode: params.publish_dir_mode,
                        saveAs: { filename -> filename.equals('versions.yml') ? null : filename }
                    ]
                }
            }
        }
    }

    if (!params.skip_peak_annotation) {
        process {
            withName: '.*:MERGED_REPLICATE_CONSENSUS_PEAKS:HOMER_ANNOTATEPEAKS' {
                ext.args   = '-gid'
                ext.prefix = "consensus_peaks.mRp.clN"
                publishDir = [
                    path: { "${params.outdir}/${params.aligner}/merged_replicate/macs2/${params.narrow_peak ? '/narrow_peak' : '/broad_peak'}/consensus" },
                    mode: params.publish_dir_mode,
                    saveAs: { filename -> filename.equals('versions.yml') ? null : filename }
                ]
            }
        }
    }
}

if (!params.skip_igv) {
    process {
        withName: 'IGV' {
            publishDir = [
                [
                    path: { "${params.outdir}/igv/${params.narrow_peak ? '/narrow_peak' : '/broad_peak'}" },
                    mode: params.publish_dir_mode,
                    pattern: '*.{txt,xml}'
                ],
                [
                    path: { "${params.outdir}/genome" },
                    mode: params.publish_dir_mode,
                    pattern: '*.{fa,fasta,fai}'
                ]
            ]
        }
    }
}

if (!params.skip_multiqc) {
    process {
        withName: 'MULTIQC' {
            ext.args   = params.multiqc_title ? "--title \"$params.multiqc_title\"" : ''
            publishDir = [
                path: { "${params.outdir}/multiqc/${params.narrow_peak ? '/narrow_peak' : '/broad_peak'}" },
                mode: params.publish_dir_mode,
                saveAs: { filename -> filename.equals('versions.yml') ? null : filename }
            ]
        }
    }
}
