// RASView.cpp : implementation of the CRASView class
//

#include "stdafx.h"
#include "RAS.h"

#include<stdlib.h>
#include<stdio.h>
#include<math.h>
#include "RAS_Doc.h"
#include "Figure.h"
#include "SharedConstants.h"
#include "RAS_View.h"
#include "SinTable.h"
#include "MainFrm.h"
#include "Dialog_Box.h"
#include "StringEdit.h"
#include "AcceptOneNum.h"
#include "FigureProperty.h"
#include "Trial.h"
#include "VarDefinitionsSDF.h"
#include "Dialog_ECodeContitions.h"


#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

BOOL CRASView::m_bIsON;
/////////////////////////////////////////////////////////////////////////////
// CRASView

IMPLEMENT_DYNCREATE(CRASView, CView)

BEGIN_MESSAGE_MAP(CRASView, CView)
	//{{AFX_MSG_MAP(CRASView)
	ON_WM_KEYDOWN()
	ON_COMMAND(ID_2DGraph_III, &CRASView::On_Start_AFRESH)
	ON_COMMAND(ID_2DGraph_IV, &CRASView::OnRasterPlot)
	ON_UPDATE_COMMAND_UI(ID_2DGraph_IV, &CRASView::CheckRasterPlot)
	ON_COMMAND(ID_2DGraph_V, OnStop_or_Pause)
	ON_COMMAND(ID_Parameters, OnChangeParameters)
	//}}AFX_MSG_MAP
	// Standard printing commands
	ON_COMMAND(ID_FILE_PRINT, CView::OnFilePrint)
	ON_COMMAND(ID_FILE_PRINT_DIRECT, CView::OnFilePrint)
	ON_COMMAND(ID_FILE_PRINT_PREVIEW, CView::OnFilePrintPreview)
	ON_COMMAND(ID_IS_TO_DISP_MARKS, &CRASView::OnIsToDisplayMarks)
	ON_UPDATE_COMMAND_UI(ID_IS_TO_DISP_MARKS, &CRASView::OnUpdateIsToDisplayMarks)
	ON_UPDATE_COMMAND_UI(ID_2DGraph_V, &CRASView::Check_Stop_or_Pause)
	ON_WM_LBUTTONDOWN()
	ON_WM_CONTEXTMENU()
	ON_WM_RBUTTONDOWN()
	ON_WM_KEYUP()
	ON_COMMAND(ID_SCALE_DELETE_FIGS, &CRASView::OnDeleteFigs)
	ON_COMMAND(ID_SCALE_DELETE_THE_REST, &CRASView::OnDelete_the_Rest_Figs)
	ON_COMMAND(ID_FILE_SAVE, &CRASView::OnFileSave)
	ON_COMMAND(ID_FILE_OPEN, &CRASView::OnFileOpen)
	ON_EN_CHANGE(IDC_EDIT_STRING1, &CRASView::OnEnChangeEditString1)
	ON_COMMAND(ID_FIGURE_PROPERTY, &CRASView::OnFigureProperty)
	ON_COMMAND(ID_OPEN_RST_FILE, &CRASView::OnOpen_RST_File)
	ON_COMMAND(ID_VIEW_SDF, &CRASView::OnViewSDF)
	ON_UPDATE_COMMAND_UI(ID_VIEW_SDF, &CRASView::OnUpdateViewSDF)
	ON_COMMAND(ID_VIEW_RASTER, &CRASView::OnViewRaster)
	ON_UPDATE_COMMAND_UI(ID_VIEW_RASTER, &CRASView::OnUpdateViewRaster)
	ON_COMMAND(ID_SIGMA, &CRASView::OnSigma)
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////


// CRASView construction/destruction
CRASView::CRASView()
{
	// TODO: add construction code here
	m_nColorShow=BLACK_BRUSH;
	m_isRAS_Closing = 0;
	m_bFistTime=1;
	m_nKey=0;
	m_nSpeed=0;
	FlagVerScreen=0;
	m_bIsON=0;
	m_dScaleUpDn=1;
	m_dHowManyRows=MaxFigRow; m_dHowManyClmns=MaxFigCln;
	m_BlownUpPaneID=-1;
	m_bIsScrXYforIJ=0;
	m_usableTrialIdxInMem=-1;
	m_Stop_Or_Pause=1;
	m_NumTrialsInMap_InThisProgram=0;
	FirstTimeMsg=1;
	m_DispEventIdx=0;
	m_isDisplayerRunning=0;
	int i,j;
	for(i=0;i<MAX_TRLS_IN_MAP;i++){
		m_PrvEvent_ReMapped[i]=0;
		for(j=0;j<NUM_NN_AI_CHAN;j++){
			m_PrvSpkTimeOfNn1MAP_ReMapped[i][j]=0;
			m_PrvSpkTimeOfNn2MAP_ReMapped[i][j]=0;
			m_PrvSpkTimeOfNn3MAP_ReMapped[i][j]=0;
		}
	}

	////////////////////////////////////
	m_NULL.CreatePen(PS_NULL, 1,RGB(0,0,0));
	m_RED.CreatePen(PS_SOLID, 1,RGB(255,0,0));
	m_RED3.CreatePen(PS_SOLID, 3,RGB(255,0,0));
	m_RED5.CreatePen(PS_SOLID, 5,RGB(255,0,0));
	m_RED8.CreatePen(PS_SOLID, 8,RGB(255,0,0));
	m_White2.CreatePen(PS_SOLID, 2,RGB(255,255,255));
	m_ORANGE2.CreatePen(PS_SOLID, 2,RGB(255,150,0));
	m_GREEN.CreatePen(PS_SOLID, 1,RGB(0,255,0));
	m_BLUE.CreatePen(PS_SOLID, 1,RGB(100,100,255));
	m_BLUE3.CreatePen(PS_SOLID, 3,RGB(100,100,255));
	m_BLUE5.CreatePen(PS_SOLID, 5,RGB(100,100,255));
	m_BLUE8.CreatePen(PS_SOLID, 8,RGB(100,100,255));
	m_GREEN3.CreatePen(PS_SOLID, 3,RGB(0,255,0));
	m_DkGREEN.CreatePen(PS_SOLID, 1,RGB(0,155,0));
	m_CYAN.CreatePen(PS_SOLID, 1,RGB(0,255,255));
	m_CYAN3.CreatePen(PS_SOLID, 3,RGB(200,255,255));
	m_PINK.CreatePen(PS_SOLID, 1,RGB(255,150,150));
	m_PINK3.CreatePen(PS_SOLID, 3,RGB(255,150,150));
	m_BROWN.CreatePen(PS_SOLID, 1,RGB(240,130,0));
	m_VIOLET.CreatePen(PS_SOLID, 1,RGB(200,90,250));
	m_VIOLET2.CreatePen(PS_SOLID, 2,RGB(200,90,250));
	m_VIOLET3.CreatePen(PS_SOLID, 3,RGB(200,90,250));
	m_bkPen.CreatePen(PS_SOLID, 1,RGB(220,220,220));
	m_GRAY2.CreatePen(PS_SOLID, 3,RGB(170,170,170));
	m_BlueGRAY.CreatePen(PS_SOLID, 1,RGB(210,210,240));
	m_BLACK.CreatePen(PS_SOLID, 1,RGB(0,0,0));
	m_BLACK3.CreatePen(PS_SOLID, 3,RGB(0,0,0));
	m_BLACK2.CreatePen(PS_SOLID, 2,RGB(0,0,0));
	m_BLACK5.CreatePen(PS_SOLID, 5,RGB(0,0,0));
	/////////////
	//SigmoidColorMix(m_RGB100,MaxRGB100);
	//GaussianColorMix(m_RGB100,MaxRGB100);
	MyOriginalColorMix(m_RGB100,MaxRGB100);

	for(i=0;i<MaxPen;i++){
		j=(MaxRGB100-1)-i*(MaxRGB100/MaxPen);
		if(j<0)j=0;
		m_rgbPEN1[i].CreatePen(PS_SOLID, 1,m_RGB100[j]);
		m_rgbPEN2[i].CreatePen(PS_SOLID, 2,m_RGB100[j]);
		m_rgbPEN3[i].CreatePen(PS_SOLID, 3,m_RGB100[j]);
	}

	/////////////// Parameters For Applications
	m_toShowRaster=1; m_toShowSDF=1;
	m_GlobalTitle="NoName";
	m_NewlyLoaded=0; m_DoNotErase=0;
	m_dMinimumX=-1000;m_dMaximumX=1000;
	m_dMinimumY=0;m_dMaximumY=100;
	m_savedClientRect.top=0;m_savedClientRect.bottom=0;m_savedClientRect.left=0;m_savedClientRect.right=0;
	m_SelectedItemID=-1; m_numCaptured=0;
	m_AlignmentEcode=0;
	for(i=0;i<MaxFigCln;i++){
		for(j=0;j<MaxFigRow;j++){
			m_Fig[j][i][0].m_row=j;
			m_Fig[j][i][0].m_clm=i;
			m_Fig[j][i][0].m_dpth=0;
		}
	}

	
	m_FirstTime0ElementErr=1;
	m_isFirst_RST=1;
	m_IsFirstTimeRasterPlot=1;
	m_IsFromFile=0;//Bt default, it is from the online recording
	m_IsToDisplayMarks=0;
}					


