code:
#import <Cocoa/Cocoa.h>

#include "compat.h"
#include "build.h"
#include "baselayer.h"
#include "common.h"
#include "common_game.h"
#include "config.h"
#include "grpscan.h"
#include "osxbits.h"

#import "GrpFile.game.h"
#import "GameListSource.game.h"

#ifndef MAC_OS_X_VERSION_10_5
# define NSImageScaleNone NSScaleNone
#endif

#ifndef MAC_OS_X_VERSION_10_12
# define NSEventModifierFlagOption NSAlternateKeyMask
# define NSEventModifierFlagCommand NSCommandKeyMask
# define NSEventMaskAny NSAnyEventMask
# define NSWindowStyleMaskTitled NSTitledWindowMask
# define NSWindowStyleMaskClosable NSClosableWindowMask
# define NSWindowStyleMaskMiniaturizable NSMiniaturizableWindowMask
# define NSWindowStyleMaskResizable NSResizableWindowMask
# define NSAlertStyleInformational NSInformationalAlertStyle
# define NSControlSizeSmall NSSmallControlSize
#endif

#ifndef MAC_OS_X_VERSION_10_14
# define NSButtonTypeSwitch NSSwitchButton
# define NSBezelStyleRounded NSRoundedBezelStyle
# define NSControlStateValueOn NSOnState
# define NSControlStateValueOff NSOffState
#endif

static inline NSRect NSRectChangeXY(NSRect const rect, CGFloat const x, CGFloat const y)
{
    return NSMakeRect(x, y, rect.size.width, rect.size.height);
}
static inline NSRect NSSizeAddXY(NSSize const size, CGFloat const x, CGFloat const y)
{
    return NSMakeRect(x, y, size.width, size.height);
}
static inline CGFloat NSRightEdge(NSRect rect)
{
    return rect.origin.x + rect.size.width;
}
static inline CGFloat NSTopEdge(NSRect rect)
{
    return rect.origin.y + rect.size.height;
}

static inline void setFontToSmall(id control)
{
    [control setFont:[NSFont fontWithDescriptor:[[control font] fontDescriptor] size:[NSFont smallSystemFontSize]]];
}

static inline void setControlToSmall(id control)
{
    [control setControlSize:NSControlSizeSmall];
}

static inline NSTextField * makeLabel(NSString * labelText)
{
    NSTextField *textField = [[NSTextField alloc] init];
    setFontToSmall(textField);
    setControlToSmall([textField cell]);
    [textField setStringValue:labelText];
    [textField setBezeled:NO];
    [textField setDrawsBackground:NO];
    [textField setEditable:NO];
    [textField setSelectable:NO];
    [textField sizeToFit];
    return textField;
}

static inline NSButton * makeCheckbox(NSString * labelText)
{
    NSButton *checkbox = [[NSButton alloc] init];
    setFontToSmall(checkbox);
    setControlToSmall([checkbox cell]);
    [checkbox setTitle:labelText];
    [checkbox setButtonType:NSButtonTypeSwitch];
    [checkbox sizeToFit];
    return checkbox;
}

static inline NSPopUpButton * makeComboBox(void)
{
    NSPopUpButton *comboBox = [[NSPopUpButton alloc] init];
    [comboBox setPullsDown:NO];
    setFontToSmall(comboBox);
    setControlToSmall([comboBox cell]);
    [comboBox setBezelStyle:NSBezelStyleRounded];
    [comboBox setPreferredEdge:NSMaxYEdge];
    [[comboBox cell] setArrowPosition:NSPopUpArrowAtCenter];
    [comboBox sizeToFit];
    return comboBox;
}

/* setAppleMenu disappeared from the headers in 10.4 */
@interface NSApplication(NSAppleMenu)
- (void)setAppleMenu:(NSMenu *)menu;
@end

static inline NSString * GetApplicationName(void)
{
    NSString *appName = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleDisplayName"];
    if (!appName)
        appName = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleName"];
    if (![appName length])
        appName = [[NSProcessInfo processInfo] processName];

    return appName;
}

static inline void CreateApplicationMenus(void)
{
    NSString *appName;
    NSString *title;
    NSMenu *rootMenu;
    NSMenu *serviceMenu;
    NSMenuItem *menuItem;

    NSMenu *mainMenu = [[NSMenu alloc] init];

    /* Create the application menu */
    appName = GetApplicationName();
    rootMenu = [[NSMenu alloc] init];

    /* Put menu into the menubar */
    menuItem = [[NSMenuItem alloc] initWithTitle:@"" action:nil keyEquivalent:@""];
    [menuItem setSubmenu:rootMenu];
    [mainMenu addItem:menuItem];
    [menuItem release];

    /* Add menu items */
    title = [@"About " stringByAppendingString:appName];
    [rootMenu addItemWithTitle:title action:@selector(orderFrontStandardAboutPanel:) keyEquivalent:@""];

    [rootMenu addItem:[NSMenuItem separatorItem]];

    serviceMenu = [[NSMenu alloc] init];
    menuItem = (NSMenuItem *)[rootMenu addItemWithTitle:@"Services" action:nil keyEquivalent:@""];
    [menuItem setSubmenu:serviceMenu];

    [nsapp setServicesMenu:serviceMenu];
    [serviceMenu release];

    [rootMenu addItem:[NSMenuItem separatorItem]];

    title = [@"Hide " stringByAppendingString:appName];
    [rootMenu addItemWithTitle:title action:@selector(hide:) keyEquivalent:@"h"];

    menuItem = (NSMenuItem *)[rootMenu addItemWithTitle:@"Hide Others" action:@selector(hideOtherApplications:) keyEquivalent:@"h"];
    [menuItem setKeyEquivalentModifierMask:(NSEventModifierFlagOption|NSEventModifierFlagCommand)];

    [rootMenu addItemWithTitle:@"Show All" action:@selector(unhideAllApplications:) keyEquivalent:@""];

    [rootMenu addItem:[NSMenuItem separatorItem]];

    title = [@"Quit " stringByAppendingString:appName];
    [rootMenu addItemWithTitle:title action:@selector(terminate:) keyEquivalent:@"q"];

    /* Create the main menu bar */
    [nsapp setMainMenu:mainMenu];
    [mainMenu release];  /* we're done with it, let NSApp own it. */

    /* Tell the application object that this is now the application menu */
    [nsapp setAppleMenu:rootMenu];
    [rootMenu release];
}

static int retval = -1;

static struct {
    grpfile_t const * grp;
    ud_setup_t shared;
} settings;

@interface StartupWindow : NSWindow <NSWindowDelegate>
{
    NSMutableArray *modeslist3d;
    GameListSource *gamelistsrc;

    NSButton *alwaysShowButton;
    NSButton *fullscreenButton;
    NSTextView *messagesView;
    NSTabView *tabView;
    NSTabViewItem *tabViewItemSetup;
    NSTabViewItem *tabViewItemMessageLog;
    NSPopUpButton *videoMode3DPUButton;
    NSScrollView *gameList;

    NSButton *cancelButton;
    NSButton *startButton;
}

- (StartupWindow *)init;

- (void)dealloc;
- (void)populateVideoModes:(BOOL)firstTime;

- (void)fullscreenClicked:(id)sender;

- (void)cancel:(id)sender;
- (void)start:(id)sender;

- (void)setupRunMode;
- (void)setupMessagesMode;

- (void)putsMessage:(NSString *)str;

@end

@implementation StartupWindow : NSWindow

