#include "defs.h"
#include <stdarg.h>

/* Item info record */
typedef struct {
    const char *name;
    char glyph;
    int weight;
    int value;
    int flags;
    int power; /* damage for weapons, AC for armor, charges for tools */
    int max_ammo;
} item_info_t;

static const item_info_t item_table[IT_COUNT] = {
 /* name                    gl  wt  val  flags                                pow ammo */
 {"rock",                   ')', 3,   1, ICF_WEAPON|ICF_MELEE,                 1,  0},
 {"butcher knife",          ')', 2,   5, ICF_WEAPON|ICF_MELEE,                 3,  0},
 {"crowbar",                ')', 5,   8, ICF_WEAPON|ICF_MELEE|ICF_TOOL,        4,  0},
 {"combat knife",           ')', 2,  15, ICF_WEAPON|ICF_MELEE,                 5,  0},
 {"blaster",                ')', 3,  50, ICF_WEAPON|ICF_RANGED,                6, 20},
 {"blaster rifle",          ')', 5,  80, ICF_WEAPON|ICF_RANGED,                8, 30},
 {"laser pistol",           ')', 3,  60, ICF_WEAPON|ICF_RANGED,                7, 15},
 {"laser rifle",            ')', 5, 100, ICF_WEAPON|ICF_RANGED,                9, 25},
 {"gyrojet pistol",         ')', 3,  40, ICF_WEAPON|ICF_RANGED,                6,  6},
 {"gyrojet rifle",          ')', 5,  70, ICF_WEAPON|ICF_RANGED,                8, 10},
 {"gyrojet shotgun",        ')', 6,  90, ICF_WEAPON|ICF_RANGED,               10,  8},
 {"stunrod",                ')', 3,  35, ICF_WEAPON|ICF_MELEE,                 4, 10},
 {"stimmer",                ')', 3,  45, ICF_WEAPON|ICF_MELEE,                 5, 12},
 {"discombobulator",        ')', 4,  55, ICF_WEAPON|ICF_RANGED,                7, 15},
 {"disruptor",              ')', 4,  75, ICF_WEAPON|ICF_RANGED,                9, 20},
 {"disflorger",             ')', 5,  95, ICF_WEAPON|ICF_RANGED,               11, 20},
 {"disintegrator",          ')', 5, 150, ICF_WEAPON|ICF_RANGED,               14, 15},
 {"plasma cannon",          ')', 8, 200, ICF_WEAPON|ICF_RANGED,               16, 10},
 {"needler",                ')', 3,  30, ICF_WEAPON|ICF_RANGED,                5, 20},
 {"jacket",                 '[', 4,  10, ICF_ARMOR|ICF_WEARABLE,               1,  0},
 {"leather jacket",         '[', 5,  20, ICF_ARMOR|ICF_WEARABLE,               2,  0},
 {"armored vest",           '[', 8,  40, ICF_ARMOR|ICF_WEARABLE,               3,  0},
 {"kevlar jacket",          '[', 6,  60, ICF_ARMOR|ICF_WEARABLE,               4,  0},
 {"kevlar suit",            '[', 10, 90, ICF_ARMOR|ICF_WEARABLE,               5,  0},
 {"battle armor",           '[', 15,150, ICF_ARMOR|ICF_WEARABLE,               7,  0},
 {"forcefield pack",        '[', 5, 200, ICF_ARMOR|ICF_WEARABLE,               8, 50},
 {"coin",                   '$', 1,   1, 0,                                    0,  0},
 {"powercell",              '(', 1,  10, ICF_AMMO,                            20,  0},
 {"large powercell",        '(', 2,  25, ICF_AMMO,                            50,  0},
 {"dead powercell",         '(', 1,   1, ICF_JUNK,                             0,  0},
 {"large dead powercell",   '(', 2,   2, ICF_JUNK,                             0,  0},
 {"gyrojet",                '(', 1,   5, ICF_AMMO,                             1,  0},
 {"AutoDoc",                '+', 0,   0, ICF_INSTALL,                          0,  0},
 {"Transmat Booth",         '+', 0,   0, ICF_INSTALL,                          0,  0},
 {"Librarian",              '+', 0,   0, ICF_INSTALL,                          0,  0},
 {"Bank",                   '+', 0,   0, ICF_INSTALL,                          0,  0},
 {"Vending Machine",        '+', 0,   0, ICF_INSTALL,                          0,  0},
 {"pill",                   '!', 1,   5, ICF_PILL|ICF_FOOD,                    0,  0},
 {"rusty pipe",             ')', 4,   3, ICF_WEAPON|ICF_MELEE,                 3,  0},
 {"light globe",            '(', 2,  15, ICF_TOOL|ICF_LIGHT,                   0, 50},
 {"machete",                ')', 4,  12, ICF_WEAPON|ICF_MELEE,                 5,  0},
 {"antique sword",          ')', 5,  25, ICF_WEAPON|ICF_MELEE,                 6,  0},
 {"grenade",                '(', 2,  30, ICF_WEAPON,                          12,  0},
 {"landmine",               '(', 3,  35, ICF_WEAPON,                          15,  0},
 {"gravbelt",               '(', 3,  80, ICF_TOOL|ICF_WEARABLE,                0, 30},
 {"chameleon circuit",      '(', 2,  70, ICF_TOOL|ICF_WEARABLE,                0, 25},
 {"sonic screwdriver",      '(', 1,  40, ICF_TOOL,                             0, 20},
 {"gas mask",               '[', 2,  20, ICF_WEARABLE|ICF_HEADGEAR,            1,  0},
 {"biochem jumpsuit",       '[', 6,  50, ICF_ARMOR|ICF_WEARABLE,               3,  0},
 {"towel",                  '(', 1,   2, ICF_TOOL,                             0,  0},
 {"panic button",           '(', 1,  50, ICF_TOOL,                             0,  1},
 {"oddly shaped coin",      '$', 1,  50, 0,                                    0,  0},
 {"L.A.M.B.",               '*', 5, 999, ICF_TOOL,                             0,  0},
 {"jaunt box",              '(', 3, 100, ICF_TOOL,                             0, 10},
 {"brick",                  '(', 5,   1, ICF_JUNK,                             2,  0},
 {"chronograph",            '(', 1,  20, ICF_TOOL,                             0,  0},
 {"empty beer can",         '(', 1,   0, ICF_JUNK,                             0,  0},
 {"broken bottle",          ')', 1,   1, ICF_WEAPON|ICF_MELEE,                 2,  0},
 {"dirty rag",              '(', 1,   0, ICF_JUNK,                             0,  0},
 {"door",                   '(', 0,   0, 0,                                    0,  0},
 {"small generator",        '(', 0,   0, ICF_INSTALL,                          0,  0},
 {"security badge",         '(', 1,   5, ICF_TOOL,                             0,  0},
 {"keycard",                '(', 1,  10, ICF_TOOL,                             0,  0},
 {"infrared goggles",       '(', 2,  40, ICF_TOOL|ICF_WEARABLE|ICF_HEADGEAR,   0, 30},
 {"bone",                   '(', 2,   1, ICF_JUNK,                             1,  0},
 {"skull",                  '(', 3,   2, ICF_JUNK,                             1,  0},
 {"bottle top",             '(', 1,   0, ICF_JUNK,                             0,  0},
 {"milk carton",            '(', 1,   0, ICF_JUNK,                             0,  0},
 {"stale cookie",           '%', 1,   1, ICF_FOOD,                             0,  0},
 {"trash can",              '(', 5,   2, ICF_CONTAINER,                        0,  0},
 {"trash can lid",          '[', 3,   2, ICF_WEARABLE,                         1,  0},
 {"flare",                  '(', 1,  10, ICF_TOOL|ICF_LIGHT,                   0,  1},
 {"needle",                 '(', 1,   2, ICF_AMMO,                             1,  0},
 {"moly-blade",             ')', 2, 120, ICF_WEAPON|ICF_MELEE,                10,  0},
 {"magnetometer",           '(', 2,  30, ICF_TOOL,                             0, 20},
 {"spacesuit",              '[', 12,100, ICF_ARMOR|ICF_WEARABLE,               4, 99},
 {"android",                '(', 0,   0, 0,                                    0,  0},
 {"StarGate",               '(', 0,   0, ICF_INSTALL,                          0,  0},
 {"radometer",              '(', 2,  25, ICF_TOOL,                             0, 20},
 {"macro-metal jacket",     '[', 7,  80, ICF_ARMOR|ICF_WEARABLE,               5,  0},
 {"pile of rubble",         '(', 0,   0, ICF_JUNK,                             0,  0},
 {"repulsor",               '(', 3,  60, ICF_TOOL,                             0, 10},
 {"time dilator",           '(', 3, 150, ICF_TOOL,                             0, 15},
 {"macro-metal knife",      ')', 2,  60, ICF_WEAPON|ICF_MELEE,                 7,  0},
 {"MegaTech Factory Outlet",'+', 0,   0, ICF_INSTALL,                          0,  0},
 {"Reclamation Center",     '+', 0,   0, ICF_INSTALL,                          0,  0},
 {"paint pellet",           '(', 1,   1, ICF_AMMO,                             0,  0},
 {"air gun",                ')', 2,  15, ICF_WEAPON|ICF_RANGED,                2, 10},
 {"neuro-whip",             ')', 3,  55, ICF_WEAPON|ICF_MELEE,                 6, 15},
 {"holo-cube",              '(', 2,  35, ICF_TOOL,                             0, 10},
 {"LAWs rocket",            ')', 8,  80, ICF_WEAPON|ICF_RANGED,               18,  1},
 {"pickaxe",                ')', 6,   8, ICF_WEAPON|ICF_MELEE|ICF_TOOL,        5,  0},
 {"small wooden crate",     '(', 8,   5, ICF_CONTAINER,                        0,  0},
 {"wooden crate",           '(', 15, 10, ICF_CONTAINER,                        0,  0},
 {"large wooden crate",     '(', 25, 15, ICF_CONTAINER,                        0,  0},
 {"small metal locker",     '(', 12, 15, ICF_CONTAINER,                        0,  0},
 {"metal locker",           '(', 20, 25, ICF_CONTAINER,                        0,  0},
 {"large metal locker",     '(', 30, 40, ICF_CONTAINER,                        0,  0},
 {"stepladder",             '(', 10,  5, ICF_TOOL,                             0,  0},
 {"stasis bag",             '(', 2,  40, ICF_CONTAINER,                        0,  0},
 {"helmet",                 '[', 3,  20, ICF_WEARABLE|ICF_HEADGEAR,            2,  0},
 {"macro-metal helmet",     '[', 4,  50, ICF_WEARABLE|ICF_HEADGEAR,            3,  0},
 {"mirror",                 '(', 3,  15, ICF_TOOL,                             0,  0},
 {"ear protectors",         '(', 2,  10, ICF_WEARABLE|ICF_HEADGEAR,            0,  0},
 {"screamer",               '(', 2,  25, ICF_TOOL,                             0,  5},
 {"corpse",                 '%', 10,  0, ICF_FOOD|ICF_JUNK,                    0,  0},
 {"pile of assorted entrails",'%',5,  0, ICF_FOOD|ICF_JUNK,                    0,  0},
 {"pile of scrapmetal",     '(', 8,   3, ICF_JUNK,                             0,  0},
 {"vibra-knife",            ')', 2, 100, ICF_WEAPON|ICF_MELEE,                 9, 20},
 {"vibra-sword",            ')', 3, 140, ICF_WEAPON|ICF_MELEE,                11, 25},
 {"vibra-lance",            ')', 5, 180, ICF_WEAPON|ICF_MELEE,                13, 30},
 {"scrambler",              '(', 3,  60, ICF_TOOL,                             0, 15},
 {"powerpack",              '(', 3,  40, ICF_AMMO,                           100,  0},
 {"battle helmet",          '[', 5,  70, ICF_WEARABLE|ICF_HEADGEAR,            4,  0},
 {"oxygen cylinder",        '(', 4,  15, ICF_TOOL,                             0, 99},
 {"helgun",                 ')', 6, 160, ICF_WEAPON|ICF_RANGED,               12, 20},
 {"water fountain",         '(', 0,   0, ICF_INSTALL,                          0,  0},
 {"bottle",                 '(', 2,   5, ICF_CONTAINER,                        0,  0},
 {"soft pillow",            '(', 2,   1, ICF_JUNK,                             0,  0},
 {"colloidal jacket",       '[', 7,  70, ICF_ARMOR|ICF_WEARABLE,               4,  0},
 {"colloidal armor",        '[', 12,110, ICF_ARMOR|ICF_WEARABLE,               6,  0},
 {"macro-metal armor",      '[', 14,130, ICF_ARMOR|ICF_WEARABLE,               6,  0},
 {"battle jacket",          '[', 10,100, ICF_ARMOR|ICF_WEARABLE,               5,  0},
 {"exoskeleton",            '[', 18,250, ICF_ARMOR|ICF_WEARABLE,               9,  0},
 {"wooden club",            ')', 5,   3, ICF_WEAPON|ICF_MELEE,                 3,  0},
};