CRASView::~CRASView() 
{
	m_isRAS_Closing = 1;
	m_bIsON=0;

	CloseSharedMemoryArea();
	CloseTrialMemoryMAP();

	for(int timeOut=0; timeOut<10; timeOut++){
		Sleep(10);
	}	

	POSITION aPos;
	aPos = m_TrialList.GetHeadPosition();
	while(aPos){
		delete m_TrialList.GetNext(aPos); //It deletes the entities connected to the list.
	}
	m_TrialList.RemoveAll(); //It deletes the list itself.

	int i;
	for(i=0; i<MaxDC;i++){
		m_DC[i].DeleteDC();
		m_bmp[i].DeleteObject();
	}
	m_bkBrush.DeleteObject();
	for(i=0; i<MaxPen;i++){
		m_rgbPEN1[i].DeleteObject(); m_rgbPEN2[i].DeleteObject(); m_rgbPEN3[i].DeleteObject();
	}
	m_font.DeleteObject();
	m_NULL.DeleteObject(); m_RED.DeleteObject(); m_BLUE.DeleteObject(); m_GREEN.DeleteObject();m_DkGREEN.DeleteObject();m_CYAN.DeleteObject(); m_PINK.DeleteObject();m_BROWN.DeleteObject();m_VIOLET.DeleteObject();
	m_White2.DeleteObject(); m_ORANGE2.DeleteObject(); m_VIOLET2.DeleteObject();m_VIOLET3.DeleteObject();m_BLACK.DeleteObject();m_BLACK2.DeleteObject();m_BLACK3.DeleteObject();m_bkPen.DeleteObject();
	m_GRAY2.DeleteObject();m_CYAN3.DeleteObject();m_BlueGRAY.DeleteObject();m_PINK3.DeleteObject();m_RED3.DeleteObject(); m_BLUE3.DeleteObject(); m_GREEN3.DeleteObject();
	m_RED5.DeleteObject(); m_BLUE5.DeleteObject(); m_BLACK5.DeleteObject(); m_RED8.DeleteObject(); m_BLUE8.DeleteObject(); m_BLACK8;
}

BOOL CRASView::PreCreateWindow(CREATESTRUCT& cs)
{
	// TODO: Modify the Window class or styles here by modifying
	//  the CREATESTRUCT cs

	return CView::PreCreateWindow(cs);
}
UINT KILL_THREAD(LPVOID WinObjPtr) //A global Function
{
	CRASView* pView=(CRASView*) WinObjPtr;
	while(1){
		if(*(pView->M_Blip_OFF)==1){
			Sleep(50); //Give some time for the RAS_Main() loop to close, in the case it is running.
			AfxGetApp()->m_pMainWnd->SendMessage(WM_CLOSE);
			return 0;
		}
		if(pView->m_isRAS_Closing == 1)return 0;
		Sleep(5);
	}
	return 0;
}
/////////////////////////////////////////////////////////////////////////////
// CRASView drawing
#define SIZE_OF_BITMAP_X 0.8
#define SIZE_OF_BITMAP_Y 0.6
void CRASView::OnDraw(CDC* pDC)
{
#define CH_SIZE_X 8
#define CH_SIZE_Y 10
#define LINE_GAP  5
#define STR_SIZE  150
#define SFT		  0
#define SFT1      200
#define SFT2      400
#define SFT3      600

	CRASDoc* pDoc = GetDocument();
	ASSERT_VALID(pDoc);

	if(m_bFistTime==1){
		VirMemDC();
		m_dHowManyClmns=-1;
		OnFileOpen();//Try to open a default root file.
		CreateSharedMemoryArea();
		AfxBeginThread( KILL_THREAD, this); //This is running just to detect the user's commend of "close all Blip windows". This thread is needed to close RAS even when it is Stopped. There must be a better way to do this rather than running a thread all the time. 
		if(m_dHowManyClmns!=-1){
			m_bFistTime=0;
			return;//Opening a default root file has been successful.
		}
		//Failed to open a default root file => implement the programs own version.
		sprintf(m_FileName,"");
		sprintf(m_JustFileName,"NO root file");
		m_dHowManyClmns=MaxFigCln; 
		Re_measure_ClientView();
		Start_a_NEW_set_of_figures();
		m_bFistTime=0;
	}
	else{
		CRect rt;
		GetClientRect(&rt);
		if(m_savedClientRect.right!=rt.right||m_savedClientRect.bottom!=rt.bottom){//Specifies the window's coordinates when the window is in the normal (restored) position. 
			if(m_savedClientRect.right<rt.right ||m_savedClientRect.bottom<rt.bottom){
				if(m_savedClientRect.right>=SIZE_OF_BITMAP_X*m_nScrMaxX ||m_savedClientRect.bottom>=SIZE_OF_BITMAP_Y*m_nScrMaxY){
					int Y=SIZE_OF_BITMAP_Y*m_nScrMaxY;
					char ScreenMsg[1024]; sprintf(ScreenMsg,"Simon: To save Bitmap memory, the size of the window is currently limited to Horizontal:%d, Vertical:%d\n To change this setting, adjust SIZE_OF_BITMAP_X and SIZE_OF_BITMAP_Y in the program.\n Let me know if you have an easier solution.",(int)(SIZE_OF_BITMAP_X*m_nScrMaxX),Y);
					AfxMessageBox(ScreenMsg);
				}
			}
			if(	m_isDisplayerRunning==1)RequestDisplayEvent(RESIZING_WIN);
			else { CClientDC ObjDC(this); DispForResizing( &ObjDC);	}
		}
		else{//Just display without changing anything
			if(m_isDisplayerRunning==1)RequestDisplayEvent(REFRESH_SCREEN);
			else{
				CClientDC ObjDC(this);
				ObjDC.BitBlt(0,0,m_nScrMaxX,m_nScrMaxY,&m_DC[0],0,0,SRCCOPY);
			}
		}
	}
}

