

// Kiran Srinivas Bhat, The Robotics Institute, CMU

//*********************************************************************************//
// bitmapDlg.cpp : implementation file
//
// This program is a part of a project that implements image mosaicing 
// using feature points tracked by a feature tracker.
// This program implements:
//			- an user interface for handling images using MFC
//			- calles functions from the feature tracker to track features in real time
//			- computes an affine transformation between image pairs using data from 
//																	the feature tracker
//			- warps images togather and displays it
//			- additional functions for background subtraction.
//*********************************************************************************//


#include "stdafx.h"
#include "math.h"
#include "pnmio.h"
#include "klt.h"
#include "pyramid.h"
#include "bitmap.h"
#include "bitmapDlg.h"
#include "assert.h"
#include <windows.h>
#include  <fstream.h>
#include  <iostream.h>
#include "ios.h"
#include "VideoPro.h"
#include "Servo.h"
//#include "Matrix.h"
//#include "Matrix2.h"

#define ind(x,y,l) (l*y+x);
#define pi 3.1417
//#define Col 320
//#define Row 240
//int Col=310;
//int Row=220;
int Col=300;
int Row=200;
int Global_B=Col*3;
int update_number=12;
int global_update_counter=0;
//int Col=300;
//int Row=190;

float d_x=0;
float d_y=0;
int shift_x=0;
int shift_y=0;
int m_mosaic_count=0;
float store_dx[300];
float store_reverse_dx[300];
bool track_status[300];
bool show_emos=true;
bool track=false;
bool dont_track=true;
int start_panAngle = 45;
int total_feature;
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CAboutDlg dialog used for App About

class CAboutDlg : public CDialog
{
public:
	CAboutDlg();


// Dialog Data
	//{{AFX_DATA(CAboutDlg)
	enum { IDD = IDD_ABOUTBOX };
	//}}AFX_DATA

	// ClassWizard generated virtual function overrides
	//{{AFX_VIRTUAL(CAboutDlg)
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	//}}AFX_VIRTUAL

// Implementation
protected:
	//{{AFX_MSG(CAboutDlg)
	afx_msg void OnTimer(UINT nIDEvent);
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)
{
	//{{AFX_DATA_INIT(CAboutDlg)
	//}}AFX_DATA_INIT
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CAboutDlg)
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)
	//{{AFX_MSG_MAP(CAboutDlg)
	ON_WM_TIMER()
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CBitmapDlg dialog

CBitmapDlg::CBitmapDlg(CWnd* pParent /*=NULL*/)
	: CDialog(CBitmapDlg::IDD, pParent)
{

	//{{AFX_DATA_INIT(CBitmapDlg)
	m_max_features = 0;
	m_update_features = 0;
	m_all = FALSE;
	m_mosaic = 0;
	m_thresh=0;
	//}}AFX_DATA_INIT
	// Note that LoadIcon does not require a subsequent DestroyIcon in Win32
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CBitmapDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialog::DoDataExchange(pDX);
	//{{AFX_DATA_MAP(CBitmapDlg)
	DDX_Text(pDX, IDC_FEATURES, m_max_features);
	DDV_MinMaxInt(pDX, m_max_features, 0, 1000);
	DDX_Text(pDX, IDC_UPDATE_FEATURE, m_update_features);
	DDV_MinMaxInt(pDX, m_update_features, 0, 100);
	DDX_Text(pDX, IDC_MOSAIC, m_mosaic);
	DDV_MinMaxInt(pDX, m_mosaic, 0, 500);
	DDX_Text(pDX, IDC_THRESHOLD, m_thresh);
	DDV_MinMaxInt(pDX, m_thresh, 0, 100);

	DDX_Check(pDX, IDC_All, m_all);
	
	//}}AFX_DATA_MAP
}

BEGIN_MESSAGE_MAP(CBitmapDlg, CDialog)
	//{{AFX_MSG_MAP(CBitmapDlg)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_WM_MOUSEMOVE()
	ON_WM_LBUTTONDOWN()
	ON_WM_RBUTTONDOWN()
	ON_WM_TIMER()
	ON_BN_CLICKED(IDC_NEXT_IMAGE, OnNextImage)
	ON_BN_CLICKED(IDC_START_FEATURE, OnStartFeature)
	ON_BN_CLICKED(IDC_RESET, OnReset)
	ON_WM_CLOSE()
	ON_BN_CLICKED(IDC_stream1, Onstream1)
	ON_BN_CLICKED(IDC_stream2, Onstream2)
	ON_BN_CLICKED(IDC_stream3, Onstream3)
	ON_EN_UPDATE(IDC_FEATURES, OnUpdateFeatures)
	ON_BN_CLICKED(IDC_RADIO1, OnRadio1)
	ON_BN_CLICKED(IDC_RADIO2, OnRadio2)
	ON_BN_CLICKED(IDC_STOP, OnStop)
	ON_EN_CHANGE(IDC_UPDATE_FEATURES, OnChangeUpdateFeatures)
	ON_BN_CLICKED(IDC_AUTOTRACKER, OnAutotracker)
	ON_BN_CLICKED(IDC_stream4, Onstream4)
	ON_BN_CLICKED(IDC_stream5, Onstream5)
	ON_BN_CLICKED(IDC_PAUSE, OnPause)
	ON_BN_CLICKED(IDC_GRABBER, OnGrabber)
	ON_BN_CLICKED(IDC_CLOSECAMERA, OnClosecamera)
	ON_BN_CLICKED(IDC_BUTTON1, OnButton1)
	ON_BN_CLICKED(IDC_All, OnAll)
	ON_BN_CLICKED(IDC_INITIAL_FEATURE, OnInitialFeature)
	ON_BN_CLICKED(IDC_FRAME_NUM, OnFrameNum)
	ON_BN_CLICKED(IDC_Bx, OnBx)
	ON_EN_CHANGE(IDC_MOSAIC, OnChangeMosaic)
	ON_BN_CLICKED(IDC_MOS_BUTTON, OnMosButton)
	ON_EN_CHANGE(IDC_FEATURES2, OnChangeFeature)
	ON_EN_CHANGE(IDC_UPDATE_FEATURE, OnChangeUpdateFeature)
	ON_BN_CLICKED(IDC_shift, Onshift)
	ON_BN_CLICKED(IDC_STOP_ALL, OnStopAll)
	ON_EN_CHANGE(IDC_THRESHOLD, OnChangeThreshold)
	ON_BN_CLICKED(IDC_MOS_BUTTON2, OnPanLeft)
	ON_BN_CLICKED(IDC_MOS_BUTTON3, OnPanRight)
	ON_BN_CLICKED(IDC_ERR_MOSAIC, OnErrMosaic)
	ON_BN_CLICKED(IDC_MOS_BUTTON4, OnMosButton4)
	ON_BN_CLICKED(IDC_IMos, OnIMos)
	ON_BN_CLICKED(IDC_EMos, OnEMos)
	ON_BN_CLICKED(IDC_TRACK_ON, OnTrackOn)
	ON_BN_CLICKED(IDC_TRACK_OFF, OnTrackOff)
	ON_BN_CLICKED(IDC_MOSAIC_INC, OnMosaicInc)
	ON_BN_CLICKED(IDC_MOSAIC_DEC, OnMosaicDec)
	ON_BN_CLICKED(IDC_RADIO3, OnRadio3)
	ON_BN_CLICKED(IDC_RADIO4, OnRadio4)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CBitmapDlg message handlers

BOOL CBitmapDlg::OnInitDialog()
{
	CDialog::OnInitDialog();
	offset_x=35;
	offset_y=40;
	// Add "About..." menu item to system menu.

	// IDM_ABOUTBOX must be in the system command range.
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);
    loaded=false;
	
 //   AfxInitRichEdit();
	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		CString strAboutMenu;
		strAboutMenu.LoadString(IDS_ABOUTBOX);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon
	
	// TODO: Add extra initialization here

	//dcmem.CreateCompatibleDC(GetDC());

	mydc=GetDC();
	//hbitmap=(HBITMAP)::LoadImage(AfxGetInstanceHandle(),"e:\\kiran\\klt\\try\\std1.bmp",IMAGE_BITMAP,0,0,LR_LOADFROMFILE | LR_CREATEDIBSECTION);
	hbitmap=(HBITMAP)::LoadImage(AfxGetInstanceHandle(),"e:\\kiran\\klt\\try\\cam5.bmp",IMAGE_BITMAP,0,0,LR_LOADFROMFILE | LR_CREATEDIBSECTION);
	//hbitmap_mos=(HBITMAP)::LoadImage(AfxGetInstanceHandle(),"e:\\kiran\\klt\\try\\std_mosaic1.bmp",IMAGE_BITMAP,0,0,LR_LOADFROMFILE | LR_CREATEDIBSECTION);
	hbitmap_mos=(HBITMAP)::LoadImage(AfxGetInstanceHandle(),"e:\\kiran\\klt\\try\\cam_new_mosaic.bmp",IMAGE_BITMAP,0,0,LR_LOADFROMFILE | LR_CREATEDIBSECTION);
	bitmap.Attach(hbitmap);	
	base_bitmap.Attach(hbitmap);  //****
	tracked_bitmap.Attach(hbitmap);//****
	mosaic_bitmap.Attach(hbitmap_mos);
	dcmem.CreateCompatibleDC(mydc);
	
	//dcmem.SelectObject(&bitmap);
    //BITMAP bm;
	//GetObject(hbitmap,sizeof(BITMAP),&bm);  
	//mydc->BitBlt(offset_x,offset_y,bm.bmWidth,bm.bmHeight,&dcmem,0,0,SRCCOPY);
	//mydc->BitBlt(offset_x,offset_y,320,240,&dcmem,0,0,SRCCOPY);
	SetTimer(ID_CLOCK_TIMER,100,NULL);
	filenum=0;
	i=0;
	
	nFrames = 600;
	img2=NULL;
	img1=NULL;
	img3=NULL;
	img4=NULL;
	img_mosaic=NULL;
	err_mosaic=NULL;
	delta_err_mosaic=NULL;
	my_frame=0;
	m_max_features=100;
	m_mosaic=10;
	m_thresh=0;
	nFeatures=m_max_features;
	m_update_features=10;
	automate=false;
	start_automation=false;
	mosaic_shift=false;
	auto_frames=0;
	f_x=0;
	f_y=0;
	
	//Initialising the frame by frame transfomation matrix
	for(int a=0;a<300;a++)
	{
		matrx[a][0]= 1.0;
		matrx[a][1]= 0.0;
		matrx[a][2]= 0.0;
		matrx[a][3]= 0.0;
		matrx[a][4]= 1.0;
		matrx[a][5]= 0.0;
	}

	//Initialising the peridic (every 15 frames) transformation matrix
	for(a=0;a<25;a++)
	{
		PMatrix[a][0]= 1.0;
		PMatrix[a][1]= 0.0;
		PMatrix[a][2]= 0.0;
		PMatrix[a][3]= 0.0;
		PMatrix[a][4]= 1.0;
		PMatrix[a][5]= 0.0;
	}	
	
	//Used in Feedback loop
	king[0]= 1.0;
	king[1]= 0.0;
	king[2]= 0.0;
	king[3]= 0.0;
	king[4]= 1.0;
	king[5]= 0.0;

	pause=false;
	GetDlgItem(IDC_AUTOTRACKER)->EnableWindow(FALSE);
	GetDlgItem(IDC_PAUSE)->EnableWindow(FALSE);
	total_frames=0;
	//img2=new unsigned char[Col*Row];    

    reset=false;
	MyCam=new CVideoPro();
	realtime=false;
    

	//Create the pan tilt class
	panTilt = new CServo(1);
	//panAngle = 0; tiltAngle = 0;

	OnHome();	
	for(int st=0;st<300;st++)
	{
		store_dx[st]=0;
		store_reverse_dx[st]=0;
		track_status[st]=1;
	}
	
	UpdateData(FALSE);
		

	return TRUE;  // return TRUE  unless you set the focus to a control
}

void CBitmapDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialog::OnSysCommand(nID, lParam);
	}
}

// If you add a minimize button to your dialog, you will need the code below
//  to draw the icon.  For MFC applications using the document/view model,
//  this is automatically done for you by the framework.

void CBitmapDlg::OnPaint() 
{

	if (loaded==true)
		{
	    dcmem.SelectObject(&bitmap);
		
//		mydc->BitBlt(0,0,640,480,&dcmem,0,0,SRCCOPY);
//		mydc->StretchBlt(10,10,400,400,&dcmem,0,0,1000,760,SRCCOPY);


		BITMAP bm;
	GetObject(hbitmap,sizeof(BITMAP),&bm);
   
	//mydc->StretchBlt(10,10,400,400,&dcmem,0,0,1000,760,SRCCOPY);
	mydc->BitBlt(offset_x,offset_y,bm.bmWidth,bm.bmHeight,&dcmem,0,0,SRCCOPY);
		copy_base_image();
	copy_tracked_image();


		}
		
	if (IsIconic())
	{
		CPaintDC dc(this); // device context for painting

		//SendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);

		// Center icon in client rectangle
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// Draw the icon
		dc.DrawIcon(x, y, m_hIcon);
   	    
		
	//dc->StretchBlt(10,10,400,400,&dcmem,0,0,640,480,SRCCOPY);

	}
	else
	{
		CDialog::OnPaint();
	}
}

// The system calls this to obtain the cursor to display while the user drags
//  the minimized window.
HCURSOR CBitmapDlg::OnQueryDragIcon()
{
	return (HCURSOR) m_hIcon;
}




void CBitmapDlg::OnMouseMove(UINT nFlags, CPoint point) 
{
	// TODO: Add your message handler code here and/or call default
	CString t="Hello";
	//SetDlgItemText(IDC_CX,(LPVOID )t.Format("%d , %d ",point.x,point.y));
	t.Format("%d , %d",point.x,point.y);
	//SetDlgItemText(IDC_CX,t);
	
	CDialog::OnMouseMove(nFlags, point);
}


void CBitmapDlg::OnLButtonDown(UINT nFlags, CPoint point) 
{
	// TODO: Add your message handler code here and/or call default
	//CPen apen;
	//apen.CreatePen(PS_SOLID,2,RGB(250,250,50));
	//CPen *pen=mydc->SelectObject(&apen);
    mydc->SetPixel(point.x,point.y,RGB(250,250,50));
	//mydc->SelectObject(pen);
	
	
	CDialog::OnLButtonDown(nFlags, point);
}

void CBitmapDlg::OnRButtonDown(UINT nFlags, CPoint point) 
{
	// TODO: Add your message handler code here and/or call default
	
	CDialog::OnRButtonDown(nFlags, point);
}

void CAboutDlg::OnTimer(UINT nIDEvent) 
{
	
	

	
	CDialog::OnTimer(nIDEvent);
}

void CBitmapDlg::OnTimer(UINT nIDEvent) 
{

	if (start_automation==true)
		Automate();

	//if(track==true) track_moving_object();
	
	CDialog::OnTimer(nIDEvent);
}