/* Pill color names */
static const char *pill_colors[PILL_COLORS] = {
    "aqua", "black", "blue", "brown", "cadet blue",
    "coral", "cyan", "dark blue", "dark green", "dark grey",
    "forest green", "gold", "golden", "green", "grey",
    "lemon yellow", "light blue", "light green", "light grey", "lime green",
    "magenta", "maroon", "midnight blue", "navy blue", "olive green",
    "orange", "pale blue", "pale green", "pale yellow", "pink",
    "plum", "puce", "purple", "red", "salmon",
    "sea green", "silver", "silvery", "sky blue", "slate blue",
    "spotted", "spring green", "steel blue", "striped", "tan",
    "translucent", "turquoise", "violet", "white", "yellow"
};

/* Pill effect names (for identification) */
static const char *pill_names[PILL_COUNT] = {
    "death", "a poisonous substance", "enhance Strength", "deplete Strength",
    "invigoration", "debilitation", "manual dexterity", "ineptitude",
    "glamor", "beastliness", "cleverness", "dimwittedness",
    "acumen", "stupidity", "keen sightedness", "blindness",
    "speed", "clumsiness", "dizziness", "cure blindness",
    "cure clumsiness", "cure dizziness", "neutralize poison", "good health",
    "improved hearing", "perception", "antagonism", "sleep",
    "disorientation", "cure confusion", "slowness", "flying",
    "healing", "learning", "regression", "forgetfulness",
    "memory loss", "unknown properties", "unknown properties"
};

