#pragma ident "@(#) cmslistbox.c 1.0.4 2012.12.10,15:00"
/*
	cmslistbox.c
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
#include <memory.h>
#include <malloc.h>
#include <locale.h>
#include <time.h>
#include <sys/types.h>
#include <dirent.h>
#include <sys/stat.h>
#include <curses.h>
#include <signal.h>
#include <unistd.h>

#ifdef MSDOS
#define		CR				0x0d
#define		TAB				0x09
#define		ESC				0x1bff
#define		CLEAR_LINE		"\033[0K"
#define		locate(a, b)	printf("\033[%d;%dH", b, a)
#define		clear_line() 	printf("%c%s", CR, CLEAR_LINE)
#endif

#define b4(c) ((c << 8) | 0xff)

char *basename(char *path)
{
	int i,j;
	int len;
	char *p;

	len = strlen(path);
	p = (char *)malloc(sizeof(path));
	for(i=0;i<len;i++)
	{
		if(path[len-i] == '/')
		{
			i--;
			break;
		}
	}
	for(j=0;i != 0;j++,i--)
	{
		p[j] = path[len-i];
	}
	p[j] = '\0';
	return((char *)p);
}

int main(int argc,char *argv[],char *envp)
{
	int ret;
	WINDOW *pvs;
	long ch;
	int item = 1;
	int x2;
	int i;
	int j = 0;
	char rbuff[256];
	int yy = 0;
	int n;
	char buff[64];
	char listbox[128][64];
	char *newline;
	static ylen = 16;
	char *env;
	int qid;
	int pid;

	if (argc< 2)
	{
		exit(1);
	}
	initscr();
	cbreak();
	noecho();
	n = 0;
	for(i = 0;i < argc-1;i++)
	{
		memset(listbox[i],'\0',sizeof(listbox[i]));
		sprintf(listbox[i],"%s",argv[i+1]);
		n++;
	}
	n = n - 1;

	pvs = newwin(ylen,24,(LINES/2)-(16/2),(COLS/2)-(24/2));
	wattron(pvs,A_REVERSE);
	box(pvs,' ',' ');
	mvwprintw(pvs,0,0,"- %s -",argv[argc - 1]);
	wattroff(pvs,A_REVERSE);
	for(;;)
	{
		for(i=0;i<ylen-2;i++)
		{
			if(i < n)
			{
				mvwprintw(pvs,i+1,1,"                    ");
				memset(buff,'\0',strlen(listbox[i+yy]));
				mvwprintw(pvs,i+1,1,buff);
				mvwprintw(pvs,i+1,1,"%s",listbox[i+yy]);
			}
		}

		wmove(pvs,j+1,2);
		wattron(pvs,A_REVERSE);
		mvwprintw(pvs,j+1,1,"%s",listbox[j+yy]);
		wattroff(pvs,A_REVERSE);

		wrefresh(pvs);
		ch = wgetch(pvs);
		getyx(pvs,item,x2);

		switch(ch)
		{
		case 'j': case 0x42:
			if(j + yy >= n - 1)
				break;
			if(j > ylen - 4)
			{
				yy++;
				break;
			}
			if(j <= ylen - 4 && (n-1) > j)
			{
				j++;
			}
			break;
		case 'k': case 0x41:
            if(j == 0 &&  yy > 0)
            {
                yy--;
                break;
            }
			if(j > 0)
				j--;
			if(j < 1)
				j = 0;
			break;

        case 't':
			j = 0;
			yy = 0;
			break;

        case 'g':
			if(n < ylen)
			{
				j = n - 1;
				break;
			}
			if(j + yy > n)
				break;
			j = ylen - 3;
			yy = (n - ylen)+2;
			break;

		case 0x0d: case 0x0a: case 'Z':
			delwin(pvs);
			echo();
			nocbreak();
			endwin();
			clear();
			if((env = getenv("CMS_QUEID")) == NULL)
				qid = 30001;
			else
				qid = atoi(env);
			sprintf(buff,"cmsctl -s %d %s %s",qid,listbox[j+yy],listbox[argc-2]);
			ret = system(buff);
			exit(0);

		case 'q':
			delwin(pvs);
			echo();
			nocbreak();
			endwin();
			exit(-1);
		defualt:
			break;
		}
	}
}

