/* ----------------------------------------------------------------------- *
 *
 *   Copyright 2008 rPath, Inc. - All Rights Reserved
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
 *   Boston MA 02110-1301, USA; either version 2 of the License, or
 *   (at your option) any later version; incorporated herein by reference.
 *
 * ----------------------------------------------------------------------- */

/*
 * segment.c
 *
 * Sort segments according to base address
 * Eventually add support here for merging segments
 */

#include "wraplinux.h"

#include <stdlib.h>
#include <alloca.h>
#include "segment.h"

static int comp_seg(const void *a, const void *b)
{
	const struct segment * const *ap = a;
	const struct segment * const *bp = b;

	if ((*ap)->address < (*bp)->address)
		return -1;
	else if ((*ap)->address > (*bp)->address)
		return 1;
	else
		return 0;
}

struct segment *sort_segments(struct segment *list)
{
	struct segment **ptrs;
	int nsegments, i;
	struct segment *sp, **spp;

	nsegments = 0;
	for (sp = list; sp; sp = sp->next)
		nsegments++;

	ptrs = alloca(nsegments * sizeof *ptrs);
	spp = ptrs;
	for (sp = list; sp; sp = sp->next)
		*spp++ = sp;

	qsort(ptrs, nsegments, sizeof *ptrs, comp_seg);

	for (i = 0; i < nsegments-1; i++)
		ptrs[i]->next = ptrs[i+1];
	ptrs[i]->next = NULL;

	return ptrs[0];
}
