#!/usr/bin/env bash
################################################################################
# This file is part of polap.
#
# polap is free software: you can redistribute it and/or modify it under the
# terms of the GNU General Public License as published by the Free Software
# Foundation, either version 3 of the License, or (at your option) any later
# version.
#
# polap is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
# A PARTICULAR PURPOSE. See the GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with
# polap. If not, see <https://www.gnu.org/licenses/>.
################################################################################

# polap and polap-data-cflye are release-versions with _POLAP_RELEASE to be 1.
: "${_POLAP_DEBUG:=0}"
export _POLAP_DEBUG
: "${_POLAP_RELEASE:=0}"
export _POLAP_RELEASE

# Data directories: we download data from the NCBI SRA database
# unless they exist in the following folders.
_local_host="thorne"
_media_dir="/media/h2/sra"
_media1_dir="/media/h1/sra"
_media2_dir="/media/h2/sra"

# Use man folder for a release-version
# otherwise use a custom folder.
if [[ -d "man" ]]; then
  _brg_default_target_dir="man/v0.4/figures"
else
  _brg_default_target_dir="$HOME/all/manuscript/polap-v0.4/figures"
fi

help_message=$(
  cat <<HEREDOC
usage: polap-data-dflye [-h] [-y] [-c CSV] [--version] COMMAND [-h] ...

polap-data-dflye is a tool for data analysis of plant mitochondrial genome assembly using directional reads

options:
  -h, --help          Show this help message and exit.
  -y                  Enable -y flag to say YES to any question.
  -c <arg>            Set value for -c option (default: off)
  -t <arg>            Set value for -t option (default: t1)
  -m <arg>            Set value for -m option figure folder (default: ${_brg_default_target_dir})
  -e <ame>            Call <name>_genus_species function and exit.
  --version           Show the conda version number and exit.

commands:
  The following commands are available for the script.

  COMMAND
    install            Install a list of tools to some conda environments.
    setup              Setup installed tools.
    update             Update tools.
    list (search)      List tools.
    run                Run an executable in a conda environment.
    remove (uninstall) Remove a list of tools.
    build (assemble)   Build plastid or mitochondrial genomes.
    download (mkdir)   Download data.
    benchmark          Benchmark GetOrganelle, ptGAUL, PMAT, TIPPo, and Oatk.
    clean (delete, rm) Remove unnecessary folders.
    get                Get results.
    archive            Archive results.
    man                Generate reports.
    help               Print help message for commands and others.
    print-help-all     List all help messages.
HEREDOC
)

# Tesing groups of datasets
declare -a Sall

Smain=(
  'Eucalyptus_pauciflora'
)

# Data28
Stest=(
  Test_species
  Taxon_genus
)

S=(
  'Macadamia_tetraphylla'
  'Punica_granatum'
  'Lolium_perenne'
)

# OTHER STUFF GENERATED BY Argbash
_polap_script_bin_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" || {
  echo "Couldn't determine the script's running directory, which probably matters, bailing out" >&2
  exit 2
}
_POLAPLIB_DIR="${_polap_script_bin_dir}/polaplib"

# Target version is 0.4.4
source "${_POLAPLIB_DIR}/polap-git-hash-version.sh"
_polap_version=v0.5.0.1-"${_polap_git_hash_version}"
if [ -z "${_polap_version+x}" ]; then
  _polap_version="0.5.0.1"
fi

source "${_POLAPLIB_DIR}/polap-lib-conda.sh"
source "${_POLAPLIB_DIR}/polap-lib-timing.sh"
source "${_POLAPLIB_DIR}/polap-lib-unit.sh"
source "${_POLAPLIB_DIR}/polap-lib-array.sh"
source "${_POLAPLIB_DIR}/polap-lib-number.sh"
source "${_POLAPLIB_DIR}/polap-lib-data.sh"
source "${_POLAPLIB_DIR}/polap-lib-file.sh"
source "${_POLAPLIB_DIR}/polap-lib-process.sh"
source "${_POLAPLIB_DIR}/polap-lib-extract.sh"
source <(echo 'export PATH="$PWD/bin:$PATH"')
source <(echo 'export QT_QPA_PLATFORM=minimal')
# source <(echo 'export QT_QPA_PLATFORM=offscreen')
# echo "export QT_QPA_PLATFORM=offscreen"

