code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "compat.h"
#include "baselayer.h"
#include "build.h"
#include "common_game.h"
#include "gfx.h"
#include "globals.h"
#include "gui.h"
#include "keyboard.h"
#include "resource.h"
#include "screen.h"
#include "music.h"

Resource gGuiRes;

QFONT* pFont;

QBITMAP* pMouseCursor;

inline char ScanToAsciiShifted(int scan)
{
    if (scan < 128)
        return g_keyAsciiTableShift[scan];
    return 0;
}

int blinkClock;

void SetBlinkOn(void)
{
    blinkClock = 0;
}

void SetBlinkOff(void)
{
    blinkClock = 60;
}

char IsBlinkOn(void)
{
    return blinkClock < 60;
}

void UpdateBlinkClock(int n)
{
    blinkClock += n;
    while (blinkClock >= 100)
        blinkClock -= 100;
}

void CenterLabel(int a1, int a2, const char *a3, int a4)
{
    if (pFont)
        a2 -= pFont->at13/2;

    a1 -= gfxGetLabelLen(a3, pFont) / 2;
    gfxDrawLabel(a1, a2, a4, a3, pFont);
}

void DrawBevel(int x0, int y0, int x1, int y1, int c0, int c1)
{
    gColor = c0;
    gfxHLine(y0, x0, x1 - 2);
    gfxVLine(x0, y0 + 1, y1 - 2);
    gColor = c1;
    gfxHLine(y1 - 1, x0 + 1, x1 - 1);
    gfxVLine(x1 - 1, y0 + 1, y1 - 2);
}

void DrawRect(int x0, int y0, int x1, int y1, int c)
{
    gColor = c;
    gfxHLine(y0, x0, x1 - 1);
    gfxHLine(y1 - 1, x0, x1 - 1);
    gfxVLine(x0, y0 + 1, y1 - 2);
    gfxVLine(x1 - 1, y0 + 1, y1 - 2);
}

void DrawButtonFace(int x0, int y0, int x1, int y1, char a5)
{
    gColor = gStdColor[20];
    gfxFillBox(x0, y0, x1, y1);

    if (a5)
    {
        gColor = gStdColor[26];
        gfxHLine(y0, x0, x1 - 1);
        gfxVLine(x0, y0 + 1, y1 - 1);
        gColor = gStdColor[24];
        gfxHLine(y0 + 1, x0 + 1, x1 - 1);
        gfxVLine(x0 + 1, y0 + 2, y1 - 1);
        DrawBevel(x0+2, y0+2, x1, y1, gStdColor[19], gStdColor[22]);
    }
    else
    {
        DrawBevel(x0, y0, x1, y1, gStdColor[16], gStdColor[24]);
        DrawBevel(x0+1, y0+1, x1-1, y1-1, gStdColor[18], gStdColor[22]);
    }
}

void DrawMouseCursor(int x, int y)
{
    dassert(pMouseCursor != NULL);

    gfxDrawBitmap(pMouseCursor, x, y);
}

char GetHotKey(const char *pzLabel)
{
    for (const char* s = pzLabel; *s != 0; s++)
    {
        if (*s == '&')
            return (char)toupper(*(s+1));
    }
    return 0;
}

Label::Label(int a1, int a2, const char* a3) : Widget(a1, a2, 0, 0)
{
    at8 = strlen(a3);
    strcpy(at24, a3);
}

void Label::Paint(int x, int y, char)
{
    gfxDrawLabel(x, y, gStdColor[0], at24, pFont);
}

Container::Container(int a1, int a2, int a3, int a4) : Widget(a1, a2, a3, a4)
{
    at1e = 1;
    at24 = 0;
    at25 = MODAL_RESULT_0;

    at2e.at10 = at2e.at14 = &at2e;
    at26 = &at2e;

    at2a = NULL;
}

Container::~Container()
{
    for (Widget* pWidget = at2e.at14; pWidget != &at2e; pWidget = at2e.at14)
    {
        Remove(pWidget);
        delete pWidget;
    }
}

char Container::SetFocus(int a1)
{
    do
    {
        if (at26->at1e && ((Container*)at26)->SetFocus(a1))
            return 1;
        if (a1 > 0)
            at26 = at26->at14;
        else
            at26 = at26->at10;
        if (at26 == &at2e)
            return 0;
    } while (!at26->at1c);
    return 1;
}

void Container::Insert(Widget* widget)
{
    dassert(widget != NULL);
    widget->at10 = at2e.at10;
    widget->at14 = &at2e;
    widget->at10->at14 = widget;
    widget->at14->at10 = widget;
    widget->at18 = this;
}

void Container::Remove(Widget* widget)
{
    dassert(widget != NULL);
    widget->at10->at14 = widget->at14;
    widget->at14->at10 = widget->at10;
}

void Container::Paint(int x, int y, char a3)
{
    UNREFERENCED_PARAMETER(a3);
    for (Widget* pWidget = at2e.at14; pWidget != &at2e; pWidget = pWidget->at14)
    {
        pWidget->Paint(x + pWidget->at0, y + pWidget->at4, at26 == pWidget);
    }
}

void Container::HandleEvent(GEVENT* event)
{
    if (event->at0 & GEVENT_TYPE_MOUSE_MASK)
    {
        event->at6.mouse.at8 -= at0;
        event->at6.mouse.atc -= at4;
        if (event->at0 == 1)
        {
            at2a = NULL;
            for (Widget* pWidget = at2e.at10; pWidget != &at2e; pWidget = pWidget->at10)
            {
                if (pWidget->Inside(event->at6.mouse.at8, event->at6.mouse.atc))
                {
                    at2a = pWidget;
                    if (pWidget->at1c)
                        at26 = pWidget;
                    break;
                }
            }
        }
        if (at2a)
            at2a->HandleEvent(event);
        return;
    }
    else if (event->at0 == GEVENT_TYPE_KEYBOARD)
    {
        if (event->at6.keyboard.at2.bits.at2 && g_keyAsciiTableShift[event->at6.keyboard.at1])
        {
            for (Widget* pWidget = at2e.at10; pWidget != &at2e; pWidget = pWidget->at10)
            {
                if (pWidget->at1f == g_keyAsciiTableShift[event->at6.keyboard.at1] && pWidget->at1c)
                {
                    at26 = pWidget;
                    at26->HandleEvent(event);
                    return;
                }
            }
        }
        at26->HandleEvent(event);

        if (event->at0 != GEVENT_TYPE_NONE)
        {
            for (Widget* pWidget = at2e.at10; pWidget != &at2e; pWidget = pWidget->at10)
            {
                if (pWidget->at1f == g_keyAsciiTableShift[event->at6.keyboard.at1] && pWidget->at1c)
                {
                    at26 = pWidget;
                    at26->HandleEvent(event);
                    return;
                }
            }
        }
    }
}

void Container::EndModal(MODAL_RESULT result)
{
    if (at24)
    {
        at24 = 0;
        at25 = result;
        return;
    }
    at18->EndModal(result);
}

void Panel::Paint(int x, int y, char a3)
{
    gColor = gStdColor[20];
    gfxFillBox(x, y, x + at8, y + atc);
    int j = 0;
    for (int i = klabs(at52); i > 0; i--, j++)
    {
        if (at52 > 0)
        {
            DrawBevel(x+j,y+j,x+at8-j,y+atc-j, gStdColor[16], gStdColor[24]);
        }
        else
        {
            DrawBevel(x+j,y+j,x+at8-j,y+atc-j, gStdColor[24], gStdColor[16]);
        }
    }
    j += at56;
    for (int i = klabs(at5a); i > 0; i--, j++)
    {
        if (at5a > 0)
        {
            DrawBevel(x+j,y+j,x+at8-j,y+atc-j, gStdColor[16], gStdColor[24]);
        }
        else
        {
            DrawBevel(x+j,y+j,x+at8-j,y+atc-j, gStdColor[24], gStdColor[16]);
        }
    }
    Container::Paint(x, y, a3);
}

TitleBar::TitleBar(int a1, int a2, int a3, int a4, const char *a5) : Widget(a1, a2, a3, a4)
{
    strcpy(at24, a5);
    at124 = strlen(a5);
}

void TitleBar::Paint(int x, int y, char a3)
{
    UNREFERENCED_PARAMETER(a3);
    gColor = gStdColor[1];
    gfxFillBox(x, y, x + at8, y + atc);
    DrawBevel(x, y, x + at8, y + atc, gStdColor[9], gStdColor[30]);
    CenterLabel(x + at8 / 2, y + atc / 2, at24, gStdColor[15]);
}

void TitleBar::HandleEvent(GEVENT *event)
{
    if (event->at0 & GEVENT_TYPE_MOUSE_MASK)
    {
        if (event->at6.mouse.at4 == 0)
        {
            switch (event->at0)
            {
            case GEVENT_TYPE_MOUSE_8:
                at18->at0 += event->at6.mouse.at10;
                at18->at4 += event->at6.mouse.at14;
                event->at0 = GEVENT_TYPE_NONE;
                break;
            case GEVENT_TYPE_MOUSE_2:
                break;
            }
        }
    }
}

Win::Win(int a1, int a2, int a3, int a4, const char* a5) : Panel(a1, a2, a3, a4, 1, 1, -1)
{
    at62 = new TitleBar(3, 3, a3-6, 12, a5);
    at5e = new Container(3, 15, a3-6, a4-18);
    Insert(at62);
    Insert(at5e);
    at2a = NULL;
}

Button::Button(int a1, int a2, int a3, int a4, MODAL_RESULT a5) : Widget(a1, a2, a3, a4)
{
    at24 = a5;
    at25 = NULL;
    at29 = 0;
}

Button::Button(int a1, int a2, int a3, int a4, void (*a5)(Widget*)) : Widget(a1, a2, a3, a4)
{
    at24 = MODAL_RESULT_0;
    at25 = a5;
    at29 = 0;
}

void Button::Paint(int x, int y, char a3)
{
    UNREFERENCED_PARAMETER(a3);
    gColor = gStdColor[0];
    gfxHLine(y, x + 1, x + at8 - 2);
    gfxHLine(y + atc - 1, x + 1, x + at8 - 2);
    gfxVLine(x, y + 1, y + atc - 2);
    gfxVLine(x + at8 - 1, y + 1, y + atc - 2);
    DrawButtonFace(x + 1, y + 1, x + at8 - 1, y + atc - 1, at29);
}

void Button::HandleEvent(GEVENT* event)
{
    if (event->at0 == GEVENT_TYPE_KEYBOARD)
    {
        if (event->at6.keyboard.at0 == ' ' || ScanToAsciiShifted(event->at6.keyboard.at1) == at1f)
        {
            at29 = !at29;
            if (at25)
                at25(this);
            if (at24)
                EndModal(at24);
            event->at0 = GEVENT_TYPE_NONE;
        }
    }
    else if ((event->at0 & GEVENT_TYPE_MOUSE_MASK) && event->at6.mouse.at4 == 0)
    {
        switch (event->at0)
        {
        case GEVENT_TYPE_MOUSE_1:
            at29 = 1;
            at0 = GEVENT_TYPE_NONE;
            break;
        case GEVENT_TYPE_MOUSE_8:
            at29 = Inside(event->at6.mouse.at8, event->at6.mouse.atc);
            at0 = GEVENT_TYPE_NONE;
            break;
        case GEVENT_TYPE_MOUSE_2:
            at29 = 0;
            if (Inside(event->at6.mouse.at8, event->at6.mouse.atc))
            {
                if (at25)
                    at25(this);
                if (at24)
                    EndModal(at24);
            }
            at0 = GEVENT_TYPE_NONE;
            break;
        }
    }
}

TextButton::TextButton(int a1, int a2, int a3, int a4, const char *a5, MODAL_RESULT a6) : Button(a1, a2, a3, a4, a6)
{
    at2a = a5;
    at1f = GetHotKey(a5);
    at1c = 1;
}

