#include "defs.h"

int input_get_direction(void)
{
    int ch = wgetch(G->win_map);

    switch (ch) {
    /* vi keys */
    case 'k': return DIR_N;
    case 'u': return DIR_NE;
    case 'l': return DIR_E;
    case 'n': return DIR_SE;
    case 'j': return DIR_S;
    case 'b': return DIR_SW;
    case 'h': return DIR_W;
    case 'y': return DIR_NW;
    case '<': return DIR_UP;
    case '>': return DIR_DOWN;
    case ' ': return DIR_STAY;

    /* Numpad */
    case '8': return DIR_N;
    case '9': return DIR_NE;
    case '6': return DIR_E;
    case '3': return DIR_SE;
    case '2': return DIR_S;
    case '1': return DIR_SW;
    case '4': return DIR_W;
    case '7': return DIR_NW;
    case '5': return DIR_STAY;

    /* Arrow keys */
    case KEY_UP:    return DIR_N;
    case KEY_DOWN:  return DIR_S;
    case KEY_LEFT:  return DIR_W;
    case KEY_RIGHT: return DIR_E;

    /* Cancel */
    case 27:  /* ESC */
    case '\n':
    case KEY_ENTER:
        return -1;

    default:
        return -2;  /* Unknown */
    }
}

static void handle_tab_command(void)
{
    int ch = wgetch(G->win_map);
    int dir, slot;

    switch (ch) {
    case 'c':  /* Close inventory item */
        msg("Close item (container)");
        slot = display_prompt_item("Close");
        if (slot >= 0) {
            item_t *it = &G->player.inventory[slot];
            if (it->is_open) {
                it->is_open = 0;
                msg("Click!");
            } else {
                msg("It's already closed!");
            }
        }
        break;

    case 'd':  /* Disable trap */
        msg("Disable trap (direction or CANCEL) ");
        dir = display_prompt_dir("Disable trap");
        if (dir >= 0 && dir < 8) {
            int tx = G->player.x + dx[dir];
            int ty = G->player.y + dy[dir];
            if (tx >= 0 && tx < MAP_W && ty >= 0 && ty < MAP_H) {
                level_t *lev = G->levels[G->cur_level];
                cell_t *c = &lev->map[ty][tx];
                if (c->has_trap) {
                    if (rng_chance(G->player.dex + G->player.intel)) {
                        c->has_trap = 0;
                        msg("You disabled the trap!");
                    } else {
                        msg("Doesn't seem to do any good ...");
                    }
                } else {
                    msg("Nothing to disable!");
                }
            }
        }
        break;

    case 'e':  /* Empty inventory item */
        msg("Empty ... toward (direction) ");
        /* Simplified: just show message */
        dir = display_prompt_dir("Empty");
        if (dir >= 0) {
            msg("It doesn't seem to contain anything ...");
        }
        break;

    case 'f':  /* Fill */
        msg("Fill ... from (direction) ");
        dir = display_prompt_dir("Fill from");
        if (dir >= 0) {
            msg("Nope!");
        }
        break;

    case 'F':  /* Fix inventory item */
        msg("Fix item");
        slot = display_prompt_item("Fix");
        if (slot >= 0) {
            item_t *it = &G->player.inventory[slot];
            if (it->damage_level > 0) {
                if (rng_chance(G->player.dex + G->player.intel)) {
                    it->damage_level--;
                    if (it->damage_level == 0)
                        msg("Good as new again!");
                    else
                        msg("Looks a bit better now ...");
                } else {
                    msg("Doesn't seem to be doing any good ...");
                }
            } else {
                msg("It doesn't seem to be damaged ...");
            }
        }
        break;

    case 'g':
    case 'G':  /* Get from container */
        msg("Get item from (container)");
        slot = display_prompt_item("Get from");
        if (slot >= 0) {
            msg("It's empty ...");
        }
        break;

    case 'I':  /* Show item info */
        msg("Show item");
        slot = display_prompt_item("Show");
        if (slot >= 0)
            item_examine(slot);
        break;

    case 'j':  /* Jump */
        msg("Jump (direction or CANCEL) ");
        dir = display_prompt_dir("Jump");
        if (dir >= 0 && dir < 8) {
            int jx = G->player.x + dx[dir] * 2;
            int jy = G->player.y + dy[dir] * 2;
            if (jx >= 0 && jx < MAP_W && jy >= 0 && jy < MAP_H &&
                map_passable(jx, jy)) {
                if (rng_chance(G->player.dex * 3 + G->player.str)) {
                    G->player.x = jx;
                    G->player.y = jy;
                    msg("You jumped!");
                } else {
                    msg("You fail to jump a meaningful distance ...");
                }
            } else {
                msg("Don't be ridiculous!");
            }
        }
        break;

    case 'l':  /* Look */
        if (player_has_status(SF_BLINDED)) {
            msg("You're BLIND, dummy!!!!");
            break;
        }
        msg("Look (direction or CANCEL) ");
        dir = display_prompt_dir("Look");
        if (dir >= 0 && dir < 8) {
            int lx = G->player.x + dx[dir];
            int ly = G->player.y + dy[dir];
            if (lx >= 0 && lx < MAP_W && ly >= 0 && ly < MAP_H) {
                monster_t *m = map_monster_at(lx, ly);
                if (m && m->active) {
                    msg("You see %s", monster_name(m->type));
                    if (m->friendly) msg(" (it looks friendly)");
                    else msg(" (it looks angry)");
                } else {
                    msg("You see nothing of interest");
                }
            }
        }
        break;

    case 'n':  /* Name friend */
        msg("Give name to (direction or CANCEL) ");
        dir = display_prompt_dir("Name");
        if (dir >= 0 && dir < 8) {
            int nx = G->player.x + dx[dir];
            int ny = G->player.y + dy[dir];
            monster_t *m = map_monster_at(nx, ny);
            if (m && m->active && m->friendly) {
                char buf[32];
                if (display_prompt_str("... new name (max 15 chars): ", buf, 15) > 0) {
                    strncpy(m->name, buf, 31);
                }
            } else if (m && !m->friendly) {
                msg("You can only name things that are friendly");
            } else {
                msg("Nothing there to name!");
            }
        }
        break;

    case 'N':  /* Name class of device */
        msg("Class of items to rename");
        slot = display_prompt_item("Rename class");
        if (slot >= 0) {
            item_t *it = &G->player.inventory[slot];
            if (it->type == IT_PILL && !it->is_identified) {
                char buf[32];
                if (display_prompt_str("... new name (max 15 chars): ", buf, 15) > 0) {
                    /* Store custom name */
                    strncpy(it->name, buf, 31);
                }
            } else {
                msg("You can only name \"strange\" devices");
            }
        }
        break;

    case 'o':  /* Open inventory item */
        msg("Open item (container)");
        slot = display_prompt_item("Open");
        if (slot >= 0) {
            item_t *it = &G->player.inventory[slot];
            if (it->type >= IT_SM_WOODEN_CRATE && it->type <= IT_LG_METAL_LOCKER) {
                if (it->is_open) {
                    msg("It's already open!");
                } else {
                    it->is_open = 1;
                    msg("It creaks open ...");
                }
            } else {
                msg("You can't open that!");
            }
        }
        break;

    case 'p':  /* Pause soundly */
        msg("You attempt to sleep soundly ...");
        while (G->player.hp < G->player.max_hp) {
            G->player.hp++;
            G->player.turns++;
            /* Check for monster attacks */
            level_t *lev = G->levels[G->cur_level];
            for (int i = 0; i < lev->n_monsters; i++) {
                monster_t *m = &lev->monsters[i];
                if (m->active && !m->friendly &&
                    abs(m->x - G->player.x) <= 1 && abs(m->y - G->player.y) <= 1) {
                    msg("You are attacked in your sleep!");
                    combat_monster_attacks_player(m);
                    goto done_sleep;
                }
            }
        }
done_sleep:
        msg("You wake up");
        break;

    case 's':  /* Shove */
        msg("Shove (direction or CANCEL) ");
        dir = display_prompt_dir("Shove");
        if (dir >= 0 && dir < 8) {
            int sx = G->player.x + dx[dir];
            int sy = G->player.y + dy[dir];
            monster_t *m = map_monster_at(sx, sy);
            if (m && m->active) {
                int px = sx + dx[dir];
                int py = sy + dy[dir];
                if (px >= 0 && px < MAP_W && py >= 0 && py < MAP_H &&
                    map_passable(px, py) && !map_has_monster(px, py)) {
                    if (rng_chance(G->player.str * 3)) {
                        m->x = px;
                        m->y = py;
                        msg("You shove %s!", monster_name(m->type));
                    } else {
                        msg("You fail to budge it");
                    }
                } else {
                    msg("Nope!");
                }
            } else {
                msg("Nothing to shove!");
            }
        }
        break;

    case 't':  /* Throw approximate */
        msg("Throw (item)");
        slot = display_prompt_item("Throw");
        if (slot >= 0) {
            dir = display_prompt_dir("... toward (direction) ");
            if (dir >= 0 && dir < 8)
                combat_throw(slot, dir);
        }
        break;

    case 'T':  /* Toss into container */
        msg("Toss ... into container (item)");
        slot = display_prompt_item("Toss into");
        if (slot >= 0)
            msg("That is not a container!");
        break;

    case '?':  /* Assorted help */
        msg("Help available for: (c) commands (h) current health (k) key mappings");
        {
            int hch = wgetch(G->win_map);
            switch (hch) {
            case 'c': display_help(); break;
            case 'h': display_health(); break;
            case 'k': display_help(); break;
            default:  msg("(cancelled)"); break;
            }
        }
        break;

    default:
        msg("(cancelled TAB prefix)");
        break;
    }
}

