/*
Warning: PLEASE DO NOT REMOVE THIS COMMENT WHEN REDISTRIBUTING!
This is the second official release of the Phi-prompt TUI (text user interface), library version 20110523
Released for Phi-1 and Phi-2 shields for Arduino
User is encouraged to obtain a Phi shield or is solely responsible for converting it to work on other shields or configurations.

Programmed by Dr. John Liu
Revision: 05/23/2011
Free software for educational and personal uses.
No warrantee!
Commercial use without authorization is prohibited.

Obtain the documentation or find details of the phi_prompt TUI library, Phi-1 shield, Phi-2 shield, and Phi-prompt or contact Dr. Liu at
http://liudr.wordpress.com/phi-1-shield/
http://liudr.wordpress.com/phi-2-shield/
http://liudr.wordpress.com/phi_prompt/
All rights reserved.
*/

/*
.______    __    __   __        .______   .______        ______   .___  ___. .______   .___________.
|   _  \  |  |  |  | |  |       |   _  \  |   _  \      /  __  \  |   \/   | |   _  \  |           |
|  |_)  | |  |__|  | |  |       |  |_)  | |  |_)  |    |  |  |  | |  \  /  | |  |_)  | `---|  |----`
|   ___/  |   __   | |  |       |   ___/  |      /     |  |  |  | |  |\/|  | |   ___/      |  |     
|  |      |  |  |  | |  |       |  |      |  |\  \----.|  `--'  | |  |  |  | |  |          |  |     
| _|      |__|  |__| |__|  _____| _|      | _| `._____| \______/  |__|  |__| | _|          |__|     

 _______  .______                 __       __   __    __  
|       \ |   _  \               |  |     |  | |  |  |  | 
|  .--.  ||  |_)  |              |  |     |  | |  |  |  | 
|  |  |  ||      /               |  |     |  | |  |  |  | 
|  '--'  ||  |\  \----.    __    |  `----.|  | |  `--'  | 
|_______/ | _| `._____|   (__)   |_______||__|  \______/  

http://liudr.wordpress.com
*/

#include <WProgram.h>
#include <LiquidCrystal.h>
#include <avr/pgmspace.h>
#include <phi_buttons.h>
#include "phi_prompt.h"

PROGMEM prog_char lcd_ch0[]={ 4,14,31,64,31,31,31,31,0};// Up triangle with block
PROGMEM prog_char lcd_ch1[]={ 4,14,31,64,64,64,64,64,0};//Up triangle 
PROGMEM prog_char lcd_ch2[]={31,31,31,31,64,64,64,64,0};// Top block
PROGMEM prog_char lcd_ch3[]={64,64,64,64,31,31,31,31,0};// Bottom block
PROGMEM prog_char lcd_ch4[]={64,64,64,64,64,31,14, 4,0};// Down triangle
PROGMEM prog_char lcd_ch5[]={31,31,31,31,64,31,14, 4,0};// Down triangle with block
PROGMEM const char *ch_item[] = {lcd_ch0, lcd_ch1, lcd_ch2, lcd_ch3, lcd_ch4, lcd_ch5};

PROGMEM prog_char yn_00[]=" YES >NO<";
PROGMEM prog_char yn_01[]=">YES< NO ";
PROGMEM const char *yn_items[]= {yn_00,yn_01};

static LiquidCrystal * lcd;
static phi_buttons ** btns;
static int lcd_w;
static int lcd_h;
static char indicator;

//Utilities
void init_phi_prompt(LiquidCrystal *l, phi_buttons ** b, int w, int h, char i)
{
  lcd=l;
  btns=b;
  lcd_w=w;
  lcd_h=h;
  indicator=i;
  byte ch_buffer[10]; // This buffer is required for custom characters on the LCD.
  for (int i=0;i<6;i++)
  {
    strcpy_P((char*)ch_buffer,(char*)pgm_read_word(&(ch_item[i])));
    lcd->createChar(i, ch_buffer);
  }
}

