#!/bin/bash
[[ -s "$1" ]] || { printf "Need a file.\n">&2 && exit 1; }
source "$(dirname $0)"/notevars.shh
IFS=$'\n'
function sampnote_gen() {
  sample_template="$(echo -n "$1" | cut -d\! -f3)"
  sample_glob="$(echo -n "$1" | cut -d\! -f2 | cut -d\| -f1)"
  sample_extract="$(echo -n "$1" | cut -d\! -f2 | cut -d\| -f2)"
  note_name=( $(find -name "$sample_glob" | sed -e "$sample_extract" | sort -k 1.2 -g | uniq | tr '-' 'n' | tr '#' 's') )
  note=( $(for f in "${note_name[@]}";do echo "${!f}";done | sort -n) )
  layers=( $(for n in "${note[@]}";do find -name "$sample_glob" | grep "${num_to_note[n]}" | wc -l;done) )
  for (( i=0; i<${#note[*]}; i++ ));do
    hikey[i]=$(( i>=${#note[*]}-1?${note[i]}:(note[i]+7<note[i+1] ? note[i]+7 : note[i+1]-1) ))
    lokey[i]=$(( i==0?0:hikey[i-1]+1 ))
    layer_file=( $(find -name "$sample_glob" | grep "${num_to_note[note[i]]}" | cut -d/ -f2-) )
    for (( l=0; l<${layers[i]}; l++ ));do
      hivel[l]=$(( l==${layers[i]}-1?127:(127/${layers[i]})*(l+1) ))
      lovel[l]=$(( l==0?0:hivel[l-1]+1 ))
      printf "$sample_template\n" | sed \
      -e "s#_SAMPLE_#${layer_file[l]}#g" \
      -e "s/_KEY_/${note[i]}/g" \
      -e "s/_LOKEY_/${lokey[i]}/g" \
      -e "s/_HIKEY_/${hikey[i]}/g" \
      -e "s/_LOVEL_/${lovel[l]}/g" \
      -e "s/_HIVEL_/${hivel[l]}/g"
    done
  done
}

function sample_gen() {
  sample_glob="$(printf "$1" | cut -d@ -f2)"
  sample_template="$(printf "$1" | cut -d@ -f3)"
  layers=$(find -name "$sample_glob" | wc -l)
  layer_file=( $(find -name "$sample_glob" | cut -d/ -f2-) )
  for (( l=0; l<$layers; l++ ));do
    hivel[l]=$(( l==layers-1?127:(127/layers)*(l+1) ))
    lovel[l]=$(( l==0?0:hivel[l-1]+1 ))
    printf "$sample_template\n" | sed \
    -e "s#_SAMPLE_#${layer_file[l]}#g" \
    -e "s/_LOVEL_/${lovel[l]}/g" \
    -e "s/_HIVEL_/${hivel[l]}/g"
  done
}

function allnote_gen() {
  for (( n=0; n<128; n++));do
    printf "$1\n" | sed -e "s/_KEY_/$n/g"
  done
}

for line in $(cat "$1" | grep -v '^////');do
  case "${line:0:1}" in
    '!') sampnote_gen "$line" ;;
    '%') allnote_gen "$line" ;;
    '@') sample_gen "$line" ;;
    *) printf "$line\n" ;;
  esac
done
