*/------------------------------------------------------------------------*/
/*                                                                        */
/*  Copyright (c) 2008 by MESA Imaging SA,                                */
/*                     http://www.mesa-imaging.ch						  */
/*				Modify by Lubos Sedlak 78328   							  */
/*------------------------------------------------------------------------*/
#include "stdafx.h"
#include "KameraTOF.h"
#include "commdlg.h"
#include "commctrl.h"
#pragma comment( lib, "comctl32" )  //Used for slider control
#include "richedit.h"
#include <math.h>

// Global Variables:
static HINSTANCE hInst;                // current instance
float Pix[10];
int CntAq = 0;

HINSTANCE AfxGetInstanceHandle(){return hInst;}

CPreciseTimer precTimer;

#define LIMIT(val,min,max) (((val)<(min))?(min):(((val)>(max))? (max):(val)))

#ifndef D3DCOLOR_ARGB
typedef DWORD D3DCOLOR; //!<32 bit color value
#define D3DCOLOR_ARGB(a,r,g,b) \
	((D3DCOLOR)((((a)&0xff)<<24)|(((r)&0xff)<<16)|(((g)&0xff)<<8)|((b)&0xff)))
#endif

//Colors for error overflow etc.
#define OVFL_COL D3DCOLOR_ARGB(0,0xff,0xe0,0xc0)
#define UDFL_COL D3DCOLOR_ARGB(0,0xc0,0xe0,0xff)
#define ERR_COL  D3DCOLOR_ARGB(0,0x00,0xe0,0x00)

//!The RGBColMap struct is used to generate colormaps.
//!This is a local class in the file OCTViewSlice.cpp
typedef struct
{
	BYTE    pos;//!<position in the color shading
	BYTE    r;  //!<red value
	BYTE    g;  //!<green value
	BYTE    b;  //!<blue value
} RGBColMap; //!<colormap entry for SetColormap()

static const RGBColMap jet[]={
	{0x00, 0x00, 0x00, 0x80},
	{0x20, 0x00, 0x00, 0xff},
	{0x60, 0x00, 0xff, 0xff},
	{0xa0, 0xff, 0xff, 0x00},
	{0xe0, 0xff, 0x00, 0x00},
	{0xff, 0x80, 0x00, 0x00}
};

//!fills a folormap with a desired color shading
void SetColormap(const RGBColMap* cm, RGBQUAD* col)
{
	int i,x;
	float f;
	col[0].rgbBlue =(BYTE)cm[0].b;
	col[0].rgbGreen=(BYTE)cm[0].g;
	col[0].rgbRed  =(BYTE)cm[0].r;
	col[0].rgbReserved=0x00;
	x=1;
	for (i=1;i<256;i++)
	{
		while (cm[x].pos<i)x++;
		f=((float)i-cm[x-1].pos)/(cm[x].pos-cm[x-1].pos);
		col[i].rgbBlue =(BYTE)(f*cm[x].b+(1.-f)*cm[x-1].b);
		col[i].rgbGreen=(BYTE)(f*cm[x].g+(1.-f)*cm[x-1].g);
		col[i].rgbRed  =(BYTE)(f*cm[x].r+(1.-f)*cm[x-1].r);
		col[i].rgbReserved=0x00;
	}
}

//!Loops and calls CWndSwissranger::Acquire() until CCameraThread::Stop() is called
DWORD CCameraThread::CameraLoop()
{
	while(!_stop)
	{
		_srWnd->Acquire();
	}
	return 0;
}


const TCHAR* CWndSwissranger::_wndClass="WndSwissrangerClass";
const TCHAR* CWndSwissranger::_wndTitle="Swissranger";