- (StartupWindow *)init
{
    NSUInteger const style = NSWindowStyleMaskTitled | NSWindowStyleMaskClosable | NSWindowStyleMaskMiniaturizable | NSWindowStyleMaskResizable;
    NSRect const windowFrame = NSMakeRect(0, 0, 480, 280);
    self = [super initWithContentRect:windowFrame styleMask:style backing:NSBackingStoreBuffered defer:NO];

    if (self)
    {
        // window properties
        [self setDelegate:self];
        [self setReleasedWhenClosed:NO];
#if defined MAC_OS_X_VERSION_10_3 && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_3
        [self setContentMinSize:[[self contentView] frame].size];
#else
        [self setMinSize:[NSWindow frameRectForContentRect:[[self contentView] frame] styleMask:[self styleMask]].size];
#endif

        // image on the left
        NSRect const imageFrame = NSMakeRect(0, 0, 100, 280);
        NSImageView * imageView = [[NSImageView alloc] initWithFrame:imageFrame];
        [imageView setImageScaling:NSImageScaleNone];
        [imageView setImage:[NSImage imageNamed:@"game"]];
        [[self contentView] addSubview:imageView];
        [imageView setAutoresizingMask:NSViewMaxXMargin | NSViewHeightSizable];

        // buttons
        CGFloat const buttonWidth = 80;
        CGFloat const buttonHeight = 32;

        NSRect const startButtonFrame = NSMakeRect(windowFrame.size.width - buttonWidth, 0, buttonWidth, buttonHeight);
        startButton = [[NSButton alloc] initWithFrame:startButtonFrame];
        [[self contentView] addSubview:startButton];
        [startButton setTitle:@"Start"];
        [startButton setTarget:self];
        [startButton setAction:@selector(start:)];
        [startButton setBezelStyle:NSBezelStyleRounded];
        [startButton setKeyEquivalent:@"\r"];
        [startButton setAutoresizingMask:NSViewMinXMargin | NSViewMaxYMargin];

        NSRect const cancelButtonFrame = NSMakeRect(startButtonFrame.origin.x - buttonWidth, 0, buttonWidth, buttonHeight);
        cancelButton = [[NSButton alloc] initWithFrame:cancelButtonFrame];
        [[self contentView] addSubview:cancelButton];
        [cancelButton setTitle:@"Cancel"];
        [cancelButton setTarget:self];
        [cancelButton setAction:@selector(cancel:)];
        [cancelButton setBezelStyle:NSBezelStyleRounded];
        [cancelButton setAutoresizingMask:NSViewMinXMargin | NSViewMaxYMargin];

        // tab frame
        NSRect const tabViewFrame = NSMakeRect(imageFrame.size.width, buttonHeight, windowFrame.size.width - imageFrame.size.width, windowFrame.size.height - buttonHeight - 5);
        tabView = [[NSTabView alloc] initWithFrame:tabViewFrame];
        [[self contentView] addSubview:tabView];
        setFontToSmall(tabView);
        setControlToSmall(tabView);
        [tabView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];

        // setup tab

        tabViewItemSetup = [[NSTabViewItem alloc] init];
        [tabView addTabViewItem:tabViewItemSetup];
        [tabViewItemSetup setLabel:@"Setup"];
        NSRect const tabViewItemSetupFrame = [[tabViewItemSetup view] frame];

        // always show checkbox
        alwaysShowButton = makeCheckbox(@"Always show this window at startup");
        [[tabViewItemSetup view] addSubview:alwaysShowButton];
        NSSize const alwaysShowButtonSize = [alwaysShowButton frame].size;
        NSRect const alwaysShowButtonFrame = NSSizeAddXY(alwaysShowButtonSize, tabViewItemSetupFrame.size.width - alwaysShowButtonSize.width, 0);
        [alwaysShowButton setFrame:alwaysShowButtonFrame];
        [alwaysShowButton setAutoresizingMask:NSViewMinXMargin | NSViewMaxYMargin];

        // video mode selectors and labels
        NSTextField * labelVideoMode = makeLabel(@"Video mode:");
        [[tabViewItemSetup view] addSubview:labelVideoMode];
        NSSize const labelVideoModeSize = [labelVideoMode frame].size;
        [labelVideoMode setAutoresizingMask:NSViewMaxXMargin | NSViewMinYMargin];

        fullscreenButton = makeCheckbox(@"Fullscreen");
        [[tabViewItemSetup view] addSubview:fullscreenButton];
        NSSize const fullscreenButtonSize = [fullscreenButton frame].size;
        [fullscreenButton setAction:@selector(fullscreenClicked:)];
        [fullscreenButton setAutoresizingMask:NSViewMinXMargin | NSViewMinYMargin];

        videoMode3DPUButton = makeComboBox();
        [[tabViewItemSetup view] addSubview:videoMode3DPUButton];
        NSSize const videoMode3DPUButtonSize = [videoMode3DPUButton frame].size;
        CGFloat const videoMode3DButtonX = labelVideoModeSize.width; // NSRightEdge(labelVideoModeFrame);
        NSRect const videoMode3DPUButtonFrame = NSMakeRect(videoMode3DButtonX, tabViewItemSetupFrame.size.height - videoMode3DPUButtonSize.height, tabViewItemSetupFrame.size.width - videoMode3DButtonX - fullscreenButtonSize.width, videoMode3DPUButtonSize.height);
        [videoMode3DPUButton setFrame:videoMode3DPUButtonFrame];
        [videoMode3DPUButton setAutoresizingMask:NSViewWidthSizable | NSViewMinYMargin];

        NSRect const labelVideoModeFrame = NSSizeAddXY(labelVideoModeSize, 0, videoMode3DPUButtonFrame.origin.y + rintf((videoMode3DPUButtonSize.height - labelVideoModeSize.height) * 0.5f) + 1);
        [labelVideoMode setFrame:labelVideoModeFrame];

        NSRect const fullscreenButtonFrame = NSSizeAddXY(fullscreenButtonSize, tabViewItemSetupFrame.size.width - fullscreenButtonSize.width, videoMode3DPUButtonFrame.origin.y + rintf((videoMode3DPUButtonSize.height - fullscreenButtonSize.height) * 0.5f) + 1);
        [fullscreenButton setFrame:fullscreenButtonFrame];

        // game selector and label
        NSTextField * labelGame = makeLabel(@"Game:");
        [[tabViewItemSetup view] addSubview:labelGame];
        NSSize const labelGameSize = [labelGame frame].size;
        NSRect const labelGameFrame = NSSizeAddXY(labelGameSize, 0, videoMode3DPUButtonFrame.origin.y - labelGameSize.height);
        [labelGame setFrame:labelGameFrame];
        [labelGame setAutoresizingMask:NSViewMaxXMargin | NSViewMinYMargin];

        CGFloat const gameListVerticalPadding = 3;
        CGFloat const gameListY = NSTopEdge(alwaysShowButtonFrame) + gameListVerticalPadding;
        NSRect const gameListFrame = NSMakeRect(0, gameListY, tabViewItemSetupFrame.size.width, labelGameFrame.origin.y - gameListY - gameListVerticalPadding);
        gameList = [[NSScrollView alloc] initWithFrame:gameListFrame];
        [[tabViewItemSetup view] addSubview:gameList];
        [gameList setBorderType:NSBezelBorder];
        [gameList setHasVerticalScroller:YES];
        [gameList setHasHorizontalScroller:NO];
        setControlToSmall([[gameList verticalScroller] cell]);
        NSSize const gameListContentSize = [gameList contentSize];
        [gameList setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];

        NSTableView * gameListTable = [[NSTableView alloc] initWithFrame:NSMakeRect(0, 0, gameListContentSize.width, gameListContentSize.height)];
        [gameList setDocumentView:gameListTable];

        NSTableColumn * nameColumn = [[NSTableColumn alloc] initWithIdentifier:@"0"];
        [gameListTable addTableColumn:nameColumn];
        NSTableColumn * fileColumn = [[NSTableColumn alloc] initWithIdentifier:@"1"];
        [gameListTable addTableColumn:fileColumn];
        [nameColumn setEditable:NO];
        [[nameColumn headerCell] setStringValue:@"Name"];
        [nameColumn setWidth:gameListContentSize.width * (2.f/3.f)];
        [fileColumn setEditable:NO];
        [[fileColumn headerCell] setStringValue:@"File"];
        [gameListTable sizeLastColumnToFit];
        [gameListTable setAutoresizingMask:NSViewWidthSizable];

        // message log tab

        tabViewItemMessageLog = [[NSTabViewItem alloc] init];
        [tabView addTabViewItem:tabViewItemMessageLog];
        [tabViewItemMessageLog setLabel:@"Message Log"];
        NSRect const tabViewItemMessageLogFrame = [[tabViewItemMessageLog view] frame];

        // message log
        NSScrollView * messagesScrollView = [[NSScrollView alloc] initWithFrame:NSRectChangeXY(tabViewItemMessageLogFrame, 0, 0)];
        [[tabViewItemMessageLog view] addSubview:messagesScrollView];
        [messagesScrollView setBorderType:NSBezelBorder];
        [messagesScrollView setHasVerticalScroller:YES];
        [messagesScrollView setHasHorizontalScroller:NO];
        setControlToSmall([[messagesScrollView verticalScroller] cell]);
        NSSize const messagesScrollViewContentSize = [messagesScrollView contentSize];
        [messagesScrollView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];

        messagesView = [[NSTextView alloc] initWithFrame:NSMakeRect(0, 0, messagesScrollViewContentSize.width, messagesScrollViewContentSize.height)];
        [messagesScrollView setDocumentView:messagesView];
        [messagesView setEditable:NO];
        [messagesView setRichText:NO];
        setFontToSmall(messagesView);
        [messagesView setMinSize:NSMakeSize(0.0, messagesScrollViewContentSize.height)];
        [messagesView setMaxSize:NSMakeSize(FLT_MAX, FLT_MAX)];
        [messagesView setVerticallyResizable:YES];
        [messagesView setHorizontallyResizable:NO];
        [messagesView setAutoresizingMask:NSViewWidthSizable];

        [[messagesView textContainer] setContainerSize:NSMakeSize(messagesScrollViewContentSize.width, FLT_MAX)];
        [[messagesView textContainer] setWidthTracksTextView:YES];
    }

    return self;
}

- (BOOL)canBecomeKeyWindow
{
    return YES;
}

- (BOOL)canBecomeMainWindow
{
    return YES;
}

- (BOOL) windowShouldClose:(id)sender
{
    UNREFERENCED_PARAMETER(sender);

    retval = 0;

    return YES;
}

- (void)dealloc
{
    [gamelistsrc release];
    [modeslist3d release];
    [super dealloc];
}

- (void)populateVideoModes:(BOOL)firstTime
{
    int i, mode3d, fullscreen = ([fullscreenButton state] == NSControlStateValueOn);
    int idx3d = -1;
    int xdim = 0, ydim = 0, bpp = 0;

    if (firstTime) {
        xdim = settings.shared.xdim;
        ydim = settings.shared.ydim;
        bpp  = settings.shared.bpp;
    } else {
        mode3d = [[modeslist3d objectAtIndex:[videoMode3DPUButton indexOfSelectedItem]] intValue];
        if (mode3d >= 0) {
            xdim = validmode[mode3d].xdim;
            ydim = validmode[mode3d].ydim;
            bpp = validmode[mode3d].bpp;
        }

    }
    mode3d = videoCheckMode(&xdim, &ydim, bpp, fullscreen, 1);
    if (mode3d < 0) {
        int i, cd[] = { 32, 24, 16, 15, 8, 0 };
        for (i=0; cd[i]; ) { if (cd[i] >= bpp) i++; else break; }
        for ( ; cd[i]; i++) {
            mode3d = videoCheckMode(&xdim, &ydim, cd[i], fullscreen, 1);
            if (mode3d < 0) continue;
            break;
        }
    }

    [modeslist3d release];
    [videoMode3DPUButton removeAllItems];

    modeslist3d = [[NSMutableArray alloc] init];

    for (i = 0; i < validmodecnt; i++) {
        if (fullscreen == validmode[i].fs) {
            if (i == mode3d) idx3d = [modeslist3d count];
            [modeslist3d addObject:[NSNumber numberWithInt:i]];
            [videoMode3DPUButton addItemWithTitle:[NSString stringWithFormat:@"%d %C %d %d-bpp",
                                                   validmode[i].xdim, 0xd7, validmode[i].ydim, validmode[i].bpp]];
        }
    }

    if (idx3d >= 0) [videoMode3DPUButton selectItemAtIndex:idx3d];
}

- (void)fullscreenClicked:(id)sender
{
    UNREFERENCED_PARAMETER(sender);

    [self populateVideoModes:NO];
}

- (void)cancel:(id)sender
{
    UNREFERENCED_PARAMETER(sender);

    retval = 0;
}

- (void)start:(id)sender
{
    UNREFERENCED_PARAMETER(sender);

    int mode = [[modeslist3d objectAtIndex:[videoMode3DPUButton indexOfSelectedItem]] intValue];
    if (mode >= 0) {
        settings.shared.xdim = validmode[mode].xdim;
        settings.shared.ydim = validmode[mode].ydim;
        settings.shared.bpp = validmode[mode].bpp;
        settings.shared.fullscreen = validmode[mode].fs;
    }

    int row = [[gameList documentView] selectedRow];
    if (row >= 0) {
        settings.grp = [[gamelistsrc grpAtIndex:row] entryptr];
    }

    settings.shared.forcesetup = [alwaysShowButton state] == NSControlStateValueOn;

    retval = 1;
}

- (void)setupRunMode
{
    videoGetModes();

    [fullscreenButton setState: (settings.shared.fullscreen ? NSControlStateValueOn : NSControlStateValueOff)];
    [alwaysShowButton setState: (settings.shared.forcesetup ? NSControlStateValueOn : NSControlStateValueOff)];
    [self populateVideoModes:YES];

    // enable all the controls on the Configuration page
    NSEnumerator *enumerator = [[[tabViewItemSetup view] subviews] objectEnumerator];
    NSControl *control;
    while ((control = [enumerator nextObject]))
    {
        if ([control respondsToSelector:@selector(setEnabled:)])
            [control setEnabled:true];
    }

    gamelistsrc = [[GameListSource alloc] init];
    [[gameList documentView] setDataSource:gamelistsrc];
    [[gameList documentView] deselectAll:nil];

    if (settings.grp)
    {
        int row = [gamelistsrc findIndexForGrpname:[NSString stringWithUTF8String:settings.grp->filename]];
        if (row >= 0)
        {
            [[gameList documentView] scrollRowToVisible:row];
#if defined MAC_OS_X_VERSION_10_3 && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_3
            [[gameList documentView] selectRowIndexes:[NSIndexSet indexSetWithIndex:row] byExtendingSelection:NO];
#else
            [[gameList documentView] selectRow:row byExtendingSelection:NO];
#endif
        }
    }

    [cancelButton setEnabled:true];
    [startButton setEnabled:true];

    [tabView selectTabViewItem:tabViewItemSetup];
    [NSCursor unhide]; // Why should I need to do this?
}

- (void)setupMessagesMode
{
    [tabView selectTabViewItem:tabViewItemMessageLog];

    // disable all the controls on the Configuration page except "always show", so the
    // user can enable it if they want to while waiting for something else to happen
    NSEnumerator *enumerator = [[[tabViewItemSetup view] subviews] objectEnumerator];
    NSControl *control;
    while ((control = [enumerator nextObject]))
    {
        if (control != alwaysShowButton && [control respondsToSelector:@selector(setEnabled:)])
            [control setEnabled:false];
    }

    [cancelButton setEnabled:false];
    [startButton setEnabled:false];
}

- (void)putsMessage:(NSString *)str
{
    NSRange end;
    NSTextStorage *text = [messagesView textStorage];
    BOOL shouldAutoScroll;

    shouldAutoScroll = ((int)NSMaxY([messagesView bounds]) == (int)NSMaxY([messagesView visibleRect]));

    end.location = [text length];
    end.length = 0;

    [text beginEditing];
    [messagesView replaceCharactersInRange:end withString:str];
    [text endEditing];

    if (shouldAutoScroll) {
        end.location = [text length];
        end.length = 0;
        [messagesView scrollRangeToVisible:end];
    }
}

@end

static StartupWindow *startwin = nil;

