Fix prefix and context counting code + tests