#!/usr/bin/env python3
# Cleans up font produced by FontForge.

import sys
from fontTools.ttLib import TTFont
from fontTools.feaLib import builder as feaBuilder


# Read arguments
SOURCE   = sys.argv[1] # *.otf|*.ttf
FEATURES = sys.argv[2] # *.fea
TARGET   = sys.argv[3] # *.otf|*.ttf


# Load font
font = TTFont(SOURCE)
tmpFont = TTFont(SOURCE)


# Remove FontForge FFTM table
if 'FFTM' in font: del font['FFTM']


# Compile the GSUB table with FontTools,
# but retain the GPOS table from FontForge
if 'GPOS' in tmpFont: del tmpFont['GPOS']
if 'GSUB' in tmpFont: del tmpFont['GSUB']

feaBuilder.addOpenTypeFeatures(tmpFont, FEATURES)
font['GSUB'] = tmpFont['GSUB']


# Remove characters with a period in their name
# from the kern table, because they do not have a
# unicode mapping, which can cause problems on Windows
if 'kern' in font:
	for kernTable in font['kern'].kernTables:
		kernSubTable = kernTable.kernTable
		pairsToRemove = []

		# Search for problematic characters
		for pair in kernSubTable:
			if "." in pair[0] or "." in pair[1]:
				pairsToRemove.append(pair)

		# Remove problematic characters
		for pair in pairsToRemove:
			kernSubTable.pop(pair)


# Calculate correct OS/2.xAvgCharWidth
widths = [m[0] for m in font['hmtx'].metrics.values() if m[0] > 0]
font['OS/2'].xAvgCharWidth = int(round(sum(widths) / len(widths)))


# Save font
font.save(TARGET)