void item_init_tables(void) {
    /* Shuffle pill color assignments */
    for (int i = 0; i < PILL_COUNT; i++)
        G->pill_color_map[i] = i;
    for (int i = PILL_COUNT - 1; i > 0; i--) {
        int j = rng(0, i);
        int tmp = G->pill_color_map[i];
        G->pill_color_map[i] = G->pill_color_map[j];
        G->pill_color_map[j] = tmp;
    }
}

const char *item_type_name(int type) {
    if (type < 0 || type >= IT_COUNT) return "something";
    return item_table[type].name;
}

char item_glyph(int type) {
    if (type < 0 || type >= IT_COUNT) return '?';
    return item_table[type].glyph;
}

int item_weight(int type) {
    if (type < 0 || type >= IT_COUNT) return 1;
    return item_table[type].weight;
}

int item_is_weapon(int type) {
    if (type < 0 || type >= IT_COUNT) return 0;
    return (item_table[type].flags & ICF_WEAPON) != 0;
}

int item_is_armor(int type) {
    if (type < 0 || type >= IT_COUNT) return 0;
    return (item_table[type].flags & ICF_ARMOR) != 0;
}

int item_is_ranged(int type) {
    if (type < 0 || type >= IT_COUNT) return 0;
    return (item_table[type].flags & ICF_RANGED) != 0;
}