void CBitmapDlg::OnNextImage() 
{
	// TODO: Add your control notification handler code here  	        
		
	
	float m_x=0;float m_y=0;
	float mm_x=0;
	float mm_y=0;
	float max_x=0;
	float min_y=0;
	int cnt=0;
	float Bx=0; float By=0;
	

	i=i+1;
	global_update_counter++;
	if (i<=total_frames-1 || realtime == true)
	{
		my_frame++;
		if (my_frame==2) GetDlgItem(IDC_STOP)->EnableWindow(TRUE);
	
    	sprintf(fnamein,"%s%s%d%s",directory,"mg",i,".pgm");
    
		img2=new unsigned char[Col*Row];	
		img_morph=new unsigned char[Col*Row];	

		for(int hh=0;hh<Col*Row;hh++) 
		{
			img_morph[hh]=0;
		}

		if(panAngle >= -85)
		{
			panAngle--;
			panTilt->SetPositionAbs(panAngle, TILT);

		}
		
		for(int tm=0;tm<5000;tm++)
			for(int tj=0;tj<5000;tj++);

		if (realtime==true)
			GrabImage(img2, Col*Row);
	   	else	 
			pgmReadFile(fnamein, img2, &Col, &Row);
	
		if((i%28==0) && realtime ==true)
		{
			GrabImage(img1, Col*Row);
			//f_x=d_x;
			f_x=matrx[i-1][2];
			f_y=0;
		}

		int tmp_total=0;
		for (int j = 0 ; j < fl->nFeatures ; j++)
		{
		 	fl_x[j]=fl->feature[j]->x;
			fl_y[j]=fl->feature[j]->y;
			tmp_total++;
		}

			

		KLTTrackFeatures(tc, img1, img2, Col, Row, fl);
		KLTStoreFeatureList(fl, ft, i);


		char feat_img[50];
		sprintf(feat_img,"%s%s%d%s","e:\\kiran\\klt\\Tracking_affine\\","feat_image",i,".ppm");
		
		KLTWriteFeatureListToPPM(fl, img2, Col, Row, feat_img);

		SetDlgItemInt(IDC_FRAME_NUM,i);
		bitmap.SetBitmapBits(Col*Row,img2);		
		dcmem.SelectObject(&bitmap);
		BITMAP bm;
		GetObject(hbitmap,sizeof(BITMAP),&bm);
		mydc->BitBlt(offset_x,offset_y,bm.bmWidth,bm.bmHeight,&dcmem,0,0,SRCCOPY);

		bitmap.SetBitmapBits(Col*Row,img1);		
		dcmem.SelectObject(&bitmap);
		mydc->BitBlt(offset_x+600,offset_y,bm.bmWidth,bm.bmHeight,&dcmem,0,0,SRCCOPY);

		total_feature=0;
	
		for ( j = 0 ; j < fl->nFeatures ; j++)
		{
			if (fl->feature[j]->val==0)
			{
				total_feature++;
				CPoint p;
				p.x=fl->feature[j]->x+offset_x;
				p.y=fl->feature[j]->y+offset_y;

				CPen solidpen(PS_SOLID,3,RGB(250,250,50));
				CPen *oldpen;
				oldpen=mydc->SelectObject(&solidpen);
				mydc->MoveTo(p);
				mydc->LineTo(p);
				mydc->SelectObject(oldpen);
				
			}
			else track_status[j]=0;
		}

		SetDlgItemInt(IDC_TOTAL_FEATURE,total_feature);
					
		char buffer[50];
		sprintf(buffer,"Frame %d",i);
		SetDlgItemText(IDC_TRACKED,buffer);
		
		fstream fpt;
		fpt.open("e:\\kiran\\klt\\try\\transf.out",ios::out|ios::app);
	
		Y = new float[total_feature];
		Z = new float[total_feature];
		X1 = new float[total_feature];
		X2 = new float[total_feature];
		Res = new float[6];
		

		for (j = 0 ; j < (fl->nFeatures) ; j++)
		{
			if (fl->feature[j]->val==0)
			{
				
				X1[cnt]= fl_x[j];
				X2[cnt] = fl_y[j];
				
				Y[cnt] = fl->feature[j]->x;
				Z[cnt] = fl->feature[j]->y;
				fpt<<j<<"\t"<<fl_x[j]<<"\t"<<fl->feature[j]->x<<"\t"<<"\t"<<fl_y[j]<<"\t"<<fl->feature[j]->y<<endl;
				
				//fpt<<cnt<<"\t"<<X1[cnt]<<"\t"<<Y[cnt]<<endl;
				m_x= fl_x[j] - fl->feature[j]->x;
				m_y= fl_y[j] - fl->feature[j]->y;

				if(fabs(m_x)>fabs(max_x))max_x=m_x;
				if(fabs(m_y)<fabs(min_y))min_y=m_y;
		
				mm_x+=m_x;
				mm_y+=m_y;
				cnt++;
			}
		} 
		fpt.close();
		
		float average_distance =0;

		if(cnt>0) average_distance = mm_x/cnt;
		
		Matrix A(total_feature,3);
		Matrix A_inter(3,3);
		ColVector b1(total_feature);
		ColVector b2(total_feature);
		ColVector x_1(3);
		ColVector x_2(3);
		
		for( int ja=0;ja<total_feature;ja++)
		{
			A[ja][0]=(double) Y[ja];
			A[ja][1]=(double) Z[ja];
			A[ja][2]= 1;
		}
		
		
		for(ja=0;ja<total_feature;ja++)
		{
			b1[ja]=(double) X1[ja];
			b2[ja]=(double) X2[ja];
		}

		A.solveBySVD(b1,x_1);
		A.solveBySVD(b2,x_2);
		
		fstream fptA1;
		fptA1.open("e:\\kiran\\klt\\Tracking_affine\\A1.out",ios::out|ios::app);
		fptA1<<i<<"  "<< total_feature<<endl;
		fptA1 << x_1 <<"  "<< x_2 <<endl;
		fptA1.close();
		
		for(int a=0;a<3;a++)
			Res[a]=x_1[a];
		for(a=3;a<6;a++)
			Res[a]=x_2[a-3];

		/*
		if(total_feature>40)
		{
			//gradient_descent(total_feature,Y,Z,X1,X2,Res);
			gradient_descent(total_feature,X1,X2,Y,Z,Res); //Computes the transformation of the current frame w.r.t mosaic
														   // i.e, finds the coordinates in the mosaic which correspond 
														   // to the coordinates of the current image (mosaic coord is output- x',y')	
		}
		else 
		{
			fstream frej;
			frej.open("e:\\kiran\\klt\\try\\reject.out",ios::out|ios::app);
			//Res[0]=matrx[i-1][0];
			//Res[1]=matrx[i-1][1];
			Res[2]=average_distance;
			//Res[3]=matrx[i-1][3];
			//Res[4]=matrx[i-1][4];
			
			Res[0]=1.0;
			Res[1]=0;
			Res[3]=0;
			Res[4]=1.0;
			Res[5]=0;
			SetDlgItemInt(IDC_min,4444444);
			frej<<i<<"\t"<<Res[0]<<"\t"<<Res[1]<<"\t"<<Res[2]<<"\t"<<Res[3]<<"\t"<<Res[4]<<"\t"<<Res[5]<<endl;
			frej.close();

		}
		*/
		/*
		if(global_update_counter==update_number-1)
		{
			fstream f1;
			f1.open("e:\\kiran\\klt\\try\\global.out",ios::out|ios::app);
			Res_global = new float[6];
			cnt=0;
			for (j = 0 ; j < (fl->nFeatures) ; j++)
				if (fl->feature[j]->val==0)
					if(track_status[j]==1)
					{
						X1[cnt]= fl_global_x[j];
						X2[cnt]= fl_global_y[j];
						Y[cnt] = fl->feature[j]->x;
						Z[cnt] = fl->feature[j]->y;
						//f1<<j<<"\t"<<X1[cnt]<<"\t"<<"\t"<<Y[cnt]<<endl; 
						//fpt<<j<<"\t"<<fl_x[j]<<"\t"<<fl->feature[j]->x<<"\t"<<"\t"<<fl_y[j]<<"\t"<<fl->feature[j]->y<<endl;
						cnt++;
					}
			gradient_descent(cnt,X1,X2,Y,Z,Res_global);	
			f1<<"Count is"<<"\t"<<cnt<<"  Total_feature is"<<"\t"<<total_feature<<endl;
			f1<<i<<"\t"<<Res_global[0]<<"\t"<<Res_global[1]<<"\t"<<Res_global[2]<<"\t"<<Res_global[3]<<"\t"<<Res_global[4]<<"\t"<<Res_global[5]<<endl;
			f1.close();
			//update_Matrix(i,Res_global);
			global_update_counter=1;
			delete []Res_global;
		} 
		
		fstream f2;
		f2.open("e:\\kiran\\klt\\try\\global.out",ios::out|ios::app);
		//f2<<"Total_feature is"<<"\t"<<total_feature<<endl;
		f2.close();
		*/
		
		fstream fptres;
		fptres.open("e:\\kiran\\klt\\Tracking_affine\\res.out",ios::out|ios::app);
		fptres<<i<<"\t"<<Res[0]<<"\t"<<Res[1]<<"\t"<<Res[2]<<"\t"<<Res[3]<<"\t"<<Res[4]<<"\t"<<Res[5]<<"\t"<<endl;
		fptres.close();

		fstream fptr1;
		fptr1.open("e:\\kiran\\klt\\Tracking_affine\\matrix.out",ios::out|ios::app);
	
		//if(global_update_counter<update_number-1)
		update_Matrix(i,Res);
		
		fptr1.width(12);
		fptr1<<i<<"\t"<<matrx[i][0]<<"\t"<<matrx[i][1]<<"\t"<<matrx[i][2]<<"\t"<<matrx[i][3]<<"\t"<<matrx[i][4]<<"\t"<<matrx[i][5]<<"\t"<<endl;
		//fptr1<<i<<"\t"<<matrx[i][2]<<"\t"<<matrx[i][5]<<"\t"<<endl;
		fptr1.close();
	
		/*
		if(i%45==0)
		{
			//update_periodic_Matrix(i,m_update_features);
			update_periodic_Matrix(i,45);
			matrx[i][0]=1;
			matrx[i][1]=0;
			matrx[i][2]=450;
			matrx[i][3]=0;
			matrx[i][4]=1;
			matrx[i][5]=0;
			float warp_data[6];
			for(int ka=0;ka<6;ka++) warp_data[ka]=matrx[i][ka];
			fill_mosaic_warped(Col*3,Row,Col,Row,warp_data,img2);
		}
		*/	

		


		if((mm_x/cnt)<1.0)
		{
			mm_x=0;
			mm_y=0;
		}

		d_x+=sqrt(((mm_x*mm_x)/(cnt*cnt))+((mm_y*mm_y)/(cnt*cnt)));
		d_y+= sqrt(((mm_x*mm_x)/(cnt*cnt))+((mm_y*mm_y)/(cnt*cnt)));


		// This fill mosaic was changed......
		//fill_mosaic(Col*3,Row,Col,Row,ceil(d_x),0,img2);
		//fprintf(stream, "%f\n",ceil(d_x));

	
		//Feedback loop
	
				
		if((i)%20==0)
		{
			/*
			king[0]=0.9766;
			king[1]=-0.0193;
			king[3]=-0.0066;
			king[4]=0.9976;
			*/
			
			//king[0] = PMatrix[int((i)/20)][0];
			//king[1] = PMatrix[int((i)/20)][1];
			//king[3] = PMatrix[int((i)/20)][3];
			//king[4] = PMatrix[int((i)/20)][4];
			
			//king[4] = PMatrix[int((i-1)/20)][4];
			fstream file;
			file.open("e:\\kiran\\klt\\try\\king.out",ios::out|ios::app);
			//file<<i<<"\t"<<king[0]<<"\t"<<king[1]<<"\t"<<king[3]<<"\t"<<king[4]<<endl;	
			file.close();

		}

		if(i%13 == 0)
		{
	
			float warp_data[6];
			for(int ka=0;ka<6;ka++) warp_data[ka]=matrx[i][ka];
			/*warp_data[5]=0;
			warp_data[0]= 1.0*king[0];
			warp_data[1]= king[1];
			warp_data[3]= king[3];
			warp_data[4]= 1.0*king[4];
			*/
	
			fstream file1;
			file1.open("e:\\kiran\\klt\\Tracking_affine\\king.out",ios::out|ios::app);
			//file1<<i<<"\t"<<warp_data[0]<<"\t"<<warp_data[1]<<"\t"<<warp_data[2]<<"\t"<<warp_data[3]<<"\t"<<warp_data[4]<<"\t"<<warp_data[5]<<endl;	
			file1.close();

			fill_mosaic_warped(Col*3,Row,Col,Row,warp_data,img2);
			//fill_mosaic(Col*3,Row,Col,Row,warp_data[2],0,img2);

			
			char out_img[50];
			sprintf(out_img,"%s%s%d%s","e:\\kiran\\klt\\Tracking_affine\\","per_image",i,".txt");
		
			fstream fpimg1;
			fpimg1.open(out_img,ios::out);
			for(int t=0;t<Col*Row;t++)
				fpimg1<<(int)img2[t]<<endl;
			fpimg1.close();
			
			
			
			int minimum=10000000;

			float warp_data_init[6];
			
			warp_data_init[0]= 1.0;
			warp_data_init[1]= 0.0;
			warp_data_init[2]= f_x;
			warp_data_init[3]= 0.0;
			warp_data_init[4]= 1.0;
			warp_data_init[5]= f_y;

			unsigned char *feed_image= new unsigned char[Col*Row];
			index_mosaic_warped(Col*3, Row, Col, Row,warp_data_init,feed_image);
			//index_mosaic(Col*3, Row, Col, Row,f_x,f_y); //Indexes first image of the current mosaic and
													//stores it in img4
			//DifferenceImage(img1, img4, Col, Row);
			DifferenceImage(img1, feed_image, Col, Row);
			ThresholdDiffImage(0,Col,Row);
			int dif = CalcDiff(img3,Col,Row,1);
			int dif1=0;
			SetDlgItemInt(IDC_min,dif);
			int disp_x=1;
			float warp_trans=warp_data[2];

			/*
			while((dif<minimum))
			{
				minimum=dif;
				warp_data[2]=warp_trans+disp_x;
				fill_mosaic_warped(Col*3,Row,Col,Row,warp_data,img2);
				index_mosaic_warped(Col*3, Row, Col, Row,warp_data_init,feed_image);
				DifferenceImage(img1, feed_image, Col, Row);
				//fill_mosaic(Col*3,Row,Col,Row,ceil(d_x + (++disp_x)),0,img2);
				//index_mosaic(Col*3, Row, Col, Row,f_x,f_y);
				//DifferenceImage(img1, img4, Col, Row);
				ThresholdDiffImage(50,Col,Row);
				dif = CalcDiff(img3,Col,Row,2);						
				SetDlgItemInt(IDC_min,dif);
				//SetDlgItemInt(IDC_shift,dif);
				
				warp_data[2]=warp_trans+disp_x+1;
				fill_mosaic_warped(Col*3,Row,Col,Row,warp_data,img2);
				index_mosaic_warped(Col*3, Row, Col, Row,warp_data_init,feed_image);
				DifferenceImage(img1, feed_image, Col, Row);
				//fill_mosaic(Col*3,Row,Col,Row,ceil(d_x + (++disp_x)),0,img2);
				//index_mosaic(Col*3, Row, Col, Row,f_x,f_y);
				//DifferenceImage(img1, img4, Col, Row);
				ThresholdDiffImage(0,Col,Row);
				dif1 = CalcDiff(img3,Col,Row,2);
				disp_x++;
						
				if(dif1<dif) dif=dif1;
				
			}
	
			
			
			warp_data[2]=warp_trans+disp_x-1;
			fill_mosaic_warped(Col*3,Row,Col,Row,warp_data,img2);
			matrx[i][2]=warp_data[2];
			SetDlgItemInt(IDC_shift,disp_x-1);	
			store_dx[i-1]=warp_data[2];
			SetDlgItemInt(IDC_min,store_dx[i-1]);
			index_mosaic_warped(Col*3, Row, Col, Row,warp_data_init,feed_image);
			DifferenceImage(img1, feed_image, Col, Row);
			
			bitmap.SetBitmapBits(Col*Row,img3);		
			dcmem.SelectObject(&bitmap);
			mydc->BitBlt(offset_x+600,offset_y+225,bm.bmWidth,bm.bmHeight,&dcmem,0,0,SRCCOPY);
			*/

			delete []feed_image;
			//if(disp_x==1)		
			//	fill_mosaic(Col*3,Row,Col,Row,ceil(d_x + (disp_x -1)),0,img2);
			//else
			{
				//index_image(Col, Row, disp_x-1,0,img_morph,img2);
				//fill_mosaic(Col*3,Row,Col,Row,ceil(d_x + (disp_x -1)),0,img_morph);
				//SetDlgItemInt(IDC_shift,9999);
			}
	
		
			
			//fprintf(stream, "%f\t%d\n",ceil(sqrt(((mm_x*mm_x)/(cnt*cnt))+((mm_y*mm_y)/(cnt*cnt))) + (disp_x -1)),(disp_x -1));
			//fprintf(stream,"\n");
			//SetDlgItemInt(IDC_feedback,disp_x-1);
			d_x=d_x+(disp_x-1);
			SetDlgItemInt(IDC_feedback,d_x);
			//fprintf(stream, "%f\n",ceil(d_x));
	    
		}

		//store_dx[i-1]=d_x;
		//FILE *stream;
		//stream=fopen("e:\\kiran\\klt\\try\\data.out","a");	  
		//fprintf(stream, "%f\t %d\n",store_dx[i-1],i-1);	
		//fclose(stream);	
		
		unsigned char* temp_err_img = new unsigned char[Col*Row];
		for(int k=0;k<Col*Row;k++) temp_err_img[k]=0;
		
		//index_mosaic(Col*3, Row, Col, Row,ceil(d_x),0);
		//DifferenceImage(img2, img4, Col, Row);
		//fill_error_mosaic(Col*3,Row,Col,Row,ceil(d_x),0,img3);
		//fill_delta_error_mosaic(Col*3,Row,Col,Row,ceil(d_x),0,img3);
		
		//index_mosaic(Col*3, Row, Col, Row, 0,0);
		//DifferenceImage(img1, img4, Col, Row);
		//bitmap.SetBitmapBits(Col*Row,img3);		
		//dcmem.SelectObject(&bitmap);
		//GetObject(hbitmap,sizeof(BITMAP),&bm);
		//mydc->BitBlt(offset_x+600,offset_y,bm.bmWidth,bm.bmHeight,&dcmem,0,0,SRCCOPY);
	
	
		mosaic_bitmap.SetBitmapBits(Col*Row*3,img_mosaic); 
		dcmem.SelectObject(&mosaic_bitmap);
		BITMAP bm_mos;
		GetObject(hbitmap_mos,sizeof(BITMAP),&bm_mos);
		mydc->BitBlt(offset_x-30,offset_y+450,bm_mos.bmWidth,bm_mos.bmHeight,&dcmem,0,0,SRCCOPY);
	
		//if(i%5==0)
		//calc_warp_params(store_dx[i-1], (pi/180)*(i-1));
  

		delete []img2;
		delete []img_morph;  	
		delete []temp_err_img;
		delete []X1;
		delete []X2;
		delete []Y;
		delete []Z;
		delete []Res;
		
	
	}
}