void set_indicator(char i) // Sets the indicator of the highlighted item in various places.
{
  indicator=i;
}

char inc(char ch, phi_prompt_struct *para)// Increase character. Used in input panels
/*
Option 0: default, option 1: include 0-9 as valid inputs, option 2: only 0-9 are valid, option 3: only 0-9 are valid and the first digit can be '-', option 4: only 0-9 are valid and number increments, option 5: only 0-9 are valid and the first digit can be '-' and number increments.
To do:
Option 2-4, automatically increment or decrement a whole series of numbers when they are connected, such as File0009.txt when increase 9 (if only 0-9 are allowed) will give File0010.txt.
*/
{
  if ((ch<para->high.c)&&(ch>=para->low.c)) return (++ch);
  else
  {
    switch (para->option)
    {
      case 0: // No options. The high and low determine range of characters you can enter.
      if (ch==para->high.c) ch=para->low.c;
      break;
      
      case 1: // Include 0-9
      if (ch=='9') ch=para->low.c;
      else if ((ch>='0')&&(ch<'9')) ch++;
      else if (ch==para->high.c) ch='0';
      break;

      case 2: // only 0-9
      case 4: // only 0-9 and automatically decrements (done at higher level)
      if (ch=='9') ch='0';
      else ch++;
      break;

      case 3: // only 0-9 and '-'
      case 5: // only 0-9 and '-' and automatically increments (done at higher level)
      if (ch=='9') ch='-';
      else if (ch=='-') ch='0';
      else ch++;
      break;
    }
  }
  return ch;
}

char dec(char ch, phi_prompt_struct *para)// Decrease character. Used in input panels
/*
Option 0: default, option 1: include 0-9 as valid inputs, option 2: only 0-9 are valid, option 3: only 0-9 are valid and the first digit can be '-', option 4: only 0-9 are valid and number increments, option 5: only 0-9 are valid and the first digit can be '-' and number increments.
To do:
Option 2-4, automatically increment or decrement a whole series of numbers when they are connected, such as File0009.txt when increase 9 (if only 0-9 are allowed) will give File0010.txt.
*/
{
  if ((ch<=para->high.c)&&(ch>para->low.c)) return (--ch);
  else
  {
    switch (para->option)
    {
      case 0: // No options. The high and low determine range of characters you can enter.
      if (ch==para->low.c) ch=para->high.c;
      break;
      
      case 1: // Include 0-9
      if (ch=='0') ch=para->high.c;
      else if ((ch>'0')&&(ch<='9')) ch--;
      else if (ch==para->low.c) ch='9';
      break;

      case 2: // only 0-9
      case 4: // only 0-9 and automatically decrements (done at higher level)
      if (ch=='0') ch='9';
      else ch--;
      break;

      case 3: // only 0-9 and '-'
      case 5: // only 0-9 and '-' and automatically decrements (done at higher level)
      if (ch=='0') ch='-';
      else if (ch=='-') ch='9';
      else ch--;
      break;
    }
  }
  return ch;
}

//Text renderers
void center_text(char * src) // This outputs a text center-aligned on the display depending on the display size. Eg. center_title("Introduction") outputs ">>>>Introduction<<<<" on 20 column display.
{
  char msg_buffer[21];
  byte j=0;
  for (byte i=0;i<lcd_w;i++)
  {
    if (i<lcd_w/2-(strlen(src)-strlen(src)/2)) msg_buffer[i]='>';
    else if (i>=lcd_w/2+strlen(src)/2) msg_buffer[i]='<';
    else 
    {
      msg_buffer[i]=src[j];
      j++;
    }
  }
  msg_buffer[lcd_w]=0; // Terminate the string
  lcd->print(msg_buffer);
}

void scroll_text(char * src, char * dst, char dst_len, short pos)
{
  for (byte j=0;j<dst_len;j++)
  {
    if ((pos<0)||(pos>strlen(src)-1))
    {
      dst[j]=' ';
    }
    else dst[j]=src[pos];
    pos++;
  }
  dst[dst_len]=0;
}