static int item_is_install(int type) {
    if (type < 0 || type >= IT_COUNT) return 0;
    return (item_table[type].flags & ICF_INSTALL) != 0;
}

const char *item_name(item_t *it) {
    static char buf[128];
    if (!it) return "nothing";

    if (it->type == IT_PILL) {
        int ci = G->pill_color_map[it->pill_type % PILL_COUNT];
        const char *col = (ci < PILL_COLORS) ? pill_colors[ci] : "strange";
        if (G->pill_names_known[it->pill_type]) {
            snprintf(buf, sizeof(buf), "%s pill of %s",
                     col, pill_names[it->pill_type]);
        } else {
            snprintf(buf, sizeof(buf), "%s pill", col);
        }
        return buf;
    }

    if (it->type == IT_SECURITY_BADGE) {
        snprintf(buf, sizeof(buf), "security badge `%d'", it->badge_num);
        return buf;
    }
    if (it->type == IT_KEYCARD) {
        snprintf(buf, sizeof(buf), "keycard `%c'", it->keycard_sym);
        return buf;
    }

    const char *base = item_type_name(it->type);
    if (it->qty > 1) {
        snprintf(buf, sizeof(buf), "%d %ss", it->qty, base);
    } else {
        snprintf(buf, sizeof(buf), "%s", base);
    }

    if (it->is_active) {
        strncat(buf, " (active)", sizeof(buf) - strlen(buf) - 1);
    }
    if (it->damage_level > 0) {
        const char *dmg_desc[] = {
            "", " (slightly damaged)", " (damaged)",
            " (seriously damaged)", " (critically damaged)"
        };
        int di = it->damage_level;
        if (di > 4) di = 4;
        strncat(buf, dmg_desc[di], sizeof(buf) - strlen(buf) - 1);
    }

    return buf;
}

item_t item_create(int type) {
    item_t it;
    memset(&it, 0, sizeof(it));
    it.type = type;
    it.qty = 1;

    if (type >= 0 && type < IT_COUNT) {
        it.weight = item_table[type].weight;
        it.value = item_table[type].value;
        if (item_table[type].max_ammo > 0) {
            it.ammo = item_table[type].max_ammo;
            it.charges = item_table[type].max_ammo;
        }
    }

    if (type == IT_PILL) {
        it.pill_type = rng(0, PILL_COUNT - 1);
        it.pill_color = G->pill_color_map[it.pill_type % PILL_COUNT];
    }
    if (type == IT_COIN) {
        it.qty = rng(1, 20);
    }
    if (type == IT_SECURITY_BADGE) {
        it.badge_num = rng(100, 999);
    }
    if (type == IT_KEYCARD) {
        it.keycard_sym = 'A' + rng(0, 5);
    }
    if (type == IT_GYROJET) {
        it.qty = rng(1, 6);
    }
    if (type == IT_NEEDLE) {
        it.qty = rng(1, 10);
    }
    if (type == IT_PAINT_PELLET) {
        it.qty = rng(1, 5);
    }

    strncpy(it.name, item_type_name(type), sizeof(it.name) - 1);
    return it;
}

static int inv_add(item_t *it) {
    player_t *p = &G->player;
    if (p->inv_count >= MAX_INV) return -1;

    /* Stack stackable items */
    if (it->type == IT_COIN || it->type == IT_GYROJET ||
        it->type == IT_NEEDLE || it->type == IT_PAINT_PELLET ||
        it->type == IT_ROCK || it->type == IT_BRICK) {
        for (int i = 0; i < p->inv_count; i++) {
            if (p->inventory[i].type == it->type) {
                p->inventory[i].qty += it->qty;
                return i;
            }
        }
    }

    int slot = p->inv_count;
    p->inventory[slot] = *it;
    p->inv_count++;
    return slot;
}

static void inv_remove(int slot) {
    player_t *p = &G->player;
    if (slot < 0 || slot >= p->inv_count) return;

    for (int i = slot; i < p->inv_count - 1; i++)
        p->inventory[i] = p->inventory[i + 1];
    p->inv_count--;

    /* Fix references */
    if (p->wielded == slot) p->wielded = -1;
    else if (p->wielded > slot) p->wielded--;
    if (p->reserve == slot) p->reserve = -1;
    else if (p->reserve > slot) p->reserve--;
    if (p->worn_armor == slot) p->worn_armor = -1;
    else if (p->worn_armor > slot) p->worn_armor--;
    if (p->worn_helmet == slot) p->worn_helmet = -1;
    else if (p->worn_helmet > slot) p->worn_helmet--;
}

static void floor_add_item(item_t *it, int x, int y) {
    level_t *lev = G->levels[G->cur_level];
    if (!lev || lev->n_floor_items >= MAX_ITEMS_FLOOR) return;
    int idx = lev->n_floor_items;
    lev->floor_items[idx] = *it;
    lev->floor_item_x[idx] = x;
    lev->floor_item_y[idx] = y;
    lev->n_floor_items++;
    lev->map[y][x].items_here = 1;
}