void input_process(void)
{
    player_t *p = &G->player;
    int ch = wgetch(G->win_map);
    int dir, slot;

    if (player_has_status(SF_STUNNED)) {
        msg("You can't move!");
        p->turns++;
        player_tick_status();
        return;
    }

    if (player_has_status(SF_SLEEPING)) {
        msg("Zzzzz...");
        p->turns++;
        player_tick_status();
        return;
    }

    switch (ch) {
    /* Movement - vi keys */
    case 'k': player_move(DIR_N); break;
    case 'u': player_move(DIR_NE); break;
    case 'l': player_move(DIR_E); break;
    case 'n': player_move(DIR_SE); break;
    case 'j': player_move(DIR_S); break;
    case 'b': player_move(DIR_SW); break;
    case 'h': player_move(DIR_W); break;
    case 'y': player_move(DIR_NW); break;

    /* Movement - numpad */
    case '8': player_move(DIR_N); break;
    case '9': player_move(DIR_NE); break;
    case '6': player_move(DIR_E); break;
    case '3': player_move(DIR_SE); break;
    case '2': player_move(DIR_S); break;
    case '1': player_move(DIR_SW); break;
    case '4': player_move(DIR_W); break;
    case '7': player_move(DIR_NW); break;
    case '5': player_rest(); break;
    case ' ': player_rest(); break;

    /* Movement - arrow keys */
    case KEY_UP:    player_move(DIR_N); break;
    case KEY_DOWN:  player_move(DIR_S); break;
    case KEY_LEFT:  player_move(DIR_W); break;
    case KEY_RIGHT: player_move(DIR_E); break;

    /* Stairs */
    case '<': player_go_up(); break;
    case '>': player_go_down(); break;

    /* Running - uppercase vi keys */
    case 'K': player_run(DIR_N); break;
    case 'U': player_run(DIR_NE); break;
    case 'L': player_run(DIR_E); break;
    case 'N': player_run(DIR_SE); break;
    case 'J': player_run(DIR_S); break;
    case 'B': player_run(DIR_SW); break;
    case 'H': player_run(DIR_W); break;
    case 'Y': player_run(DIR_NW); break;

    /* Attack */
    case 'a':
        msg("Attack (direction or CANCEL) ");
        dir = display_prompt_dir("Attack");
        if (dir >= 0 && dir < 8)
            combat_attack(dir);
        break;

    /* Activate item */
    case 'A':
        slot = display_prompt_item("Activate");
        if (slot >= 0) item_activate(slot);
        break;

    /* Close */
    case 'c':
        msg("Close (direction or CANCEL) ");
        dir = display_prompt_dir("Close");
        if (dir >= 0 && dir < 8) {
            int cx = p->x + dx[dir];
            int cy = p->y + dy[dir];
            if (cx >= 0 && cx < MAP_W && cy >= 0 && cy < MAP_H) {
                level_t *lev = G->levels[G->cur_level];
                if (lev->map[cy][cx].tile == T_DOOR_OPEN) {
                    lev->map[cy][cx].tile = T_DOOR_CLOSED;
                    msg("Click!");
                } else {
                    msg("You can't close that!");
                }
            }
        }
        break;

    /* Charge/Recharge */
    case 'C':
        slot = display_prompt_item("Charge/Recharge");
        if (slot >= 0) {
            item_t *it = &p->inventory[slot];
            if (it->charges >= 100) {
                msg("It is already fully charged");
            } else {
                /* Look for powercell */
                int found = -1;
                for (int i = 0; i < p->inv_count; i++) {
                    if (p->inventory[i].type == IT_POWERCELL ||
                        p->inventory[i].type == IT_LARGE_POWERCELL ||
                        p->inventory[i].type == IT_POWERPACK) {
                        found = i;
                        break;
                    }
                }
                if (found >= 0) {
                    it->charges = 100;
                    p->inventory[found].qty--;
                    if (p->inventory[found].qty <= 0) {
                        for (int i = found; i < p->inv_count - 1; i++)
                            p->inventory[i] = p->inventory[i + 1];
                        p->inv_count--;
                        if (p->wielded > found) p->wielded--;
                        if (p->reserve > found) p->reserve--;
                        if (p->worn_armor > found) p->worn_armor--;
                        if (p->worn_helmet > found) p->worn_helmet--;
                    }
                    msg("thrummmmm!");
                } else {
                    msg("Nothing to recharge it with!");
                }
            }
        }
        break;

    /* Drop */
    case 'd':
        slot = display_prompt_item("Drop");
        if (slot >= 0) item_drop(slot);
        break;

    /* Deactivate */
    case 'D':
        slot = display_prompt_item("Deactivate");
        if (slot >= 0) item_deactivate(slot);
        break;

    /* Eat */
    case 'e':
        slot = display_prompt_item("Eat");
        if (slot >= 0) item_eat(slot);
        break;

    /* Examine */
    case 'E':
        slot = display_prompt_item("Examine");
        if (slot >= 0) item_examine(slot);
        break;

    /* Fire */
    case 'f':
        msg("Fire (direction or CANCEL) ");
        dir = display_prompt_dir("Fire");
        if (dir >= 0 && dir < 8)
            combat_fire(dir);
        break;

    /* Fix adjacent */
    case 'F':
        msg("Fix (direction or CANCEL) ");
        dir = display_prompt_dir("Fix");
        if (dir >= 0 && dir < 8) {
            int fx = p->x + dx[dir];
            int fy = p->y + dy[dir];
            if (fx >= 0 && fx < MAP_W && fy >= 0 && fy < MAP_H) {
                level_t *lev = G->levels[G->cur_level];
                cell_t *c = &lev->map[fy][fx];
                if (c->tile == T_DOOR_CLOSED || c->tile == T_DOOR_OPEN) {
                    msg("Huh uh");
                } else {
                    msg("There isn't anything there to repair!");
                }
            }
        }
        break;

    /* Get/pickup */
    case 'g':
        item_pickup();
        break;

    /* Get from container */
    case 'G':
        msg("Get item from (container)");
        slot = display_prompt_item("Get from");
        if (slot >= 0) msg("It's empty ...");
        break;

    /* Inspect */
    case 'i':
        if (player_has_status(SF_BLINDED)) {
            msg("You're BLIND, dummy!!!!");
            break;
        }
        msg("Inspect (direction or CANCEL) ");
        dir = display_prompt_dir("Inspect");
        if (dir >= 0 && dir < 8) {
            int ix = p->x + dx[dir];
            int iy = p->y + dy[dir];
            if (ix >= 0 && ix < MAP_W && iy >= 0 && iy < MAP_H) {
                level_t *lev = G->levels[G->cur_level];
                cell_t *c = &lev->map[iy][ix];
                monster_t *m = map_monster_at(ix, iy);
                if (m && m->active) {
                    msg("You see %s", monster_name(m->type));
                    if (m->hp < m->max_hp / 4)
                        msg(" that is critically injured");
                    else if (m->hp < m->max_hp / 2)
                        msg(" that is seriously injured");
                    else if (m->hp < m->max_hp)
                        msg(" that is injured");
                    if (m->friendly) msg("... it looks rather friendly");
                    else msg("... it looks rather angry");
                    if (monster_is_mechanical(m->type))
                        msg("... it has a metallic sheen");
                } else if (c->tile == T_WALL) {
                    msg("A nondescript section of wall");
                } else if (c->tile == T_DOOR_CLOSED) {
                    msg("A door");
                    if (c->has_trap) msg("... it looks trapped");
                } else if (c->tile == T_WASTE) {
                    msg("A rather vile looking expanse of industrial waste fluids");
                } else if (c->tile == T_HOLE) {
                    msg("There is a large hole in the floor");
                } else {
                    msg("You see nothing of interest");
                }
            }
        }
        break;

    /* Toggle inventory */
    case 'I':
    case '*':
        G->inv_visible = !G->inv_visible;
        if (G->inv_visible)
            display_inventory();
        else
            display_clear_inv();
        break;

    /* Message review */
    case 'm':
        if (G->opts.log_messages) {
            display_msgs();
        } else {
            msg("Message logging is not enabled");
        }
        break;

    /* Mail - not implemented */
    case 'M':
        msg("Mail is not available on this system");
        break;

    /* Open */
    case 'o':
        msg("Open (direction or CANCEL) ");
        dir = display_prompt_dir("Open");
        if (dir >= 0 && dir < 8) {
            int ox = p->x + dx[dir];
            int oy = p->y + dy[dir];
            if (ox >= 0 && ox < MAP_W && oy >= 0 && oy < MAP_H) {
                level_t *lev = G->levels[G->cur_level];
                cell_t *c = &lev->map[oy][ox];
                if (c->tile == T_DOOR_CLOSED) {
                    c->tile = T_DOOR_OPEN;
                    msg("It creaks open ...");
                    if (c->has_trap && rng_chance(50)) {
                        msg("... noxious fumes billow out ...");
                        if (!rng_chance(p->con * 2)) {
                            msg("... and make you choke!");
                            player_take_damage(rng(1, 4), "trap");
                        } else {
                            msg("... but you are unaffected");
                        }
                        c->has_trap = 0;
                    }
                } else if (c->tile == T_DOOR_LOCKED) {
                    msg("It's locked ...");
                    /* Check for keycard */
                    int have_key = 0;
                    for (int ki = 0; ki < p->inv_count; ki++) {
                        if (p->inventory[ki].type == IT_KEYCARD) {
                            have_key = 1;
                            break;
                        }
                    }
                    (void)have_key;
                    /* For now, brute force */
                    if (rng_chance(p->str * 2)) {
                        c->tile = T_DOOR_OPEN;
                        msg("Click!");
                    } else {
                        msg("Doesn't seem to do any good ...");
                    }
                } else if (c->tile == T_DOOR_OPEN) {
                    msg("It's already open!");
                } else {
                    msg("You can't open that!");
                }
            }
        }
        break;

    /* Snapshot */
    case 'O':
        msg("(writing snapshot...)");
        break;

    /* Pause/rest until healed */
    case 'p':
        if (p->hp >= p->max_hp) {
            msg("You are already fully healed!");
            break;
        }
        msg("Resting...");
        {
            level_t *lev = G->levels[G->cur_level];
            int interrupted = 0;
            while (p->hp < p->max_hp && !interrupted) {
                p->turns++;
                player_tick_status();
                /* Check for nearby enemies */
                for (int mi = 0; mi < lev->n_monsters; mi++) {
                    monster_t *m = &lev->monsters[mi];
                    if (m->active && !m->friendly) {
                        int dist = abs(m->x - p->x) + abs(m->y - p->y);
                        if (dist <= 3) {
                            msg("You sense danger and wake up!");
                            interrupted = 1;
                            break;
                        }
                    }
                }
                monsters_move(lev);
            }
        }
        break;

    /* Print screen - not implemented */
    case 'P':
        msg("Printing is not supported");
        break;

    /* Quaff/drink */
    case 'q':
        slot = display_prompt_item("Drink");
        if (slot >= 0) {
            item_t *it = &p->inventory[slot];
            if (it->type == IT_BOTTLE) {
                if (it->charges > 0) {
                    msg("Glug glug glug!");
                    msg("Slurp!");
                    msg("Tastes clean and refreshing ...");
                    it->charges--;
                    player_heal(rng(2, 6));
                    if (player_has_status(SF_DIZZY)) {
                        player_remove_status(SF_DIZZY);
                        msg("You no longer feel dizzy");
                    }
                    if (player_has_status(SF_CONFUSED)) {
                        player_remove_status(SF_CONFUSED);
                        msg("You no longer feel confused");
                    }
                } else {
                    msg("It's empty!");
                }
            } else {
                msg("Nope!");
            }
        }
        break;

    /* Quit */
    case 'Q':
        if (display_prompt_yn("Really want to quit?  If so, your game will be saved ... ")) {
            save_game(SAVE_FILE);
            G->running = 0;
        }
        break;

    /* Reload */
    case 'r':
        if (p->wielded < 0) {
            msg("You aren't wielding a weapon!");
            break;
        }
        {
            item_t *wpn = &p->inventory[p->wielded];
            if (!item_is_ranged(wpn->type)) {
                msg("Hmmmmmm ...");
                break;
            }
            if (wpn->ammo >= 10) {
                msg("It's already fully loaded");
                break;
            }
            /* Find appropriate ammo */
            int ammo_type = -1;
            if (wpn->type >= IT_GYROJET_PISTOL && wpn->type <= IT_GYROJET_SHOTGUN)
                ammo_type = IT_GYROJET;
            else if (wpn->type == IT_NEEDLER)
                ammo_type = IT_NEEDLE;

            if (ammo_type >= 0) {
                int found = -1;
                for (int ai = 0; ai < p->inv_count; ai++) {
                    if (p->inventory[ai].type == ammo_type) {
                        found = ai;
                        break;
                    }
                }
                if (found >= 0) {
                    int load = 10 - wpn->ammo;
                    if (load > p->inventory[found].qty)
                        load = p->inventory[found].qty;
                    wpn->ammo += load;
                    p->inventory[found].qty -= load;
                    if (p->inventory[found].qty <= 0) {
                        for (int i = found; i < p->inv_count - 1; i++)
                            p->inventory[i] = p->inventory[i + 1];
                        p->inv_count--;
                        if (p->wielded > found) p->wielded--;
                        if (p->reserve > found) p->reserve--;
                        if (p->worn_armor > found) p->worn_armor--;
                        if (p->worn_helmet > found) p->worn_helmet--;
                    }
                    msg("click-clack!");
                } else {
                    msg("Nothing to reload it with!");
                }
            } else {
                /* Energy weapons use powercells */
                int found = -1;
                for (int ai = 0; ai < p->inv_count; ai++) {
                    if (p->inventory[ai].type == IT_POWERCELL ||
                        p->inventory[ai].type == IT_LARGE_POWERCELL) {
                        found = ai;
                        break;
                    }
                }
                if (found >= 0) {
                    wpn->ammo = 10;
                    p->inventory[found].qty--;
                    if (p->inventory[found].qty <= 0) {
                        /* Replace with dead powercell */
                        p->inventory[found].type = IT_DEAD_POWERCELL;
                        p->inventory[found].qty = 1;
                    }
                    msg("thrummmmm!");
                } else {
                    msg("Nothing to reload it with!");
                }
            }
        }
        break;

    /* Remove worn item */
    case 'R':
        slot = display_prompt_item("Remove");
        if (slot >= 0) item_remove(slot);
        break;

    /* Search */
    case 's':
        player_search();
        break;

    /* Toggle auto-search */
    case 'S':
        p->auto_search = !p->auto_search;
        msg(p->auto_search ? "Auto-Search" : "(auto-search off)");
        break;

    /* Throw */
    case 't':
        slot = display_prompt_item("Throw (item)");
        if (slot >= 0) {
            dir = display_prompt_dir("... toward (direction) ");
            if (dir >= 0 && dir < 8)
                combat_throw(slot, dir);
        }
        break;

    /* Toss */
    case 'T':
        slot = display_prompt_item("Toss");
        if (slot >= 0) {
            dir = display_prompt_dir("... in adjacent location (direction) ");
            if (dir >= 0 && dir < 8)
                item_drop(slot);
        }
        break;

    /* Version/score */
    case 'v':
        display_version();
        break;

    /* Wield */
    case 'w':
        slot = display_prompt_item("Wield");
        if (slot >= 0) item_wield(slot);
        break;

    /* Wear */
    case 'W':
        slot = display_prompt_item("Wear");
        if (slot >= 0) item_wear(slot);
        break;

    /* Exchange weapons */
    case 'x':
    case ',': {
        int tmp = p->wielded;
        p->wielded = p->reserve;
        p->reserve = tmp;
        if (p->wielded >= 0) {
            msg("Now wielding %s", item_type_name(p->inventory[p->wielded].type));
            p->wc = 3; /* Recalculate based on weapon */
        } else {
            msg("Not wielding anything now");
            p->wc = 0;
        }
        break;
    }

    /* Checkpoint */
    case 'X':
        msg("(saving game...)");
        save_game(SAVE_FILE);
        msg("Game saved");
        break;

    /* Toggle options */
    case 'z':
        msg("Options: (a) auto-take (c) cursor (i) ignore objects (v) verbosity");
        {
            int och = wgetch(G->win_map);
            switch (och) {
            case 'a':
                p->auto_take = !p->auto_take;
                msg(p->auto_take ? "(auto-take on)" : "(auto-take off)");
                break;
            case 'i':
                p->ignore_objects = !p->ignore_objects;
                msg(p->ignore_objects ? "(ignoring objects)" : "(no longer ignoring objects)");
                break;
            case 'v':
                p->brief_mode = !p->brief_mode;
                msg(p->brief_mode ? "(verbose off)" : "(verbose on)");
                break;
            default:
                msg("(cancelled)");
                break;
            }
        }
        break;

    /* TAB prefix commands ('\t' == 9, handled via Ctrl-I) */
    case '\t':
        handle_tab_command();
        break;

    /* Health */
    case '/':
        display_health();
        break;

    /* Help */
    case '?':
        display_help();
        break;

    /* DCL/Shell (spawn) */
    case '$':
    case '!':
        msg("Shell access is not available");
        break;

    /* Scroll inventory */
    case KEY_PPAGE:
        if (G->inv_visible && G->inv_scroll > 0)
            G->inv_scroll -= 10;
        break;
    case KEY_NPAGE:
        if (G->inv_visible)
            G->inv_scroll += 10;
        break;

    /* Ctrl-R, Ctrl-W: refresh */
    case 18:  /* Ctrl-R */
    case 23:  /* Ctrl-W */
        display_refresh();
        break;

    default:
        break;
    }
}