//!\ingroup swissRangerSampleGui
//!This is he main entry function that allocates a CWndSwissranger object, creates the window and starts the message loop.
int APIENTRY _tWinMain(HINSTANCE hInstance,
					   HINSTANCE hPrevInstance,
					   LPTSTR    lpCmdLine,
					   int       nCmdShow)
{
	MSG msg;
	WINDOWINFO winf;
	HACCEL hAccelTable;
	HWND dlg;
	hInst = hInstance;
	InitCommonControls();

	SR_CheckForNewDllVersion(0);

	CWndSwissranger wndSR;

	wndSR.Create(hInstance,0);
	hAccelTable = LoadAccelerators(hInstance, (LPCTSTR)IDC_SWISSRANGERSAMPLEGUI);

	// Main message loop:
	while (GetMessage(&msg, NULL, 0, 0))
	{
		if (TranslateAccelerator(msg.hwnd, hAccelTable, &msg))continue;

		dlg=msg.hwnd;
		while(IsWindow(dlg) && GetWindowInfo(dlg,&winf))
		{
			if ((winf.dwStyle&WS_POPUP) && IsDialogMessage(dlg, &msg))
			{
				goto cont2;
			}
			dlg=GetParent(dlg);
		}
		TranslateMessage(&msg);
		DispatchMessage(&msg);
cont2:;
	}
	return (int) msg.wParam;
}

//!redirects the call from this static function to the method WindowProc
BOOL CALLBACK CDlgAbout::SWindowProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
	CDlgAbout* pWnd;
	if (message == WM_INITDIALOG)
	{
		pWnd=(CDlgAbout*)lParam;
		pWnd->_hWnd=hDlg;
		// get the pointer to the window from lpCreateParams which was set in CreateWindow
		SetWindowLong(hDlg, GWL_USERDATA, (long)(lParam));
		pWnd->OnInitialUpdate();
		return TRUE;
	}
	// get the pointer to the window
	pWnd = GetObjectFromWindow(hDlg);
	// if we have the pointer, go to the message handler of the window
	// else, use DefWindowProc
	if (pWnd)
		return pWnd->WindowProc(hDlg, message, wParam, lParam);
	else
		return FALSE;
}

//!window message handling function
BOOL CALLBACK CDlgAbout::WindowProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
	switch (message)
	{
	case WM_INITDIALOG:
		return TRUE;

	case WM_COMMAND:
		if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
		{
			EndDialog(hDlg, LOWORD(wParam));
			return TRUE;
		}
		break;
	}
	return FALSE;
}

CWndSwissranger* CWndSwissranger::_cbInstance=0;
//!registers a new window class
ATOM CWndSwissranger::RegisterClass(HINSTANCE hInstance)
{
	static bool registered=false;
	if(registered)return 0;
	registered=true;
	WNDCLASSEX wcex;

	wcex.cbSize = sizeof(WNDCLASSEX);

	wcex.style      = CS_HREDRAW | CS_VREDRAW;
	//wcex.lpfnWndProc  = SWindowProc;
	wcex.cbClsExtra    = 0;
	wcex.cbWndExtra    = 0;
	wcex.hInstance    = hInstance;
	wcex.hIcon      = LoadIcon(hInstance, (LPCTSTR)IDI_SWISSRANGERSAMPLEGUI);
	wcex.hCursor    = LoadCursor(NULL, IDC_ARROW);
	wcex.hbrBackground  = (HBRUSH)(COLOR_WINDOW+1);
	wcex.lpszMenuName  = (LPCTSTR)IDC_SWISSRANGERSAMPLEGUI;
	wcex.lpszClassName  = _wndClass;
	wcex.hIconSm    = LoadIcon(wcex.hInstance, (LPCTSTR)IDI_SMALL);
	return RegisterClassEx(&wcex);
}