void item_drop(int slot) {
    player_t *p = &G->player;
    if (slot < 0 || slot >= p->inv_count) {
        msg("You don't have any items!");
        return;
    }
    if (slot == p->worn_armor || slot == p->worn_helmet) {
        msg("You have to take it off first!");
        return;
    }

    item_t it = p->inventory[slot];
    int was_wielded = (slot == p->wielded);
    int was_reserve = (slot == p->reserve);
    inv_remove(slot);

    floor_add_item(&it, p->x, p->y);
    msg("You dropped %s", item_name(&it));
    if (was_wielded) msg("You drop your weapon!");
    if (was_reserve) msg("You drop your reserve!");
}

void item_pickup(void) {
    player_t *p = &G->player;
    level_t *lev = G->levels[G->cur_level];
    if (!lev) return;

    int found = 0;
    for (int i = lev->n_floor_items - 1; i >= 0; i--) {
        if (lev->floor_item_x[i] != p->x || lev->floor_item_y[i] != p->y)
            continue;

        item_t *fi = &lev->floor_items[i];
        if (item_is_install(fi->type)) continue;

        int tw = player_total_weight(p) + fi->weight * fi->qty;
        if (tw > player_max_weight(p)) {
            msg("You are carrying all you can handle");
            return;
        }
        if (p->inv_count >= MAX_INV) {
            msg("You are carrying all you can handle");
            return;
        }

        int slot = inv_add(fi);
        if (slot >= 0) {
            msg("(item %c.)", 'a' + slot);
            found = 1;
            if (fi->type == IT_LAMB) {
                G->player.has_lamb = 1;
                msg("You have found the L.A.M.B.!");
                msg("You must return to the surface!");
            }
        }

        /* Remove from floor */
        for (int j = i; j < lev->n_floor_items - 1; j++) {
            lev->floor_items[j] = lev->floor_items[j + 1];
            lev->floor_item_x[j] = lev->floor_item_x[j + 1];
            lev->floor_item_y[j] = lev->floor_item_y[j + 1];
        }
        lev->n_floor_items--;
    }

    if (!found)
        msg("There is nothing here that can be taken");

    /* Update items_here flag */
    int any = 0;
    for (int i = 0; i < lev->n_floor_items; i++) {
        if (lev->floor_item_x[i] == p->x && lev->floor_item_y[i] == p->y) {
            any = 1;
            break;
        }
    }
    lev->map[p->y][p->x].items_here = any;
}

void item_wield(int slot) {
    player_t *p = &G->player;
    if (slot < 0 || slot >= p->inv_count) {
        msg("You don't have any items!");
        return;
    }
    if (player_has_status(SF_WEBBED)) {
        msg("You can't do that while covered with webbing!");
        return;
    }
    if (slot == p->worn_armor || slot == p->worn_helmet) {
        msg("You have to take it off before you can do that!");
        return;
    }

    if (p->wielded >= 0) {
        msg("(were wielding %c.)", 'a' + p->wielded);
        /* Move current weapon to reserve */
        if (p->reserve < 0) p->reserve = p->wielded;
    }

    p->wielded = slot;
    item_t *it = &p->inventory[slot];
    p->wc = item_table[it->type].power;
    msg("Now wielding %s", item_name(it));
}

void item_wear(int slot) {
    player_t *p = &G->player;
    if (slot < 0 || slot >= p->inv_count) {
        msg("You don't have any items!");
        return;
    }
    if (player_has_status(SF_WEBBED)) {
        msg("You can't do that while covered with webbing!");
        return;
    }

    item_t *it = &p->inventory[slot];
    int flags = item_table[it->type].flags;

    if (!(flags & ICF_WEARABLE)) {
        msg("You can't wear that");
        return;
    }

    if (flags & ICF_HEADGEAR) {
        if (p->worn_helmet >= 0) {
            msg("You have to take off the %s first!",
                item_name(&p->inventory[p->worn_helmet]));
            return;
        }
        p->worn_helmet = slot;
    } else if (flags & ICF_ARMOR) {
        if (p->worn_armor >= 0) {
            msg("You have to take off the %s first!",
                item_name(&p->inventory[p->worn_armor]));
            return;
        }
        p->worn_armor = slot;
        p->ac += item_table[it->type].power;
    } else {
        /* Other wearables like gravbelt, chameleon */
        if (it->type == IT_GRAVBELT && it->charges > 0) {
            msg("You rise up into the air");
            player_add_status(SF_FLOATING, 999);
            it->is_active = 1;
        } else if (it->type == IT_CHAMELEON_CIRCUIT && it->charges > 0) {
            msg("You have trouble seeing yourself now");
            it->is_active = 1;
        } else if (it->type == IT_GAS_MASK) {
            if (p->worn_helmet >= 0) {
                msg("You have to take off the %s first!",
                    item_name(&p->inventory[p->worn_helmet]));
                return;
            }
            p->worn_helmet = slot;
        }
    }
}

void item_remove(int slot) {
    player_t *p = &G->player;
    if (slot < 0 || slot >= p->inv_count) {
        msg("You don't have any items!");
        return;
    }
    if (player_has_status(SF_WEBBED)) {
        msg("You can't do that while covered with webbing!");
        return;
    }

    if (slot == p->worn_armor) {
        item_t *it = &p->inventory[slot];
        p->ac -= item_table[it->type].power;
        if (p->ac < 0) p->ac = 0;
        p->worn_armor = -1;
        msg("(removed %c.)", 'a' + slot);
    } else if (slot == p->worn_helmet) {
        p->worn_helmet = -1;
        msg("(removed %c.)", 'a' + slot);
    } else {
        item_t *it = &p->inventory[slot];
        if (it->is_active) {
            it->is_active = 0;
            if (it->type == IT_GRAVBELT) {
                player_remove_status(SF_FLOATING);
                msg("You settle back to the floor");
            }
        } else {
            msg("You aren't wearing that");
        }
    }
}

