#!/bin/bash

if [ $# -ne 1 ]; then
    echo >&2 "silentscorefile by bcov - a tool to extract a scorefile from a silentfile"
    echo >&2 "Usage:"
    echo >&2 "        silentscorefile myfile.silent"
    echo >&2 ""
    echo >&2 "Note: This utility ensures that all score lines contain the same elements in"
    echo >&2 "       the same order. If this is not the case, multiple scorefiles are produced"
    exit 1
fi

if [[ ! -f $1 ]]; then
    echo >&2 "silentscorefile: File not found: $1"
    exit 1
fi

silent_dir="$(dirname $(type -p "$0"))"

"$silent_dir"/silentassertuniquetags $1

silentname=$(basename $1 .silent)
scorename=${silentname}.sc

# tmp_file=$(head /dev/urandom | tr -dc A-Za-z0-9 | head -c 13)
# tmp_file="tmp_${tmp_file}.tmp"

types=$(grep -a description $1 | tr -d "[:blank:]" | sort | uniq)
num_types=$(echo "$types" | wc -l)

if [[ $num_types -eq 1 ]]; then
    head -n 2 $1 | grep -a description > $scorename    # just in case there's no sequence line
    grep -a '^SCORE:' $1 | grep -a -v description >> $scorename
    exit 0
fi

# Don't change this wording unless you change silentinjectscores
echo >&2 "Warning!! Multiple scorefiles produced!!"
for tp in $(echo $types); do echo >&2 $tp; done

scorefiles=()
has_header=()
for i in $(seq 1 ${num_types}); do
    scorefiles+=(${silentname}${i}.sc)
    has_header+=('0')
done


current_file=-1
IFS=$'\n' 
for line in $(grep -a '^SCORE:' $1); do
    if $(echo "$line" | grep -a -q description); then
        # echo >&2 "$line"
        current_file=$(echo "$types" | grep -a --line-number $(echo $line | tr -d "[:blank:]" ) | cut -d ':' -f1)
        if [[ -z $current_file ]]; then
            echo >&2 "Uh oh"
            exit 1
        fi
        current_file=$((current_file-1))
        if [[ ${has_header[current_file]} -eq 0 ]]; then
            echo "$line" > ${scorefiles[current_file]}
            has_header[$current_file]='1'
        fi
    else
        # echo >&2 "$current_file"
        # echo >&2 "$line"
        # echo >&2 "${scorefiles[current_file]}"
        echo "$line" >> ${scorefiles[current_file]}
    fi

done


unset IFS
