move global variable M,N into generate function