#!/bin/bash
# Merge a filename-sc.codepoints into filename.codepoints.
# Every codepoint in the smallcaps file must exist in the main file
# because smallcaps are a variation, but my extract might contain
# rubbish from unexpected items.
#
function help() {
	echo "Merge filename-sc.codepoints into filename.codepoints."
	echo "Pass only 'filename' without an extension."
	echo "'filename.codepoints' and 'filename-sc.codepoints' must exist in current directory."
	exit 2
}

if [ $# -ne 1 ]; then
	help
fi

test -r ${1}.codepoints || help;
test -r ${1}-sc.codepoints || help;

grep -q ' +sc' ${1}.codepoints
if [ $? -eq 0 ]; then
	echo "${1}.codepoints already includes small cap markers"
	exit 2
fi

> /tmp/${1}.codepoints

while read line
  do
	ITEM=$(echo $line | awk '{ print $1 }')
	# noisy, if I want to be sure it is doing something
	#echo "grep for $ITEM"
	grep -q "$ITEM" $1-sc.codepoints
	if [ $? -eq 0 ]; then
		echo "$line" " +sc" >>/tmp/$1.codepoints
	else
		echo "$line" >>/tmp/$1.codepoints
	fi
   done < $1.codepoints

mv -v $1.codepoints{,.orig}
mv -v /tmp/$1.codepoints .

# Does the number of added codepoints match ?
FOUND=$(wc -l $1-sc.codepoints | awk '{ print $1 }')
ADDED=$(grep ' +sc'  $1.codepoints | wc -l | awk '{ print $1 }')
if [ "$ADDED" = "$FOUND" ]; then
	echo "$ADDED small cap markers were added to $1.codepoints"
elif [ "$1" = "EBGaramond" ] && [ "$ADDED" = "1193" ] && [ "$FOUND" = "1197" ]; then
	# EBGaramondSC08-Regular adds 4 combining glyphs that are not in
	# EBGaramond08-REgular.otf, U+030D, U+030E, U+0310, U+0345
	echo "$ADDED small cap markers were added to $1.codepoints"
	echo "this SC08 font contains 4 items not in the main font"
else
	echo "ERROR"
	# 'supposedly' because rubbish probably got in
	echo "$FOUND small caps were supposedly found, but ony $ADDED were processed"
	echo "Please review $1-sc.codepoints"
fi


