major rewrite by LumenTeun