void scroll_text_P(PGM_P src, char * dst, char dst_len, short pos)
{
  for (byte j=0;j<dst_len;j++)
  {
    if ((pos<0)||(pos>strlen_P(src)-1))
    {
      dst[j]=' ';
    }
    else dst[j]=pgm_read_byte_near(src+pos);
    pos++;
  }
  dst[dst_len]=0;
}

void msg_lcd(char* msg_line) // Displays message from PROGMEM to lcd at current cursor position.
{
  char msg_buffer[21];
  strcpy_P(msg_buffer,msg_line); 
  lcd->print(msg_buffer);
}

void long_msg_lcd(phi_prompt_struct* para) // Displays a long message stored in SRAM that could span multiple lines.
// Option 0: just display message.
// Option 1: display message with a scrollbar to the right.
{
  byte columns=para->step.c_arr[1], rows=para->step.c_arr[0], ch;
  if (para->low.i>=strlen(para->ptr.msg)) ch=0;
  else ch=para->ptr.msg[para->low.i];
  for (byte i=0;i<rows;i++)
  {
    lcd->setCursor(para->col,para->row+i);
    for (byte j=0;j<columns;j++)
    {
      if (ch==0) lcd->write(' ');
      else
      {
        lcd->write(ch);
        ch=para->ptr.msg[para->low.i+i*columns+j+1];
      }
    }
  }
  if (para->option==1)
  {
    scroll_bar_v(((long)para->low.i)*100/strlen(para->ptr.msg),para->col+columns,para->row,rows);
  }
}

void long_msg_lcd_P(phi_prompt_struct* para) // Displays a long message stored in PROGMEM that could span multiple lines.
// Option 0: just display message.
// Option 1: display message with a scrollbar to the right.
{
  byte columns=para->step.c_arr[1], rows=para->step.c_arr[0], ch;
  if (para->low.i>=strlen_P(para->ptr.msg_P)) ch=0;
  else ch=pgm_read_byte_near(para->ptr.msg_P+para->low.i);
  for (byte i=0;i<rows;i++)
  {
    lcd->setCursor(para->col,para->row+i);
    for (byte j=0;j<columns;j++)
    {
      if (ch==0) lcd->write(' ');
      else
      {
        lcd->write(ch);
        ch=pgm_read_byte_near(para->ptr.msg_P+para->low.i+i*columns+j+1);
      }
    }
  }
  if (para->option==1)
  {
    scroll_bar_v(((long)para->low.i)*100/strlen_P(para->ptr.msg_P),para->col+columns,para->row,rows);
  }
}

void scroll_bar_v(byte percent, byte column, byte row, byte v_height)
{
  int mapped;
  if (percent>99) percent=99;
  mapped=(int)(v_height*2-2)*percent/100; // This is mapped position, 2 per row of bar.
  for (byte i=0;i<v_height;i++)
  {
    lcd->setCursor(column,row+i);
    if (i==(mapped+1)/2)
    {
      if (i==0)
      {
        lcd->write(0);
      }
      else if (i==v_height-1)
      {
        lcd->write(5);
      }
      else
      {
        if (mapped+1==(mapped+1)/2*2) lcd->write(2);
        else lcd->write(3);
      }
    }
    else
    {
      if (i==0)
      {
        lcd->write(1);
      }
      else if (i==v_height-1)
      {
        lcd->write(4);
      }
      else
      {
        lcd->write(' ');
      }
    }
  }
}

