// GigaCam.cpp : Defines the class behaviors for the application.
//

#include "stdafx.h"
#include "GigaCam.h"
#include "GigaCamDlg.h"
#include <initguid.h>
#include "GigaCam_i.c"
#include ".\gigacam.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif

HANDLE _hEventLog;


// CGigaCamApp


class CGigaCamModule :
	public CAtlMfcModule
{
public:
	DECLARE_LIBID(LIBID_GLXRegServerLib);
	DECLARE_REGISTRY_APPID_RESOURCEID(IDR_GIGACAM, "{CB55A870-3EF1-4E03-8FFF-28C25661091D}");};

CGigaCamModule _AtlModule;

BEGIN_MESSAGE_MAP(CGigaCamApp, CWinApp)
	ON_COMMAND(ID_HELP, CWinApp::OnHelp)
END_MESSAGE_MAP()


// CGigaCamApp construction

CGigaCamApp::CGigaCamApp()
: m_bAdjustMode(FALSE),
  m_bAutoAdjustGain(false)
{
	EnableHtmlHelp();

	// TODO: add construction code here,
	// Place all significant initialization in InitInstance
}

// The one and only CGigaCamApp object

CGigaCamApp theApp;


// CGigaCamApp initialization

BOOL CGigaCamApp::InitInstance()
{
	AfxOleInit();
	// InitCommonControls() is required on Windows XP if an application
	// manifest specifies use of ComCtl32.dll version 6 or later to enable
	// visual styles.  Otherwise, any window creation will fail.
	InitCommonControls();

	AfxInitRichEdit2();

	CWinApp::InitInstance();

	if (!AfxSocketInit())
	{
		AfxMessageBox(IDP_SOCKETS_INIT_FAILED);
		return FALSE;
	}

	AfxEnableControlContainer();
	// Parse command line for standard shell commands, DDE, file open
	CCommandLineInfo cmdInfo;
	ParseCommandLine(cmdInfo);

	// Register class factories via CoRegisterClassObject().
	//if (FAILED(_AtlModule.RegisterClassObjects(CLSCTX_LOCAL_SERVER, REGCLS_MULTIPLEUSE)))
	//	return FALSE;
	//// App was launched with /Embedding or /Automation switch.
	//// Run app as automation server.
	////if (cmdInfo.m_bRunEmbedded || cmdInfo.m_bRunAutomated)
	////{
	////	// Don't show the main window
	////	return TRUE;
	////}
	//// App was launched with /Unregserver or /Unregister switch.
	//if (cmdInfo.m_nShellCommand == CCommandLineInfo::AppUnregister)
	//{
	//	_AtlModule.UpdateRegistryAppId(FALSE);
	//	_AtlModule.UnregisterServer(TRUE);
	//	return FALSE;
	//}
	//// App was launched with /Register or /Regserver switch.
	//if (cmdInfo.m_nShellCommand == CCommandLineInfo::AppRegister)
	//{
	//	_AtlModule.UpdateRegistryAppId(TRUE);
	//	_AtlModule.RegisterServer(TRUE);
	//	return FALSE;
	//}

	// Standard initialization
	// If you are not using these features and wish to reduce the size
	// of your final executable, you should remove from the following
	// the specific initialization routines you do not need
	// Change the registry key under which our settings are stored
	// TODO: You should modify this string to be something appropriate
	// such as the name of your company or organization
	SetRegistryKey(_T("Local AppWizard-Generated Applications"));

	// START CHANGES MADE FOR AUTOMATION
	COleTemplateServer::RegisterAll();
	// END CHANGES MADE FOR AUTOMATION

		// START CHANGES MADE FOR AUTOMATION
	if (cmdInfo.m_nShellCommand == CCommandLineInfo::AppUnregister){
		AfxOleUnregisterTypeLib(LIBID_GLXRegServerLib);
		return TRUE; 
	} 

	BOOL ret =  COleObjectFactory::UpdateRegistryAll(TRUE);
	

	HINSTANCE hInst = AfxGetInstanceHandle();
	 ret = AfxOleRegisterTypeLib(hInst, LIBID_GLXRegServerLib);
	if (!ret)
		ResultFromScode(SELFREG_E_TYPELIB);

	// end changes for automation

	m_hdd = DrawDibOpen();

	//DetectHS();

	//SIZE_T minws;
	//SIZE_T maxws;

	//GetProcessWorkingSetSize(GetCurrentProcess(), &minws, &maxws);

	//MEMORYSTATUSEX ms;

	//ms.dwLength = sizeof(ms);

	//GlobalMemoryStatusEx(&ms);

	//SIZE_T inc = ms.ullAvailPhys;

	//minws = maxws + inc;
	//maxws = maxws + inc;

	//BOOL b = SetProcessWorkingSetSize(GetCurrentProcess(), minws, maxws);

	//_hEventLog = RegisterEventSource( NULL, "GigaCam" );

	//ReportEvent( _hEventLog, EVENTLOG_INFORMATION_TYPE, NULL, MSG_APPLICATION_START, NULL, 0, 0, NULL, NULL );

	m_iWFMInterval = 3;

	//locale::global(locale("japanese"));

#ifdef _LOGFILE
	if( !LogStart() )
		return FALSE;
#endif

	CGigaCamDlg dlg;
	m_pMainWnd = &dlg;
	INT_PTR nResponse = dlg.DoModal();
	if (nResponse == IDOK)
	{
		// TODO: Place code here to handle when the dialog is
		//  dismissed with OK
	}
	else if (nResponse == IDCANCEL)
	{
		// TODO: Place code here to handle when the dialog is
		//  dismissed with Cancel
	}

#ifdef _LOGFILE
	LogEnd();
#endif

	// Since the dialog has been closed, return FALSE so that we exit the
	//  application, rather than start the application's message pump.
	return FALSE;
}

