ported code partly to armadillo