void TextButton::Paint(int x, int y, char a3)
{
    gColor = gStdColor[0];
    gfxHLine(y + 1, x + 2, x + at8 - 3);
    gfxHLine(y + atc - 2, y + 2, x + at8 - 3);
    gfxVLine(x + 1, y + 2, y + atc - 3);
    gfxVLine(x + at8 - 2, y + 2, y + atc - 3);
    if (a3)
    {
        gColor = gStdColor[15];
        gfxHLine(y, x + 1, x + at8 - 2);
        gfxHLine(y + atc - 1, x + 1, x + at8 - 2);
        gfxVLine(x, y + 1, y + atc - 2);
        gfxVLine(x + at8 - 1, y + 1, y + atc - 2);
        gfxPixel(x + 1, y + 1);
        gfxPixel(x + at8 - 2, y + 1);
        gfxPixel(x + 1, y + atc - 2);
        gfxPixel(x + at8 - 2, y + atc - 2);
    }
    DrawButtonFace(x + 2, y + 2, x + at8 - 2, y + atc - 2, at29);
    if (at29)
        CenterLabel(x + at8 / 2 + 1, y + atc / 2 + 1, at2a, gStdColor[0]);
    else
        CenterLabel(x + at8 / 2, y + atc / 2, at2a, gStdColor[0]);
}

void TextButton::HandleEvent(GEVENT* event)
{
    if (event->at0 == GEVENT_TYPE_KEYBOARD && ScanToAsciiShifted(event->at6.keyboard.at1) == at1f)
    {
        at29 = !at29;
        if (at25)
            at25(this);
        if (at24)
            EndModal(at24);
        event->at0 = GEVENT_TYPE_NONE;
    }
    Button::HandleEvent(event);
}

void BitButton::Paint(int x, int y, char a3)
{
    UNREFERENCED_PARAMETER(a3);
    gColor = gStdColor[0];
    gfxHLine(y, x + 1, x + at8 - 2);
    gfxHLine(y + atc -1, x + 1, x + at8 - 2);
    gfxVLine(x, y + 1, y + atc - 2);
    gfxVLine(x + at8 - 1, y + 1, y + atc - 2);
    DrawButtonFace(x + 1, y + 1, x + at8 - 1, y + atc - 1, at29);

    int bx = x + at8 / 2;
    int by = y + atc / 2;
    QBITMAP* pQBM = (QBITMAP*)gGuiRes.Load(bitmap);

    if (at29)
        gfxDrawBitmap(pQBM, bx - pQBM->at2 / 2 + 1, by - pQBM->at4 / 2 + 1);
    else
        gfxDrawBitmap(pQBM, bx - pQBM->at2 / 2, by - pQBM->at4 / 2);
}

EditText::EditText(int a1, int a2, int a3, int a4, const char *a5) : Widget(a1,a2,a3,a4)
{
    at1c = 1;
    strcpy(at24, a5);
    at128 = at124 = strlen(a5);
    at12c = a3 / 8 - 1;
}

void EditText::Paint(int x, int y, char a3)
{
    DrawBevel(x, y, x + at8 - 1, y + atc - 1, gStdColor[24], gStdColor[16]);
    DrawRect(x + 1, y + 1, x + at8 - 2, y + atc - 2, gStdColor[0]);
    gColor = gStdColor[a3 ? 15 : 20];
    gfxFillBox(x + 2, y + 2, x + at8 - 3, y + atc - 3);
    gfxDrawText(x + 3, y + atc / 2 - 4, gStdColor[0], at24, pFont);

    if (a3 && IsBlinkOn())
    {
        gColor = gStdColor[0];
        y += atc / 2;
        gfxVLine(x + gfxGetTextNLen(at24, pFont, at128) + 3, y - 4, y + 3);
    }
}

void EditText::HandleEvent(GEVENT *event)
{
    if (event->at0 & GEVENT_TYPE_MOUSE_MASK)
    {
        if (event->at6.mouse.at4 == 0)
        {
            switch (event->at0)
            {
            case GEVENT_TYPE_MOUSE_1:
            case GEVENT_TYPE_MOUSE_8:
                at128 = gfxFindTextPos(at24, pFont, event->at6.mouse.at8 - at0);
                SetBlinkOn();
                event->at0 = GEVENT_TYPE_NONE;
                break;
            }
        }
    }
    else if (event->at0 == GEVENT_TYPE_KEYBOARD)
    {
        switch (event->at6.keyboard.at1)
        {
        case sc_BackSpace:
            if (at128 > 0)
            {
                memmove(at24+at128-1, at24+at128, at124-at128);
                at128--;
                at124--;
                at24[at124] = 0;
            }
            event->at0 = GEVENT_TYPE_NONE;
            SetBlinkOn();
            break;
        case sc_Delete:
            if (at128 < at124)
            {
                at124--;
                memmove(at24+at128, at24+at128+1, at124-at128);
                at24[at124] = 0;
            }
            event->at0 = GEVENT_TYPE_NONE;
            SetBlinkOn();
            break;
        case sc_LeftArrow:
            if (at128 > 0)
                at128--;
            event->at0 = GEVENT_TYPE_NONE;
            SetBlinkOn();
            break;
        case sc_RightArrow:
            if (at128 < at124)
                at128++;
            event->at0 = GEVENT_TYPE_NONE;
            SetBlinkOn();
            break;
        case sc_Home:
            at128 = 0;
            event->at0 = GEVENT_TYPE_NONE;
            SetBlinkOn();
            break;
        case sc_End:
            at128 = at124;
            event->at0 = GEVENT_TYPE_NONE;
            SetBlinkOn();
            break;
        default:
            if (event->at6.keyboard.at0)
            {
                if (at124 < at12c)
                {
                    memmove(at24+at128+1,at24+at128,at124-at128);
                    at24[at128++] = event->at6.keyboard.at0;
                    at124++;
                    at24[at124] = 0;
                }
                event->at0 = GEVENT_TYPE_NONE;
            }
            SetBlinkOn();
            break;
        }
    }
}

EditNumber::EditNumber(int a1, int a2, int a3, int a4, int a5) : EditText(a1, a2, a3, a4, "")
{
    at130 = a5;
    snprintf(at24, 0x100, "%i", a5);
    at128 = at124 = strlen(at24);
}

void EditNumber::HandleEvent(GEVENT *event)
{
    if (event->at0 == GEVENT_TYPE_KEYBOARD)
    {
        switch (event->at6.keyboard.at1)
        {
        case sc_Minus:
            if (at128 == 0 && at24[0] != '-' && at124 < at12c)
            {
                memmove(at24+1, at24, at124);
                at24[at128++] = '-';
                at124++;
                at24[at124] = 0;
            }
            event->at0 = GEVENT_TYPE_NONE;
            break;
        case sc_BackSpace:
            break;
        case sc_Delete:
            break;
        case sc_LeftArrow:
            break;
        case sc_RightArrow:
            break;
        case sc_Home:
            break;
        case sc_End:
            break;
        default:
            if (event->at6.keyboard.at0)
            {
                if (event->at6.keyboard.at0 >= '0' && event->at6.keyboard.at0 <= '9' && at124 < at12c)
                {
                    memmove(at24+at128+1,at24+at128,at124-at128);
                    at24[at128++] = event->at6.keyboard.at0;
                    at124++;
                    at24[at124] = 0;
                }
                event->at0 = GEVENT_TYPE_NONE;
            }
            break;
        }
    }
    EditText::HandleEvent(event);
    at130 = atoi(at24);
}

void ThumbButton::HandleEvent(GEVENT* event)
{
    if (event->at0 & GEVENT_TYPE_MOUSE_MASK)
    {
        if (event->at6.mouse.at4 == 0)
        {
            switch (event->at0)
            {
            case GEVENT_TYPE_MOUSE_8:
                at4 = ClipRange(event->at6.mouse.atc-atc/2, 10, at18->atc-10-atc);
                break;
            case GEVENT_TYPE_MOUSE_1:
                at29 = 1;
                break;
            case GEVENT_TYPE_MOUSE_2:
                at29 = 0;
                break;
            }
        }
    }
}

void ScrollButton::HandleEvent(GEVENT* event)
{
    if (event->at0 & GEVENT_TYPE_MOUSE_MASK)
    {
        if (event->at6.mouse.at4 == 0)
        {
            switch (event->at0)
            {
            case GEVENT_TYPE_MOUSE_1:
                at29 = 1;
                if (at25)
                    at25(this);
                break;
            case GEVENT_TYPE_MOUSE_8:
                at29 = Inside(event->at6.mouse.at8, event->at6.mouse.atc);
                break;
            case GEVENT_TYPE_MOUSE_4:
                if (at29 || at25)
                    at25(this);
                break;
            case GEVENT_TYPE_MOUSE_2:
                at29 = 0;
                break;
            }
        }
    }
}

void ScrollLineUp(Widget* widget)
{
    ((ScrollBar*)widget->at18)->ScrollRelative(-1);
}

void ScrollLineDown(Widget* widget)
{
    ((ScrollBar*)widget->at18)->ScrollRelative(1);
}

ScrollBar::ScrollBar(int a1, int a2, int a3, int a4, int a5, int a6) : Container(a1, a2, 13, a3)
{
    at52 = a4;
    at56 = a5;
    at6e = a6;

    at5e = new ScrollButton(1, 1, 11, 10, gGuiRes.Lookup("UPARROW", "QBM"), ScrollLineUp);
    at62 = new ScrollButton(1, a3-11, 11, 10, gGuiRes.Lookup("DNARROW", "QBM"), ScrollLineDown);
    at6a = new ThumbButton(1, 10, 11, 20);

    Insert(at5e);
    Insert(at62);
    Insert(at6a);

    at5a = 0;
}

void ScrollBar::ScrollRelative(int a1)
{
    at6a->at4 = ClipRange(at6a->at4 + a1, 10, atc - 10 - at6a->atc);
}

void ScrollBar::Paint(int x, int y, char a1)
{
    DrawBevel(x, y, x + at8, y + atc, gStdColor[24], gStdColor[16]);
    DrawRect(x + 1, y + 1, x + at8 - 1, y + atc - 1, gStdColor[0]);
    gColor = gStdColor[24];
    gfxFillBox(x + 2, y + 2, x + at8 - 2, y + atc - 2);

    Container::Paint(x, y, a1);
}

int MouseX, MouseY, MousedX, MousedY;

GEVENT_TYPE GetEvent(GEVENT* event)
{
    memset(event, 0, sizeof(GEVENT));

    char key = keyGetScan();
    if (key)
    {
        if (keystatus[sc_LeftShift])
            event->at6.keyboard.at2.bits.at3 = 1;
        if (keystatus[sc_RightShift])
            event->at6.keyboard.at2.bits.at4 = 1;
        event->at6.keyboard.at2.bits.at0 = event->at6.keyboard.at2.bits.at3 | event->at6.keyboard.at2.bits.at4;
        if (keystatus[sc_LeftControl])
            event->at6.keyboard.at2.bits.at5 = 1;
        if (keystatus[sc_RightShift])
            event->at6.keyboard.at2.bits.at6 = 1;
        event->at6.keyboard.at2.bits.at1 = event->at6.keyboard.at2.bits.at5 | event->at6.keyboard.at2.bits.at6;
        if (keystatus[sc_LeftAlt])
            event->at6.keyboard.at2.bits.at7 = 1;
        if (keystatus[sc_RightAlt])
            event->at6.keyboard.at2.bits.at8 = 1;
        event->at6.keyboard.at2.bits.at2 = event->at6.keyboard.at2.bits.at7 | event->at6.keyboard.at2.bits.at8;
        if (event->at6.keyboard.at2.bits.at2)
            event->at6.keyboard.at0 = 0;
        else if (event->at6.keyboard.at2.bits.at1)
            event->at6.keyboard.at0 = 0;
        else if (event->at6.keyboard.at2.bits.at0)
            event->at6.keyboard.at0 = key < 128 ? g_keyAsciiTableShift[key] : 0;
        else
            event->at6.keyboard.at0 = key < 128 ? g_keyAsciiTable[key] : 0;
        event->at0 = GEVENT_TYPE_KEYBOARD;
        event->at6.keyboard.at1 = key;
        if (key == sc_Escape)
            keystatus[sc_Escape] = 0;
        return event->at0;
    }

    event->at6.mouse.at10 = MousedX;
    event->at6.mouse.at14 = MousedY;
    event->at6.mouse.at8 = MouseX;
    event->at6.mouse.atc = MouseY;

    static int oldbuttons;
    static ClockTicks clickTime[5], downTime[5];
    int buttons = mouseReadButtons();

    int delta = buttons & ~oldbuttons;

    for (int i = 0, j = 1; i < 5; i++, j <<= 1)
    {
        event->at6.mouse.at4 = i;
        if (delta & j)
        {
            oldbuttons |= j;
            event->at0 = GEVENT_TYPE_MOUSE_1;
            if (clickTime[i]+60 < gFrameClock)
                event->at6.mouse.at18 = 1;
            clickTime[i] = gFrameClock;
            downTime[i] = 0;
            return event->at0;
        }
        else if (oldbuttons & j)
        {
            if (buttons & j)
            {
                downTime[i] += gFrameTicks;
                if (event->at6.mouse.at10 || event->at6.mouse.at14)
                {
                    event->at0 = GEVENT_TYPE_MOUSE_8;
                    return event->at0;
                }
                else if (downTime[i] > 60)
                {
                    downTime[i] -= 6;
                    event->at0 = GEVENT_TYPE_MOUSE_4;
                    return event->at0;
                }
            }
            else
            {
                oldbuttons &= ~j;
                event->at0 = GEVENT_TYPE_MOUSE_2;
                return event->at0;
            }
        }
    }
    return GEVENT_TYPE_NONE;
}

