fix bugs and better handling of n