#include <stdio.h>
#ifndef __TARGET_TOOLAPP
#include "screen.h"
#endif
/*
typedef struct
{
    unsigned long   fSaveSP,fSaveCR,fSaveLR,fResv0,fResv1,fSaveRTOC;
}   tStackFrame;

asm unsigned long   GetCallersSP( void )
{
 	lwz r3,0(SP)
    blr
}

Str255  *FindRoutineName( unsigned long *codeAddress )
{
    // look for the callers' "blr" instruction
    // assume it's going to be within 8K instructions of the call site.
    // this may or may not work for your code, worked for me.

    // the MacsBug name follows shortly after the 'blr'
    // and at a fixed offset that I figured out empirically.
	int i;
    for( i=0; i<8000; i++)
    {
        if (codeAddress[i] == 0x4E800020)
        {
            // found the 'blr'
            if (codeAddress[i+1] == 0x00000000)
            {
                return (Str255*) ( ((unsigned char*)&codeAddress[i])+21 );
            }
        }
    }
    return nil;
}

inline void GetCallerName(Str255 callerName)
{
    tStackFrame     *frame = (tStackFrame*) GetCallersSP();
    unsigned long   *address = (unsigned long*)frame->fSaveLR;
    Str255          *name = FindRoutineName( address );
	if(name)
		BlockMoveData(*name,callerName,(*name)[0]+1);
	else
		BlockMoveData("\p<Anonymous Routine>",callerName,20);
}
*/

void ShowAlert(char *str1, char *str2)
{
#ifndef __TARGET_TOOLAPP
	ScreenExit();
#endif
	AlertStdAlertParamRec alertParam={
		false,false,nil,
		"\pExit",
		nil,
		nil,
		kAlertStdAlertOKButton,
		0,
		kWindowDefaultPosition};

	Str255 pStr1,pStr2;
	CopyCStringToPascal(str1,pStr1);
	CopyCStringToPascal(str2,pStr2);
	
	short hit;
	OSErr err=StandardAlert(kAlertStopAlert,
		pStr1,
		pStr2,
		&alertParam,
		&hit);
	if(err)ExitToShell();
}

void FailWithErrorString(char *string)
{
	ShowAlert(string,"");
	ExitToShell();
}

void PrintConsoleString(const char *fmt, ...)
{
	va_list		ap;					// Pointer To List Of Arguments

	if (fmt == NULL)					// If There's No Text
			return;						// Do Nothing

	char error[256];
	va_start(ap, fmt);					// Parses The String For Variables
	vsprintf(error,fmt,ap);				// And Converts Symbols To Actual Numbers
	va_end(ap);						// Results Are Stored In Text
/*
	Str255 pStr;
	CopyCStringToPascal(error,pStr);
	DebugStr(pStr);	*/
	printf("%s\n",error);
}

void HandleError(int code)
{
	if(code)
	{
		char str1[80],str2[80];	
		char caller[80]="/p";
		//GetCallerName((unsigned char*)caller);
		CopyPascalStringToC((unsigned char*)caller,caller);
		sprintf(str1,"A fatal error has occurred!!");
		sprintf(str2,"Error ID=%d",code);// in function %s",code,caller);
		ShowAlert(str1,str2);
		ExitToShell();
	}
}