MODAL_RESULT ShowModal(Container* container)
{
    Container screen(0, 0, xdim, ydim);

    screen.Insert(container);

    container->at0 = (xdim - container->at8) / 2;
    container->at4 = (ydim - container->atc) / 2;

    int vc = xdim * ydim;

    while (!screen.SetFocus(1)) {}

    DICTNODE* hMouseCursor = gGuiRes.Lookup("MOUSE1", "QBM");
    dassert(hMouseCursor != NULL);
    pMouseCursor = (QBITMAP*)gGuiRes.Lock(hMouseCursor);

    DICTNODE* hFont = gGuiRes.Lookup("FONT1", "QFN");
    dassert(hFont != NULL);
    pFont = (QFONT*)gGuiRes.Lock(hFont);

    char* pFrameBackup = NULL;

    if (videoGetRenderMode() == REND_CLASSIC)
    {
        pFrameBackup = (char*)Xmalloc(vc);
        videoBeginDrawing();
        memcpy(pFrameBackup, (void*)frameplace, vc);
        videoEndDrawing();
    }

    MouseX = scale(g_mouseAbs.x, xdim, xres);
    MouseY = scale(g_mouseAbs.y, ydim, yres);

    container->at24 = 1;
    while (container->at24)
    {
        gFrameTicks = totalclock - gFrameClock;
        gFrameClock += gFrameTicks;
        UpdateBlinkClock((int)gFrameTicks);
        gameHandleEvents();
        MUSIC_Update();

        int nMouseX, nMouseY;

        nMouseX = scale(g_mouseAbs.x, xdim, xres);
        nMouseY = scale(g_mouseAbs.y, ydim, yres);

        MousedX = nMouseX - MouseX;
        MousedY = nMouseY - MouseY;

        MouseX = nMouseX;
        MouseY = nMouseY;

        GEVENT event;
        GetEvent(&event);
        if (event.at0 == GEVENT_TYPE_KEYBOARD)
        {
            switch (event.at6.keyboard.at1)
            {
            case sc_Escape:
                container->EndModal(MODAL_RESULT_2);
                continue;
            case sc_Return:
                container->EndModal(MODAL_RESULT_1);
                continue;
            case sc_Tab:
                if (event.at6.keyboard.at2.bits.at0)
                {
                    while (!screen.SetFocus(-1)) {}
                }
                else
                {
                    while (!screen.SetFocus(1)) {}
                }
                continue;
            }
        }
        screen.HandleEvent(&event);
        if (videoGetRenderMode() == REND_CLASSIC)
        {
            videoBeginDrawing();
            memcpy((void*)frameplace, pFrameBackup, vc);
            videoEndDrawing();
        }
        screen.Paint(0, 0, 0);
        DrawMouseCursor(MouseX, MouseY);
        scrNextPage();
    }

    if (videoGetRenderMode() == REND_CLASSIC)
    {
        videoBeginDrawing();
        memcpy((void*)frameplace, pFrameBackup, vc);
        videoEndDrawing();
    }
    scrNextPage();

    gGuiRes.Unlock(hMouseCursor);
    pMouseCursor = NULL;

    gGuiRes.Unlock(hFont);
    pFont = NULL;

    Xfree(pFrameBackup);

    screen.Remove(container);

    return container->at25;
}

int GetNumberBox(const char* a1, int a2, int a3)
{
    Win window(0, 0, 168, 40, a1);
    EditNumber* editnumber = new EditNumber(4, 4, 154, 16, a2);

    window.at5e->Insert(editnumber);

    ShowModal(&window);

    if (window.at25 != MODAL_RESULT_1)
        return a3;

    return editnumber->at130;
}

void Label::HandleEvent(GEVENT*)
{
}

void HeadWidget::HandleEvent(GEVENT*)
{
}

void HeadWidget::Paint(int, int, char)
{
}

HeadWidget::HeadWidget(void) : Widget(0, 0, 0, 0)
{
}

void Widget::EndModal(MODAL_RESULT a1)
{
    at18->EndModal(a1);
}

Widget::~Widget()
{
}

Widget::Widget(int a1, int a2, int a3, int a4)
{
    at1c = 0;
    at1d = 0;
    at1e = 0;
    at1f = 0;

    at0 = a1;
    at4 = a2;
    at8 = a3;
    atc = a4;

    at10 = NULL;
    at14 = NULL;
    at18 = NULL;
}

Panel::Panel(int a1, int a2, int a3, int a4, int a5, int a6, int a7) : Container(a1, a2, a3, a4)
{
    at52 = a5;
    at56 = a6;
    at5a = a7;
    at1c = 0;
}

BitButton::BitButton(int a1, int a2, int a3, int a4, DICTNODE* _bitmap, void(*a6)(Widget*)) : Button(a1, a2, a3, a4, a6)
{
    bitmap = _bitmap;
}

ThumbButton::ThumbButton(int a1, int a2, int a3, int a4) : Button(a1, a2, a3, a4, MODAL_RESULT_0)
{
}

ScrollButton::ScrollButton(int a1, int a2, int a3, int a4, DICTNODE* _bitmap, void(*a6)(Widget*)) : BitButton(a1, a2, a3, a4, _bitmap, a6)
{
}


code:
#pragma once
#include "compat.h"
#include "resource.h"

extern Resource gGuiRes;

struct GEVENT_MOUSE
{
    int at4;
    int at8;
    int atc;
    int at10;
    int at14;
    char at18; // double click
};

struct GEVENT_KEYBOARD
{
    char at0; // ascii
    char at1; // scan
    union {
        int number;
        struct {
            unsigned int at0 : 1; // shift
            unsigned int at1 : 1; // ctrl
            unsigned int at2 : 1; // alt
            unsigned int at3 : 1; // lshift
            unsigned int at4 : 1; // rshift
            unsigned int at5 : 1; // lctrl
            unsigned int at6 : 1; // rctrl
            unsigned int at7 : 1; // lalt
            unsigned int at8 : 1; // ralt
        } bits;
    } at2;
};

enum GEVENT_TYPE {
    GEVENT_TYPE_NONE = 0x00,
    GEVENT_TYPE_MOUSE_1 = 0x01,
    GEVENT_TYPE_MOUSE_2 = 0x02,
    GEVENT_TYPE_MOUSE_4 = 0x04,
    GEVENT_TYPE_MOUSE_8 = 0x08,
    GEVENT_TYPE_MOUSE_MASK = 0xFF,
    GEVENT_TYPE_KEYBOARD = 0x100
};

struct GEVENT
{
    GEVENT_TYPE at0;
    int at4;
    union {
        GEVENT_MOUSE mouse;
        GEVENT_KEYBOARD keyboard;
    } at6;
};

enum MODAL_RESULT {
    MODAL_RESULT_0 = 0,
    MODAL_RESULT_1,
    MODAL_RESULT_2
};

class Widget
{
public:
    Widget(int, int, int, int);
    virtual ~Widget();

    int at0;
    int at4;
    int at8;
    int atc;
    Widget* at10;
    Widget* at14;
    Widget* at18;
    char at1c;
    char at1d;
    char at1e;
    char at1f;
    bool Inside(int x, int y) {
        return x >= at0 && y >= at4 && x < at0+at8 && y < at4+atc;
    }
    virtual void Paint(int, int, char) = 0;
    virtual void HandleEvent(GEVENT*) = 0;
    virtual void EndModal(MODAL_RESULT);
};

class Label : public Widget
{
public:
    Label(int, int, const char*);

    char at24[0x100];

    virtual void Paint(int, int, char);
    virtual void HandleEvent(GEVENT*);
};

class HeadWidget : public Widget
{
public:
    HeadWidget();

    virtual void Paint(int, int, char);
    virtual void HandleEvent(GEVENT*);
};

class Container : public Widget
{
public:
    Container(int, int, int, int);
    virtual ~Container();
    char at24;
    MODAL_RESULT at25;
    Widget *at26;
    Widget *at2a;
    HeadWidget at2e;

    virtual void Paint(int, int, char);
    virtual void HandleEvent(GEVENT*);
    virtual void EndModal(MODAL_RESULT);
    virtual char SetFocus(int);

    void Remove(Widget*);
    void Insert(Widget*);
};

class Panel : public Container
{
public:
    int at52, at56, at5a;
    Panel(int a1, int a2, int a3, int a4, int a5, int a6, int a7);
    virtual void Paint(int, int, char);
};

class TitleBar : public Widget
{
public:
    TitleBar(int, int, int, int, const char*);
    virtual void Paint(int, int, char);
    virtual void HandleEvent(GEVENT*);
    char at24[256];
    int at124;
};

class Win : public Panel
{
public:
    Container* at5e;
    TitleBar* at62;
    Win(int, int, int, int, const char*);
};

class Button : public Widget
{
public:
    Button(int a1, int a2, int a3, int a4, MODAL_RESULT a5);
    Button(int a1, int a2, int a3, int a4, void (*a6)(Widget*));
    MODAL_RESULT at24;
    void (*at25)(Widget*);
    char at29; // pressed
    virtual void Paint(int, int, char);
    virtual void HandleEvent(GEVENT*);
};

class TextButton : public Button
{
public:
    TextButton(int, int, int, int, const char*, MODAL_RESULT);
    const char* at2a;
    virtual void Paint(int, int, char);
    virtual void HandleEvent(GEVENT*);
};

class BitButton : public Button
{
public:
    BitButton(int, int, int, int, DICTNODE *_bitmap, void (*a6)(Widget*));
    DICTNODE* bitmap;
    virtual void Paint(int, int, char);
};

class EditText : public Widget
{
public:
    EditText(int, int, int, int, const char*);
    char at24[0x100];
    int at124, at128, at12c;
    virtual void Paint(int, int, char);
    virtual void HandleEvent(GEVENT*);
};

class EditNumber : public EditText
{
public:
    EditNumber(int, int, int, int, int);
    int at130;
    virtual void HandleEvent(GEVENT*);
};

class ThumbButton : public Button
{
public:
    ThumbButton(int, int, int, int);
    virtual void HandleEvent(GEVENT*);
};

class ScrollButton : public BitButton
{
public:
    ScrollButton(int, int, int, int, DICTNODE* _bitmap, void (*a6)(Widget*));
    virtual void HandleEvent(GEVENT*);
};

class ScrollBar : public Container
{
public:
    ScrollBar(int, int, int, int, int, int);
    int at52;
    int at56;
    int at5a;
    ScrollButton* at5e;
    ScrollButton* at62;

    ThumbButton* at6a;
    int at6e;
    void ScrollRelative(int);
    virtual void Paint(int, int, char);
};

MODAL_RESULT ShowModal(Container* container);
int GetNumberBox(const char* a1, int a2, int a3);

repo_name: orochi/nblood

license: mit