byte render_list(phi_prompt_struct* para)
{
  byte ret=0, _first_item, _last_item, columns=para->step.c_arr[1], rows=para->step.c_arr[0], item_per_screen=columns*rows, x1=para->col, y1=para->row, x2=para->step.c_arr[3], y2=para->step.c_arr[2]; // Which items to display.
  char list_buffer[22];
  long pos=millis()/500;

  if (para->option&phi_prompt_center_choice) // Determine first item on whether choice is displayed centered.
  {
    _first_item=para->low.i-item_per_screen/2;
    if (_first_item>127) _first_item=0;
    else if (para->low.i-item_per_screen/2+item_per_screen>para->high.i) _first_item=para->high.i+1-item_per_screen;
  }
  else
  {
    _first_item=(para->low.i/item_per_screen)*item_per_screen;
  }
    
  _last_item=_first_item+item_per_screen-1; // Determine last item based on first item, total item per screen, and total item.
  if (_last_item>para->high.i) _last_item=para->high.i;
  
  for (byte i=_first_item;i<_first_item+item_per_screen;i++)
  {
    if (i<=_last_item) // Copy item
    {
      if ((para->option&phi_prompt_auto_scroll)&&(i==para->low.i)&&strlen_P((char*)pgm_read_word(para->ptr.list+i))>para->width) // Determine what portion of the item to be copied. In case of no auto scrolling, only first few characters are copied till the display buffer fills. In case of auto scrolling, a certain portion of the item is copied.
      {
        pos=pos%(strlen_P((char*)pgm_read_word(para->ptr.list+i))+para->width)-para->width;
        scroll_text_P((char*)pgm_read_word(para->ptr.list+i), list_buffer, para->width, pos);//Does the actual copy
        ret=1; // More update is needed to scroll text.
      }
      else //Does the actual truncation
      {
        byte len=strlcpy_P(list_buffer,(char*)pgm_read_word(para->ptr.list+i), para->width+1);
        if (len<para->width)
        {
          for (byte k=len;k<para->width;k++)
          {
            list_buffer[k]=' ';
          }
          list_buffer[para->width]=0;
        }
      }
    }
    else // Fill blank
    {
      byte j;
      for (j=0;j<para->width;j++)
      {
        list_buffer[j]=' ';
      }
      list_buffer[j]=0;
    }
//Display item on LCD
    lcd->setCursor(para->col+((i-_first_item)/rows)*(para->width+1), para->row+(i-_first_item)%rows);

    if (para->option&phi_prompt_arrow_dot) // Determine whether to render arrow and dot. In case of yes, the buffer is shifted to the right one character.       
    {
      if (i<=_last_item)
      {
      lcd->write((i==para->low.i)?indicator:'\xA5');// Show ">" or a dot
      }
      else
      {
        lcd->write(' ');
      }
    }
    lcd->print(list_buffer);
  }

  if (para->option&phi_prompt_index_list) // Determine whether to display 1234567890 index
  {
    lcd->setCursor(x2,y2);
    for (byte i=0;i<=para->high.i;i++)
    {
      if (i==para->low.i) lcd->write(indicator); // Display indicator on index
      else lcd->write(i%10+'1');
    }
  }
  
  else if (para->option&phi_prompt_current_total) // Determine whether to display current/total index
  {
    sprintf(list_buffer,"%c%d/%d", indicator,para->low.i+1, para->high.i+1);
    lcd->setCursor(x2,y2);
    lcd->print(list_buffer);// Prints index
  }
  
  if (para->option&phi_prompt_scroll_bar) // Determine whether to display scroll bar
  {
    scroll_bar_v(((int)para->low.i+1)*100/(para->high.i+1),para->col+columns*(para->width+1)-1*(!(para->option&phi_prompt_arrow_dot)),para->row,rows);
  }
  
  if (para->option&phi_prompt_flash_cursor) // Determine whether to display flashing cursor
  {
    lcd->setCursor(para->col+((para->low.i-_first_item)/rows)*(para->width+1), para->row+(para->low.i-_first_item)%rows);
    lcd->blink();
  }
  else lcd->noBlink();
  
  if (para->option&phi_prompt_invert_text) // Determine whether to invert highlighted item
  {
    
  }
  return ret;  
}