int startwin_open(void)
{
    if (startwin != nil) return 1;

    startwin = [[StartupWindow alloc] init];
    if (startwin == nil) return -1;

    [startwin setupMessagesMode];

    [startwin center];
    [startwin makeKeyAndOrderFront:nil];

    CreateApplicationMenus();

    return 0;
}

int startwin_close(void)
{
    if (startwin == nil) return 1;

    [startwin close];
    [startwin release];
    startwin = nil;

    return 0;
}

int startwin_puts(const char *s)
{
    NSString *ns;

    if (!s) return -1;
    if (startwin == nil) return 1;

    ns = [NSString stringWithUTF8String:s];
    [startwin putsMessage:ns];
    [ns release];

    return 0;
}

int startwin_settitle(const char *s)
{
    NSString *ns;

    if (!s) return -1;
    if (startwin == nil) return 1;

    ns = [NSString stringWithUTF8String:s];
    [startwin setTitle:ns];
    [ns release];

    return 0;
}

int startwin_idle(void *v)
{
    UNREFERENCED_PARAMETER(v);

    if (startwin)
    {
        NSEvent *event;
        do
        {
            event = [nsapp nextEventMatchingMask:NSEventMaskAny untilDate:[NSDate date] inMode:NSDefaultRunLoopMode dequeue:YES];
            [nsapp sendEvent:event];
        }
        while (event != nil);

        [startwin displayIfNeeded];
        [nsapp updateWindows];
    }

    return 0;
}

int startwin_run(void)
{
    if (startwin == nil) return 0;

    settings.shared = gSetup;
    settings.grp = g_selectedGrp;

    [startwin setupRunMode];

    do
    {
        NSEvent *event = [nsapp nextEventMatchingMask:NSEventMaskAny untilDate:[NSDate distantFuture] inMode:NSDefaultRunLoopMode dequeue:YES];
        [nsapp sendEvent:event];
        [nsapp updateWindows];
    }
    while (retval == -1);

    [startwin setupMessagesMode];
    [nsapp updateWindows];

    if (retval) {
        gSetup = settings.shared;
        g_selectedGrp = settings.grp;
    }

    return retval;
}


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 _WIN32
#error Only for Windows
#endif

#include "renderlayer.h"

#ifdef STARTUP_SETUP_WINDOW

#define NEED_WINDOWSX_H
#define NEED_COMMCTRL_H
#define ONLY_USERDEFS

#include "_control.h"
#include "build.h"
#include "cache1d.h"
#include "compat.h"
#include "keyboard.h"
#include "control.h"
#include "exhumed.h"
#include "config.h"
#include "grpscan.h"
#include "startwin.game.h"
#include "windows_inc.h"

#define TAB_CONFIG 0
#define TAB_MESSAGES 1

static struct
{
    struct grpfile_t const * grp;
    char *gamedir;
    ud_setup_t shared;
    int polymer;
}
settings;

static HWND startupdlg;
static HWND pages[3];
static int done = -1;
static int mode = TAB_CONFIG;

static BUILDVFS_FIND_REC *finddirs;

static inline void clearfilenames(void)
{
    klistfree(finddirs);
    finddirs = NULL;
}

static inline void getfilenames(char const *path)
{
    clearfilenames();
    finddirs = klistpath(path,"*",BUILDVFS_FIND_DIR);
}

#define POPULATE_VIDEO 1
#define POPULATE_CONFIG 2
#define POPULATE_GAME 4
#define POPULATE_GAMEDIRS 8

#ifdef INPUT_MOUSE
#undef INPUT_MOUSE
#endif

#define INPUT_KB 0
#define INPUT_MOUSE 1
#define INPUT_JOYSTICK 2
#define INPUT_ALL 3

const char *controlstrings[] = { "Keyboard only", "Keyboard and mouse", "Keyboard and joystick", "All supported devices" };

static void PopulateForm(int32_t pgs)
{
    char buf[512];

    if (pgs & POPULATE_GAMEDIRS)
    {
        HWND hwnd = GetDlgItem(pages[TAB_CONFIG], IDCGAMEDIR);

        getfilenames("/");
        (void)ComboBox_ResetContent(hwnd);
        int const r = ComboBox_AddString(hwnd, "None");
        (void)ComboBox_SetItemData(hwnd, r, 0);
        (void)ComboBox_SetCurSel(hwnd, r);
        auto dirs = finddirs;
        for (int i=1, j=1; dirs != NULL; dirs=dirs->next)
        {
            if (Bstrcasecmp(dirs->name, "autoload") == 0)
            {
                j++;
                continue;
            }

            (void)ComboBox_AddString(hwnd, dirs->name);
            (void)ComboBox_SetItemData(hwnd, i, j);
            if (Bstrcasecmp(dirs->name, settings.gamedir) == 0)
                (void)ComboBox_SetCurSel(hwnd, i);

            i++;
            j++;
        }
    }

    if (pgs & POPULATE_VIDEO)
    {
        HWND hwnd = GetDlgItem(pages[TAB_CONFIG], IDCVMODE);
        int mode = videoCheckMode(&settings.shared.xdim, &settings.shared.ydim, settings.shared.bpp, settings.shared.fullscreen, 1);

        if (mode < 0 || (settings.shared.bpp < 15 && (settings.polymer)))
        {
            int CONSTEXPR cd[] = { 32, 24, 16, 15, 8, 0 };
            int i;

            for (i=0; cd[i];)
            {
                if (cd[i] >= settings.shared.bpp) i++;
                else break;
            }
            for (; cd[i]; i++)
            {
                mode = videoCheckMode(&settings.shared.xdim, &settings.shared.ydim, cd[i], settings.shared.fullscreen, 1);
                if (mode < 0) continue;
                settings.shared.bpp = cd[i];
                break;
            }
        }

        Button_SetCheck(GetDlgItem(pages[TAB_CONFIG], IDCFULLSCREEN), ((settings.shared.fullscreen) ? BST_CHECKED : BST_UNCHECKED));
        Button_SetCheck(GetDlgItem(pages[TAB_CONFIG], IDCPOLYMER), ((settings.polymer) ? BST_CHECKED : BST_UNCHECKED));

        (void)ComboBox_ResetContent(hwnd);

        for (int i=0; i<validmodecnt; i++)
        {
            if (validmode[i].fs != (settings.shared.fullscreen)) continue;
            if ((validmode[i].bpp < 15) && (settings.polymer)) continue;

            // all modes get added to the 3D mode list
            Bsprintf(buf, "%dx%d %s", validmode[i].xdim, validmode[i].ydim, validmode[i].bpp == 8 ? "software" : "OpenGL");
            int const j = ComboBox_AddString(hwnd, buf);
            (void)ComboBox_SetItemData(hwnd, j, i);
            if (i == mode)(void)ComboBox_SetCurSel(hwnd, j);
        }
    }

    if (pgs & POPULATE_CONFIG)
    {
        Button_SetCheck(GetDlgItem(pages[TAB_CONFIG], IDCALWAYSSHOW), (settings.shared.forcesetup ? BST_CHECKED : BST_UNCHECKED));
        Button_SetCheck(GetDlgItem(pages[TAB_CONFIG], IDCAUTOLOAD), (!(settings.shared.noautoload) ? BST_CHECKED : BST_UNCHECKED));

        HWND hwnd = GetDlgItem(pages[TAB_CONFIG], IDCINPUT);

        (void)ComboBox_ResetContent(hwnd);
        (void)ComboBox_SetCurSel(hwnd, 0);

        int j = 4;

#ifdef RENDERTYPEWIN
        if (di_disabled) j = 2;
#endif

        for (int i=0; i<j; i++)
        {
            (void)ComboBox_InsertString(hwnd, i, controlstrings[i]);
            (void)ComboBox_SetItemData(hwnd, i, i);

            switch (i)
            {
            case INPUT_MOUSE:
                if (settings.shared.usemouse && !settings.shared.usejoystick)(void)ComboBox_SetCurSel(hwnd, i);
                break;
            case INPUT_JOYSTICK:
                if (!settings.shared.usemouse && settings.shared.usejoystick)(void)ComboBox_SetCurSel(hwnd, i);
                break;
            case INPUT_ALL:
                if (settings.shared.usemouse && settings.shared.usejoystick)(void)ComboBox_SetCurSel(hwnd, i);
                break;
            }
        }
    }

    if (pgs & POPULATE_GAME)
    {
        HWND hwnd = GetDlgItem(pages[TAB_CONFIG], IDCDATA);

        for (auto fg = foundgrps; fg; fg=fg->next)
        {
            Bsprintf(buf, "%s\t%s", fg->type->name, fg->filename);
            int const j = ListBox_AddString(hwnd, buf);
            (void)ListBox_SetItemData(hwnd, j, (LPARAM)fg);
            if (settings.grp == fg)
                (void)ListBox_SetCurSel(hwnd, j);
        }
    }
}

static INT_PTR CALLBACK ConfigPageProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    switch (uMsg)
    {
    case WM_COMMAND:
        switch (LOWORD(wParam))
        {
        case IDCFULLSCREEN:
            settings.shared.fullscreen = !settings.shared.fullscreen;
            PopulateForm(POPULATE_VIDEO);
            return TRUE;
        case IDCPOLYMER:
            settings.polymer = !settings.polymer;
            if (settings.shared.bpp == 8) settings.shared.bpp = 32;
            PopulateForm(POPULATE_VIDEO);
            return TRUE;
        case IDCVMODE:
            if (HIWORD(wParam) == CBN_SELCHANGE)
            {
                int i = ComboBox_GetCurSel((HWND)lParam);
                if (i != CB_ERR) i = ComboBox_GetItemData((HWND)lParam, i);
                if (i != CB_ERR)
                {
                    settings.shared.xdim = validmode[i].xdim;
                    settings.shared.ydim = validmode[i].ydim;
                    settings.shared.bpp  = validmode[i].bpp;
                }
            }
            return TRUE;
        case IDCALWAYSSHOW:
            settings.shared.forcesetup = IsDlgButtonChecked(hwndDlg, IDCALWAYSSHOW) == BST_CHECKED;
            return TRUE;
        case IDCAUTOLOAD:
            settings.shared.noautoload = (IsDlgButtonChecked(hwndDlg, IDCAUTOLOAD) != BST_CHECKED);
            return TRUE;
        case IDCINPUT:
            if (HIWORD(wParam) == CBN_SELCHANGE)
            {
                int i = ComboBox_GetCurSel((HWND)lParam);
                if (i != CB_ERR) i = ComboBox_GetItemData((HWND)lParam, i);
                if (i != CB_ERR)
                {
                    switch (i)
                    {
                    case INPUT_KB:
                        settings.shared.usemouse = settings.shared.usejoystick = 0;
                        break;
                    case INPUT_MOUSE:
                        settings.shared.usemouse = 1;
                        settings.shared.usejoystick = 0;
                        break;
                    case INPUT_JOYSTICK:
                        settings.shared.usemouse = 0;
                        settings.shared.usejoystick = 1;
                        break;
                    case INPUT_ALL:
                        settings.shared.usemouse = settings.shared.usejoystick = 1;
                        break;
                    }
                }
            }
            return TRUE;

        case IDCGAMEDIR:
            if (HIWORD(wParam) == CBN_SELCHANGE)
            {
                int i = ComboBox_GetCurSel((HWND)lParam);
                if (i != CB_ERR) i = ComboBox_GetItemData((HWND)lParam, i);
                if (i != CB_ERR)
                {
                    if (i==0)
                        settings.gamedir = NULL;
                    else
                    {
                        BUILDVFS_FIND_REC *dir = finddirs;
                        for (int j = 1; dir != NULL; dir = dir->next, j++)
                        {
                            if (j == i)
                            {
                                settings.gamedir = dir->name;
                                break;
                            }
                        }
                    }
                }
            }
            return TRUE;
        case IDCDATA:
        {
            if (HIWORD(wParam) != LBN_SELCHANGE) break;
            intptr_t i = ListBox_GetCurSel((HWND)lParam);
            if (i != CB_ERR) i = ListBox_GetItemData((HWND)lParam, i);
            if (i != CB_ERR)
            {
                settings.grp = (grpfile_t const *)i;
            }
            return TRUE;
        }
        default:
            break;
        }
        break;
    default:
        break;
    }
    return FALSE;
}

