include { BOWTIE2_ALIGNMENT } from '../../modules/local/hicstuff/align_bowtie2'
include { FRAGMENT_ENZYME } from '../../modules/local/hicstuff/fragment_enzyme'
include { BAM2PAIRS } from '../../modules/local/hicstuff/bam2pairs'

// Paired-end to Single-end
def pairToSingle(row, mates) {
    def meta = row[0].clone()
    meta.single_end = true
    meta.mates = mates
    if (mates == "R1") {
        return [meta, [ row[1][0]] ]
    }else if (mates == "R2"){
        return [meta, [ row[1][1]] ]
    }
}

// Single-end to Paired-end
def singleToPair(row){
    def meta = row[0].clone()
    meta.remove('mates')
    meta.single_end = false
    return [ meta, row[1] ]
}

workflow HICSTUFF_SUB {

    take:
    reads
    index
    ligation_site
    digestion
    fasta

    main:

    // Align each mates separetly and add mates information in [meta]
    ch_reads_r1 = reads.map{ it -> pairToSingle(it,"R1") }
    ch_reads_r2 = reads.map{ it -> pairToSingle(it,"R2") }
    ch_reads = ch_reads_r1.concat(ch_reads_r2)

    BOWTIE2_ALIGNMENT(
        ch_reads,
        index.collect()
    )

    FRAGMENT_ENZYME(
        digestion,
        fasta
    )

    BAM2PAIRS(
        BOWTIE2_ALIGNMENT.out.bam.collect(),
        FRAGMENT_ENZYME.out.info_contigs,
        digestion,
        fasta
    )
}