//Interactions
int wait_on_escape(int ref_time) // Returns key pressed or 0 if time expires before any key was pressed.
{
//Wait on button push.
  long temp0;
  byte temp1;
  temp0=millis();
  do
  {
    for (byte i=0;i<6;i++)
    {
      temp1=(*btns+i)->sense();

      if((temp1==buttons_released)||(temp1==buttons_held))
      {
        return(i+1);
      }
    }
  }   while ((millis()-temp0<ref_time));

  return (0);
}

//Inputs
int input_integer(phi_prompt_struct *para)
/*
Input an integer value with wrap-around capability.
This function prints the initial value first so the caller doesn't need to.
Function traps until the update is finalized by the left, right, enter button or escape button.
Return values are updated throught the pointer.
Returns buttons pushed so the caller can determine what to do:
Go back to the last slot with left (-3)
Go forward to the next slot with right (-4)
Enter(1)
Escape(-1).
Display options for integers:
0: space pad right, 1: zero pad left, 2: space pad left.
*/
{
  
  int number=*(para->ptr.i_buffer);
  byte temp1;
  byte space=para->width;
  char msg[space+1];
  char format[]="%00d";
  for (byte i=0;i<space;i++) msg[i]=' '; // Create mask the size of the output space.
  msg[space]=0;
  lcd->setCursor(para->col,para->row); // Write mask to erase previous content.
  lcd->print(msg);
  lcd->setCursor(para->col,para->row); // Write initial value.
  switch (para->option) // Prints out the content once before accepting user inputs.
  {
    case 0://padding with space to the right (padding done in erasing phase)
    sprintf(msg,"%d",number);
    break;

    case 1://padding with zero to the right
    format[2]+=space;
    sprintf(msg,format,number);
    break;
  }

  lcd->print(msg);
  lcd->setCursor(para->col,para->row); // Write initial value.
  lcd->cursor();

  while(true)
  {
    temp1=wait_on_escape(50);
    switch (temp1)
    {
      case 1:
      if (number+(para->step.i)<=(para->high.i)) number+=(para->step.i);
      else number=para->low.i;
      lcd->setCursor(para->col,para->row);
      for (byte i=0;i<space;i++) msg[i]=' '; // Create mask the size of the output space.
      msg[space]=0;
      lcd->print(msg);
      lcd->setCursor(para->col,para->row);
      
      switch (para->option)
      {
        case 0://padding with space to the right (padding done in erasing phase)
        sprintf(msg,"%d",number);
        break;

        case 1://padding with zero to the right
        format[2]='0'+space;
        sprintf(msg,format,number);
        break;
      }

      lcd->print(msg);
      lcd->setCursor(para->col,para->row);
      break;
      
      case 2:
      if (number-para->step.i>=para->low.i) number-=para->step.i;
      else number=para->high.i;
      lcd->setCursor(para->col,para->row);
      for (byte i=0;i<space;i++) msg[i]=' '; // Create mask the size of the output space.
      msg[space]=0;
      lcd->print(msg);
      lcd->setCursor(para->col,para->row);

      switch (para->option)
      {
        case 0://padding with space to the right (padding done in erasing phase)
        sprintf(msg,"%d",number);
        break;

        case 1://padding with zero to the right
        format[2]='0'+space;
        sprintf(msg,format,number);
        break;
      }

      lcd->print(msg);
      lcd->setCursor(para->col,para->row);
      break;
      
      case 3: // Left is pressed
      *(para->ptr.i_buffer)=number;
      lcd->noCursor();
      return (-3);
      break;
      
      case 4: // Right is pressed
      *(para->ptr.i_buffer)=number;
      lcd->noCursor();
      return (-4);
      break;
      
      case 5: // Enter is pressed
      *(para->ptr.i_buffer)=number;
      lcd->noCursor();
      return(1);
      break;
      
      case 6: // Escape is pressed
      lcd->noCursor();
      return (-1);
      break;
      
      default:
      break;
    }
  }
}