void item_eat(int slot) {
    player_t *p = &G->player;
    if (slot < 0 || slot >= p->inv_count) {
        msg("You don't have any items!");
        return;
    }

    item_t *it = &p->inventory[slot];

    if (it->type == IT_PILL) {
        int pt = it->pill_type;
        G->pill_names_known[pt] = 1;

        switch (pt) {
        case PILL_DEATH:
            msg("Sleep overcomes you as you fall to the floor ...");
            p->hp = 0;
            p->alive = 0;
            break;
        case PILL_POISON:
            msg("Yech!  That tasted terrible.  And poisonous!");
            player_add_status(SF_POISONED, rng(15, 40));
            break;
        case PILL_ENHANCE_STR:
            msg("You feel stronger");
            p->str += rng(1, 3);
            break;
        case PILL_DEPLETE_STR:
            msg("You suddenly feel weaker");
            p->str -= rng(1, 3);
            if (p->str < 1) p->str = 1;
            break;
        case PILL_INVIGORATION:
            msg("You feel revitalized");
            p->con += rng(1, 2);
            player_heal(rng(5, 15));
            break;
        case PILL_DEBILITATION:
            msg("You suddenly don't feel very well");
            p->con -= rng(1, 2);
            if (p->con < 1) p->con = 1;
            break;
        case PILL_DEXTERITY:
            msg("You feel more dexterous");
            p->dex += rng(1, 3);
            break;
        case PILL_INEPTITUDE:
            msg("You suddenly feel less dexterous");
            p->dex -= rng(1, 3);
            if (p->dex < 1) p->dex = 1;
            break;
        case PILL_GLAMOR:
            msg("Strangely colored spots appear all over your skin");
            p->chr += rng(1, 3);
            break;
        case PILL_BEASTLINESS:
            msg("Strangely colored spots appear all over your skin");
            p->chr -= rng(1, 3);
            if (p->chr < 1) p->chr = 1;
            break;
        case PILL_CLEVERNESS:
            msg("You feel more clear-headed");
            p->wis += rng(1, 3);
            break;
        case PILL_DIMWITTEDNESS:
            msg("You suddenly feel less clever");
            p->wis -= rng(1, 3);
            if (p->wis < 1) p->wis = 1;
            break;
        case PILL_ACUMEN:
            msg("You feel more intelligent");
            p->intel += rng(1, 3);
            break;
        case PILL_STUPIDITY:
            msg("You suddenly feel a bit dim witted");
            p->intel -= rng(1, 3);
            if (p->intel < 1) p->intel = 1;
            break;
        case PILL_KEEN_SIGHT:
            msg("Your vision suddenly improves");
            player_add_status(SF_KEEN_EYED, rng(30, 80));
            break;
        case PILL_BLINDNESS:
            msg("You suddenly go blind!");
            player_add_status(SF_BLINDED, rng(10, 30));
            break;
        case PILL_SPEED:
            msg("You suddenly begin to move faster");
            player_add_status(SF_SPEEDED, rng(20, 60));
            break;
        case PILL_CLUMSINESS:
            msg("You suddenly feel clumsy");
            player_add_status(SF_CLUMSY, rng(10, 30));
            break;
        case PILL_DIZZINESS:
            msg("You suddenly feel dizzy");
            player_add_status(SF_DIZZY, rng(10, 30));
            break;
        case PILL_CURE_BLIND:
            msg("Your eyesight returns");
            player_remove_status(SF_BLINDED);
            break;
        case PILL_CURE_CLUMSY:
            msg("You no longer feel clumsy");
            player_remove_status(SF_CLUMSY);
            break;
        case PILL_CURE_DIZZY:
            msg("You no longer feel dizzy");
            player_remove_status(SF_DIZZY);
            break;
        case PILL_NEUTRALIZE_POISON:
            msg("You no longer feel poisoned");
            player_remove_status(SF_POISONED);
            break;
        case PILL_GOOD_HEALTH:
            msg("You feel healthier!");
            player_remove_status(SF_POISONED);
            player_remove_status(SF_DIZZY);
            player_remove_status(SF_CONFUSED);
            player_heal(rng(5, 15));
            break;
        case PILL_IMPROVED_HEARING:
            msg("Your hearing suddenly improves");
            player_add_status(SF_SHARP_EARED, rng(30, 80));
            break;
        case PILL_PERCEPTION:
            msg("Your perception greatly improves");
            player_add_status(SF_KEEN_EYED, rng(30, 80));
            player_add_status(SF_SHARP_EARED, rng(30, 80));
            break;
        case PILL_ANTAGONISM:
            msg("You have the feeling that you are being watched from afar");
            break;
        case PILL_SLEEP:
            msg("You fall asleep ...");
            player_add_status(SF_SLEEPING, rng(5, 20));
            break;
        case PILL_DISORIENTATION:
            msg("You suddenly feel rather confused");
            player_add_status(SF_CONFUSED, rng(10, 30));
            break;
        case PILL_CURE_CONFUSION:
            msg("You no longer feel confused");
            player_remove_status(SF_CONFUSED);
            break;
        case PILL_SLOWNESS:
            msg("You begin to move more slowly");
            player_add_status(SF_SLOWED, rng(15, 40));
            break;
        case PILL_FLYING:
            msg("You gently float upward off the floor!");
            player_add_status(SF_FLOATING, rng(20, 60));
            break;
        case PILL_HEALING:
            msg("You feel better");
            player_heal(rng(10, 30));
            break;
        case PILL_LEARNING:
            msg("You feel your competency slip away ...");
            player_gain_exp(rng(50, 200));
            break;
        case PILL_REGRESSION:
            msg("You feel your competency slip away ...");
            p->eps -= rng(20, 100);
            if (p->eps < 0) p->eps = 0;
            break;
        case PILL_FORGETFULNESS:
        case PILL_MEMORY_LOSS:
            msg("Your memories begin to slip away ...");
            break;
        default:
            msg("You feel a bit peculiar all of a sudden ...");
            break;
        }

        msg("It was a pill of %s", pill_names[pt]);

        if (it->qty > 1) {
            it->qty--;
        } else {
            inv_remove(slot);
        }
        return;
    }

    if (it->type == IT_STALE_COOKIE) {
        msg("Crunch!  Crunch!");
        msg("Yummm!  A little stale, though ...");
        player_heal(rng(1, 3));
        if (it->qty > 1) it->qty--; else inv_remove(slot);
        return;
    }

    if (it->type == IT_CORPSE) {
        int r = rng(1, 5);
        if (r == 1) msg("Munch!  Munch!\n... pretty ghoulish, ain't it?");
        else if (r == 2) msg("... you have a very sick mind");
        else if (r == 3) msg("... does your mother know about this?");
        else if (r == 4) msg("... what a gross-out");
        else msg("... thoroughly disgusting!");
        if (rng_chance(30)) {
            msg("Yuggg!  Tasted rotten ...");
            player_add_status(SF_POISONED, rng(5, 15));
        }
        if (it->qty > 1) it->qty--; else inv_remove(slot);
        return;
    }

    if (it->type == IT_BONE) {
        msg("Crunch!  Crunch!\nYum.  That was good.");
        if (it->qty > 1) it->qty--; else inv_remove(slot);
        return;
    }

    msg("It's not edible");
}

