fixed up Gary's suggestion properly, with correct numbering and limits stuff, but need to modify so that this code is memory efficient at large N
(#563)