# NOTE: globaly defined in polap-lib-data.sh
#
# _polap_data_csv="$(basename "$0" .sh).csv"
# _polap_data_data="$(basename "$0" .sh).data"
# _polap_data_txt="$(basename "$0" .sh).txt"

setup-csv_genus_species() {
  local _brg_data="${1:-${_polap_data_csv}}"
  local _brg_species_tsv="${2:-csv}"

  local _data=$(
    cat <<HEREDOC
species,long,short
Anthoceros_agrestis,SRR10190639,SRR10250248
Arabidopsis_thaliana,ERR2173373,ERR2173372
Canavalia_ensiformis,SRR18714551,SRR18714547
Cinchona_pubescens,SRR20784020,SRR20784021
Codonopsis_lanceolata,SRR11585869,SRR11585868
Cucumis_sativus_var_hardwickii,SRR28091980,SRR28091977
Dioscorea_japonica,SRR16108312,SRR16108386
Dunaliella_tertiolecta,SRR22857204,SRR22857205
Eucalyptus_pauciflora,SRR7153095,SRR7161123
Euonymus_alatus,SRR16133411,SRR16122871
Gossypium_herbaceum,SRR17224483,SRR17211914
Juncus_effusus,SRR14298760,SRR14298746
Juncus_inflexus,SRR14298751,SRR14298745
Juncus_roemerianus,SRR21976090,SRR21976092
Juncus_validus,SRR21976089,SRR21976091
Leiosporoceros_dussii,SRR25387688,SRR25387689
Macadamia_jansenii,SRR11191910,SRR11191912
Musa_acuminata_subsp_malaccensis,ERR5455028,ERR3606950
Notothylas_orbicularis,SRR25405055,SRR25405056
Ophrys_lutea,ERR5167480,ERR5303530
Oryza_rufipogon,SRR12104676,SRR12102351
Phaeomegaceros_chiloensis,SRR25430413,SRR25430414
Populus_x_sibirica,SRR15146668,SRR12963707
Prunus_mandshurica,ERR4656977,ERR4656978
Solanum_lycopersicum,SRR11073833,SRR11205474
Spirodela_polyrhiza,SRR11472010,SRR11472009
Vaccinium_vitis-idaea,SRR25468450,SRR25477290
Vitis_vinifera,SRR26163227,SRR26163231
HEREDOC
  )

  local confirm="no"
  if [[ "${_brg_species_tsv}" == "csv" ]]; then
    if [[ -s "${_brg_data}" ]]; then
      read -p "Do you want to replace ${_brg_data}? (y/N): " confirm
    fi

    if [[ "${confirm,,}" == "yes" || "${confirm,,}" == "y" ]]; then
      # Write the output to CSV
      {
        # Print the header
        echo species,taxon,long,short,host,random,down,memory,p,n,r,alpha,delta,ptgaul,pmat,tippo,oatk,ref,dummy,status

        local seed=101
        # Skip the header and read each line
        while IFS=',' read -r species long short; do
          # Skip header
          if [[ "$species" == "species" ]]; then
            continue
          fi
          echo "$species,$species,$long,$short,hostname,$seed,10,16,10,10,5,1.0,0.25,160000,0.1,ont,30,NA,dummy,done"
          seed=$((seed + 2))
        done <<<"$_data"
      } >"${_brg_data}"
      _log_echo "A new CSV: ${_brg_data}"
    else
      echo "Canceled: A new CSV: ${_brg_data}"
    fi
  elif [[ "${_brg_species_tsv}" == "tsv" ]]; then
    {
      while IFS=',' read -r species long short; do
        # Skip header
        if [[ "$species" == "species" ]]; then
          continue
        fi
        printf "%s\t%s\t%s\n" "$species" "$long" "$short"
      done <<<"$_data"
    } >"${_brg_data}"
    _log_echo "A new TSV: ${_brg_data}"
  fi
}