void CRASView::Start_a_NEW_set_of_figures()
{
	int i, j;
	double SigmaToInherit = 10; //Without this inheriting, the Sigmas could be different from figure to figure.
	CFigure *pFig;
	m_numCaptured = 0;
	//See if there was any Previous having Sigma
	for (i = 0; i < m_dHowManyClmns; i++) {
		for (j = 0; j < m_dHowManyRows; j++) {
			pFig = &m_Fig[j][i][0];
			if (pFig->m_Deleted == 0) {
				SigmaToInherit = pFig->m_dSigma;
				goto OutofThisLoop;
			}
		}
	}
OutofThisLoop:;
	for (i = 0; i < m_dHowManyClmns; i++) {
		for (j = 0; j < m_dHowManyRows; j++) {
			pFig = &m_Fig[j][i][0];
			pFig->SetMinMaxXY(-1000, 1000, 0, 100); pFig->SetLabelsXY("", "");
			pFig->m_Captured = 0;
			pFig->m_Deleted = 0;
			pFig->m_dSigma = SigmaToInherit;
		}
	}
	Batch_FigPosition_Settings(m_dSizeOfOneRow, m_dSizeOfOneClmn, m_dScaleUpDn);
	Batch_SetFontSize(&m_DC[0]);
	Batch_Prepare4FigFrame();
	Batch_DrawFigureFrames(1);
}

void CRASView::Re_measure_ClientView()
{			
	CRect rt;
	GetClientRect(&rt);
	if(m_bFistTime==1){
		CFont* pFont = m_DC[0].GetCurrentFont();
		LOGFONT LogFont;
		pFont->GetLogFont(&LogFont);
		m_fontHeight=LogFont.lfHeight;
	}
	m_TitleArea.top=rt.top;	m_TitleArea.bottom=rt.top+m_fontHeight*2; m_topOfFigs=m_TitleArea.bottom;
	m_TitleArea.left=rt.left; m_TitleArea.right=rt.right;
	m_dSizeOfOneRow =(rt.bottom-m_topOfFigs-ViewMargin4FigsAlongEdges)/m_dHowManyRows;  if(m_dSizeOfOneRow <=0)m_dSizeOfOneRow=0;
	m_dSizeOfOneClmn=(rt.right-rt.left-ViewMargin4FigsAlongEdges)/m_dHowManyClmns; if(m_dSizeOfOneClmn<=0)m_dSizeOfOneClmn=0;
	m_savedClientRect=rt;m_savedClientRect.top=m_topOfFigs;
}


/////////////////////////////////////////////////////////////////////////////
// CRASView printing

BOOL CRASView::OnPreparePrinting(CPrintInfo* pInfo)
{
	// default preparation
	return DoPreparePrinting(pInfo);
}

void CRASView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
	// TODO: add extra initialization before printing
}

void CRASView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
	// TODO: add cleanup after printing
}

/////////////////////////////////////////////////////////////////////////////
// CRASView diagnostics

#ifdef _DEBUG
void CRASView::AssertValid() const
{
	CView::AssertValid();
}

void CRASView::Dump(CDumpContext& dc) const
{
	CView::Dump(dc);
}

CRASDoc* CRASView::GetDocument() // non-debug version is inline
{
	ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CRASDoc)));
	return (CRASDoc*)m_pDocument;
}
#endif //_DEBUG

/////////////////////////////////////////////////////////////////////////////
// CRASView message handlers

UINT RASTER_Plot(LPVOID WinObjPtr) //A global Function
{
	CRASView* pView=(CRASView*) WinObjPtr;
	pView->RAS_Main();

	return 0;
}

void CRASView::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags) 
{
	//if(m_nShowMode==GRAPH_3D){ThD.KeyDown(nChar); goto ToEND;}
	m_KeyCode=nChar;
	switch(nChar){
		case VK_DELETE:
			OnDeleteFigs();
			break;
		default: break;
	}

	CView::OnKeyDown(nChar, nRepCnt, nFlags);
}


void CRASView::On_Start_AFRESH() 
{
	ClearHistory(1);	
	OnRasterPlot();//This function starts to run, only when it is not already runing.
}

void CRASView::ClearHistory(int isToDispCleanFig) 
{
	m_Stop_Or_Pause=1;
	int row,clm;
	CFigure *pFig;
	for(clm=0;clm<m_dHowManyClmns;clm++){
		for(row=0;row<m_dHowManyRows;row++){
			pFig=&m_Fig[row][clm][0];
			//if(pFig->m_Captured!=1)continue;
			pFig->EmptyHistogramAndSpikes();
			if(isToDispCleanFig==1 &&(pFig->m_Deleted==0 && m_NewlyLoaded!=1))DrawOneFigure(pFig, pFig->m_Captured); //Newly Loaded ones are already drawn by "EliminateExcluded()"
	}	}	
}

void CRASView::OnRasterPlot() 
{
	if(m_Stop_Or_Pause==1){
		m_Stop_Or_Pause=0;//Starting
		if(m_isDisplayerRunning==1)RequestDisplayEvent(REDRAW_ALL_CONTENT);
		else 		RedrawAllContent(); //Since the display loop is not running.
	}
	if(m_bIsON==0){
		AfxBeginThread( RASTER_Plot, this);
	}
}
void CRASView::CheckRasterPlot(CCmdUI *pCmdUI) 
{
	pCmdUI->SetCheck(m_Stop_Or_Pause==0);
}
void CRASView::OnStop_or_Pause() 
{
	if(m_Stop_Or_Pause==0){
		m_Stop_Or_Pause=1; //Stop or pause da
		if(m_isDisplayerRunning==1)RequestDisplayEvent(REDRAW_ALL_CONTENT);
		else 		RedrawAllContent(); //Since the display loop is not running.
	}
}
void CRASView::Check_Stop_or_Pause(CCmdUI *pCmdUI) 
{
	pCmdUI->SetCheck(m_Stop_Or_Pause==1);
}


void CRASView::VirMemDC()
{
	//########  Preparing Virtual Window  ##########
	if(FlagVerScreen==1){
		//Clear screen
		//m_DC[0].PatBlt(0,0,m_nScrMaxX,m_nScrMaxY,PATCOPY);
		return;
	}
	FlagVerScreen=1;
////////////////////////////////
   LOGFONT lf;                        // Used to create the CFont.
   memset(&lf, 0, sizeof(LOGFONT));   // Clear out structure.
   lf.lfWidth = 6;                   // Width of font
   lf.lfHeight = 12;                  // Request a 20-pixel-high font
   strcpy(lf.lfFaceName, "Times New Roman");    //    with face name "Arial".
   m_font.CreateFontIndirect(&lf);    // Create the font.
   // Use the font to paint a control. This code assumes
   // a control named IDC_TEXT1 in the dialog box.
   SetFont(&m_font);
//////////////////////////////////////
	
	m_nScrMaxX=GetSystemMetrics(SM_CXSCREEN);
	m_nScrMaxY=GetSystemMetrics(SM_CYSCREEN);
	LOGBRUSH LogBrh;
	LogBrh.lbStyle=BS_SOLID;	LogBrh.lbColor=RGB(220,220,220);	
	m_bkBrush.CreateBrushIndirect( &LogBrh );
	//m_bkBrush.CreateStockObject(WHITE_BRUSH);
	CClientDC aDC(this);
	
	int result;
	for(int i=0;i<MaxDC;i++){
		result=m_DC[i].CreateCompatibleDC(&aDC);
		result=m_bmp[i].CreateCompatibleBitmap(&aDC, m_nScrMaxX*SIZE_OF_BITMAP_X, m_nScrMaxY*SIZE_OF_BITMAP_Y);
		m_DC[i].SelectObject(&m_bmp[i]);
		m_DC[i].SelectObject(&m_bkBrush);
		m_DC[i].SelectObject(&m_font);
		//m_DC[i].PatBlt(0,0,m_nScrMaxX,m_nScrMaxY,PATCOPY);
	}
	m_SavedDC=m_DC[0].SaveDC();
}