int input_float(phi_prompt_struct *para)
/*
Input a floating point value with fixed decimal point. Ironic but true.
This function prints the initial value first so the caller doesn't need to.
Function traps until the update is finalized by the enter button or escape button.
Return values are updated throught the pointer.
Returns buttons pushed so the caller can determine what to do:
Go back to the last slot with left (-3)
Go forward to the next slot with right (-4)
Enter(1)
Escape(-1).
Display options for floats:
0: only positive numbers allowed, 1: only negative numbers allowed, 2: both positive and negative numbers are allowed.
*/
{
  phi_prompt_struct myTextInput;
  char number[17]; // This is the buffer that will store the content of the text panel.
  char format[]="%04d.%02d";
  byte before=para->step.c_arr[1], after=para->step.c_arr[0]; // How many digits to display before and after decimal point.
  int ret;
  format[2]=before+'0';
  format[7]=after+'0';
  sprintf(number,format,int(*para->ptr.f_buffer),int((*para->ptr.f_buffer-int(*para->ptr.f_buffer))*pow(10,after)*(*para->ptr.f_buffer>0?1:-1)+0.5)); // Form the string to represent current value. This string will be the default value of the float input.

  myTextInput.ptr.msg=number; // Assign the text buffer address
  myTextInput.width=before+after+1; // Length of the input panel is 12 characters.
  myTextInput.col=para->col; // Display input panel at required column
  myTextInput.row=para->row; // Display input panel at required row
  switch (para->option)
  {
    case 0:
    myTextInput.low.c='0'; // Text panel valid input starts with character '-'.
    myTextInput.high.c='9'; // Text panel valid input ends with character '-'. Could end with '.' if real floating number is enabled.
    myTextInput.option=0; // Option 1 incluess 0-9 as valid characters. Option 0, default, option 1 include 0-9 as valid inputs.
    break;

    case 1:
    number[0]='-';
    myTextInput.low.c='0'; // Text panel valid input starts with character '-'.
    myTextInput.high.c='9'; // Text panel valid input ends with character '-'. Could end with '.' if real floating number is enabled.
    myTextInput.option=0; // Option 1 incluess 0-9 as valid characters. Option 0, default, option 1 include 0-9 as valid inputs.
    break;

    case 2:
    myTextInput.low.c='-'; // Text panel valid input starts with character '-'.
    myTextInput.high.c='-'; // Text panel valid input ends with character '-'. Could end with '.' if real floating number is enabled.
    myTextInput.option=1; // Option 1 incluess 0-9 as valid characters. Option 0, default, option 1 include 0-9 as valid inputs.
    break;

    default:
    break;
  }
  
  ret=input_panel(&myTextInput);
  if (ret!=-1)
  {  
    sscanf(number,"%d%*c%d",&myTextInput.high.i,&myTextInput.low.i);
    *para->ptr.f_buffer=(-1)*(myTextInput.high.i<0?1:-1)*myTextInput.low.i/pow(10.0,(float)after)+myTextInput.high.i;
  }
  return ret;  
}

int select_list(phi_prompt_struct *para)
/*
Select from a list with wrap-around capability.
This function prints the initial value first so the caller doesn't need to.
Function traps until the update is finalized by the left, right, enter button or escape button.
Return values are updated throught the pointer.
Returns buttons pushed so the caller can determine what to do:
Go back to the last slot with left (-3)
Go forward to the next slot with right (-4)
Enter(1)
Escape(-1).
Display options for list:
Option 0: display classic list, option 1: display MXN list, option 2: display list with index, option 3: display list with index2, option 4: display MXN list with scrolling
*/
{
  int temp1;
  byte render, width=para->width;
  char msg[width+1];
  render=render_list(para);
  while(true)
  {
    temp1=wait_on_escape(50);
    switch (temp1)
    {
      case 0:
      if (render)
      {
        render=render_list(para);
      }
      break;
      
      case 1:
      if ((para->low.i+1)<=(para->high.i)) para->low.i++;
      else para->low.i=0;
      render=render_list(para);
      break;
      
      case 2:
      if (para->low.i-1>=0) para->low.i--;
      else para->low.i=para->high.i;
      render=render_list(para);
      break;
      
      case 3: // Left is pressed
      lcd->noCursor();
      return (-3);
      break;
      
      case 4: // Right is pressed
      lcd->noCursor();
      return (-4);
      break;
      
      case 5: // Enter is pressed
      lcd->noCursor();
      return(1);
      break;
      
      case 6: // Escape is pressed
      lcd->noCursor();
      return (-1);
      break;
      
      default:
      break;
    }
  }
}