//!redirects the call from this static function to the method WindowProc
BOOL CALLBACK CWndSwissranger::SWindowProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
	CWndSwissranger* pWnd;
	if (message == WM_INITDIALOG)
	{
		pWnd=(CWndSwissranger*)lParam;
		pWnd->_hWnd=hDlg;
		// get the pointer to the window from lpCreateParams which was set in CreateWindow
		SetWindowLong(hDlg, GWL_USERDATA, (long)(lParam));
		pWnd->OnInitialUpdate();
		return TRUE;
	}
	// get the pointer to the window
	pWnd = GetObjectFromWindow(hDlg);
	// if we have the pointer, go to the message handler of the window
	// else, use DefWindowProc
	if (pWnd)
		return pWnd->WindowProc(hDlg, message, wParam, lParam);
	else
		return FALSE;
}

//!window message handling function
BOOL CALLBACK CWndSwissranger::WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
	int wmId, wmEvent;

	switch (message)
	{
	case WM_COMMAND:
		wmId    = LOWORD(wParam);
		wmEvent = HIWORD(wParam);
		// Parse the menu selections:
		switch (wmId)
		{
		case IDOK:
		case IDCANCEL:
			{
				_camThread.Stop(1000);
				if(IsWindowEnabled(::GetDlgItem(hWnd,IDC_CLOSE)))
				{
					OnCloseDev();
				}
				DestroyWindow(hWnd);
				break;
			}
		case IDM_ABOUT:
			{
				CDlgAbout about;
				about.DoModal(AfxGetInstanceHandle(),hWnd);
				break;
			}
		
		case IDC_OPEN:
		case ID_OPEN_DLG:
			{
				short s=GetKeyState(VK_LSHIFT);
				if(s<0)//shift pressed?
					OnOpenDlg(2);
				else
					OnOpenDlg(3);
	
				if(_camThread.IsRunning())
				{
					_camThread.Stop(0);
					EnableWindow(::GetDlgItem(hWnd,IDC_CLOSE),TRUE);
					::SendMessage(::GetDlgItem(hWnd,IDC_ACQUIRE),WM_SETTEXT,0,(LPARAM)"Acquire");
				}
				else
				{
					EnableWindow(::GetDlgItem(hWnd,IDC_CLOSE),FALSE);
					::SendMessage(::GetDlgItem(hWnd,IDC_ACQUIRE),WM_SETTEXT,0,(LPARAM)"Stop");
					precTimer.StartTimer();
					_camThread.Run(this);
				}
				break;
			}
		case IDC_CLOSE:
			{
				OnCloseDev();
				break;
			}
		default:
			return FALSE;            // Didn't process the message: Got a WM_COMMAND message with unknown id.
		}
		break;
	case WM_PAINT:
		{
			OnPaint();
			break;
		}
	case WM_SIZE:
		{
			RECT rct0;
			RECT cltRct;
			HWND imgWnd0=GetDlgItem(hWnd,IDC_IMAGE0);
			int w = LOWORD(lParam);
			int h = HIWORD(lParam);
			TRACE("WM_SIZE %d,%d",w,h);
			GetClientRect(hWnd,&cltRct);
			GetWindowRect(imgWnd0,&rct0);ScreenToClient(hWnd,(LPPOINT)&rct0);ScreenToClient(hWnd,((LPPOINT)&rct0)+1);
			int d=10;
			int ww=(cltRct.right-rct0.left-d);
			MoveWindow(imgWnd0,
				rct0.left,//
				rct0.top,//
				ww,
				cltRct.bottom-rct0.top-d,
				true);
			break;
		}
	case WM_DESTROY:
		PostQuitMessage(0);
		break;
	default:
		return FALSE;            // Didn't process the message: Got a WM_COMMAND message with unknown id.
	}
	return TRUE;            // processed the message
}

