reorganzing- dividing into matrix operation and general purpose code