Pretty sure that this line should be using $next_pid... Any reason not to use a foreach loop?