/***********************************************/
/* 検索処理                                    */
/*     ORDER BY 節作成関数                     */
/*---------------------------------------------*/
/*                      ver 0.1                */
/*                           make  A.Kobayashi */
/*                           date  2010.05.01  */
/***********************************************/
#include "colmn.h"

#define BUFF_SIZE 64

extern ExtTBL  ExtTbl;

char *cl_sl_ext_order()
{
	char *buf, atrnam[40], *alias, *atrb;
	int   i, j, *index, *order, n, rc;
	MCAT mcat;

/*
*** order by文節の生成
 */
	index = (int *)Malloc(sizeof(int)*ExtTbl.iItemNum);
	order = (int *)Malloc(sizeof(int)*ExtTbl.iItemNum);
	if (!index || !order) {
		ERROROUT("memory allocate error");
		if (index) Free(index);
		if (order) Free(order);
		return(NULL);
	}

	/* アトリビュート数分ループ */
	j = 0;
	for (i=0; i<ExtTbl.iItemNum; i++) {
		if (ExtTbl.Line[i].OrderNumber > 0) {
			index[j] = i;
			order[j++] = ExtTbl.Line[i].OrderNumber;
		}
	}

	if(!(buf = (char *)Malloc(BUFF_SIZE))) {
		ERROROUT("memory allocate error");
		if (index) Free(index);
		if (order) Free(order);
		return NULL;
	}
	mcat.mc_extlen = BUFF_SIZE;
	mcat.mc_maxcnt = 0;
	mcat.mc_extcnt = 0;
	mcat.mc_alclen = BUFF_SIZE;
	mcat.mc_bufp = buf;
	mcat.mc_ipos = 0;

	*buf = '\0';

	n = clsort(j,order,index);

	for (i=0;i<n;i++) {
		if (i) rc = axtmcats(&mcat,",");
		else rc = axtmcats(&mcat, " order by ");
		if (rc < 0) goto Err;
		j = index[i];
		sprintf(atrnam,"%s.%s", ExtTbl.Line[j].ALIASNAME,
		                        ExtTbl.Line[j].AttrName);
		if (axtmcats(&mcat, atrnam) < 0) goto Err;
		if (ExtTbl.Line[j].OrderType == 'D')
			if (axtmcats(&mcat," desc") < 0) goto Err;
	}
	if (index) Free(index);
	if (order) Free(order);

	return buf;
 Err:
	if (index) Free(index);
	if (order) Free(order);
	if (mcat.mc_bufp) Free(mcat.mc_bufp);
	return NULL;
}

int clsort (n,obj,index)
int n,obj[],index[];
{
	int i,j,im,val,tmp;

	for (i=0;i<n-1;i++) {
		im=i;
		val=obj[im];
		for (j=i+1;j<n;j++) {
			if (obj[j]<val) {
				im=j;
				val=obj[im];
			}
		}
		if (im>i) {
			obj[im]=obj[i];
			obj[i]=val;
			tmp=index[im];
			index[im]=index[i];
			index[i]=tmp;
		}
	}
	return n;
}
