#! /bin/bash
#
# $1 - path to Stats folder
# $2 - command to execute on first matching file
# $3 - input file name template, with "?" replacing the lane number
# $4 - command to execute on other matching files, default=$2
# $5 - comma separated lanes to operate on, default = all in path
#
set -e

path=$1;
comm1=$2;
template=$3;
comm=${4:-$comm1};
# parse lanes
if [[ -z $5 ]]; then
  readarray -t lanes < <(cat $path/AdapterTrimming.txt | cut -f 1 | sed '/^$/q' | head -n -1 | sed '1d' | sort -n | uniq)
else
  IFS="," read -ra lanes <<< "$2"
fi

# execute
for ((i=0; i<${#lanes[@]}; i++ )); do
    lane=${lanes[i]}
    fn="${template/\?/$lane}";
    cmd=$([ "$i" == 0 ] && echo "$comm1" || echo "$comm")
    eval "cat $path/$fn | $cmd"
done