static void SetPage(int pageNum)
{
    HWND tab = GetDlgItem(startupdlg, WIN_STARTWIN_TABCTL);
    auto const cur = SendMessage(tab, TCM_GETCURSEL, 0, 0);
    ShowWindow(pages[cur], SW_HIDE);
    SendMessage(tab, TCM_SETCURSEL, pageNum, 0);
    ShowWindow(pages[pageNum], SW_SHOW);
    mode = pageNum;

    SetFocus(GetDlgItem(startupdlg, WIN_STARTWIN_TABCTL));
}

static void EnableConfig(bool n)
{
    //EnableWindow(GetDlgItem(startupdlg, WIN_STARTWIN_CANCEL), n);
    EnableWindow(GetDlgItem(startupdlg, WIN_STARTWIN_START), n);
    EnableWindow(GetDlgItem(pages[TAB_CONFIG], IDCDATA), n);
    EnableWindow(GetDlgItem(pages[TAB_CONFIG], IDCFULLSCREEN), n);
    EnableWindow(GetDlgItem(pages[TAB_CONFIG], IDCGAMEDIR), n);
    EnableWindow(GetDlgItem(pages[TAB_CONFIG], IDCINPUT), n);
    EnableWindow(GetDlgItem(pages[TAB_CONFIG], IDCPOLYMER), n);
    EnableWindow(GetDlgItem(pages[TAB_CONFIG], IDCVMODE), n);
}

static INT_PTR CALLBACK startup_dlgproc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    static HBITMAP hbmp = NULL;

    switch (uMsg)
    {
    case WM_INITDIALOG:
    {
        // Fetch the positions (in screen coordinates) of all the windows we need to tweak
        RECT chrome = {};
        AdjustWindowRect(&chrome, GetWindowLong(hwndDlg, GWL_STYLE), FALSE);
        RECT rdlg;
        GetWindowRect(hwndDlg, &rdlg);

        // Knock off the non-client area of the main dialogue to give just the client area
        rdlg.left -= chrome.left;
        rdlg.top -= chrome.top;
        rdlg.right -= chrome.right;
        rdlg.bottom -= chrome.bottom;

        RECT rtab;
        GetWindowRect(GetDlgItem(hwndDlg, WIN_STARTWIN_TABCTL), &rtab);

        // Translate them to client-relative coordinates wrt the main dialogue window
        rtab.right -= rtab.left - 1;
        rtab.bottom -= rtab.top - 1;
        rtab.left  -= rdlg.left;
        rtab.top -= rdlg.top;

        RECT rcancel;
        GetWindowRect(GetDlgItem(hwndDlg, WIN_STARTWIN_CANCEL), &rcancel);

        rcancel.right -= rcancel.left - 1;
        rcancel.bottom -= rcancel.top - 1;
        rcancel.left -= rdlg.left;
        rcancel.top -= rdlg.top;

        RECT rstart;
        GetWindowRect(GetDlgItem(hwndDlg, WIN_STARTWIN_START), &rstart);

        rstart.right -= rstart.left - 1;
        rstart.bottom -= rstart.top - 1;
        rstart.left -= rdlg.left;
        rstart.top -= rdlg.top;

        // And then convert the main dialogue coordinates to just width/length
        rdlg.right -= rdlg.left - 1;
        rdlg.bottom -= rdlg.top - 1;
        rdlg.left = 0;
        rdlg.top = 0;

        // Load the bitmap into the bitmap control and fetch its dimensions
        hbmp = LoadBitmap((HINSTANCE)win_gethinstance(), MAKEINTRESOURCE(RSRC_BMP));

        HWND hwnd = GetDlgItem(hwndDlg, WIN_STARTWIN_BITMAP);
        SendMessage(hwnd, STM_SETIMAGE, IMAGE_BITMAP, (LPARAM)hbmp);

        RECT r;
        GetClientRect(hwnd, &r);

        int const xoffset = r.right;
        int const yoffset = r.bottom - rdlg.bottom;

        // Shift and resize the controls that require it
        rtab.left += xoffset;
        rtab.bottom += yoffset;
        rcancel.left += xoffset;
        rcancel.top += yoffset;
        rstart.left += xoffset;
        rstart.top += yoffset;
        rdlg.right += xoffset;
        rdlg.bottom += yoffset;

        // Move the controls to their new positions
        MoveWindow(GetDlgItem(hwndDlg, WIN_STARTWIN_TABCTL), rtab.left, rtab.top, rtab.right, rtab.bottom, FALSE);
        MoveWindow(GetDlgItem(hwndDlg, WIN_STARTWIN_CANCEL), rcancel.left, rcancel.top, rcancel.right, rcancel.bottom, FALSE);
        MoveWindow(GetDlgItem(hwndDlg, WIN_STARTWIN_START), rstart.left, rstart.top, rstart.right, rstart.bottom, FALSE);

        // Move the main dialogue to the centre of the screen
        HDC hdc = GetDC(NULL);
        rdlg.left = (GetDeviceCaps(hdc, HORZRES) - rdlg.right) / 2;
        rdlg.top = (GetDeviceCaps(hdc, VERTRES) - rdlg.bottom) / 2;
        ReleaseDC(NULL, hdc);
        MoveWindow(hwndDlg, rdlg.left + chrome.left, rdlg.top + chrome.left,
                   rdlg.right + (-chrome.left+chrome.right), rdlg.bottom + (-chrome.top+chrome.bottom), TRUE);

        // Add tabs to the tab control
        {
            static char textSetup[] = TEXT("Setup");
            static char textMessageLog[] = TEXT("Message Log");

            hwnd = GetDlgItem(hwndDlg, WIN_STARTWIN_TABCTL);

            TCITEM tab = {};
            tab.mask = TCIF_TEXT;
            tab.pszText = textSetup;
            SendMessage(hwnd, TCM_INSERTITEM, (WPARAM)TAB_CONFIG, (LPARAM)&tab);
            tab.mask = TCIF_TEXT;
            tab.pszText = textMessageLog;
            SendMessage(hwnd, TCM_INSERTITEM, (WPARAM)TAB_MESSAGES, (LPARAM)&tab);

            // Work out the position and size of the area inside the tab control for the pages
            ZeroMemory(&r, sizeof(r));
            GetClientRect(hwnd, &r);
            SendMessage(hwnd, TCM_ADJUSTRECT, FALSE, (LPARAM)&r);
            r.right -= r.left-1;
            r.bottom -= r.top-1;
            r.top += rtab.top;
            r.left += rtab.left;

            // Create the pages and position them in the tab control, but hide them
            pages[TAB_CONFIG] = CreateDialog((HINSTANCE)win_gethinstance(), MAKEINTRESOURCE(WIN_STARTWINPAGE_CONFIG), hwndDlg, ConfigPageProc);
            SetWindowPos(pages[TAB_CONFIG], hwnd, r.left, r.top, r.right, r.bottom, SWP_HIDEWINDOW);

            pages[TAB_MESSAGES] = GetDlgItem(hwndDlg, WIN_STARTWIN_MESSAGES);
            SetWindowPos(pages[TAB_MESSAGES], hwnd, r.left, r.top, r.right, r.bottom, SWP_HIDEWINDOW);

            // Tell the editfield acting as the console to exclude the width of the scrollbar
            GetClientRect(pages[TAB_MESSAGES], &r);
            r.right -= GetSystemMetrics(SM_CXVSCROLL)+4;
            r.left = r.top = 0;
            SendMessage(pages[TAB_MESSAGES], EM_SETRECTNP,0,(LPARAM)&r);

            // Set a tab stop in the game data listbox
            {
                DWORD tabs[1] = { 150 };
                (void)ListBox_SetTabStops(GetDlgItem(pages[TAB_CONFIG], IDCDATA), 1, tabs);
            }

            SetFocus(GetDlgItem(hwndDlg, WIN_STARTWIN_START));
            SetWindowText(hwndDlg, apptitle);
        }
        return FALSE;
    }

    case WM_NOTIFY:
    {
        auto nmhdr = (LPNMHDR)lParam;
        if (nmhdr->idFrom != WIN_STARTWIN_TABCTL) break;
        int const cur = SendMessage(nmhdr->hwndFrom, TCM_GETCURSEL,0,0);
        switch (nmhdr->code)
        {
            case TCN_SELCHANGING:
            case TCN_SELCHANGE:
                if (cur < 0 || !pages[cur])
                    break;
                ShowWindow(pages[cur], nmhdr->code == TCN_SELCHANGING ? SW_HIDE : SW_SHOW);
                return TRUE;
        }
        break;
    }

    case WM_CLOSE:
        if (mode == TAB_CONFIG) done = 0;
        else quitevent++;
        return TRUE;

    case WM_DESTROY:
        if (hbmp)
        {
            DeleteObject(hbmp);
            hbmp = NULL;
        }

        if (pages[TAB_CONFIG])
        {
            DestroyWindow(pages[TAB_CONFIG]);
            pages[TAB_CONFIG] = NULL;
        }

        startupdlg = NULL;
        return TRUE;

    case WM_COMMAND:
        switch (LOWORD(wParam))
        {
        case WIN_STARTWIN_CANCEL:
            if (mode == TAB_CONFIG) done = 0;
            else quitevent++;
            return TRUE;
        case WIN_STARTWIN_START:
            done = 1;
            return TRUE;
        }
        return FALSE;

    case WM_CTLCOLORSTATIC:
        if ((HWND)lParam == pages[TAB_MESSAGES])
            return (BOOL)(intptr_t)GetSysColorBrush(COLOR_WINDOW);
        break;

    default:
        break;
    }

    return FALSE;
}

bool startwin_isopen(void)
{
    return !!startupdlg;
}

int32_t startwin_open(void)
{
    if (startupdlg) return 1;
    INITCOMMONCONTROLSEX icc = { sizeof(icc), ICC_TAB_CLASSES };
    InitCommonControlsEx(&icc);
    startupdlg = CreateDialog((HINSTANCE)win_gethinstance(), MAKEINTRESOURCE(WIN_STARTWIN), NULL, startup_dlgproc);
    if (startupdlg)
    {
        SetPage(TAB_MESSAGES);
        EnableConfig(0);
        return 0;
    }
    return -1;
}

int32_t startwin_close(void)
{
    if (!startupdlg) return 1;
    DestroyWindow(startupdlg);
    startupdlg = NULL;
    return 0;
}

int32_t startwin_puts(const char *buf)
{
    if (!startupdlg) return 1;

    const HWND edctl = pages[TAB_MESSAGES];

    if (!edctl) return -1;

    static HWND dactrl = NULL;
    if (!dactrl) dactrl = GetDlgItem(startupdlg, WIN_STARTWIN_TABCTL);

    int const vis = ((int)SendMessage(dactrl, TCM_GETCURSEL,0,0) == TAB_MESSAGES);

    if (vis)
        SendMessage(edctl, WM_SETREDRAW, FALSE, 0);

    int const curlen = SendMessage(edctl, WM_GETTEXTLENGTH, 0,0);
    SendMessage(edctl, EM_SETSEL, (WPARAM)curlen, (LPARAM)curlen);

    int const   numlines = SendMessage(edctl, EM_GETLINECOUNT, 0, 0);
    static bool newline  = false;
    const char *p        = buf;

    while (*p)
    {
        if (newline)
        {
            SendMessage(edctl, EM_REPLACESEL, 0, (LPARAM)"\r\n");
            newline = false;
        }
        const char *q = p;
        while (*q && *q != '\n') q++;
        static char workbuf[1024];
        Bmemcpy(workbuf, p, q-p);
        if (*q == '\n')
        {
            if (!q[1])
            {
                newline = true;
                workbuf[q-p] = 0;
            }
            else
            {
                workbuf[q-p] = '\r';
                workbuf[q-p+1] = '\n';
                workbuf[q-p+2] = 0;
            }
            p = q+1;
        }
        else
        {
            workbuf[q-p] = 0;
            p = q;
        }
        SendMessage(edctl, EM_REPLACESEL, 0, (LPARAM)workbuf);
    }

    int const newnumlines = SendMessage(edctl, EM_GETLINECOUNT, 0, 0);
    SendMessage(edctl, EM_LINESCROLL, 0, newnumlines - numlines);

    if (vis)
        SendMessage(edctl, WM_SETREDRAW, TRUE, 0);

    return 0;
}