///////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////
//################################################  2D Graphics #######################################
#define MY_PEEK_MESSAGE {if(::PeekMessage (&message, NULL,0,0, PM_REMOVE)){::TranslateMessage(&message);::DispatchMessage(&message);}	}	
//With a 32bit int (INT_MAX~ 2147,000,000), a micro second counter will last only ~ 30 minutes!!
//With a 64bit int (INT_MAX~ 9,223,372,036,854,775,807), a micro second counter will last ~287000 years!!

void CRASView::SetParametersForFigures() 
{
	int size;
	int row, clm,i;
	CFigure *pFig;
	for(clm=0;clm<m_dHowManyClmns;clm++){
		for(row=0;row<m_dHowManyRows;row++){
			pFig=&m_Fig[row][clm][0];
			if(pFig->m_Deleted==1)continue;
			pFig->m_dMinXMinus2Sigma=pFig->m_dMinX-MAX_SIGMA_x2; pFig->m_dMaxXPlus2Sigma=pFig->m_dMaxX+MAX_SIGMA_x2;
			size=pFig->m_dMaxX-pFig->m_dMinX+2*MAX_SIGMA_x2;
			pFig->m_HistOfSpikes.SetSize(size);
			pFig->m_SDF.SetSize(size);
			pFig->m_HistArraySize=size;
			pFig->EmptyHistogramAndSpikes();
		}
	}
	//Register (parce) the ECode condition for each figure 
	for(clm=0;clm<m_dHowManyClmns;clm++){
		for(row=0;row<m_dHowManyRows;row++){
			pFig=&m_Fig[row][clm][0];
			if(pFig->m_Deleted==1)continue;
			pFig->ExtractECodeConditions(pFig->m_MustExiestECodes,ECODE_MUST_EXIEST);
			pFig->ExtractECodeConditions(pFig->m_MustNotExiestECodes,ECODE_MUST_NOT_EXIEST);
			pFig->ExtractECodeConditions(pFig->m_OneOfThemMustExiestECodes,ONE_OF_ECODES_MUST_EXIEST);
	}	}
	OnIsToDisplayMarks(); 
}

void CRASView::RAS_Main() 
{	
	m_bIsON=1;
	m_IsFromFile=0;
	if(m_Stop_Or_Pause==1){
		m_Stop_Or_Pause=0;
		RedrawAllContent(); //Since the display loop is not running.
	}

	CClientDC objDC(this);
	CFigure *pFig;
	int row, clm,i;
	CSingleLock ___SyncObj_Display(&m_sema); 

	//Just for the first-time running: Prepare and initialize variables .
	if(m_IsFirstTimeRasterPlot){
		m_IsFirstTimeRasterPlot=0;
		m_fSigma=40;
		m_RangeX_ms=2*m_fSigma;
		CreateKer(m_fSigma, m_RangeX_ms);
		m_IsToDisplayMarks=1; 
		SetParametersForFigures(); 
	}

	//Wait for DAS-server to start & initialize "DYNAMIC" variables.
	while(*M_isDAS_Running==0||*M_usableTrialIdxInMem<0){Sleep(10); if(m_bIsON==0|| *M_Blip_OFF==1)goto EndProgram; }

	//Register where the trial data should be read from the Memory Map.
	for(clm=0;clm<m_dHowManyClmns;clm++){
		for(row=0;row<m_dHowManyRows;row++){
			pFig=&m_Fig[row][clm][0];
			if(pFig->m_Deleted==1)continue;
			pFig->m_prvUsableTrialIdxInMem=*M_usableTrialIdxInMem-1; if(pFig->m_prvUsableTrialIdxInMem<-1)pFig->m_prvUsableTrialIdxInMem=-1;
	}	}
	m_ProcessedUsableTrialIdxInMem=*M_usableTrialIdxInMem-1; if(m_ProcessedUsableTrialIdxInMem<-1)m_ProcessedUsableTrialIdxInMem=-1;


	//#########################  The main loop ####################################################
	//#########################  The main loop ####################################################
	int DispIdx=0, nextDispIDx, DispIdxDist; 
	m_DispEventIdx=0;
	m_isDisplayerRunning=1;
	while(1){
		//Do this only when it is NOT in Pause or Stop.
		if(m_Stop_Or_Pause==0){	
			if(m_NumTrialsInMap_InThisProgram<*M_NumTrlsInMAP)CatchUpWithMemMap(); 
			if(m_ProcessedUsableTrialIdxInMem!=*M_usableTrialIdxInMem && *M_usableTrialIdxInMem>-1){
				m_ProcessedUsableTrialIdxInMem=*M_usableTrialIdxInMem;
				___SyncObj_Display.Lock();
				StoreToFigures_n_Draw();
				___SyncObj_Display.Unlock();
			}
			else{ for(i=0;i<10; i++){Sleep(5); if(m_bIsON==0|| *M_Blip_OFF==1)goto EndProgram;}}
		}

		//Pause or Stop
		if(m_Stop_Or_Pause==1)Sleep(5);

		//################  Display ############################
		if(DispIdx<=m_DispEventIdx)DispIdxDist=m_DispEventIdx-DispIdx;
		else DispIdxDist=MAX_DISP_REQUESTS-DispIdx+m_DispEventIdx;
		if(DispIdxDist>0){
			for(i=0;i<DispIdxDist; i++){
				if(DispIdx+1<MAX_DISP_REQUESTS)nextDispIDx=DispIdx+1; else nextDispIDx=0;
				if(i+1<DispIdxDist && m_DispEvents[DispIdx][0]==m_DispEvents[nextDispIDx][0]){
					if(m_DispEvents[DispIdx][1]>=1){//Number of arguments
						if(m_DispEvents[DispIdx][2]==m_DispEvents[nextDispIDx][2]){//The 1st argument
							if(m_DispEvents[DispIdx][1]>=2){
								if(m_DispEvents[DispIdx][3]==m_DispEvents[nextDispIDx][3]){//The 2st argument
									DispIdx=nextDispIDx; continue;//In case the next dispaly request is the same as the current one, skip the current one.
								}
							}
							else {DispIdx=nextDispIDx; continue;}//In case the next dispaly request is the same as the current one, skip the current one.
						}
					}
					else {DispIdx=nextDispIDx; continue;}//In case the next dispaly request is the same as the current one, skip the current one.
				}
				___SyncObj_Display.Lock();
				DisplayStuff(DispIdx,&objDC);
				___SyncObj_Display.Unlock();
				DispIdx=nextDispIDx;				
			}
		}
		//######################################################

		if(m_bIsON==0|| *M_Blip_OFF==1) break;
	}
	//#############################################################################
	//#############################################################################
EndProgram:;
	m_isDisplayerRunning=0;
	CloseTrialMemoryMAP();//Clear all trial views so that TAS could restart again, in case TAS has been closed and now is opening.
	m_bIsON=0;
	//m_Stop_Or_Pause=1;

}
void CRASView::DisplayStuff(int RequestIdx, CDC *pObjDC)
{		
	switch(m_DispEvents[RequestIdx][0]){
	case RESIZING_WIN:
		DispForResizing(pObjDC);
		break;
	//case RENAMING_FIG:
	//	for(rowP=0;rowP<m_dHowManyRows;rowP++){
	//		for(clmP=0;clmP<m_dHowManyClmns;clmP++){
	//			pFig=&m_Fig[rowP][clmP][0];
	//			pFig->DispNameOfFigure(&m_DC[0]);
	//			pFig->RefreshNameBox(pObjDC, &m_DC[0]);
	//	}	}
 //		RefreshFrame();
	//	break;	
	case RESCALING_AXES:
		DispForRescalingAxes(pObjDC);
		break;	
	//case DISP_FILE_NAME:
	//	DispFileName();
		break;	
	case REDRAW_ALL_CONTENT:
		RedrawAllContent();
		break;	
	case REDRAW_ONE_FIG_CONTENT:
		Draw_OneFig_andContent(m_DispEvents[RequestIdx][2], m_DispEvents[RequestIdx][3]);
		break;	
	case REFRESH_SCREEN:
		pObjDC->BitBlt(0,0,m_nScrMaxX,m_nScrMaxY,&m_DC[0],0,0,SRCCOPY);
		break;	
	}
}	