int input_panel(phi_prompt_struct *para)
/*
Alphanumerical input panel for texts up to 16 characters.
The option starts with the character _start and ends with character _end
The total length will not exceed length.
The first letter appears at column, row
The function prints the content of the buffer msg before polling for input
The function returns number of actual characters
The function returns -1 if the input is cancelled.
The function fills the buffer after the last character with \0 only if the buffer is not filled. The caller is responsible to fill the character beyond the end of the buffer with \0.
Input character options for input panel:
Option 0: default, option 1: include 0-9 as valid inputs, option 2: only 0-9 are valid, option 3: only 0-9 are valid and the first digit can be '-', option 4: only 0-9 are valid and number increments, option 5: only 0-9 are valid and the first digit can be '-' and number increments.
To do:
Option 2-4, automatically increment or decrement a whole series of numbers when they are connected, such as File0009.txt when increase 9 (if only 0-9 are allowed) will give File0010.txt.
*/
{
  byte pointer=0, chr;
  int temp1;
  lcd->setCursor(para->col,para->row);
  lcd->print(para->ptr.msg);
  lcd->setCursor(para->col,para->row);
  lcd->cursor();
  while(true)
  {
    temp1=wait_on_escape(50);
    chr=*(para->ptr.msg+pointer); // Loads the current character.
    switch (temp1)
    {
      case 1:
      *(para->ptr.msg+pointer)=inc(chr, para);
      lcd->write(*(para->ptr.msg+pointer));
      lcd->setCursor(pointer+para->col,para->row);
      
      //do automatic increment
      break;
      
      case 2:
      *(para->ptr.msg+pointer)=dec(chr, para);
      lcd->write(*(para->ptr.msg+pointer));
      lcd->setCursor(pointer+para->col,para->row);
      
      //do automatic decrement
      break;
      
      case 3: // Left is pressed
      if (pointer>0)
      {
        pointer--;
        lcd->setCursor(pointer+para->col,para->row);
      }
      else
      {
        lcd->noCursor();
        return (-3);
      }
      break;
      
      case 4: // Right is pressed
      if (pointer<(para->width)-1)
      {
        pointer++;
        lcd->setCursor(pointer+para->col,para->row);
      }
      else
      {
        lcd->noCursor();
        return (-4);
      }
      break;
      
      case 5: // Enter is pressed
      lcd->noCursor();
      return(1);
      break;
      
      case 6: // Escape is pressed
      lcd->noCursor();
      return (-1);
      break;
      
      default:
      break;
    }
  }
}

int text_area(phi_prompt_struct *para) // Displays a text area using message stored in the SRAM
{
  byte columns=para->step.c_arr[1], rows=para->step.c_arr[0], ch;
  long_msg_lcd(para);
  while(true)
  {
    byte temp1=wait_on_escape(50);
    switch (temp1)
    {
      case 1:
      if (para->low.i+columns<para->high.i)
      {
        para->low.i+=columns;
        long_msg_lcd(para);
      }
      break;
      
      case 2:
      if (para->low.i-columns>=0)
      {
        para->low.i-=columns;
        long_msg_lcd(para);
      }
      break;
      case 3: // Left is pressed
      return(-3);
      break;
      
      case 4: // Right is pressed
      return(-4);
      break;
      
      case 5: // Enter is pressed
      return(1);
      break;
      
      case 6: // Escape is pressed
      return (-1);
      break;
      
      default:
      break;
    }
  }
}