int32_t startwin_settitle(const char *str)
{
    if (!startupdlg) return 1;
    SetWindowText(startupdlg, str);
    return 0;
}

int32_t startwin_idle(void *v)
{
    if (!startupdlg || !IsWindow(startupdlg)) return 0;
    if (IsDialogMessage(startupdlg, (MSG *)v)) return 1;
    return 0;
}

int32_t startwin_run(void)
{
    if (!startupdlg) return 1;

    done = -1;

    SetPage(TAB_CONFIG);
    EnableConfig(1);

#ifdef POLYMER
    settings.polymer = (glrendmode == REND_POLYMER);
#else
    settings.polymer = 0;
#endif

    settings.shared = gSetup;
    settings.grp = g_selectedGrp;
    settings.gamedir = g_modDir;

    PopulateForm(-1);

    do
    {
        MSG msg;

        switch (GetMessage(&msg, NULL, 0,0))
        {
        case 0:
            done = 1;
            break;
        case -1:
            return -1;
        default:
            if (IsWindow(startupdlg) && IsDialogMessage(startupdlg, &msg))
                break;
            TranslateMessage(&msg);
            DispatchMessage(&msg);
            break;
        }
    }
    while (done < 0);

    SetPage(TAB_MESSAGES);
    EnableConfig(0);

    if (done)
    {
        gSetup = settings.shared;
#ifdef USE_OPENGL
        glrendmode = (settings.polymer) ? REND_POLYMER : REND_POLYMOST;
#endif
        g_selectedGrp = settings.grp;
        if (g_modDir != settings.gamedir)
            Bstrcpy(g_modDir, (g_noSetup == 0 && settings.gamedir != NULL) ? settings.gamedir : "/");
    }

    return done;
}

#endif // STARTUP_SETUP_WINDOW

repo_name: orochi/nblood

license: mit


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.
*/
//-------------------------------------------------------------------------

// resource ids
#define WIN_STARTWIN		1000
#define WIN_STARTWINPAGE_CONFIG 2000
#define WIN_STARTWIN_BITMAP	100	// banner bitmap
#define WIN_STARTWIN_TABCTL	101
#define WIN_STARTWIN_CANCEL	IDCANCEL
#define WIN_STARTWIN_START	IDOK

#define WIN_STARTWIN_MESSAGES	104	// output list box

#define RSRC_ICON		100
#define RSRC_BMP		200

// config page
#define IDCFULLSCREEN	100
#define IDCVMODE	    101
#define IDCSOUNDDRV	    102
#define IDCMIDIDEV	    103
#define IDCCDADEV	    104
#define IDCALWAYSSHOW	105
#define IDCDATA         106
#define IDCGAMEDIR      107
#define IDCPOLYMER      108
#define IDCAUTOLOAD     109
#define IDCINPUT	    110


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

This file is part of PCExhumed.

PCExhumed 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 "engine.h"
#include "player.h"
#include "anims.h"
#include "status.h"
#include "exhumed.h"
#include "sequence.h"
#include "init.h"
#include "names.h"
#include "items.h"
#include "view.h"
#include "trigdat.h"
#include "light.h"
#include "save.h"
#include <string.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include "typedefs.h"

//short nMaskY;
//short statusmask[MAXXDIM];

static short nAnimsFree = 0;

short message_timer = 0;
char message_text[80];
int magicperline;
int airperline;
int healthperline;
int nAirFrames;
int nCounter;
int nCounterDest;

short nStatusSeqOffset;
short nItemFrames;

int laststatusx;
int laststatusy;

int16_t nItemSeq;
short nDigit[3];

short nMagicFrames;
short nHealthLevel;
short nItemFrame;
short nMeterRange;
short nMagicLevel;
short nHealthFrame;
short nMagicFrame;

short statusx;
short statusy;
short nHealthFrames;
short airframe;

int16_t nFirstAnim;
int16_t nLastAnim;
short nItemAltSeq;

short airpages = 0;
short ammodelay = 3;
short nCounterBullet = -1;

struct statusAnim
{
    int16_t s1;
    int16_t s2;
//    int16_t nPage;
    int8_t nPrevAnim;
    int8_t nNextAnim;
};

#define kMaxStatusAnims		50

statusAnim StatusAnim[kMaxStatusAnims];
uint8_t StatusAnimsFree[kMaxStatusAnims];
uint8_t StatusAnimFlags[kMaxStatusAnims];

short nItemSeqOffset[] = {91, 72, 76, 79, 68, 87, 83};

short word_9AD54[kMaxPlayers] = {0, 0, 0, 0, 0, 0, 0, 0};
int dword_9AD64[kMaxPlayers] = {0, 0, 0, 0, 0, 0, 0, 0};

void SetCounterDigits();
void SetItemSeq();
void SetItemSeq2(int nSeqOffset);
void DestroyStatusAnim(short nAnim);

int BuildStatusAnim(int val, int nFlags)
{
    // destroy this anim if it already exists
    for (int i = nFirstAnim; i >= 0; i = StatusAnim[i].nPrevAnim)
    {
        if (StatusAnim[i].s1 == val) {
            DestroyStatusAnim(i);
            break;
        }
    }

    if (nAnimsFree <= 0) {
        return -1;
    }

    nAnimsFree--;

    uint8_t nStatusAnim = StatusAnimsFree[nAnimsFree];

    StatusAnim[nStatusAnim].nPrevAnim = -1;
    StatusAnim[nStatusAnim].nNextAnim = nLastAnim;

    if (nLastAnim < 0) {
        nFirstAnim = nStatusAnim;
    }
    else {
        StatusAnim[nLastAnim].nPrevAnim = nStatusAnim;
    }

    nLastAnim = nStatusAnim;

    StatusAnim[nStatusAnim].s1 = val;
    StatusAnim[nStatusAnim].s2 = 0;
    StatusAnimFlags[nStatusAnim] = nFlags;
//    StatusAnim[nStatusAnim].nPage = numpages;
    return nStatusAnim;
}

void RefreshStatus()
{
    short nLives = nPlayerLives[nLocalPlayer];
    if (nLives < 0 || nLives > kMaxPlayerLives) {
        bail2dos("illegal value for nPlayerLives #%d\n", nLocalPlayer);
    }

    // draws the red dots that indicate the lives amount
    BuildStatusAnim(145 + (2 * nLives), 0);

    uint16_t nKeys = PlayerList[nLocalPlayer].keys;

    int val = 37;

    for (int i = 0; i < 4; i++)
    {
        if (nKeys & 0x1000) {
            BuildStatusAnim(val, 0);
        }

        nKeys >>= 1;
        val += 2;
    }

    SetPlayerItem(nLocalPlayer, nPlayerItem[nLocalPlayer]);
    SetHealthFrame(0);
    SetMagicFrame();
    SetAirFrame();
}

void InitStatus()
{
    nStatusSeqOffset = SeqOffsets[kSeqStatus];
    nHealthFrames = SeqSize[nStatusSeqOffset + 1];
    int nPicNum   = seq_GetSeqPicnum(kSeqStatus, 1, 0);
    nMagicFrames  = SeqSize[nStatusSeqOffset + 129];
    nHealthFrame  = 0;
    nMagicFrame   = 0;
    nHealthLevel  = 0;
    nMagicLevel   = 0;
    nMeterRange   = tilesiz[nPicNum].y;
    magicperline  = 1000 / nMeterRange;
    healthperline = 800 / nMeterRange;
    nAirFrames = SeqSize[nStatusSeqOffset + 133];
    airperline = 100 / nAirFrames;
    nCounter   = 0;
    nCounterDest = 0;

    memset(nDigit, 0, sizeof(nDigit));

    SetCounter(0);
    SetHealthFrame(0);
    SetMagicFrame();

    for (int i = 0; i < kMaxStatusAnims; i++) {
        StatusAnimsFree[i] = i;
    }

    nLastAnim  = -1;
    nFirstAnim = -1;
    nItemSeq   = -1;
    nAnimsFree = kMaxStatusAnims;
    statusx    = xdim - 320;
    textpages  = 0;
    message_timer = 0;
    statusy = ydim - 200;
}

void MoveStatusAnims()
{
    for (int i = nFirstAnim; i >= 0; i = StatusAnim[i].nPrevAnim)
    {
        seq_MoveSequence(-1, nStatusSeqOffset + StatusAnim[i].s1, StatusAnim[i].s2);

        StatusAnim[i].s2++;

        short nSize = SeqSize[nStatusSeqOffset + StatusAnim[i].s1];

        if (StatusAnim[i].s2 >= nSize)
        {
            if (StatusAnimFlags[i] & 0x10) {
                StatusAnim[i].s2 = 0;
            }
            else {
                StatusAnim[i].s2 = nSize - 1; // restart it
            }
        }
    }
}

void DestroyStatusAnim(short nAnim)
{
    int8_t nPrev = StatusAnim[nAnim].nPrevAnim;
    int8_t nNext = StatusAnim[nAnim].nNextAnim;

    if (nNext >= 0) {
        StatusAnim[nNext].nPrevAnim = nPrev;
    }

    if (nPrev >= 0) {
        StatusAnim[nPrev].nNextAnim = nNext;
    }

    if (nAnim == nFirstAnim) {
        nFirstAnim = nPrev;
    }

    if (nAnim == nLastAnim) {
        nLastAnim = nNext;
    }

    StatusAnimsFree[nAnimsFree] = (uint8_t)nAnim;
    nAnimsFree++;
}

void DrawStatusAnims()
{
    for (int i = nFirstAnim; i >= 0; i = StatusAnim[i].nPrevAnim)
    {
        int nSequence = nStatusSeqOffset + StatusAnim[i].s1;

        seq_DrawStatusSequence(nSequence, StatusAnim[i].s2, 0);

/*
        if (StatusAnim[nAnim].s2 >= (SeqSize[nSequence] - 1))
        {
            if (!(StatusAnimFlags[nAnim] & 0x10))
            {
                StatusAnim[nAnim].nPage--;
                if (StatusAnim[nAnim].nPage <= 0) {
                    DestroyStatusAnim(nAnim);
                }
            }
        }
*/
    }
}

void SetMagicFrame()
{
    nMagicLevel = (kMaxMagic - PlayerList[nLocalPlayer].nMagic) / magicperline;

    if (nMagicLevel >= nMeterRange) {
        nMagicLevel = nMeterRange - 1;
    }

    if (nMagicLevel < 0) {
        nMagicLevel = 0;
    }

    SetItemSeq();
}

void SetHealthFrame(short nVal)
{
    nHealthLevel = (kMaxHealth - PlayerList[nLocalPlayer].nHealth) / healthperline;

    if (nHealthLevel >= nMeterRange ) {
        nHealthLevel = nMeterRange - 1;
    }

    if (nHealthLevel < 0) {
        nHealthLevel = 0;
    }

    if (nVal < 0) {
        BuildStatusAnim(4, 0);
    }
}

void SetAirFrame()
{
    airframe = PlayerList[nLocalPlayer].nAir / airperline;

    if (airframe >= nAirFrames)
    {
        airframe = nAirFrames - 1;
    }
    else if (airframe < 0)
    {
        airframe = 0;
    }
}

