Start of the big refactor, using linear indexing to speed things up.