#!/usr/bin/env nextflow

r_script_path = "${workflow.projectDir}/bin/R"

// Generated reference genome base name
ref_dir = file(params.reference).baseName

// This process should go between GENERATE TABLE and the various TE_HEATMAP_* processes.
// It will produce a couple of *.Rd files that these will read into R.
// It should also publish the tables in text format.
process PREPARE_TABLE {
    //Heatmap visualization

    //publishDir "${params.data_dir}/${ref_dir}_${params.sra_run}_png", mode: 'copy', enabled: true

    container "tegreedy/rtools:1.0.0"

    input:
    path table_fragments

    output:
    tuple val(params.sra_run), path("tab*.Rdata"), emit: table_ch

    script:
    """
    Rscript "${r_script_path}"/split_save_tables.R ${table_fragments}
    """
}

process PLOT_CHR {
    //Chromomal map of HiC reads

    publishDir "${params.data_dir}/${ref_dir}_${params.sra_run}_png", mode: 'copy', enabled: true

    container "tegreedy/rtools:1.0.0"

    input:
    path genome_file
    path aligned_bam

    output:
    path "*.png"

    script:
    """
    Rscript "${r_script_path}"/plotBamCoverage.R ${genome_file} ${aligned_bam}
    """
}

process PLOT_BARPLOT {
    //Barplot visualization for families

    publishDir "${params.data_dir}/${ref_dir}_${params.sra_run}_png", mode: 'copy', enabled: true

    container "tegreedy/rtools:1.0.0"

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

    output:
    path "*.png"

    script:
    """
    Rscript "${r_script_path}"/plot_barplot.R ${tab[0]}
    """
}

process TE_HEATMAP_NORM1 {
    //Heatmap visualization

    publishDir "${params.data_dir}/${ref_dir}_${params.sra_run}_png", mode: 'copy', enabled: true

    container "tegreedy/rtools:1.0.0"

    input:
    tuple val(id), path(tab)
    path tab_repeats
    each heatmap_types

    output:
    path "*.png"

    script:
    """
    Rscript "${r_script_path}"/generate_heatmap_reference_joint_probability_norm.R ${tab[0]} ${heatmap_types} ${tab_repeats}
    """
}

process TE_HEATMAP_NORM2 {
    //Heatmap visualization

    publishDir "${params.data_dir}/${ref_dir}_${params.sra_run}_png", mode: 'copy', enabled: true

    container "tegreedy/rtools:1.0.0"

    input:
    tuple val(id), path(tab)
    path tab_repeats
    each heatmap_types

    output:
    path "*.png"

    script:
    """
    Rscript "${r_script_path}"/generate_heatmap_reference_label_permutation_norm.R ${tab[0]} ${heatmap_types} ${tab_repeats} "reference"
    """
}

process TE_HEATMAP_NORM3 {
    //Heatmap visualization

    publishDir "${params.data_dir}/${ref_dir}_${params.sra_run}_png", mode: 'copy', enabled: true

    container "tegreedy/rtools:1.0.0"

    input:
    tuple val(id), path(tab)
    path tab_shuffled
    path tab_repeats
    each heatmap_types

    output:
    path "*.png"

    script:
    """
    Rscript "${r_script_path}"/generate_heatmap_reference_genome_reshuffling_norm.R ${tab[0]} ${heatmap_types} ${tab_shuffled} ${tab_repeats}
    """
}
