//	ADFS_LogFile.c

#include "Utils.h"
#include "FSUtils.h"
#include "ADFS_LogFile.h"

#ifdef OLD68K
	FILE		*gLogfile = NULL;
#else
	#ifdef __GNUC__
		FILE		*gLogfile = NULL;
	#else
		std::FILE		*gLogfile = NULL;
	#endif
#endif

Boolean		gShowNewSessionB	= TRUE;

void		ADFS_OpenLogFile(void)
{
	#if USE_LOG_FILE		
		if (!gLogfile) {
			char	mode[] = "a";
			
			#ifdef __ROSE__
				gLogfile = fopen("Rose log", mode);
			#else
				gLogfile = fopen("ADFS log", mode);
			#endif
		
			if (gShowNewSessionB) {
				char	string[256];
		
				ADFS_Log("------------------\nNew Session:\n------------------\n");			
				sprintf(string, "System version: 0x%hx\n", GetSystemVers());
				
				#ifdef __68k__
					ADFS_Log("68k ");
				#elif defined(__POWERPC__)
					ADFS_Log("PowerPC ");
				#elif defined(__x86__)
					ADFS_Log("Intel ");
				#endif
				
				ADFS_Log(string);
				
				#ifndef __68k__
					sprintf(string, "CarbonLib 0x%hx\n", GetInterfaceVers());
				#else
					sprintf(string, "InterfaceLib 0x%hx\n", GetInterfaceVers());
				#endif
			}
		}
	#endif
}

void	ADFS_LaunchLogFile(void)
{
	FSSpec	logFile;
	OSErr	err = FSpThisApp(&logFile);

	if (!err) {
		CopyString(c2p("ADFS log"), logFile.name);
		FSpLaunchInFinder(&logFile);
	}
}

char		tabsAC[256] = "";
Boolean		tabsB = true;

void		ADFS_Log_Tabs(short tabsS)
{
	if (tabsS > 255) {
		tabsS = 255;
	}
	
	memfill(tabsAC, '\t', tabsS);
	tabsAC[tabsS] = 0;
}


void		ADFS_Log(char *logStr)
{
	if (gLogfile) {
		if (tabsB) {
			fprintf(gLogfile, "%s", tabsAC);
		}
	
		fprintf(gLogfile, "%s", logStr);
		fflush(gLogfile);
		
		tabsB = logStr[strlen(logStr) - 1] == '\n';
	}
}

void		ADFS_Log_Hex(ulong number)
{
	char	strAC[256];
	
	sprintf(strAC, "0x%lx", number);
	ADFS_Log(strAC);
}

void		ADFS_Log_Hex(ushort number)
{
	char	strAC[256];
	
	sprintf(strAC, "0x%hx", number);
	ADFS_Log(strAC);
}

void		ADFS_Log_Number(ulong number)
{
	char	strAC[256];
	
	sprintf(strAC, "%lu", number);
	ADFS_Log(strAC);
}

void		ADFS_Log_Number(long number)
{
	char	strAC[256];
	
	sprintf(strAC, "%ld", number);
	ADFS_Log(strAC);
}

void		ADFS_Log_Number(ushort number)
{
	char	strAC[256];
	
	sprintf(strAC, "%hu", number);
	ADFS_Log(strAC);
}

void		ADFS_Log_Number(short number)
{
	char	strAC[256];
	
	sprintf(strAC, "%hd", number);
	ADFS_Log(strAC);
}

void		ADFS_LogAlways(char *logStr)
{
	Boolean		wasLoggingB = gLogfile != NULL;
	
	if (!wasLoggingB) {
		gShowNewSessionB = FALSE;
		ADFS_OpenLogFile();
		gShowNewSessionB = TRUE;
	}
	
	ADFS_Log(logStr);

	if (!wasLoggingB) {
		ADFS_CloseLogFile();
	}
}

void		ADFS_CloseLogFile(void)
{
	if (gLogfile) {
		fclose(gLogfile);
		gLogfile = NULL;
	}
}

void		ADFS_Log_FSType(FSType osType)
{
	char	str256[256];
	
	str256[0] = 0;
	
	ADFS_Log(strcat_FSType(osType, str256));
}