void CRASView::RedrawAllContent() 
{
	CClientDC objDC(this);
	Batch_DrawFigureFrames(0);
	RedrawSDFandRaster_inAllFigures();
	DisplayTitle();
	Hilight_AllCaptured_Figs();
	m_DC[0].SetBkColor(RGB(220, 220, 220));
	m_DC[0].TextOut( m_TitleArea.left+5,m_TitleArea.top+5, m_JustFileName);
	objDC.BitBlt(0,0,m_nScrMaxX,m_nScrMaxY,&m_DC[0],0,0,SRCCOPY);
	m_DC[0].SetBkColor(RGB(255, 255, 255));
}

void CRASView::Draw_OneFig_andContent(int row, int clm) 
{
	Draw_OneFig_andContent(&m_Fig[row][clm][0]) ;
}

void CRASView::Draw_OneFig_andContent(CFigure *pFig) 
{
	if(pFig->m_Deleted==1)return; 
	pFig->Frame_Graph2D(&m_DC[0],1, !m_Stop_Or_Pause); 
	pFig->DispSpkRaster_OneType(&m_DC[0],m_toShowRaster);
	pFig->DispSDF_OneType(&m_DC[0], m_toShowSDF);
	pFig->EmboseAndHighlightFrame(&m_DC[0], 1, !m_Stop_Or_Pause);
	CClientDC objDC(this);
	pFig->DispLabel(pFig->m_EcodeToMarkLabel,&objDC, &m_DC[0]);
	pFig->RefreshFrame(&objDC, &m_DC[0]);
	m_DC[0].SetBkColor(RGB(220, 220, 220));
	m_DC[0].TextOut( m_TitleArea.left+5,m_TitleArea.top+5, m_JustFileName);
	m_DC[0].SetBkColor(RGB(255, 255, 255));
}

void CRASView::DispForResizing(CDC *pObjDC) 
{
	Re_measure_ClientView();
	Batch_FigPosition_Settings(m_dSizeOfOneRow, m_dSizeOfOneClmn, m_dScaleUpDn);
	Batch_Prepare4FigFrame();
	Batch_DrawFigureFrames(0);
	Hilight_AllCaptured_Figs();
	DisplayTitle();
	RedrawSDFandRaster_inAllFigures();
	m_bIsScrXYforIJ=0;
	pObjDC->BitBlt(0,0,m_nScrMaxX,m_nScrMaxY,&m_DC[0],0,0,SRCCOPY);
}

void CRASView::DispForRescalingAxes(CDC *pObjDC) 
{
	int rowP,clmP;
	CFigure *pFig;
	for(rowP=0;rowP<m_dHowManyRows;rowP++){
		for(clmP=0;clmP<m_dHowManyClmns;clmP++){
			pFig=&m_Fig[rowP][clmP][0];
			if(pFig->m_Captured!=1||pFig->m_Deleted==1)continue;
			pFig->Prepare4FigFrame(); 
			pFig->Frame_Graph2D(&m_DC[0],1, !m_Stop_Or_Pause); 
			Hilight_OneCapturedFig(pFig);
			pFig->DispSpkRaster_OneType(&m_DC[0], m_toShowRaster);
			pFig->DispSDF_OneType(&m_DC[0], m_toShowSDF);
			pFig->RefreshFrame(pObjDC,&m_DC[0]); 
	}	}	
}

void CRASView::RequestDisplayEvent(int Event) 
{
	RequestDisplayEvent(Event, 0, NULL,  NULL);
}
void CRASView::RequestDisplayEvent(int Event,  int SomeIntValue) 
{
	RequestDisplayEvent(Event, 1, SomeIntValue,  NULL); 
}
void CRASView::RequestDisplayEvent(int Event,  int SomeIntValue1,  int SomeIntValue2) 
{
	RequestDisplayEvent(Event, 2, SomeIntValue1, SomeIntValue2);
}
void CRASView::RequestDisplayEvent(int Event, int NumVariables,  int SomeIntValue1,  int SomeIntValue2) 
{	
	m_DispEvents[m_DispEventIdx][0]=Event;
	m_DispEvents[m_DispEventIdx][1]=NumVariables;
	for(int i=0; i<NumVariables;i++){
		if(i==0)m_DispEvents[m_DispEventIdx][i+2]=SomeIntValue1; 
		else if(i==1)m_DispEvents[m_DispEventIdx][i+2]=SomeIntValue2; 
	}
	if(m_DispEventIdx+1<MAX_DISP_REQUESTS)m_DispEventIdx++; else m_DispEventIdx=0;
}

void CRASView::CatchUpWithMemMap() 
{	
	int i, difference=*M_NumTrlsInMAP-m_NumTrialsInMap_InThisProgram; 
	int TrlIdxInMap,sizeOfMap;
	int IsToCreate=0;//This is to inform the Memory Map creator that this is just to see the exising map, that the size of the map needs to be drived from the map itself.
	for(i=0;i<difference;i++){
		TrlIdxInMap=m_NumTrialsInMap_InThisProgram;
		#include "MemMap_Open_Trials.h"
		m_NumTrialsInMap_InThisProgram++;
	}
}
void CRASView::RedrawSDFandRaster_inAllFigures()
{
	CFigure *pFig;
	int row, clm;
	for(clm=0;clm<m_dHowManyClmns;clm++){
		for(row=0;row<m_dHowManyRows;row++){
			pFig=&m_Fig[row][clm][0];
			if(pFig->m_Deleted==1)continue;
			pFig->DispSpkRaster_OneType(&m_DC[0], m_toShowRaster);
			pFig->DispSDF_OneType(&m_DC[0], m_toShowSDF);
		}
	}
}

