Reference counting implemented

Added reference counting to the matrix struct to support caching and sharing matrices. The touched a lot of the code base -- all in good ways I think.