/*============================================================*/
/*============================================================*/
/*==														==*/
/*==						Main Body						==*/
/*==														==*/
/*============================================================*/
/*============================================================*/


/*											*/
/*		Pararena 2.06 by john calhoun		*/
/*		© 1992 Casady & Greene, Inc.		*/
/*											*/


/*========================================================  Includes  */

#include "Globals.h"
#include "UnivUtilities.h"
#include "AnimCursor.h"
#include "Prefs.h"
#include "Main.h"
#include "Idle.h"
#include "IdleRoutines.h"
#include "Render.h"
#include "PlayCore.h"
#include "Initialize.h"
#include "AppleTalkDDP.h"
#include "SoundUtils.h"
#include "MainWindow.h"
#include <Sound.h>


/*========================================================  Globals  */

ballType		theBall;
playerType		thePlayer;
playerType		theOpponent;
doorType		theDoor;
digiDispType	scoreDisplays[2];
cursorType		boardCursor;
replayType		*replayData;
masterSendType	masterMessage;
slaveSendType	slaveMessage;
statType		theStats[10];
string31		theNames[10];
macEnvironment	thisMac;
soundQueue		crowdQueue, incidentalQueue;
WindowPtr		mainWndo;
KeyMap			theKeyMap;
RGBColor		RGBBlackColor, RGBWhiteColor;
RGBColor		starColors[3];
RgnHandle		screenRgn;
EventRecord		theEvent;
Cursor			handCursor;
GrafPtr			offBackPtr, offPartsPtr, offWorkPtr, offMaskPtr;
BitMap			offBackBits, offPartsBits, offWorkBits, offMaskMap;
CGrafPort		offCBackPort, offCPartsPort, offCWorkPort, offCMaskPort;
CGrafPtr		offCBackPtr, offCPartsPtr, offCWorkPtr, offCMaskPtr;
Ptr				offBackPix, offPartsPix, offWorkPix, offMaskPix;
Str255			courseFName, gameFName;
string31		mostTitlesName, mostPointsName;
string31		mostFoulsName, mostCritsName;
Rect			offBackRect, offPartsRect, offWorkRect, offMaskRect;
Rect			screenRect, dragRect, nullRect, mouseFrame;
Rect			replayRect, cameraRect, colonDest, leftTimingDest, rightTimingDest;
Rect			leftArrowSrc, rightArrowSrc, leftArrowDest, rightArrowDest;
Rect			leftArrowStorage, rightArrowStorage, timingSource;
Rect			playerSrcRects[9][3], fadeMaskRects[9][3], opponentSrcRects[9][3];
Rect			colonSrc[2];
Point			starList[kNumberOfStars];
long			screenBase, mostTitlesDate, mostPointsDate, speedFlag, theirSpeed;
long			mostFoulsDate, mostCritsDate, oldDistSquared, tempLong;
long			insetBytes, replaySrc, replayDest, lifeTime, thisTime, encryptedNumber;
long			ballSrcAddr, ballMaskAddr;
long			screenRowAddrs[480], workRowOffsets[480];
long			playerSrcAddrs[9][3], fadeMaskAddrs[9][3], opponentSrcAddrs[9][3];
long			maskAddrs[9][3];
long			timeElapsed, baseTime, wasTime, timePaused, replayFlag;
short			frameCounter, newFrameCount, lastFrameCount;
short			mostTitles, mostPoints, mostFouls, mostCrits, isLeague;
short			screenRowBytes, workRowBytes, backRowBytes, partsRowBytes;
short			maskCRowBytes, maskRowBytes, displayMode, screenWide, screenHigh;
short			primaryMode, arenaSize, isDepth, whichGame, loopsBallHeld;
short			displayHCenter, displayVCenter, playerFouls, opponentFouls;
short			playerTotalFouls, opponentTotalFouls, playerTotalGoals, opponentTotalGoals;
short			playerTotalCrits, opponentTotalCrits, lastSoundPriority, spottedPoints;
short			masterSendSize, slaveSendSize, loopDelay, soundFileRefNum;
short			droppedPackets, sentPackets, wasSoundVolume, wasLastSound;
short			playerScore, opponentScore, whosGotBall, maxBoardForce;
short			whichHumanNumber, leftPlayerNumber, rightPlayerNumber, spotPoints;
short			screenHCenter, screenVCenter, soundVolume, lengthOfApplause, lengthOfMob;
short			leftGoalLeague, rightGoalLeague, theirLeague, system7HelpItem;
short			horizontal, vertical;
short			vertTable[41][81];
short			*littleForceTable, *juniorForceTable, *varsityForceTable;
short			*minorForceTable, *proForceTable;
short			fadeMaskSequence[69];
short			spacialToDirection[9];
short			boardForceTable[9][2];
short			teaksThreshholds[10];
short			antiFacing[9];
short			antiWhosBall[4];
short			soundPriorities[kMaxNumberOfSounds];
char			playerWonTheGame;
Boolean			quitting, inBackground, isColor, knowsColor, autoSetDepth, doSkipFrames;
Boolean			useQD, playerInBack, canReplay, gameIsOver, newGame, smsActivated;
Boolean			pausing, leftScoredLast, netGameInSession, madeThePickUp, drawThisFrame;
Boolean			autoTeamsDialog, leftGoalIsPlayers, canNetwork, netMirroring, netOnly;
Boolean			replayGoals, replayFouls, replayOnR, replaySomething, willUseQD;
Boolean			playerJustScored, showBoardCursor, disableBoardCursor, enableAnnouncer;
Boolean			soundOn, beamSoundOn, incidentSoundOn, collisionSoundOn, crowdSoundOn;
Boolean			enableBackground, theyAreMajor, wasBrakeOn, doZooms, replayZooms;
Boolean			splashIsUp;
Boolean			soundLoaded[kMaxNumberOfSounds];
Boolean			incidentSoundLoaded[kMaxIncidentalSounds];