void CRASView::StoreToFigures_n_Draw()
{	
	CClientDC objDC(this);
	int row, clm,i,numSpks, TrlIdxInMap, ch;
	CFigure *pFig;
	int	sizeOfMap; //sizeOfMap is given here just because "MemMap_Open_SpikesNnX.h" contains it. But is not used at all because it by passes the CreateFileMapping() function; RAS just opens the existing Memory Map created by TAS. 
	char NameOfMap[256], Msg[1000];
	int		*pECode, *pSpkTimes, numEcodes, index, InitEcode, FirstTimeOfTrial;
	int IsToCreate;
	__int64 *pETime, alignTime, eventTimeToMark, *pSpksMAP,dumy;
	CSpksInTrialByChan *pSpkInChan;
	int	*pSpksFig;
	for(clm=0;clm<m_dHowManyClmns;clm++){
		for(row=0;row<m_dHowManyRows;row++){
			pFig=&m_Fig[row][clm][0]; 
			if(pFig->m_Deleted==1)continue;
			if(pFig->m_prvUsableTrialIdxInMem!=*M_usableTrialIdxInMem){//This comparison is not needed(?), in case there is no action going back in time and registering prior trials. Currently RAS does not register trials happend before the start of the RAS.
				//Memory Map
				pFig->m_prvUsableTrialIdxInMem=*M_usableTrialIdxInMem;
				TrlIdxInMap=pFig->m_prvUsableTrialIdxInMem;
				if(TrlIdxInMap>m_NumTrialsInMap_InThisProgram-1){


					//==> This happened when I pressed the save icon after a long pause of the trial

					AfxMessageBox("Does it really happpen?");//This should not happen because of the following line: "while(*M_isDAS_Running==0||*M_usableTrialIdxInMem<0){Sleep(10); if(m_bIsON==0)goto EndProgram; }"
				}
				if(M_Events_ReMapped[TrlIdxInMap]!=m_PrvEvent_ReMapped[TrlIdxInMap]){//This means that there has been a bigger-than-memoryMap size event number and the memrryMap needed to re-create a bigger space for the events.
					m_PrvEvent_ReMapped[TrlIdxInMap]=M_Events_ReMapped[TrlIdxInMap];
					IsToCreate=3;//Re-open (because the TAS has remapped the memory map using "IsToCreate=2".
					#include "MemMap_Open_Ecodes.h"
				}
				pECode=M_ECodesMAP[TrlIdxInMap];
				pETime=M_EventTimesMAP[TrlIdxInMap];
				numEcodes=*M_numEcodesMAP[TrlIdxInMap];
				InitEcode=0; FirstTimeOfTrial=1; 
				while(1){//Find all Events, even when it occurrs more than once in a trial.
					//##############  Filter with (1) trial type, (2) alignment, And find an event to mark  ###############
					if(ConditionsToMeet(pFig, pECode, pETime, numEcodes, InitEcode, alignTime, eventTimeToMark)==0){
						if(FirstTimeOfTrial==1 && pFig->m_PrvActive==1){pFig->BlackZeroAxes(&m_DC[0]);pFig->RefreshFrame(&objDC, &m_DC[0]);	}
						goto NEXT_FIG;
					}

					if(FirstTimeOfTrial==1){//Do it only once for a trial
						//#####################  Memory Map  #############################
						if(*M_NumChansHavingSpikes[TrlIdxInMap]>0){//Was there any spike among the channels?
							ch=pFig->m_ChanID;
							if(pFig->m_NnID==0){
								if(M_SpkTimeOfNn1MAP_ReMapped[TrlIdxInMap][ch]!=m_PrvSpkTimeOfNn1MAP_ReMapped[TrlIdxInMap][ch]){
									m_PrvSpkTimeOfNn1MAP_ReMapped[TrlIdxInMap][ch]=M_SpkTimeOfNn1MAP_ReMapped[TrlIdxInMap][ch];
									IsToCreate=3;//Re-open (because the TAS has remapped the memory map using "IsToCreate=2".
									#include "MemMap_Open_SpikesNn1.h"
								}
								pSpksMAP=M_SpkTimeOfNn1MAP[TrlIdxInMap][ch]; numSpks=*M_numSpksOfNn1MAP[TrlIdxInMap][ch];
							}
							else if(pFig->m_NnID==1){
								if(M_SpkTimeOfNn2MAP_ReMapped[TrlIdxInMap][ch]!=m_PrvSpkTimeOfNn2MAP_ReMapped[TrlIdxInMap][ch]){
									m_PrvSpkTimeOfNn2MAP_ReMapped[TrlIdxInMap][ch]=M_SpkTimeOfNn2MAP_ReMapped[TrlIdxInMap][ch];
									IsToCreate=3;//Re-open
									#include "MemMap_Open_SpikesNn2.h"
								}
								pSpksMAP=M_SpkTimeOfNn2MAP[TrlIdxInMap][ch]; numSpks=*M_numSpksOfNn2MAP[TrlIdxInMap][ch];
							}
							else if(pFig->m_NnID==2){
								if(M_SpkTimeOfNn3MAP_ReMapped[TrlIdxInMap][ch]!=m_PrvSpkTimeOfNn3MAP_ReMapped[TrlIdxInMap][ch]){
									m_PrvSpkTimeOfNn3MAP_ReMapped[TrlIdxInMap][ch]=M_SpkTimeOfNn3MAP_ReMapped[TrlIdxInMap][ch];
									IsToCreate=3;//Re-open
									#include "MemMap_Open_SpikesNn3.h"
								}
								pSpksMAP=M_SpkTimeOfNn3MAP[TrlIdxInMap][ch]; numSpks=*M_numSpksOfNn3MAP[TrlIdxInMap][ch];
							}
							else{AfxMessageBox("pFig->m_NnID==?");}
						}
						else numSpks=0;
					}
					//#####################  Figure  #############################
					if(pFig->m_numSpkArrayLists<MAX_TRLS_STORED_IN_FIG){
						pFig->m_CurrIdxOfSpkTimes++;// == pFig->m_numSpkArrayLists
						if(DEFAULT_SPK_NUM_PER_TRIAL<numSpks)pFig->m_SpkTimes[pFig->m_numSpkArrayLists].SetSize(numSpks);
						else pFig->m_SpkTimes[pFig->m_numSpkArrayLists].SetSize(DEFAULT_SPK_NUM_PER_TRIAL);
						pSpksFig=&(pFig->m_SpkTimes[pFig->m_numSpkArrayLists][0]);
						pFig->m_numSpks[pFig->m_numSpkArrayLists]=numSpks;
						if(pFig->m_numSpkArrayLists!=pFig->m_CurrIdxOfSpkTimes){
							sprintf(Msg,"pFig->m_numSpkArrayLists(%d) != pFig->m_CurrIdxOfSpkTimes(%d)",pFig->m_numSpkArrayLists,pFig->m_CurrIdxOfSpkTimes);
							AfxMessageBox(Msg);
						}
						pFig->m_EventTimeToMark[pFig->m_numSpkArrayLists]=(int)(0.001*(eventTimeToMark-alignTime));
						pFig->m_numSpkArrayLists++;
					}
					else{
						index=pFig->m_CurrIdxOfSpkTimes+1;
						if(index>=MAX_TRLS_STORED_IN_FIG)index=0;
						pFig->m_CurrIdxOfSpkTimes=index;
						if(pFig->m_OldestSpkArrayIdx+1<MAX_TRLS_STORED_IN_FIG)pFig->m_OldestSpkArrayIdx++; else pFig->m_OldestSpkArrayIdx=0;
						if(pFig->m_SpkTimes[index].GetSize()<numSpks)pFig->m_SpkTimes[index].SetSize(numSpks);
						pSpksFig=&(pFig->m_SpkTimes[index][0]);
						pFig->m_numSpks[index]=numSpks;
						pFig->m_EventTimeToMark[index]=(int)(0.001*(eventTimeToMark-alignTime));
					}
					//Copy the spike time data in the Memory Map M_SpkTimeOfNnXMAP[trl][ch][] to pFig->m_SpkTimes[pFig->m_CurrIdxOfSpkTimes+1][]
					for(i=0;i<numSpks;i++){
						pSpksFig[i]=(int)(0.001*(pSpksMAP[i]-alignTime));
					}
					pFig->Build_SpkHistogram_withoutSDF(); 
					FirstTimeOfTrial=0;
				}
				NEXT_FIG:;
				pFig->Make_SDF_from_Histogram(); 
				{//Display
					pFig->Frame_Graph2D(&m_DC[0],1, !m_Stop_Or_Pause);
					if(FirstTimeOfTrial==0)pFig->RedZeroAxes(&m_DC[0]);
					pFig->DispSpkRaster_OneType(&m_DC[0], m_toShowRaster);	
					pFig->DispSDF_OneType(&m_DC[0], m_toShowSDF);
				}
				pFig->RefreshFrame(&objDC, &m_DC[0]);
			}
		}
	}
}