void CBitmapDlg::OnStartFeature() 

{

	
	if (!loaded)
	{
		GetDlgItem(IDC_RADIO1)->EnableWindow(FALSE);
		GetDlgItem(IDC_RADIO2)->EnableWindow(FALSE);
		GetDlgItem(IDC_UPDATE_FEATURES)->EnableWindow(FALSE);
		GetDlgItem(IDC_UPDATE_FEATURE)->EnableWindow(FALSE);
		if (automate==false)
		{
			GetDlgItem(IDC_NEXT_IMAGE)->EnableWindow(TRUE);
			GetDlgItem(IDC_RESET)->EnableWindow(TRUE);
		}
		else
		{
			GetDlgItem(IDC_AUTOTRACKER)->EnableWindow(TRUE);
			GetDlgItem(IDC_PAUSE)->EnableWindow(FALSE);
		}
		GetDlgItem(IDC_START_FEATURE)->EnableWindow(FALSE);
		GetDlgItem(IDC_FEATURES)->EnableWindow(FALSE);
		GetDlgItem(IDC_STOP)->EnableWindow(TRUE);
		GetDlgItem(IDC_STOP)->EnableWindow(FALSE);
		my_frame=0;
		loaded=true;
		GetDlgItem(IDC_stream1)->EnableWindow(FALSE);
		GetDlgItem(IDC_stream2)->EnableWindow(FALSE);
		GetDlgItem(IDC_stream3)->EnableWindow(FALSE);
	
		img1=new unsigned char[Col*Row];
		img3=new unsigned char[Col*Row];
		img4=new unsigned char[Col*Row];
		img_mosaic=new unsigned char[Col*Row*3];
		err_mosaic=new unsigned char[Col*Row*3];
		delta_err_mosaic=new unsigned char[Col*Row*3];
	
	    tc = KLTCreateTrackingContext();
	    fl = KLTCreateFeatureList(nFeatures);
	    ft = KLTCreateFeatureTable(nFrames, nFeatures);
	    tc->sequentialMode = TRUE;
	    i=1;
		global_update_counter=1;	
		CString filename;
		filename.Empty();
		filename=directory;
		filename.Format("%s%s",directory,"mg0.pgm");
		
		//sprintf(fnamein,"%s%s",directory,"mg0.pgm");
		
		
		if (realtime==true)
			GrabImage(img1, Col*Row);	   
		else
			img1 = pgmReadFile(filename.GetBuffer(filename.GetLength()), NULL, &Col, &Row);


		char out_img[50];
		sprintf(out_img,"%s%s%d%s","e:\\kiran\\klt\\Tracking_affine\\","init_image",i,".txt");
		
		fstream fpimg;
		fpimg.open(out_img,ios::out);
		for(int t=0;t<Col*Row;t++)
		fpimg<<(int)img1[t]<<endl;
		fpimg.close();

		bitmap.SetBitmapBits(Col*Row,img1);  	
		base_bitmap.SetBitmapBits(Col*Row,img1); 
  		dcmem.SelectObject(&bitmap);
		BITMAP bm;
		GetObject(hbitmap,sizeof(BITMAP),&bm);
		mydc->BitBlt(offset_x,offset_y,bm.bmWidth,bm.bmHeight,&dcmem,0,0,SRCCOPY);
  
	
		KLTSelectGoodFeatures(tc, img1, Col, Row, fl);
		KLTStoreFeatureList(fl, ft, 0);
		SetDlgItemInt(IDC_INITIAL_FEATURE,fl->nFeatures);

		fstream fpt;
		fpt.open("e:\\kiran\\klt\\try\\transf.out",ios::out|ios::app);

		for(int j = 0 ; j < fl->nFeatures ; j++)
		{
	
			CPoint p;
			p.x=fl->feature[j]->x+offset_x;
			p.y=fl->feature[j]->y+offset_y;
		
			CPen solidpen(PS_SOLID,3,RGB(250,250,50));
			CPen *oldpen;
			oldpen=mydc->SelectObject(&solidpen);
			mydc->MoveTo(p);
			mydc->LineTo(p);

			//	fpt<<j<<"\t"<<fl->feature[j]->x<<"\t"<<fl->feature[j]->y<<endl;
			fl_global_x[j]=fl->feature[j]->x;
			fl_global_y[j]=fl->feature[j]->y;
		}

		fpt.close();
		SetDlgItemInt(IDC_INITIAL_FEATURE,fl->nFeatures);

		memcpy(img4,img1,Col*Row);

		for(int ii=0;ii<Col*Row;ii++)
			img3[ii]=0;

		for(int ij=0;ij<Col*Row*3;ij++)
		{
			img_mosaic[ij]=0;
			err_mosaic[ij]=0;		
			delta_err_mosaic[ij]=0;		
		}

		store_dx[0]=0;
		fill_mosaic(Col*3,Row,Col,Row,0,0,img1);
		fill_error_mosaic(Col*3,Row,Col,Row,0,0,img3); //error mosaic is initially 0 (img3 is the diff image)
	
	}	


}

void CBitmapDlg::find_tracked_features()
{
}

void CBitmapDlg::copy_base_image()
{
//base_bitmap.SetBitmapBits(Col*Row,img1); 
	
    dcmem.SelectObject(&base_bitmap);
    BITMAP bm;
    GetObject(hbitmap,sizeof(BITMAP),&bm);
    mydc->BitBlt(offset_x+600,offset_y,bm.bmWidth,bm.bmHeight,&dcmem,0,0,SRCCOPY);

	for (int j = 0 ; j < fl->nFeatures ; j++)
	{
	  if (fl->feature[j]->val==0)
	  {

		CPoint p;
		p.x=fl->feature[j]->x+offset_x+600;
		p.y=fl->feature[j]->y+offset_y;

		CPen solidpen(PS_SOLID,3,RGB(250,250,50));
		CPen *oldpen;
		oldpen=mydc->SelectObject(&solidpen);
		mydc->MoveTo(p);
		mydc->LineTo(p);

		mydc->SelectObject(oldpen);
	  }
	}


}
void CBitmapDlg::copy_base_image1()
{
//base_bitmap.SetBitmapBits(Col*Row,img1); 
	
    dcmem.SelectObject(&base_bitmap);
    BITMAP bm;
    GetObject(hbitmap,sizeof(BITMAP),&bm);
    mydc->BitBlt(offset_x+600,offset_y,bm.bmWidth,bm.bmHeight,&dcmem,0,0,SRCCOPY);

	for (int j = 0 ; j < fl->nFeatures ; j++)
	{
	  if (fl->feature[j]->val==0)
	  {

		CPoint p;
		p.x=fl->feature[j]->x+offset_x+600;
		p.y=fl->feature[j]->y+offset_y;

		CPen solidpen(PS_SOLID,3,RGB(250,250,50));
		CPen *oldpen;
		oldpen=mydc->SelectObject(&solidpen);
		mydc->MoveTo(p);
		mydc->LineTo(p);

		mydc->SelectObject(oldpen);
	  }
	}


}

void CBitmapDlg::copy_tracked_image()
{
	
//	tracked_bitmap.SetBitmapBits(Col*Row,img1); 
    dcmem.SelectObject(&tracked_bitmap);
    BITMAP bm;
    GetObject(hbitmap,sizeof(BITMAP),&bm);
    mydc->BitBlt(offset_x+600,offset_y+240,bm.bmWidth,bm.bmHeight,&dcmem,0,0,SRCCOPY);

for (int j = 0 ; j < fl->nFeatures ; j++)
	{
	  if (fl->feature[j]->val==0)
	  {
		
		CPoint p;
		p.x=fl->feature[j]->x+offset_x+600;
		p.y=fl->feature[j]->y+offset_y+240;

		CPen solidpen(PS_SOLID,3,RGB(250,250,50));
		CPen *oldpen;
		oldpen=mydc->SelectObject(&solidpen);
		mydc->MoveTo(p);
		mydc->LineTo(p);

		mydc->SelectObject(oldpen);
	  }
	}


}
void CBitmapDlg::Automate()
{
if (pause==false)
{
	auto_frames++;

		if (i%m_update_features==0)
			{
			OnReset();
			reset=true;
			auto_frames=0;
				
			}
		else
			{
			OnNextImage();	
			}
}

}


void CBitmapDlg::OnReset() 
{
	// TODO: Add your control notification handler code here

	float m_x=0;float m_y=0;
	float mm_x=0;
	float mm_y=0;
	int cnt=0;
	
	i=i+1;
	global_update_counter++;
	if (i<nFrames || realtime==true)
	{    
		
	
		my_frame++;
	  	sprintf(fnamein,"%s%s%d%s",directory,"mg",i,".pgm");
		
		if(panAngle >= -85)
		{
			panAngle--;
			panTilt->SetPositionAbs(panAngle, TILT);
		}
		
		for(int tm=0;tm<5000;tm++)
			for(int tj=0;tj<5000;tj++);

		img2=new unsigned char[Col*Row];	   
		
		if (realtime==true)
		{
			GrabImage(img2, Col*Row);
	    }
		else
		{
			pgmReadFile(fnamein, img2, &Col, &Row);	
		}
		
		if((i%28==0) && realtime ==true)
		{
			GrabImage(img1, Col*Row);
			//f_x=d_x;
			f_x=matrx[i-1][2];
			f_y=0;
		}

		for (int j = 0 ; j < fl->nFeatures ; j++)
		{
		 	fl_x[j]=fl->feature[j]->x;
			fl_y[j]=fl->feature[j]->y;
		}

		Y = new float[total_feature];
		Z = new float[total_feature];
		X1 = new float[total_feature];
		X2 = new float[total_feature];

		if(global_update_counter==update_number-1)
		{
			fstream f1;
			f1.open("e:\\kiran\\klt\\try\\global.out",ios::out|ios::app);
			Res_global = new float[6];
			cnt=0;
			for (j = 0 ; j < (fl->nFeatures) ; j++)
				if (fl->feature[j]->val==0)
					if(track_status[j]==1)
					{
						X1[cnt]= fl_global_x[j];
						X2[cnt]= fl_global_y[j];
						Y[cnt] = fl->feature[j]->x;
						Z[cnt] = fl->feature[j]->y;
						//f1<<j<<"\t"<<X1[cnt]<<"\t"<<Y[cnt]<<"\t"<<X2[cnt]<<"\t"<<Z[cnt]<<endl; 
						//f1<<j<<"\t"<<fl_x[j]<<"\t"<<fl->feature[j]->x<<"\t"<<"\t"<<fl_y[j]<<"\t"<<fl->feature[j]->y<<endl;
						cnt++;
					}
			int total_feature = cnt;

			Matrix A(total_feature,3);
			ColVector b1(total_feature);
			ColVector b2(total_feature);
			ColVector x_1(3);
			ColVector x_2(3);
		
			for( int ja=0;ja<total_feature;ja++)
			{
				A[ja][0]=(double) Y[ja];
				A[ja][1]=(double) Z[ja];
				A[ja][2]= 1;
			}
		
		
			for(ja=0;ja<total_feature;ja++)
			{
				b1[ja]=(double) X1[ja];
				b2[ja]=(double) X2[ja];
				
			}

			A.solveBySVD(b1,x_1);
			A.solveBySVD(b2,x_2);
		
			fstream fptA1;
			fptA1.open("e:\\kiran\\klt\\try\\A1.out",ios::out|ios::app);
			fptA1<<i<<"  "<< total_feature<<endl;
			fptA1 << x_1 <<"  "<< x_2 <<endl;
			fptA1.close();
		
			for(int a=0;a<3;a++)
				Res_global[a]=x_1[a];
			for(a=3;a<6;a++)
				Res_global[a]=x_2[a-3];

					
			
			//gradient_descent(cnt,X1,X2,Y,Z,Res_global); //Computes the transformation of the current frame w.r.t mosaic
														   // i.e, finds the coordinates in the mosaic which correspond 
														   // to the coordinates of the current image (mosaic coord is output- x',y')	
				
			//f1<<"RESET FRAME::: Count is"<<"\t"<<cnt<<"  Total_feature is"<<"\t"<<total_feature<<endl;
			f1<<i<<"\t"<<Res_global[0]<<"\t"<<Res_global[1]<<"\t"<<Res_global[2]<<"\t"<<Res_global[3]<<"\t"<<Res_global[4]<<"\t"<<Res_global[5]<<endl;
			f1.close();
			update_Matrix(i,Res_global);
			
			
			update_periodic_Matrix(i-1,m_update_features,Res_global);
			fstream fptr1;
			fptr1.open("e:\\kiran\\klt\\try\\matrix.out",ios::out|ios::app);
			fptr1.width(12);
			//fptr1<<"RESET FRAME:::::"<<i<<"\t"<<Res_global[0]<<"\t"<<Res_global[1]<<"\t"<<Res_global[2]<<"\t"<<Res_global[3]<<"\t"<<Res_global[4]<<"\t"<<Res_global[5]<<endl;
			fptr1.close();
					
			global_update_counter=1;
			delete []Res_global;
	
			/*matrx[i-1][0]=PMatrix[int((i-1)/m_update_features)][0];
			matrx[i-1][1]=PMatrix[int((i-1)/m_update_features)][1];
			matrx[i-1][2]=PMatrix[int((i-1)/m_update_features)][2];
			matrx[i-1][3]=PMatrix[int((i-1)/m_update_features)][3];
			matrx[i-1][4]=PMatrix[int((i-1)/m_update_features)][4];
			matrx[i-1][5]=PMatrix[int((i-1)/m_update_features)][5];
			*/
		} 
	
		
		fstream fr1;
		fr1.open("e:\\kiran\\klt\\try\\matrix.out",ios::out|ios::app);
		//fr1.width(12);
		//fr1<<"UPDATED RESET FRAME:::::"<<i<<"\t"<<matrx[i][0]<<"\t"<<matrx[i][1]<<"\t"<<matrx[i][2]<<"\t"<<matrx[i][3]<<"\t"<<matrx[i][4]<<"\t"<<matrx[i][5]<<"\t"<<endl;
		fr1<<"UPDATED   "<<i-1<<"\t"<<matrx[i-1][0]<<"\t"<<matrx[i-1][1]<<"\t"<<matrx[i-1][2]<<"\t"<<matrx[i-1][3]<<"\t"<<matrx[i-1][4]<<"\t"<<matrx[i-1][5]<<"\t"<<endl;
		fr1.close();


		//copy_matrix_pmatrix(i-1,m_update_features);
		KLTTrackFeatures(tc, img1, img2, Col, Row, fl);
		KLTReplaceLostFeatures(tc, img2, Col, Row, fl);
		KLTStoreFeatureList(fl, ft, i);
		KLTTrackFeatures(tc, img1, img2, Col, Row, fl);

		
		SetDlgItemInt(IDC_INITIAL_FEATURE,fl->nFeatures);
		SetDlgItemInt(IDC_FRAME_NUM,i);

		
		bitmap.SetBitmapBits(Col*Row,img2);  
		dcmem.SelectObject(&bitmap);
		BITMAP bm;
		GetObject(hbitmap,sizeof(BITMAP),&bm);
		mydc->BitBlt(offset_x,offset_y,bm.bmWidth,bm.bmHeight,&dcmem,0,0,SRCCOPY);
	
		bitmap.SetBitmapBits(Col*Row,img1);		
		dcmem.SelectObject(&bitmap);
		mydc->BitBlt(offset_x+600,offset_y,bm.bmWidth,bm.bmHeight,&dcmem,0,0,SRCCOPY);
		
		
		reset_track_status();
		int tmp_totall=0;
		for (j = 0 ; j < fl->nFeatures ; j++)
		{
	 		fl_global_x[j]=fl->feature[j]->x;
			fl_global_y[j]=fl->feature[j]->y;
			tmp_totall++;
		}
		fstream fpta;
		fpta.open("e:\\kiran\\klt\\try\\global.out",ios::out|ios::app);
		//fpta<<"GLOBAL PARAMETERS GET UPDATED WHEN # OF FEATURES = "<<tmp_totall<<endl;
		fpta.close();
		
	
		total_feature=0;
		for (j = 0 ; j < fl->nFeatures ; j++)
		{
			if (fl->feature[j]->val==0)
			{
				total_feature++;
				CPoint p;
				p.x=fl->feature[j]->x+offset_x;
				p.y=fl->feature[j]->y+offset_y;

				CPen solidpen(PS_SOLID,3,RGB(250,250,50));
				CPen *oldpen;
				oldpen=mydc->SelectObject(&solidpen);
				mydc->MoveTo(p);
				mydc->LineTo(p);

				mydc->SelectObject(oldpen);
			}
		}
  		SetDlgItemInt(IDC_TOTAL_FEATURE,total_feature);

		fstream f3;
		f3.open("e:\\kiran\\klt\\try\\global.out",ios::out|ios::app);
		//f3<<"Total_feature is"<<"\t"<<total_feature<<endl;
		f3.close();


		/*if(global_update_counter==update_number-1)
		{
			fstream f1;
			f1.open("e:\\kiran\\klt\\try\\global.out",ios::out|ios::app);
			f1<<i<<"\t"<<global_update_counter<<endl;
			f1.close();
			global_update_counter=1;
			
		} 
		*/
		

	d_x+=store_dx[i-2]-store_dx[i-3];

	for(int kr=0;kr<6;kr++)
		matrx[i][kr] = matrx[i-1][kr];
		matrx[i][2] = matrx[i-1][2] + (matrx[i-1][2]-matrx[i-2][2]);
	//  matrx[i][2] = matrx[i][2] + (matrx[i-1][2]-matrx[i-2][2]);
	//	matrx[i][5] = 0;

	
	fstream fptr2;
	fptr2.open("e:\\kiran\\klt\\try\\matrix.out",ios::out|ios::app);
	fptr2<<i<<"\t"<<matrx[i][0]<<"\t"<<matrx[i][1]<<"\t"<<matrx[i][2]<<"\t"<<matrx[i][3]<<"\t"<<matrx[i][4]<<"\t"<<matrx[i][5]<<"\t"<<endl;
	//fptr2<<i<<"\t"<<matrx[i][2]<<"\t"<<matrx[i][1]<<"\t"<<d_x<<endl;
	fptr2.close();
			
	float warp_data[6];
	for(int ka=0;ka<5;ka++) warp_data[ka]=matrx[i][ka];
	warp_data[5]=0;
	//fill_mosaic_warped(Col*3,Row,Col,Row,warp_data,img2);
	store_dx[i-1]=warp_data[2];
	
	}
  
		SetDlgItemInt(IDC_INITIAL_FEATURE,fl->nFeatures);  
		if (pause==false && automate==true)
			{
				tracked_bitmap.SetBitmapBits(Col*Row,img2); 
			//	copy_tracked_image();
				char buffer[50];
				sprintf(buffer,"Frame %d",i);
				SetDlgItemText(IDC_TRACKED,buffer);
			}

		
		
	delete []img2;
	delete []X1;
	delete []X2;
	delete []Y;
	delete []Z;
	/*delete []Res;*/

}


