/*****************************************************************************

	unsort - reorder files semi-randomly
	Copyright (C) 2008  Wessel Dankers <wsl@fruit.je>

	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, either version 3 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.

*****************************************************************************/

#include <stdbool.h>
#include <stdint.h>
#include <inttypes.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/uio.h>

#include "unfind.h"
#include "lsort.h"

__attribute__((optimize(3)))
static int lsort_cmp(const struct iovec *a, const struct iovec *b) {
	const uint8_t *abuf, *bbuf, *pbuf, *qbuf;
	size_t alen, blen, mlen;

	abuf = a->iov_base;
	alen = a->iov_len;
	bbuf = b->iov_base;
	blen = b->iov_len;

	pbuf = abuf;
	qbuf = abuf + (alen < blen ? alen : blen);

	while(abuf < qbuf && *abuf == *bbuf) {
		abuf++;
		bbuf++;
	}
	mlen = (size_t)(abuf - pbuf);
	alen -= mlen;
	blen -= mlen;

	if(!alen)
		return blen ? -1 : 0;
	if(!blen)
		return 1;

	pbuf = memchr(abuf, unfind_sep, alen);
	qbuf = memchr(bbuf, unfind_sep, blen);

	if(qbuf) {
		if(!pbuf)
			return -1;
	} else {
		if(pbuf)
			return 1;
	}

	if(abuf == pbuf)
		return -1;
	if(bbuf == qbuf)
		return 1;

	return *abuf < *bbuf ? -1 : 1;
}

#if 0

static void lsort_update(struct iovec *iov, uint32_t count, uint32_t o) {
	struct iovec vv, *v, *v1, *v2;
	uint32_t o1, o2;

	if(!count)
		return;

	v = iov + o;
	vv = *v;

	for(;;) {
		o1 = o * 2 + 1;
		if(o1 >= count)
			break;
		v1 = iov + o1;

		o2 = o * 2 + 2;
		if(o2 < count) {
			v2 = iov + o2;
			if(lsort_cmp(v1, v2) < 0) {
				o1 = o2;
				v1 = v2;
			}
		}

		if(lsort_cmp(v1, &vv) <= 0)
			break;

		*v = *v1;
		o = o1;
		v = v1;
	}

	*v = vv;
}

void lsort(struct iovec *iov, uint32_t count) {
	uint32_t u = count / 2;
	struct iovec vv;

	if(!iov || !u)
		return;

	do lsort_update(iov, count, u);
		while(u--);

	while(count-- > 1) {
		vv = iov[0];
		iov[0] = iov[count];
		iov[count] = vv;
		lsort_update(iov, count, 0);
	}
}

#else

typedef int (*cmp)(const void *, const void *);

void lsort(struct iovec *iov, uint32_t count) {
	qsort(iov, (size_t)count, sizeof *iov, (cmp)lsort_cmp);
}

#endif
