Rewritten the logic, in the hope of making it work better with large files