void item_activate(int slot) {
    player_t *p = &G->player;
    if (slot < 0 || slot >= p->inv_count) {
        msg("You don't have any items!");
        return;
    }
    item_t *it = &p->inventory[slot];

    if (it->is_active) {
        msg("It's already active");
        return;
    }

    if (it->type == IT_LIGHT_GLOBE) {
        if (it->charges <= 0) {
            msg("Click!\nThere is a surge of power ... but nothing happens");
            return;
        }
        it->is_active = 1;
        msg("Click!");
        return;
    }

    if (it->type == IT_GRAVBELT) {
        if (it->charges <= 0) {
            msg("Click!\nThere is a surge of power ... but nothing happens");
            return;
        }
        it->is_active = 1;
        msg("You rise up into the air");
        player_add_status(SF_FLOATING, 999);
        return;
    }

    if (it->type == IT_CHAMELEON_CIRCUIT) {
        if (it->charges <= 0) {
            msg("Click!\nThere is a surge of power ... but nothing happens");
            return;
        }
        it->is_active = 1;
        msg("You have trouble seeing yourself now");
        return;
    }

    if (it->type == IT_FORCEFIELD_PACK) {
        if (it->charges <= 0) {
            msg("Click!\nThere is a surge of power ... but nothing happens");
            return;
        }
        it->is_active = 1;
        msg("It begins to quietly hum to itself");
        return;
    }

    if (it->type == IT_SPACESUIT) {
        it->is_active = 1;
        msg("The spacesuit pressurizes with a hiss");
        return;
    }

    if (it->type == IT_PANIC_BUTTON) {
        if (it->charges <= 0) {
            msg("Click!\nNothing happens");
            return;
        }
        it->charges--;
        msg("There is a momentary surge of powerful forces around you ...");
        /* Scare nearby monsters */
        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->hp <= 0) continue;
            int d = abs(m->x - p->x) + abs(m->y - p->y);
            if (d <= 5 && !m->friendly) {
                m->panic = rng(3, 10);
            }
        }
        return;
    }

    if (it->type == IT_SCREAMER) {
        if (it->charges <= 0) {
            msg("Click!\nNothing happens");
            return;
        }
        it->charges--;
        if (rng_chance(50))
            msg("SCREEEEEEEEEEECH!!!!!\nGeez, that was loud ...\n... and disorienting!");
        else
            msg("You hear an almost subsonic whine ...");
        return;
    }

    msg("Not sure how you'd do that ...");
}

void item_deactivate(int slot) {
    player_t *p = &G->player;
    if (slot < 0 || slot >= p->inv_count) {
        msg("You don't have any items!");
        return;
    }
    item_t *it = &p->inventory[slot];

    if (!it->is_active) {
        msg("It isn't currently active");
        return;
    }

    it->is_active = 0;

    if (it->type == IT_GRAVBELT) {
        player_remove_status(SF_FLOATING);
        msg("You settle back to the floor");
        return;
    }
    if (it->type == IT_FORCEFIELD_PACK) {
        msg("It stops humming");
        return;
    }

    msg("Click!");
}

