cleans up code and fixes bug for M!=N