BOOL CGigaCamApp::ExitInstance(void)
{
	DrawDibClose(m_hdd);

	//if(m_bHS)
	//	HSTerminate(0);
	//ReportEvent( _hEventLog, EVENTLOG_INFORMATION_TYPE, NULL, MSG_APPLICATION_EXIT, NULL, 0, 0, NULL, NULL );

	_AtlModule.RevokeClassObjects();

	return CWinApp::ExitInstance();
}

void CGigaCamApp::DetectHS()
{
	m_bHS = false;

	//__try
	//{
	//	if(SUCCEEDED(__HrLoadAllImportsForDll("HyperStream.dll")))
	//	{
	//		//if(HSInitialize(0))
	//		//{
	//			m_bHS = true;
	//			OutputDebugString("GigaCam: Using HyperStream\n");
	//		//}
	//		//else
	//		//{
	//		//	OutputDebugString("GigaCam: HyperStream is available but could not be initialized\n");
	//		//}
	//	}
	//}
	//__except(EXCEPTION_EXECUTE_HANDLER)
	//{
	//}
}

BOOL CGigaCamApp::LogStart()
{
	//LPTSTR pathName;
	//const HMODULE moduleHandle = GetModuleHandle(NULL);
	//::GetModuleFileNameA(moduleHandle, pathName, _MAX_PATH);
	//CString log = pathName;
	//log += ".log";
	CString filename = m_pszAppName;
	filename = "C:\\" + filename + ".log";
	if (!m_Log.file.Open(filename, CFile::modeWrite | CFile::modeCreate | CFile::modeNoTruncate)) return FALSE;
	m_Log.file.SeekToEnd();
	m_Log.file.WriteString("-------------------- START --------------------\n");
	m_Log.file.WriteString("FrameCount, LogCount, Time\n");
	m_Log.num = 0;

	return TRUE;
}
void CGigaCamApp::LogEnd()
{
	m_Log.file.WriteString("--------------------  END  --------------------");
	m_Log.file.Close();
}

void CLogFile::Write(DWORD frames)
{
#ifdef _LOGFILE

	if (file.m_pStream != NULL) {
		num++;

		CString s, t;

		s.Format("%u",frames);
		t.Format("%u",num);

		s += ", " + t + ", " + CTime::GetCurrentTime().Format("%Y/%m/%d %H:%M:%S") + "\n";

		file.WriteString(s);
	}

#endif
}
