/*
 *	Sort.c - Copyright © 1991 by S.R. & P.C.
 *
 *	Created:	21 Feb 1991  09:39:43
 *	Modified:	15 Mar 1991  21:01:37
 *
 *	Make>> make
 */

#include "Global.h"
#include "proto/Sort.h"


int CmpName(struct ScrollEntry **e1, struct ScrollEntry **e2);

static int CmpSize(struct ScrollEntry **e1, struct ScrollEntry **e2);
#pragma regcall(CmpSize(a0, a1))

static int CmpDate(struct ScrollEntry **e1, struct ScrollEntry **e2);
#pragma regcall(CmpDate(a0, a1))

static int CmpKey(struct ScrollEntry **e1, struct ScrollEntry **e2);
#pragma regcall(CmpKey(a0, a1))

static int CmpType(struct ScrollEntry **e1, struct ScrollEntry **e2);
#pragma regcall(CmpType(a0, a1))


static int (*SortTab[])() = { CmpName, CmpDate, CmpSize, CmpKey };


/***    public stuff    ***/

void Sort(struct BrowserWindow *Win)
{
	int (*SortFct)();

	SortFct = SortTab[Win->bw_Sort & 0x0F];
	if (Win->bw_Sort & TYPE_SORT) {
		QSort(Win->bw_EntryArray, Win->bw_ShownEntries, 4, CmpType);
		QSort(Win->bw_EntryArray, Win->bw_ShownDirs, 4, SortFct);
		QSort(&Win->bw_EntryArray[Win->bw_ShownDirs], Win->bw_ShownFiles, 4, SortFct);
	}
	else
		QSort(Win->bw_EntryArray, Win->bw_ShownEntries, 4, SortFct);
}


/***    local stuff    ***/

static int CmpNumber(long n1, long n2);
#pragma regcall(CmpNumber(a0, a1))

static int CCmpName(struct ScrollEntry **e1, struct ScrollEntry **e2);
#pragma regcall(CCmpName(a0, a1))


/* Can't be call directly from QSort since _ArpBase must be accessed through a4 */

static int CCmpName(struct ScrollEntry **e1, struct ScrollEntry **e2)
{
	return Strcmp((*e1)->se_FileInfo.fi_Name, (*e2)->se_FileInfo.fi_Name);
}


#asm

	public _CmpName
	public _geta4

_CmpName:
	move.l	a4,-(sp)
	bsr		_geta4
	bsr		_CCmpName
	move.l	(sp)+,a4
	rts

#endasm


static int CmpNumber(long n1, long n2)
{
    if (n1 < n2)
		return -1;
    else if (n1 > n2)
		return 1;
    else
		return 0;
}


static int CmpSize(struct ScrollEntry **e1, struct ScrollEntry **e2)
{
	return CmpNumber((*e1)->se_FileInfo.fi_Size, (*e2)->se_FileInfo.fi_Size);
}


static int CmpDate(struct ScrollEntry **e1, struct ScrollEntry **e2)
{
	return CmpNumber((*e1)->se_FileInfo.fi_Secs, (*e2)->se_FileInfo.fi_Secs);
}


static int CmpKey(struct ScrollEntry **e1, struct ScrollEntry **e2)
{
	return CmpNumber((*e1)->se_FileInfo.fi_DiskKey, (*e2)->se_FileInfo.fi_DiskKey);
}


static int CmpType(struct ScrollEntry **e1, struct ScrollEntry **e2)
{
	if ((*e1)->se_FileInfo.fi_Type == (*e2)->se_FileInfo.fi_Type)
		return 0;
	else if((*e1)->se_FileInfo.fi_Type == DLX_DIR)
		return -1;
	else
		return 1;
}