//!fills the dib with image data from the camera
void CWndSwissranger::SetDib()
{
	if(_dibCam)
	{
		int i,idx,img;
		int RcntPix = 5;
		int Sum_m = 0;
		float v,minVal,step;
		float Pix_near = 9999;
		img=0;idx=0;
		if(_coordTrf)
		{
			int res;
			float lambda[MF_LAST]={3.75f, 5.f, 7.142857f, 7.5f, 7.894737f, 2.5f, 10.f, 15.f, 5.172414f, 4.838710f, 10.344828f, 9.677419f};//MF_40MHz,MF_30MHz,MF_21MHz,MF_20MHz,MF_19MHz,...
			ModulationFrq frq=SR_GetModulationFrequency(_srCam);
			res=SR_CoordTrfFlt(_srCam, 0,0,_z, sizeof(float),sizeof(float),sizeof(float));
			minVal=_minVal[img];
			step=(float)0xff/(_maxVal[img]-_minVal[img]);

			for(i=0;i<(_imgSz.cx*_imgSz.cy);i++,idx++)
			{
				v=(_z[i]*((float)(1<<16)/lambda[frq])-minVal)*step;
				_dibCam[idx]=_bmiScale->bmiColors[(BYTE)LIMIT(v,0,255)];
			}
			img++;

			Pix[0] = Rctngl(10,72,RcntPix,img);
			Pix[1] = Rctngl(166,72,RcntPix,img);
			Pix[2] = Rctngl(88,72,RcntPix,img);
			Pix[3] = Rctngl(20,124,RcntPix,img);
			Pix[4] = Rctngl(156,124,RcntPix,img);

			for (int i = 0; i < 10; i++){
				if (Pix[i] < 3) {
					Pix[i] = 999;
				}
			}			
		}	
		for(;img<_numImg;img++)
		{
			WORD* p=(WORD*)_imgEntryArray[img].data;
			minVal=_minVal[img];
			step=(float)0xff/(_maxVal[img]-_minVal[img]);
			for(i=0;i<(_imgSz.cx*_imgSz.cy);i++,idx++)
			{
				v=((float)p[i]-minVal)*step;
				_dibCam[idx]=_bmiScale->bmiColors[(BYTE)LIMIT(v,0,255)];
			}
		}
	}
	InvalidateRect(_hWnd,0,false);
}

float CWndSwissranger::Rctngl(int PositionAreaX, int PositionAreaY, int SizeArea, int img) {
	int res,PositionArea;
	float v_PIX, minVal, step, Pix_near = 9999;
	float lambda[MF_LAST]={3.75f, 5.f, 7.142857f, 7.5f, 7.894737f, 2.5f, 10.f, 15.f, 5.172414f, 4.838710f, 10.344828f, 9.677419f};//MF_40MHz,MF_30MHz,MF_21MHz,MF_20MHz,MF_19MHz,...
	ModulationFrq frq=SR_GetModulationFrequency(_srCam);
	res=SR_CoordTrfFlt(_srCam, 0,0,_z, sizeof(float),sizeof(float),sizeof(float));
	minVal=_minVal[img];
	step=(float)0xff/(_maxVal[img]-_minVal[img]);
	if (PositionAreaX <= SizeArea)
		PositionAreaX = SizeArea + 1;
	else if (PositionAreaX >= (_imgSz.cx - SizeArea))
		PositionAreaX = (_imgSz.cx - SizeArea) - 1;
	if (PositionAreaY <= SizeArea)
		PositionAreaY = SizeArea + 1;
	else if (PositionAreaY >= (_imgSz.cy - SizeArea))
		PositionAreaY = (_imgSz.cy - SizeArea) - 1;

	PositionArea = (PositionAreaY - 1) * _imgSz.cx + PositionAreaX;
	
	int i,j,k,l,m;
	for (i=(PositionArea-SizeArea)-SizeArea*_imgSz.cx,j=i,
		k=(PositionArea+SizeArea)+SizeArea*_imgSz.cx,l=k;
		i<(PositionArea+SizeArea+1)-SizeArea*_imgSz.cx;
		i++,j=j+_imgSz.cx,k--,l=l-_imgSz.cx) {
		for (m=j;m<(2*SizeArea)+j;m++) {
			if (Pix_near > _z[m]) {
				Pix_near = _z[m];
			}
		}
		v_PIX = (_z[i]*((float)(1<<16)/lambda[frq])-minVal)*step;
		_dibCam[i] = _bmiScale->bmiColors[(BYTE)LIMIT(v_PIX,1000,1000)];
		v_PIX = (_z[j]*((float)(1<<16)/lambda[frq])-minVal)*step;
		_dibCam[j] = _bmiScale->bmiColors[(BYTE)LIMIT(v_PIX,1000,1000)];
		v_PIX = (_z[k]*((float)(1<<16)/lambda[frq])-minVal)*step;
		_dibCam[k] = _bmiScale->bmiColors[(BYTE)LIMIT(v_PIX,1000,1000)];
		v_PIX = (_z[l]*((float)(1<<16)/lambda[frq])-minVal)*step;
		_dibCam[l] = _bmiScale->bmiColors[(BYTE)LIMIT(v_PIX,1000,1000)];
	}
	return (Pix_near*100);
}
//!redirects the call from this static function to the method SRFuncCB
int CWndSwissranger::SSRFuncCB(SRCAM srCam, unsigned int msg, unsigned int param, void* data)
{
	if(!_cbInstance)
		return 0;
	return _cbInstance->SRFuncCB(srCam, msg, param, data);
}
//!callback function of the libMesaSR. It enters/leaves the critical section during changes
int CWndSwissranger::SRFuncCB(SRCAM srCam, unsigned int msg, unsigned int param, void* data)
{
	switch(msg)
	{
	default:
		return SR_GetDefaultCallback()(0,msg,param,data);
		break;
	case CM_CHANGING:
		EnterCritSec();
		break;
	case CM_CHANGED:
		if(param)
			AllocObj();
		LeaveCritSec();
		break;
	}
	return 0;
}

