Clean-up Matrix Generation Code

Overall clean up of the matrix code. No functionality changes.