/*========================================================  ThisSysBeep  */

pascal void ThisSysBeep (short sndNum)

{
	long		dummyLong;
	short		i;
	
	if (sndNum == 0)
		return;
	
	for (i = 0; i < sndNum; i++)
	{
		FlashMenuBar(0);
		Delay(8, &dummyLong);
		FlashMenuBar(0);
		Delay(8, &dummyLong);
	}
}


/*========================================================  RootLoop  */

void RootLoop (void)

{
	switch (primaryMode)			/* depending upon which 'mode' we're in */
	{
		case kIdleMode:				/* idling - basically interface hashing */
			HandleEvent();
			if (!splashIsUp)
				TwinkleAStar();
			break;
		case kPlayMode:				/* playing - an active game is in session */
			if (!pausing)
				PlayGame();
			else
			{
				HandleEvent();
			}
			break;
	}
}


/*========================================================  Main  */

main()

{
	InitializeAll();				/* initialize everything! */
	UnloadSeg(InitializeAll);
	ErrorSound((ProcPtr)ThisSysBeep);
	InitCursor();
	
	while (!quitting)				/* call the root loop until we quit */
	{
		RootLoop();					/* see above */
	}

	ShutItDown();					/* destroy all data, restore Mac */
}


/*========================================================  DumpTheDefaults  */

void DumpTheDefaults (void)

