create function nextpower2(a bigint) returns bigint as
$$
declare n
bigint := 1;
begin
	while n < a
	loop
		n := n * 2;
	end loop;
	return n;
end;
$$ language plpgsql;



create or replace function show_parallel_scan_chunks(relsize bigint, nchunks int, rampdown_chunks int) returns int as
$$
declare chunksize bigint;
declare allocated bigint;
declare chunk_num bigint;
begin
	chunksize := nextpower2(relsize / nchunks);
	allocated := 0;
	chunk_num := 0;
	while (allocated <= relsize)
	loop
		if (chunksize > 1 AND allocated > relsize - chunksize * rampdown_chunks)
		then
			chunksize := chunksize / 2;
		end if;

		raise notice 'chunk_num = %, chunksize = %, allocated = %', chunk_num, chunksize, allocated;

		allocated := allocated + chunksize;
		chunk_num := chunk_num + 1;
	end loop;

	return 1;
end;
$$ language plpgsql;
