#!/usr/bin/env bash

# deseq2 v4.0.3
# 
# This wrapper script is auto-generated by viash 0.9.4 and is thus a derivative
# work thereof. This software comes with ABSOLUTELY NO WARRANTY from Data
# Intuitive.
# 
# The component may contain files which fall under a different license. The
# authors of this component should specify the license in the header of such
# files, or include a separate license file detailing the licenses of all included
# files.
# 
# Component authors:
#  * Jakub Majercik (author)
#  * Dorien Roosen (author)
#  * Dries De Maeyer (contributor)
#  * Weiwei Schultz (contributor)

set -e

if [ -z "$VIASH_TEMP" ]; then
  VIASH_TEMP=${VIASH_TEMP:-$VIASH_TMPDIR}
  VIASH_TEMP=${VIASH_TEMP:-$VIASH_TEMPDIR}
  VIASH_TEMP=${VIASH_TEMP:-$VIASH_TMP}
  VIASH_TEMP=${VIASH_TEMP:-$TMPDIR}
  VIASH_TEMP=${VIASH_TEMP:-$TMP}
  VIASH_TEMP=${VIASH_TEMP:-$TEMPDIR}
  VIASH_TEMP=${VIASH_TEMP:-$TEMP}
  VIASH_TEMP=${VIASH_TEMP:-/tmp}
fi