//!allocates memory for _dibCam buffer and initializes the _bmiCam structure
void CWndSwissranger::AllocObj()
{
	_imgSz.cx=SR_GetCols(_srCam);
	_imgSz.cy=SR_GetRows(_srCam);
	_numImg=SR_GetImageList(_srCam,&_imgEntryArray);

	SAFE_FREE(_dibCam);
	_dibCam=(RGBQUAD*)malloc(_imgSz.cx*_imgSz.cy*_numImg*sizeof(RGBQUAD));//RGBQUAD,  RGBTRIPLE, BYTE, WORD
	_bmiCam->bmiHeader.biWidth =_imgSz.cx;
	_bmiCam->bmiHeader.biHeight=-_numImg*_imgSz.cy;

	SAFE_FREE(_z);
	_z=(float*)malloc(_imgSz.cx*_imgSz.cy*sizeof(float));
}

//!frees all allocated objects
void CWndSwissranger::Free()
{
	SAFE_FREE(_dibCam);
	SAFE_FREE(_bmiCam);
	SAFE_FREE(_dibScale);
	SAFE_FREE(_bmiScale);
	SAFE_FREE(_z);
}

//!initializes _maxVal,_bmiCam, _bmiScale and allocates _dibScale
void CWndSwissranger::Initialize()
{
	int i;
	for(i=0;i<_countof(_minVal);i++)
	{
		_minVal[i]=0;
		_maxVal[i]=0xffff;
	}
	_maxVal[0]=30000.f;
	_maxVal[1]=15000.f;
	_maxVal[2]=30000.f;
	_maxVal[3]=15000.f;

	_bmiCam=(BITMAPINFO*)malloc(sizeof(BITMAPINFOHEADER)+1*sizeof(RGBQUAD));
	memset(_bmiCam,0,sizeof(BITMAPINFOHEADER));
	_bmiCam->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
	_bmiCam->bmiHeader.biPlanes = 1;
	_bmiCam->bmiHeader.biBitCount = 32;
	_bmiCam->bmiHeader.biCompression = BI_RGB;

	_bmiScale=(BITMAPINFO*)malloc(sizeof(BITMAPINFOHEADER)+256*sizeof(RGBQUAD));
	memset(_bmiScale,0,sizeof(BITMAPINFOHEADER));
	_bmiScale->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
	_bmiScale->bmiHeader.biPlanes = 1;
	_bmiScale->bmiHeader.biBitCount = 8;
	_bmiScale->bmiHeader.biCompression = BI_RGB;
	_bmiScale->bmiHeader.biWidth=256;
	_bmiScale->bmiHeader.biHeight=1;

	//alloc and fill scale DIB
	int x;
	_dibScale=(BYTE*)malloc(256*sizeof(BYTE));
	for (x=0;x<256;x++)_dibScale[x]=x;
	SetColormap(jet,_bmiScale->bmiColors);
}
//!When the window is created this function will be called
void CWndSwissranger::OnInitialUpdate()
{
	LRESULT lResult;
	HWND hcntrl;
	int i;
	char buf[64];

	HICON hIcon=LoadIcon(hInst, (LPCTSTR)IDI_SMALL);
	lResult = SendMessage(_hWnd, WM_SETICON, ICON_BIG, (LPARAM)hIcon);
	lResult = SendMessage(_hWnd, WM_SETICON, ICON_SMALL, (LPARAM)hIcon);

	hcntrl=GetDlgItem(_hWnd,IDC_CB_COL);
	for(i=0;i<_countof(_minVal);i++)
	{
		_snprintf(buf,_countof(buf),"Image %d",i);
		lResult = SendMessage(hcntrl,CB_INSERTSTRING,-1,(LPARAM)buf);
	}
	lResult = SendMessage(hcntrl,CB_SETCURSEL,0,0);
	SetColorLim(0);
}