_log_echo() {
  if [[ -s "${_brg_outdir}/polap-data-v2.txt" ]]; then
    echo "$(date '+%Y-%m-%d %H:%M:%S') [$subcmd1] - $1" >>"${_brg_outdir}/polap-data-v2.txt"
  fi
}

################################################################################
# main command arguments used before a subcommand
#
# Default values for options
opt_c_arg="off"
opt_t_arg="t1"
opt_m_arg="off"
opt_y_flag=false
opt_e_arg=""

print_help() {
  echo "${help_message}"
}

print_version() {
  echo "polap-data-dflye ${_polap_version}"
}

# Parse options
while [[ "${1-}" == -* ]]; do
  case "$1" in
  -c)
    shift
    if [[ -z "${1-}" || "${1-}" == -* ]]; then
      echo "Error: -c requires an argument"
      exit 1
    fi
    opt_c_arg="$1"
    ;;
  -t)
    shift
    if [[ -z "${1-}" || "${1-}" == -* ]]; then
      echo "Error: -t requires an argument"
      exit 1
    fi
    opt_t_arg="$1"
    ;;
  -m)
    shift
    if [[ -z "${1-}" || "${1-}" == -* ]]; then
      echo "Error: -t requires an argument"
      exit 1
    fi
    opt_m_arg="$1"
    ;;
  -y)
    opt_y_flag=true
    ;;
  -e)
    shift
    if [[ -z "${1-}" || "${1-}" == -* ]]; then
      echo "Error: -e requires an argument"
      exit 1
    fi
    opt_e_arg="$1"
    func_name="${opt_e_arg}_genus_species"
    if declare -f "$func_name" >/dev/null; then
      "$func_name"
      exit 0
    else
      echo "Error: function '$func_name' not found"
      exit 1
    fi
    ;;
  --version)
    print_version
    exit 0
    ;;
  -h | --help)
    print_help
    exit 0
    ;;
  --) # End of options
    shift
    break
    ;;
  -*)
    echo "Unknown option: $1"
    exit 1
    ;;
  esac
  shift || break
done

if [[ "${opt_m_arg}" != "off" ]]; then
  _brg_default_target_dir="${opt_m_arg}"
fi

if [[ "${opt_c_arg}" != "off" ]]; then
  csv_file="${opt_c_arg}"
fi

# Input parameter
subcmd1="${1:-help}"

if [[ "${subcmd1}" == "search" ]]; then
  subcmd1="list"
fi

# TODO: depending on _POLAP_RELEASE, we could use polap
# but then polap needs to be the current conda env, which is not.
_polap_cmd="${_polap_script_bin_dir}/polap.sh"
if [[ "${_POLAP_RELEASE}" == "1" ]]; then
  _polap_cmd="${_polap_script_bin_dir}/polap"
else
  _polap_cmd="${_polap_script_bin_dir}/polap.sh"
fi

################################################################################
# BEGIN: Help messages
help_message_old=$(
  cat <<HEREDOC
Polap version: ${_polap_version}
Usage: $0 [-c file.csv] [-y] <subcommand> [species_folder] [[option] ...]

Polap data analysis of directional mitochondrial genome assembly

List of subcommands:
  install-conda, setup-conda, install-polap, install-fmlrc, install-cflye
  install-getorganelle, install-pmat, install-man
  download-polap-github, patch-polap, bleeding-edge-polap
  delete-polap-github, uninstall, test-polap, download-test-data, help, system
  mkdir-all, rm-empty, rm, example-data, convert-data, sample-csv
  sra, refs, getorganelle, ptgaul, msbwt,
  local-batch, remote-batch, batch, archive, clean, report, get
  seeds, map, reads, dflye, directional, archive, report,
  maintable1, supptable1, suppfigure1, suppfigure3, suppfigure4
  download-man, make-man

How to set a custom CSV:
csv_file=a.csv $0

More help for subcommands:
$(basename $0) help <subcommand>
HEREDOC
)

help_message_seeds=$(
  cat <<HEREDOC

  Test the code.
HEREDOC
)

help_message_map=$(
  cat <<HEREDOC

  Test the code.
HEREDOC
)

help_message_reads=$(
  cat <<HEREDOC

  Test the code.
HEREDOC
)