# define helper functions
# ViashQuote: put quotes around non flag values
# $1     : unquoted string
# return : possibly quoted string
# examples:
#   ViashQuote --foo      # returns --foo
#   ViashQuote bar        # returns 'bar'
#   Viashquote --foo=bar  # returns --foo='bar'
function ViashQuote {
  if [[ "$1" =~ ^-+[a-zA-Z0-9_\-]+=.+$ ]]; then
    echo "$1" | sed "s#=\(.*\)#='\1'#"
  elif [[ "$1" =~ ^-+[a-zA-Z0-9_\-]+$ ]]; then
    echo "$1"
  else
    echo "'$1'"
  fi
}
# ViashRemoveFlags: Remove leading flag
# $1     : string with a possible leading flag
# return : string without possible leading flag
# examples:
#   ViashRemoveFlags --foo=bar  # returns bar
function ViashRemoveFlags {
  echo "$1" | sed 's/^--*[a-zA-Z0-9_\-]*=//'
}
# ViashSourceDir: return the path of a bash file, following symlinks
# usage   : ViashSourceDir ${BASH_SOURCE[0]}
# $1      : Should always be set to ${BASH_SOURCE[0]}
# returns : The absolute path of the bash file
function ViashSourceDir {
  local source="$1"
  while [ -h "$source" ]; do
    local dir="$( cd -P "$( dirname "$source" )" >/dev/null 2>&1 && pwd )"
    source="$(readlink "$source")"
    [[ $source != /* ]] && source="$dir/$source"
  done
  cd -P "$( dirname "$source" )" >/dev/null 2>&1 && pwd
}
# ViashFindTargetDir: return the path of the '.build.yaml' file, following symlinks
# usage   : ViashFindTargetDir 'ScriptPath'
# $1      : The location from where to start the upward search
# returns : The absolute path of the '.build.yaml' file
function ViashFindTargetDir {
  local source="$1"
  while [[ "$source" != "" && ! -e "$source/.build.yaml" ]]; do
    source=${source%/*}
  done
  echo $source
}
# see https://en.wikipedia.org/wiki/Syslog#Severity_level
VIASH_LOGCODE_EMERGENCY=0
VIASH_LOGCODE_ALERT=1
VIASH_LOGCODE_CRITICAL=2
VIASH_LOGCODE_ERROR=3
VIASH_LOGCODE_WARNING=4
VIASH_LOGCODE_NOTICE=5
VIASH_LOGCODE_INFO=6
VIASH_LOGCODE_DEBUG=7
VIASH_VERBOSITY=$VIASH_LOGCODE_NOTICE

# ViashLog: Log events depending on the verbosity level
# usage: ViashLog 1 alert Oh no something went wrong!
# $1: required verbosity level
# $2: display tag
# $3+: messages to display
# stdout: Your input, prepended by '[$2] '.
function ViashLog {
  local required_level="$1"
  local display_tag="$2"
  shift 2
  if [ $VIASH_VERBOSITY -ge $required_level ]; then
    >&2 echo "[$display_tag]" "$@"
  fi
}

# ViashEmergency: log events when the system is unstable
# usage: ViashEmergency Oh no something went wrong.
# stdout: Your input, prepended by '[emergency] '.
function ViashEmergency {
  ViashLog $VIASH_LOGCODE_EMERGENCY emergency "$@"
}

# ViashAlert: log events when actions must be taken immediately (e.g. corrupted system database)
# usage: ViashAlert Oh no something went wrong.
# stdout: Your input, prepended by '[alert] '.
function ViashAlert {
  ViashLog $VIASH_LOGCODE_ALERT alert "$@"
}

# ViashCritical: log events when a critical condition occurs
# usage: ViashCritical Oh no something went wrong.
# stdout: Your input, prepended by '[critical] '.
function ViashCritical {
  ViashLog $VIASH_LOGCODE_CRITICAL critical "$@"
}

# ViashError: log events when an error condition occurs
# usage: ViashError Oh no something went wrong.
# stdout: Your input, prepended by '[error] '.
function ViashError {
  ViashLog $VIASH_LOGCODE_ERROR error "$@"
}

# ViashWarning: log potentially abnormal events
# usage: ViashWarning Something may have gone wrong.
# stdout: Your input, prepended by '[warning] '.
function ViashWarning {
  ViashLog $VIASH_LOGCODE_WARNING warning "$@"
}

# ViashNotice: log significant but normal events
# usage: ViashNotice This just happened.
# stdout: Your input, prepended by '[notice] '.
function ViashNotice {
  ViashLog $VIASH_LOGCODE_NOTICE notice "$@"
}

# ViashInfo: log normal events
# usage: ViashInfo This just happened.
# stdout: Your input, prepended by '[info] '.
function ViashInfo {
  ViashLog $VIASH_LOGCODE_INFO info "$@"
}

# ViashDebug: log all events, for debugging purposes
# usage: ViashDebug This just happened.
# stdout: Your input, prepended by '[debug] '.
function ViashDebug {
  ViashLog $VIASH_LOGCODE_DEBUG debug "$@"
}

# find source folder of this component
VIASH_META_RESOURCES_DIR=`ViashSourceDir ${BASH_SOURCE[0]}`

# find the root of the built components & dependencies
VIASH_TARGET_DIR=`ViashFindTargetDir $VIASH_META_RESOURCES_DIR`

# define meta fields
VIASH_META_NAME="deseq2"
VIASH_META_FUNCTIONALITY_NAME="deseq2"
VIASH_META_EXECUTABLE="$VIASH_META_RESOURCES_DIR/$VIASH_META_NAME"
VIASH_META_CONFIG="$VIASH_META_RESOURCES_DIR/.config.vsh.yaml"
VIASH_META_TEMP_DIR="$VIASH_TEMP"



# initialise variables
VIASH_MODE='run'
VIASH_ENGINE_ID='docker'

######## Helper functions for setting up Docker images for viash ########
# expects: ViashDockerBuild

# ViashDockerInstallationCheck: check whether Docker is installed correctly
#
# examples:
#   ViashDockerInstallationCheck
function ViashDockerInstallationCheck {
  ViashDebug "Checking whether Docker is installed"
  if [ ! command -v docker &> /dev/null ]; then
    ViashCritical "Docker doesn't seem to be installed. See 'https://docs.docker.com/get-docker/' for instructions."
    exit 1
  fi

  ViashDebug "Checking whether the Docker daemon is running"
  local save=$-; set +e
  local docker_version=$(docker version --format '{{.Client.APIVersion}}' 2> /dev/null)
  local out=$?
  [[ $save =~ e ]] && set -e
  if [ $out -ne 0 ]; then
    ViashCritical "Docker daemon does not seem to be running. Try one of the following:"
    ViashCritical "- Try running 'dockerd' in the command line"
    ViashCritical "- See https://docs.docker.com/config/daemon/"
    exit 1
  fi
}

# ViashDockerRemoteTagCheck: check whether a Docker image is available 
# on a remote. Assumes `docker login` has been performed, if relevant.
#
# $1                  : image identifier with format `[registry/]image[:tag]`
# exit code $?        : whether or not the image was found
# examples:
#   ViashDockerRemoteTagCheck python:latest
#   echo $?                                     # returns '0'
#   ViashDockerRemoteTagCheck sdaizudceahifu
#   echo $?                                     # returns '1'
function ViashDockerRemoteTagCheck {
  docker manifest inspect $1 > /dev/null 2> /dev/null
}

# ViashDockerLocalTagCheck: check whether a Docker image is available locally
#
# $1                  : image identifier with format `[registry/]image[:tag]`
# exit code $?        : whether or not the image was found
# examples:
#   docker pull python:latest
#   ViashDockerLocalTagCheck python:latest
#   echo $?                                     # returns '0'
#   ViashDockerLocalTagCheck sdaizudceahifu
#   echo $?                                     # returns '1'
function ViashDockerLocalTagCheck {
  [ -n "$(docker images -q $1)" ]
}

# ViashDockerPull: pull a Docker image
#
# $1                  : image identifier with format `[registry/]image[:tag]`
# exit code $?        : whether or not the image was found
# examples:
#   ViashDockerPull python:latest
#   echo $?                                     # returns '0'
#   ViashDockerPull sdaizudceahifu
#   echo $?                                     # returns '1'
function ViashDockerPull {
  ViashNotice "Checking if Docker image is available at '$1'"
  if [ $VIASH_VERBOSITY -ge $VIASH_LOGCODE_INFO ]; then
    docker pull $1 && return 0 || return 1
  else
    local save=$-; set +e
    docker pull $1 2> /dev/null > /dev/null
    local out=$?
    [[ $save =~ e ]] && set -e
    if [ $out -ne 0 ]; then
      ViashWarning "Could not pull from '$1'. Docker image doesn't exist or is not accessible."
    fi
    return $out
  fi
}

# ViashDockerPush: push a Docker image
#
# $1                  : image identifier with format `[registry/]image[:tag]`
# exit code $?        : whether or not the image was found
# examples:
#   ViashDockerPush python:latest
#   echo $?                                     # returns '0'
#   ViashDockerPush sdaizudceahifu
#   echo $?                                     # returns '1'
function ViashDockerPush {
  ViashNotice "Pushing image to '$1'"
  local save=$-; set +e
  local out
  if [ $VIASH_VERBOSITY -ge $VIASH_LOGCODE_INFO ]; then
    docker push $1
    out=$?
  else
    docker push $1 2> /dev/null > /dev/null
    out=$?
  fi
  [[ $save =~ e ]] && set -e
  if [ $out -eq 0 ]; then
    ViashNotice "Container '$1' push succeeded."
  else
    ViashError "Container '$1' push errored. You might not be logged in or have the necessary permissions."
  fi
  return $out
}

# ViashDockerPullElseBuild: pull a Docker image, else build it
#
# $1                  : image identifier with format `[registry/]image[:tag]`
# ViashDockerBuild    : a Bash function which builds a docker image, takes image identifier as argument.
# examples:
#   ViashDockerPullElseBuild mynewcomponent
function ViashDockerPullElseBuild {
  local save=$-; set +e
  ViashDockerPull $1
  local out=$?
  [[ $save =~ e ]] && set -e
  if [ $out -ne 0 ]; then
    ViashDockerBuild $@
  fi
}

# ViashDockerSetup: create a Docker image, according to specified docker setup strategy
#
# $1          : image identifier with format `[registry/]image[:tag]`
# $2          : docker setup strategy, see DockerSetupStrategy.scala
# examples:
#   ViashDockerSetup mynewcomponent alwaysbuild
function ViashDockerSetup {
  local image_id="$1"
  local setup_strategy="$2"
  if [ "$setup_strategy" == "alwaysbuild" -o "$setup_strategy" == "build" -o "$setup_strategy" == "b" ]; then
    ViashDockerBuild $image_id --no-cache $(ViashDockerBuildArgs "$engine_id")
  elif [ "$setup_strategy" == "alwayspull" -o "$setup_strategy" == "pull" -o "$setup_strategy" == "p" ]; then
    ViashDockerPull $image_id
  elif [ "$setup_strategy" == "alwayspullelsebuild" -o "$setup_strategy" == "pullelsebuild" ]; then
    ViashDockerPullElseBuild $image_id --no-cache $(ViashDockerBuildArgs "$engine_id")
  elif [ "$setup_strategy" == "alwayspullelsecachedbuild" -o "$setup_strategy" == "pullelsecachedbuild" ]; then
    ViashDockerPullElseBuild $image_id $(ViashDockerBuildArgs "$engine_id")
  elif [ "$setup_strategy" == "alwayscachedbuild" -o "$setup_strategy" == "cachedbuild" -o "$setup_strategy" == "cb" ]; then
    ViashDockerBuild $image_id $(ViashDockerBuildArgs "$engine_id")
  elif [[ "$setup_strategy" =~ ^ifneedbe ]]; then
    local save=$-; set +e
    ViashDockerLocalTagCheck $image_id
    local outCheck=$?
    [[ $save =~ e ]] && set -e
    if [ $outCheck -eq 0 ]; then
      ViashInfo "Image $image_id already exists"
    elif [ "$setup_strategy" == "ifneedbebuild" ]; then
      ViashDockerBuild $image_id --no-cache $(ViashDockerBuildArgs "$engine_id")
    elif [ "$setup_strategy" == "ifneedbecachedbuild" ]; then
      ViashDockerBuild $image_id $(ViashDockerBuildArgs "$engine_id")
    elif [ "$setup_strategy" == "ifneedbepull" ]; then
      ViashDockerPull $image_id
    elif [ "$setup_strategy" == "ifneedbepullelsebuild" ]; then
      ViashDockerPullElseBuild $image_id --no-cache $(ViashDockerBuildArgs "$engine_id")
    elif [ "$setup_strategy" == "ifneedbepullelsecachedbuild" ]; then
      ViashDockerPullElseBuild $image_id $(ViashDockerBuildArgs "$engine_id")
    else
      ViashError "Unrecognised Docker strategy: $setup_strategy"
      exit 1
    fi
  elif [ "$setup_strategy" == "push" -o "$setup_strategy" == "forcepush" -o "$setup_strategy" == "alwayspush" ]; then
    ViashDockerPush "$image_id"
  elif [ "$setup_strategy" == "pushifnotpresent" -o "$setup_strategy" == "gentlepush" -o "$setup_strategy" == "maybepush" ]; then
    local save=$-; set +e
    ViashDockerRemoteTagCheck $image_id
    local outCheck=$?
    [[ $save =~ e ]] && set -e
    if [ $outCheck -eq 0 ]; then
      ViashNotice "Container '$image_id' exists, doing nothing."
    else
      ViashNotice "Container '$image_id' does not yet exist."
      ViashDockerPush "$image_id"
    fi
  elif [ "$setup_strategy" == "donothing" -o "$setup_strategy" == "meh" ]; then
    ViashNotice "Skipping setup."
  else
    ViashError "Unrecognised Docker strategy: $setup_strategy"
    exit 1
  fi
}

# ViashDockerCheckCommands: Check whether a docker container has the required commands
#
# $1                  : image identifier with format `[registry/]image[:tag]`
# $@                  : commands to verify being present
# examples:
#   ViashDockerCheckCommands bash:4.0 bash ps foo
function ViashDockerCheckCommands {
  local image_id="$1"
  shift 1
  local commands="$@"
  local save=$-; set +e
  local missing # mark 'missing' as local in advance, otherwise the exit code of the command will be missing and always be '0'
  missing=$(docker run --rm --entrypoint=sh "$image_id" -c "for command in $commands; do command -v \$command >/dev/null 2>&1; if [ \$? -ne 0 ]; then echo \$command; exit 1; fi; done")
  local outCheck=$?
  [[ $save =~ e ]] && set -e
  if [ $outCheck -ne 0 ]; then
  	ViashError "Docker container '$image_id' does not contain command '$missing'."
  	exit 1
  fi
}

# ViashDockerBuild: build a docker image
# $1                               : image identifier with format `[registry/]image[:tag]`
# $...                             : additional arguments to pass to docker build
# $VIASH_META_TEMP_DIR             : temporary directory to store dockerfile & optional resources in
# $VIASH_META_NAME                 : name of the component
# $VIASH_META_RESOURCES_DIR        : directory containing the resources
# $VIASH_VERBOSITY                 : verbosity level
# exit code $?                     : whether or not the image was built successfully
function ViashDockerBuild {
  local image_id="$1"
  shift 1

  # create temporary directory to store dockerfile & optional resources in
  local tmpdir=$(mktemp -d "$VIASH_META_TEMP_DIR/dockerbuild-$VIASH_META_NAME-XXXXXX")
  local dockerfile="$tmpdir/Dockerfile"
  function clean_up {
    rm -rf "$tmpdir"
  }
  trap clean_up EXIT

  # store dockerfile and resources
  ViashDockerfile "$VIASH_ENGINE_ID" > "$dockerfile"

  # generate the build command
  local docker_build_cmd="docker build -t '$image_id' $@ '$VIASH_META_RESOURCES_DIR' -f '$dockerfile'"

  # build the container
  ViashNotice "Building container '$image_id' with Dockerfile"
  ViashInfo "$docker_build_cmd"
  local save=$-; set +e
  if [ $VIASH_VERBOSITY -ge $VIASH_LOGCODE_INFO ]; then
    eval $docker_build_cmd
  else
    eval $docker_build_cmd &> "$tmpdir/docker_build.log"
  fi

  # check exit code
  local out=$?
  [[ $save =~ e ]] && set -e
  if [ $out -ne 0 ]; then
    ViashError "Error occurred while building container '$image_id'"
    if [ $VIASH_VERBOSITY -lt $VIASH_LOGCODE_INFO ]; then
      ViashError "Transcript: --------------------------------"
      cat "$tmpdir/docker_build.log"
      ViashError "End of transcript --------------------------"
    fi
    exit 1
  fi
}

######## End of helper functions for setting up Docker images for viash ########

# ViashDockerFile: print the dockerfile to stdout
# $1    : engine identifier
# return : dockerfile required to run this component
# examples:
#   ViashDockerFile
function ViashDockerfile {
  local engine_id="$1"

  if [[ "$engine_id" == "docker" ]]; then
    cat << 'VIASHDOCKER'
FROM rocker/r2u:24.04
ENTRYPOINT []
RUN apt-get update && \
  DEBIAN_FRONTEND=noninteractive apt-get install -y libhdf5-dev libgeos-dev hdf5-tools && \
  rm -rf /var/lib/apt/lists/*

RUN Rscript -e 'options(warn = 2); if (!requireNamespace("remotes", quietly = TRUE)) install.packages("remotes")' && \
  Rscript -e 'options(warn = 2); if (!requireNamespace("BiocManager", quietly = TRUE)) install.packages("BiocManager")' && \
  Rscript -e 'options(warn = 2); if (!requireNamespace("DESeq2", quietly = TRUE)) BiocManager::install("DESeq2")' && \
  Rscript -e 'options(warn = 2); remotes::install_cran(c("hdf5r"), repos = "https://cran.rstudio.com")'

RUN --mount=type=secret,id=GITHUB_TOKEN,env=GITHUB_TOKEN
RUN Rscript -e 'options(warn = 2); remotes::install_github(c("scverse/anndataR@36f3caad9a7f360165c1510bbe0c62657580415a"), repos = "https://cran.rstudio.com")'
LABEL org.opencontainers.image.authors="Jakub Majercik, Dorien Roosen, Dries De Maeyer, Weiwei Schultz"
LABEL org.opencontainers.image.description="Companion container for running component differential_expression deseq2"
LABEL org.opencontainers.image.created="2026-02-18T09:29:54Z"
LABEL org.opencontainers.image.source="https://github.com/openpipelines-bio/openpipeline"
LABEL org.opencontainers.image.revision="7bfad4ea12f87eca59213be3ab08deff67cc4206"
LABEL org.opencontainers.image.version="v4.0.3"

VIASHDOCKER
  fi
}

# ViashDockerBuildArgs: return the arguments to pass to docker build
# $1    : engine identifier
# return : arguments to pass to docker build
function ViashDockerBuildArgs {
  local engine_id="$1"

  if [[ "$engine_id" == "docker" ]]; then
    echo ""
  fi
}

# ViashAbsolutePath: generate absolute path from relative path
# borrowed from https://stackoverflow.com/a/21951256
# $1     : relative filename
# return : absolute path
# examples:
#   ViashAbsolutePath some_file.txt   # returns /path/to/some_file.txt
#   ViashAbsolutePath /foo/bar/..     # returns /foo
function ViashAbsolutePath {
  local thePath
  local parr
  local outp
  local len
  if [[ ! "$1" =~ ^/ ]]; then
    thePath="$PWD/$1"
  else
    thePath="$1"
  fi
  echo "$thePath" | (
    IFS=/
    read -a parr
    declare -a outp
    for i in "${parr[@]}"; do
      case "$i" in
      ''|.) continue ;;
      ..)
        len=${#outp[@]}
        if ((len==0)); then
          continue
        else
          unset outp[$((len-1))]
        fi
        ;;
      *)
        len=${#outp[@]}
        outp[$len]="$i"
      ;;
      esac
    done
    echo /"${outp[*]}"
  )
}
# ViashDockerAutodetectMount: auto configuring docker mounts from parameters
# $1                             : The parameter value
# returns                        : New parameter
# $VIASH_DIRECTORY_MOUNTS        : Added another parameter to be passed to docker
# $VIASH_DOCKER_AUTOMOUNT_PREFIX : The prefix to be used for the automounts
# examples:
#   ViashDockerAutodetectMount /path/to/bar      # returns '/viash_automount/path/to/bar'
#   ViashDockerAutodetectMountArg /path/to/bar   # returns '--volume="/path/to:/viash_automount/path/to"'
function ViashDockerAutodetectMount {
  local abs_path=$(ViashAbsolutePath "$1")
  local mount_source
  local base_name
  if [ -d "$abs_path" ]; then
    mount_source="$abs_path"
    base_name=""
  else
    mount_source=`dirname "$abs_path"`
    base_name=`basename "$abs_path"`
  fi
  local mount_target="$VIASH_DOCKER_AUTOMOUNT_PREFIX$mount_source"
  if [ -z "$base_name" ]; then
    echo "$mount_target"
  else
    echo "$mount_target/$base_name"
  fi
}
function ViashDockerAutodetectMountArg {
  local abs_path=$(ViashAbsolutePath "$1")
  local mount_source
  local base_name
  if [ -d "$abs_path" ]; then
    mount_source="$abs_path"
    base_name=""
  else
    mount_source=`dirname "$abs_path"`
    base_name=`basename "$abs_path"`
  fi
  local mount_target="$VIASH_DOCKER_AUTOMOUNT_PREFIX$mount_source"
  ViashDebug "ViashDockerAutodetectMountArg $1 -> $mount_source -> $mount_target"
  echo "--volume=\"$mount_source:$mount_target\""
}
function ViashDockerStripAutomount {
  local abs_path=$(ViashAbsolutePath "$1")
  echo "${abs_path#$VIASH_DOCKER_AUTOMOUNT_PREFIX}"
}
# initialise variables
VIASH_DIRECTORY_MOUNTS=()

# configure default docker automount prefix if it is unset
if [ -z "${VIASH_DOCKER_AUTOMOUNT_PREFIX+x}" ]; then
  VIASH_DOCKER_AUTOMOUNT_PREFIX="/viash_automount"
fi

# initialise docker variables
VIASH_DOCKER_RUN_ARGS=(-i --rm)


# ViashHelp: Display helpful explanation about this executable
function ViashHelp {
  echo "deseq2 v4.0.3"
  echo ""
  echo "Performs differential expression analysis using DESeq2 on bulk samples or"
  echo "pseudobulk samples aggregated from single-cell data."
  echo "Note that this component only considers factors as explanatory variables, and"
  echo "excludes covariates from the analysis."
  echo ""
  echo "Inputs:"
  echo "    -i, --input"
  echo "        type: file, required parameter, file must exist"
  echo "        Input h5mu file containing (pseudo-)bulk transcriptomic samples."
  echo ""
  echo "    --modality"
  echo "        type: string"
  echo "        default: rna"
  echo "        Which modality from the input MuData file to process."
  echo ""
  echo "    --input_layer"
  echo "        type: string"
  echo "        Input layer to use. If None, X is used. This layer must contain raw"
  echo "        counts."
  echo ""
  echo "    --var_gene_names"
  echo "        type: string"
  echo "        example: gene_symbol"
  echo "        Name of the .var field that contains gene symbols. If not provided,"
  echo "        .var.index will be used."
  echo ""
  echo "    --obs_cell_group"
  echo "        type: string"
  echo "        .obs field containing the cell group information, for example per cell"
  echo "        type or per cell cluster."
  echo "        If true, performs per-cell-group analysis with cell-group-specific"
  echo "        results."
  echo ""
  echo "Arguments:"
  echo "    --design_formula"
  echo "        type: string, required parameter"
  echo "        example: ~ disease + treatment"
  echo "        The formula should be a tilde (~) followed by the variables with plus"
  echo "        signs between them."
  echo "        The design formula is used to estimate the dispersions and to estimate"
  echo "        the log2 fold changes of the model."
  echo ""
  echo "    --contrast_column"
  echo "        type: string, required parameter"
  echo "        example: treatment"
  echo "        Column in the metadata to use for the contrast."
  echo "        This column should contain the conditions to compare."
  echo ""
  echo "    --contrast_values"
  echo "        type: string, required parameter, multiple values allowed"
  echo "        example: ctrl;stim"
  echo "        Values to compare in the contrast column."
  echo "        First value is the control group, following values are comparison"
  echo "        groups."
  echo "        Values must be present in the fields specified for the design formula."
  echo ""
  echo "    --p_adj_threshold"
  echo "        type: double"
  echo "        default: 0.05"
  echo "        min: 0.0"
  echo "        max: 1.0"
  echo "        Adjusted p-value threshold for significance, corrected with the"
  echo "        Benjamini and Hochberg method."
  echo "        Genes with adjusted p-values below this threshold will be considered"
  echo "        significant."
  echo ""
  echo "    --log2fc_threshold"
  echo "        type: double"
  echo "        default: 0.0"
  echo "        min: 0.0"
  echo "        Log2 fold change threshold for significance."
  echo "        Genes with absolute log2 fold change above this threshold will be"
  echo "        considered significant."
  echo ""
  echo "Outputs:"
  echo "    -o, --output_dir"
  echo "        type: file, required parameter, output, file must exist"
  echo "        Output directory for DESeq2 results."
  echo "        If cell groups are defined (using \`--obs_cell_group\`), the output folder"
  echo "        will contain one CSV per cell group, otherwise it will contain a single"
  echo "        output file."
  echo ""
  echo "    --output_prefix"
  echo "        type: string"
  echo "        default: deseq2_analysis"
  echo "        Prefix for output CSV files."
  echo "        If no cell groups are specified, the output file will be named"
  echo "        \"{prefix}.csv\"."
  echo "        If cell groups are specified, files will be named"
  echo "        \"{prefix}_{cell_group}.csv\"."
  echo ""
  echo "Viash built in Computational Requirements:"
  echo "    ---cpus=INT"
  echo "        Number of CPUs to use"
  echo "    ---memory=STRING"
  echo "        Amount of memory to use. Examples: 4GB, 3MiB."
  echo ""
  echo "Viash built in Docker:"
  echo "    ---setup=STRATEGY"
  echo "        Setup the docker container. Options are: alwaysbuild, alwayscachedbuild, ifneedbebuild, ifneedbecachedbuild, alwayspull, alwayspullelsebuild, alwayspullelsecachedbuild, ifneedbepull, ifneedbepullelsebuild, ifneedbepullelsecachedbuild, push, pushifnotpresent, donothing."
  echo "        Default: ifneedbepullelsecachedbuild"
  echo "    ---dockerfile"
  echo "        Print the dockerfile to stdout."
  echo "    ---docker_run_args=ARG"
  echo "        Provide runtime arguments to Docker. See the documentation on \`docker run\` for more information."
  echo "    ---docker_image_id"
  echo "        Print the docker image id to stdout."
  echo "    ---debug"
  echo "        Enter the docker container for debugging purposes."
  echo ""
  echo "Viash built in Engines:"
  echo "    ---engine=ENGINE_ID"
  echo "        Specify the engine to use. Options are: docker, native."
  echo "        Default: docker"
}

# initialise array
VIASH_POSITIONAL_ARGS=''

while [[ $# -gt 0 ]]; do
    case "$1" in
        -h|--help)
            ViashHelp
            exit
            ;;
        ---v|---verbose)
            let "VIASH_VERBOSITY=VIASH_VERBOSITY+1"
            shift 1
            ;;
        ---verbosity)
            VIASH_VERBOSITY="$2"
            shift 2
            ;;
        ---verbosity=*)
            VIASH_VERBOSITY="$(ViashRemoveFlags "$1")"
            shift 1
            ;;
        --version)
            echo "deseq2 v4.0.3"
            exit
            ;;
        --input)
            [ -n "$VIASH_PAR_INPUT" ] && ViashError Bad arguments for option \'--input\': \'$VIASH_PAR_INPUT\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_INPUT="$2"
            [ $# -lt 2 ] && ViashError Not enough arguments passed to --input. Use "--help" to get more information on the parameters. && exit 1
            shift 2
            ;;
        --input=*)
            [ -n "$VIASH_PAR_INPUT" ] && ViashError Bad arguments for option \'--input=*\': \'$VIASH_PAR_INPUT\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_INPUT=$(ViashRemoveFlags "$1")
            shift 1
            ;;
        -i)
            [ -n "$VIASH_PAR_INPUT" ] && ViashError Bad arguments for option \'-i\': \'$VIASH_PAR_INPUT\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_INPUT="$2"
            [ $# -lt 2 ] && ViashError Not enough arguments passed to -i. Use "--help" to get more information on the parameters. && exit 1
            shift 2
            ;;
        --modality)
            [ -n "$VIASH_PAR_MODALITY" ] && ViashError Bad arguments for option \'--modality\': \'$VIASH_PAR_MODALITY\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_MODALITY="$2"
            [ $# -lt 2 ] && ViashError Not enough arguments passed to --modality. Use "--help" to get more information on the parameters. && exit 1
            shift 2
            ;;
        --modality=*)
            [ -n "$VIASH_PAR_MODALITY" ] && ViashError Bad arguments for option \'--modality=*\': \'$VIASH_PAR_MODALITY\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_MODALITY=$(ViashRemoveFlags "$1")
            shift 1
            ;;
        --input_layer)
            [ -n "$VIASH_PAR_INPUT_LAYER" ] && ViashError Bad arguments for option \'--input_layer\': \'$VIASH_PAR_INPUT_LAYER\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_INPUT_LAYER="$2"
            [ $# -lt 2 ] && ViashError Not enough arguments passed to --input_layer. Use "--help" to get more information on the parameters. && exit 1
            shift 2
            ;;
        --input_layer=*)
            [ -n "$VIASH_PAR_INPUT_LAYER" ] && ViashError Bad arguments for option \'--input_layer=*\': \'$VIASH_PAR_INPUT_LAYER\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_INPUT_LAYER=$(ViashRemoveFlags "$1")
            shift 1
            ;;
        --var_gene_names)
            [ -n "$VIASH_PAR_VAR_GENE_NAMES" ] && ViashError Bad arguments for option \'--var_gene_names\': \'$VIASH_PAR_VAR_GENE_NAMES\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_VAR_GENE_NAMES="$2"
            [ $# -lt 2 ] && ViashError Not enough arguments passed to --var_gene_names. Use "--help" to get more information on the parameters. && exit 1
            shift 2
            ;;
        --var_gene_names=*)
            [ -n "$VIASH_PAR_VAR_GENE_NAMES" ] && ViashError Bad arguments for option \'--var_gene_names=*\': \'$VIASH_PAR_VAR_GENE_NAMES\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_VAR_GENE_NAMES=$(ViashRemoveFlags "$1")
            shift 1
            ;;
        --obs_cell_group)
            [ -n "$VIASH_PAR_OBS_CELL_GROUP" ] && ViashError Bad arguments for option \'--obs_cell_group\': \'$VIASH_PAR_OBS_CELL_GROUP\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_OBS_CELL_GROUP="$2"
            [ $# -lt 2 ] && ViashError Not enough arguments passed to --obs_cell_group. Use "--help" to get more information on the parameters. && exit 1
            shift 2
            ;;
        --obs_cell_group=*)
            [ -n "$VIASH_PAR_OBS_CELL_GROUP" ] && ViashError Bad arguments for option \'--obs_cell_group=*\': \'$VIASH_PAR_OBS_CELL_GROUP\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_OBS_CELL_GROUP=$(ViashRemoveFlags "$1")
            shift 1
            ;;
        --design_formula)
            [ -n "$VIASH_PAR_DESIGN_FORMULA" ] && ViashError Bad arguments for option \'--design_formula\': \'$VIASH_PAR_DESIGN_FORMULA\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_DESIGN_FORMULA="$2"
            [ $# -lt 2 ] && ViashError Not enough arguments passed to --design_formula. Use "--help" to get more information on the parameters. && exit 1
            shift 2
            ;;
        --design_formula=*)
            [ -n "$VIASH_PAR_DESIGN_FORMULA" ] && ViashError Bad arguments for option \'--design_formula=*\': \'$VIASH_PAR_DESIGN_FORMULA\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_DESIGN_FORMULA=$(ViashRemoveFlags "$1")
            shift 1
            ;;
        --contrast_column)
            [ -n "$VIASH_PAR_CONTRAST_COLUMN" ] && ViashError Bad arguments for option \'--contrast_column\': \'$VIASH_PAR_CONTRAST_COLUMN\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_CONTRAST_COLUMN="$2"
            [ $# -lt 2 ] && ViashError Not enough arguments passed to --contrast_column. Use "--help" to get more information on the parameters. && exit 1
            shift 2
            ;;
        --contrast_column=*)
            [ -n "$VIASH_PAR_CONTRAST_COLUMN" ] && ViashError Bad arguments for option \'--contrast_column=*\': \'$VIASH_PAR_CONTRAST_COLUMN\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_CONTRAST_COLUMN=$(ViashRemoveFlags "$1")
            shift 1
            ;;
        --contrast_values)
            if [ -z "$VIASH_PAR_CONTRAST_VALUES" ]; then
              VIASH_PAR_CONTRAST_VALUES="$2"
            else
              VIASH_PAR_CONTRAST_VALUES="$VIASH_PAR_CONTRAST_VALUES;""$2"
            fi
            [ $# -lt 2 ] && ViashError Not enough arguments passed to --contrast_values. Use "--help" to get more information on the parameters. && exit 1
            shift 2
            ;;
        --contrast_values=*)
            if [ -z "$VIASH_PAR_CONTRAST_VALUES" ]; then
              VIASH_PAR_CONTRAST_VALUES=$(ViashRemoveFlags "$1")
            else
              VIASH_PAR_CONTRAST_VALUES="$VIASH_PAR_CONTRAST_VALUES;"$(ViashRemoveFlags "$1")
            fi
            shift 1
            ;;
        --p_adj_threshold)
            [ -n "$VIASH_PAR_P_ADJ_THRESHOLD" ] && ViashError Bad arguments for option \'--p_adj_threshold\': \'$VIASH_PAR_P_ADJ_THRESHOLD\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_P_ADJ_THRESHOLD="$2"
            [ $# -lt 2 ] && ViashError Not enough arguments passed to --p_adj_threshold. Use "--help" to get more information on the parameters. && exit 1
            shift 2
            ;;
        --p_adj_threshold=*)
            [ -n "$VIASH_PAR_P_ADJ_THRESHOLD" ] && ViashError Bad arguments for option \'--p_adj_threshold=*\': \'$VIASH_PAR_P_ADJ_THRESHOLD\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_P_ADJ_THRESHOLD=$(ViashRemoveFlags "$1")
            shift 1
            ;;
        --log2fc_threshold)
            [ -n "$VIASH_PAR_LOG2FC_THRESHOLD" ] && ViashError Bad arguments for option \'--log2fc_threshold\': \'$VIASH_PAR_LOG2FC_THRESHOLD\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_LOG2FC_THRESHOLD="$2"
            [ $# -lt 2 ] && ViashError Not enough arguments passed to --log2fc_threshold. Use "--help" to get more information on the parameters. && exit 1
            shift 2
            ;;
        --log2fc_threshold=*)
            [ -n "$VIASH_PAR_LOG2FC_THRESHOLD" ] && ViashError Bad arguments for option \'--log2fc_threshold=*\': \'$VIASH_PAR_LOG2FC_THRESHOLD\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_LOG2FC_THRESHOLD=$(ViashRemoveFlags "$1")
            shift 1
            ;;
        --output_dir)
            [ -n "$VIASH_PAR_OUTPUT_DIR" ] && ViashError Bad arguments for option \'--output_dir\': \'$VIASH_PAR_OUTPUT_DIR\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_OUTPUT_DIR="$2"
            [ $# -lt 2 ] && ViashError Not enough arguments passed to --output_dir. Use "--help" to get more information on the parameters. && exit 1
            shift 2
            ;;
        --output_dir=*)
            [ -n "$VIASH_PAR_OUTPUT_DIR" ] && ViashError Bad arguments for option \'--output_dir=*\': \'$VIASH_PAR_OUTPUT_DIR\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_OUTPUT_DIR=$(ViashRemoveFlags "$1")
            shift 1
            ;;
        -o)
            [ -n "$VIASH_PAR_OUTPUT_DIR" ] && ViashError Bad arguments for option \'-o\': \'$VIASH_PAR_OUTPUT_DIR\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_OUTPUT_DIR="$2"
            [ $# -lt 2 ] && ViashError Not enough arguments passed to -o. Use "--help" to get more information on the parameters. && exit 1
            shift 2
            ;;
        --output_prefix)
            [ -n "$VIASH_PAR_OUTPUT_PREFIX" ] && ViashError Bad arguments for option \'--output_prefix\': \'$VIASH_PAR_OUTPUT_PREFIX\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_OUTPUT_PREFIX="$2"
            [ $# -lt 2 ] && ViashError Not enough arguments passed to --output_prefix. Use "--help" to get more information on the parameters. && exit 1
            shift 2
            ;;
        --output_prefix=*)
            [ -n "$VIASH_PAR_OUTPUT_PREFIX" ] && ViashError Bad arguments for option \'--output_prefix=*\': \'$VIASH_PAR_OUTPUT_PREFIX\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_PAR_OUTPUT_PREFIX=$(ViashRemoveFlags "$1")
            shift 1
            ;;
        ---engine)
            VIASH_ENGINE_ID="$2"
            shift 2
            ;;
        ---engine=*)
            VIASH_ENGINE_ID="$(ViashRemoveFlags "$1")"
            shift 1
            ;;
        ---setup)
            VIASH_MODE='setup'
            VIASH_SETUP_STRATEGY="$2"
            shift 2
            ;;
        ---setup=*)
            VIASH_MODE='setup'
            VIASH_SETUP_STRATEGY="$(ViashRemoveFlags "$1")"
            shift 1
            ;;
        ---dockerfile)
            VIASH_MODE='dockerfile'
            shift 1
            ;;
        ---docker_run_args)
            VIASH_DOCKER_RUN_ARGS+=("$2")
            shift 2
            ;;
        ---docker_run_args=*)
            VIASH_DOCKER_RUN_ARGS+=("$(ViashRemoveFlags "$1")")
            shift 1
            ;;
        ---docker_image_id)
            VIASH_MODE='docker_image_id'
            shift 1
            ;;
        ---debug)
            VIASH_MODE='debug'
            shift 1
            ;;
        ---cpus)
            [ -n "$VIASH_META_CPUS" ] && ViashError Bad arguments for option \'---cpus\': \'$VIASH_META_CPUS\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_META_CPUS="$2"
            [ $# -lt 2 ] && ViashError Not enough arguments passed to ---cpus. Use "--help" to get more information on the parameters. && exit 1
            shift 2
            ;;
        ---cpus=*)
            [ -n "$VIASH_META_CPUS" ] && ViashError Bad arguments for option \'---cpus=*\': \'$VIASH_META_CPUS\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_META_CPUS=$(ViashRemoveFlags "$1")
            shift 1
            ;;
        ---memory)
            [ -n "$VIASH_META_MEMORY" ] && ViashError Bad arguments for option \'---memory\': \'$VIASH_META_MEMORY\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_META_MEMORY="$2"
            [ $# -lt 2 ] && ViashError Not enough arguments passed to ---memory. Use "--help" to get more information on the parameters. && exit 1
            shift 2
            ;;
        ---memory=*)
            [ -n "$VIASH_META_MEMORY" ] && ViashError Bad arguments for option \'---memory=*\': \'$VIASH_META_MEMORY\' \& \'$2\' - you should provide exactly one argument for this option. && exit 1
            VIASH_META_MEMORY=$(ViashRemoveFlags "$1")
            shift 1
            ;;
        *)  # positional arg or unknown option
            # since the positional args will be eval'd, can we always quote, instead of using ViashQuote
            VIASH_POSITIONAL_ARGS="$VIASH_POSITIONAL_ARGS '$1'"
            [[ $1 == -* ]] && ViashWarning $1 looks like a parameter but is not a defined parameter and will instead be treated as a positional argument. Use "--help" to get more information on the parameters.
            shift # past argument
            ;;
    esac
done

# parse positional parameters
eval set -- $VIASH_POSITIONAL_ARGS


if   [ "$VIASH_ENGINE_ID" == "native" ]  ; then
  VIASH_ENGINE_TYPE='native'
elif   [ "$VIASH_ENGINE_ID" == "docker" ]  ; then
  VIASH_ENGINE_TYPE='docker'
else
  ViashError "Engine '$VIASH_ENGINE_ID' is not recognized. Options are: docker, native."
  exit 1
fi

if [[ "$VIASH_ENGINE_TYPE" == "docker" ]]; then
  # check if docker is installed properly
  ViashDockerInstallationCheck

  # determine docker image id
  if [[ "$VIASH_ENGINE_ID" == 'docker' ]]; then
    VIASH_DOCKER_IMAGE_ID='images.viash-hub.com/vsh/openpipeline/differential_expression/deseq2:v4.0.3'
  fi

  # print dockerfile
  if [ "$VIASH_MODE" == "dockerfile" ]; then
    ViashDockerfile "$VIASH_ENGINE_ID"
    exit 0

  elif [ "$VIASH_MODE" == "docker_image_id" ]; then
    echo "$VIASH_DOCKER_IMAGE_ID"
    exit 0
  
  # enter docker container
  elif [[ "$VIASH_MODE" == "debug" ]]; then
    VIASH_CMD="docker run --entrypoint=bash ${VIASH_DOCKER_RUN_ARGS[@]} -v '$(pwd)':/pwd --workdir /pwd -t $VIASH_DOCKER_IMAGE_ID"
    ViashNotice "+ $VIASH_CMD"
    eval $VIASH_CMD
    exit 

  # build docker image
  elif [ "$VIASH_MODE" == "setup" ]; then
    ViashDockerSetup "$VIASH_DOCKER_IMAGE_ID" "$VIASH_SETUP_STRATEGY"
    ViashDockerCheckCommands "$VIASH_DOCKER_IMAGE_ID" 'bash'
    exit 0
  fi

  # check if docker image exists
  ViashDockerSetup "$VIASH_DOCKER_IMAGE_ID" ifneedbepullelsecachedbuild
  ViashDockerCheckCommands "$VIASH_DOCKER_IMAGE_ID" 'bash'
fi

# setting computational defaults

# helper function for parsing memory strings
function ViashMemoryAsBytes {
  local memory=`echo "$1" | tr '[:upper:]' '[:lower:]' | tr -d '[:space:]'`
  local memory_regex='^([0-9]+)([kmgtp]i?b?|b)$'
  if [[ $memory =~ $memory_regex ]]; then
    local number=${memory/[^0-9]*/}
    local symbol=${memory/*[0-9]/}
    
    case $symbol in
      b)      memory_b=$number ;;
      kb|k)   memory_b=$(( $number * 1000 )) ;;
      mb|m)   memory_b=$(( $number * 1000 * 1000 )) ;;
      gb|g)   memory_b=$(( $number * 1000 * 1000 * 1000 )) ;;
      tb|t)   memory_b=$(( $number * 1000 * 1000 * 1000 * 1000 )) ;;
      pb|p)   memory_b=$(( $number * 1000 * 1000 * 1000 * 1000 * 1000 )) ;;
      kib|ki)   memory_b=$(( $number * 1024 )) ;;
      mib|mi)   memory_b=$(( $number * 1024 * 1024 )) ;;
      gib|gi)   memory_b=$(( $number * 1024 * 1024 * 1024 )) ;;
      tib|ti)   memory_b=$(( $number * 1024 * 1024 * 1024 * 1024 )) ;;
      pib|pi)   memory_b=$(( $number * 1024 * 1024 * 1024 * 1024 * 1024 )) ;;
    esac
    echo "$memory_b"
  fi
}
# compute memory in different units
if [ ! -z ${VIASH_META_MEMORY+x} ]; then
  VIASH_META_MEMORY_B=`ViashMemoryAsBytes $VIASH_META_MEMORY`
  # do not define other variables if memory_b is an empty string
  if [ ! -z "$VIASH_META_MEMORY_B" ]; then
    VIASH_META_MEMORY_KB=$(( ($VIASH_META_MEMORY_B+999) / 1000 ))
    VIASH_META_MEMORY_MB=$(( ($VIASH_META_MEMORY_KB+999) / 1000 ))
    VIASH_META_MEMORY_GB=$(( ($VIASH_META_MEMORY_MB+999) / 1000 ))
    VIASH_META_MEMORY_TB=$(( ($VIASH_META_MEMORY_GB+999) / 1000 ))
    VIASH_META_MEMORY_PB=$(( ($VIASH_META_MEMORY_TB+999) / 1000 ))
    VIASH_META_MEMORY_KIB=$(( ($VIASH_META_MEMORY_B+1023) / 1024 ))
    VIASH_META_MEMORY_MIB=$(( ($VIASH_META_MEMORY_KIB+1023) / 1024 ))
    VIASH_META_MEMORY_GIB=$(( ($VIASH_META_MEMORY_MIB+1023) / 1024 ))
    VIASH_META_MEMORY_TIB=$(( ($VIASH_META_MEMORY_GIB+1023) / 1024 ))
    VIASH_META_MEMORY_PIB=$(( ($VIASH_META_MEMORY_TIB+1023) / 1024 ))
  else
    # unset memory if string is empty
    unset $VIASH_META_MEMORY_B
  fi
fi
# unset nproc if string is empty
if [ -z "$VIASH_META_CPUS" ]; then
  unset $VIASH_META_CPUS
fi


# check whether required parameters exist
if [ -z ${VIASH_PAR_INPUT+x} ]; then
  ViashError '--input' is a required argument. Use "--help" to get more information on the parameters.
  exit 1
fi
if [ -z ${VIASH_PAR_DESIGN_FORMULA+x} ]; then
  ViashError '--design_formula' is a required argument. Use "--help" to get more information on the parameters.
  exit 1
fi
if [ -z ${VIASH_PAR_CONTRAST_COLUMN+x} ]; then
  ViashError '--contrast_column' is a required argument. Use "--help" to get more information on the parameters.
  exit 1
fi
if [ -z ${VIASH_PAR_CONTRAST_VALUES+x} ]; then
  ViashError '--contrast_values' is a required argument. Use "--help" to get more information on the parameters.
  exit 1
fi
if [ -z ${VIASH_PAR_OUTPUT_DIR+x} ]; then
  ViashError '--output_dir' is a required argument. Use "--help" to get more information on the parameters.
  exit 1
fi
if [ -z ${VIASH_META_NAME+x} ]; then
  ViashError 'name' is a required argument. Use "--help" to get more information on the parameters.
  exit 1
fi
if [ -z ${VIASH_META_FUNCTIONALITY_NAME+x} ]; then
  ViashError 'functionality_name' is a required argument. Use "--help" to get more information on the parameters.
  exit 1
fi
if [ -z ${VIASH_META_RESOURCES_DIR+x} ]; then
  ViashError 'resources_dir' is a required argument. Use "--help" to get more information on the parameters.
  exit 1
fi
if [ -z ${VIASH_META_EXECUTABLE+x} ]; then
  ViashError 'executable' is a required argument. Use "--help" to get more information on the parameters.
  exit 1
fi
if [ -z ${VIASH_META_CONFIG+x} ]; then
  ViashError 'config' is a required argument. Use "--help" to get more information on the parameters.
  exit 1
fi
if [ -z ${VIASH_META_TEMP_DIR+x} ]; then
  ViashError 'temp_dir' is a required argument. Use "--help" to get more information on the parameters.
  exit 1
fi

# filling in defaults
if [ -z ${VIASH_PAR_MODALITY+x} ]; then
  VIASH_PAR_MODALITY="rna"
fi
if [ -z ${VIASH_PAR_P_ADJ_THRESHOLD+x} ]; then
  VIASH_PAR_P_ADJ_THRESHOLD="0.05"
fi
if [ -z ${VIASH_PAR_LOG2FC_THRESHOLD+x} ]; then
  VIASH_PAR_LOG2FC_THRESHOLD="0.0"
fi
if [ -z ${VIASH_PAR_OUTPUT_PREFIX+x} ]; then
  VIASH_PAR_OUTPUT_PREFIX="deseq2_analysis"
fi

# check whether required files exist
if [ ! -z "$VIASH_PAR_INPUT" ] && [ ! -e "$VIASH_PAR_INPUT" ]; then
  ViashError "Input file '$VIASH_PAR_INPUT' does not exist."
  exit 1
fi

# check whether parameters values are of the right type
if [[ -n "$VIASH_PAR_P_ADJ_THRESHOLD" ]]; then
  if ! [[ "$VIASH_PAR_P_ADJ_THRESHOLD" =~ ^[-+]?(\.[0-9]+|[0-9]+(\.[0-9]*)?)([eE][-+]?[0-9]+)?$ ]]; then
    ViashError '--p_adj_threshold' has to be a double. Use "--help" to get more information on the parameters.
    exit 1
  fi
  if command -v bc &> /dev/null; then
    if ! [[ `echo $VIASH_PAR_P_ADJ_THRESHOLD '>=' 0.0 | bc` -eq 1 ]]; then
      ViashError '--p_adj_threshold' has be more than or equal to 0.0. Use "--help" to get more information on the parameters.
      exit 1
    fi
  elif command -v awk &> /dev/null; then
    if ! [[ `awk -v n1=$VIASH_PAR_P_ADJ_THRESHOLD -v n2=0.0 'BEGIN { print (n1 >= n2) ? "1" : "0" }'` -eq 1 ]]; then
      ViashError '--p_adj_threshold' has be more than or equal to 0.0. Use "--help" to get more information on the parameters.
      exit 1
    fi
  else
    ViashWarning '--p_adj_threshold' specifies a minimum value but the value was not verified as neither \'bc\' or \`awk\` are present on the system.
  fi
  if command -v bc &> /dev/null; then
    if ! [[ `echo $VIASH_PAR_P_ADJ_THRESHOLD '<=' 1.0 | bc` -eq 1 ]]; then
      ViashError '--p_adj_threshold' has to be less than or equal to 1.0. Use "--help" to get more information on the parameters.
      exit 1
    fi
  elif command -v awk &> /dev/null; then
    if ! [[ `awk -v n1=$VIASH_PAR_P_ADJ_THRESHOLD -v n2=1.0 'BEGIN { print (n1 <= n2) ? "1" : "0" }'` -eq 1 ]]; then
      ViashError '--p_adj_threshold' has be less than or equal to 1.0. Use "--help" to get more information on the parameters.
      exit 1
    fi
  else
    ViashWarning '--p_adj_threshold' specifies a maximum value but the value was not verified as neither \'bc\' or \'awk\' are present on the system.
  fi
fi
if [[ -n "$VIASH_PAR_LOG2FC_THRESHOLD" ]]; then
  if ! [[ "$VIASH_PAR_LOG2FC_THRESHOLD" =~ ^[-+]?(\.[0-9]+|[0-9]+(\.[0-9]*)?)([eE][-+]?[0-9]+)?$ ]]; then
    ViashError '--log2fc_threshold' has to be a double. Use "--help" to get more information on the parameters.
    exit 1
  fi
  if command -v bc &> /dev/null; then
    if ! [[ `echo $VIASH_PAR_LOG2FC_THRESHOLD '>=' 0.0 | bc` -eq 1 ]]; then
      ViashError '--log2fc_threshold' has be more than or equal to 0.0. Use "--help" to get more information on the parameters.
      exit 1
    fi
  elif command -v awk &> /dev/null; then
    if ! [[ `awk -v n1=$VIASH_PAR_LOG2FC_THRESHOLD -v n2=0.0 'BEGIN { print (n1 >= n2) ? "1" : "0" }'` -eq 1 ]]; then
      ViashError '--log2fc_threshold' has be more than or equal to 0.0. Use "--help" to get more information on the parameters.
      exit 1
    fi
  else
    ViashWarning '--log2fc_threshold' specifies a minimum value but the value was not verified as neither \'bc\' or \`awk\` are present on the system.
  fi
fi
if [[ -n "$VIASH_META_CPUS" ]]; then
  if ! [[ "$VIASH_META_CPUS" =~ ^[-+]?[0-9]+$ ]]; then
    ViashError 'cpus' has to be an integer. Use "--help" to get more information on the parameters.
    exit 1
  fi
fi
if [[ -n "$VIASH_META_MEMORY_B" ]]; then
  if ! [[ "$VIASH_META_MEMORY_B" =~ ^[-+]?[0-9]+$ ]]; then
    ViashError 'memory_b' has to be a long. Use "--help" to get more information on the parameters.
    exit 1
  fi
fi
if [[ -n "$VIASH_META_MEMORY_KB" ]]; then
  if ! [[ "$VIASH_META_MEMORY_KB" =~ ^[-+]?[0-9]+$ ]]; then
    ViashError 'memory_kb' has to be a long. Use "--help" to get more information on the parameters.
    exit 1
  fi
fi
if [[ -n "$VIASH_META_MEMORY_MB" ]]; then
  if ! [[ "$VIASH_META_MEMORY_MB" =~ ^[-+]?[0-9]+$ ]]; then
    ViashError 'memory_mb' has to be a long. Use "--help" to get more information on the parameters.
    exit 1
  fi
fi
if [[ -n "$VIASH_META_MEMORY_GB" ]]; then
  if ! [[ "$VIASH_META_MEMORY_GB" =~ ^[-+]?[0-9]+$ ]]; then
    ViashError 'memory_gb' has to be a long. Use "--help" to get more information on the parameters.
    exit 1
  fi
fi
if [[ -n "$VIASH_META_MEMORY_TB" ]]; then
  if ! [[ "$VIASH_META_MEMORY_TB" =~ ^[-+]?[0-9]+$ ]]; then
    ViashError 'memory_tb' has to be a long. Use "--help" to get more information on the parameters.
    exit 1
  fi
fi
if [[ -n "$VIASH_META_MEMORY_PB" ]]; then
  if ! [[ "$VIASH_META_MEMORY_PB" =~ ^[-+]?[0-9]+$ ]]; then
    ViashError 'memory_pb' has to be a long. Use "--help" to get more information on the parameters.
    exit 1
  fi
fi
if [[ -n "$VIASH_META_MEMORY_KIB" ]]; then
  if ! [[ "$VIASH_META_MEMORY_KIB" =~ ^[-+]?[0-9]+$ ]]; then
    ViashError 'memory_kib' has to be a long. Use "--help" to get more information on the parameters.
    exit 1
  fi
fi
if [[ -n "$VIASH_META_MEMORY_MIB" ]]; then
  if ! [[ "$VIASH_META_MEMORY_MIB" =~ ^[-+]?[0-9]+$ ]]; then
    ViashError 'memory_mib' has to be a long. Use "--help" to get more information on the parameters.
    exit 1
  fi
fi
if [[ -n "$VIASH_META_MEMORY_GIB" ]]; then
  if ! [[ "$VIASH_META_MEMORY_GIB" =~ ^[-+]?[0-9]+$ ]]; then
    ViashError 'memory_gib' has to be a long. Use "--help" to get more information on the parameters.
    exit 1
  fi
fi
if [[ -n "$VIASH_META_MEMORY_TIB" ]]; then
  if ! [[ "$VIASH_META_MEMORY_TIB" =~ ^[-+]?[0-9]+$ ]]; then
    ViashError 'memory_tib' has to be a long. Use "--help" to get more information on the parameters.
    exit 1
  fi
fi
if [[ -n "$VIASH_META_MEMORY_PIB" ]]; then
  if ! [[ "$VIASH_META_MEMORY_PIB" =~ ^[-+]?[0-9]+$ ]]; then
    ViashError 'memory_pib' has to be a long. Use "--help" to get more information on the parameters.
    exit 1
  fi
fi

# create parent directories of output files, if so desired
if [ ! -z "$VIASH_PAR_OUTPUT_DIR" ] && [ ! -d "$(dirname "$VIASH_PAR_OUTPUT_DIR")" ]; then
  mkdir -p "$(dirname "$VIASH_PAR_OUTPUT_DIR")"
fi

if  [ "$VIASH_ENGINE_ID" == "native" ]  ; then
  if [ "$VIASH_MODE" == "run" ]; then
    VIASH_CMD="bash"
  else
    ViashError "Engine '$VIASH_ENGINE_ID' does not support mode '$VIASH_MODE'."
    exit 1
  fi
fi

if [[ "$VIASH_ENGINE_TYPE" == "docker" ]]; then
  # detect volumes from file arguments
  VIASH_CHOWN_VARS=()
if [ ! -z "$VIASH_PAR_INPUT" ]; then
  VIASH_DIRECTORY_MOUNTS+=( "$(ViashDockerAutodetectMountArg "$VIASH_PAR_INPUT")" )
  VIASH_PAR_INPUT=$(ViashDockerAutodetectMount "$VIASH_PAR_INPUT")
fi
if [ ! -z "$VIASH_PAR_OUTPUT_DIR" ]; then
  VIASH_DIRECTORY_MOUNTS+=( "$(ViashDockerAutodetectMountArg "$VIASH_PAR_OUTPUT_DIR")" )
  VIASH_PAR_OUTPUT_DIR=$(ViashDockerAutodetectMount "$VIASH_PAR_OUTPUT_DIR")
  VIASH_CHOWN_VARS+=( "$VIASH_PAR_OUTPUT_DIR" )
fi
if [ ! -z "$VIASH_META_RESOURCES_DIR" ]; then
  VIASH_DIRECTORY_MOUNTS+=( "$(ViashDockerAutodetectMountArg "$VIASH_META_RESOURCES_DIR")" )
  VIASH_META_RESOURCES_DIR=$(ViashDockerAutodetectMount "$VIASH_META_RESOURCES_DIR")
fi
if [ ! -z "$VIASH_META_EXECUTABLE" ]; then
  VIASH_DIRECTORY_MOUNTS+=( "$(ViashDockerAutodetectMountArg "$VIASH_META_EXECUTABLE")" )
  VIASH_META_EXECUTABLE=$(ViashDockerAutodetectMount "$VIASH_META_EXECUTABLE")
fi
if [ ! -z "$VIASH_META_CONFIG" ]; then
  VIASH_DIRECTORY_MOUNTS+=( "$(ViashDockerAutodetectMountArg "$VIASH_META_CONFIG")" )
  VIASH_META_CONFIG=$(ViashDockerAutodetectMount "$VIASH_META_CONFIG")
fi
if [ ! -z "$VIASH_META_TEMP_DIR" ]; then
  VIASH_DIRECTORY_MOUNTS+=( "$(ViashDockerAutodetectMountArg "$VIASH_META_TEMP_DIR")" )
  VIASH_META_TEMP_DIR=$(ViashDockerAutodetectMount "$VIASH_META_TEMP_DIR")
fi
  
  # get unique mounts
  VIASH_UNIQUE_MOUNTS=($(for val in "${VIASH_DIRECTORY_MOUNTS[@]}"; do echo "$val"; done | sort -u))
fi

if [[ "$VIASH_ENGINE_TYPE" == "docker" ]]; then
  # change file ownership
  function ViashPerformChown {
    if (( ${#VIASH_CHOWN_VARS[@]} )); then
      set +e
      VIASH_CMD="docker run --entrypoint=bash --rm ${VIASH_UNIQUE_MOUNTS[@]} $VIASH_DOCKER_IMAGE_ID -c 'chown $(id -u):$(id -g) --silent --recursive ${VIASH_CHOWN_VARS[@]}'"
      ViashDebug "+ $VIASH_CMD"
      eval $VIASH_CMD
      set -e
    fi
  }
  trap ViashPerformChown EXIT
fi

if [[ "$VIASH_ENGINE_TYPE" == "docker" ]]; then
  # helper function for filling in extra docker args
  if [ ! -z "$VIASH_META_MEMORY_B" ]; then
    VIASH_DOCKER_RUN_ARGS+=("--memory=${VIASH_META_MEMORY_B}")
  fi
  if [ ! -z "$VIASH_META_CPUS" ]; then
    VIASH_DOCKER_RUN_ARGS+=("--cpus=${VIASH_META_CPUS}")
  fi
fi

if [[ "$VIASH_ENGINE_TYPE" == "docker" ]]; then
  VIASH_CMD="docker run --entrypoint=bash ${VIASH_DOCKER_RUN_ARGS[@]} ${VIASH_UNIQUE_MOUNTS[@]} $VIASH_DOCKER_IMAGE_ID"
fi


# set dependency paths


ViashDebug "Running command: $(echo $VIASH_CMD)"
cat << VIASHEOF | eval $VIASH_CMD
set -e
tempscript=\$(mktemp "$VIASH_META_TEMP_DIR/viash-run-deseq2-XXXXXX").R
function clean_up {
  rm "\$tempscript"
}
function interrupt {
  echo -e "\nCTRL-C Pressed..."
  exit 1
}
trap clean_up EXIT
trap interrupt INT SIGINT
cat > "\$tempscript" << 'VIASHMAIN'
library(DESeq2)
library(anndataR)
library(hdf5r)

## VIASH START
# The following code has been auto-generated by Viash.
# treat warnings as errors
.viash_orig_warn <- options(warn = 2)

par <- list(
  "input" = $( if [ ! -z ${VIASH_PAR_INPUT+x} ]; then echo -n "'"; echo -n "$VIASH_PAR_INPUT" | sed "s#['\\]#\\\\&#g"; echo "'"; else echo NULL; fi ),
  "modality" = $( if [ ! -z ${VIASH_PAR_MODALITY+x} ]; then echo -n "'"; echo -n "$VIASH_PAR_MODALITY" | sed "s#['\\]#\\\\&#g"; echo "'"; else echo NULL; fi ),
  "input_layer" = $( if [ ! -z ${VIASH_PAR_INPUT_LAYER+x} ]; then echo -n "'"; echo -n "$VIASH_PAR_INPUT_LAYER" | sed "s#['\\]#\\\\&#g"; echo "'"; else echo NULL; fi ),
  "var_gene_names" = $( if [ ! -z ${VIASH_PAR_VAR_GENE_NAMES+x} ]; then echo -n "'"; echo -n "$VIASH_PAR_VAR_GENE_NAMES" | sed "s#['\\]#\\\\&#g"; echo "'"; else echo NULL; fi ),
  "obs_cell_group" = $( if [ ! -z ${VIASH_PAR_OBS_CELL_GROUP+x} ]; then echo -n "'"; echo -n "$VIASH_PAR_OBS_CELL_GROUP" | sed "s#['\\]#\\\\&#g"; echo "'"; else echo NULL; fi ),
  "design_formula" = $( if [ ! -z ${VIASH_PAR_DESIGN_FORMULA+x} ]; then echo -n "'"; echo -n "$VIASH_PAR_DESIGN_FORMULA" | sed "s#['\\]#\\\\&#g"; echo "'"; else echo NULL; fi ),
  "contrast_column" = $( if [ ! -z ${VIASH_PAR_CONTRAST_COLUMN+x} ]; then echo -n "'"; echo -n "$VIASH_PAR_CONTRAST_COLUMN" | sed "s#['\\]#\\\\&#g"; echo "'"; else echo NULL; fi ),
  "contrast_values" = $( if [ ! -z ${VIASH_PAR_CONTRAST_VALUES+x} ]; then echo -n "strsplit('"; echo -n "$VIASH_PAR_CONTRAST_VALUES" | sed "s#['\\]#\\\\&#g"; echo "', split = ';')[[1]]"; else echo NULL; fi ),
  "p_adj_threshold" = $( if [ ! -z ${VIASH_PAR_P_ADJ_THRESHOLD+x} ]; then echo -n "as.numeric('"; echo -n "$VIASH_PAR_P_ADJ_THRESHOLD" | sed "s#['\\]#\\\\&#g"; echo "')"; else echo NULL; fi ),
  "log2fc_threshold" = $( if [ ! -z ${VIASH_PAR_LOG2FC_THRESHOLD+x} ]; then echo -n "as.numeric('"; echo -n "$VIASH_PAR_LOG2FC_THRESHOLD" | sed "s#['\\]#\\\\&#g"; echo "')"; else echo NULL; fi ),
  "output_dir" = $( if [ ! -z ${VIASH_PAR_OUTPUT_DIR+x} ]; then echo -n "'"; echo -n "$VIASH_PAR_OUTPUT_DIR" | sed "s#['\\]#\\\\&#g"; echo "'"; else echo NULL; fi ),
  "output_prefix" = $( if [ ! -z ${VIASH_PAR_OUTPUT_PREFIX+x} ]; then echo -n "'"; echo -n "$VIASH_PAR_OUTPUT_PREFIX" | sed "s#['\\]#\\\\&#g"; echo "'"; else echo NULL; fi )
)
meta <- list(
  "name" = $( if [ ! -z ${VIASH_META_NAME+x} ]; then echo -n "'"; echo -n "$VIASH_META_NAME" | sed "s#['\\]#\\\\&#g"; echo "'"; else echo NULL; fi ),
  "functionality_name" = $( if [ ! -z ${VIASH_META_FUNCTIONALITY_NAME+x} ]; then echo -n "'"; echo -n "$VIASH_META_FUNCTIONALITY_NAME" | sed "s#['\\]#\\\\&#g"; echo "'"; else echo NULL; fi ),
  "resources_dir" = $( if [ ! -z ${VIASH_META_RESOURCES_DIR+x} ]; then echo -n "'"; echo -n "$VIASH_META_RESOURCES_DIR" | sed "s#['\\]#\\\\&#g"; echo "'"; else echo NULL; fi ),
  "executable" = $( if [ ! -z ${VIASH_META_EXECUTABLE+x} ]; then echo -n "'"; echo -n "$VIASH_META_EXECUTABLE" | sed "s#['\\]#\\\\&#g"; echo "'"; else echo NULL; fi ),
  "config" = $( if [ ! -z ${VIASH_META_CONFIG+x} ]; then echo -n "'"; echo -n "$VIASH_META_CONFIG" | sed "s#['\\]#\\\\&#g"; echo "'"; else echo NULL; fi ),
  "temp_dir" = $( if [ ! -z ${VIASH_META_TEMP_DIR+x} ]; then echo -n "'"; echo -n "$VIASH_META_TEMP_DIR" | sed "s#['\\]#\\\\&#g"; echo "'"; else echo NULL; fi ),
  "cpus" = $( if [ ! -z ${VIASH_META_CPUS+x} ]; then echo -n "as.integer('"; echo -n "$VIASH_META_CPUS" | sed "s#['\\]#\\\\&#g"; echo "')"; else echo NULL; fi ),
  "memory_b" = $( if [ ! -z ${VIASH_META_MEMORY_B+x} ]; then echo -n "bit64::as.integer64('"; echo -n "$VIASH_META_MEMORY_B" | sed "s#['\\]#\\\\&#g"; echo "')"; else echo NULL; fi ),
  "memory_kb" = $( if [ ! -z ${VIASH_META_MEMORY_KB+x} ]; then echo -n "bit64::as.integer64('"; echo -n "$VIASH_META_MEMORY_KB" | sed "s#['\\]#\\\\&#g"; echo "')"; else echo NULL; fi ),
  "memory_mb" = $( if [ ! -z ${VIASH_META_MEMORY_MB+x} ]; then echo -n "bit64::as.integer64('"; echo -n "$VIASH_META_MEMORY_MB" | sed "s#['\\]#\\\\&#g"; echo "')"; else echo NULL; fi ),
  "memory_gb" = $( if [ ! -z ${VIASH_META_MEMORY_GB+x} ]; then echo -n "bit64::as.integer64('"; echo -n "$VIASH_META_MEMORY_GB" | sed "s#['\\]#\\\\&#g"; echo "')"; else echo NULL; fi ),
  "memory_tb" = $( if [ ! -z ${VIASH_META_MEMORY_TB+x} ]; then echo -n "bit64::as.integer64('"; echo -n "$VIASH_META_MEMORY_TB" | sed "s#['\\]#\\\\&#g"; echo "')"; else echo NULL; fi ),
  "memory_pb" = $( if [ ! -z ${VIASH_META_MEMORY_PB+x} ]; then echo -n "bit64::as.integer64('"; echo -n "$VIASH_META_MEMORY_PB" | sed "s#['\\]#\\\\&#g"; echo "')"; else echo NULL; fi ),
  "memory_kib" = $( if [ ! -z ${VIASH_META_MEMORY_KIB+x} ]; then echo -n "bit64::as.integer64('"; echo -n "$VIASH_META_MEMORY_KIB" | sed "s#['\\]#\\\\&#g"; echo "')"; else echo NULL; fi ),
  "memory_mib" = $( if [ ! -z ${VIASH_META_MEMORY_MIB+x} ]; then echo -n "bit64::as.integer64('"; echo -n "$VIASH_META_MEMORY_MIB" | sed "s#['\\]#\\\\&#g"; echo "')"; else echo NULL; fi ),
  "memory_gib" = $( if [ ! -z ${VIASH_META_MEMORY_GIB+x} ]; then echo -n "bit64::as.integer64('"; echo -n "$VIASH_META_MEMORY_GIB" | sed "s#['\\]#\\\\&#g"; echo "')"; else echo NULL; fi ),
  "memory_tib" = $( if [ ! -z ${VIASH_META_MEMORY_TIB+x} ]; then echo -n "bit64::as.integer64('"; echo -n "$VIASH_META_MEMORY_TIB" | sed "s#['\\]#\\\\&#g"; echo "')"; else echo NULL; fi ),
  "memory_pib" = $( if [ ! -z ${VIASH_META_MEMORY_PIB+x} ]; then echo -n "bit64::as.integer64('"; echo -n "$VIASH_META_MEMORY_PIB" | sed "s#['\\]#\\\\&#g"; echo "')"; else echo NULL; fi )
)
dep <- list(
  
)


# restore original warn setting
options(.viash_orig_warn)
rm(.viash_orig_warn)

## VIASH END

cat("Starting DESeq2 analysis...\\n")

h5mu_to_h5ad <- function(h5mu_path, modality_name) {
  tmp_path <- tempfile(fileext = ".h5ad")
  mod_location <- paste("mod", modality_name, sep = "/")
  h5src <- hdf5r::H5File\$new(h5mu_path, "r")
  h5dest <- hdf5r::H5File\$new(tmp_path, "w")
  children <- hdf5r::list.objects(h5src,
    path = mod_location,
    full.names = FALSE, recursive = FALSE
  )
  for (child in children) {
    h5dest\$obj_copy_from(
      h5src, paste(mod_location, child, sep = "/"),
      paste0("/", child)
    )
  }
  # Also copy the root attributes
  root_attrs <- hdf5r::h5attr_names(x = h5src)
  for (attr in root_attrs) {
    h5a <- h5src\$attr_open(attr_name = attr)
    robj <- h5a\$read()
    h5dest\$create_attr_by_name(
      attr_name = attr,
      obj_name = ".",
      robj = robj,
      space = h5a\$get_space(),
      dtype = h5a\$get_type()
    )
  }
  h5src\$close()
  h5dest\$close()

  tmp_path
}

# Extract design factors from formula
parse_design_formula <- function(design_formula) {
  if (!grepl("^~\\\\s*\\\\w+(\\\\s*\\\\+\\\\s*\\\\w+)*\$", design_formula)) {
    stop(
      sprintf(
        paste(
          "Invalid design formula: '%s'.",
          "Formula must start with '~' and contain factors separated by '+'.",
          "Example: '~ disease + treatment'",
          sep = "\\n"
        ),
        design_formula
      )
    )
  }
  design_factors <- all.vars(as.formula(design_formula))
  cat("Design formula:", design_formula, "\\n")
  cat("Extracted factors:", paste(design_factors, collapse = ", "), "\\n")
  design_factors
}

# Validate and prepare contrast specifications
prepare_contrast_matrix <- function(
  design_factors, contrast_column, metadata
) {
  # Validate required columns exist
  required_columns <- unique(c(design_factors, contrast_column))
  missing_columns <- setdiff(required_columns, colnames(metadata))

  if (length(missing_columns) > 0) {
    stop(sprintf(
      paste(
        "Missing required columns in metadata: %s\\n",
        "Available metadata columns: %s"
      ),
      paste(missing_columns, collapse = ", "),
      paste(colnames(metadata), collapse = ", ")
    ))
  }

  # Check contrast values exist
  contrast_values <- par\$contrast_values
  available_values <- unique(metadata[[contrast_column]])
  missing_values <- setdiff(contrast_values, available_values)

  if (length(missing_values) > 0) {
    stop(sprintf(
      paste("Contrast values %s not found in %s.",
        "Available values: %s",
        sep = "\\n"
      ),
      paste(missing_values, collapse = ", "),
      contrast_column,
      paste(available_values, collapse = ", ")
    ))
  }

  # Handle different contrast scenarios
  if (length(contrast_values) == 2) {
    # Pairwise comparison
    comparison_group <- contrast_values[1]
    control_group <- contrast_values[2]
    contrast_spec <- c(contrast_column, comparison_group, control_group)
    cat(
      "Performing pairwise contrast:", contrast_column,
      comparison_group, "vs", control_group, "\\n"
    )
    contrast_spec
  } else if (length(contrast_values) > 2) {
    # Multiple comparisons against first value (control_group)
    control_group <- contrast_values[1]
    contrast_specs <- list()
    for (i in 2:length(contrast_values)) {
      comparison_group <- contrast_values[i]
      contrast_specs[[length(contrast_specs) + 1]] <-
        c(contrast_column, comparison_group, control_group)
    }
    cat(
      "Performing multiple contrasts against control_group '",
      control_group, "':",
      paste(sapply(contrast_specs, function(x) x[2]), collapse = ", "), "\\n"
    )
    contrast_specs
  } else {
    stop(sprintf(
      "Need at least 2 values for contrast, got: %s",
      paste(contrast_values, collapse = ", ")
    ))
  }
}

# Convert expression matrix to counts data frame
prepare_counts_matrix <- function(layer, var_names, obs_names) {
  counts <- if (is(layer, "sparseMatrix") || is(layer, "dgCMatrix")) {
    as.matrix(layer)
  } else {
    layer
  }

  # Create properly named data frame (transpose for DESeq2 format)
  counts_df <- data.frame(counts)
  colnames(counts_df) <- var_names
  rownames(counts_df) <- obs_names

  # Ensure integer counts (required for DESeq2)
  counts_df[] <- lapply(counts_df, function(x) as.integer(round(x)))
  counts_df
}

# Create and configure DESeq2 dataset
create_deseq2_dataset <- function(counts, metadata, design_formula) {
  cat("Creating DESeq2 dataset\\n")

  # Ensure matching samples between counts and metadata
  common_samples <- intersect(rownames(counts), rownames(metadata))
  if (length(common_samples) == 0) {
    stop("No common samples found between counts and metadata")
  }

  counts <- counts[common_samples, , drop = FALSE]
  metadata <- metadata[common_samples, , drop = FALSE]

  # Create DESeqDataSet (transpose for gene x sample format)
  dds <- DESeq2::DESeqDataSetFromMatrix(
    countData = t(counts),
    colData = metadata,
    design = as.formula(design_formula)
  )
  dds
}

# Perform DESeq2 differential expression analysis
deseq2_analysis <- function(dds, contrast_specs) {
  cat("Running DESeq2 analysis\\n")

  dds <- DESeq2::DESeq(dds)

  # Ensure contrast_specs is a list
  if (!is.list(contrast_specs)) {
    contrast_specs <- list(contrast_specs)
  }

  all_results <- lapply(seq_along(contrast_specs), function(i) {
    contrast_spec <- contrast_specs[[i]]
    cat(
      "Performing statistical test for contrast:",
      paste(contrast_spec, collapse = " "), "\\n"
    )

    # Get DESeq2 results for this contrast
    res <- DESeq2::results(
      dds,
      contrast = contrast_spec, alpha = par\$p_adj_threshold
    )

    # Convert to data frame and add metadata
    results_df <- as.data.frame(res)
    results_df\$gene_id <- rownames(results_df)
    results_df\$contrast <- paste0(contrast_spec[2], "_vs_", contrast_spec[3])
    results_df\$comparison_group <- contrast_spec[2]
    results_df\$control_group <- contrast_spec[3]
    results_df\$abs_log2FoldChange <- abs(results_df\$log2FoldChange)
    results_df\$significant <- (
      results_df\$padj < par\$p_adj_threshold &
        !is.na(results_df\$padj) &
        abs(results_df\$log2FoldChange) > par\$log2fc_threshold
    )

    # Sort by effect size
    results_df[order(results_df\$log2FoldChange, decreasing = TRUE), ]
  })

  # Combine all results
  combined_results <- do.call(rbind, all_results)

  # Log summary statistics
  for (i in seq_along(contrast_specs)) {
    contrast_spec <- contrast_specs[[i]]
    contrast_name <- paste0(contrast_spec[2], "_vs_", contrast_spec[3])
    contrast_subset <- combined_results[
      combined_results\$contrast == contrast_name,
    ]
    n_significant <- sum(contrast_subset\$significant, na.rm = TRUE)
    cat("Contrast", contrast_name, ":", n_significant, "significant genes\\n")
  }

  combined_results
}

# Save results and print summary statistics
save_results_and_log_summary <- function(
  results, output_file, cell_group = NULL
) {
  group_text <- if (!is.null(cell_group)) paste(" for", cell_group) else ""
  cat("Saving results", group_text, "to", output_file, "\\n")

  write.csv(results, output_file, row.names = FALSE)

  # Calculate summary statistics
  sig_results <- results[results\$significant & !is.na(results\$significant), ]
  upregulated <- sig_results[sig_results\$log2FoldChange > 0, ]
  downregulated <- sig_results[sig_results\$log2FoldChange < 0, ]

  cat("Summary", group_text, ":\\n")
  cat("  Total genes analyzed:", nrow(results), "\\n")
  cat("  Significant upregulated:", nrow(upregulated), "\\n")
  cat("  Significant downregulated:", nrow(downregulated), "\\n")
}

# Main analysis workflow
main <- function() {
  cat("Loading pseudobulk data from", par\$input, "\\n")

  # Load and prepare data
  h5ad_path <- h5mu_to_h5ad(par\$input, par\$modality)
  mod <- anndataR::read_h5ad(h5ad_path, as = "InMemoryAnnData")
  metadata <- as.data.frame(mod\$obs)

  # Get expression matrix
  layer <- if (!is.null(par\$input_layer)) {
    mod\$layers[[par\$input_layer]]
  } else {
    mod\$X
  }

  # Prepare analysis components
  cat("Preparing design formula\\n")
  design_factors <- parse_design_formula(par\$design_formula)

  cat("Preparing contrast matrix\\n")
  contrast_specs <- prepare_contrast_matrix(
    design_factors, par\$contrast_column, metadata
  )

  cat("Preparing counts matrix for DESeq2\\n")
  var_names <- if (!is.null(par\$var_gene_names)) {
    if (par\$var_gene_names %in% colnames(mod\$var)) {
      mod\$var[[par\$var_gene_names]]
    } else {
      stop(
        sprintf(
          "var_gene_names '%s' not found in mod\$var columns: %s",
          par\$var_gene_names,
          paste(colnames(mod\$var), collapse = ", ")
        )
      )
    }
  } else {
    mod\$var_names
  }
  obs_names <- mod\$obs_names
  counts <- prepare_counts_matrix(layer, var_names, obs_names)

  # Ensure output directory exists
  if (!dir.exists(par\$output_dir)) {
    dir.create(par\$output_dir, recursive = TRUE)
  }

  # Run analysis (per cell group or overall)
  tryCatch(
    {
      if (
        !is.null(par\$obs_cell_group) &&
          par\$obs_cell_group %in% colnames(metadata)
      ) {
        run_per_cell_group_analysis(counts, metadata, contrast_specs)
      } else {
        run_overall_analysis(counts, metadata, contrast_specs)
      }
      cat("DESeq2 analysis completed successfully\\n")
    },
    error = function(e) {
      cat("Error in analysis. Check input data and parameters:\\n")
      cat("Contrast column:", par\$contrast_column, "\\n")
      cat("Contrast values:", paste(par\$contrast_values, collapse = ", "), "\\n")
      cat("Number of samples:", nrow(metadata), "\\n")
      cat("Number of genes:", ncol(counts), "\\n")
      stop(e)
    }
  )
}

# Run analysis per cell group
run_per_cell_group_analysis <- function(counts, metadata, contrast_specs) {
  cat("Running DESeq2 analysis per cell group\\n")

  # Remove cell group from design formula
  design_no_celltype <- gsub(
    paste0("\\\\+\\\\s*", par\$obs_cell_group), "", par\$design_formula
  )
  design_no_celltype <- gsub(
    paste0(par\$obs_cell_group, "\\\\s*\\\\+"), "", design_no_celltype
  )
  design_no_celltype <- gsub("\\\\s+", " ", design_no_celltype)

  cell_groups <- unique(metadata[[par\$obs_cell_group]])

  for (cell_group in cell_groups) {
    cat("Processing cell group:", cell_group, "\\n")

    # Subset data
    cell_mask <- metadata[[par\$obs_cell_group]] == cell_group
    counts_subset <- counts[cell_mask, , drop = FALSE]
    metadata_subset <- metadata[cell_mask, , drop = FALSE]

    # Skip if insufficient samples
    if (nrow(counts_subset) < 2) {
      cat("Skipping cell group", cell_group, "- too few samples\\n")
      next
    }

    # Run analysis
    dds <- create_deseq2_dataset(
      counts_subset, metadata_subset, design_no_celltype
    )
    results <- deseq2_analysis(dds, contrast_specs)
    results[[par\$obs_cell_group]] <- cell_group

    # Save results
    safe_name <- gsub("[/ \\\\(\\\\)]", "_", as.character(cell_group))
    safe_name <- gsub("_+", "_", safe_name)
    output_file <- file.path(
      par\$output_dir,
      paste0(par\$output_prefix, "_", safe_name, ".csv")
    )
    save_results_and_log_summary(results, output_file, cell_group)
  }
}

# Run overall analysis (all samples together)
run_overall_analysis <- function(counts, metadata, contrast_specs) {
  dds <- create_deseq2_dataset(counts, metadata, par\$design_formula)
  results <- deseq2_analysis(dds, contrast_specs)

  output_file <- file.path(
    par\$output_dir,
    paste0(par\$output_prefix, ".csv")
  )
  save_results_and_log_summary(results, output_file)
}

# Run main function if script is executed directly
if (!interactive()) {
  main()
}
VIASHMAIN
Rscript "\$tempscript" &
wait "\$!"

VIASHEOF


if [[ "$VIASH_ENGINE_TYPE" == "docker" ]]; then
  # strip viash automount from file paths
  
  if [ ! -z "$VIASH_PAR_INPUT" ]; then
    VIASH_PAR_INPUT=$(ViashDockerStripAutomount "$VIASH_PAR_INPUT")
  fi
  if [ ! -z "$VIASH_PAR_OUTPUT_DIR" ]; then
    VIASH_PAR_OUTPUT_DIR=$(ViashDockerStripAutomount "$VIASH_PAR_OUTPUT_DIR")
  fi
  if [ ! -z "$VIASH_META_RESOURCES_DIR" ]; then
    VIASH_META_RESOURCES_DIR=$(ViashDockerStripAutomount "$VIASH_META_RESOURCES_DIR")
  fi
  if [ ! -z "$VIASH_META_EXECUTABLE" ]; then
    VIASH_META_EXECUTABLE=$(ViashDockerStripAutomount "$VIASH_META_EXECUTABLE")
  fi
  if [ ! -z "$VIASH_META_CONFIG" ]; then
    VIASH_META_CONFIG=$(ViashDockerStripAutomount "$VIASH_META_CONFIG")
  fi
  if [ ! -z "$VIASH_META_TEMP_DIR" ]; then
    VIASH_META_TEMP_DIR=$(ViashDockerStripAutomount "$VIASH_META_TEMP_DIR")
  fi
fi


# check whether required files exist
if [ ! -z "$VIASH_PAR_OUTPUT_DIR" ] && [ ! -e "$VIASH_PAR_OUTPUT_DIR" ]; then
  ViashError "Output file '$VIASH_PAR_OUTPUT_DIR' does not exist."
  exit 1
fi


exit 0