code:
//-------------------------------------------------------------------------
/*
Copyright (C) 2010-2019 EDuke32 developers and contributors
Copyright (C) 2019 sirlemonhead, Nuke.YKT

This file is part of NBlood.

NBlood is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License version 2
as published by the Free Software Foundation.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/
//-------------------------------------------------------------------------
// Note: This module is based on the sirlemonhead's work

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include "common_game.h"

#include "inifile.h"
#include "misc.h"

IniFile::IniFile(const char *fileName)
{
    head.next = &head;

    // debug stuff
    // curNode = NULL;
    // anotherNode = NULL;
    //_13 = NULL;

    strcpy(this->fileName, fileName);
    Load();
}

IniFile::IniFile(void *res)
{
    head.next = &head;
    strcpy(fileName, "menus.mat");
    LoadRes(res);
}

void IniFile::LoadRes(void *res)
{
    char buffer[256];

    curNode = &head;

    while (ResReadLine(buffer, sizeof(buffer), &res) != 0)
    {
        char *ch = strchr(buffer, '\n');
        if (ch != NULL) {
            ch[0] = '\0';
        }

        // do the same for carriage return?
        ch = strchr(buffer, '\r');
        if (ch != NULL) {
            ch[0] = '\0';
        }

        char *pBuffer = buffer;

        // remove whitespace from buffer
        while (isspace(*pBuffer)) {
            pBuffer++;
        }

        curNode->next = (FNODE*)malloc(strlen(pBuffer) + sizeof(FNODE));
        dassert(curNode->next != NULL);

        anotherNode = curNode;
        curNode = curNode->next;

        strcpy(curNode->name, pBuffer);

        /*
            check for:
            ; - comment line. continue and grab a new line  (59)
            [ - start of section marker                     (91)
            ] - end of section marker                       (93)
            = - key and value seperator                     (61)
        */

        switch (*pBuffer)
        {
        case 0:
        case ';': // comment line
            break;
        case '[':
            if (!strchr(pBuffer, ']'))
            {
                free(curNode);
                curNode = anotherNode;
            }
            break;
        default:

            if (strchr(pBuffer, '=') <= pBuffer) {
                free(curNode);
                curNode = anotherNode;
            }
            break;
        }
    }

    curNode->next = &head;
}

void IniFile::Load()
{
    // char buffer[256];

    curNode = &head;

    int fp = kopen4loadfrommod(fileName, 0);
    if (fp >= 0)
    {
        int nSize = kfilelength(fp);
        void *pBuffer = Xcalloc(1, nSize + 1);
        kread(fp, pBuffer, nSize);
        LoadRes(pBuffer);
        Xfree(pBuffer);
    }
    else
        curNode->next = &head;
#if 0
    if (fp)
    {
        while (fgets(buffer, sizeof(buffer), fp) != NULL)
        {
            char *ch = strchr(buffer, '\n');
            if (ch != NULL) {
                ch[0] = '\0';
            }

            // do the same for carriage return?
            ch = strchr(buffer, '\r');
            if (ch != NULL) {
                ch[0] = '\0';
            }

            char *pBuffer = buffer;

            // remove whitespace from buffer
            while (isspace(*pBuffer)) {
                pBuffer++;
            }

            curNode->next = (FNODE*)malloc(strlen(pBuffer) + sizeof(FNODE));
            dassert(curNode->next != NULL);

            anotherNode = curNode;
            curNode = curNode->next;

            strcpy(curNode->name, pBuffer);

            /*
                check for:
                ; - comment line. continue and grab a new line  (59)
                [ - start of section marker                     (91)
                ] - end of section marker                       (93)
                = - key and value seperator                     (61)
            */

            switch (*pBuffer)
            {
            case 0:
            case ';': // comment line
                break;
            case '[':
                if (!strchr(pBuffer, ']'))
                {
                    free(curNode);
                    curNode = anotherNode;
                }
                break;
            default:

                if (strchr(pBuffer, '=') <= pBuffer) {
                    free(curNode);
                    curNode = anotherNode;
                }
                break;
            }
        }
        fclose(fp);
    }

    curNode->next = &head;
#endif
}

void IniFile::Save(void)
{
    char buffer[256];
    FILE *hFile = fopen(fileName, "w");
    dassert(hFile != NULL);
    curNode = head.next;
    while (curNode != &head)
    {
        sprintf(buffer, "%s\n", curNode->name);
        fwrite(buffer, 1, strlen(buffer), hFile);
        curNode = curNode->next;
    }
    fclose(hFile);
}

bool IniFile::FindSection(const char *section)
{
    char buffer[256];
    curNode = anotherNode = &head;
    if (section)
    {
        sprintf(buffer, "[%s]", section);
        do
        {
            anotherNode = curNode;
            curNode = curNode->next;
            if (curNode == &head)
                return false;
        } while(Bstrcasecmp(curNode->name, buffer) != 0);
    }
    return true;
}

bool IniFile::SectionExists(const char *section)
{
    return FindSection(section);
}

bool IniFile::FindKey(const char *key)
{
    anotherNode = curNode;
    curNode = curNode->next;
    while (curNode != &head)
    {
        char c = curNode->name[0];

        if (c == ';' || c == '\0') {
            anotherNode = curNode;
            curNode = curNode->next;
            continue;
        }

        if (c == '[') {
            return 0;
        }

        char *pEqual = strchr(curNode->name, '=');
        char *pEqualStart = pEqual;
        dassert(pEqual != NULL);

        // remove whitespace
        while (isspace(*(pEqual - 1))) {
            pEqual--;
        }

        c = *pEqual;
        *pEqual = '\0';

        if (strcmp(key, curNode->name) == 0)
        {
            // strings match
            *pEqual = c;
            _13 = ++pEqualStart;
            while (isspace(*_13)) {
                _13++;
            }

            return true;
        }
        *pEqual = c;
        anotherNode = curNode;
        curNode = curNode->next;
    }

    return false;
}

void IniFile::AddSection(const char *section)
{
    char buffer[256];

    if (anotherNode != &head)
    {
        FNODE *newNode = (FNODE*)malloc(sizeof(FNODE));
        dassert(newNode != NULL);

        newNode->name[0] = 0;
        newNode->next = anotherNode->next;
        anotherNode->next = newNode;
        anotherNode = newNode;
    }

    sprintf(buffer, "[%s]", section);
    FNODE *newNode = (FNODE*)malloc(strlen(buffer) + sizeof(FNODE));
    dassert(newNode != NULL);

    strcpy(newNode->name, buffer);

    newNode->next = anotherNode->next;
    anotherNode->next = newNode;
    anotherNode = newNode;
}

void IniFile::AddKeyString(const char *key, const char *value)
{
    char buffer[256];

    sprintf(buffer, "%s=%s", key, value);

    FNODE *newNode = (FNODE*)malloc(strlen(buffer) + sizeof(FNODE));
    dassert(newNode != NULL);

    strcpy(newNode->name, buffer);

    newNode->next = anotherNode->next;
    anotherNode->next = newNode;
    curNode = newNode;
}

void IniFile::ChangeKeyString(const char *key, const char *value)
{
    char buffer[256];

    sprintf(buffer, "%s=%s", key, value);

    FNODE *newNode = (FNODE*)realloc(curNode, strlen(buffer) + sizeof(FNODE));
    dassert(newNode != NULL);

    strcpy(newNode->name, buffer);

    anotherNode->next = newNode;
}

bool IniFile::KeyExists(const char *section, const char *key)
{
    if (FindSection(section) && FindKey(key))
        return true;

    return false;
}

void IniFile::PutKeyString(const char *section, const char *key, const char *value)
{
    if (FindSection(section))
    {
        if (FindKey(key))
        {
            ChangeKeyString(key, value);
            return;
        }
    }
    else
    {
        AddSection(section);
    }

    AddKeyString(key, value);
}

const char* IniFile::GetKeyString(const char *section, const char *key, const char *defaultValue)
{
    if (FindSection(section) && FindKey(key))
        return _13;
    return defaultValue;
}

void IniFile::PutKeyInt(const char *section, const char *key, int value)
{
    char buffer[256];

    // convert int to string
    sprintf(buffer,"%d",value);

    PutKeyString(section, key, buffer);
}

int IniFile::GetKeyInt(const char *section, const char *key, int defaultValue)
{
    if (FindSection(section) && FindKey(key))
    {
        // convert string to int int
        return strtol(_13, NULL, 0);
    }
    return defaultValue;
}

void IniFile::PutKeyHex(const char *section, const char *key, int value)
{
    char buffer[256] = "0x";

    // convert int to string
    sprintf(buffer,"%x",value);

    PutKeyString(section, key, buffer);
}

int IniFile::GetKeyHex(const char *section, const char *key, int defaultValue)
{
    return GetKeyInt(section, key, defaultValue);
}

bool IniFile::GetKeyBool(const char *section, const char *key, int defaultValue)
{
    return (bool)GetKeyInt(section, key, defaultValue);
}

void IniFile::RemoveKey(const char *section, const char *key)
{
    if (FindSection(section) && FindKey(key))
    {
        anotherNode->next = curNode->next;
        free(curNode);
        curNode = anotherNode->next;
    }
}

void IniFile::RemoveSection(const char *section)
{
    if (FindSection(section))
    {
        anotherNode = curNode;

        curNode = curNode->next;

        while (curNode != &head)
        {
            if (curNode->name[0] == '[') {
                return;
            }

            anotherNode->next = curNode->next;
            free(curNode);
            curNode = anotherNode->next;
        }
    }
}

IniFile::~IniFile()
{
    curNode = head.next;

    while (curNode != &head)
    {
        anotherNode = curNode;
        curNode = curNode->next;
        free(anotherNode);
    }
}