void SetCounter(short nVal)
{
    if (nVal <= 999)
    {
        if (nVal < 0) {
            nVal = 0;
        }
    }
    else {
        nVal = 999;
    }

    nCounterDest = nVal;
}

void SetCounterImmediate(short nVal)
{
    SetCounter(nVal);
    nCounter = nCounterDest;

    SetCounterDigits();
}

void SetCounterDigits()
{
    nDigit[2] = 3 * (nCounter / 100 % 10);
    nDigit[1] = 3 * (nCounter / 10 % 10);
    nDigit[0] = 3 * (nCounter % 10);
}

void SetItemSeq()
{
    short nItem = nPlayerItem[nLocalPlayer];
    if (nItem < 0)
    {
        nItemSeq = -1;
        return;
    }

    short nOffset = nItemSeqOffset[nItem];

    SetItemSeq2(nOffset);
}

void SetItemSeq2(int nSeqOffset)
{
    short nItem = nPlayerItem[nLocalPlayer];

    if (nItemMagic[nItem] <= PlayerList[nLocalPlayer].nMagic) {
        nItemAltSeq = 0;
    }
    else {
        nItemAltSeq = 2;
    }

    nItemFrame = 0;
    nItemSeq = nSeqOffset + nItemAltSeq;
    nItemFrames = SeqSize[nItemSeq + nStatusSeqOffset];
}

void SetPlayerItem(short nPlayer, short nItem)
{
    nPlayerItem[nPlayer] = nItem;

    if (nPlayer == nLocalPlayer)
    {
        SetItemSeq();
        if (nItem >= 0) {
            BuildStatusAnim(156 + (2 * PlayerList[nLocalPlayer].items[nItem]), 0);
        }
    }
}

void SetNextItem(int nPlayer)
{
    short nItem = nPlayerItem[nPlayer];

    int i;

    for (i = 6; i > 0; i--)
    {
        nItem++;
        if (nItem == 6)
            nItem = 0;

        if (PlayerList[nPlayer].items[nItem] != 0)
            break;
    }

    if (i > 0) {
        SetPlayerItem(nPlayer, nItem);
    }
}

void SetPrevItem(int nPlayer)
{
    if (nPlayerItem[nPlayer] == -1)
        return;

    int nItem = nPlayerItem[nPlayer];

    int i;

    for (i = 6; i > 0; i--)
    {
        nItem--;
        if (nItem < 0)
            nItem = 5;

        if (PlayerList[nPlayer].items[nItem] != 0)
            break;
    }

    if (i > 0) {
        SetPlayerItem(nPlayer, nItem);
    }
}

void MoveStatus()
{
    if (nItemSeq >= 0)
    {
        nItemFrame++;

        if (nItemFrame >= nItemFrames)
        {
            if (nItemSeq == 67) {
                SetItemSeq();
            }
            else
            {
                nItemSeq -= nItemAltSeq;

                if (nItemAltSeq || totalmoves & 0x1F)
                {
                    if (nItemSeq < 2) {
                        nItemAltSeq = 0;
                    }
                }
                else
                {
                    nItemAltSeq = 1;
                }

                nItemFrame = 0;
                nItemSeq += nItemAltSeq;
                nItemFrames = SeqSize[nStatusSeqOffset + nItemSeq];
            }
        }
    }

    if (message_timer)
    {
        message_timer -= 4;
        if (message_timer <= 0)
        {
            if (screensize > 0) {
                textpages = numpages;
            }

            message_timer = 0;
        }
    }

    nHealthFrame++;
    if (nHealthFrame >= nHealthFrames) {
        nHealthFrame = 0;
    }

    nMagicFrame++;
    if (nMagicFrame >= nMagicFrames) {
        nMagicFrame = 0;
    }

    MoveStatusAnims();

    if (nCounter == nCounterDest)
    {
        nCounter = nCounterDest;
        ammodelay = 3;
        return;
    }
    else
    {
        ammodelay--;
        if (ammodelay > 0) {
            return;
        }
    }

    int eax = nCounterDest - nCounter;

    if (eax <= 0)
    {
        if (eax >= -30)
        {
            for (int i = 0; i < 3; i++)
            {
                nDigit[i]--;

                if (nDigit[i] < 0)
                {
                    nDigit[i] += 30;
                }

                if (nDigit[i] < 27) {
                    break;
                }
            }
        }
        else
        {
            nCounter += (nCounterDest - nCounter) >> 1;
            SetCounterDigits();
            return;
        }
    }
    else
    {
        if (eax <= 30)
        {
            for (int i = 0; i < 3; i++)
            {
                nDigit[i]++;

                if (nDigit[i] <= 27) {
                    break;
                }

                if (nDigit[i] >= 30) {
                    nDigit[i] -= 30;
                }
            }
        }
        else
        {
            nCounter += (nCounterDest - nCounter) >> 1;
            SetCounterDigits();
            return;
        }
    }

    if (!(nDigit[0] % 3)) {
        nCounter = nDigit[0] / 3 + 100 * (nDigit[2] / 3) + 10 * (nDigit[1] / 3);
    }

    eax = nCounterDest - nCounter;
    if (eax < 0) {
        eax = -eax;
    }

    ammodelay = 4 - (eax >> 1);
    if (ammodelay < 1) {
        ammodelay = 1;
    }
}

void UnMaskStatus()
{
#if 0
    for (int i = 0; i < xdim; i++) {
        startdmost[i] = ydim;
    }
#endif
}

void MaskStatus()
{
#if 0
    for (int i = 0; i < xdim; i++)
    {
        short bx = startdmost[i];
        short cx = statusmask[i];

        if (bx > cx) {
            startdmost[i] = cx;
        }
    }
#endif
}

void LoadStatus()
{
#if 0
    int i;
    short nSize;
    short tmp;
    short buffer[1024];
//	memset(buffer, 0, sizeof(buffer)); // bjd - added by me

    for (i = 0; i < xdim; i++) {
        statusmask[i] = ydim;
    }

    nMaskY = ydim;

    int hStatus = kopen4load("status.msk", 1);
    if (!hStatus) {
        return;
    }

    kread(hStatus, &nSize, sizeof(nSize));

    int nCount = nSize >> 1;

    kread(hStatus, &tmp, sizeof(tmp));
    kread(hStatus, buffer, nSize);

    kclose(hStatus);

    short *pStatusMask = statusmask;

    for (i = 0; i < nCount; i++)
    {
        int v8 = ydim - ((ydim * buffer[i]) / 200);
        *pStatusMask++ = ydim - v8;

        if (bHiRes) {
            *pStatusMask++ = ydim - v8;
        }

        if (ydim - v8 < nMaskY) {
            nMaskY = ydim - v8;
        }
    }
#endif
}

void ClearStatusMessage()
{
    message_timer = 0;
    message_text[0] = '\0';
}

void StatusMessage(int messageTime, const char *fmt, ...)
{
    message_timer = messageTime;

    va_list args;
    va_start(args, fmt);

    vsprintf(message_text, fmt, args);

    if (screensize > 0) {
        textpages = numpages;
    }
}

void DrawSnakeCamStatus()
{
    printext(0, 0, "S E R P E N T   C A M", kTileFont);
}

void DrawStatus()
{
    char numberBuf[10] = {0};
    char stringBuf[20] = {0};
    char coordBuf[50] = {0}; // not sure of the size for this?

    if (!bFullScreen && nNetTime)
    {
        // bjd - commenting out this check seems to fix the black status bar at 320x200 resolution
//		if (bHiRes) {
            NoClip();
//		}

        // draw the main bar itself
        seq_DrawStatusSequence(nStatusSeqOffset, 0, 0);

        seq_DrawStatusSequence(nStatusSeqOffset + 128, 0, 0);
        seq_DrawStatusSequence(nStatusSeqOffset + 127, 0, 0);
        seq_DrawStatusSequence(nStatusSeqOffset + 1, nHealthFrame, nHealthLevel);
        seq_DrawStatusSequence(nStatusSeqOffset + 129, nMagicFrame, nMagicLevel);
        seq_DrawStatusSequence(nStatusSeqOffset + 125, 0, 0); // draw ankh on health pool
        seq_DrawStatusSequence(nStatusSeqOffset + 130, 0, 0); // draw health pool frame (top)
        seq_DrawStatusSequence(nStatusSeqOffset + 131, 0, 0); // magic pool frame (bottom)

        if (nItemSeq >= 0) {
            seq_DrawStatusSequence(nItemSeq + nStatusSeqOffset, nItemFrame, 0);
        }

        // draws health level dots, animates breathing lungs and other things
        DrawStatusAnims();

        // draw the blue air level meter when underwater (but not responsible for animating the breathing lungs otherwise)
        if (airpages)
        {
            seq_DrawStatusSequence(nStatusSeqOffset + 133, airframe, 0);
            // airpages--;
        }

        // draw compass
        seq_DrawStatusSequence(nStatusSeqOffset + 35, ((inita + 128) & kAngleMask) >> 8, 0);

        /*
        if (bCoordinates)
        {
            sprintf(numberBuf, "%i", lastfps);
            // char *cFPS = itoa(lastfps, numberBuf, 10);
            printext(xdim - 20, nViewTop, numberBuf, kTile159, -1);
        }
        */

        // draw ammo count
        seq_DrawStatusSequence(nStatusSeqOffset + 44, nDigit[2], 0);
        seq_DrawStatusSequence(nStatusSeqOffset + 45, nDigit[1], 0);
        seq_DrawStatusSequence(nStatusSeqOffset + 46, nDigit[0], 0);

        // bjd - commenting out this check seems to fix the black status bar at 320x200 resolution
//		if (bHiRes) {
            Clip();
//		}
    }

    if (nNetPlayerCount)
    {
        NoClip();

        int shade;

        if ((int)totalclock / kTimerTicks & 1) {
            shade = -100;
        }
        else {
            shade = 127;
        }

        int nTile = kTile3593;

        int x = 320 / (nTotalPlayers + 1);

        for (int i = 0; i < nTotalPlayers; i++)
        {
            int nScore = nPlayerScore[i];
            if (word_9AD54[i] == nScore)
            {
                int v9 = dword_9AD64[i];
                if (v9 && v9 <= (int)totalclock) {
                    dword_9AD64[i] = 0;
                }
            }
            else
            {
                word_9AD54[i] = nScore;
                dword_9AD64[i] = (int)totalclock + 30;
            }

            overwritesprite(x, 7, nTile, 0, 3, kPalNormal);

            if (i != nLocalPlayer) {
                shade = -100;
            }

            sprintf(stringBuf, "%d", nPlayerScore[i]);
            int nStringLen = MyGetStringWidth(stringBuf);

            myprintext(x - (nStringLen / 2), 4, stringBuf, shade);

            x *= 2;
            nTile++;
        }

        if (nNetTime >= 0)
        {
            int y = nViewTop;

            if (nNetTime)
            {
                int v12 = (nNetTime + 29) / 30 % 60;
                int v13 = (nNetTime + 29) / 1800;
                nNetTime += 29;

                sprintf(stringBuf, "%d.%02d", v13, v12);

                if (bHiRes) {
                    y = nViewTop / 2;
                }

                if (nViewTop <= 0) {
                    y += 20;
                }
                else {
                    y += 15;
                }

                nNetTime -= 29;
            }
            else
            {
                y = 100;
                strcpy(stringBuf, "GAME OVER");
            }

            int nLenString = MyGetStringWidth(stringBuf);
            myprintext((320 - nLenString) / 2, y, stringBuf, 0);
        }

        Clip();
    }

    if (bCoordinates)
    {
        int nSprite = PlayerList[nLocalPlayer].nSprite;

        int x = (nViewLeft + nViewRight) / 2;

        sprintf(coordBuf, "X %d", (int)sprite[nSprite].x);
        printext(x, nViewTop + 1, coordBuf, kTileFont);

        sprintf(coordBuf, "Y %d", (int)sprite[nSprite].y);
        printext(x, nViewTop + 10, coordBuf, kTileFont);
    }

    if (bHolly)
    {
        sprintf(message_text, "HOLLY: %s", sHollyStr);
        printext(0, 0, message_text, kTileFont);
    }
    else if (nSnakeCam < 0)
    {
        if (message_timer) {
            printext(0, 0, message_text, kTileFont);
        }
    }
}

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

