/* c.events  */
#include <stdio.h>
#include <string.h>
#include "allegro.h"
#include "asm.h"

/*********************************************************************
 *
 * char *poll_loop(char * string,int mode)
 *
 * This function is very similar to function interp() (asm.c).
 * This function is used to poll parameters if the questionmark
 * is used as a parameter or when parameters are lacking.
 *
 *********************************************************************/
extern int asm_font_width ;

char *poll_loop(char * string,int mode)
{
	int k = 0,i= 0,c;
	char buf[ASM_COMMAND_LENGTH];     /* temporarial buffer */


	/* clear the commandline  */
	rectfill(screen, 0, SCREEN_H-1*text_height(font), SCREEN_W, SCREEN_H, gui_bg_color);

	/* place the prompt on the command line */

	sprintf(buf,"%s", ASM_POLL_PROMPT);
	textout_ex(screen, font, buf, ASM_TEXT_OFFSET, SCREEN_H-1*text_height(font) , ASM_RED_COLOR, 0);

	/* place cursor on the commandline */
	c = '_';
	sprintf(buf,"%c", c);
	textout_ex(screen, font, buf, ASM_TEXT_OFFSET+asm_font_width*strlen(ASM_POLL_PROMPT), SCREEN_H-1*text_height(font) , ASM_FG_COLOR, 0);

	do {
		if (keypressed()) {

			k = readkey();
			c = k & 0xFF;
			k >>= 8;

			switch(k)
			{

			case KEY_ESC:
				string[0] = EOS;

				break;

			case KEY_BACKSPACE:
			case KEY_LEFT:
			case KEY_DEL:

				c = ' ';
				sprintf(buf,"%c", c);
				textout_ex(screen, font, buf, ASM_TEXT_OFFSET+(i+strlen(ASM_POLL_PROMPT))*asm_font_width, SCREEN_H-1*text_height(font)
				    , ASM_FG_COLOR, 0);

				if( i > 0 )
					i-- ;

				c = '_';
				sprintf(buf,"%c", c);
				textout_ex(screen, font, buf, ASM_TEXT_OFFSET+(i+strlen(ASM_POLL_PROMPT))*asm_font_width, SCREEN_H-1*text_height(font)
				    , ASM_FG_COLOR, 0);

				break;

			case KEY_ENTER:

				string[i] = EOS;

				asm_wprintf("%s", string);

				break;

			default:

				if ((c < ' ') || (c >= ' '+FONT_SIZE) || (i > (ASM_COMMAND_LENGTH-2)) )
					c = ' ';
				else
				{
					string[i] = (char)c;
					sprintf(buf,"%c",c);
					textout_ex(screen, font,buf,ASM_TEXT_OFFSET+(i+strlen(ASM_POLL_PROMPT))*asm_font_width, SCREEN_H-1*text_height(font)
					    , ASM_FG_COLOR, 0);
					if (i < (ASM_COMMAND_LENGTH -2))
						i++;
					else i = ASM_COMMAND_LENGTH -1;

					c = '_';                 /* print the cursor */
					sprintf(buf,"%c",c);
					textout_ex(screen, font,buf,ASM_TEXT_OFFSET+(i+strlen(ASM_POLL_PROMPT))*asm_font_width, SCREEN_H-1*text_height(font)
					    , ASM_FG_COLOR, 0);
				}
				break;
			}

		}
	} while ( (k != KEY_ESC) && (k != KEY_ENTER) );

	return(string);
}
