/***************************************************************************
 *   Nintendo GameCube/Wii disc-header classifier                         *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 ***************************************************************************/

#include "nintendo_disc_header.h"

#define NINTENDO_WII_MAGIC 0x5d1c9ea3u
#define NINTENDO_GAMECUBE_MAGIC 0xc2339f3du

static uint32_t nintendo_read_be32(const uint8_t *data) {
    return ((uint32_t)data[0] << 24) |
           ((uint32_t)data[1] << 16) |
           ((uint32_t)data[2] << 8) |
           (uint32_t)data[3];
}

nintendo_disc_header_type nintendo_disc_header_detect(
    const uint8_t *sector,
    size_t sector_length
) {
    if (!sector || sector_length < 0x20)
        return NINTENDO_DISC_HEADER_UNKNOWN;

    if (nintendo_read_be32(sector + 0x18) == NINTENDO_WII_MAGIC)
        return NINTENDO_DISC_HEADER_WII;

    if (nintendo_read_be32(sector + 0x1c) == NINTENDO_GAMECUBE_MAGIC)
        return NINTENDO_DISC_HEADER_GAMECUBE;

    return NINTENDO_DISC_HEADER_UNKNOWN;
}

const char *nintendo_disc_header_type_name(
    nintendo_disc_header_type type
) {
    switch (type) {
        case NINTENDO_DISC_HEADER_GAMECUBE:
            return "GameCube";
        case NINTENDO_DISC_HEADER_WII:
            return "Wii";
        default:
            return "Unknown";
    }
}
