/*
 * Terminal test for VMS - tries raw VT escape sequences
 * Then tries curses with touchwin/explicit refresh
 */
#ifdef __VMS
#include <curses.h>
#include <stdio.h>
#include <stdlib.h>
#include <descrip.h>
#include <iodef.h>
#include <starlet.h>
#include <ssdef.h>
#include <lib$routines.h>
#ifndef cbreak
#define cbreak() ((void)0)
#endif
#else
#include <ncurses.h>
#include <stdio.h>
#include <stdlib.h>
#endif

int main(void)
{
    FILE *log = fopen("CURSTEST.LOG", "w");

#ifdef __VMS
    /* Test 1: Raw escape sequences via printf */
    fprintf(log, "=== Test 1: Raw VT escape sequences ===\n"); fflush(log);

    /* Clear screen */
    printf("\033[2J");
    /* Move to row 2, col 5 */
    printf("\033[2;5H");
    printf("=== Raw VT Escape Sequence Test ===");
    printf("\033[5;10H");
    printf("Line 5: Hello via raw escape sequences!");
    printf("\033[7;10H");
    printf("Line 7: If you see this, raw VT output works.");
    printf("\033[9;10H");
    printf("Line 9: Press ENTER to continue to curses test...");
    fflush(stdout);

    fprintf(log, "raw VT output written, waiting for input\n"); fflush(log);

    /* Read a line from stdin */
    char buf[80];
    fgets(buf, sizeof(buf), stdin);
    fprintf(log, "got input: 0x%02X\n", (unsigned char)buf[0]); fflush(log);

    /* Test 2: Curses with explicit touchwin */
    fprintf(log, "\n=== Test 2: VMS native curses with touchwin ===\n"); fflush(log);
#endif

    WINDOW *w = initscr();
    fprintf(log, "initscr: %p LINES=%d COLS=%d\n", (void*)w, LINES, COLS); fflush(log);
    cbreak();
    noecho();

    clear();
    mvaddstr(2, 5, "=== Curses Test (after touchwin) ===");
    mvaddstr(5, 10, "Hello from curses + touchwin!");
    mvaddstr(7, 10, "Press any key...");

    touchwin(stdscr);
    fprintf(log, "touchwin done, calling wrefresh\n"); fflush(log);
    wrefresh(stdscr);
    fprintf(log, "wrefresh done, calling getch\n"); fflush(log);

    int ch = getch();
    fprintf(log, "getch returned %d (0x%02X)\n", ch, ch); fflush(log);

    /* Test 3: Try subwindow */
    WINDOW *sub = newwin(5, 40, 12, 20);
    if (sub) {
        fprintf(log, "newwin: %p\n", (void*)sub); fflush(log);
        box(sub, '|', '-');
        mvwaddstr(sub, 2, 5, "Subwindow text!");
        touchwin(sub);
        wrefresh(sub);
        mvaddstr(19, 10, "Subwindow drawn. Press any key to exit...");
        touchwin(stdscr);
        wrefresh(stdscr);
        ch = getch();
        fprintf(log, "sub getch returned %d\n", ch); fflush(log);
        delwin(sub);
    }

    endwin();
    fprintf(log, "test complete\n"); fflush(log);
    fclose(log);

    printf("Done. Check CURSTEST.LOG\n");
    return 0;
}