help_message_dflye=$(
  cat <<HEREDOC

  Test the code.
HEREDOC
)

help_message_directional=$(
  cat <<HEREDOC

  Test the code.
HEREDOC
)
##### INSERT_HELP_HERE #####
help_message_main=$(
  cat <<HEREDOC

  main menu title
HEREDOC
)

#
# END: Help messages
################################################################################

############################################################
# CSV setting for each analysis
#
declare -A _taxon
declare -A _long
declare -A _short
declare -A _host
declare -A _ssh
declare -A _min_read
declare -A _range
declare -A _inref
declare -A _random_seed
declare -A _dummy
declare -A _status
declare -A _dummy
declare -A _status

set +u

# Read the config files
read-a-tsv-file-into-associative-arrays() {
  # Define input TSV file
  if [ -z "${csv_file+x}" ]; then
    csv_file="${PWD}/${_polap_data_csv}"
  fi
  if [[ ! -s "${csv_file}" ]]; then
    csv_file="${_POLAPLIB_DIR}/${_polap_data_csv}"
  fi

  # Read the TSV file (skip header)
  #
  while IFS=$',' read -r species long short host inref min_read range random_seed; do
    # Skip header line
    [[ "$species" == "species" ]] && continue
    [[ "$species" == \#* ]] && continue

    # Store in associative arrays
    if [[ -z "${species:-}" ]]; then
      continue
    fi
    # _taxon["$species"]="$taxon"
    _long["$species"]="$long"
    _short["$species"]="$short"
    _host["$species"]="$host"
    _inref["$species"]="$inref"
    _min_read["$species"]="$min_read"
    _range["$species"]="$range"
    _random_seed["$species"]="$random_seed"
    # _dummy["$species"]="$dummy"
    # _status["$species"]="$status"
  done <"$csv_file"

  # Create Sall with all species folder names
  mapfile -t Sall < <(
    for key in "${!_long[@]}"; do
      echo "${key%%-*}"
    done | sort -u
  )
}

read-a-tsv-file-into-associative-arrays

# Create all keys
keys_array=($(for key in "${!_long[@]}"; do echo "$key"; done | sort))
Skeys=("${keys_array[@]}")

# Command arguments
_arg1=${1:-arg1}
# Check if the species folder is provided
if [[ "${_arg1}" == "arg1" ]]; then
  echo "${help_message}"
  exit 1
fi

_arg2=${2:-arg2}
if [[ "${_arg2}" != "arg2" ]]; then
  _arg2="${2%/}"
fi

_arg3=${3:-arg3}
_arg4=${4:-arg4}
_arg5=${5:-arg5}
_arg6=${6:-arg6}
_arg7=${7:-arg7}
_arg8=${8:-arg8}
_arg9=${9:-arg9}
_arg10=${10:-arg10}

# _polap_subcmd=(
#   'test'
#   'seeds'
#   'map'
#   'reads'
#   'dflye'
#   'directional'
#   'archive'
#   'report'
#   'table1'
#   'figure1'
# )

################################################################################
# Part of genus_species
#
test_genus_species_for() {
  local _brg_outdir="${1}"
  local _brg_inum="${2:-0}"
  local key="${_brg_outdir}-${_brg_inum}"

  local long_sra="${_long["$key"]}"
  local short_sra="${_short["$key"]}"

  echo "Key: $key"
  if [[ "${_POLAP_RELEASE}" == "1" ]]; then
    echo "  long_sra: ${long_sra}"
    echo "  short_sra: ${short_sra}"
  fi
}

test_genus_species() {
  local _brg_outdir="${1:-all}"
  local _brg_inum="${2:-0}"

  if [[ "${_brg_outdir}" == "all" ]]; then
    for _v1 in "${Sall[@]}"; do
      test_genus_species_for "${_v1}" "${_brg_inum}"
    done
  elif [[ "${_brg_outdir}" == "each" ]]; then
    for key in "${Skeys[@]}"; do
      _brg_outdir="${key%-*}"
      _brg_inum="${key##*-}"
      test_genus_species_for "${_brg_outdir}" "${_brg_inum}"
    done
  else
    test_genus_species_for "$@"
  fi
}

##### INSERT_FUNCTION_HERE #####
main_genus_species() {
  local _brg_outdir="${1:-all}"
  local _brg_inum="${2:-0}"

  if [[ "${_brg_outdir}" == "all" ]]; then
    for _v1 in "${Sall[@]}"; do
      echo main_genus_species_for "${_v1}" "${@:2}"
    done
  elif [[ "${_brg_outdir}" == "each" ]]; then
    for _v1 in "${Sall[@]}"; do
      echo main_genus_species_for "${_v1}" "${@:2}"
    done
  else
    echo main_genus_species_for "$@"
  fi
}

# whole-genome assembly
# assemble1
# mt.contig.name-1

# Step 1
# Create directional seed contigs:
# mt.contig.name has one contiguous sequence per line using direction as well
#
# /home/goshng/all/polap/dflye/Lolium_perenne/o/1/mt.contig.name-2
# edge_5-,edge_11+,edge_12+,edge_8+,edge_4+,edge_8-,edge_6-,edge_11-,edge_10+,edge_9-
# -> each line becomes contig_<number>
#
# /home/goshng/all/polap/dflye1/Lolium_perenne/o/2
# └── 01-contig
#     ├── contig1.fa
#     ├── contig1.name.txt
#     ├── contig2.fa
#     └── contig2.name.txt
#
# contig1.name.txt
# ----------------
# contig_1
#
# contig2.name.txt: edges with only one direction; edge_11 has +/- so it is excluded
# ----------------
# edge_9-
# edge_6-
# edge_5-
# edge_4+
# edge_12+
# edge_10+
#
seed_genus_species() {
  local _brg_outdir="${1:-all}"
  local _brg_inum="${2:-0}"

  # mt.contig.name-1 with plus/minus signed edge_<number>[+-]
  ${_polap_cmd} directional-prepare-seeds \
    -o ${_brg_outdir}/o \
    -i 1 -j 2
}

# Step 2
# Map the long-read data on the seed contigs
#
# input:
# o/lk.fq.gz
# o/nk.fq.gz
# seed contigs
#
# output:
# /home/goshng/all/polap/dflye1/Lolium_perenne/o/2
# └── 01-contig
#     ├── contig1.paf
#     ├── contig1.tab
#     ├── contig1_total_length.txt
#     ├── contig2.paf
#     └── contig2.tab
#
map_genus_species() {
  local _brg_outdir="${1:-all}"
  local _brg_inum="${2:-0}"

  # o/lk.fq.gz
  # o/nk.fq.gz
  ${_polap_cmd} directional-map-reads \
    -o ${_brg_outdir}/o \
    -i 1 -j 2
}

# Step 3
# Select reads mapped on the reference and subsample
# -s option for filtering long-read data? not sure.
#
# /home/goshng/all/polap/dflye1/Lolium_perenne/o/2
# └── 01-contig
#     ├── contig1_total_length.txt
#     ├── ptgaul.txt
# ├── 02-reads
# │   └── ptgaul
# │       ├── 0
# │       │   ├── ptgaul.contig1.forward.names.txt
# │       │   └── ptgaul.contig.forward.names.txt
# │       ├── 1
# │       │   ├── ptgaul.contig1.forward.names.txt
# │       │   └── ptgaul.contig.forward.names.txt
# │       └── 2
# │           ├── ptgaul.contig1.forward.names.txt
# │           └── ptgaul.contig.forward.names.txt
# ├── 03-seeds
# │   └── ptgaul
# │       ├── 0.fq.gz
# │       ├── 1.fq.gz
# │       └── 2.fq.gz
# ├── 04-subsample
# │   └── ptgaul
# │       ├── 0.fq.gz
# │       ├── 1.fq.gz
# │       └── 2.fq.gz
#
#
# contig1_total_length.txt <- length of sequences in 01-contig/contig1.fa
# ptgaul.txt <- values to use for read selection
# 02-reads
# 03-seeds
# 04-subsample
# 05-flye
# 06-summary
# 07-plot
#
# STOPPED HERE
select_genus_species() {
  local _brg_outdir="${1:-all}"
  local _brg_inum="${2:-0}"

  # -s 3000,6000,2
  # -s 3000,27000,9
  # -s 30000,42000,5
  ${_polap_cmd} directional-select-reads \
    -o ${_brg_outdir}/o \
    -i 1 -j 2 \
    -s 33000,45000,5
}

# Assembly using dflye
#
# The following produces a circular graph of size 677 kb.
# /home/goshng/all/polap/dflye1/Lolium_perenne/o/2/05-flye/ptgaul/2/30-contigger/graph_final.gfa
# -s 39k produces a circular graph.
#
# Two stages:
# 1. we need to assemble using flye without directional reads but across a range of reads.
# 2. we pick a seed and then using a similar size selection to build.
# Or, we had a candidate with 39k of -w option.
# The directional assembly was also done using 39k.
#
flye_genus_species() {
  local _brg_outdir="${1:-all}"
  local _brg_inum="${2:-0}"

  # -s 3000,6000,2
  # -s 3000,27000,9
  # -s 30000,42000,5
  ${_polap_cmd} directional-flye-reads \
    -o ${_brg_outdir}/o \
    -i 1 -j 2
}

# assemble the directinoal reads using dflye
dflye_genus_species() {
  local _brg_outdir="${1:-all}"
  local _brg_inum="${2:-0}"

  # mt_fastq=/home/goshng/all/polap/dflye1/Lolium_perenne/o/2/03-seeds/ptgaul/2.fq.gz
  # bin/dflye \
  #   --nano-raw ${mt_fastq} \
  #   --debug \
  #   --stop-after contigger \
  #   --asm-coverage 30 \
  #   --directional-reads \
  #   -g 800000 -o $out_dir -t 56 -m 10000

  # run-polap-function-dga -> _run_polap_dflye
  ${_polap_cmd} dflye \
    -o ${_brg_outdir}/o \
    -i 1 -j 2
}

# the first step is a typical polap-assemble1 and assemble2 with seed contig selection.
# now, we use the organelle genome assembly as a seed to apply this directional method.
#
# this is later step.
#
directional_genus_species() {
  local _brg_outdir="${1:-all}"
  local _brg_inum="${2:-0}"
  local target_index="${_brg_outdir}-${_brg_inum}"

  # IFS=':' read -r -a extracted_array_n <<<"${_range["$target_index"]}"

  local extracted_range="${_range["$target_index"]//:/,}"
  local extracted_min_read="${_min_read["$target_index"]}"

  ${_polap_cmd} directional \
    -v -v \
    --select-read-range "${extracted_range}" \
    -o ${_brg_outdir}/o \
    --directional-i 1 \
    --min-read-length "${extracted_min_read}" \
    -i 1 -j 3
}

################################################################################
# main cases
#
# if [[ "${subcmd1}" == "help" ]]; then
#   if [[ "${_arg2}" == "arg2" ]]; then
#     subcmd1="help"
#   else
#     subcmd1="${_arg2}"
#     _arg2="arg2"
#   fi
# fi

if [[ "$_POLAP_DEBUG" == "1" ]]; then
  echo "option -y: ${opt_y_flag}"
  echo "option -c: ${opt_c_arg}"
  echo "option -t: ${opt_t_arg}"
  for item in "$@"; do
    echo "A: $item"
  done
fi

all_args=("$@")               # Save all arguments to an array
cmd_args=("${all_args[@]:1}") # Slice from index 1 onward

# Call common case first
common_handled=1
# _polap_lib_data-execute-common-subcommand "$subcmd1" "${_arg2}" "${_arg3}" "$opt_y_flag"
_polap_lib_data-execute-common-subcommand "$subcmd1" "$opt_y_flag" cmd_args
common_handled=$?

# Main case statement
case "$subcmd1" in
##### INSERT_CASE_HERE #####
main)
  if [[ -z "${_arg2}" || "${_arg2}" == arg2 || "${_arg2}" == "-h" || "${_arg2}" == "--help" ]]; then
    echo "Help: ${subcmd1} <outdir> [inum:0|N]"
    echo "  $(basename ${0}) ${subcmd1} Arabidopsis_thaliana"
    _subcmd1_clean="${subcmd1//-/_}"
    declare -n ref="help_message_${_subcmd1_clean}"
    echo "$ref"
    exit 0
  fi
  ${subcmd1}_genus_species "${cmd_args[@]}"
  ;;
example-data)
  if [[ "${_arg2}" == arg2 ]]; then
    echo "Help: ${subcmd1} <data:${_polap_data_data}>"
    echo "  $(basename $0) ${subcmd1} 1.data"
    exit 0
  fi
  _polap_lib_data-${subcmd1} "${_arg2}"
  ;;
