'
' Demo shamelessly ripped from the NCURSES PROGRAMMING HOWTO:
'   http://tldp.org/HOWTO/NCURSES-Programming-HOWTO
'
' Ported to BaCon in June 2010 - PvE (GPLv3)
'
'------------------------------------------------------------------

INCLUDE "curses.bac"
INCLUDE "panel.bac"

CONST NLINES = 10
CONST NCOLS = 40

DECLARE my_wins[3]
DECLARE my_panels[3]
DECLARE top
DECLARE ch TYPE int

' Initialize curses
stdscr = initscr()
start_color()
cbreak()
noecho()
keypad(stdscr, TRUE)

' Initialize all the colors
init_pair(1, COLOR_RED, COLOR_BLACK)
init_pair(2, COLOR_GREEN, COLOR_BLACK)
init_pair(3, COLOR_BLUE, COLOR_BLACK)
init_pair(4, COLOR_CYAN, COLOR_BLACK)

CALL init_wins(my_wins, 3)
        
' Attach a panel to each window, order is bottom up
my_panels[0] = new_panel(my_wins[0])
my_panels[1] = new_panel(my_wins[1])
my_panels[2] = new_panel(my_wins[2])

' Set up the user pointers to the next panel
set_panel_userptr(my_panels[0], my_panels[1])
set_panel_userptr(my_panels[1], my_panels[2])
set_panel_userptr(my_panels[2], my_panels[0])

' Update the stacking order. 2nd panel will be on top
update_panels()

' Show it on the screen
attron(COLOR_PAIR(4))
mvprintw(LINES - 2, 0, "Use tab to browse through the windows (F2 to Exit)")
attroff(COLOR_PAIR(4))
doupdate()

top = my_panels[2]

WHILE ch NE KEY_F(2)

    ch = getch()

    IF ch EQ 9 THEN
        top = panel_userptr(top)
        top_panel(top)
    END IF
    update_panels()
    doupdate()
WEND

endwin()
END

' Put all the windows
SUB init_wins(NUMBER wins[], int n)

    LOCAL x, y, i TYPE int

    y = 2
    x = 10

    FOR i = 0 TO n-1
        wins[i] = newwin(NLINES, NCOLS, y, x)
        CALL win_show(wins[i], CONCAT$("Window Number ", STR$(i + 1)), i + 1);
        INCR y, 3
        INCR x, 7
    NEXT

END SUB

' Show the window with a border and a label
SUB win_show(NUMBER win, STRING label, int label_color)

    DECLARE startx, starty, height, width TYPE int

    getbegyx(win, starty, startx)
    getmaxyx(win, height, width)

    box(win, 0, 0)
    mvwaddch(win, 2, 0, ACS_LTEE)
    mvwhline(win, 2, 1, ACS_HLINE, width - 2)
    mvwaddch(win, 2, width - 1, ACS_RTEE)
        
    CALL print_in_middle(win, 1, 0, width, label, COLOR_PAIR(label_color))

END SUB

SUB print_in_middle(NUMBER win, int starty, int startx, int width, STRING string, long color)

    DECLARE length, x, y TYPE int
    DECLARE temp TYPE float

    IF win EQ 0 THEN win = stdscr

    getyx(win, y, x)
 
    IF startx != 0 THEN x = startx
    IF starty != 0 THEN y = starty
    IF width EQ 0 THEN width = 80

    length = strlen(string)
    temp = (width - length)/ 2
    x = startx + (int)temp
    wattron(win, color)
    mvwprintw(win, y, x, "%s", string)
    wattroff(win, color)
    refresh()

END SUB