//!Sets the acuire mode of the camera
void CWndSwissranger::SetMode(int mode)
{
	EnterCritSec();
	_acquMode=mode;
	SR_SetMode(_srCam, mode);
	LeaveCritSec();
}
//!Sets color limits _minVal[idx] and _maxVal[idx] according to the gui settings
void CWndSwissranger::SetColorLim(int idx)
{
	HWND hcntrl;
	char buf[64];
	hcntrl=GetDlgItem(_hWnd,IDC_MINCOL);
	_snprintf(buf,_countof(buf),"%.2f",_minVal[idx]);
	SetWindowText(hcntrl,buf);
	hcntrl=GetDlgItem(_hWnd,IDC_MAXCOL);
	_snprintf(buf,_countof(buf),"%.2f",_maxVal[idx]);
	SetWindowText(hcntrl,buf);
}
//!called when close button is pressed
void CWndSwissranger::OnCloseDev()
{
	int res;
	TRACE("swissrangerTester: SR_Close");
	res=SR_Close(_srCam);
	EnableWindow(::GetDlgItem(_hWnd,IDC_OPEN),TRUE);
	if (res < 0)
	{
		TRACE("Failed to close device: error %d",res);
		//but change the button states anyway, no return;
	}
	_srCam=0;//there are no valid device opened
}

