static char sccsid[]="%Z% %M% %I% %E% %U%";
/*
    cc -g -DLINUX -I../include testeditor.c libakx.a -o testeditor
*/
#include "akxcommon.h"

int _add_src(pQue,n1,n2,s,s_len)
tdtQueCtl *pQue;
int n1,n2;
char *s;
int s_len;
{
	int rc,n;
	char *cp;

printf("_add_src: n1=%d n2=%d s_len=%d s=[%s]\n",n1,n2,s_len,s);
	if (s_len <= 0) return 0;
	if ((rc=akxs_que_peek(pQue,QUE_BOT,&cp)) > 0) {
		memcpy(&n,cp,sizeof(int));
		n += n2;
	}
	else n = n1;
	cp = Malloc(sizeof(int)+s_len+1);
	memcpy(cp,&n,sizeof(int));
	memcpy(cp+sizeof(int),s,s_len+1);
	akxs_que_put(pQue,QUE_BOT,cp);
	return 0;
}

int _ins_src(pQue,num,s,s_len)
tdtQueCtl *pQue;
int num;
char *s;
int s_len;
{
	int rc,n;
	char *cp;

printf("_ins_src: num=%d s_len=%d s=[%s]\n",num,s_len,s);
	akxs_que_move(pQue,QUE_TOP,NULL);
	for (;;) {
		if ((rc=akxs_que_peek(pQue,QUE_PEEK_CUR,&cp)) <= 0) break;
		memcpy(&n,cp,sizeof(int));
printf("_add_src: peek: rc=%d n=%d\n",rc,n);
		if (n >= num) break;
		akxs_que_move(pQue,QUE_NEXT,NULL);
	}
	if (n == num) {
		if (s_len <= 0) {
			akxs_que_get(pQue,QUE_CUR,&cp);
			Free(cp);
			return 0;
		}
		Free(cp);
	}
	else {
		if (s_len <= 0) return 0;
		akxs_que_move(pQue,QUE_PREV,NULL);
	}
	cp = Malloc(sizeof(int)+s_len+1);
	memcpy(cp,&num,sizeof(int));
	memcpy(cp+sizeof(int),s,s_len+1);
	akxs_que_put(pQue,QUE_CUR,cp);
	return 0;
}

int _list_src(pQue)
tdtQueCtl *pQue;
{
	int rc,n;
	char *cp;

	akxs_que_move(pQue,QUE_TOP,NULL);
	for (;;) {
		if ((rc=akxs_que_peek(pQue,QUE_PEEK_NEXT,&cp)) <= 0) break;
		memcpy(&n,cp,sizeof(int));
		printf("%5d %s\n",n,cp+sizeof(int));
	}
	return 0;
}

int _renumber(pQue,n1,n2)
tdtQueCtl *pQue;
int n1,n2;
{
	int rc,n;
	char *cp;

	n = n1;
	akxs_que_move(pQue,QUE_TOP,NULL);
	for (;;) {
		if ((rc=akxs_que_peek(pQue,QUE_PEEK_CUR,&cp)) <= 0) break;
		memcpy(cp,&n,sizeof(int));
		n += n2;
		akxs_que_move(pQue,QUE_NEXT,NULL);
	}
	return 0;
}

main()
{
	tdtQueCtl *pQue;
	char buf[128],work[128],*p;
	int line_len,len,num,s_len,pos,n1,n2;
	SSP_S ssp;

	n1 = n2 = 10;
	ssp.wd = work;
	pQue = akxs_que_new(0,0);
	for (;;) {
		printf(">");
		line_len = akxa_read_line_opt(buf,sizeof(buf),stdin,2);
		ssp.sp = 0;
		if ((len=akxtgwse(buf,&ssp," \n",1)) > 0) {
			if (!strcmp(work,"/")) break;
			else if (!stricmp(work,"/list")) {
				_list_src(pQue);
			}
			else if (!stricmp(work,"/renum")) {
				if ((len=akxtgwse(buf,&ssp," \n",1)) > 0) {
					n1 = atoi(work);
					if ((len=akxtgwse(buf,&ssp," \n",1)) > 0) n2 = atoi(work);
				}
				if (n1 <= 0) n1 = 10;
				if (n2 <= 0) n2 = 10;
				_renumber(pQue,n1,n2);
			}
			else {
				num = atoi(work);
				if (num < 0) continue;
				else if (num > 0) {
					p = buf + ssp.sp + 1;
					s_len = line_len - ssp.sp - 1;
					_ins_src(pQue,num,p,s_len);
				}
				else {
					_add_src(pQue,n1,n2,buf,line_len);
				}
			}
		}
	}
	return 0;
}