code:
//-------------------------------------------------------------------------
/*
Copyright (C) 2010-2019 EDuke32 developers and contributors
Copyright (C) 2019 sirlemonhead, Nuke.YKT

This file is part of NBlood.

NBlood is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License version 2
as published by the Free Software Foundation.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/
//-------------------------------------------------------------------------
// Note: This module is based on the sirlemonhead's work
#pragma once
struct FNODE
{
    FNODE *next;
    char name[1];
};

// 161 bytes
class IniFile
{
public:
    IniFile(const char *fileName);
    IniFile(void *res);
    ~IniFile();

    void Save(void);
    bool FindSection(const char *section);
    bool SectionExists(const char *section);
    bool FindKey(const char *key);
    void AddSection(const char *section);
    void AddKeyString(const char *key, const char *value);
    void ChangeKeyString(const char *key, const char *value);
    bool KeyExists(const char *section, const char *key);
    void PutKeyString(const char *section, const char *key, const char *value);
    const char* GetKeyString(const char *section, const char *key, const char *defaultValue);
    void PutKeyInt(const char *section, const char *key, const int value);
    int GetKeyInt(const char *section, const char *key, int defaultValue);
    void PutKeyHex(const char *section, const char *key, int value);
    int GetKeyHex(const char *section, const char *key, int defaultValue);
    bool GetKeyBool(const char *section, const char *key, int defaultValue);
    void RemoveKey(const char *section, const char *key);
    void RemoveSection(const char *section);

private:
    FNODE head;
    FNODE *curNode;
    FNODE *anotherNode;

    char *_13;

    char fileName[BMAX_PATH]; // watcom maxpath

    void LoadRes(void *);
    void Load();
};


code:
//-------------------------------------------------------------------------
/*
Copyright (C) 2010-2019 EDuke32 developers and contributors
Copyright (C) 2019 Nuke.YKT

This file is part of NBlood.

NBlood is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License version 2
as published by the Free Software Foundation.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/
//-------------------------------------------------------------------------
#include <stdlib.h>
#include <string.h>
#include "compat.h"
#include "common_game.h"
#include "iob.h"

IOBuffer::IOBuffer(int _nRemain, char *_pBuffer)
{
    nRemain = _nRemain;
    pBuffer =_pBuffer;
}

void IOBuffer::Read(void *pData, int nSize)
{
    if (nSize <= nRemain)
    {
        memcpy(pData, pBuffer, nSize);
        nRemain -= nSize;
        pBuffer += nSize;
    }
    else
    {
        ThrowError("Read buffer overflow");
    }
}

void IOBuffer::Write(void *pData, int nSize)
{
    if (nSize <= nRemain)
    {
        memcpy(pBuffer, pData, nSize);
        nRemain -= nSize;
        pBuffer += nSize;
    }
    else
    {
        ThrowError("Write buffer overflow");
    }
}

void IOBuffer::Skip(int nSize)
{
    if (nSize <= nRemain)
    {
        nRemain -= nSize;
        pBuffer += nSize;
    }
    else
    {
        ThrowError("Skip overflow");
    }
}


code:
//-------------------------------------------------------------------------
/*
Copyright (C) 2010-2019 EDuke32 developers and contributors
Copyright (C) 2019 Nuke.YKT

This file is part of NBlood.

NBlood is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License version 2
as published by the Free Software Foundation.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/
//-------------------------------------------------------------------------
#pragma once

class IOBuffer
{
public:
    IOBuffer(int _nRemain, char *pBuffer);
    int nRemain;
    char *pBuffer;
    void Read(void *, int);
    void Write(void *, int);
    void Skip(int);
};


code:
//-------------------------------------------------------------------------
/*
Copyright (C) 2010 EDuke32 developers and contributors

This file is part of EDuke32.

EDuke32 is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License version 2
as published by the Free Software Foundation.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/
//-------------------------------------------------------------------------

#ifndef KEYS_H

#define KEYS_H

   #define NUM_CODES     128

   #define ESC    0x1B
   #define ENTER  0x0D

   #define KEYSC_ESC	  0x01
   #define KEYSC_1  	  0x02
   #define KEYSC_2  	  0x03
   #define KEYSC_3  	  0x04
   #define KEYSC_4  	  0x05
   #define KEYSC_5  	  0x06
   #define KEYSC_6  	  0x07
   #define KEYSC_7  	  0x08
   #define KEYSC_8  	  0x09
   #define KEYSC_9  	  0x0a
   #define KEYSC_0  	  0x0b
   #define KEYSC_DASH     0x0c
   #define KEYSC_EQUAL    0x0d

   #define KEYSC_BS 	  0x0e
   #define KEYSC_TAB	  0x0f
   #define KEYSC_Q  	  0x10
   #define KEYSC_W  	  0x11
   #define KEYSC_E  	  0x12
   #define KEYSC_R  	  0x13
   #define KEYSC_T  	  0x14
   #define KEYSC_Y  	  0x15
   #define KEYSC_U  	  0x16
   #define KEYSC_I  	  0x17
   #define KEYSC_O  	  0x18
   #define KEYSC_P  	  0x19
   #define KEYSC_LBRACK   0x1a
   #define KEYSC_RBRACK   0x1b
   #define KEYSC_ENTER    0x1c

   #define KEYSC_LCTRL    0x1d
   #define KEYSC_A  	  0x1e
   #define KEYSC_S  	  0x1f
   #define KEYSC_D  	  0x20
   #define KEYSC_F  	  0x21
   #define KEYSC_G  	  0x22
   #define KEYSC_H  	  0x23
   #define KEYSC_J  	  0x24
   #define KEYSC_K  	  0x25
   #define KEYSC_L  	  0x26
   #define KEYSC_SEMI     0x27
   #define KEYSC_QUOTE    0x28
   #define KEYSC_BQUOTE   0x29
   #define KEYSC_TILDE    0x29

   #define KEYSC_LSHIFT   0x2a
   #define KEYSC_BSLASH   0x2b
   #define KEYSC_Z  	  0x2c
   #define KEYSC_X  	  0x2d
   #define KEYSC_C  	  0x2e
   #define KEYSC_V  	  0x2f
   #define KEYSC_B  	  0x30
   #define KEYSC_N  	  0x31
   #define KEYSC_M  	  0x32
   #define KEYSC_COMMA    0x33
   #define KEYSC_PERIOD   0x34
   #define KEYSC_SLASH    0x35
   #define KEYSC_RSHIFT   0x36
   #define KEYSC_gSTAR    0x37

   #define KEYSC_LALT     0x38
   #define KEYSC_SPACE    0x39
   #define KEYSC_CAPS     0x3a

   #define KEYSC_F1 	  0x3b
   #define KEYSC_F2 	  0x3c
   #define KEYSC_F3 	  0x3d
   #define KEYSC_F4 	  0x3e
   #define KEYSC_F5 	  0x3f
   #define KEYSC_F6 	  0x40
   #define KEYSC_F7 	  0x41
   #define KEYSC_F8 	  0x42
   #define KEYSC_F9 	  0x43
   #define KEYSC_F10	  0x44

   #define KEYSC_gNUM     0x45
   #define KEYSC_SCROLL   0x46

   #define KEYSC_gHOME    0x47
   #define KEYSC_gUP	  0x48
   #define KEYSC_gPGUP    0x49
   #define KEYSC_gMINUS   0x4a
   #define KEYSC_gLEFT    0x4b
   #define KEYSC_gKP5     0x4c
   #define KEYSC_gRIGHT   0x4d
   #define KEYSC_gPLUS    0x4e
   #define KEYSC_gEND     0x4f
   #define KEYSC_gDOWN    0x50
   #define KEYSC_gPGDN    0x51
   #define KEYSC_gINS     0x52
   #define KEYSC_gDEL     0x53

   #define KEYSC_F11    0x57
   #define KEYSC_F12    0x58

   #define KEYSC_gENTER   0x9C
   #define KEYSC_RCTRL    0x9D
   #define KEYSC_gSLASH   0xB5
   #define KEYSC_RALT     0xB8
   #define KEYSC_PRTSCN   0xB7
   #define KEYSC_PAUSE    0xC5
   #define KEYSC_HOME     0xC7
   #define KEYSC_UP 	  0xC8
   #define KEYSC_PGUP     0xC9
   #define KEYSC_LEFT     0xCB
   #define KEYSC_RIGHT    0xCD
   #define KEYSC_END	  0xCF
   #define KEYSC_DOWN     0xD0
   #define KEYSC_PGDN     0xD1
   #define KEYSC_INSERT   0xD2
   #define KEYSC_DELETE   0xD3

    #define asc_Esc         27
    #define asc_Enter       13
    #define asc_Space       32

#endif


code:
//-------------------------------------------------------------------------
/*
Copyright (C) 2010-2019 EDuke32 developers and contributors
Copyright (C) 2019 Nuke.YKT

This file is part of NBlood.

NBlood is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License version 2
as published by the Free Software Foundation.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/
//-------------------------------------------------------------------------
#include <stdlib.h>
#include <string.h>
#include "compat.h"
#include "common_game.h"

#include "asound.h"
#include "blood.h"
#include "config.h"
#include "credits.h"
#include "endgame.h"
#include "inifile.h"
#include "levels.h"
#include "loadsave.h"
#include "messages.h"
#include "network.h"
#include "screen.h"
#include "seq.h"
#include "sound.h"
#include "sfx.h"
#include "view.h"
#include "eventq.h"

GAMEOPTIONS gGameOptions;

GAMEOPTIONS gSingleGameOptions = {
    0, 2, 0, 0, "", "", 2, "", "", 0, 0, 0, 1, 0, 0, 0, 0, 0, 2, 3600, 1800, 1800, 7200
};

EPISODEINFO gEpisodeInfo[kMaxEpisodes+1];

int gSkill = 2;
int gEpisodeCount;
int gNextLevel;
bool gGameStarted;

int gLevelTime;

char BloodIniFile[BMAX_PATH] = "BLOOD.INI";
char BloodIniPre[BMAX_PATH];
bool bINIOverride = false;
IniFile *BloodINI;

void levelInitINI(const char *pzIni)
{
    int fp = kopen4loadfrommod(pzIni, 0);
    if (fp < 0)
        ThrowError("Initialization: %s does not exist", pzIni);
    kclose(fp);
    BloodINI = new IniFile(pzIni);
    Bstrncpy(BloodIniFile, pzIni, BMAX_PATH);
    Bstrncpy(BloodIniPre, pzIni, BMAX_PATH);
    ChangeExtension(BloodIniPre, "");
}

void levelOverrideINI(const char *pzIni)
{
    bINIOverride = true;
    strcpy(BloodIniFile, pzIni);
}

void levelPlayIntroScene(int nEpisode)
{
    gGameOptions.uGameFlags &= ~kGameFlagPlayIntro;
    sndStopSong();
    sndKillAllSounds();
    sfxKillAllSounds();
    ambKillAll();
    seqKillAll();
    EPISODEINFO *pEpisode = &gEpisodeInfo[nEpisode];
    credPlaySmk(pEpisode->cutsceneASmkPath, pEpisode->cutsceneAWavPath, pEpisode->cutsceneAWavRsrcID);
    scrSetDac();
    viewResizeView(gViewSize);
    credReset();
    scrSetDac();
    ControlInfo info;
    CONTROL_GetInput(&info); // clear mouse and all input after cutscene has finished playing
    ctrlClearAllInput();
}

void levelPlayEndScene(int nEpisode)
{
    gGameOptions.uGameFlags &= ~kGameFlagPlayOutro;
    sndStopSong();
    sndKillAllSounds();
    sfxKillAllSounds();
    ambKillAll();
    seqKillAll();
    EPISODEINFO *pEpisode = &gEpisodeInfo[nEpisode];
    credPlaySmk(pEpisode->cutsceneBSmkPath, pEpisode->cutsceneBWavPath, pEpisode->cutsceneBWavRsrcID);
    scrSetDac();
    viewResizeView(gViewSize);
    credReset();
    scrSetDac();
}

void levelClearSecrets(void)
{
    gSecretMgr.Clear();
}

void levelSetupSecret(int nCount)
{
    gSecretMgr.SetCount(nCount);
}

void levelTriggerSecret(int nSecret)
{
    gSecretMgr.Found(nSecret);
}

void CheckSectionAbend(const char *pzSection)
{
    if (!pzSection || !BloodINI->SectionExists(pzSection))
        ThrowError("Section [%s] expected in BLOOD.INI", pzSection);
}

void CheckKeyAbend(const char *pzSection, const char *pzKey)
{
    dassert(pzSection != NULL);

    if (!pzKey || !BloodINI->KeyExists(pzSection, pzKey))
        ThrowError("Key %s expected in section [%s] of BLOOD.INI", pzKey, pzSection);
}

LEVELINFO * levelGetInfoPtr(int nEpisode, int nLevel)
{
    dassert(nEpisode >= 0 && nEpisode < gEpisodeCount);
    EPISODEINFO *pEpisodeInfo = &gEpisodeInfo[nEpisode];
    dassert(nLevel >= 0 && nLevel < pEpisodeInfo->nLevels);
    return &pEpisodeInfo->levelsInfo[nLevel];
}

char * levelGetFilename(int nEpisode, int nLevel)
{
    dassert(nEpisode >= 0 && nEpisode < gEpisodeCount);
    EPISODEINFO *pEpisodeInfo = &gEpisodeInfo[nEpisode];
    dassert(nLevel >= 0 && nLevel < pEpisodeInfo->nLevels);
    return pEpisodeInfo->levelsInfo[nLevel].Filename;
}

char * levelGetMessage(int nMessage)
{
    int nEpisode = gGameOptions.nEpisode;
    int nLevel = gGameOptions.nLevel;
    dassert(nMessage < kMaxMessages);
    char *pMessage = gEpisodeInfo[nEpisode].levelsInfo[nLevel].Messages[nMessage];
    if (*pMessage == 0)
        return NULL;
    return pMessage;
}

char * levelGetTitle(void)
{
    int nEpisode = gGameOptions.nEpisode;
    int nLevel = gGameOptions.nLevel;
    char *pTitle = gEpisodeInfo[nEpisode].levelsInfo[nLevel].Title;
    if (*pTitle == 0)
        return NULL;
    return pTitle;
}

char * levelGetAuthor(void)
{
    int nEpisode = gGameOptions.nEpisode;
    int nLevel = gGameOptions.nLevel;
    char *pAuthor = gEpisodeInfo[nEpisode].levelsInfo[nLevel].Author;
    if (*pAuthor == 0)
        return NULL;
    return pAuthor;
}

void levelSetupOptions(int nEpisode, int nLevel)
{
    gGameOptions.nEpisode = nEpisode;
    gGameOptions.nLevel = nLevel;
    strcpy(gGameOptions.zLevelName, gEpisodeInfo[nEpisode].levelsInfo[nLevel].Filename);
    gGameOptions.uMapCRC = dbReadMapCRC(gGameOptions.zLevelName);
    // strcpy(gGameOptions.zLevelSong, gEpisodeInfo[nEpisode].at28[nLevel].atd0);
    gGameOptions.nTrackNumber = gEpisodeInfo[nEpisode].levelsInfo[nLevel].SongId;
}

void levelLoadMapInfo(IniFile *pIni, LEVELINFO *pLevelInfo, const char *pzSection)
{
    char buffer[16];
    strncpy(pLevelInfo->Title, pIni->GetKeyString(pzSection, "Title", pLevelInfo->Filename), 31);
    strncpy(pLevelInfo->Author, pIni->GetKeyString(pzSection, "Author", ""), 31);
    strncpy(pLevelInfo->Song, pIni->GetKeyString(pzSection, "Song", ""), BMAX_PATH);
    pLevelInfo->SongId = pIni->GetKeyInt(pzSection, "Track", -1);
    pLevelInfo->EndingA = pIni->GetKeyInt(pzSection, "EndingA", -1);
    pLevelInfo->EndingB = pIni->GetKeyInt(pzSection, "EndingB", -1);
    pLevelInfo->Fog = pIni->GetKeyInt(pzSection, "Fog", -0);
    pLevelInfo->Weather = pIni->GetKeyInt(pzSection, "Weather", -0);
    for (int i = 0; i < kMaxMessages; i++)
    {
        sprintf(buffer, "Message%d", i+1);
        strncpy(pLevelInfo->Messages[i], pIni->GetKeyString(pzSection, buffer, ""), 63);
    }
}

extern void MenuSetupEpisodeInfo(void);

void levelLoadDefaults(void)
{
    char buffer[64];
    char buffer2[16];
    levelInitINI(pINISelected->zName);
    memset(gEpisodeInfo, 0, sizeof(gEpisodeInfo));
    strncpy(gEpisodeInfo[MUS_INTRO/kMaxLevels].levelsInfo[MUS_INTRO%kMaxLevels].Song, "PESTIS", BMAX_PATH);
    int i;
    for (i = 0; i < kMaxEpisodes; i++)
    {
        sprintf(buffer, "Episode%d", i+1);
        if (!BloodINI->SectionExists(buffer))
            break;
        EPISODEINFO *pEpisodeInfo = &gEpisodeInfo[i];
        strncpy(pEpisodeInfo->title, BloodINI->GetKeyString(buffer, "Title", buffer), 31);
        strncpy(pEpisodeInfo->cutsceneASmkPath, BloodINI->GetKeyString(buffer, "CutSceneA", ""), BMAX_PATH);
        pEpisodeInfo->cutsceneAWavRsrcID = BloodINI->GetKeyInt(buffer, "CutWavA", -1);
        if (pEpisodeInfo->cutsceneAWavRsrcID == 0)
            strncpy(pEpisodeInfo->cutsceneAWavPath, BloodINI->GetKeyString(buffer, "CutWavA", ""), BMAX_PATH);
        else
            pEpisodeInfo->cutsceneAWavPath[0] = 0;
        strncpy(pEpisodeInfo->cutsceneBSmkPath, BloodINI->GetKeyString(buffer, "CutSceneB", ""), BMAX_PATH);
        pEpisodeInfo->cutsceneBWavRsrcID = BloodINI->GetKeyInt(buffer, "CutWavB", -1);
        if (pEpisodeInfo->cutsceneBWavRsrcID == 0)
            strncpy(pEpisodeInfo->cutsceneBWavPath, BloodINI->GetKeyString(buffer, "CutWavB", ""), BMAX_PATH);
        else
            pEpisodeInfo->cutsceneBWavPath[0] = 0;

        pEpisodeInfo->bloodbath = BloodINI->GetKeyInt(buffer, "BloodBathOnly", 0);
        pEpisodeInfo->cutALevel = BloodINI->GetKeyInt(buffer, "CutSceneALevel", 0);
        if (pEpisodeInfo->cutALevel > 0)
            pEpisodeInfo->cutALevel--;
        int j;
        for (j = 0; j < kMaxLevels; j++)
        {
            LEVELINFO *pLevelInfo = &pEpisodeInfo->levelsInfo[j];
            sprintf(buffer2, "Map%d", j+1);
            if (!BloodINI->KeyExists(buffer, buffer2))
                break;
            const char *pMap = BloodINI->GetKeyString(buffer, buffer2, NULL);
            CheckSectionAbend(pMap);
            strncpy(pLevelInfo->Filename, pMap, BMAX_PATH);
            levelLoadMapInfo(BloodINI, pLevelInfo, pMap);
        }
        pEpisodeInfo->nLevels = j;
    }
    gEpisodeCount = i;
    MenuSetupEpisodeInfo();
}

void levelAddUserMap(const char *pzMap)
{
    char buffer[BMAX_PATH];
    //strcpy(buffer, g_modDir);
    strncpy(buffer, pzMap, BMAX_PATH);
    ChangeExtension(buffer, ".DEF");

    IniFile UserINI(buffer);
    int nEpisode = ClipRange(UserINI.GetKeyInt(NULL, "Episode", 0), 0, 5);
    EPISODEINFO *pEpisodeInfo = &gEpisodeInfo[nEpisode];
    int nLevel = ClipRange(UserINI.GetKeyInt(NULL, "Level", pEpisodeInfo->nLevels), 0, 15);
    if (nLevel >= pEpisodeInfo->nLevels)
    {
        if (pEpisodeInfo->nLevels == 0)
        {
            gEpisodeCount++;
            sprintf(pEpisodeInfo->title, "Episode %d", nEpisode);
        }
        nLevel = pEpisodeInfo->nLevels++;
    }
    LEVELINFO *pLevelInfo = &pEpisodeInfo->levelsInfo[nLevel];
    ChangeExtension(buffer, "");
    strncpy(pLevelInfo->Filename, buffer, BMAX_PATH);
    levelLoadMapInfo(&UserINI, pLevelInfo, NULL);
    gGameOptions.nEpisode = nEpisode;
    gGameOptions.nLevel = nLevel;
    gGameOptions.uMapCRC = dbReadMapCRC(pLevelInfo->Filename);
    strcpy(gGameOptions.zLevelName, pLevelInfo->Filename);
    MenuSetupEpisodeInfo();
}

void levelGetNextLevels(int nEpisode, int nLevel, int *pnEndingA, int *pnEndingB)
{
    dassert(pnEndingA != NULL && pnEndingB != NULL);
    LEVELINFO *pLevelInfo = &gEpisodeInfo[nEpisode].levelsInfo[nLevel];
    int nEndingA = pLevelInfo->EndingA;
    if (nEndingA >= 0)
        nEndingA--;
    int nEndingB = pLevelInfo->EndingB;
    if (nEndingB >= 0)
        nEndingB--;
    *pnEndingA = nEndingA;
    *pnEndingB = nEndingB;
}

void levelEndLevel(int nExitType)
{
    int nEndingA, nEndingB;
    EPISODEINFO *pEpisodeInfo = &gEpisodeInfo[gGameOptions.nEpisode];
    gGameOptions.uGameFlags |= kGameFlagContinuing;
    levelGetNextLevels(gGameOptions.nEpisode, gGameOptions.nLevel, &nEndingA, &nEndingB);
    switch (nExitType)
    {
    case kLevelExitNormal:
        if (nEndingA == -1) // no more levels (reached end of episode), trigger credits
        {
            if (pEpisodeInfo->cutsceneBSmkPath[0]) // if ending cutscene file present, set to play movie
                gGameOptions.uGameFlags |= kGameFlagPlayOutro;
            gGameOptions.nLevel = 0;
            gGameOptions.uGameFlags |= kGameFlagEnding;
        }
        else
            gNextLevel = nEndingA;
        break;
    case kLevelExitSecret:
        if (nEndingB == -1) // no more levels (reached end of episode), trigger credits
        {
            if (gGameOptions.nEpisode + 1 < gEpisodeCount)
            {
                if (pEpisodeInfo->cutsceneBSmkPath[0]) // if ending cutscene file present, set to play movie
                    gGameOptions.uGameFlags |= kGameFlagPlayOutro;
                gGameOptions.nLevel = 0;
                gGameOptions.uGameFlags |= kGameFlagEnding;
            }
            else
            {
                gGameOptions.nLevel = 0;
                gGameOptions.uGameFlags |= kGameFlagContinuing;
            }
        }
        else
            gNextLevel = nEndingB;
        break;
    }
}

void levelRestart(void)
{
    levelSetupOptions(gGameOptions.nEpisode, gGameOptions.nLevel);
    gStartNewGame = true;
}

int levelGetMusicIdx(const char *str)
{
    int32_t lev, ep;
    signed char b1, b2;

    int numMatches = sscanf(str, "%c%d%c%d", &b1, &ep, &b2, &lev);

    if (numMatches != 4 || Btoupper(b1) != 'E' || Btoupper(b2) != 'L')
        return -1;

    if ((unsigned)--lev >= kMaxLevels || (unsigned)--ep >= kMaxEpisodes)
        return -2;

    return (ep * kMaxLevels) + lev;
}

bool levelTryPlayMusic(int nEpisode, int nLevel, bool bSetLevelSong)
{
    char buffer[BMAX_PATH];
    if (CDAudioToggle && gEpisodeInfo[nEpisode].levelsInfo[nLevel].SongId > 0)
        snprintf(buffer, BMAX_PATH, "blood%02i.ogg", gEpisodeInfo[nEpisode].levelsInfo[nLevel].SongId);
    else
        strncpy(buffer, gEpisodeInfo[nEpisode].levelsInfo[nLevel].Song, BMAX_PATH);
    bool bReturn = !!sndPlaySong(buffer, true);
    if (!bReturn || bSetLevelSong)
        strncpy(gGameOptions.zLevelSong, buffer, BMAX_PATH);
    return bReturn;
}

void levelTryPlayMusicOrNothing(int nEpisode, int nLevel)
{
    if (levelTryPlayMusic(nEpisode, nLevel, true))
        sndStopSong();
}

class LevelsLoadSave : public LoadSave
{
    virtual void Load(void);
    virtual void Save(void);
};

static LevelsLoadSave *myLoadSave;

void LevelsLoadSave::Load(void)
{
    Read(&gNextLevel, sizeof(gNextLevel));
    Read(&gGameOptions, sizeof(gGameOptions));
    Read(&gGameStarted, sizeof(gGameStarted));
}

void LevelsLoadSave::Save(void)
{
    Write(&gNextLevel, sizeof(gNextLevel));
    Write(&gGameOptions, sizeof(gGameOptions));
    Write(&gGameStarted, sizeof(gGameStarted));
}

void LevelsLoadSaveConstruct(void)
{
    myLoadSave = new LevelsLoadSave();
}


code:
//-------------------------------------------------------------------------
/*
Copyright (C) 2010-2019 EDuke32 developers and contributors
Copyright (C) 2019 Nuke.YKT

This file is part of NBlood.

NBlood is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License version 2
as published by the Free Software Foundation.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/
//-------------------------------------------------------------------------
#pragma once
#include "common_game.h"
#include "inifile.h"

#define kMaxMessages 32
#define kMaxEpisodes 7
#define kMaxLevels 16

#pragma pack(push, 1)

struct GAMEOPTIONS {
    char nGameType;
    char nDifficulty;
    int nEpisode;
    int nLevel;
    char zLevelName[BMAX_PATH];
    char zLevelSong[BMAX_PATH];
    int nTrackNumber; //at12a;
    char szSaveGameName[BMAX_PATH];
    char szUserGameName[BMAX_PATH];
    short nSaveGameSlot;
    int picEntry;
    unsigned int uMapCRC;
    char nMonsterSettings;
    int uGameFlags;
    int uNetGameFlags;
    char nWeaponSettings;
    char nItemSettings;
    char nRespawnSettings;
    char nTeamSettings;
    int nMonsterRespawnTime;
    int nWeaponRespawnTime;
    int nItemRespawnTime;
    int nSpecialRespawnTime;
    int weaponsV10x;
    bool bFriendlyFire;
    PLAYERKEYSMODE bPlayerKeys;
    char szUserMap[BMAX_PATH];
};

#pragma pack(pop)

enum {
    kLevelExitNormal = 0,
    kLevelExitSecret
};

enum {
    MUS_FIRST_SPECIAL = kMaxEpisodes*kMaxLevels,

    MUS_INTRO = MUS_FIRST_SPECIAL,
    MUS_LOADING = MUS_FIRST_SPECIAL + 1,
};

struct LEVELINFO
{
    char Filename[BMAX_PATH];
    char Title[32];
    char Author[32];
    char Song[BMAX_PATH];
    int SongId;
    int EndingA;
    int EndingB;
    char Messages[kMaxMessages][64];
    char Fog;
    char Weather;
}; // 0x8ee bytes

struct EPISODEINFO
{
    char title[32];
    int nLevels;
    unsigned int bloodbath : 1;
    unsigned int cutALevel : 4;
    LEVELINFO levelsInfo[kMaxLevels];
    char cutsceneASmkPath[BMAX_PATH];
    char cutsceneBSmkPath[BMAX_PATH];
    int cutsceneAWavRsrcID;
    int cutsceneBWavRsrcID;
    char cutsceneAWavPath[BMAX_PATH];
    char cutsceneBWavPath[BMAX_PATH];
};

extern EPISODEINFO gEpisodeInfo[];
extern GAMEOPTIONS gSingleGameOptions;
extern GAMEOPTIONS gGameOptions;
extern int gSkill;
extern char BloodIniFile[];
extern char BloodIniPre[];
extern bool bINIOverride;
extern int gEpisodeCount;
extern int gNextLevel;
extern bool gGameStarted;
extern int gLevelTime;

void levelInitINI(const char *pzIni);
void levelOverrideINI(const char *pzIni);
void levelPlayIntroScene(int nEpisode);
void levelPlayEndScene(int nEpisode);
void levelClearSecrets(void);
void levelSetupSecret(int nCount);
void levelTriggerSecret(int nSecret);
void CheckSectionAbend(const char *pzSection);
void CheckKeyAbend(const char *pzSection, const char *pzKey);
LEVELINFO * levelGetInfoPtr(int nEpisode, int nLevel);
char * levelGetFilename(int nEpisode, int nLevel);
char * levelGetMessage(int nMessage);
char * levelGetTitle(void);
char * levelGetAuthor(void);
void levelSetupOptions(int nEpisode, int nLevel);
void levelLoadMapInfo(IniFile *pIni, LEVELINFO *pLevelInfo, const char *pzSection);
void levelLoadDefaults(void);
void levelAddUserMap(const char *pzMap);
// EndingA is normal ending, EndingB is secret level
void levelGetNextLevels(int nEpisode, int nLevel, int *pnEndingA, int *pnEndingB);
// arg: 0 is normal exit, 1 is secret level
void levelEndLevel(int nExitType);
void levelRestart(void);
int levelGetMusicIdx(const char *str);
bool levelTryPlayMusic(int nEpisode, int nlevel, bool bSetLevelSong = false);
void levelTryPlayMusicOrNothing(int nEpisode, int nLevel);


code:
//-------------------------------------------------------------------------
/*
Copyright (C) 2010-2019 EDuke32 developers and contributors
Copyright (C) 2019 Nuke.YKT

This file is part of NBlood.

NBlood is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License version 2
as published by the Free Software Foundation.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/
//-------------------------------------------------------------------------
#include <stdio.h>
#include "build.h"
#include "compat.h"
#include "mmulti.h"
#include "common_game.h"
#include "config.h"
#include "ai.h"
#include "asound.h"
#include "blood.h"
#include "demo.h"
#include "globals.h"
#include "db.h"
#include "messages.h"
#include "menu.h"
#include "network.h"
#include "loadsave.h"
#include "resource.h"
#include "screen.h"
#include "sectorfx.h"
#include "seq.h"
#include "sfx.h"
#include "sound.h"
#include "view.h"
#ifdef NOONE_EXTENSIONS
#include "nnexts.h"
#endif

GAMEOPTIONS gSaveGameOptions[10];
char *gSaveGamePic[10];
unsigned int gSavedOffset = 0;

unsigned int dword_27AA38 = 0;
unsigned int dword_27AA3C = 0;
unsigned int dword_27AA40 = 0;
void *dword_27AA44 = NULL;

LoadSave LoadSave::head(123);
FILE *LoadSave::hSFile = NULL;
int LoadSave::hLFile = -1;

short word_27AA54 = 0;

void sub_76FD4(void)
{
    if (!dword_27AA44)
        dword_27AA44 = Resource::Alloc(0x186a0);
}

void LoadSave::Save(void)
{
    ThrowError("Pure virtual function called");
}

void LoadSave::Load(void)
{
    ThrowError("Pure virtual function called");
}

void LoadSave::Read(void *pData, int nSize)
{
    dword_27AA38 += nSize;
    dassert(hLFile != -1);
    if (kread(hLFile, pData, nSize) != nSize)
        ThrowError("Error reading save file.");
}

void LoadSave::Write(void *pData, int nSize)
{
    dword_27AA38 += nSize;
    dword_27AA3C += nSize;
    dassert(hSFile != NULL);
    if (fwrite(pData, 1, nSize, hSFile) != (size_t)nSize)
        ThrowError("File error #%d writing save file.", errno);
}

void LoadSave::LoadGame(char *pzFile)
{
    const char bDemoWasPlayed = gDemo.at1;
    const char bGameWasStarted = gGameStarted;
    if (gDemo.at1)
        gDemo.Close();

    gViewPos = VIEWPOS_0;
    gViewIndex = myconnectindex;
    sndKillAllSounds();
    sfxKillAllSounds();
    ambKillAll();
    seqKillAll();
    if (!gGameStarted)
    {
        memset(xsprite, 0, sizeof(xsprite));
        memset(sprite, 0, sizeof(spritetype)*kMaxSprites);
        automapping = 1;
    }
    hLFile = kopen4load(pzFile, 0);
    if (hLFile == -1)
        ThrowError("Error loading save file.");
    LoadSave *rover = head.next;
    while (rover != &head)
    {
        rover->Load();
        rover = rover->next;
    }
    kclose(hLFile);
    hLFile = -1;
    if (!gGameStarted)
        scrLoadPLUs();
    InitSectorFX();
    viewInitializePrediction();
    PreloadCache();
    if (!bVanilla && !gMe->packSlots[1].isActive) // if diving suit is not active, turn off reverb sound effect
        sfxSetReverb(0);
    ambInit();
#ifdef YAX_ENABLE
    yax_update(numyaxbunches > 0 ? 2 : 1);
#endif
    calc_sector_reachability();
    memset(myMinLag, 0, sizeof(myMinLag));
    otherMinLag = 0;
    myMaxLag = 0;
    gNetFifoClock = 0;
    gNetFifoTail = 0;
    memset(gNetFifoHead, 0, sizeof(gNetFifoHead));
    gPredictTail = 0;
    gNetFifoMasterTail = 0;
    memset(gFifoInput, 0, sizeof(gFifoInput));
    memset(gChecksum, 0, sizeof(gChecksum));
    memset(gCheckFifo, 0, sizeof(gCheckFifo));
    memset(gCheckHead, 0, sizeof(gCheckHead));
    gSendCheckTail = 0;
    gCheckTail = 0;
    gBufferJitter = 0;
    bOutOfSync = 0;
    for (int i = 0; i < gNetPlayers; i++)
        playerSetRace(&gPlayer[i], gPlayer[i].lifeMode);
    if (VanillaMode())
        viewSetMessage("");
    else
        gGameMessageMgr.Clear();
    viewSetErrorMessage("");
    if (!gGameStarted)
    {
        netWaitForEveryone(0);
        memset(gPlayerReady, 0, sizeof(gPlayerReady));
    }
    gFrameTicks = 0;
    gFrame = 0;
    gCacheMiss = 0;
    gFrameRate = 0;
    totalclock = 0;
    gPaused = 0;
    gGameStarted = 1;
    bVanilla = false;

#ifdef USE_STRUCT_TRACKERS
    Bmemset(sectorchanged, 0, sizeof(sectorchanged));
    Bmemset(spritechanged, 0, sizeof(spritechanged));
    Bmemset(wallchanged, 0, sizeof(wallchanged));
#endif

#ifdef USE_OPENGL
    Polymost_prepare_loadboard();
#endif

#ifdef POLYMER
    if (videoGetRenderMode() == REND_POLYMER)
        polymer_loadboard();

    // this light pointer nulling needs to be outside the videoGetRenderMode check
    // because we might be loading the savegame using another renderer but
    // change to Polymer later
    for (int i=0; i<kMaxSprites; i++)
    {
        gPolymerLight[i].lightptr = NULL;
        gPolymerLight[i].lightId = -1;
    }
#endif

    if (gGameOptions.nEpisode >= gEpisodeCount || gGameOptions.nLevel >= gEpisodeInfo[gGameOptions.nEpisode].nLevels
        || Bstrcasecmp(gEpisodeInfo[gGameOptions.nEpisode].levelsInfo[gGameOptions.nLevel].Filename, gGameOptions.zLevelName) != 0)
    {
        if (!gSysRes.Lookup(gGameOptions.zLevelName, "MAP"))
        {
            gGameOptions.nEpisode = 0;
            gGameOptions.nLevel = 0;
        }
        else
        {
            levelAddUserMap(gGameOptions.zLevelName);
        }
    }

    if (MusicRestartsOnLoadToggle
        || bDemoWasPlayed
        || !bGameWasStarted
        || (gMusicPrevLoadedEpisode != gGameOptions.nEpisode || gMusicPrevLoadedLevel != gGameOptions.nLevel))
    {
        levelTryPlayMusicOrNothing(gGameOptions.nEpisode, gGameOptions.nLevel);
    }
    gMusicPrevLoadedEpisode = gGameOptions.nEpisode;
    gMusicPrevLoadedLevel = gGameOptions.nLevel;

    netBroadcastPlayerInfo(myconnectindex);
    //sndPlaySong(gGameOptions.zLevelSong, 1);
}

void LoadSave::SaveGame(char *pzFile)
{
    hSFile = fopen(pzFile, "wb");
    if (hSFile == NULL)
        ThrowError("File error #%d creating save file.", errno);
    dword_27AA38 = 0;
    dword_27AA40 = 0;
    LoadSave *rover = head.next;
    while (rover != &head)
    {
        rover->Save();
        if (dword_27AA38 > dword_27AA40)
            dword_27AA40 = dword_27AA38;
        dword_27AA38 = 0;
        rover = rover->next;
    }
    fclose(hSFile);
    hSFile = NULL;
}

class MyLoadSave : public LoadSave
{
public:
    virtual void Load(void);
    virtual void Save(void);
};

void MyLoadSave::Load(void)
{
    psky_t *pSky = tileSetupSky(0);
    int id;
    Read(&id, sizeof(id));
    if (id != 0x5653424e/*'VSBN'*/)
        ThrowError("Old saved game found");
    short version;
    Read(&version, sizeof(version));
    if (version != BYTEVERSION)
        ThrowError("Incompatible version of saved game found!");
    Read(&gGameOptions, sizeof(gGameOptions));
    Read(&numsectors, sizeof(numsectors));
    Read(&numwalls, sizeof(numwalls));
    Read(&numsectors, sizeof(numsectors));
    int nNumSprites;
    Read(&nNumSprites, sizeof(nNumSprites));
    memset(sector, 0, sizeof(sector[0])*kMaxSectors);
    memset(wall, 0, sizeof(wall[0])*kMaxWalls);
    memset(sprite, 0, sizeof(sprite[0])*kMaxSprites);
    memset(spriteext, 0, sizeof(spriteext[0])*kMaxSprites);
    Read(sector, sizeof(sector[0])*numsectors);
    Read(wall, sizeof(wall[0])*numwalls);
    Read(sprite, sizeof(sprite[0])*kMaxSprites);
    Read(spriteext, sizeof(spriteext[0])*kMaxSprites);
    Read(qsector_filler, sizeof(qsector_filler[0])*numsectors);
    Read(qsprite_filler, sizeof(qsprite_filler[0])*kMaxSprites);
    Read(&randomseed, sizeof(randomseed));
    Read(&parallaxtype, sizeof(parallaxtype));
    Read(&showinvisibility, sizeof(showinvisibility));
    Read(&pSky->horizfrac, sizeof(pSky->horizfrac));
    Read(&pSky->yoffs, sizeof(pSky->yoffs));
    Read(&pSky->yscale, sizeof(pSky->yscale));
    Read(&gVisibility, sizeof(gVisibility));
    Read(&g_visibility, sizeof(g_visibility));
    Read(&parallaxvisibility, sizeof(parallaxvisibility));
    Read(pSky->tileofs, sizeof(pSky->tileofs));
    Read(&pSky->lognumtiles, sizeof(pSky->lognumtiles));
    Read(headspritesect, sizeof(headspritesect));
    Read(headspritestat, sizeof(headspritestat));
    Read(prevspritesect, sizeof(prevspritesect));
    Read(prevspritestat, sizeof(prevspritestat));
    Read(nextspritesect, sizeof(nextspritesect));
    Read(nextspritestat, sizeof(nextspritestat));
    Read(show2dsector, sizeof(show2dsector));
    Read(show2dwall, sizeof(show2dwall));
    Read(show2dsprite, sizeof(show2dsprite));
    Read(&automapping, sizeof(automapping));
    Read(gotpic, sizeof(gotpic));
    Read(gotsector, sizeof(gotsector));
    Read(&gFrameClock, sizeof(gFrameClock));
    Read(&gFrameTicks, sizeof(gFrameTicks));
    Read(&gFrame, sizeof(gFrame));
    ClockTicks nGameClock;
    Read(&totalclock, sizeof(totalclock));
    totalclock = nGameClock;
    Read(&gLevelTime, sizeof(gLevelTime));
    Read(&gPaused, sizeof(gPaused));
    Read(&gbAdultContent, sizeof(gbAdultContent));
    Read(baseWall, sizeof(baseWall[0])*numwalls);
    Read(baseSprite, sizeof(baseSprite[0])*nNumSprites);
    Read(baseFloor, sizeof(baseFloor[0])*numsectors);
    Read(baseCeil, sizeof(baseCeil[0])*numsectors);
    Read(velFloor, sizeof(velFloor[0])*numsectors);
    Read(velCeil, sizeof(velCeil[0])*numsectors);
    Read(&gHitInfo, sizeof(gHitInfo));
    Read(&byte_1A76C6, sizeof(byte_1A76C6));
    Read(&byte_1A76C8, sizeof(byte_1A76C8));
    Read(&byte_1A76C7, sizeof(byte_1A76C7));
    Read(&byte_19AE44, sizeof(byte_19AE44));
    Read(gStatCount, sizeof(gStatCount));
    Read(nextXSprite, sizeof(nextXSprite));
    Read(nextXWall, sizeof(nextXWall));
    Read(nextXSector, sizeof(nextXSector));
    memset(xsprite, 0, sizeof(xsprite));
    for (int nSprite = 0; nSprite < kMaxSprites; nSprite++)
    {
        if (sprite[nSprite].statnum < kMaxStatus)
        {
            int nXSprite = sprite[nSprite].extra;
            if (nXSprite > 0)
                Read(&xsprite[nXSprite], sizeof(XSPRITE));
        }
    }
    memset(xwall, 0, sizeof(xwall));
    for (int nWall = 0; nWall < numwalls; nWall++)
    {
        int nXWall = wall[nWall].extra;
        if (nXWall > 0)
            Read(&xwall[nXWall], sizeof(XWALL));
    }
    memset(xsector, 0, sizeof(xsector));
    for (int nSector = 0; nSector < numsectors; nSector++)
    {
        int nXSector = sector[nSector].extra;
        if (nXSector > 0)
            Read(&xsector[nXSector], sizeof(XSECTOR));
    }
    Read(xvel, nNumSprites*sizeof(xvel[0]));
    Read(yvel, nNumSprites*sizeof(yvel[0]));
    Read(zvel, nNumSprites*sizeof(zvel[0]));
    Read(&gMapRev, sizeof(gMapRev));
    Read(&gSongId, sizeof(gSkyCount));
    Read(&gFogMode, sizeof(gFogMode));
