cleaned up the ported matlab code