{
	prefsInfo		thePreferred;
	short			i;
	Boolean			howItWent;
	
	thePreferred.prefVersion = 0x0100;
	thePreferred.encryption = encryptedNumber;
	thePreferred.timeWas = lifeTime + (Ticks - thisTime);
	
	PasStringCopy((StringPtr)mostTitlesName, (StringPtr)thePreferred.mostTitlesName);
	thePreferred.mostTitlesDate = mostTitlesDate;
	thePreferred.mostTitles = mostTitles;
	PasStringCopy((StringPtr)mostPointsName, (StringPtr)thePreferred.mostPointsName);
	thePreferred.mostPointsDate = mostPointsDate;
	thePreferred.mostPoints = mostPoints;
	PasStringCopy((StringPtr)mostFoulsName, (StringPtr)thePreferred.mostFoulsName);
	thePreferred.mostFoulsDate = mostFoulsDate;
	thePreferred.mostFouls = mostFouls;
	PasStringCopy((StringPtr)mostCritsName, (StringPtr)thePreferred.mostCritsName);
	thePreferred.mostCritsDate = mostCritsDate;
	thePreferred.mostCrits = mostCrits;
	
	PasStringCopy((StringPtr)theNames[0], (StringPtr)thePreferred.namesWere[0]);
	PasStringCopy((StringPtr)theNames[1], (StringPtr)thePreferred.namesWere[1]);
	PasStringCopy((StringPtr)theNames[2], (StringPtr)thePreferred.namesWere[2]);
	PasStringCopy((StringPtr)theNames[3], (StringPtr)thePreferred.namesWere[3]);
	PasStringCopy((StringPtr)theNames[4], (StringPtr)thePreferred.namesWere[4]);
	PasStringCopy((StringPtr)theNames[5], (StringPtr)thePreferred.namesWere[5]);
	PasStringCopy((StringPtr)theNames[6], (StringPtr)thePreferred.namesWere[6]);
	PasStringCopy((StringPtr)theNames[7], (StringPtr)thePreferred.namesWere[7]);
	PasStringCopy((StringPtr)theNames[8], (StringPtr)thePreferred.namesWere[8]);
	PasStringCopy((StringPtr)theNames[9], (StringPtr)thePreferred.namesWere[9]);
	
	thePreferred.opponentWas = theOpponent.persona;
	thePreferred.playerWas = whichHumanNumber;
	thePreferred.gameWas = whichGame;
	for (i = 0; i < 10; i++)
	{
		thePreferred.wasTeaksThresh[i] = teaksThreshholds[i];
	}
	thePreferred.wasVolume = soundVolume;
	thePreferred.wasLeague = isLeague;
	
	thePreferred.wasUseQD = willUseQD;
	thePreferred.wasAutoTeams = autoTeamsDialog;
	thePreferred.replayGoalsWas = replayGoals;
	thePreferred.replayFoulsWas = replayFouls;
	thePreferred.replayOnRWas = replayOnR;
	thePreferred.wasShowCursor = showBoardCursor;
	thePreferred.leftGoalWasPlayers = leftGoalIsPlayers;
	thePreferred.wasSoundOn = soundOn;
	thePreferred.wasBeamSoundOn = beamSoundOn;
	thePreferred.wasIncidentSoundOn = incidentSoundOn;
	thePreferred.wasCollisionSoundOn = collisionSoundOn;
	thePreferred.wasCrowdSoundOn = crowdSoundOn;
	thePreferred.wasSetDepth = autoSetDepth;
	thePreferred.wasAnnouncer = enableAnnouncer;
	thePreferred.wasBackground = enableBackground;
	thePreferred.wasZooms = doZooms;
	thePreferred.wasReplayZooms = replayZooms;
	thePreferred.wasSkipFrames = doSkipFrames;
	thePreferred.wasNetOnly = netOnly;
	
	for (i = 0; i < 10; i++)
	{
		thePreferred.wasStats[i].tournamentTime = theStats[i].tournamentTime;
		thePreferred.wasStats[i].bestPlatinumTime = theStats[i].bestPlatinumTime;
		thePreferred.wasStats[i].copperTitles = theStats[i].copperTitles;
		thePreferred.wasStats[i].bronzeTitles = theStats[i].bronzeTitles;
		thePreferred.wasStats[i].silverTitles = theStats[i].silverTitles;
		thePreferred.wasStats[i].goldTitles = theStats[i].goldTitles;
		thePreferred.wasStats[i].platinumTitles = theStats[i].platinumTitles;
		thePreferred.wasStats[i].played = theStats[i].played;
		thePreferred.wasStats[i].won = theStats[i].won;
		thePreferred.wasStats[i].goals = theStats[i].goals;
		thePreferred.wasStats[i].fouls = theStats[i].fouls;
		thePreferred.wasStats[i].criticals = theStats[i].criticals;
		thePreferred.wasStats[i].oppGoals = theStats[i].oppGoals;
		thePreferred.wasStats[i].oppFouls = theStats[i].oppFouls;
		thePreferred.wasStats[i].oppCriticals = theStats[i].oppCriticals;
		thePreferred.wasStats[i].georgeState = theStats[i].georgeState;
		thePreferred.wasStats[i].maraState = theStats[i].maraState;
		thePreferred.wasStats[i].ottoState = theStats[i].ottoState;
		thePreferred.wasStats[i].claireState = theStats[i].claireState;
		thePreferred.wasStats[i].eazeState = theStats[i].eazeState;
		thePreferred.wasStats[i].teakState = theStats[i].teakState;
	}
	
	howItWent = SavePrefs(&thePreferred);
}