#ifdef NOONE_EXTENSIONS
    Read(&gModernMap, sizeof(gModernMap));
#endif
#ifdef YAX_ENABLE
    Read(&numyaxbunches, sizeof(numyaxbunches));
#endif
    psky_t skyInfo;
    Read(&skyInfo, sizeof(skyInfo));

    *tileSetupSky(0) = skyInfo;
    gCheatMgr.ResetCheats();

}

void MyLoadSave::Save(void)
{
    psky_t *pSky = tileSetupSky(0);
    int nNumSprites = 0;
    int id = 0x5653424e/*'VSBN'*/;
    Write(&id, sizeof(id));
    short version = BYTEVERSION;
    Write(&version, sizeof(version));
    for (int nSprite = 0; nSprite < kMaxSprites; nSprite++)
    {
        if (sprite[nSprite].statnum < kMaxStatus && nSprite > nNumSprites)
            nNumSprites = nSprite;
    }
    //nNumSprites += 2;
    nNumSprites++;
    Write(&gGameOptions, sizeof(gGameOptions));
    Write(&numsectors, sizeof(numsectors));
    Write(&numwalls, sizeof(numwalls));
    Write(&numsectors, sizeof(numsectors));
    Write(&nNumSprites, sizeof(nNumSprites));
    Write(sector, sizeof(sector[0])*numsectors);
    Write(wall, sizeof(wall[0])*numwalls);
    Write(sprite, sizeof(sprite[0])*kMaxSprites);
    Write(spriteext, sizeof(spriteext[0])*kMaxSprites);
    Write(qsector_filler, sizeof(qsector_filler[0])*numsectors);
    Write(qsprite_filler, sizeof(qsprite_filler[0])*kMaxSprites);
    Write(&randomseed, sizeof(randomseed));
    Write(&parallaxtype, sizeof(parallaxtype));
    Write(&showinvisibility, sizeof(showinvisibility));
    Write(&pSky->horizfrac, sizeof(pSky->horizfrac));
    Write(&pSky->yoffs, sizeof(pSky->yoffs));
    Write(&pSky->yscale, sizeof(pSky->yscale));
    Write(&gVisibility, sizeof(gVisibility));
    Write(&g_visibility, sizeof(g_visibility));
    Write(&parallaxvisibility, sizeof(parallaxvisibility));
    Write(pSky->tileofs, sizeof(pSky->tileofs));
    Write(&pSky->lognumtiles, sizeof(pSky->lognumtiles));
    Write(headspritesect, sizeof(headspritesect));
    Write(headspritestat, sizeof(headspritestat));
    Write(prevspritesect, sizeof(prevspritesect));
    Write(prevspritestat, sizeof(prevspritestat));
    Write(nextspritesect, sizeof(nextspritesect));
    Write(nextspritestat, sizeof(nextspritestat));
    Write(show2dsector, sizeof(show2dsector));
    Write(show2dwall, sizeof(show2dwall));
    Write(show2dsprite, sizeof(show2dsprite));
    Write(&automapping, sizeof(automapping));
    Write(gotpic, sizeof(gotpic));
    Write(gotsector, sizeof(gotsector));
    Write(&gFrameClock, sizeof(gFrameClock));
    Write(&gFrameTicks, sizeof(gFrameTicks));
    Write(&gFrame, sizeof(gFrame));
    ClockTicks nGameClock = totalclock;
    Write(&nGameClock, sizeof(nGameClock));
    Write(&gLevelTime, sizeof(gLevelTime));
    Write(&gPaused, sizeof(gPaused));
    Write(&gbAdultContent, sizeof(gbAdultContent));
    Write(baseWall, sizeof(baseWall[0])*numwalls);
    Write(baseSprite, sizeof(baseSprite[0])*nNumSprites);
    Write(baseFloor, sizeof(baseFloor[0])*numsectors);
    Write(baseCeil, sizeof(baseCeil[0])*numsectors);
    Write(velFloor, sizeof(velFloor[0])*numsectors);
    Write(velCeil, sizeof(velCeil[0])*numsectors);
    Write(&gHitInfo, sizeof(gHitInfo));
    Write(&byte_1A76C6, sizeof(byte_1A76C6));
    Write(&byte_1A76C8, sizeof(byte_1A76C8));
    Write(&byte_1A76C7, sizeof(byte_1A76C7));
    Write(&byte_19AE44, sizeof(byte_19AE44));
    Write(gStatCount, sizeof(gStatCount));
    Write(nextXSprite, sizeof(nextXSprite));
    Write(nextXWall, sizeof(nextXWall));
    Write(nextXSector, sizeof(nextXSector));
    for (int nSprite = 0; nSprite < kMaxSprites; nSprite++)
    {
        if (sprite[nSprite].statnum < kMaxStatus)
        {
            int nXSprite = sprite[nSprite].extra;
            if (nXSprite > 0)
                Write(&xsprite[nXSprite], sizeof(XSPRITE));
        }
    }
    for (int nWall = 0; nWall < numwalls; nWall++)
    {
        int nXWall = wall[nWall].extra;
        if (nXWall > 0)
            Write(&xwall[nXWall], sizeof(XWALL));
    }
    for (int nSector = 0; nSector < numsectors; nSector++)
    {
        int nXSector = sector[nSector].extra;
        if (nXSector > 0)
            Write(&xsector[nXSector], sizeof(XSECTOR));
    }
    Write(xvel, nNumSprites*sizeof(xvel[0]));
    Write(yvel, nNumSprites*sizeof(yvel[0]));
    Write(zvel, nNumSprites*sizeof(zvel[0]));
    Write(&gMapRev, sizeof(gMapRev));
    Write(&gSongId, sizeof(gSkyCount));
    Write(&gFogMode, sizeof(gFogMode));
#ifdef NOONE_EXTENSIONS
    Write(&gModernMap, sizeof(gModernMap));
#endif
#ifdef YAX_ENABLE
    Write(&numyaxbunches, sizeof(numyaxbunches));
#endif
    psky_t skyInfo = *tileSetupSky(0);
    Write(&skyInfo, sizeof(skyInfo));
}