int text_area_P(phi_prompt_struct *para) // Displays a text area using message stored in the PROGMEM
{
  byte columns=para->step.c_arr[1], rows=para->step.c_arr[0], ch;
  long_msg_lcd_P(para);
  while(true)
  {
    byte temp1=wait_on_escape(50);
    switch (temp1)
    {
      case 1:
      if (para->low.i+columns<para->high.i)
      {
        para->low.i+=columns;
        long_msg_lcd_P(para);
      }
      break;
      
      case 2:
      if (para->low.i-columns>=0)
      {
        para->low.i-=columns;
        long_msg_lcd_P(para);
      }
      break;
      case 3: // Left is pressed
      return(-3);
      break;
      
      case 4: // Right is pressed
      return(-4);
      break;
      
      case 5: // Enter is pressed
      return(1);
      break;
      
      case 6: // Escape is pressed
      return (-1);
      break;
      
      default:
      break;
    }
  }
}

int yn_dialog(char msg[]) // The function auto scales to fit on any LCD.
{
  phi_prompt_struct yn_list;
  
  lcd->clear(); // Clear the lcd.
// Use the yn_list struct to display the message as a long message to enable multiple line question.
  yn_list.ptr.msg=msg; // Assign the address of the text string to the pointer.
  yn_list.low.i=0; // Default text starting position. 0 is highly recommended.
  yn_list.high.i=((sizeof(msg)-1)>lcd_w*lcd_h-10)?lcd_w*lcd_h-10:(sizeof(msg)-1); // Position of the last character in the text string, which is size of the string - 1.
  yn_list.step.c_arr[0]=lcd_h; // row
  yn_list.step.c_arr[1]=lcd_w; // column
  yn_list.col=0; // Display the text area starting at column 0
  yn_list.row=0; // Display the text area starting at row 0
  yn_list.option=0; // Option 0, display classic message, option 1, display message with scroll bar on right.

  long_msg_lcd(&yn_list);

  yn_list.ptr.list=(char**)&yn_items; // Assign the address of the list array to the pointer.
  yn_list.low.i=0; // Default item highlighted on the list is #0, the first item on the list.
  yn_list.high.i=1; // Last item on the list is size of the list - 1.
  yn_list.width=9; // Length in characters of the longest list item, for screen update purpose.
  yn_list.col=lcd_w-9; // Display the list a column to make it right-alighed
  yn_list.row=lcd_h-1; // Display the list at a row to make it bottom-alighed
  yn_list.step.c_arr[0]=1; // 1 row
  yn_list.step.c_arr[1]=1; // 1 column
  yn_list.option=0; // Option 3 is an indexed list for clarity. Option 0, display classic list, option 1, display MXN list, option 2, display list with index, option 3, display list with index2.

  if (select_list(&yn_list)!=-1) return yn_list.low.i; //If the user didn't press escape (return -1) then update the user choice with the value in myListInput.low.
}

int ok_dialog(char msg[]) // The function auto scales to fit on any LCD.
{
  phi_prompt_struct yn_list;
  
  lcd->clear(); // Clear the lcd.
// Use the yn_list struct to display the message as a long message to enable multiple line question.
  yn_list.ptr.msg=msg; // Assign the address of the text string to the pointer.
  yn_list.low.i=0; // Default text starting position. 0 is highly recommended.
  yn_list.high.i=((sizeof(msg)-1)>lcd_w*lcd_h-5)?lcd_w*lcd_h-5:(sizeof(msg)-1); // Position of the last character in the text string, which is size of the string - 1.
  yn_list.step.c_arr[0]=lcd_h; // row
  yn_list.step.c_arr[1]=lcd_w; // column
  yn_list.col=0; // Display the text area starting at column 0
  yn_list.row=0; // Display the text area starting at row 0
  yn_list.option=0; // Option 0, display classic message, option 1, display message with scroll bar on right.

  long_msg_lcd(&yn_list);

  lcd->setCursor((lcd_w-4),lcd_h-1);
  lcd->print(">OK<");
  
  while(wait_on_escape(500)==0)
  {
  }
}