void StatusLoadSave::Load()
{
    Read(&nAnimsFree, sizeof(nAnimsFree));
    Read(&message_timer, sizeof(message_timer));
    Read(&message_text, sizeof(message_text));
    Read(&magicperline, sizeof(magicperline));
    Read(&airperline, sizeof(airperline));
    Read(&healthperline, sizeof(healthperline));
    Read(&nAirFrames, sizeof(nAirFrames));
    Read(&nCounter, sizeof(nCounter));
    Read(&nCounterDest, sizeof(nCounterDest));
    Read(&nStatusSeqOffset, sizeof(nStatusSeqOffset));
    Read(&nItemFrames, sizeof(nItemFrames));
    Read(&laststatusx, sizeof(laststatusx));
    Read(&laststatusy, sizeof(laststatusy));
    Read(&nItemSeq, sizeof(nItemSeq));
    Read(nDigit, sizeof(nDigit));
    Read(&nMagicFrames, sizeof(nMagicFrames));
    Read(&nHealthLevel, sizeof(nHealthLevel));
    Read(&nItemFrame, sizeof(nItemFrame));
    Read(&nMeterRange, sizeof(nMeterRange));
    Read(&nMagicLevel, sizeof(nMagicLevel));
    Read(&nHealthFrame, sizeof(nHealthFrame));
    Read(&nMagicFrame, sizeof(nMagicFrame));
    Read(&statusx, sizeof(statusx));
    Read(&statusy, sizeof(statusy));
    Read(&nHealthFrames, sizeof(nHealthFrames));
    Read(&airframe, sizeof(airframe));
    Read(&nFirstAnim, sizeof(nFirstAnim));
    Read(&nLastAnim, sizeof(nLastAnim));
    Read(&nItemAltSeq, sizeof(nItemAltSeq));
    Read(&airpages, sizeof(airpages));
    Read(&ammodelay, sizeof(ammodelay));
    Read(&nCounterBullet, sizeof(nCounterBullet));

    Read(StatusAnim, sizeof(StatusAnim));
    Read(StatusAnimsFree, sizeof(StatusAnimsFree));
    Read(StatusAnimFlags, sizeof(StatusAnimFlags));
}

void StatusLoadSave::Save()
{
    Write(&nAnimsFree, sizeof(nAnimsFree));
    Write(&message_timer, sizeof(message_timer));
    Write(&message_text, sizeof(message_text));
    Write(&magicperline, sizeof(magicperline));
    Write(&airperline, sizeof(airperline));
    Write(&healthperline, sizeof(healthperline));
    Write(&nAirFrames, sizeof(nAirFrames));
    Write(&nCounter, sizeof(nCounter));
    Write(&nCounterDest, sizeof(nCounterDest));
    Write(&nStatusSeqOffset, sizeof(nStatusSeqOffset));
    Write(&nItemFrames, sizeof(nItemFrames));
    Write(&laststatusx, sizeof(laststatusx));
    Write(&laststatusy, sizeof(laststatusy));
    Write(&nItemSeq, sizeof(nItemSeq));
    Write(nDigit, sizeof(nDigit));
    Write(&nMagicFrames, sizeof(nMagicFrames));
    Write(&nHealthLevel, sizeof(nHealthLevel));
    Write(&nItemFrame, sizeof(nItemFrame));
    Write(&nMeterRange, sizeof(nMeterRange));
    Write(&nMagicLevel, sizeof(nMagicLevel));
    Write(&nHealthFrame, sizeof(nHealthFrame));
    Write(&nMagicFrame, sizeof(nMagicFrame));
    Write(&statusx, sizeof(statusx));
    Write(&statusy, sizeof(statusy));
    Write(&nHealthFrames, sizeof(nHealthFrames));
    Write(&airframe, sizeof(airframe));
    Write(&nFirstAnim, sizeof(nFirstAnim));
    Write(&nLastAnim, sizeof(nLastAnim));
    Write(&nItemAltSeq, sizeof(nItemAltSeq));
    Write(&airpages, sizeof(airpages));
    Write(&ammodelay, sizeof(ammodelay));
    Write(&nCounterBullet, sizeof(nCounterBullet));

    Write(StatusAnim, sizeof(StatusAnim));
    Write(StatusAnimsFree, sizeof(StatusAnimsFree));
    Write(StatusAnimFlags, sizeof(StatusAnimFlags));
}

static StatusLoadSave* myLoadSave;

void StatusLoadSaveConstruct()
{
    myLoadSave = new StatusLoadSave();
}


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

This file is part of PCExhumed.

PCExhumed 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 __status_h__
#define __status_h__

//extern short nMaskY;
extern short nCounterBullet;
extern short airpages;

void RefreshStatus();
void InitStatus();
void UnMaskStatus();
void MaskStatus();
void LoadStatus();
void SetPlayerItem(short nPlayer, short nItem);
void SetMagicFrame();
void SetHealthFrame(short nVal);
void SetAirFrame();
void MoveStatus();
void DrawSnakeCamStatus();
void DrawStatus();
int BuildStatusAnim(int val, int nFlags);
void SetNextItem(int nPlayer);
void SetPrevItem(int nPlayer);
void SetCounter(short nVal);
void SetCounterImmediate(short nVal);

void ClearStatusMessage();
void StatusMessage(int messageTime, const char* fmt, ...);

#endif


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

This file is part of PCExhumed.

PCExhumed 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 "stream.h"


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

This file is part of PCExhumed.

PCExhumed 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 __stream_h__
#define __stream_h__

#endif


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

This file is part of PCExhumed.

PCExhumed 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 "switch.h"
#include "exhumed.h"
#include "runlist.h"
#include "engine.h"
#include "player.h"
#include "sound.h"
#include "save.h"
#include "status.h"
#include <string.h>
#include <assert.h>

struct Switch
{
    short field_0;
    short nPause;
    short nChannel;
    short nLink;
    short field_8;
    short nSector;
    short field_C;
    short nWall;
    short field_10;
    uint16_t field_12;
    short field_14;
//  char pad[10];
};

short LinkCount = -1;
short SwitchCount = -1;

int8_t LinkMap[kMaxLinks][8];
Switch SwitchData[kMaxSwitches];

void InitLink()
{
    LinkCount = kMaxLinks;
}

int BuildLink(int nCount, ...)
{
    if (LinkCount <= 0) {
        return -1;
    }

    va_list list;
    va_start(list, nCount);

    LinkCount--;

    for (int i = 0; i < 8; i++)
    {
        int ebx;

        if (i >= nCount)
        {
            ebx = -1;
        }
        else
        {
            ebx = va_arg(list, int);
        }

        LinkMap[LinkCount][i] = (int8_t)ebx;
    }
    va_end(list);

    return LinkCount;
}

void InitSwitch()
{
    SwitchCount = kMaxSwitches;
    memset(SwitchData, 0, sizeof(SwitchData));
}

int BuildSwReady(int nChannel, short nLink)
{
    if (SwitchCount <= 0 || nLink < 0) {
        bail2dos("Too many switch readys!\n");
        return -1;
    }

    SwitchCount--;
    SwitchData[SwitchCount].nChannel = nChannel;
    SwitchData[SwitchCount].nLink = nLink;

    return SwitchCount;
}

void FuncSwReady(int a, int UNUSED(b), int nRun)
{
    short nSwitch = RunData[nRun].nVal;
    assert(nSwitch >= 0 && nSwitch < kMaxSwitches);

    int nMessage = a & 0x7F0000;

    short nChannel = SwitchData[nSwitch].nChannel;
    short nLink = SwitchData[nSwitch].nLink;

    switch (nMessage)
    {
        case 0x10000:
            return;

        case 0x30000:
        {
            assert(sRunChannels[nChannel].c < 8);
            int8_t nVal = LinkMap[nLink][sRunChannels[nChannel].c];
            if (nVal >= 0) {
                runlist_ChangeChannel(nChannel, nVal);
            }

            break;
        }

        default:
            return;
    }
}

int BuildSwPause(int nChannel, int nLink, int ebx)
{
    for (int i = kMaxSwitches - 1; i >= SwitchCount; i--)
    {
        if (SwitchData[i].nChannel == nChannel && SwitchData[i].nPause != 0) {
            return i;
        }
    }

    if (SwitchCount <= 0 || nLink < 0) {
        bail2dos("Too many switches!\n");
        return -1;
    }

    SwitchCount--;

    SwitchData[SwitchCount].nChannel = nChannel;
    SwitchData[SwitchCount].nLink = nLink;
    SwitchData[SwitchCount].nPause = ebx;
    SwitchData[SwitchCount].field_8 = -1;

    return SwitchCount;
}

void FuncSwPause(int a, int UNUSED(b), int nRun)
{
    short nSwitch = RunData[nRun].nVal;
    assert(nSwitch >= 0 && nSwitch < kMaxSwitches);

    int nMessage = a & 0x7F0000;

    short nChannel = SwitchData[nSwitch].nChannel;
    short nLink = SwitchData[nSwitch].nLink;

    switch (nMessage)
    {
        default:
            return;

        case 0x10000:
        {
            if (SwitchData[nSwitch].field_8 >= 0)
            {
                runlist_SubRunRec(SwitchData[nSwitch].field_8);
                SwitchData[nSwitch].field_8 = -1;
            }

            return;
        }

        case 0x20000:
        {
            SwitchData[nSwitch].field_0--;
            if (SwitchData[nSwitch].field_0 <= 0)
            {
                runlist_SubRunRec(SwitchData[nSwitch].field_8);
                SwitchData[nSwitch].field_8 = -1;

                assert(sRunChannels[nChannel].c < 8);
                assert(nLink < 1024);

                runlist_ChangeChannel(nChannel, LinkMap[nLink][sRunChannels[nChannel].c]);
            }

            return;
        }

        case 0x30000:
        {
            assert(sRunChannels[nChannel].c < 8);

            if (LinkMap[nLink][sRunChannels[nChannel].c] < 0) {
                return;
            }

            if (SwitchData[nSwitch].field_8 >= 0) {
                return;
            }

            SwitchData[nSwitch].field_8 = runlist_AddRunRec(NewRun, RunData[nRun].nVal, RunData[nRun].nRef);

            int eax;

            if (SwitchData[nSwitch].nPause <= 0)
            {
                eax = 100;
            }
            else
            {
                eax = SwitchData[nSwitch].nPause;
            }

            SwitchData[nSwitch].field_0 = eax;
            return;
        }
    }
}

int BuildSwStepOn(int nChannel, int nLink, int nSector)
{
    if (SwitchCount <= 0 || nLink < 0 || nSector < 0)
        bail2dos("Too many switches!\n");

    int nSwitch = --SwitchCount;

    SwitchData[nSwitch].nChannel = nChannel;
    SwitchData[nSwitch].nLink = nLink;
    SwitchData[nSwitch].nSector = nSector;
    SwitchData[nSwitch].field_C = -1;

    return nSwitch;
}