int CRASView::ConditionsToMeet(CFigure *pFig, int *pECode, __int64 *pETime, int numEcodes, int &InitEcode, __int64 &alignTime, __int64 &eventTimeToMark)
{	
	//Find the trial type
	if(pFig->Find_MUST_and_MustNOT_ECodes(pECode, numEcodes)==0 || pFig->Find_OneOfThemMustExist_ECodes(pECode, numEcodes)==0){
		return 0;
	}

	//Find the alignment ECode
	int i;
	for(i=InitEcode;i<numEcodes;i++){
		if(pFig->m_Alignment.m_AssociatedVar==pECode[i]){
			alignTime=pETime[i]; break;
	}	}
	InitEcode=i+1;//The ecode index to search for the next round.
	if(i>=numEcodes){
		return 0;//The Ecode was not found.
	}
	else 

	////Find the Nth trl
	//if(m_ToUse_TrialIdxOfTheBlock==1 && Find_OneOfThese_MustExist_NthTrials(TrlInfo[trl].m_InBlockSuccessfulTrlIdx)==0){
	//	return 0;
	//}
	//RT requirement
	//if(TrlInfo[trl].m_RT_excludingAbortedTrials>225)return 0;

	//Event to mark
	eventTimeToMark=INT_MAX;
	for(i=0;i<numEcodes;i++){
		if(pFig->m_EcodeToMarkLabel.m_AssociatedVar==pECode[i]){
			eventTimeToMark=pETime[i]; break;
	}	}

	
	return 1;
}

void CRASView::Show2D_I() 
{
}
void CRASView::Show2D_III() 
{	
}
void CRASView::Show2D_IV() 
{
}

void CRASView::Show2D_VI() 
{
}
void CRASView::Show2D_VII() 
{
}

void CRASView::Tics_n_Lines(CFigure *pBrd, int HowManyTicsX, int HowManyTicsY) 
{
#define TICK_STEPX(pB) ((pB->m_dMaxX-pB->m_dMinX)/(pB->m_howManyXguideLines-1))
#define TICK_STEPY(pB) ((pB->m_dMaxY-pB->m_dMinY)/(pB->m_howManyYguideLines-1))
	int i;
	float TickStepX, TickStepY;

	pBrd->m_howManyXguideLines=HowManyTicsX; TickStepX=TICK_STEPX(pBrd);
	for(i=0;i<pBrd->m_howManyXguideLines;i++){pBrd->m_IsLabeledTicX[i]=1;pBrd->m_XTics[i]=pBrd->m_dMinX+i*TickStepX;} 
	pBrd->m_howManyYguideLines=HowManyTicsY; TickStepY=TICK_STEPY(pBrd);
	for(i=0;i<pBrd->m_howManyYguideLines;i++){pBrd->m_IsLabeledTicY[i]=1;pBrd->m_YTics[i]=pBrd->m_dMinY+i*TickStepY;} 
}

void CRASView::Batch_FigPosition_Settings(int sizeOfOneRow, int sizeOfOneClmn, double scale) 
{
#define F2FY 5
#define F2FX 5
	int i,j;
	CFigure *pFig;

	for(i=0;i<m_dHowManyClmns;i++){
		for(j=0;j<m_dHowManyRows;j++){
			pFig=&m_Fig[j][i][0];
			pFig->m_normTx=scale*((i+1)*F2FX+    i*(sizeOfOneClmn-F2FX));  pFig->m_normTy=scale*((j+1)*F2FY+    j*(sizeOfOneRow-F2FY)+m_topOfFigs);   
			pFig->m_normBx=scale*((i+1)*F2FX+(i+1)*(sizeOfOneClmn-F2FX));  pFig->m_normBy=scale*((j+1)*F2FY+(j+1)*(sizeOfOneRow-F2FY)+m_topOfFigs); 
			pFig-> m_LateralMargin=20;
			pFig->SetFig_Position_in_ClientView(pFig->m_normTx,pFig->m_normTy,pFig->m_normBx,pFig->m_normBy);

			pFig->m_BlownUpTx=200; pFig->m_BlownUpTy=5; pFig->m_BlownUpBx=820; pFig->m_BlownUpBy=605; pFig->m_LateralMargin=20;
		}	
	}
}
void CRASView::Batch_SetFontSize(CDC* pDC) 
{
	int i,j;
	CFigure *pFig;

	for(i=0;i<m_dHowManyClmns;i++){
		for(j=0;j<m_dHowManyRows;j++){
			pFig=&m_Fig[j][i][0];
			pFig->SetFontSize(pDC);
		}	
	}
}
void CRASView::Batch_Prepare4FigFrame() 
{
	int i,j;
	CFigure *pFig;

	for(i=0;i<m_dHowManyClmns;i++){
		for(j=0;j<m_dHowManyRows;j++){
			pFig=&m_Fig[j][i][0];
			pFig->Prepare4FigFrame();
		}	
	}
}

void CRASView::Batch_DrawFigureFrames(int isToUnveil) 
{	
	CClientDC objDC(this);
	m_DC[0].Rectangle(0,0,m_nScrMaxX,m_nScrMaxY); 
	m_DoNotErase=1;//This is to inform the Labeling part not to erase previous site, which may not correspond to new position due to resize.
	int i,j;
	CFigure *pFig;
	for(i=0;i<m_dHowManyClmns;i++){
		for(j=0;j<m_dHowManyRows;j++){
			pFig=&m_Fig[j][i][0];
			if(pFig->m_Deleted==0)pFig->Frame_Graph2D(&m_DC[0],1, !m_Stop_Or_Pause); 
		}
	}
	m_DC[0].SetBkColor(RGB(220, 220, 220));
	m_DC[0].TextOut( m_TitleArea.left+5,m_TitleArea.top+5, m_JustFileName);
	if(isToUnveil)objDC.BitBlt(0,0,m_nScrMaxX,m_nScrMaxY,&m_DC[0],0,0,SRCCOPY);
	m_DC[0].SetBkColor(RGB(255, 255, 255));
}