void CBitmapDlg::cleanup()
{
   if (my_frame>1) KLTStopSequentialMode(tc);	
   KLTFreeFeatureTable(ft);
   KLTFreeFeatureList(fl);
   KLTFreeTrackingContext(tc);
   

}
void CBitmapDlg::OnClose() 
{
	// TODO: Add your message handler code here and/or call default
	//delete []img1;
//	delete []img2;


	MyCam->freeBuffs();
	delete MyCam;
	delete panTilt;	
	delete []img1;
	delete []img3;
	delete []img4;
	delete []img_mosaic;
	delete []err_mosaic;
	delete []delta_err_mosaic;

	//fclose(stream);
	if (loaded)
	{
	cleanup();
	bitmap.DeleteObject();
	base_bitmap.DeleteObject();
	tracked_bitmap.DeleteObject();
	mosaic_bitmap.DeleteObject();
	DeleteObject(hbitmap);
	DeleteObject(hbitmap);
	cleanup();
	dcmem.DeleteDC();
	ReleaseDC(mydc);
	
		
	}
	CDialog::OnClose();
}


void CBitmapDlg::Onstream1() 
{
	// TODO: Add your control notification handler code here
	
	//directory="c:\\sequence\\4\\";
	directory="e:\\kiran\\klt\\";
	SetDlgItemText(IDC_VIDEOSTREAM,"Stream 1");
    total_frames=11;
	SetDlgItemInt(IDC_TOTALFRAMES,total_frames,FALSE);
}

void CBitmapDlg::Onstream2() 
{
	// TODO: Add your control notification handler code here
	//directory="c:\\sequence\\5\\";
	directory="e:\\kiran\\images\\";
	SetDlgItemText(IDC_VIDEOSTREAM,"Stream 2");
	total_frames=500;
	SetDlgItemInt(IDC_TOTALFRAMES,total_frames,FALSE);
	
}

void CBitmapDlg::Onstream3() 
{
	// TODO: Add your control notification handler code here
	//directory="c:\\sequence\\6\\";
	directory="e:\\kiran\\image\\";
	SetDlgItemText(IDC_VIDEOSTREAM,"Stream 3");
	total_frames=501;
	SetDlgItemInt(IDC_TOTALFRAMES,total_frames,FALSE);

	
}


void CBitmapDlg::OnUpdateFeatures() 
{
	UpdateData(TRUE);

	nFeatures=m_max_features;
//SetDlgItemInt(IDC_12,m_max_features,TRUE);
	// TODO: If this is a RICHEDIT control, the control will not
	// send this notification unless you override the CDialog::OnInitDialog()
	// function to send the EM_SETEVENTMASK message to the control
	// with the ENM_UPDATE flag ORed into the lParam mask.
	
	// TODO: Add your control notification handler code here
	
}

void CBitmapDlg::OnRadio1() 
{
	// TODO: Add your control notification handler code here
	GetDlgItem(IDC_NEXT_IMAGE)->EnableWindow(FALSE);
	GetDlgItem(IDC_RESET)->EnableWindow(FALSE);
	GetDlgItem(IDC_AUTOTRACKER)->EnableWindow(TRUE);
	automate=true;
	
	
}

void CBitmapDlg::OnRadio2() 
{
GetDlgItem(IDC_NEXT_IMAGE)->EnableWindow(TRUE);	
GetDlgItem(IDC_RESET)->EnableWindow(TRUE);
GetDlgItem(IDC_AUTOTRACKER)->EnableWindow(FALSE);
automate=false;
}

void CBitmapDlg::OnStop() 
{
	// TODO: Add your control notification handler code here
	loaded=false;
	start_automation=false;
	GetDlgItem(IDC_FEATURES)->EnableWindow(TRUE);
	GetDlgItem(IDC_stream1)->EnableWindow(TRUE);
	GetDlgItem(IDC_stream2)->EnableWindow(TRUE);
	GetDlgItem(IDC_stream3)->EnableWindow(TRUE);
	GetDlgItem(IDC_NEXT_IMAGE)->EnableWindow(FALSE);
	GetDlgItem(IDC_RESET)->EnableWindow(FALSE);
	GetDlgItem(IDC_RADIO1)->EnableWindow(TRUE);
	GetDlgItem(IDC_RADIO2)->EnableWindow(TRUE);
	GetDlgItem(IDC_STOP)->EnableWindow(FALSE);
	GetDlgItem(IDC_START_FEATURE)->EnableWindow(TRUE);
	
	GetDlgItem(IDC_UPDATE_FEATURES)->EnableWindow(TRUE);	
	GetDlgItem(IDC_UPDATE_FEATURE)->EnableWindow(TRUE);	
	//GetDlgItem(IDC_AUTOTRACKER)->EnableWindow(TRUE);	
	GetDlgItem(IDC_AUTOTRACKER)->EnableWindow(FALSE);
	GetDlgItem(IDC_PAUSE)->EnableWindow(FALSE);


cleanup();


	
}

void CBitmapDlg::OnChangeUpdateFeatures() 
{

	UpdateData(TRUE);

	
	// TODO: If this is a RICHEDIT control, the control will not
	// send this notification unless you override the CDialog::OnInitDialog()
	// function and call CRichEditCtrl().SetEventMask()
	// with the ENM_CHANGE flag ORed into the mask.
	
	// TODO: Add your control notification handler code here
	
}

void CBitmapDlg::OnAutotracker() 
{
	// TODO: Add your control notification handler code here
	GetDlgItem(IDC_AUTOTRACKER)->EnableWindow(FALSE);	
	start_automation=true;
	GetDlgItem(IDC_PAUSE)->EnableWindow(TRUE);
	
}

void CBitmapDlg::find_total_frames()
{
	
	SetDlgItemInt(IDC_TOTALFRAMES,total_frames,FALSE);
}


void CBitmapDlg::Onstream4() 
{
	// TODO: Add your control notification handler code here
		//directory="c:\\sequence\\7\\";
	directory="e:\\kiran\\image1\\";
	SetDlgItemText(IDC_VIDEOSTREAM,"Stream 4");
	total_frames=300;
	SetDlgItemInt(IDC_TOTALFRAMES,total_frames,FALSE);

	
}

void CBitmapDlg::Onstream5() 
{
	// TODO: Add your control notification handler code here
	//directory="c:\\sequence\\8\\";
	directory="e:\\kiran\\images\\";
	SetDlgItemText(IDC_VIDEOSTREAM,"Stream 5");
	total_frames=300;
	SetDlgItemInt(IDC_TOTALFRAMES,total_frames,FALSE);

	
}

void CBitmapDlg::OnPause() 
{
	// TODO: Add your control notification handler code here
	if (pause==false) 
	{
		pause=true;
		SetDlgItemText(IDC_PAUSE,"Continue");
	}
	else
	{
		pause=false;
		SetDlgItemText(IDC_PAUSE,"Pause");
	}

	
}


void CBitmapDlg::GrabImage(unsigned char tt[], int Size)
{
	
	MyCam->setFrameBuf();	
	MyCam->grabFrame();

	int B=320;
	int H=200;
	int s_x=10;
	int s_y=0;
	int b=B-2*s_x;
	int h=H-2*s_y;

	unsigned char *ptr=MyCam->getFrameBuf();
	unsigned char *pt = new unsigned char[B*H];
	unsigned char *temp = new unsigned char[B*H];
	int dumbcounter=0;
	
	for (int a=0;a<=B*H-1;a++)
		temp[a]=0;

	//for (int tx=0;tx<=B*H-1;tx++)	
	//	pt[tx]=ptr[dumbcounter++];
	
	/*for(int i=0;i<B;i++)
		for(int j=0;j<H;j++)
		{
		int indx1 = ind(i,j,B);
		int indx2 = ind(i,H-j,B);
		pt[indx2] = ptr[indx2];
		}
	*/
	
	for (int tx=B*H-1;tx>=0;tx--)
	//for (int tx=0;tx<=B*H-1;tx++)	
	 pt[tx]=ptr[dumbcounter++];
	
	for (int i=0; i<B; i++)
		for (int j=0; j<H; j++)
			if(i>=s_x && i< s_x+b && j>=s_y && j<=s_y+h)
			{
				int img_indx = ind(i-s_x,j-s_y,b);
				int mosaic_indx = ind(i,j,B);	
				temp[img_indx]=pt[mosaic_indx];
			}

	memcpy(tt,temp,Size);
	//for (int r=0;r<=Size-1;r++)
	//	tt[r]=temp[r];

	//delete []ptr;
	delete []pt;
	delete []temp;
}
void CBitmapDlg::OnCamera() 
{

	realtime=true	;
	
	bitmap.SetBitmapBits(MyCam->getHeight()*MyCam->getWidth(),t1);  
		
		
	dcmem.SelectObject(&bitmap);
	BITMAP bm;
	GetObject(hbitmap,sizeof(BITMAP),&bm);
	mydc->BitBlt(offset_x,offset_y,bm.bmWidth,bm.bmHeight,&dcmem,0,0,SRCCOPY);
    

	
}

void CBitmapDlg::OnShoot() 
{
	// TODO: Add your control notification handler code here
	unsigned char *temp1=new unsigned char[Col*Row];
	GrabImage(temp1, Col*Row);
	bitmap.SetBitmapBits(Col*Row,temp1);  
		
		
	dcmem.SelectObject(&bitmap);
	BITMAP bm;
	GetObject(hbitmap,sizeof(BITMAP),&bm);
	mydc->BitBlt(offset_x,offset_y,bm.bmWidth,bm.bmHeight,&dcmem,0,0,SRCCOPY);
	delete []temp1;
}

void CBitmapDlg::OnExit() 
{
	// TODO: Add your control notification handler code here
	MyCam->freeBuffs();
}

void CBitmapDlg::OnGrabber() 
{
	// TODO: Add your control notification handler code here

	realtime=true;
}

void CBitmapDlg::OnClosecamera() 
{
	// TODO: Add your control notification handler code here
	
	MyCam->freeBuffs();
	MyCam->check(VPP_closedown(VPP_true));	
	MessageBox("The framegrabber has been powered-off",NULL,MB_OK);
	
}

void CBitmapDlg::OnButton1() 
{
	// TODO: Add your control notification handler code here
	realtime=false;
}


int CBitmapDlg::minim_vector(int ax,int ay) 
{

	int tempx=0;
	int tempy=0;
	int dist=0;

	int ii=-1;
		int min=65525;

	for (int j = 0 ; j < fl->nFeatures ; j++)
	{
	  if (fl->feature[j]->val==0)
	  {
		
		tempx = fl->feature[j]->x;
		tempy = fl->feature[j]->y;
		dist = abs(tempx-ax) + abs(tempy-ay);
		if(dist<50) 
		{
			if(dist<min) 
			{
				min=dist;
				ii = j;
			}

		}
	  
	  }
	  if(min<15) return(ii);
	}
return(ii);
}