void FuncSwStepOn(int a, int UNUSED(b), int nRun)
{
    short nSwitch = RunData[nRun].nVal;
    assert(nSwitch >= 0 && nSwitch < kMaxSwitches);

    short nLink = SwitchData[nSwitch].nLink;
    short nChannel = SwitchData[nSwitch].nChannel;
    short nSector = SwitchData[nSwitch].nSector;

    assert(sRunChannels[nChannel].c < 8);

    int8_t var_14 = LinkMap[nLink][sRunChannels[nChannel].c];

    int nMessage = a & 0x7F0000;

    switch (nMessage)
    {
        default:
            return;

        case 0x10000:
        {
            if (SwitchData[nSwitch].field_C >= 0)
            {
                runlist_SubRunRec(SwitchData[nSwitch].field_C);
                SwitchData[nSwitch].field_C = -1;
            }

            if (var_14 >= 0)
            {
                SwitchData[nSwitch].field_C = runlist_AddRunRec(sector[nSector].lotag - 1, RunData[nRun].nVal, RunData[nRun].nRef);
            }

            return;
        }

        case 0x50000:
        {
            if (var_14 != sRunChannels[nChannel].c)
            {
                short nWall = sector[nSector].wallptr;
                PlayFXAtXYZ(StaticSound[nSwitchSound], wall[nWall].x, wall[nWall].y, sector[nSector].floorz, nSector);

                assert(sRunChannels[nChannel].c < 8);

                runlist_ChangeChannel(nChannel, LinkMap[nLink][sRunChannels[nChannel].c]);
            }
        }

        return;
    }

}

int BuildSwNotOnPause(int nChannel, int nLink, int nSector, int ecx)
{
    if (SwitchCount <= 0 || nLink < 0 || nSector < 0)
        bail2dos("Too many switches!\n");

    int nSwitch = --SwitchCount;

    SwitchData[nSwitch].nChannel = nChannel;
    SwitchData[nSwitch].nLink    = nLink;
    SwitchData[nSwitch].nPause  = ecx;
    SwitchData[nSwitch].nSector  = nSector;
    SwitchData[nSwitch].field_8  = -1;
    SwitchData[nSwitch].field_C  = -1;

    return nSwitch;
}

void FuncSwNotOnPause(int a, int UNUSED(b), int nRun)
{
    short nSwitch = RunData[nRun].nVal;
    assert(nSwitch >= 0 && nSwitch < kMaxSwitches);

    int nMessage = a & 0x7F0000;

    short nChannel = SwitchData[nSwitch].nChannel;
    short nLink = SwitchData[nSwitch].nLink;

    switch (nMessage)
    {
        default:
            return;

        case 0x10000:
        {
            if (SwitchData[nSwitch].field_C >= 0)
            {
                runlist_SubRunRec(SwitchData[nSwitch].field_C);
                SwitchData[nSwitch].field_C = -1;
            }

            if (SwitchData[nSwitch].field_8 >= 0)
            {
                runlist_SubRunRec(SwitchData[nSwitch].field_8);
                SwitchData[nSwitch].field_8 = -1;
            }

            return;
        }

        case 0x20000:
        {
            SwitchData[nSwitch].field_0 -= 4;
            if (SwitchData[nSwitch].field_0 <= 0)
            {
                assert(sRunChannels[nChannel].c < 8);

                runlist_ChangeChannel(nChannel, LinkMap[nLink][sRunChannels[nChannel].c]);
            }

            return;
        }

        case 0x30000:
        {
            assert(sRunChannels[nChannel].c < 8);

            if (LinkMap[nLink][sRunChannels[nChannel].c] >= 0)
            {
                if (SwitchData[nSwitch].field_8 < 0)
                {
                    SwitchData[nSwitch].field_8 = runlist_AddRunRec(NewRun, RunData[nRun].nVal, RunData[nRun].nRef);

                    short nSector = SwitchData[nSwitch].nSector;

                    SwitchData[nSwitch].field_0 = SwitchData[nSwitch].nPause;
                    SwitchData[nSwitch].field_C = runlist_AddRunRec(sector[nSector].lotag - 1, RunData[nRun].nVal, RunData[nRun].nRef);
                }
            }

            return;
        }

        case 0x50000:
        {
            SwitchData[nSwitch].field_0 = SwitchData[nSwitch].nPause;
            return;
        }
    }
}

int BuildSwPressSector(int nChannel, int nLink, int nSector, int keyMask)
{
    if (SwitchCount <= 0 || nLink < 0 || nSector < 0)
        bail2dos("Too many switches!\n");

    int nSwitch = --SwitchCount;

    SwitchData[nSwitch].nChannel = nChannel;
    SwitchData[nSwitch].nLink = nLink;
    SwitchData[nSwitch].nSector = nSector;
    SwitchData[nSwitch].field_12 = keyMask;
    SwitchData[nSwitch].field_C = -1;

    return nSwitch;
}

void FuncSwPressSector(int a, int UNUSED(b), int nRun)
{
    short nSwitch = RunData[nRun].nVal;
    assert(nSwitch >= 0 && nSwitch < kMaxSwitches);

    int nMessage = a & 0x7F0000;

    short nChannel = SwitchData[nSwitch].nChannel;
    short nLink = SwitchData[nSwitch].nLink;
    short nPlayer = a & 0xFFFF;

    switch (nMessage)
    {
        default:
            return;

        case 0x10000:
        {
            if (SwitchData[nSwitch].field_C >= 0)
            {
                runlist_SubRunRec(SwitchData[nSwitch].field_C);
                SwitchData[nSwitch].field_C = -1;
            }

            assert(sRunChannels[nChannel].c < 8);

            if (LinkMap[nLink][sRunChannels[nChannel].c] < 0) {
                return;
            }

            short nSector = SwitchData[nSwitch].nSector;

            SwitchData[nSwitch].field_C = runlist_AddRunRec(sector[nSector].lotag - 1, RunData[nRun].nVal, RunData[nRun].nRef);
            return;
        }

        case 0x40000:
        {
            if ((PlayerList[nPlayer].keys & SwitchData[nSwitch].field_12) == SwitchData[nSwitch].field_12)
            {
                runlist_ChangeChannel(nChannel, LinkMap[nLink][sRunChannels[nChannel].c]);
            }
            else
            {
                if (SwitchData[nSwitch].field_12)
                {
                    short nSprite = PlayerList[nPlayer].nSprite;
                    PlayFXAtXYZ(StaticSound[nSwitchSound], sprite[nSprite].x, sprite[nSprite].y, 0, sprite[nSprite].sectnum);

                    StatusMessage(300, "YOU NEED THE KEY FOR THIS DOOR");
                }
            }
        }
    }
}

int BuildSwPressWall(short nChannel, short nLink, short nWall)
{
    if (SwitchCount <= 0 || nLink < 0 || nWall < 0) {
        bail2dos("Too many switches!\n");
    }

    SwitchCount--;

    SwitchData[SwitchCount].nChannel = nChannel;
    SwitchData[SwitchCount].nLink = nLink;
    SwitchData[SwitchCount].nWall = nWall;
    SwitchData[SwitchCount].field_10 = -1;
    SwitchData[SwitchCount].field_14 = 0;

    return SwitchCount;
}

void FuncSwPressWall(int a, int UNUSED(b), int nRun)
{
    short nSwitch = RunData[nRun].nVal;
    assert(nSwitch >= 0 && nSwitch < kMaxSwitches);

    short nChannel = SwitchData[nSwitch].nChannel;
    short nLink = SwitchData[nSwitch].nLink;

    // TEMP
//	assert(nLink < 1024);
//	assert(nChannel < 8);

    int nMessage = a & 0x7F0000;

    switch (nMessage)
    {
        default:
            return;

        case 0x30000:
        {
            if (SwitchData[nSwitch].field_10 >= 0)
            {
                runlist_SubRunRec(SwitchData[nSwitch].field_10);
                SwitchData[nSwitch].field_10 = -1;
            }

            if (LinkMap[nLink][sRunChannels[nChannel].c] >= 0)
            {
                short nWall = SwitchData[nSwitch].nWall;
                SwitchData[nSwitch].field_10 = runlist_AddRunRec(wall[nWall].lotag - 1, RunData[nRun].nVal, RunData[nRun].nRef);
            }

            return;
        }

        case 0x40000:
        {
            int8_t cx = LinkMap[nLink][sRunChannels[nChannel].c];

            runlist_ChangeChannel(nChannel, LinkMap[nLink][sRunChannels[nChannel].c]);

            if (cx < 0 || LinkMap[nLink][cx] < 0)
            {
                runlist_SubRunRec(SwitchData[nSwitch].field_10);
                SwitchData[nSwitch].field_10 = -1;
            }

            short nWall = SwitchData[nSwitch].nWall;
            short nSector = SwitchData[nSwitch].nSector; // CHECKME - where is this set??

            PlayFXAtXYZ(StaticSound[nSwitchSound], wall[nWall].x, wall[nWall].y, 0, nSector);
            return;
        }
    }
}

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

void SwitchLoadSave::Load()
{
    Read(&LinkCount, sizeof(LinkCount));
    Read(&SwitchCount, sizeof(SwitchCount));
    Read(LinkMap, sizeof(LinkMap));
    Read(SwitchData, sizeof(SwitchData));
}

void SwitchLoadSave::Save()
{
    Write(&LinkCount, sizeof(LinkCount));
    Write(&SwitchCount, sizeof(SwitchCount));
    Write(LinkMap, sizeof(LinkMap));
    Write(SwitchData, sizeof(SwitchData));
}

static SwitchLoadSave* myLoadSave;

void SwitchLoadSaveConstruct()
{
    myLoadSave = new SwitchLoadSave();
}


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

This file is part of PCExhumed.

PCExhumed 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 __switch_h__
#define __switch_h__

#define kMaxLinks		1024
#define kMaxSwitches	1024

void InitLink();
void InitSwitch();

void FuncSwReady(int, int, int);
void FuncSwPause(int, int, int);
void FuncSwStepOn(int, int, int);
void FuncSwNotOnPause(int, int, int);
void FuncSwPressSector(int, int, int);
void FuncSwPressWall(int, int, int);

int BuildSwPause(int nChannel, int nLink, int ebx);
int BuildSwNotOnPause(int nChannel, int nLink, int nSector, int ecx);
int BuildLink(int nCount, ...);
int BuildSwPressSector(int nChannel, int nLink, int nSector, int keyMask);
int BuildSwStepOn(int nChannel, int nLink, int nSector);
int BuildSwReady(int nChannel, short nLink);

int BuildSwPressWall(short nChannel, short nLink, short nWall);

#endif


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

This file is part of PCExhumed.

PCExhumed 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 "text2.h"


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

This file is part of PCExhumed.

PCExhumed 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 __text2_h__
#define __text2_h__

#endif


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

This file is part of PCExhumed.

PCExhumed 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 "compat.h"
#include "baselayer.h"
#include "timer.h"
#include "exhumed.h"

void timerhandler();

void InitTimer()
{
    htimer = 1;

    timerInit(kTimerTicks);
    timerSetCallback(timerhandler);
}


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

This file is part of PCExhumed.

PCExhumed 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 __timer_h__
#define __timer_h__

#define kTimerTicks		120

void InitTimer();

#ifdef __WATCOMC__
void uninittimer();
#endif

#endif


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

This file is part of PCExhumed.

PCExhumed 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 __trigdat_h__
#define __trigdat_h__

#define kAngleMask	0x7FF

int GetMyAngle(int x, int y);

int AngleDiff(short a, short b);
int AngleDelta(int a, int b, int c);

#endif


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

This file is part of PCExhumed.

PCExhumed 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 __typedefs_h__
#define __typedefs_h__

#define kTrue (0 == 0)
#define kFalse (0 != 0)

#endif


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

This file is part of PCExhumed.

PCExhumed 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 __util_h__
#define __util_h__

static inline int Min(int a, int b)
{
    if (a < b)
        return a;
    else
        return b;
}

static inline int Max(int a, int b)
{
    if (a < b)
        return b;
    else
        return a;
}

inline int ClipRange(int a, int b, int c)
{
    if (a < b)
        return b;
    if (a > c)
        return c;
    return a;
}

#endif


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

This file is part of PCExhumed.

PCExhumed 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 "version.h"

const char *versionstr = "Mar 19 1997 17:31:18";


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

This file is part of PCExhumed.

PCExhumed 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 __version_h__
#define __version_h__

extern const char *versionstr;

#endif