#!/usr/bin/env bash
# do a pseudo-random subselection of sequences in a file
# relabel them using a given species tag

[[ $# -eq 3 ]] || { echo "usage: $0 <tag> <file> <nsel>"; exit 255; }

spectag=$1
filename=$2
nsel=$3

[[ -f $filename ]] || { echo "error: missing or unreadable file $filename"; exit 255; }

fseqs=$(mktemp /tmp/raw_XXXXXX)
# remove all lines with labels and comments (starting with #)
# select the requested nr of sequences
# random sort
grep -v -e '^>' -e '^#' $filename | head -n $nsel | sort -R > $fseqs

numid=0
line=""
while read line; do
    echo ">${spectag}:$numid"
    echo $line
    numid=$((numid+1))
done < $fseqs

rm -f $fseqs