seed)
  if [[ "${_arg2}" == arg2 ]]; then
    echo "Help: ${subcmd1} <outdir|all> <inum:N>"
    echo "  $(basename $0) ${subcmd1} all"
    _subcmd1_clean="${subcmd1//-/_}"
    declare -n ref="help_message_${_subcmd1_clean}"
    echo "$ref"
    exit 0
  fi
  [[ "${_arg3}" == arg3 ]] && _arg3=""
  ${subcmd1}_genus_species "${_arg2}" "${_arg3}"
  ;;
map)
  if [[ "${_arg2}" == arg2 ]]; then
    echo "Help: ${subcmd1} <outdir|all> <inum:N>"
    echo "  $(basename $0) ${subcmd1} all"
    _subcmd1_clean="${subcmd1//-/_}"
    declare -n ref="help_message_${_subcmd1_clean}"
    echo "$ref"
    exit 0
  fi
  [[ "${_arg3}" == arg3 ]] && _arg3=""
  ${subcmd1}_genus_species "${_arg2}" "${_arg3}"
  ;;
select)
  if [[ "${_arg2}" == arg2 ]]; then
    echo "Help: ${subcmd1} <outdir|all> <inum:N>"
    echo "  $(basename $0) ${subcmd1} all"
    _subcmd1_clean="${subcmd1//-/_}"
    declare -n ref="help_message_${_subcmd1_clean}"
    echo "$ref"
    exit 0
  fi
  [[ "${_arg3}" == arg3 ]] && _arg3=""
  ${subcmd1}_genus_species "${_arg2}" "${_arg3}"
  ;;