void LoadSavedInfo(void)
{
    auto pList = klistpath("./", "game*.sav", BUILDVFS_FIND_FILE);
    int nCount = 0;
    for (auto pIterator = pList; pIterator != NULL && nCount < 10; pIterator = pIterator->next, nCount++)
    {
        int hFile = kopen4loadfrommod(pIterator->name, 0);
        if (hFile == -1)
            ThrowError("Error loading save file header.");
        int vc;
        short v4;
        vc = 0;
        v4 = word_27AA54;
        if ((uint32_t)kread(hFile, &vc, sizeof(vc)) != sizeof(vc))
        {
            kclose(hFile);
            continue;
        }
        if (vc != 0x5653424e/*'VSBN'*/)
        {
            kclose(hFile);
            continue;
        }
        kread(hFile, &v4, sizeof(v4));
        if (v4 != BYTEVERSION)
        {
            kclose(hFile);
            continue;
        }
        if ((uint32_t)kread(hFile, &gSaveGameOptions[nCount], sizeof(gSaveGameOptions[0])) != sizeof(gSaveGameOptions[0]))
            ThrowError("Error reading save file.");
        UpdateSavedInfo(nCount);
        kclose(hFile);
    }
    klistfree(pList);
}

void UpdateSavedInfo(int nSlot)
{
    strcpy(strRestoreGameStrings[gSaveGameOptions[nSlot].nSaveGameSlot], gSaveGameOptions[nSlot].szUserGameName);
    restoreGameDifficulty[gSaveGameOptions[nSlot].nSaveGameSlot] = gSaveGameOptions[nSlot].nDifficulty;
}