//Used in morphing code
void CBitmapDlg::put_blk(int a_x,int a_y,int mv_x, int mv_y, int flg)
{
	int i = a_x-mv_x/2;
	int j = a_y-mv_y/2;
	
	if((i)<=0) i=0;
	if((i)>=Col) i=Col-1;
	if((j)<=0) j=0;
	if((j)>=Row) j=Row-1;

	int index = ind(i,j,Col);

	int i1 = a_x-mv_x;
	int i2 = a_y-mv_y;
	
	if((i1)<=0) i1=0;
	if((i1)>=Col) i1=Col - 1;
	if((i2)<=0) i2=0;
	if((i2)>=Row) i2=Row - 1;

	if((a_x)<=0) a_x=0;
	if((a_x)>=Col) a_x=Col - 1;
	if((a_y)<=0) a_y=0;
	if((a_y)>=Row) a_y=Row - 1;

	int indx2 = ind(a_x,a_y,Col);
	int indx3 = ind(i1,i2,Col);
	
	img_morph[index] = 0.5*img2[indx2]+0.5*img3[indx3];
	
	if(flg==0)
		img_unfinished[index] = 0.5*img2[indx2]+0.5*img3[indx3];

}

void CBitmapDlg::OnAll() 
{
	// TODO: Add your control notification handler code here
	UpdateData(TRUE);
}

void CBitmapDlg::OnBx()
{
}
void CBitmapDlg::OnFrameNum()
{
}
void CBitmapDlg::OnInitialFeature()
{
}

//Fills the mosiac with contents of image
void CBitmapDlg::fill_mosaic(int B, int H, int b, int h, int dx, int dy, unsigned char* image)
{
	int i,j;	
	for(i=0;i<B;i++)
		for(j=0;j<H;j++)
		{
			int mosaic_indx = ind(i,j,B);
			
			if(i>=dx && i< dx+b && j>=dy && j<=dy+h)
			{
				int img_indx = ind(i-dx,j-dy,b);
				if(img_mosaic[mosaic_indx]!=0)
				//img_mosaic[mosaic_indx]=0.5*(img_mosaic[mosaic_indx]+image[img_indx]);
				img_mosaic[mosaic_indx]=image[img_indx];
				else img_mosaic[mosaic_indx]=image[img_indx];
			}
			
		}
}

void CBitmapDlg::fill_mosaic_warped(int B, int H, int b, int h, float warp_data[6], unsigned char* image) 
{
	//Warping by source scanning: forward warping
	/*int i,j;	
	int max_mos_indx = -9999;
	for(i=0;i<b;i++)
		for(j=0;j<h;j++)
		{
			float x = warp_data[0]*i + warp_data[1]*j + warp_data[2];
			float y = warp_data[3]*i + warp_data[4]*j; // + warp_data[5];
			
			//float x = i + warp_data[2];
			//float y = j;

			int mos_x = 0 ;
			int mos_y = 0;
			
			if(x<=0) mos_x=0;
			else if (x>=B) mos_x=B-1;
			else mos_x = (int) x;

			if(y<=0) mos_y=0;
			else if (y>=h) mos_y=h-1;
			else mos_y = (int) y;
			
			int mosaic_indx = ind(mos_x,mos_y,B);
			if(mosaic_indx>max_mos_indx) max_mos_indx = mosaic_indx;

			int img_indx = ind(i,j,b);
			float wx=1;float wy=1; float w=1;

			//Triangular weights
			if(i>=0 && i<=b/4) wx = 4*i/b;
			if(i>=3*b/4 && i<b) wx = -(4*i/b)+4;
			if(i>b/4 && i<3*b/4) wx=1;
			if(j>=0 && j<=h/4) wy = 4*j/h;
			if(j>=3*h/4 && j<h) wy = -(4*j/h)+4;
			if(j>h/4 && j<3*h/4) wy=1;
	*/

			/*if(i>=0 && i<=b/2) wx = 2*i/b;
			if(i>b/2 && i<b) wx = -(2*i/b)+2;
			if(j>=0 && j<=h/2) wy = 2*j/h;
			if(j>h/2 && j<h) wy = -(2*j/h)+2;
			*/
	/*
			w = wx*wy;
			//w=0.5;
			w=1;
			if(img_mosaic[mosaic_indx]!=0)
				img_mosaic[mosaic_indx]= w*image[img_indx] + (1-w)*img_mosaic[mosaic_indx];
			else
				img_mosaic[mosaic_indx]=image[img_indx];
		}
		//Fat pixels to fill holes
		for(i=20;i<max_mos_indx-20;i++)
		{
			if(img_mosaic[i]==0)
			{
				//img_mosaic[i] = 0.25*(img_mosaic[i-2]+img_mosaic[i-1]+img_mosaic[i+1]+img_mosaic[i+2]);
				unsigned char temp=0;
				if(img_mosaic[i-5]>0) temp = img_mosaic[i-5];
				if (img_mosaic[i+5]>0) temp = img_mosaic[i+5];
				if (img_mosaic[i-4]>0) temp = img_mosaic[i-4];
				if (img_mosaic[i+4]>0) temp = img_mosaic[i+4];
				if (img_mosaic[i-3]>0) temp = img_mosaic[i-3];
				if (img_mosaic[i+3]>0) temp = img_mosaic[i+3];
				if (img_mosaic[i-2]>0) temp = img_mosaic[i-2];
				if (img_mosaic[i+2]>0) temp = img_mosaic[i+2];
				if (img_mosaic[i-1]>0) temp = img_mosaic[i-1];
				if (img_mosaic[i+1]>0) temp = img_mosaic[i+1];

				img_mosaic[i] = temp;
			}
				
		}
	*/

	//Inverse warping (Destination Scan)
	fstream f3;
	f3.open("e:\\kiran\\klt\\Tracking_affine\\test.out",ios::out);
	//warp_data[5]=0;
	int i_min,j_min,i_max,j_max;
	int i,j;
	i_min = (warp_data[2]<warp_data[1]*(h-1) + warp_data[2]?warp_data[2]:warp_data[1]*(h-1) + warp_data[2]);
	j_min = (warp_data[5]<warp_data[3]*(b-1) + warp_data[5]?warp_data[5]:warp_data[3]*(b-1) + warp_data[5]);
	i_max = ((warp_data[0]*(b-1) + warp_data[1]*(h-1) + warp_data[2])>(warp_data[0]*(b-1) + warp_data[2])?(warp_data[0]*(b-1) + warp_data[1]*(h-1) + warp_data[2]):(warp_data[0]*(b-1) + warp_data[2]));
	j_max = ((warp_data[3]*(b-1) + warp_data[4]*(h-1) + warp_data[5])>(warp_data[4]*(h-1) + warp_data[5])?(warp_data[3]*(b-1) + warp_data[4]*(h-1) + warp_data[5]):(warp_data[4]*(h-1) + warp_data[5]));
	
	//i_min = warp_data[2];
	//j_min = warp_data[5];
	//i_max = (warp_data[0]*(b-1) + warp_data[1]*(h-1) + warp_data[2]);
	//j_max = (warp_data[3]*(b-1) + warp_data[4]*(h-1) + warp_data[5]);

	if(i_min<0) i_min=0;
	if(j_min<0) j_min=0;
	if(i_max>B) i_max=B;
	if(j_max>H) j_max=H;

	f3 << warp_data[0] <<"\t"<< warp_data[1] <<"\t"<< warp_data[2] <<"\t"<< warp_data[3] <<"\t"<< warp_data[4]<<"\t"<< warp_data[5] <<"\t"<<b<<"\t"<<h << endl;
	f3 << i_min <<"\t"<< j_min <<"\t"<< i_max <<"\t"<< j_max << endl;
	f3.close();

	float aA,bB,cC,dD;
	float det=0;

	det = 1/(warp_data[0]*warp_data[4] - warp_data[1]*warp_data[3]);
	aA = det * warp_data[4];
	bB = det * (-warp_data[1]);
	cC = det * (-warp_data[3]);
	dD = det * warp_data[0];
	
	//Scanning (to fill) the destination(mosaic) and finding the corresponding pixels in the source (image) 
	//Uses bilinear interpolation to fill pixels in the warped image.

	for(i=i_min;i<i_max;i++)
		for(int j=j_min;j<j_max;j++)
		{
			float x = aA * (i-warp_data[2]) + bB * (j-warp_data[5]);
			float y = cC * (i-warp_data[2]) + dD * (j-warp_data[5]);

			if(x<0) x=0;
			if(x>b) x=b;
			if(y<0) y=0;
			if(y>b) y=b;
			
			int mosaic_indx = ind(i,j,B);
			//int img_indx = ind((int)x,(int)y,b)
			int i_c = ceil(x);   
		    int i_f = floor(x);
			int j_c = ceil(y);
			int j_f = floor(y);
			float pxy=0;
			if (i_f>=0 && j_f >=0 && i_c<=b && j_c<=h)
			{
				float dx = x-i_f;
   				float dy = y-j_f;
	 			int	p00 = ind(i_f,j_f,b);
   				int p10 = ind(i_c,j_f,b);
   				int p01 = ind(i_f,j_c,b);
   				int p11 = ind(i_c,j_c,b);

   				float px0 = image[p00] + dx*(image[p10] - image[p00]);
   				float px1 = image[p01] + dx*(image[p11] - image[p01]);
   				pxy = px0 + dy*(px1 - px0);
      		}
   		

			float wx=1;
			float wy=1;
			
			if(i>=0 && i<=i_max/2) wx = 2*i/i_max;
			if(i>i_max/2 && i<i_max) wx = -(2*i/i_max)+2;
			
			//if(i>=0 && i<=i_max/2) wx = 2*(i-i_min)/(i_max-3*i_min);
			//if(i>i_max/2 && i<i_max) wx = -(2*(i-i_max)/(i_max+i_min));
			//if(j>=0 && j<=j_max/2) wy = 2*j/j_max;
			//if(j>j_max/2 && j<j_max) wy = -(2*j/j_max)+2;
			
			float w = wx*wy;
			w=1;
			if(img_mosaic[mosaic_indx]!=0)
				img_mosaic[mosaic_indx]= w*pxy + (1-w)*img_mosaic[mosaic_indx];
				//img_mosaic[mosaic_indx]= w*image[img_indx] + (1-w)*img_mosaic[mosaic_indx];

			else
				img_mosaic[mosaic_indx]=pxy;
		}
}			



void CBitmapDlg::index_mosaic_warped(int B, int H, int b, int h, float warp_data[6], unsigned char image[]) 
{

	int i,j;	
	for(i=0;i<b;i++)
		for(j=0;j<h;j++)
		{
			float x = warp_data[0]*i + warp_data[1]*j + warp_data[2];
			float y = warp_data[3]*i + warp_data[4]*j; // + warp_data[5];

			int mos_x = 0 ;
			int mos_y = 0;
			int img_x = 0;
			int img_y = 0;

			
			if(x<=0) mos_x=0;
			else if (x>=B) mos_x=B-1;
			else mos_x = (int) x;

			img_x = x-warp_data[2];
			if(img_x<=0) img_x=0;
			else if (img_x>=b) img_x=b-1;

			if(y<=0) mos_y=0;
			else if (y>=h) mos_y=h-1;
			else mos_y = (int) y;

			img_y = mos_y;
						
			int mosaic_indx = ind(mos_x,mos_y,B);
			//int img_indx = ind(i,j,b);
			int img_indx = ind(img_x,img_y,b);
			

			image[img_indx]=img_mosaic[mosaic_indx];
		}
}

void CBitmapDlg::index_error_mosaic_warped(int B, int H, int b, int h, float warp_data[6], unsigned char image[]) 
{

	int i,j;	
	for(i=0;i<b;i++)
		for(j=0;j<h;j++)
		{
			float x = warp_data[0]*i + warp_data[1]*j + warp_data[2];
			float y = warp_data[3]*i + warp_data[4]*j; // + warp_data[5];

			int mos_x = 0 ;
			int mos_y = 0;
			int img_x = 0;
			int img_y = 0;

			
			if(x<=0) mos_x=0;
			else if (x>=B) mos_x=B-1;
			else mos_x = (int) x;

			img_x = x-warp_data[2];
			if(img_x<=0) img_x=0;
			else if (img_x>=b) img_x=b-1;

			if(y<=0) mos_y=0;
			else if (y>=h) mos_y=h-1;
			else mos_y = (int) y;

			img_y = mos_y;
						
			int mosaic_indx = ind(mos_x,mos_y,B);
			//int img_indx = ind(i,j,b);
			int img_indx = ind(img_x,img_y,b);
			

			image[img_indx]=err_mosaic[mosaic_indx];
		}
}

void CBitmapDlg::put_mosaic_warped(int B, int H, int b, int h, float warp_data[6], unsigned char *image) 
{

	int i,j;	
	for(i=0;i<b;i++)
		for(j=0;j<h;j++)
		{
			float x = warp_data[0]*i + warp_data[1]*j + warp_data[2];
			float y = warp_data[3]*i + warp_data[4]*j; // + warp_data[5];

			int mos_x = 0 ;
			int mos_y = 0;
			int img_x = 0;
			int img_y = 0;

			
			if(x<=0) mos_x=0;
			else if (x>=B) mos_x=B-1;
			else mos_x = (int) x;

			img_x = x-warp_data[2];
			if(img_x<=0) img_x=0;
			else if (img_x>=b) img_x=b-1;

			if(y<=0) mos_y=0;
			else if (y>=h) mos_y=h-1;
			else mos_y = (int) y;

			img_y = mos_y;
						
			int mosaic_indx = ind(mos_x,mos_y,B);
			//int img_indx = ind(i,j,b);
			int img_indx = ind(img_x,img_y,b);

			float wx=1;float wy=1; float w=1;
			
			if(i>=0 && i<=b/2) wx = 2*i/b;
			if(i>b/2 && i<b) wx = -(2*i/b)+2;
			if(j>=0 && j<=h/2) wy = 2*j/h;
			if(j>h/2 && j<h) wy = -(2*j/h)+2;

			w = wx*wy;
			w=1;

			img_mosaic[mosaic_indx]=w*image[img_indx]+(1-w)*img_mosaic[mosaic_indx];
		}
}

void CBitmapDlg::put_error_mosaic_warped(int B, int H, int b, int h, float warp_data[6], unsigned char *image) 
{

	int i,j;	
	for(i=0;i<b;i++)
		for(j=0;j<h;j++)
		{
			float x = warp_data[0]*i + warp_data[1]*j + warp_data[2];
			float y = warp_data[3]*i + warp_data[4]*j; // + warp_data[5];

			int mos_x = 0 ;
			int mos_y = 0;
			int img_x = 0;
			int img_y = 0;

			
			if(x<=0) mos_x=0;
			else if (x>=B) mos_x=B-1;
			else mos_x = (int) x;

			img_x = x-warp_data[2];
			if(img_x<=0) img_x=0;
			else if (img_x>=b) img_x=b-1;

			if(y<=0) mos_y=0;
			else if (y>=h) mos_y=h-1;
			else mos_y = (int) y;

			img_y = mos_y;
						
			int mosaic_indx = ind(mos_x,mos_y,B);
			//int img_indx = ind(i,j,b);
			int img_indx = ind(img_x,img_y,b);

			float wx=1;float wy=1; float w=1;
			
			if(i>=0 && i<=b/2) wx = 2*i/b;
			if(i>b/2 && i<b) wx = -(2*i/b)+2;
			if(j>=0 && j<=h/2) wy = 2*j/h;
			if(j>h/2 && j<h) wy = -(2*j/h)+2;

			w = wx*wy;
			w=1;

			err_mosaic[mosaic_indx]=w*image[img_indx]+(1-w)*img_mosaic[mosaic_indx];
		}
}


void CBitmapDlg::show_warped(int B, int H, int b, int h, float warp_data[6], unsigned char* image, unsigned char disp_img[]) 
{
	int i,j;	
	for(i=0;i<b;i++)
		for(j=0;j<h;j++)
		{
			float x = warp_data[0]*i + warp_data[1]*j + warp_data[2];
			float y = warp_data[3]*i + warp_data[4]*j; // + warp_data[5];
					
			int mos_x = 0 ;
			int mos_y = 0;
			int img_x = 0;
			int img_y = 0;

			
			if(x<=0) mos_x=0;
			else if (x>=B) mos_x=B-1;
			else mos_x = (int) x;

			img_x = x-warp_data[2];
			if(img_x<=0) img_x=0;
			else if (img_x>=b) img_x=b-1;

			if(y<=0) mos_y=0;
			else if (y>=h) mos_y=h-1;
			else mos_y = (int) y;

			img_y = mos_y;
			
			int show_indx = ind(img_x,img_y,b);
			int img_indx = ind(i,j,b);
			
			disp_img[show_indx]=image[img_indx];

			
		}
}