void item_examine(int slot) {
    player_t *p = &G->player;
    if (slot < 0 || slot >= p->inv_count) {
        msg("You don't have any items!");
        return;
    }
    if (player_has_status(SF_BLINDED)) {
        msg("You can't see well enough to do that!");
        return;
    }

    item_t *it = &p->inventory[slot];
    const item_info_t *info = &item_table[it->type];

    msg("It's %s", item_name(it));

    if (it->type == IT_SECURITY_BADGE)
        msg("It's a MegaTech security badge numbered `%d'", it->badge_num);
    if (it->type == IT_KEYCARD)
        msg("It's a MegaTech keycard embossed with `%c'", it->keycard_sym);

    if (info->flags & ICF_RANGED) {
        if (it->ammo > 0)
            msg("Loaded with %d round(s)", it->ammo);
        else
            msg("It's empty");
    }

    if (it->charges > 0 && (info->flags & (ICF_TOOL | ICF_LIGHT)))
        msg("A digital readout shows: %d", it->charges);

    if (it->damage_level > 0) {
        const char *desc[] = {
            "", "It looks slightly marred from general usage",
            "It looks somewhat battered ...",
            "It looks quite battered ...",
            "It looks extremely battered ..."
        };
        int di = it->damage_level;
        if (di > 4) di = 4;
        msg("%s", desc[di]);
    }

    if (info->flags & ICF_CONTAINER) {
        if (!it->is_open)
            msg("... it's closed");
        else
            msg("... it's open");
    }
}

void item_throw(int slot, int dir) {
    player_t *p = &G->player;
    if (slot < 0 || slot >= p->inv_count) {
        msg("You don't have anything to throw!");
        return;
    }
    if (player_has_status(SF_WEBBED)) {
        msg("You can't do that while covered with webbing!");
        return;
    }
    if (slot == p->worn_armor || slot == p->worn_helmet) {
        msg("You have to take it off first!");
        return;
    }

    item_t it = p->inventory[slot];
    int throw_str = p->str / 3 + 1;

    /* Remove one from inventory */
    if (p->inventory[slot].qty > 1) {
        p->inventory[slot].qty--;
        it.qty = 1;
    } else {
        int was_wielded = (slot == p->wielded);
        inv_remove(slot);
        if (was_wielded) p->wc = 0;
    }

    /* Trace projectile path */
    int px = p->x, py = p->y;

    for (int d = 0; d < throw_str; d++) {
        px += dx[dir];
        py += dy[dir];
        if (px < 0 || px >= MAP_W || py < 0 || py >= MAP_H) break;
        if (!map_passable(px, py)) {
            msg("Splat!");
            break;
        }
        monster_t *m = map_monster_at(px, py);
        if (m) {
            int dmg = item_table[it.type].power + p->str / 5;
            if (dmg < 1) dmg = 1;
            msg("You hit %s", m->name);
            monster_take_damage(m, dmg, p);
            return;
        }
    }

    /* Item lands on floor */
    floor_add_item(&it, px, py);
}

void item_fire(int dir) {
    player_t *p = &G->player;
    if (p->wielded < 0) {
        msg("You don't have a weapon in your hand");
        return;
    }

    item_t *weapon = &p->inventory[p->wielded];
    if (!item_is_ranged(weapon->type)) {
        msg("Hmmmmmm ...\nWonder how this sucker shoots ...");
        return;
    }

    if (weapon->ammo <= 0) {
        msg("Click!");
        return;
    }

    weapon->ammo--;

    /* Fire effect text */
    const char *fire_sounds[] = {
        "Foom!", "FOOM!!!", "Zzzzt!", "Zzzzzzzzzt!",
        "Spak!", "Chok!", "KaBlam!", "Brap!", "Zzzzzp!",
        "Zap!", "ZOT!", "Crackle-Zot!", "ZORCH!",
        "BADOOOOOMMMMMMMM!", "Zip!", "Phup!", "Foosh!!!",
        "Zummmmm!"
    };
    int si = weapon->type - IT_BLASTER;
    if (si < 0) si = 0;
    if (si > 17) si = 0;
    msg("%s", fire_sounds[si]);

    /* Trace beam/projectile */
    int px = p->x, py = p->y;
    int range = 8 + item_table[weapon->type].power;

    for (int d = 0; d < range; d++) {
        px += dx[dir];
        py += dy[dir];
        if (px < 0 || px >= MAP_W || py < 0 || py >= MAP_H) break;
        if (!map_passable(px, py)) {
            msg("Splat!");
            break;
        }
        monster_t *m = map_monster_at(px, py);
        if (m) {
            int dmg = combat_damage_roll(item_table[weapon->type].power, p->str);
            if (dmg < 1) dmg = 1;
            msg("... you shot %s", m->name);
            monster_take_damage(m, dmg, p);

            /* Shotgun hits adjacent monsters too */
            if (weapon->type == IT_GYROJET_SHOTGUN) {
                for (int dd = 0; dd < 8; dd++) {
                    int mx = m->x + dx[dd], my = m->y + dy[dd];
                    monster_t *m2 = map_monster_at(mx, my);
                    if (m2 && m2 != m) {
                        int dmg2 = combat_damage_roll(
                            item_table[weapon->type].power / 2, p->str);
                        monster_take_damage(m2, dmg2, p);
                    }
                }
            }
            return;
        }
    }
    msg("... you missed");
}