static MyLoadSave *myLoadSave;

void LoadSaveSetup(void)
{
    void ActorLoadSaveConstruct(void);
    void AILoadSaveConstruct(void);
    void EndGameLoadSaveConstruct(void);
    void EventQLoadSaveConstruct(void);
    void LevelsLoadSaveConstruct(void);
    void MessagesLoadSaveConstruct(void);
    void MirrorLoadSaveConstruct(void);
    void PlayerLoadSaveConstruct(void);
    void SeqLoadSaveConstruct(void);
    void TriggersLoadSaveConstruct(void);
    void ViewLoadSaveConstruct(void);
    void WarpLoadSaveConstruct(void);
    void WeaponLoadSaveConstruct(void);
#ifdef NOONE_EXTENSIONS
    void nnExtLoadSaveConstruct(void);
#endif
    myLoadSave = new MyLoadSave();

    ActorLoadSaveConstruct();
    AILoadSaveConstruct();
    EndGameLoadSaveConstruct();
    EventQLoadSaveConstruct();
    LevelsLoadSaveConstruct();
    MessagesLoadSaveConstruct();
    MirrorLoadSaveConstruct();
    PlayerLoadSaveConstruct();
    SeqLoadSaveConstruct();
    TriggersLoadSaveConstruct();
    ViewLoadSaveConstruct();
    WarpLoadSaveConstruct();
    WeaponLoadSaveConstruct();
#ifdef NOONE_EXTENSIONS
    nnExtLoadSaveConstruct();
#endif
}


code:
//-------------------------------------------------------------------------
/*
Copyright (C) 2010-2019 EDuke32 developers and contributors
Copyright (C) 2019 Nuke.YKT

This file is part of NBlood.

NBlood is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License version 2
as published by the Free Software Foundation.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/
//-------------------------------------------------------------------------
#pragma once
#include <stdio.h>
#include "levels.h"

class LoadSave {
public:
    static LoadSave head;
    static FILE *hSFile;
    static int hLFile;
    LoadSave *prev;
    LoadSave *next;
    LoadSave() {
        prev = head.prev;
        prev->next = this;
        next = &head;
        next->prev = this;
    }
    LoadSave(int dummy)
    {
        UNREFERENCED_PARAMETER(dummy);
        next = prev = this;
    }
    //~LoadSave() { }
    virtual void Save(void);
    virtual void Load(void);
    void Read(void *, int);
    void Write(void *, int);
    static void LoadGame(char *);
    static void SaveGame(char *);
};

extern unsigned int gSavedOffset;
extern GAMEOPTIONS gSaveGameOptions[];
extern char *gSaveGamePic[10];
void UpdateSavedInfo(int nSlot);
void LoadSavedInfo(void);
void LoadSaveSetup(void);