//!called on a \b WM_PAINT message
void CWndSwissranger::OnPaint()
{	
	char buf[256];
	_snprintf(buf,_countof(buf),"%2.0f\t\t%2.0f\n%2.0f\t\n%2.0f\t\t%2.0f\n",Pix[0],Pix[1],Pix[2],Pix[3],Pix[4]);
	HWND hcntrl=GetDlgItem(_hWnd,IDC_TX_CM);
	::SetWindowText(hcntrl,buf);

	PAINTSTRUCT ps;
	HDC hdc;
	HWND imgWnd;
	hdc = BeginPaint(_hWnd, &ps);
	EndPaint(_hWnd, &ps);
	imgWnd=GetDlgItem(_hWnd,IDC_IMAGE0);
	hdc = BeginPaint(imgWnd, &ps);
	RECT rect;
	GetClientRect(imgWnd,&rect);
	float fct;
	if(_dibScale)
	{
		const SIZE sz={_bmiScale->bmiHeader.biWidth,_bmiScale->bmiHeader.biHeight};
		fct=(float)(rect.right-10)/sz.cx;
		StretchDIBits(hdc, 5, 5, (int)(fct*sz.cx), 10, 0, 0,     // x,y,w,h destination // x,y source
			_bmiScale->bmiHeader.biWidth, _bmiScale->bmiHeader.biHeight,  // width & height in source
			_dibScale, _bmiScale,                                         // pointer to 'bits' //BITMAPINFOHEADER
			DIB_RGB_COLORS, SRCCOPY);
	}

	if(_dibCam)
	{
		const SIZE sz={_bmiCam->bmiHeader.biWidth,-_bmiCam->bmiHeader.biHeight};
		fct=min((float)(rect.right-10)/sz.cx,(float)(rect.bottom-25)/sz.cy);
		StretchDIBits(hdc, 5, 20, (int)(fct*sz.cx), (int)(fct*sz.cy), 0, 0,     // x,y,w,h destination // x,y source
			_bmiCam->bmiHeader.biWidth, -_bmiCam->bmiHeader.biHeight,  // width & height in source
			_dibCam, _bmiCam,                                         // pointer to 'bits' //BITMAPINFOHEADER
			DIB_RGB_COLORS, SRCCOPY);
	}

	EndPaint(imgWnd, &ps);
	return;
}

//!called when open button is pressed
void CWndSwissranger::OnOpenDlg(int mode)
{
	TRACE("swissrangerTester: SR_Open device");
	if (_srCam)
	{
		TRACE("Swiss Ranger device already opened.");
		return;
	}
	int res;
	res=SR_OpenDlg(&_srCam,mode,_hWnd);
	SendMessage(GetDlgItem(_hWnd,IDC_AUTO_EXPOSURE), BST_UNCHECKED, 0, 0);
	_acquMode=SR_GetMode(_srCam);

	SendMessage((HWND)GetDlgItem(_hWnd,IDC_MEDIAN),(UINT)BM_SETCHECK, (_acquMode&AM_MEDIAN)?BST_CHECKED:BST_UNCHECKED,0);
	SendMessage((HWND)GetDlgItem(_hWnd,IDC_CONV_GRAY),(UINT)BM_SETCHECK, (_acquMode&AM_CONV_GRAY)?BST_CHECKED:BST_UNCHECKED,0);

	if (res<=0)
	{
		TRACE("Couldn't connect to Swiss Ranger device error %d",res);
		return;
	}
	TRACE("swissrangerTester: Device opened successfully device handle=%d",_srCam);
	AllocObj();
	EnableWindow(::GetDlgItem(_hWnd,IDC_OPEN),FALSE);
	EnableWindow(::GetDlgItem(_hWnd,IDC_CLOSE),TRUE);
	EnableWindow(::GetDlgItem(_hWnd,IDC_ACQUIRE),TRUE);
}

//!Acquires an image and displays it
void CWndSwissranger::Acquire()
{
	EnterCritSec();
	CntAq++;
	int res=SR_Acquire(_srCam);
	if (res < 0)
	{
		TRACE("Failed to acquire the measurement");
	}
	else
	{
		//logPrintf("swissrangerTester: %d bytes read", res);
		SetDib();
	}
	LeaveCritSec();
	__int64 tic=precTimer.GetTime();precTimer.StartTimer();
	static __int64 smtic=0;
	_timePerFrame=0.90f*_timePerFrame+0.10f*(float)tic/1e6f;
	smtic+=tic;
	smtic=0;
	if (CntAq) {
		SR_SetAutoExposure(_srCam, 5,40,10,45);
		SetMode(_acquMode|AM_MEDIAN);
		SetMode(_acquMode|AM_CONV_GRAY);
		_coordTrf=true;
	}
}

