bag2mat refactored