/*
 * mouse_test — exercises the libc/io/mouse driver wrappers.
 *
 * Loop: shows live cursor state (pixel + char coordinates + buttons)
 * and the current sensitivity values.  Press +/- to change horizontal
 * sensitivity, [/] to change vertical.  ESC quits.
 */

#include <stdio.h>
#include <conio.h>
#include <mouse.h>

mouse_state_t st;

int main(void)
{
    textattr(COLOR(COLOR_LIGHTGRAY, COLOR_BLACK));
    clrscr();
    cputs("Mouse test - move mouse and click.\r\n"
          "  1 / 2  : decrease / increase horizontal sensitivity\r\n"
          "  3 / 4  : decrease / increase vertical sensitivity\r\n"
          "  ESC    : exit\r\n");

    if (mouse_init() < 0) {
        cputs("mouse_init failed - no driver installed\r\n");
        return 1;
    }

    /* Text mode 03h: 80 chars * 8 = 640 px wide, 32 * 8 = 256 px tall. */
    mouse_bounds_x(0, 639);
    mouse_bounds_y(0, 255);
    mouse_show();

    int     last_x   = -1, last_y = -1;
    uint8_t last_btn = 0xFF;
    /* Sensitivity is a "raw steps per cursor pixel" divider: smaller =
     * faster cursor.  Force a known starting value so the display
     * matches what's active in the driver even when GET returns 0
     * (some drivers / MAME stub). */
    uint8_t sens_x = 2;
    uint8_t sens_y = 2;
    mouse_set_sensitivity(sens_x, sens_y);
    int     sens_dirty = 1;

    st.x = st.y = 0; st.buttons = 0;

    while (1) {
        mouse_read(&st);
        if (st.x != last_x || st.y != last_y || st.buttons != last_btn) {
            gotoxy(0, 6);
            printf("x=%4u y=%4u  text(%2u,%2u)  buttons=0x%02X  L%c R%c   ",
                    st.x, st.y,
                    st.x / 8, st.y / 8,
                    st.buttons,
                    (st.buttons & 1) ? '*' : '.',
                    (st.buttons & 2) ? '*' : '.');
            last_x   = st.x;
            last_y   = st.y;
            last_btn = st.buttons;
        }
        if (sens_dirty) {
            gotoxy(0, 8);
            printf("sensitivity  horz=%3u  vert=%3u   ", sens_x, sens_y);
            sens_dirty = 0;
        }

       if (!kbhit()) continue;
       int k = getch();
       if (k == 27) break;            /* ESC */
       if (k == '1' && sens_x > 1)   { sens_x -= 1; sens_dirty = 1; }
       if (k == '2' && sens_x < 254) { sens_x += 1; sens_dirty = 1; }
       if (k == '3' && sens_y > 1)   { sens_y -= 1; sens_dirty = 1; }
       if (k == '4' && sens_y < 254) { sens_y += 1; sens_dirty = 1; }
       if (sens_dirty)
           mouse_set_sensitivity(sens_x, sens_y);
    }

    mouse_hide();
    gotoxy(0, 10);
    cputs("press any key to exit");
    (void)getch();
    return 0;
}