void CBitmapDlg::fill_error_mosaic(int B, int H, int b, int h, int dx, int dy, unsigned char* image)
{
	int i,j;	
	for(i=0;i<B;i++)
		for(j=0;j<H;j++)
		{
			int mosaic_indx = ind(i,j,B);
			
			if(i>=dx && i< dx+b && j>=dy && j<=dy+h)
			{
				int img_indx = ind(i-dx,j-dy,b);
				//if(err_mosaic[mosaic_indx]!=0 && image[img_indx] !=0)
				//	err_mosaic[mosaic_indx]=0.5*(err_mosaic[mosaic_indx]+image[img_indx]);
					//err_mosaic[mosaic_indx]=image[img_indx];
				//else if(err_mosaic[mosaic_indx]==0 && image[img_indx] !=0)
					//err_mosaic[mosaic_indx]=image[img_indx];
				
				if(err_mosaic[mosaic_indx]==0 && image[img_indx] !=0)
					err_mosaic[mosaic_indx]=image[img_indx];

				if(err_mosaic[mosaic_indx]!=0 && image[img_indx] !=0)
				{
					//if( image[img_indx] > err_mosaic[mosaic_indx])
						err_mosaic[mosaic_indx]=image[img_indx];
						//err_mosaic[mosaic_indx]=0.5*(err_mosaic[mosaic_indx]+image[img_indx]);
				}
				
			}
			
		}
}


void CBitmapDlg::fill_delta_error_mosaic(int B, int H, int b, int h, int dx, int dy, unsigned char* image)
{
	int i,j;	
	for(i=0;i<B;i++)
		for(j=0;j<H;j++)
		{
			int mosaic_indx = ind(i,j,B);
			
			if(i>=dx && i< dx+b && j>=dy && j<=dy+h)
			{
				int img_indx = ind(i-dx,j-dy,b);
				
				if(delta_err_mosaic[mosaic_indx]==0 && image[img_indx] !=0)
					delta_err_mosaic[mosaic_indx]=image[img_indx];

				if(delta_err_mosaic[mosaic_indx]!=0 && image[img_indx] !=0)
					delta_err_mosaic[mosaic_indx]=image[img_indx];
					
			}
			
		}
}



void CBitmapDlg::OnChangeMosaic() 
{
	// TODO: If this is a RICHEDIT control, the control will not
	// send this notification unless you override the CDialog::OnInitDialog()
	// function and call CRichEditCtrl().SetEventMask()
	// with the ENM_CHANGE flag ORed into the mask.
	// TODO: Add your control notification handler code here
	UpdateData(TRUE);
	//shift_x = m_mosaic;
	
	//shift_y=0;

}

void CBitmapDlg::OnMosButton() 
{
	
	
	// TODO: Add your control notification handler code here
	SetDlgItemInt(IDC_shift,m_mosaic_count,FALSE);
	
	//panTilt->SetPositionAbs((-(m_mosaic-1)), TILT);
	
	//	for(int tm=0;tm<5000;tm++)
	//		for(int tj=0;tj<10000;tj++);

	//calc_warp_params(store_dx[i-1]+Col, (pi/180)*(i-1));
	if(mosaic_shift==false)
	{
	move_to(panAngle, start_panAngle-(m_mosaic-1));
	panAngle = start_panAngle-(m_mosaic-1);
	}
	
	BITMAP bm;
	GetObject(hbitmap,sizeof(BITMAP),&bm);
	unsigned char* temp_image=new unsigned char[Row*Col];
	//unsigned char* temp_err_image=new unsigned char[Row*Col];
	//CString direct;
	//direct="e:\\kiran\\images\\newimgs\\";
	//sprintf(fnamein,"%s%s%d%s",direct,"mg",m_mosaic,".pgm");
	//pgmReadFile(fnamein, temp_image, &Col, &Row);
	//panAngle = -m_mosaic;
	GrabImage(temp_image,Col*Row);
	//spatio_temporal_filter(temp_image,ceil(store_dx[m_mosaic]+m_mosaic_count),0.0625);
	tracked_bitmap.SetBitmapBits(Col*Row,temp_image); 
	dcmem.SelectObject(&tracked_bitmap);
	mydc->BitBlt(offset_x,offset_y,bm.bmWidth,bm.bmHeight,&dcmem,0,0,SRCCOPY);

	unsigned char* temp_warped_image=new unsigned char[Row*Col];
	//index_mosaic(Col*3, Row, Col, Row, ceil(store_dx[m_mosaic]+m_mosaic_count),shift_y);
	float warp_data[6];
	for(int c=0;c<Col*Row; c++) temp_warped_image[c]=0;
	for(int ka=0;ka<6;ka++) warp_data[ka]=matrx[m_mosaic][ka];
			
	/*warp_data[0]= 1.0;
	warp_data[1]= 0.0;
	warp_data[3]= 0.0;
	warp_data[4]= 1.0;
	warp_data[5]= 0.0;*/
	warp_data[2]=matrx[m_mosaic][2]+m_mosaic_count;

	index_mosaic_warped(Col*3,Row,Col,Row, warp_data,temp_warped_image); 

	tracked_bitmap.SetBitmapBits(Col*Row,temp_warped_image); 
	dcmem.SelectObject(&tracked_bitmap);
	mydc->BitBlt(offset_x+600,offset_y+225,bm.bmWidth,bm.bmHeight,&dcmem,0,0,SRCCOPY);
	
	unsigned char* disp_img = new unsigned char[Col*Row];
	for(c=0;c<Col*Row; c++) disp_img[c]=0;
	
	
	show_warped(Col*3,Row,Col,Row, warp_data,temp_image, disp_img); 
	tracked_bitmap.SetBitmapBits(Col*Row,disp_img); 
	dcmem.SelectObject(&tracked_bitmap);
	mydc->BitBlt(offset_x+600,offset_y,bm.bmWidth,bm.bmHeight,&dcmem,0,0,SRCCOPY);


	DifferenceImage(disp_img, temp_warped_image, Col, Row);
	/*
	int minimum=10000000;
	ThresholdDiffImage(0,Col,Row);
	int dif = CalcDiff(img3,Col,Row,1);
	//SetDlgItemInt(IDC_min,dif);
	int dis_x=0;
	
	while(dif<minimum)
	{
		minimum=dif;
		dis_x++;
		for(int ka=0;ka<6;ka++) warp_data[ka]=matrx[dis_x+m_mosaic][ka];
		index_mosaic_warped(Col*3,Row,Col,Row, warp_data,temp_warped_image); 
		DifferenceImage(disp_img, temp_warped_image, Col, Row);
		ThresholdDiffImage(0,Col,Row);
		dif = CalcDiff(img3,Col,Row,1);						
	}
		
	
	for(ka=0;ka<6;ka++) warp_data[ka]=matrx[m_mosaic+dis_x-1][ka];
	index_mosaic_warped(Col*3,Row,Col,Row, warp_data,temp_warped_image); 
	DifferenceImage(disp_img, temp_warped_image, Col, Row);
	dif = CalcDiff(img3,Col,Row,1);						
	SetDlgItemInt(IDC_min,dif);

	//unsigned char* junk = new unsigned char[Col*Row];
	//cluster_moving_objects(img3,junk,Col, Row,m_thresh,2);
	//delete []junk;
	
	*/
	tracked_bitmap.SetBitmapBits(Col*Row,img3); 
	dcmem.SelectObject(&tracked_bitmap);
	mydc->BitBlt(offset_x+600,offset_y+460,bm.bmWidth,bm.bmHeight,&dcmem,0,0,SRCCOPY);
	
	spatio_temporal_filter(disp_img, temp_warped_image, warp_data, 0.0625);
	/*
	if(show_emos==true)
	{
		mosaic_bitmap.SetBitmapBits(Col*Row*3,err_mosaic); 
		dcmem.SelectObject(&mosaic_bitmap);
		BITMAP bm_mos;
		GetObject(hbitmap_mos,sizeof(BITMAP),&bm_mos);
		mydc->BitBlt(offset_x-30,offset_y+450,bm_mos.bmWidth,bm_mos.bmHeight,&dcmem,0,0,SRCCOPY);
	}
	else
	{
		mosaic_bitmap.SetBitmapBits(Col*Row*3,img_mosaic); 
		dcmem.SelectObject(&mosaic_bitmap);
		BITMAP bm_mos;
		GetObject(hbitmap_mos,sizeof(BITMAP),&bm_mos);
		mydc->BitBlt(offset_x-30,offset_y+450,bm_mos.bmWidth,bm_mos.bmHeight,&dcmem,0,0,SRCCOPY);
	}
	*/
	/*unsigned char* warp_image = new unsigned char[Col*Row];
	for(int w=0;w<Col*Row;w++)warp_image[w]=0;
	iwarp(store_dx[m_mosaic]+m_mosaic_count, mos_r, mos_alpha, mos_beta, warp_image, img4, Col, Row);

	DifferenceImage(temp_image, img4, Col, Row);
	tracked_bitmap.SetBitmapBits(Col*Row,img3); 
	dcmem.SelectObject(&tracked_bitmap);
	mydc->BitBlt(offset_x,offset_y+460,bm.bmWidth,bm.bmHeight,&dcmem,0,0,SRCCOPY);

	
	
	DifferenceImage(temp_image, warp_image, Col, Row);
	tracked_bitmap.SetBitmapBits(Col*Row,warp_image); 
	dcmem.SelectObject(&tracked_bitmap);
	mydc->BitBlt(offset_x+600,offset_y,bm.bmWidth,bm.bmHeight,&dcmem,0,0,SRCCOPY);
	*/
	  //int d1 = CalcDiff(img3,Col,Row,1);
	//memcpy(temp_err_image,img3,Col*Row);

	//index_error_mosaic(Col*3, Row, Col, Row, ceil(store_dx[m_mosaic]+m_mosaic_count),shift_y);
	//tracked_bitmap.SetBitmapBits(Col*Row,img4); 
	//dcmem.SelectObject(&tracked_bitmap);
	//mydc->BitBlt(offset_x+600,offset_y+225,bm.bmWidth,bm.bmHeight,&dcmem,0,0,SRCCOPY);
	
	//SetDlgItemInt(IDC_shift,m_thresh);
	
	//DifferenceImage(img3, img4, Col, Row);
	//int d2 = CalcDiff(img3,Col,Row,1);
	//if(d1<d2) cluster_moving_objects(temp_err_image, img4, Col, Row,m_thresh,2);
	//else cluster_moving_objects(img3, img4, Col, Row,m_thresh,2);
	//memcpy(img3,temp_err_image,Col*Row);
	//cluster_moving_objects(temp_err_image, img4, Col, Row,m_thresh,2);
	//int x_com=find_com(img3,Col,Row);
	//SetDlgItemInt(IDC_COM,panAngle);
	/*ThresholdDiffImage(m_thresh,Col,Row);
	tracked_bitmap.SetBitmapBits(Col*Row,img3); 
	dcmem.SelectObject(&tracked_bitmap);
	mydc->BitBlt(offset_x+600,offset_y+460,bm.bmWidth,bm.bmHeight,&dcmem,0,0,SRCCOPY);
	*/
	/*	

	if(show_emos==true)
	{
		mosaic_bitmap.SetBitmapBits(Col*Row*3,err_mosaic); 
		dcmem.SelectObject(&mosaic_bitmap);
		BITMAP bm_mos;
		GetObject(hbitmap_mos,sizeof(BITMAP),&bm_mos);
		mydc->BitBlt(offset_x-30,offset_y+450,bm_mos.bmWidth,bm_mos.bmHeight,&dcmem,0,0,SRCCOPY);
	}
	else
	{
		mosaic_bitmap.SetBitmapBits(Col*Row*3,img_mosaic); 
		dcmem.SelectObject(&mosaic_bitmap);
		BITMAP bm_mos;
		GetObject(hbitmap_mos,sizeof(BITMAP),&bm_mos);
		mydc->BitBlt(offset_x-30,offset_y+450,bm_mos.bmWidth,bm_mos.bmHeight,&dcmem,0,0,SRCCOPY);
	}
		
	*/
	

	delete []temp_image;
	//delete []temp_err_image;
	//delete []warp_image;
	delete []temp_warped_image;
	delete []disp_img;
	//panAngle = track_moving_object();	

}

//Gets the part of the image with Left Top Corner coords (s_x,s_y) from the mosaic
//and stores it in img4
void CBitmapDlg::index_mosaic(int B, int H, int b, int h, float s_x, float s_y)
{
	for (int i=0; i<B; i++)
		for (int j=0; j<H; j++)
			if(i>=s_x && i< s_x+b && j>=s_y && j<=s_y+h)
			{
				int img_indx = ind(i-s_x,j-s_y,b);
				int mosaic_indx = ind(i,j,B);	
				img4[img_indx]=img_mosaic[mosaic_indx];
			}
}

void CBitmapDlg::reshape_camera_input(int B, int H, int b, int h, float s_x, float s_y, unsigned char *im_ptr, unsigned char *pt )

{
	for (int i=0; i<B; i++)
		for (int j=0; j<H; j++)
			if(i>=s_x && i< s_x+b && j>=s_y && j<=s_y+h)
			{
				int img_indx = ind(i-s_x,j-s_y,b);
				int mosaic_indx = ind(i,j,B);	
				pt[img_indx]=im_ptr[mosaic_indx];
			}
}

void CBitmapDlg::index_error_mosaic(int B, int H, int b, int h, float s_x, float s_y)
{
	for (int i=0; i<B; i++)
		for(int j=0; j<H; j++)
			if(i>=s_x && i< s_x+b && j>=s_y && j<=s_y+h)
			{
				int img_indx = ind(i-s_x,j-s_y,b);
				int mosaic_indx = ind(i,j,B);	
				img4[img_indx]=err_mosaic[mosaic_indx];
			}
}

void CBitmapDlg::index_image(int b, int h, int s_x, int s_y, unsigned char* img_new, unsigned char* img_orig)
{
	for (int i=0; i<b; i++)
		for (int j=0; j<h; j++)
			if(i>=s_x && i< s_x+b && j>=s_y && j<=s_y+h)
			{
				int img_new_indx = ind(i-s_x,j-s_y,b);
				int img_orig_indx = ind(i,j,b);	
				img_new[img_new_indx]=img_orig[img_orig_indx];
			}
}


void CBitmapDlg::OnChangeFeature() 
{
	// TODO: If this is a RICHEDIT control, the control will not
	// send this notification unless you override the CDialog::OnInitDialog()
	// function and call CRichEditCtrl().SetEventMask()
	// with the ENM_CHANGE flag ORed into the mask.
	
	// TODO: Add your control notification handler code here
	UpdateData(TRUE);
}

void CBitmapDlg::OnChangeUpdateFeature() 
{
	// TODO: If this is a RICHEDIT control, the control will not
	// send this notification unless you override the CDialog::OnInitDialog()
	// function and call CRichEditCtrl().SetEventMask()
	// with the ENM_CHANGE flag ORed into the mask.
	
	// TODO: Add your control notification handler code here
	UpdateData(TRUE);
	
}

void CBitmapDlg::Onshift() 
{
	// TODO: Add your control notification handler code here
	
}

// Generates the difference image (img3)
void CBitmapDlg::DifferenceImage(unsigned char *image1, unsigned char *image2, int b, int h)
{
	for(int i=0;i<b;i++)
		for(int j=0;j<h;j++)
		{
			int indx=ind(i,j,b);
			img3[indx] = abs(image1[indx]-image2[indx]);
		}
}

// Generates the thresholded difference image (img3)
void CBitmapDlg::ThresholdDiffImage(int thresh, int b, int h)
{
	for(int i=0;i<b;i++)
		for(int j=0;j<h;j++)
		{
			int indx=ind(i,j,b);
			if(img3[indx]<thresh) img3[indx]=0;
		}
}