/*========================================================  ShutItDown  */

void ShutItDown (void)

{
	GDHandle		theDevice;
	OSErr			theErr;
	short			netErr;
	short			GDTypeFlag = 1, colorFlag = 1;
	char			tagByte;
	Boolean			itWorked;
	
	netErr = CloseDownAppleTalk();
	
	TurnSMSOff();
	SetSoundVol(wasSoundVolume);
	
	if (soundFileRefNum != -1)
		CloseResFile(soundFileRefNum);
	
	if (isColor)
	{
		if (offCPartsPtr != kNilPointer)
			CloseCPort(offCPartsPtr);
		if (offPartsPix != kNilPointer)
			DisposPtr(offPartsPix);
		if (offCBackPtr != kNilPointer)
			CloseCPort(offCBackPtr);
		if (offBackPix != kNilPointer)
			DisposPtr(offBackPix);
		if (offCWorkPtr != kNilPointer)
			CloseCPort(offCWorkPtr);
		if (offWorkPix != kNilPointer)
			DisposPtr(offWorkPix);
	}
	else
	{
		if (offBackPtr != kNilPointer)
			ClosePort(offBackPtr);
		if (offPartsPtr != kNilPointer)
			ClosePort(offPartsPtr);
		if (offWorkPtr != kNilPointer)
			ClosePort(offWorkPtr);
	}
	
	if ((!useQD) && (isColor))
	{
		if (offCMaskPtr != kNilPointer)
			CloseCPort(offCMaskPtr);
		if (offMaskPix != kNilPointer)
			DisposPtr(offMaskPix);
	}
	
	if (offMaskPtr != kNilPointer)
		ClosePort(offMaskPtr);
	
	if (replayData != kNilPointer)
		DisposPtr((Ptr)replayData);
	
	DisposCursors();				/* drop cursors */
	DumpTheDefaults();
	CloseMainWindow();
	
	if (screenRgn != kNilPointer)	/* destroy regions */
		DisposeRgn(screenRgn);
	
	if ((thisMac.canSwitch) && (thisMac.wasDepth != thisMac.isDepth) && (autoSetDepth))
	{
		theDevice = GetMainDevice();
		if (theDevice != kNilPointer)
		{
			tagByte = HGetState((Handle)theDevice);
			HLock((Handle)theDevice);
			theErr = SetDepth(theDevice, thisMac.wasDepth, GDTypeFlag, colorFlag);
			HSetState((Handle)theDevice, tagByte);
		}
	}
	
	FlushEvents(everyEvent, kRemoveAllEvents);	/* flush and bolt! */
}