flye)
  if [[ "${_arg2}" == arg2 ]]; then
    echo "Help: ${subcmd1} <outdir|all> <inum:N>"
    echo "  $(basename $0) ${subcmd1} all"
    _subcmd1_clean="${subcmd1//-/_}"
    declare -n ref="help_message_${_subcmd1_clean}"
    echo "$ref"
    exit 0
  fi
  [[ "${_arg3}" == arg3 ]] && _arg3=""
  ${subcmd1}_genus_species "${_arg2}" "${_arg3}"
  ;;
dflye)
  if [[ "${_arg2}" == arg2 ]]; then
    echo "Help: ${subcmd1} <outdir|all> <inum:N>"
    echo "  $(basename $0) ${subcmd1} all"
    _subcmd1_clean="${subcmd1//-/_}"
    declare -n ref="help_message_${_subcmd1_clean}"
    echo "$ref"
    exit 0
  fi
  [[ "${_arg3}" == arg3 ]] && _arg3=""
  ${subcmd1}_genus_species "${_arg2}" "${_arg3}"
  ;;
directional)
  if [[ "${_arg2}" == arg2 ]]; then
    echo "Help: ${subcmd1} <outdir|all> <inum:N>"
    echo "  $(basename $0) ${subcmd1} all"
    _subcmd1_clean="${subcmd1//-/_}"
    declare -n ref="help_message_${_subcmd1_clean}"
    echo "$ref"
    exit 0
  fi
  [[ "${_arg3}" == arg3 ]] && _arg3=""
  ${subcmd1}_genus_species "${_arg2}" "${_arg3}"
  ;;
"menu")
  _run_polap_menu
  ;;
"delete-links")
  find . -type l -delete
  ;;
*)
  # only print usage if common_case didn't handle it
  if [[ $common_handled -ne 0 ]]; then
    echo "Usage: $0 <subcommand> [species_folder]"
    echo "${help_message}"
    echo "subcommand '$subcmd1' is not recognized."
    exit 1
  fi
  ;;
esac