// Counts the number of mismatches in a difference image..k defines the block size
int CBitmapDlg::CalcDiff(unsigned char *image, int b, int h, int k)
{
	int count=0;
	for(int a_x=k; a_x<b-k; a_x++)
			for(int a_y=k; a_y<h-k; a_y++)
			{
				int m1 = ind(a_x,a_y,b);
				if(image[m1]>0)
				{
					/*int m2 = ind(a_x-k,a_y,b);
					int m3 = ind(a_x,a_y-k,b);
					int m4 = ind(a_x+k,a_y,b);
					int m5 = ind(a_x,a_y+k,b);
					if(image[m2]>0 && image[m3]>0 && image[m4]>0 && image[m5]>0) count++;*/
					count++;
					
				}
			}
 	return(count);
}
					
						

			

void CBitmapDlg::OnStopAll() 
{
	// TODO: Add your control notification handler code here
	/*if (img1!=NULL) free(img1);
	if (img3!=NULL) free(img3);
	if (img4!=NULL) free(img4);
	if (img2!=NULL) free(img2);
	if (img_morph!=NULL) free(img_morph);
	if (img_mosaic!=NULL) free(img_mosaic);	
	//if (temp_image!=NULL) free(temp_image);	*/
	OnClose();
}

void CBitmapDlg::OnChangeThreshold() 
{
	// TODO: If this is a RICHEDIT control, the control will not
	// send this notification unless you override the CDialog::OnInitDialog()
	// function and call CRichEditCtrl().SetEventMask()
	// with the ENM_CHANGE flag ORed into the mask.
	
	// TODO: Add your control notification handler code here

		UpdateData(TRUE);
}

void CBitmapDlg::OnHome() 
{
	
	tiltAngle = -10;
	panAngle = start_panAngle;
	panTilt->SetPositionAbs(panAngle, TILT);
	panTilt->SetPositionAbs(tiltAngle, PAN);
	//panTilt->GoHome(PAN);
	//panTilt->GoHome(TILT);
	return;
}

void CBitmapDlg::OnPanLeft() 
{
	// TODO: Add your control notification handler code here
	if(panAngle >= -85)
	{
		panAngle--;
		panTilt->SetPositionAbs(panAngle, TILT);
	}

  return;
  
}

void CBitmapDlg::OnPanRight() 
{
	// TODO: Add your control notification handler code here
	if(panAngle <= 85)
	{
		panAngle++;
		panTilt->SetPositionAbs(panAngle, TILT);
	}
	return;
}

void CBitmapDlg::OnErrMosaic() 
{
	// TODO: Add your control notification handler code here
	//	UpdateData(TRUE);	
/*	for (int count_down=m_mosaic-1;count_down>=0;count_down--)
	{
		
		SetDlgItemInt(IDC_Servo_Pos,count_down);	
		panTilt->SetPositionAbs((-(count_down-1)), TILT);
	
		for(int tm=0;tm<5000;tm++)
			for(int tj=0;tj<10000;tj++);


		index_mosaic(Col*3, Row, Col, Row, m_mosaic*5,shift_y);
		unsigned char* temp_image1=new unsigned char[Row*Col];
		GrabImage(temp_image1,Col*Row);
		DifferenceImage(temp_image1, img4, Col, Row);
		fill_error_mosaic(Col*3,Row,Col,Row,count_down*5,0,img3);
		
		mosaic_bitmap.SetBitmapBits(Col*Row*3,err_mosaic); 
		dcmem.SelectObject(&mosaic_bitmap);
		BITMAP bm_mos;
		GetObject(hbitmap_mos,sizeof(BITMAP),&bm_mos);
		mydc->BitBlt(offset_x-30,offset_y+450,bm_mos.bmWidth,bm_mos.bmHeight,&dcmem,0,0,SRCCOPY);
	
		delete [] temp_image1;
	}
	
*/	
}

void CBitmapDlg::OnMosButton4() 
{
	// TODO: Add your control notification handler code here

	//for (int count_down=0;count_down<=m_mosaic-1;count_down++)
	for (int count_down=i-1;count_down>=0;count_down--)
	{
		
		SetDlgItemInt(IDC_Servo_Pos,count_down);	
		panTilt->SetPositionAbs((start_panAngle-(count_down)), TILT);
	
		for(int tm=0;tm<500;tm++)
			for(int tj=0;tj<10000;tj++);


		unsigned char* temp_image=new unsigned char[Row*Col];
		GrabImage(temp_image,Col*Row);
	
	
		unsigned char* temp_warped_image=new unsigned char[Row*Col];
	
		float warp_data[6];
		for(int c=0;c<Col*Row; c++) temp_warped_image[c]=0;
		for(int ka=0;ka<6;ka++) warp_data[ka]=matrx[m_mosaic+m_mosaic_count][ka];
		index_mosaic_warped(Col*3,Row,Col,Row, warp_data,temp_warped_image); 

	
		unsigned char* disp_img = new unsigned char[Col*Row];
		for(c=0;c<Col*Row; c++) disp_img[c]=0;
	
	
		show_warped(Col*3,Row,Col,Row, warp_data,temp_image, disp_img); 
		DifferenceImage(disp_img, temp_warped_image, Col, Row);
		
		put_error_mosaic_warped(Col*3,Row,Col,Row, warp_data, img3) ;
	
		mosaic_bitmap.SetBitmapBits(Col*Row*3,err_mosaic); 
		dcmem.SelectObject(&mosaic_bitmap);
		BITMAP bm_mos;
		GetObject(hbitmap_mos,sizeof(BITMAP),&bm_mos);
		mydc->BitBlt(offset_x-30,offset_y+450,bm_mos.bmWidth,bm_mos.bmHeight,&dcmem,0,0,SRCCOPY);

		delete []temp_image;
		delete []temp_warped_image;
		delete []disp_img;




		/*index_mosaic(Col*3, Row, Col, Row,ceil(store_dx[count_down]),shift_y);
		unsigned char* temp_image1=new unsigned char[Row*Col];
		GrabImage(temp_image1,Col*Row);
		
		tracked_bitmap.SetBitmapBits(Col*Row,temp_image1); 
		dcmem.SelectObject(&tracked_bitmap);
		BITMAP bm;
		GetObject(hbitmap,sizeof(BITMAP),&bm);
		mydc->BitBlt(offset_x,offset_y,bm.bmWidth,bm.bmHeight,&dcmem,0,0,SRCCOPY);
	
		
		
		
		DifferenceImage(temp_image1, img4, Col, Row);
		fill_error_mosaic(Col*3,Row,Col,Row,ceil(store_dx[count_down]),0,img3);
		
		mosaic_bitmap.SetBitmapBits(Col*Row*3,err_mosaic); 
		dcmem.SelectObject(&mosaic_bitmap);
		BITMAP bm_mos;
		GetObject(hbitmap_mos,sizeof(BITMAP),&bm_mos);
		mydc->BitBlt(offset_x-30,offset_y+450,bm_mos.bmWidth,bm_mos.bmHeight,&dcmem,0,0,SRCCOPY);
	
		delete [] temp_image1;
		*/
	}
	

}

void CBitmapDlg::OnIMos() 
{
	// TODO: Add your control notification handler code here
	
	show_emos=false;
}

void CBitmapDlg::OnEMos() 
{
	// TODO: Add your control notification handler code here
	show_emos=true;	
}

void CBitmapDlg::move_to(int angle_initial, int angle_final)
{
	int angle_to_move = angle_final-angle_initial;
	int fraction = abs(floor(angle_to_move/5));

	for(int i=1;i<=fraction;i++)
	{
		if(angle_to_move<0) panTilt->SetPositionAbs((angle_initial-5*i), TILT);
		else panTilt->SetPositionAbs((angle_initial+5*i), TILT);

		for(int tm=0;tm<500;tm++)
			for(int tj=0;tj<10000;tj++);
	}

	panTilt->SetPositionAbs((angle_final), TILT);
		for(int tm=0;tm<5000;tm++)
			for(int tj=0;tj<10000;tj++);

}

void CBitmapDlg::cluster_moving_objects(unsigned char* diff_image, unsigned char* err_mos_image, int b, int h, int thresh, int k)
{
	for(int a_x=k; a_x<b-k; a_x++)
		for(int a_y=k; a_y<h-k; a_y++)
		{
			int m1 = ind(a_x,a_y,b);
			if(diff_image[m1]>thresh)
			{
				//int thresh1 = thresh+err_mos_image[m1];
				int thresh1 = thresh;
				int m2 = ind(a_x-k,a_y,b);
				int m3 = ind(a_x,a_y-k,b);
				int m4 = ind(a_x+k,a_y,b);
				int m5 = ind(a_x,a_y+k,b);
				if(diff_image[m2]>thresh1 && diff_image[m2]>thresh1 && diff_image[m3]>thresh1 && diff_image[m4]>thresh1 && diff_image[m5]>thresh1) 
				img3[m1]=255;
			}
		}
/*
	for(a_x=k; a_x<b-k; a_x++)
		for(int a_y=k; a_y<h-k; a_y++)
		{
			int m1 = ind(a_x,a_y,b);
			if(img3[m1]==255)
			{
				int m2 = ind(a_x-k,a_y,b);
				int m3 = ind(a_x,a_y-k,b);
				int m4 = ind(a_x+k,a_y,b);
				int m5 = ind(a_x,a_y+k,b);
				if(img3[m2]<255 || img3[m3]<255 || img3[m4]<255 || img3[m5]<255) 
				img3[m1]=0;
			}
		}
*/
}

int CBitmapDlg::find_com(unsigned char* diff_img, int b, int h)
{
	int x_pos=0;
	int cnt=0;
	for(int a_x=0; a_x<b; a_x++)
		for(int a_y=0; a_y<h; a_y++)
		{
			int m1 = ind(a_x,a_y,b);
			if(diff_img[m1]==255)
			{
				x_pos+=a_x;
				cnt++;
			}
		}
	if(cnt>100)return(x_pos/cnt);
	else return(b/2);
}


int CBitmapDlg::track_moving_object()
{
	

	if(dont_track==false)
	{
		
		unsigned char* temp_image=new unsigned char[Row*Col];
		unsigned char* temp_err_image=new unsigned char[Row*Col];
		GrabImage(temp_image,Col*Row);
		tracked_bitmap.SetBitmapBits(Col*Row,temp_image); 
		BITMAP bm;
		GetObject(hbitmap,sizeof(BITMAP),&bm);
		dcmem.SelectObject(&tracked_bitmap);
		mydc->BitBlt(offset_x,offset_y,bm.bmWidth,bm.bmHeight,&dcmem,0,0,SRCCOPY);
		//spatio_temporal_filter(temp_image,ceil(store_dx[start_panAngle-panAngle]),0.0625);

		index_mosaic(Col*3, Row, Col, Row, ceil(store_dx[start_panAngle-panAngle]),shift_y);
		tracked_bitmap.SetBitmapBits(Col*Row,img4); 
		dcmem.SelectObject(&tracked_bitmap);
		mydc->BitBlt(offset_x+600,offset_y+225,bm.bmWidth,bm.bmHeight,&dcmem,0,0,SRCCOPY);

		DifferenceImage(temp_image, img4, Col, Row);
		tracked_bitmap.SetBitmapBits(Col*Row,img3); 
		dcmem.SelectObject(&tracked_bitmap);
		mydc->BitBlt(offset_x+600,offset_y,bm.bmWidth,bm.bmHeight,&dcmem,0,0,SRCCOPY);
		int d1 = CalcDiff(img3,Col,Row,1);
		memcpy(temp_err_image,img3,Col*Row);

		index_error_mosaic(Col*3, Row, Col, Row, ceil(store_dx[start_panAngle-panAngle]),shift_y);
		//tracked_bitmap.SetBitmapBits(Col*Row,img4); 
		//dcmem.SelectObject(&tracked_bitmap);
		//mydc->BitBlt(offset_x+600,offset_y+225,bm.bmWidth,bm.bmHeight,&dcmem,0,0,SRCCOPY);
	
		//SetDlgItemInt(IDC_shift,m_thresh);
		DifferenceImage(img3, img4, Col, Row);
		int d2 = CalcDiff(img3,Col,Row,1);
	
		//if(d1<d2) cluster_moving_objects(temp_err_image, img4, Col, Row,m_thresh,2);
		//else cluster_moving_objects(img3, img4, Col, Row,m_thresh,2);
		memcpy(img3,temp_err_image,Col*Row);
		cluster_moving_objects(temp_err_image, img4, Col, Row,m_thresh,2);
		int x_com=find_com(img3,Col,Row);
		panTilt->SetPositionAbs(panAngle+((Col/2)-x_com)/5, TILT);
		panAngle = panAngle+((Col/2)-x_com)/5;
		SetDlgItemInt(IDC_COM,panAngle);
		
		for(int tm=0;tm<750;tm++)
			for(int tj=0;tj<10000;tj++);

		
		//ThresholdDiffImage(m_thresh,Col,Row);
		tracked_bitmap.SetBitmapBits(Col*Row,img3); 
		dcmem.SelectObject(&tracked_bitmap);
		mydc->BitBlt(offset_x+600,offset_y+460,bm.bmWidth,bm.bmHeight,&dcmem,0,0,SRCCOPY);
		delete []temp_image;
		delete []temp_err_image;

		return(panAngle);
	}
}

void CBitmapDlg::OnTrackOn() 
{
	// TODO: Add your control notification handler code here
	track=true;
	dont_track=false;
	for(int ii=0;ii<100;ii++)
	{
		if(panAngle<start_panAngle && panAngle>= -i)
		panAngle = track_moving_object();	
		if(panAngle>start_panAngle || panAngle<-i)
		{
			panTilt->SetPositionAbs(-10,TILT);
			panAngle=-10;
		}
	}
}

void CBitmapDlg::OnTrackOff() 
{
	// TODO: Add your control notification handler code here
	dont_track=true;	
	track=false;
	int counter=0;
	while(counter<2)
	{
		for (int count_down=0;count_down<=i-1;count_down++)
		{
		
			SetDlgItemInt(IDC_Servo_Pos,count_down);	
			panTilt->SetPositionAbs((start_panAngle-(count_down)), TILT);
	
			for(int tm=0;tm<5000;tm++)
				for(int tj=0;tj<10000;tj++);


			//index_mosaic(Col*3, Row, Col, Row,ceil(store_dx[count_down]),shift_y);
			unsigned char* temp_image1=new unsigned char[Row*Col];
			GrabImage(temp_image1,Col*Row);
			tracked_bitmap.SetBitmapBits(Col*Row,temp_image1); 
			dcmem.SelectObject(&tracked_bitmap);
			BITMAP bm;
			GetObject(hbitmap,sizeof(BITMAP),&bm);
			mydc->BitBlt(offset_x,offset_y,bm.bmWidth,bm.bmHeight,&dcmem,0,0,SRCCOPY);
		
			//spatio_temporal_filter(temp_image1,ceil(store_dx[count_down]),0.0625);
			
		
			//DifferenceImage(temp_image1, img4, Col, Row);
			//fill_error_mosaic(Col*3,Row,Col,Row,ceil(store_dx[count_down]),0,img3);
		
			mosaic_bitmap.SetBitmapBits(Col*Row*3,img_mosaic); 
			dcmem.SelectObject(&mosaic_bitmap);
			BITMAP bm_mos;
			GetObject(hbitmap_mos,sizeof(BITMAP),&bm_mos);
			mydc->BitBlt(offset_x-30,offset_y+450,bm_mos.bmWidth,bm_mos.bmHeight,&dcmem,0,0,SRCCOPY);
		
			delete [] temp_image1;
		}
	counter++;
	}

}

void CBitmapDlg::spatio_temporal_filter(unsigned char* I, unsigned char* Mos, float *warp_data, float alpha)
{
	unsigned char* M = new unsigned char[Col*Row];
	for(int c_x=0;c_x<Col;c_x++)
		for(int c_y=0;c_y<Row;c_y++)
		{
			int indx=ind(c_x,c_y,Col);
	
			if(I[indx]>Mos[indx])
				M[indx]= Mos[indx]+ alpha*(I[indx]-Mos[indx]);
			else
				M[indx]= Mos[indx] - alpha*(Mos[indx]-I[indx]); 
			
			
		}
	
	put_mosaic_warped(Col*3,Row,Col,Row,warp_data,M);
	//fill_mosaic(Col*3,Row,Col,Row,warp_data[2],0,M);
	delete []M;
}

