I'm a little fuzzy on js scoping, but we are redefining lots of variables here (loop counts i, j, stack_id, etc). May be worthwhile just using fresh names to avoid confusion.