#!/bin/bash
#
# Create a list of subject IDs from numbers.

if [ $# -lt 1 ]; then
    cat <<EOF
subjids - Create a list of subject IDs from numbers.

Usage: subjids [-s separator] N1 [N2, ...]

If SUBJIDFORMAT is defined, this will be used with printf
to create each subject ID. If it is not defined, but STUDY
is, then the format will be mistr_%02d.

The default separator between IDs is ":".

Example:
export SUBJIDFORMAT=No_%03d
subjids -s " " 3 4 5 # returns "No_003 No_004 No_005"

EOF
    exit 1
fi

if [[ ! $SUBJIDFORMAT ]]; then
    if [[ ! $STUDY ]]; then
        echo "STUDY and SUBJIDFORMAT are unset; quitting."
        exit 1
    fi

    # default format: $STUDY_XX
    SUBJIDFORMAT="${STUDY}_%02d"
fi

sep=":"
while getopts ":s:" opt; do
    case $opt in
        s)
            sep="$OPTARG"
            ;;
        *)
            echo "Invalid option: $opt"
            exit 1
            ;;
    esac
done
shift $((OPTIND-1))

nos="${*}"
subjids=""
for no in ${nos//:/ }; do
    # shellcheck disable=SC2059
    subject=$(printf "$SUBJIDFORMAT" $no)
    if [ -z "$subjids" ]; then
        subjids="$subject"
    else
        subjids="${subjids}${sep}${subject}"
    fi
done
echo "$subjids"