/*
void CBitmapDlg::spatio_temporal_filter(unsigned char* I, int spatial_pos, float alpha)
{
	int * E = new int[Col*Row];
	unsigned char *Err = new unsigned char[Col*Row];
	int * delta_E = new int[Col*Row];
	unsigned char * delta_Err = new unsigned char[Col*Row];
	unsigned char * delta_Err1 = new unsigned char[Col*Row];
	unsigned char * M = new unsigned char[Col*Row];
	unsigned char * M1 = new unsigned char[Col*Row];
	unsigned char * Mos = new unsigned char[Col*Row];

	index_mosaic(Col*3, Row, Col, Row, spatial_pos,shift_y);
	memcpy(Mos,img4,Col*Row);		//Mos stores the mosaic image
	index_error_mosaic(Col*3, Row, Col, Row, spatial_pos,shift_y);
	memcpy(Err,img4,Col*Row);		//Err stores the mosaic image
	
	
	for(int c_x=0;c_x<Col;c_x++)
		for(int c_y=0;c_y<Row;c_y++)
		{
			int indx=ind(c_x,c_y,Col);
	
			if(I[indx]>Mos[indx])
				M[indx]= Mos[indx]+ alpha*(I[indx]-Mos[indx]);
			else
				M[indx]= Mos[indx] - alpha*(Mos[indx]-I[indx]); 
			
			
			if(I[indx]>Mos[indx])
			{
				if(Err[indx] >30) 
				{
					if(Err[indx] > I[indx]-Mos[indx])
					{
						if(Err[indx]-(I[indx]-Mos[indx])<25)
						M[indx]= I[indx];
						else
						M[indx]= Mos[indx]+ alpha*(I[indx]-Mos[indx]);
					}
					else
					{
						if((I[indx]-Mos[indx])-Err[indx]<25)
						M[indx]= I[indx];
						else
						M[indx]= Mos[indx]+ alpha*(I[indx]-Mos[indx]);
					}
				}

				else M[indx]= Mos[indx]+ alpha*(I[indx]-Mos[indx]);

			}

			
			else 
			{
				if(Err[indx] >30) 
				{
					if(Err[indx] > Mos[indx]-I[indx])
					{
						if(Err[indx]-(Mos[indx]-I[indx])<25)
						M[indx]= I[indx];
						else
						M[indx]= Mos[indx]+ alpha*(Mos[indx]-I[indx]);
					}
					else
					{
						if((Mos[indx]-I[indx])-Err[indx]<25)
						M[indx]= I[indx];
						else
						M[indx]= Mos[indx]+ alpha*(Mos[indx]-I[indx]);
					}
				}

				else M[indx]= Mos[indx] - alpha*(Mos[indx]-I[indx]); 
			}
			

		}
	

	for(int zx=0;zx<Col*Row;zx++)
	{
		if(M[zx]>=0 && M[zx]<255) M1[zx]=M[zx];
		else M1[zx]=img4[zx];
	}
	
	fill_mosaic(Col*3,Row,Col,Row,spatial_pos,0,M1);
	
	
	
	for(int c=0;c<Col*Row;c++) delta_Err[c]=0;
	for(int d_x=0;d_x<Col;d_x++)
		for(int d_y=0;d_y<Row;d_y++)
		{
			int indx=ind(d_x,d_y,Col);
			
			if(I[indx]>Mos[indx])
				delta_Err[indx]= Err[indx]+ (alpha)*(I[indx]-Mos[indx]);
			else 
			{
				if(Err[indx] > (alpha)*(Mos[indx]-I[indx]))
				delta_Err[indx]=Err[indx] - (alpha)*(Mos[indx]-I[indx]); 
				else 
				//delta_Err[indx]=Err[indx];
				delta_Err[indx]=0;
			}


		}
	
	for(int cx=0;cx<Col*Row;cx++)
	{
		if(delta_Err[cx]>=0) delta_Err1[cx]=delta_Err[cx];
		else delta_Err1[cx]=0;
	}
	
	//fill_error_mosaic(Col*3,Row,Col,Row,spatial_pos,0,delta_Err1);
	



	delete [] E;
	delete [] delta_E;
	delete [] delta_Err;
	delete [] delta_Err1;
	delete [] M;
	delete [] M1;
	delete [] Err;
	delete [] Mos;
}

*/

void CBitmapDlg::DifferenceCharImage(unsigned char *image1, unsigned char *image2, int result[], int b, int h)
{
	for(int i=0;i<b;i++)
		for(int j=0;j<h;j++)
		{
			int indx=ind(i,j,b);
			result[indx] = (image1[indx]-image2[indx]);
		}
}

void CBitmapDlg::OnMosaicInc() 
{
	// TODO: Add your control notification handler code here
m_mosaic_count++;	
}

void CBitmapDlg::OnMosaicDec() 
{
	// TODO: Add your control notification handler code here
	
m_mosaic_count--;
}


void CBitmapDlg::OnRadio3() 
{
	// TODO: Add your control notification handler code here
	mosaic_shift=true;
	
}

void CBitmapDlg::OnRadio4() 
{
	// TODO: Add your control notification handler code here
	mosaic_shift=false;
	
}

void CBitmapDlg::calc_warp_params(float d, float theta)
{
	fstream ft1;
	ft1.open("e:\\kiran\\klt\\try\\warp.out",ios::out|ios::app);
	mos_r = d/theta;
	//mos_r=425;
	mos_alpha = atan2((double)Col/2.0,(double)mos_r);
	mos_beta = atan2((double)Row/2.0,(double)mos_r);
	ft1<<"mos_r"<<mos_r<<"\t"<<"mos_alpha"<<(mos_alpha)<<endl;
	ft1.close();
}

void CBitmapDlg::iwarp(int d_ini, float r, double alpha, double beta, unsigned char image[], unsigned char* img_mos, int b, int h)
{
	fstream ft;
	ft.open("e:\\kiran\\klt\\try\\warp.out",ios::out|ios::app);
	int n=0;
	unsigned char* img = new unsigned char[Col*Row];
	
	for(int d_y=0;d_y<h;d_y++)
	{
		n=0;
		float d_theta=0;
		float cumul_di=0;
		for(int d_x=0;d_x<b;d_x++)
		{
			int index = ind(d_x,d_y,b);
			int pos_left = floor(cumul_di);
			int pos_right = ceil(cumul_di);
			float decim= cumul_di - pos_left;
			int val_left = ind(pos_left,d_y,b);
			int val_right = ind(pos_right,d_y,b);
			img[index] = ((1-decim)*img_mos[val_left] + decim*img_mos[val_right]);
			//image[index] = 0.5*img_mos[val_left]+0.5*img_mos[val_right];
			
			//ft<<d_y<<"\t"<<d_x<<"\t"<<cumul_di<<"\t";
			float angle = sin( pi/2 - alpha + d_theta);
			float den = sqrt( r*r + (b/2 - (n+1)*1)*(b/2 - (n+1)*1) );
			float d_i = r*(1)*angle/den;
			//float d_i = r*(1)/den;
			//ft<<d_i<<endl;
			cumul_di += d_i;
			d_theta += d_i/r;
			n++;
		}
	}

	memcpy(image,img,Col*Row);
	/*
	for(int d_x=0;d_x<b;d_x++)
	{
		n=0;
		float d_theta=0;
		float cumul_di=0;
		for(int d_y=50;d_y<150;d_y++)
		{
			int index = ind(d_x,d_y,b);
			int pos_left = floor(cumul_di);
			int pos_right = ceil(cumul_di);
			float decim= cumul_di - pos_left;
			int val_left = ind(d_x,pos_left,b);
			int val_right = ind(d_x,pos_right,b);
			image[index] = ((1-decim)*img[val_left] + decim*img[val_right]);
			float angle = sin( pi/2 - beta + d_theta);
			float den = sqrt( r*r + (h/2 - (n+1)*1)*(h/2 - (n+1)*1) );
			float d_i = r*(1)*angle/den;
			//float d_i = r*(1)/den;
			//ft<<d_i<<endl;
			cumul_di += d_i;
			d_theta += d_i/r;
			n++;
		}
	}*/

	delete []img;	
	
	ft.close();
}


void CBitmapDlg::initialise_matrixA(int size, float *x1, float *x2, float A[]) 
{
	int j=0;
	for(int i=0; i<size; i++)
	{
		A[j] = x1[i];
		A[j+1] = x2[i];
		A[j+2] = 1;
		j=j+3;
	}
}

void CBitmapDlg::initialise_matrixb(int size, float *y, float b[]) 
{

	for (int i=0; i<size; i++)
	{
		b[i] = y[i];
	}
}



//Implements Gradient descent algo.
//Input (x,y) coordinates are x1 and x2
//Output(x',y') coordinates are y and z
// Finds a,b,c,d,e,f such that
//		[y ]		[ a	b e ]   [ x1]
//		|z |  =	    | c d f | * | x2|
//		[1 ]		[ 0 0 1 ]	[ 1 ]
//


void CBitmapDlg::gradient_descent(int size, float *y, float *z, float *x1, float *x2, float res[]) 
{

	fstream fptr;
	fptr.open("e:\\kiran\\klt\\try\\grad_descent.out",ios::out|ios::app);

	float a = 1.0;
	float b = 0.0;
	float c = 0.0;
	float d = 1.0;	
	float e = 0.0;
	float f = 0.0;

	float diff1=0;
	float diff2=0;

	for(int i=0; i<size; i++)
	{
		diff1 += y[i] - x1[i];
		diff2 += z[i] - x2[i];
	}
	
	e = diff1/size;
	f = diff2/size;

	res[0]=a;
	res[1]=b;
	res[2]=e;
	res[3]=c;
	res[4]=d;
	res[5]=f;
	
	float eta = 0.0000005;
	float eta1 = 0.0000005;
	float delta_old_r1=0;
	float delta_old_r2=0;


	for(int n=0; n<50;n++)
	{

		float delta_r1=0;
		float delta_r2=0;
   
		for(int i=0;i<size;i++)
		{
			delta_r1 = y[i]-(a*x1[i] + b*x2[i] + e);
			delta_r2 = z[i]-(c*x1[i] + d*x2[i] + f);
			a = a + eta*delta_r1*x1[i];
			b = b + eta*delta_r1*x2[i];
			e = e + eta*delta_r1;
      
			c = c + eta1*delta_r2*x1[i];
			d = d + eta1*delta_r2*x2[i];
			f = f + eta1*delta_r2;
		}

		if (abs(delta_r1)<=abs(delta_old_r1))
		    eta = 1.05*eta;
		else
	        eta = (0.95)*eta;
   
		delta_old_r1 = delta_r1;
   
		if (abs(delta_r2)<=abs(delta_old_r2))
			eta1 = 1.5*eta1;
		else
			eta1 = (1/3)*eta1;
   
		delta_old_r2 = delta_r2;
		
	}

	if(a<2 && a >0)
	{
		res[0]=a;
		res[1]=b;
		res[2]=e;
		res[3]=c;
		res[4]=d;
		res[5]=f;
	}
	//if(f>2 || f<-2) res[5]=0;
	//res[5]=0;
	fptr.width(12);
	fptr<<a<<"\t"<<"\t"<<b<<"\t"<<"\t"<<c<<"\t"<<"\t"<<d<<"\t"<<"\t"<<e<<"\t"<<"\t"<<f<<endl;
	fptr.close();
}

void CBitmapDlg::update_Matrix(int i, float *res)
{
	
	if(i>0)
	{
		if( (res[0]>0.995 && res[0] <1.005) && (res[1]<0.005 && res[1] > -0.005) && (res[4]>0.995 && res[4] <1.005) && (res[3]<0.005 && res[3] > -0.005))
		{
			matrx[i][0]=res[0] * matrx[i-1][0] + res[1] * matrx[i-1][3];
			matrx[i][1]=res[0] * matrx[i-1][1] + res[1] * matrx[i-1][4];
			matrx[i][2]=res[0] * matrx[i-1][2] + res[1] * matrx[i-1][5] + res[2];
			matrx[i][3]=res[3] * matrx[i-1][0] + res[4] * matrx[i-1][3];
			matrx[i][4]=res[3] * matrx[i-1][1] + res[4] * matrx[i-1][4];
		
			if(abs(Res[5])<1.0)
				matrx[i][5]=res[3] * matrx[i-1][2] + res[4] * matrx[i-1][5] + res[5];
			else
				matrx[i][5]=res[3] * matrx[i-1][2] + res[4] * matrx[i-1][5];

		}
		/*if( (res[0]>0.995 && res[0] <1.005) && (res[1]<0.005 && res[1] > -0.005) && (res[4]>0.995 && res[4] <1.005) && (res[3]<0.005 && res[3] > -0.005) )
		{
			matrx[i][0]=res[0]; 
			matrx[i][1]=res[1];
			matrx[i][2]=res[0] * matrx[i-1][2] + res[1] * matrx[i-1][5] + res[2];
			matrx[i][3]=res[3];
			matrx[i][4]=res[4]; 
			matrx[i][5]=res[3] * matrx[i-1][2] + res[4] * matrx[i-1][5] + res[5];
		}*/
		else
		{
			matrx[i][0] = matrx[i-1][0];
			matrx[i][1] = matrx[i-1][1];
			matrx[i][2] = matrx[i-1][2] + res[2];
			matrx[i][3] = matrx[i-1][3];
			matrx[i][4] = matrx[i-1][4];
			if(abs(Res[5])<1.0)
				matrx[i][5] = matrx[i-1][5] + res[5];
			else
				matrx[i][5] = matrx[i-1][5];

		}

	}
	
	/*if(i%23==0)
	{
		matrx[i][0]=1;
		matrx[i][1]=0;
		matrx[i][3]=0;
		matrx[i][4]=1;
	}
	*/

}

void CBitmapDlg::update_periodic_Matrix(int i, int update_factor, float *res)
{
	
	int j = (int) i/update_factor;

	if(j<=1)
	{
		PMatrix[j][0]=res[0];
		PMatrix[j][1]=res[1];
		PMatrix[j][2]=res[2];
		PMatrix[j][3]=res[3];
		PMatrix[j][4]=res[4];
		PMatrix[j][5]=res[5];
	}

	else
	{
		PMatrix[j][0]=res[0] * PMatrix[j-1][0] + res[1] * PMatrix[j-1][3];
		PMatrix[j][1]=res[0] * PMatrix[j-1][1] + res[1] * PMatrix[j-1][4];
		PMatrix[j][2]=res[0] * PMatrix[j-1][2] + res[1] * PMatrix[j-1][5] + res[2];
		PMatrix[j][3]=res[3] * PMatrix[j-1][0] + res[4] * PMatrix[j-1][3];
		PMatrix[j][4]=res[3] * PMatrix[j-1][1] + res[4] * PMatrix[j-1][4];
		//PMatrix[j][5]=res[3] * PMatrix[j-1][2] + res[4] * PMatrix[j-1][5] + res[5];
		PMatrix[j][5]=0;
	}


	fstream fptr3;
	fptr3.open("e:\\kiran\\klt\\try\\pmatrix.out",ios::out|ios::app);
	fptr3<<j<<"\t"<<PMatrix[j][0]<<"\t"<<PMatrix[j][1]<<"\t"<<PMatrix[j][2]<<"\t"<<PMatrix[j][3]<<"\t"<<PMatrix[j][4]<<"\t"<<PMatrix[j][5]<<"\t"<<endl;
	fptr3.close();
}

void CBitmapDlg::reset_track_status()
{

	for(int st=0;st<300;st++)
	{
		track_status[st]=1;
	}
}

void CBitmapDlg::copy_matrix_pmatrix(int i, int update_factor)
{
	int j = (int) i/update_factor;
	matrx[i][0]=PMatrix[j][0];
	matrx[i][1]=PMatrix[j][0];
	matrx[i][2]=PMatrix[j][0];
	matrx[i][3]=PMatrix[j][0];
	matrx[i][4]=PMatrix[j][0];
	matrx[i][5]=PMatrix[j][0];
}