// Writes a string sText with a size which fits perfectly in a rectangle rFont
// Font already attached with device context pDC is scaled
// This does not work for default font of the device contex
void CRASView::FontInRect(CDC *pDC, CString sText, CRect &rFont)
{
	// Gets current font details
	CFont* pFont = pDC->GetCurrentFont();
	LOGFONT LogFont;
	pFont->GetLogFont(&LogFont);

	// Scales the font to fit in the rectangle
	int a=pDC->GetDeviceCaps(LOGPIXELSY);
	LogFont.lfHeight = -72 * rFont.Height() / pDC->GetDeviceCaps(LOGPIXELSY);
	LogFont.lfWidth = -72 * rFont.Width() / pDC->GetDeviceCaps(LOGPIXELSX) / sText.GetLength();

	// Create a font of calculated size
	CFont Font;
	Font.CreateFontIndirect(&LogFont);

	// Rechecks the string width and height
	pFont = pDC->SelectObject(&Font);
	CSize Size = pDC->GetTextExtent(sText);
	pDC->SelectObject(pFont);
	Font.DeleteObject();

	// Fine tunes the font width and height
	LogFont.lfWidth = (int) (LogFont.lfWidth * rFont.Width() / Size.cx);
	LogFont.lfHeight = (int) (LogFont.lfHeight * rFont.Height() / Size.cy);

	// Create a font with accurate size and displays string
	Font.CreateFontIndirect(&LogFont);
	pFont = pDC->SelectObject(&Font);
	pDC->DrawText(sText, rFont, DT_SINGLELINE | DT_CENTER | DT_VCENTER);
	pDC->SelectObject(pFont);
	Font.DeleteObject();
}

void CRASView::OnChangeParameters() 
{
	CDialogueBox	ParameterBOX;

	ParameterBOX.m_dVariable1=m_dMaximumX;
	ParameterBOX.m_dVariable2=m_dMinimumX;
	ParameterBOX.m_dVariable3=m_dMaximumY;
	ParameterBOX.m_dMinimumY=m_dMinimumY;
	if(ParameterBOX.DoModal()==IDOK){
		if(ParameterBOX.m_dVariable1<=ParameterBOX.m_dVariable2||ParameterBOX.m_dVariable3<=ParameterBOX.m_dMinimumY){AfxMessageBox("m_dMaximumX<=m_dMinimumX OR m_dMaximumY<=m_dMinimumY ==> Try again", MB_OK); return;}
		else{
			m_dMaximumX=ParameterBOX.m_dVariable1;
			m_dMinimumX=ParameterBOX.m_dVariable2;
			m_dMaximumY=ParameterBOX.m_dVariable3;
			m_dMinimumY=ParameterBOX.m_dMinimumY;
		}
	}
}

void CRASView::OnIsToDisplayMarks()
{
	m_IsToDisplayMarks=!m_IsToDisplayMarks;
	int clm, row;
	for(clm=0;clm<m_dHowManyClmns;clm++){
		for(row=0;row<m_dHowManyRows;row++){
			m_Fig[row][clm][0].m_isToShowMarks=m_IsToDisplayMarks;
		}
	}	
	if(m_isDisplayerRunning==1)RequestDisplayEvent(REDRAW_ALL_CONTENT);
	else 		RedrawAllContent(); //Since the display loop is not running.
}

void CRASView::OnUpdateIsToDisplayMarks(CCmdUI *pCmdUI)
{
	pCmdUI->SetCheck(m_IsToDisplayMarks==1);
}


//This routine extracts numbers from a string. 
//It registers only the last one (number e.g. -123 from 76DR-123.txt).
int CRASView::Find_Last_Num_inString(char *GivenString, int &NumToReturn)
{
	char *p = NULL;
	char *q = NULL;
	int iCount=-1,foundNum;
	int num = 0, sign=0;
	char *szString;

	foundNum=0;
	szString=GivenString;
	p=szString;
	while(*p){
		if(*p>='0' && *p<='9'){
			num=0;//This one is here to make sure that the only the last group of digits are captured (e.g. 123 from 76DR123.txt).
			q=p;
			while(*q>='0' && *q<='9'){
				++iCount ;
				++q ;
			}
			q=p;
			while(*q>='0' && *q<='9'){
				num = num + (*q-48) * pow((double)10,(double)iCount);
				--iCount;
				++q ;
				++p;
			}
			foundNum = 1 ;
		}
		else{
			if(*p=='-')sign=1; else sign=0;
			++p ;
		}
	}		
	if(foundNum==0 || num<0){
		//char strbuf[1000];
		//_snprintf(strbuf, 999, "The name does not contain a number", GivenString);
		//AfxMessageBox(strbuf);
		return -1;
	}
	if(sign==1) NumToReturn= -num;
	else		NumToReturn=  num;
	return 0;
}

//At the moment the RAS to TAS communication has been disabled
//float CRASView::Msg_from_RAS_to_TAS(char *MsgString) 
//{
//	strcpy(M_MsgFromRAStoTAS, MsgString);   
//	*M_isNewMsgFromRAStoTAS=1;
//	for(int i=0; i<10; i++){
//		if(*M_isNewMsgFromRAStoTAS==0){
//			return *M_MsgFromTAStoRAS;
//		}
//		Sleep(10);
//	}
//	return 0.5;//Since this is not an integer, it indicates that the RAS's request to TAS to let it know the corresponding ECode of the alias has failed.
//}


void CRASView::Show2D_VIII() 
{
}


void CRASView::OnViewSDF()
{
	m_toShowSDF=!m_toShowSDF;
	RedrawAllContent();
}


void CRASView::OnUpdateViewSDF(CCmdUI *pCmdUI)
{
	pCmdUI->SetCheck(m_toShowSDF==1);
}


void CRASView::OnViewRaster()
{
	m_toShowRaster=!m_toShowRaster;
	RedrawAllContent();
}


void CRASView::OnUpdateViewRaster(CCmdUI *pCmdUI)
{
	pCmdUI->SetCheck(m_toShowRaster==1);
}


void CRASView::OnSigma()
{
	int row, clm;
	for(clm=0;clm<m_dHowManyClmns;clm++){
		for(row=0;row<m_dHowManyRows;row++){
			if(m_Fig[row][clm][0].m_dSigma==0.25)m_Fig[row][clm][0].m_dSigma=MAX_SIGMA;//Due to the array size defining process (size=pFig->m_dMaxX-pFig->m_dMinX+4*pFig->m_dSigma;) m_dSigma less than 0.25 will generate an error.
			else if(m_Fig[row][clm][0].m_dSigma<3)m_Fig[row][clm][0].m_dSigma=0.25;//Due to the array size defining process (size=pFig->m_dMaxX-pFig->m_dMinX+4*pFig->m_dSigma;) m_dSigma less than 0.25 will generate an error.
			else m_Fig[row][clm][0].m_dSigma-=2;
		}
	}
	Compute_Display_NeuralActivity();
}


void CRASView::Compute_Display_NeuralActivity()
{
	CFigure *pFig;
	int row, clm, size;
	
	//Initialize Figures
	for(clm=0;clm<m_dHowManyClmns;clm++){
		for(row=0;row<m_dHowManyRows;row++){
			pFig=&m_Fig[row][clm][0];
			if(pFig->m_Deleted==1)continue;
			pFig->m_dMinXMinus2Sigma=pFig->m_dMinX-MAX_SIGMA_x2; pFig->m_dMaxXPlus2Sigma=pFig->m_dMaxX+MAX_SIGMA_x2;
			size=pFig->m_dMaxX-pFig->m_dMinX+2*MAX_SIGMA_x2;
			pFig->m_HistOfSpikes.SetSize(size);
			pFig->m_SDF.SetSize(size);
			pFig->m_HistArraySize=size;
		}
	}

	for(clm=0;clm<m_dHowManyClmns;clm++){
		for(row=0;row<m_dHowManyRows;row++){
			pFig=&m_Fig[row][clm][0]; 
			if(pFig->m_Deleted==1)continue;
			pFig->Make_SDF_from_Histogram();
		}
	}
	//#########################   Dispaly   ##############################
	//Because this function pauses the main loop (m_Stop_Or_Pause==1) "RequestDisplayEvent(REDRAW_ALL_CONTENT)" will not work.
	RedrawAllContent();
}