#!/usr/bin/env python3
# Compiles font with FontForge.

import sys
import fontforge
import htic


# Read arguments
SOURCE       = sys.argv[1] # *.sfd
COMMON       = sys.argv[2] # *.sfd
FEATURES     = sys.argv[3] # *.fea
INSTRUCTIONS = sys.argv[4] # *.hti
VERSION      = sys.argv[5] # [0-9].[0-9]
TARGET       = sys.argv[6] # *.otf|*.ttf


# Prepare font
font = fontforge.open(SOURCE)
font.mergeFonts(COMMON)
font.mergeFeature(FEATURES)
font.version = VERSION
font.appendSFNTName("English (US)", "UniqueID",
	f"{font.familyname};{font.weight};{font.version}")


# Generate font
if TARGET.endswith("otf"):

	# Unlink composite glyphs
	for glyph in font.glyphs():
		if glyph.references:
			glyph.manualHints = True
			glyph.unlinkRef()
			glyph.removeOverlap()
			glyph.round()
			glyph.simplify()
			glyph.correctDirection()
			glyph.canonicalStart()
			glyph.canonicalContours()

	# Remove glyphs that are only required for TrueType
	font['.null'].clear()
	font['nonmarkingreturn'].clear()
	for glyph in font.glyphs():
		if glyph.glyphname.endswith(".tt"):
			glyph.clear()

	# Generate
	font.generate(TARGET, flags=("opentype", "old-kern", "dummy-dsig"))

elif TARGET.endswith("ttf"):

	# Convert to quadratic outlines
	font.layers['Fore'].is_quadratic = True

	for glyph in font.glyphs():
		# If available, use custom quadratic
		# outlines from background layer
		if not glyph.background.isEmpty():
			glyph.foreground = glyph.background

		# Remove .tt mark from TrueType exclusive glyphs
		if glyph.glyphname.endswith(".tt"):
			glyph.glyphname = glyph.glyphname[:-3]

	# Add instructions
	htic.toFontforge(INSTRUCTIONS, font)

	# Generate
	font.generate(TARGET, flags=("opentype", "old-kern", "dummy-dsig"))

font.close()
