version = "1.17"
container_url = "xgrand/samtools:${version}"

params.sort_bam_out =""
process sort_bam {
  container = "${container_url}"
  label "big_mem_multi_cpus"
  tag "sorting"
  if (params.sort_bam_out != "") {
    publishDir "results/${params.sort_bam_out}", mode: 'copy'
  }

  input:
    path(bam)

  output:
    path("*sorted.bam"), emit: sorted_bam

  script:
"""
samtools sort -@ ${task.cpus} ${bam} -O BAM -o ${bam.simpleName}_sorted.bam
"""
}

params.start_position_counts_out = ""
process start_position_counts {
    container = "${container_url}"
    tag "${barcode}"
    label "big_mem_multi_cpus"
    publishDir "results/${params.start_position_counts_out}", mode: 'copy'

    input:
        tuple val(barcode), path(bam), path(index)

    output:
        tuple val(barcode), path("${barcode}/${barcode}_start_positions_counts.txt"), emit: count

    script:
"""
mkdir ${barcode}
samtools view -F 260 ${bam} |
  cut -f 1,4 |
  sort > ${barcode}/${barcode}_start_positions_counts.txt
"""
}

params.index_bam_out = ""
process index_bam {
  container = "${container_url}"
  label "small_mem_mono_cpus"
  tag "indexing"
  if (params.index_bam_out != "") {
    publishDir "results/${params.index_bam_out}", mode: 'copy'
  }

  input:
    path(bam)

  output:
    path("*.bai")

  script:
"""
samtools index -@ ${task.cpus} ${bam}
"""
}

params.indexed_bam_out =""
process sort_index_bam {
  container = "${container_url}"
  label "big_mem_multi_cpus"
  tag "${barcode}"
  if (params.indexed_bam_out != "") {
    publishDir "results/${params.indexed_bam_out}", mode: 'copy'
  }

  input:
    tuple val(barcode), path(bam)

  output:
    tuple val(barcode), path("${barcode}/*sorted.bam"), path("${barcode}/*.bai"), emit: indexed_bam

  script:
"""
mkdir ${barcode}
cd ${barcode}/
samtools sort -@ ${task.cpus} ../${bam} -o ${barcode}_sorted.bam
samtools index -@ ${task.cpus} ${barcode}_sorted.bam
"""
}

params.filtered_bam_out = ""
process filter_as {
  container = "${container_url}"
  label "big_mem_multi_cpus"
  tag "${barcode}"
  if (params.filtered_bam_out != "") {
    publishDir "results/${params.filtered_bam_out}", mode: 'copy'
  }

  input:
    tuple val(barcode), path(bam)

  output:
    tuple val(barcode), path("${barcode}/*_AS100.bam"), emit: filtered_bam

  script:
"""
mkdir ${barcode}
cd ${barcode}/
samtools view -Shb -e '[AS]>=100' -@ ${task.cpus} ../${bam} -o ${barcode}_AS100.bam
"""
}