using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using Microsoft.Win32;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Threading;


namespace SR_interface
{
	/// <summary>
	/// Summary description for Form1.
	/// </summary>
	public class Form1 : System.Windows.Forms.Form
	{
		#region Variable Definitions
		/// <summary>
		/// ============
		/// GENERAL VARs
		/// ============
		/// nSelectedFile			- the index number of the currently selected file. If -1, then no file is selected.
		/// szRequestedFile			- the absolute file path of the requested file name when the app is called (from explorer)
		/// FileArray				- the arraylist storing all the image files within the current folder
		/// FileType				- the arraylist storing all the supported image types
		/// szCurrentDirectory		- the string storing the values of the path of the folder explorer called this app from
		/// rootDirectory			- main directory including dlls
		/// workingStatus			- determines if the dll is still working
		/// useCG					- decides Conjugate Gradient will be used for SR 
		/// useSD					- decides Steepest Descent will be used for SR
		/// </summary>
		
		private int			nSelectedFile = -1;
		private string		szRequestedFile;
		public ArrayList	FileArray;
		private ArrayList	FileTypes;
		public string		szCurrentDirectory;
		public bool hasBeenInitialized=false;
		
		public string rootDirectory;
		public string fileName;
		public int imNameListLength;
		public string imageFolder;
		
		public int sigmaW=1,iterationNumber=1;
		public double Factor=2.0, lambda=.5;
		public double sigmaGauss;
		public int viewMode; // 0-LR mode
							 // 1-SR mode
							 // 2-Upref mode
		public int workingStatus=0; // Initially not working		
		System.Threading.Thread getThread;
		
		int useCG=1, useSD=0;

		string SRbefore;
		string SRafter;

		string SRbeforeRoot;
		string SRafterRoot;

		#endregion

		private System.Windows.Forms.ToolBar toolBar1;
		private System.Windows.Forms.ToolBarButton toolBarButtonOpenImage;
		private System.Windows.Forms.ImageList imageList1;
		private System.Windows.Forms.OpenFileDialog openFileDialog1;
		private System.Windows.Forms.ListBox listBoxImNames;
		private System.Windows.Forms.PictureBox pictureBoxImageSelected;
		private System.Windows.Forms.Panel panel1;
		private System.Windows.Forms.Panel panel2;
		private System.Windows.Forms.Button buttonDeleteImage;
		private System.Windows.Forms.ToolBarButton toolBarPrevious;
		private System.Windows.Forms.ToolBarButton toolBarButtonNext;
		private System.Windows.Forms.Panel panel3;
		private System.Windows.Forms.Label label1;
		private System.Windows.Forms.ComboBox comboBoxGaussSize;
		private System.Windows.Forms.TextBox textBoxGaussSigma;
		private System.Windows.Forms.Label label2;
		private System.Windows.Forms.Label label3;
		private System.Windows.Forms.ToolBarButton toolBarButtonShowSR;
		private System.Windows.Forms.ToolBarButton toolBarButtonUpref;
		private System.Windows.Forms.TextBox textBoxIterNum;
		private System.Windows.Forms.Label label4;
		private System.Windows.Forms.ComboBox comboBoxMagnificationFactor;
		private System.Windows.Forms.Button buttonAddImage;
		private System.Windows.Forms.TextBox textBoxLambda;
		private System.Windows.Forms.MainMenu mainMenu1;
		private System.Windows.Forms.MenuItem menuItemFile;
		private System.Windows.Forms.Label label5;
		private System.Windows.Forms.StatusBar statusBar1;
		private System.Windows.Forms.StatusBarPanel statusBarPanelMessage;
		private System.Windows.Forms.StatusBarPanel statusBarPanelStatus;
		private System.Windows.Forms.SaveFileDialog saveFileDialog1;
		private System.Windows.Forms.MenuItem menuItemSaveSR;
		private System.Windows.Forms.MenuItem menuItemSaveUpref;
		private System.Windows.Forms.Button buttonSaveImage;
		private System.Windows.Forms.Button buttonSaveInitial;
		private System.Windows.Forms.MenuItem menuItemLoadMultiple;
		private System.Windows.Forms.MenuItem menuItemLoadSingle;
		private System.Windows.Forms.Label label6;
		private System.Windows.Forms.GroupBox groupBox1;
		private System.Windows.Forms.RadioButton radioButtonUseCG;
		private System.Windows.Forms.RadioButton radioButtonSD;
		private System.ComponentModel.IContainer components;
		private System.Windows.Forms.Button startButton;
		private System.Windows.Forms.ProgressBar progressBar;


		class loadDLL
		{
			[DllImport("MakeTempFilenameDLL.dll")] 
			public static extern int RetrieveTempFilename(int a, int b,char[] c,double Factor,int sigmaW,double sigma,double lambda, int maxIterN, int useCG);	
		}

		#region new DLL
		GuiCallbackDelegate	callback;	// called from unmanaged code / thread!

		// API imports (from DllApi.h) :
		private delegate int GuiCallbackDelegate( int mode, int val );	// in C++ : GuiCallbackFn

		//				[DllImport( @"E:\P\Interop\UnmanagedThreads\CSharpGuiCppThread\CppDll\Debug\CppDll.dll", ExactSpelling=true, SetLastError=false )]
		[DllImport( @"SRDLL.dll", ExactSpelling=true, SetLastError=false )]
		private static extern int StartTimerThread( GuiCallbackDelegate cb,int a, int b,char[] c,double Factor,int sigmaW,double sigma,double lambda, int maxIterN, int useCG );

		//				[DllImport( @"E:\P\Interop\UnmanagedThreads\CSharpGuiCppThread\CppDll\Debug\CppDll.dll", ExactSpelling=true, SetLastError=false )]
		[DllImport( @"SRDLL.dll", ExactSpelling=true, SetLastError=false )]
		private static extern int StopTimerThread();
		#endregion

        
		public Form1()
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();
			rootDirectory=Directory.GetCurrentDirectory().ToString();

			FileArray = new ArrayList();
			
			loadMainForm();			//Load Image Types to Read

			//Make SR buttons invisible
			toolBar1.Buttons[3].Enabled=false;
			toolBar1.Buttons[4].Enabled=false;	


			//INITIAL PARAMETERS
			iterationNumber=1;
			sigmaGauss=(float)1.0;
			sigmaW=1;
			Factor=2;

			#region newDLL
			updateGuiHandler = new EventHandler( this.OnUpdateGui );		// handler for Control.Invoke
			callback = new GuiCallbackDelegate( this.GuiCallbackHandler );	// handler for C++ callback
			#endregion

			
			//
			// TODO: Add any constructor code after InitializeComponent call
			//
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if (components != null) 
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.components = new System.ComponentModel.Container();
			System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(Form1));
			this.toolBar1 = new System.Windows.Forms.ToolBar();
			this.toolBarButtonOpenImage = new System.Windows.Forms.ToolBarButton();
			this.toolBarPrevious = new System.Windows.Forms.ToolBarButton();
			this.toolBarButtonNext = new System.Windows.Forms.ToolBarButton();
			this.toolBarButtonShowSR = new System.Windows.Forms.ToolBarButton();
			this.toolBarButtonUpref = new System.Windows.Forms.ToolBarButton();
			this.imageList1 = new System.Windows.Forms.ImageList(this.components);
			this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
			this.listBoxImNames = new System.Windows.Forms.ListBox();
			this.pictureBoxImageSelected = new System.Windows.Forms.PictureBox();
			this.panel1 = new System.Windows.Forms.Panel();
			this.panel3 = new System.Windows.Forms.Panel();
			this.startButton = new System.Windows.Forms.Button();
			this.groupBox1 = new System.Windows.Forms.GroupBox();
			this.radioButtonSD = new System.Windows.Forms.RadioButton();
			this.radioButtonUseCG = new System.Windows.Forms.RadioButton();
			this.label5 = new System.Windows.Forms.Label();
			this.textBoxLambda = new System.Windows.Forms.TextBox();
			this.label6 = new System.Windows.Forms.Label();
			this.textBoxIterNum = new System.Windows.Forms.TextBox();
			this.label4 = new System.Windows.Forms.Label();
			this.comboBoxMagnificationFactor = new System.Windows.Forms.ComboBox();
			this.label3 = new System.Windows.Forms.Label();
			this.textBoxGaussSigma = new System.Windows.Forms.TextBox();
			this.label2 = new System.Windows.Forms.Label();
			this.label1 = new System.Windows.Forms.Label();
			this.comboBoxGaussSize = new System.Windows.Forms.ComboBox();
			this.progressBar = new System.Windows.Forms.ProgressBar();
			this.panel2 = new System.Windows.Forms.Panel();
			this.buttonSaveInitial = new System.Windows.Forms.Button();
			this.buttonSaveImage = new System.Windows.Forms.Button();
			this.statusBar1 = new System.Windows.Forms.StatusBar();
			this.statusBarPanelMessage = new System.Windows.Forms.StatusBarPanel();
			this.statusBarPanelStatus = new System.Windows.Forms.StatusBarPanel();
			this.buttonAddImage = new System.Windows.Forms.Button();
			this.buttonDeleteImage = new System.Windows.Forms.Button();
			this.mainMenu1 = new System.Windows.Forms.MainMenu();
			this.menuItemFile = new System.Windows.Forms.MenuItem();
			this.menuItemLoadMultiple = new System.Windows.Forms.MenuItem();
			this.menuItemLoadSingle = new System.Windows.Forms.MenuItem();
			this.menuItemSaveSR = new System.Windows.Forms.MenuItem();
			this.menuItemSaveUpref = new System.Windows.Forms.MenuItem();
			this.saveFileDialog1 = new System.Windows.Forms.SaveFileDialog();
			this.panel1.SuspendLayout();
			this.panel3.SuspendLayout();
			this.groupBox1.SuspendLayout();
			this.panel2.SuspendLayout();
			((System.ComponentModel.ISupportInitialize)(this.statusBarPanelMessage)).BeginInit();
			((System.ComponentModel.ISupportInitialize)(this.statusBarPanelStatus)).BeginInit();
			this.SuspendLayout();
			// 
			// toolBar1
			// 
			this.toolBar1.Appearance = System.Windows.Forms.ToolBarAppearance.Flat;
			this.toolBar1.Buttons.AddRange(new System.Windows.Forms.ToolBarButton[] {
																						this.toolBarButtonOpenImage,
																						this.toolBarPrevious,
																						this.toolBarButtonNext,
																						this.toolBarButtonShowSR,
																						this.toolBarButtonUpref});
			this.toolBar1.ButtonSize = new System.Drawing.Size(32, 32);
			this.toolBar1.Divider = false;
			this.toolBar1.DropDownArrows = true;
			this.toolBar1.ImageList = this.imageList1;
			this.toolBar1.Location = new System.Drawing.Point(0, 0);
			this.toolBar1.Name = "toolBar1";
			this.toolBar1.ShowToolTips = true;
			this.toolBar1.Size = new System.Drawing.Size(904, 42);
			this.toolBar1.TabIndex = 1;
			this.toolBar1.ButtonClick += new System.Windows.Forms.ToolBarButtonClickEventHandler(this.toolBar1_ButtonClick);
			// 
			// toolBarButtonOpenImage
			// 
			this.toolBarButtonOpenImage.ImageIndex = 0;
			this.toolBarButtonOpenImage.ToolTipText = "Load all Images In a Folder";
			// 
			// toolBarPrevious
			// 
			this.toolBarPrevious.ImageIndex = 3;
			this.toolBarPrevious.ToolTipText = "Displays the Previous Image";
			// 
			// toolBarButtonNext
			// 
			this.toolBarButtonNext.ImageIndex = 2;
			this.toolBarButtonNext.ToolTipText = "Displays the Next Image";
			// 
			// toolBarButtonShowSR
			// 
			this.toolBarButtonShowSR.ImageIndex = 4;
			this.toolBarButtonShowSR.ToolTipText = "Displays SR Image";
			// 
			// toolBarButtonUpref
			// 
			this.toolBarButtonUpref.ImageIndex = 5;
			this.toolBarButtonUpref.ToolTipText = "Displays Initial Estimate";
			// 
			// imageList1
			// 
			this.imageList1.ImageSize = new System.Drawing.Size(32, 32);
			this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream")));
			this.imageList1.TransparentColor = System.Drawing.Color.Transparent;
			// 
			// openFileDialog1
			// 
			this.openFileDialog1.DefaultExt = "jpg";
			this.openFileDialog1.Filter = "\"All Image Files (JPEG, GIF, BMP, etc.)|*.jpg;*.jpeg;*.gif;*.bmp;*.tif;*.tiff;*.p" +
				"ng|JPEG files (*.jpg;*.jpeg)|*.jpg;*.jpeg|GIF Files (*.gif)|*.gif|BMP Files (*.b" +
				"mp)|*.bmp|TIFF Files (*.tif;*.tiff)|*.tif;*.tiff|PNG Files (*.png)|*.png\"";
			// 
			// listBoxImNames
			// 
			this.listBoxImNames.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
				| System.Windows.Forms.AnchorStyles.Left) 
				| System.Windows.Forms.AnchorStyles.Right)));
			this.listBoxImNames.Location = new System.Drawing.Point(16, 8);
			this.listBoxImNames.Name = "listBoxImNames";
			this.listBoxImNames.Size = new System.Drawing.Size(680, 160);
			this.listBoxImNames.TabIndex = 2;
			this.listBoxImNames.SelectedIndexChanged += new System.EventHandler(this.listBoxImNames_SelectedIndexChanged);
			// 
			// pictureBoxImageSelected
			// 
			this.pictureBoxImageSelected.Location = new System.Drawing.Point(0, 0);
			this.pictureBoxImageSelected.Name = "pictureBoxImageSelected";
			this.pictureBoxImageSelected.Size = new System.Drawing.Size(592, 312);
			this.pictureBoxImageSelected.TabIndex = 3;
			this.pictureBoxImageSelected.TabStop = false;
			// 
			// panel1
			// 
			this.panel1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) 
				| System.Windows.Forms.AnchorStyles.Left) 
				| System.Windows.Forms.AnchorStyles.Right)));
			this.panel1.BackColor = System.Drawing.SystemColors.InactiveCaptionText;
			this.panel1.Controls.Add(this.panel3);
			this.panel1.Controls.Add(this.pictureBoxImageSelected);
			this.panel1.Location = new System.Drawing.Point(0, 39);
			this.panel1.Name = "panel1";
			this.panel1.Size = new System.Drawing.Size(904, 377);
			this.panel1.TabIndex = 4;
			// 
			// panel3
			// 
			this.panel3.BackColor = System.Drawing.SystemColors.Control;
			this.panel3.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
			this.panel3.Controls.Add(this.startButton);
			this.panel3.Controls.Add(this.groupBox1);
			this.panel3.Controls.Add(this.label6);
			this.panel3.Controls.Add(this.textBoxIterNum);
			this.panel3.Controls.Add(this.label4);
			this.panel3.Controls.Add(this.comboBoxMagnificationFactor);
			this.panel3.Controls.Add(this.label3);
			this.panel3.Controls.Add(this.textBoxGaussSigma);
			this.panel3.Controls.Add(this.label2);
			this.panel3.Controls.Add(this.label1);
			this.panel3.Controls.Add(this.comboBoxGaussSize);
			this.panel3.Controls.Add(this.progressBar);
			this.panel3.Dock = System.Windows.Forms.DockStyle.Right;
			this.panel3.Location = new System.Drawing.Point(696, 0);
			this.panel3.Name = "panel3";
			this.panel3.Size = new System.Drawing.Size(208, 377);
			this.panel3.TabIndex = 4;
			// 
			// startButton
			// 
			this.startButton.Location = new System.Drawing.Point(72, 336);
			this.startButton.Name = "startButton";
			this.startButton.TabIndex = 16;
			this.startButton.Text = "Start";
			this.startButton.Click += new System.EventHandler(this.startButton_Click);
			// 
			// groupBox1
			// 
			this.groupBox1.Controls.Add(this.radioButtonSD);
			this.groupBox1.Controls.Add(this.radioButtonUseCG);
			this.groupBox1.Controls.Add(this.label5);
			this.groupBox1.Controls.Add(this.textBoxLambda);
			this.groupBox1.Location = new System.Drawing.Point(8, 144);
			this.groupBox1.Name = "groupBox1";
			this.groupBox1.Size = new System.Drawing.Size(192, 96);
			this.groupBox1.TabIndex = 15;
			this.groupBox1.TabStop = false;
			this.groupBox1.Text = "Update Model";
			// 
			// radioButtonSD
			// 
			this.radioButtonSD.Location = new System.Drawing.Point(8, 40);
			this.radioButtonSD.Name = "radioButtonSD";
			this.radioButtonSD.Size = new System.Drawing.Size(120, 24);
			this.radioButtonSD.TabIndex = 1;
			this.radioButtonSD.Text = "Steepest Descent";
			this.radioButtonSD.CheckedChanged += new System.EventHandler(this.radioButtonSD_CheckedChanged);
			// 
			// radioButtonUseCG
			// 
			this.radioButtonUseCG.Checked = true;
			this.radioButtonUseCG.Location = new System.Drawing.Point(8, 16);
			this.radioButtonUseCG.Name = "radioButtonUseCG";
			this.radioButtonUseCG.Size = new System.Drawing.Size(128, 24);
			this.radioButtonUseCG.TabIndex = 0;
			this.radioButtonUseCG.TabStop = true;
			this.radioButtonUseCG.Text = "Conjugate Gradient";
			this.radioButtonUseCG.CheckedChanged += new System.EventHandler(this.radioButtonUseCG_CheckedChanged);
			// 
			// label5
			// 
			this.label5.Location = new System.Drawing.Point(8, 72);
			this.label5.Name = "label5";
			this.label5.Size = new System.Drawing.Size(120, 16);
			this.label5.TabIndex = 13;
			this.label5.Text = "Lambda :";
			// 
			// textBoxLambda
			// 
			this.textBoxLambda.Enabled = false;
			this.textBoxLambda.Location = new System.Drawing.Point(136, 72);
			this.textBoxLambda.Name = "textBoxLambda";
			this.textBoxLambda.Size = new System.Drawing.Size(40, 20);
			this.textBoxLambda.TabIndex = 12;
			this.textBoxLambda.Text = ".5";
			this.textBoxLambda.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
			// 
			// label6
			// 
			this.label6.Font = new System.Drawing.Font("Microsoft Sans Serif", 14F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
			this.label6.Location = new System.Drawing.Point(16, 8);
			this.label6.Name = "label6";
			this.label6.Size = new System.Drawing.Size(176, 23);
			this.label6.TabIndex = 14;
			this.label6.Text = "MAP Parameters";
			this.label6.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
			// 
			// textBoxIterNum
			// 
			this.textBoxIterNum.Location = new System.Drawing.Point(144, 112);
			this.textBoxIterNum.Name = "textBoxIterNum";
			this.textBoxIterNum.Size = new System.Drawing.Size(40, 20);
			this.textBoxIterNum.TabIndex = 10;
			this.textBoxIterNum.Text = "3";
			this.textBoxIterNum.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
			// 
			// label4
			// 
			this.label4.Location = new System.Drawing.Point(8, 112);
			this.label4.Name = "label4";
			this.label4.Size = new System.Drawing.Size(120, 23);
			this.label4.TabIndex = 9;
			this.label4.Text = "Iteration Number: ";
			// 
			// comboBoxMagnificationFactor
			// 
			this.comboBoxMagnificationFactor.Items.AddRange(new object[] {
																			 "1",
																			 "2",
																			 "3",
																			 "4",
																			 "5"});
			this.comboBoxMagnificationFactor.Location = new System.Drawing.Point(144, 64);
			this.comboBoxMagnificationFactor.Name = "comboBoxMagnificationFactor";
			this.comboBoxMagnificationFactor.Size = new System.Drawing.Size(48, 21);
			this.comboBoxMagnificationFactor.TabIndex = 8;
			this.comboBoxMagnificationFactor.Text = "2";
			this.comboBoxMagnificationFactor.SelectedIndexChanged += new System.EventHandler(this.comboBoxMagnificationFactor_SelectedIndexChanged);
			// 
			// label3
			// 
			this.label3.Location = new System.Drawing.Point(8, 64);
			this.label3.Name = "label3";
			this.label3.Size = new System.Drawing.Size(120, 23);
			this.label3.TabIndex = 7;
			this.label3.Text = "Magnification Factor: ";
			// 
			// textBoxGaussSigma
			// 
			this.textBoxGaussSigma.Location = new System.Drawing.Point(144, 88);
			this.textBoxGaussSigma.Name = "textBoxGaussSigma";
			this.textBoxGaussSigma.Size = new System.Drawing.Size(40, 20);
			this.textBoxGaussSigma.TabIndex = 6;
			this.textBoxGaussSigma.Text = "1";
			this.textBoxGaussSigma.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
			// 
			// label2
			// 
			this.label2.Location = new System.Drawing.Point(8, 88);
			this.label2.Name = "label2";
			this.label2.Size = new System.Drawing.Size(120, 23);
			this.label2.TabIndex = 1;
			this.label2.Text = "Gaussian Sigma: ";
			// 
			// label1
			// 
			this.label1.Location = new System.Drawing.Point(8, 40);
			this.label1.Name = "label1";
			this.label1.Size = new System.Drawing.Size(128, 23);
			this.label1.TabIndex = 0;
			this.label1.Text = "Gaussian Window Size: ";
			// 
			// comboBoxGaussSize
			// 
			this.comboBoxGaussSize.Items.AddRange(new object[] {
																   "3x3",
																   "5x5",
																   "7x7"});
			this.comboBoxGaussSize.Location = new System.Drawing.Point(144, 40);
			this.comboBoxGaussSize.Name = "comboBoxGaussSize";
			this.comboBoxGaussSize.Size = new System.Drawing.Size(48, 21);
			this.comboBoxGaussSize.TabIndex = 5;
			this.comboBoxGaussSize.Text = "3x3";
			this.comboBoxGaussSize.SelectedIndexChanged += new System.EventHandler(this.comboBoxGaussSize_SelectedIndexChanged);
			// 
			// progressBar
			// 
			this.progressBar.Location = new System.Drawing.Point(16, 304);
			this.progressBar.Name = "progressBar";
			this.progressBar.Size = new System.Drawing.Size(176, 23);
			this.progressBar.TabIndex = 5;
			// 
			// panel2
			// 
			this.panel2.BackColor = System.Drawing.SystemColors.InactiveCaptionText;
			this.panel2.Controls.Add(this.buttonSaveInitial);
			this.panel2.Controls.Add(this.buttonSaveImage);
			this.panel2.Controls.Add(this.statusBar1);
			this.panel2.Controls.Add(this.buttonAddImage);
			this.panel2.Controls.Add(this.buttonDeleteImage);
			this.panel2.Controls.Add(this.listBoxImNames);
			this.panel2.Dock = System.Windows.Forms.DockStyle.Bottom;
			this.panel2.Location = new System.Drawing.Point(0, 430);
			this.panel2.Name = "panel2";
			this.panel2.Size = new System.Drawing.Size(904, 200);
			this.panel2.TabIndex = 5;
			// 
			// buttonSaveInitial
			// 
			this.buttonSaveInitial.Anchor = System.Windows.Forms.AnchorStyles.Right;
			this.buttonSaveInitial.BackColor = System.Drawing.SystemColors.Control;
			this.buttonSaveInitial.Enabled = false;
			this.buttonSaveInitial.Location = new System.Drawing.Point(720, 128);
			this.buttonSaveInitial.Name = "buttonSaveInitial";
			this.buttonSaveInitial.Size = new System.Drawing.Size(88, 23);
			this.buttonSaveInitial.TabIndex = 6;
			this.buttonSaveInitial.Text = "Save Initial ";
			this.buttonSaveInitial.Click += new System.EventHandler(this.buttonSaveInitial_Click);
			// 
			// buttonSaveImage
			// 
			this.buttonSaveImage.Anchor = System.Windows.Forms.AnchorStyles.Right;
			this.buttonSaveImage.BackColor = System.Drawing.SystemColors.Control;
			this.buttonSaveImage.Enabled = false;
			this.buttonSaveImage.Location = new System.Drawing.Point(720, 96);
			this.buttonSaveImage.Name = "buttonSaveImage";
			this.buttonSaveImage.Size = new System.Drawing.Size(88, 23);
			this.buttonSaveImage.TabIndex = 5;
			this.buttonSaveImage.Text = "Save SR";
			this.buttonSaveImage.Click += new System.EventHandler(this.buttonSaveImage_Click);
			// 
			// statusBar1
			// 
			this.statusBar1.Location = new System.Drawing.Point(0, 176);
			this.statusBar1.Name = "statusBar1";
			this.statusBar1.Panels.AddRange(new System.Windows.Forms.StatusBarPanel[] {
																						  this.statusBarPanelMessage,
																						  this.statusBarPanelStatus});
			this.statusBar1.ShowPanels = true;
			this.statusBar1.Size = new System.Drawing.Size(904, 24);
			this.statusBar1.TabIndex = 0;
			this.statusBar1.Text = "Ready";
			// 
			// statusBarPanelMessage
			// 
			this.statusBarPanelMessage.Width = 400;
			// 
			// buttonAddImage
			// 
			this.buttonAddImage.Anchor = System.Windows.Forms.AnchorStyles.Right;
			this.buttonAddImage.BackColor = System.Drawing.SystemColors.Control;
			this.buttonAddImage.Location = new System.Drawing.Point(720, 60);
			this.buttonAddImage.Name = "buttonAddImage";
			this.buttonAddImage.Size = new System.Drawing.Size(88, 23);
			this.buttonAddImage.TabIndex = 4;
			this.buttonAddImage.Text = "Add Image";
			this.buttonAddImage.Click += new System.EventHandler(this.buttonAddImage_Click);
			// 
			// buttonDeleteImage
			// 
			this.buttonDeleteImage.Anchor = System.Windows.Forms.AnchorStyles.Right;
			this.buttonDeleteImage.BackColor = System.Drawing.SystemColors.Control;
			this.buttonDeleteImage.Location = new System.Drawing.Point(720, 28);
			this.buttonDeleteImage.Name = "buttonDeleteImage";
			this.buttonDeleteImage.Size = new System.Drawing.Size(88, 23);
			this.buttonDeleteImage.TabIndex = 3;
			this.buttonDeleteImage.Text = "Delete Image";
			this.buttonDeleteImage.Click += new System.EventHandler(this.buttonDeleteImage_Click);
			// 
			// mainMenu1
			// 
			this.mainMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
																					  this.menuItemFile});
			// 
			// menuItemFile
			// 
			this.menuItemFile.Index = 0;
			this.menuItemFile.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
																						 this.menuItemLoadMultiple,
																						 this.menuItemLoadSingle,
																						 this.menuItemSaveSR,
																						 this.menuItemSaveUpref});
			this.menuItemFile.Text = "File";
			// 
			// menuItemLoadMultiple
			// 
			this.menuItemLoadMultiple.Index = 0;
			this.menuItemLoadMultiple.Text = "Load Multiple Images";
			this.menuItemLoadMultiple.Click += new System.EventHandler(this.menuItem1_Click);
			// 
			// menuItemLoadSingle
			// 
			this.menuItemLoadSingle.Index = 1;
			this.menuItemLoadSingle.Text = "Load Single Image";
			this.menuItemLoadSingle.Click += new System.EventHandler(this.menuItem2_Click);
			// 
			// menuItemSaveSR
			// 
			this.menuItemSaveSR.Enabled = false;
			this.menuItemSaveSR.Index = 2;
			this.menuItemSaveSR.Text = "Save SR Image";
			this.menuItemSaveSR.Click += new System.EventHandler(this.menuItemSaveSR_Click);
			// 
			// menuItemSaveUpref
			// 
			this.menuItemSaveUpref.Enabled = false;
			this.menuItemSaveUpref.Index = 3;
			this.menuItemSaveUpref.Text = "Save Initial Estimate";
			this.menuItemSaveUpref.Click += new System.EventHandler(this.menuItemSaveUpref_Click);
			// 
			// saveFileDialog1
			// 
			this.saveFileDialog1.DefaultExt = "jpg";
			this.saveFileDialog1.Filter = "\"JPEG files (*.jpg;*.jpeg)|*.jpg;*.jpeg|GIF Files (*.gif)|*.gif|BMP Files (*.bmp)" +
				"|*.bmp|TIFF Files (*.tif;*.tiff)|*.tif;*.tiff|PNG Files (*.png)|*.png\"";
			// 
			// Form1
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
			this.ClientSize = new System.Drawing.Size(904, 630);
			this.Controls.Add(this.panel2);
			this.Controls.Add(this.panel1);
			this.Controls.Add(this.toolBar1);
			this.Menu = this.mainMenu1;
			this.Name = "Form1";
			this.Text = "Super Resolution GUI 1.0";
			this.Closed += new System.EventHandler(this.Form1_Closed);
			this.Paint += new System.Windows.Forms.PaintEventHandler(this.Form1_Paint);
			this.panel1.ResumeLayout(false);
			this.panel3.ResumeLayout(false);
			this.groupBox1.ResumeLayout(false);
			this.panel2.ResumeLayout(false);
			((System.ComponentModel.ISupportInitialize)(this.statusBarPanelMessage)).EndInit();
			((System.ComponentModel.ISupportInitialize)(this.statusBarPanelStatus)).EndInit();
			this.ResumeLayout(false);

		}
		#endregion

		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main() 
		{
			Application.Run(new Form1());
		}

		private void toolBar1_ButtonClick(object sender, System.Windows.Forms.ToolBarButtonClickEventArgs e)
		{	
			switch (toolBar1.Buttons.IndexOf(e.Button))
			{
				case 0 : // open
					DoAction("OpenFile");					
					break;

				case 1: // next image					
					DoAction("PreviousImage");
					break;

				case 2: // prev image
					DoAction("NextImage");
					break;


				case 3: // zoom in
					DoAction("ShowSR");
					viewMode=1;

					break;

				case 4: // no zoom
					DoAction("ShowUpref");
					viewMode=2;
					break;

				case 5: // zoom in
					DoAction("ZoomOut");
					break;


			}
		}

		private void DoAction(string szAction)
		{
			Bitmap	MyBitmap;

			switch(szAction)
			{
				case "OpenFile":
					
					openFile();

					SRbefore = @imageFolder+ "\\SRbefore.jpg";
					SRafter = @imageFolder+  "\\SRafter.jpg";
					SRbeforeRoot = @rootDirectory+ "\\SRbefore.jpg";
					SRafterRoot = @rootDirectory+  "\\SRafter.jpg";

					break;

				case "NextImage":					
					nSelectedFile++;
					if(hasBeenInitialized && nSelectedFile>=FileArray.Count)
						nSelectedFile=0;
					if(hasBeenInitialized)
					{
						listBoxImNames.SelectedIndex=nSelectedFile;
						updateImageList();
					}
					break;

				case "PreviousImage":
					nSelectedFile--;
					if(hasBeenInitialized && nSelectedFile<0)
						nSelectedFile=FileArray.Count-1;
						
					if(hasBeenInitialized)
					{
						listBoxImNames.SelectedIndex=nSelectedFile;
						updateImageList();
					}
					break;

				case "FormSR":

					#region deActivated Super Resolution Code

//					//------------------TAKE PARAMETERS ----------------------------
//					iterationNumber=Convert.ToInt32(textBoxIterNum.Text);
//					sigmaGauss=Convert.ToDouble(textBoxGaussSigma.Text);							
//					lambda=Convert.ToDouble(textBoxLambda.Text);
//					//--------------------------------------------------------------
//
//					// SET STATUS BAR TO NULL
//					statusBarPanelMessage.Text="";
//					statusBarPanelMessage.Text="";
//					
//					if(FileArray.Count>0)
//					{
//						try
//						{
//							MyBitmap = new Bitmap( FileArray[0].ToString() );
//							pictureBoxImageSelected.Width=MyBitmap.Width;
//							pictureBoxImageSelected.Height=MyBitmap.Height;
//							pictureBoxImageSelected.Image=MyBitmap;
//							pictureBoxImageSelected.Update();
//
//							if(FileArray.Count>0 && checkImageSizes()==true)
//							{
//
//								buttonSaveImage.Enabled=false;
//								buttonSaveImage.Refresh();
//								buttonSaveInitial.Enabled=false;
//								buttonSaveInitial.Refresh();
//
//								menuItemSaveSR.Enabled=false;
//								menuItemSaveUpref.Enabled=false;
//						
//								toolBar1.Buttons[4].Enabled=false;
//								toolBar1.Buttons[5].Enabled=false;
//								toolBar1.Refresh();
//
//								statusBarPanelStatus.Text="Working";
//
//								//------CALL THEVENAZ REGISTRATION DLL THROUGH THREAD-------------
//								getThread = new System.Threading.Thread(new
//								ThreadStart(this.loadThevenazDLL));
//								getThread.Start();
//								getThread.Join();
//								
//								
//									statusBarPanelStatus.Text="Finished";
//									buttonSaveImage.Enabled=true;
//									buttonSaveInitial.Enabled=true;
//
//									menuItemSaveSR.Enabled=true;
//									menuItemSaveUpref.Enabled=true;
//
//						
//									//Make SR buttons invisible
//									toolBar1.Buttons[4].Enabled=true;
//									toolBar1.Buttons[5].Enabled=true;
//
//							#region Saving part of SR	
//						
//									MyBitmap = new Bitmap(SRbefore);
//									MyBitmap.Save(SRbeforeRoot);
//									MyBitmap.Dispose();
//
//									MyBitmap=new Bitmap(SRafter);
//									MyBitmap.Save(SRafterRoot);
//									MyBitmap.Dispose();
//									
////									Image.FromFile(SRbefore).Save(SRbeforeRoot,System.Drawing.Imaging.ImageFormat.Jpeg);											
////									Image.FromFile(SRbefore).Dispose();
////									
////									Image.FromFile(SRafter).Save(SRafterRoot,System.Drawing.Imaging.ImageFormat.Jpeg);
////									Image.FromFile(SRafter).Dispose();
//								    
//							#endregion
//
//							}					
//							else
//							{
//								if(checkImageSizes()!=true)
//									statusBarPanelMessage.Text="One of the images have different size than others";
//								else
//									statusBarPanelMessage.Text="Please load input images for SR";
//							}
//						}
//						catch(System.Exception ex)
//						{
//							MessageBox.Show("ERROR: " + ex.ToString());
//						}
//					}
//					else if(FileArray.Count==0)
//					{
//						statusBarPanelMessage.Text="Please load input images for SR";
//					}
//
//					break;
					#endregion
					
				case "ShowSR":
					try
					{
						MyBitmap = new Bitmap(rootDirectory+ "\\SRafter.jpg");

						pictureBoxImageSelected.Width=MyBitmap.Width;
						pictureBoxImageSelected.Height=MyBitmap.Height;
						pictureBoxImageSelected.Update();
						Graphics g = pictureBoxImageSelected.CreateGraphics();
						g.DrawImage(MyBitmap, new Rectangle(0, 0, MyBitmap.Width, MyBitmap.Height));
						
						MyBitmap.Dispose();		
					}
					catch(Exception ex)
					{
						MessageBox.Show("ERROR: " + ex.ToString());
					}
				
					break;

				case "ShowUpref":
					try
					{
						MyBitmap = new Bitmap(rootDirectory+ "\\SRbefore.jpg");					
						
						pictureBoxImageSelected.Width=MyBitmap.Width;
						pictureBoxImageSelected.Height=MyBitmap.Height;
						pictureBoxImageSelected.Update();
						Graphics g = pictureBoxImageSelected.CreateGraphics();
						g.DrawImage(MyBitmap, new Rectangle(0, 0, MyBitmap.Width, MyBitmap.Height));
							
						MyBitmap.Dispose();
					}
					catch(Exception ex)
					{
						MessageBox.Show("ERROR: " + ex.ToString());
					}  
					break;
			}
		}

		private void loadMainForm()
		{
			// initialize the image types array
			FileTypes = new ArrayList();
			FileTypes.Add("*.JPG");
			FileTypes.Add("*.JPEG");
			FileTypes.Add("*.GIF");
			FileTypes.Add("*.BMP");
			FileTypes.Add("*.PNG");
			FileTypes.Add("*.TIF");
			FileTypes.Add("*.TIFF");
		}
		
		private void ProcessDirectory()
		{
			string[] szFiles;

			int previousLength=FileArray.Count;

			// find image files			
			foreach( string szType in FileTypes )
			{
				szFiles = Directory.GetFiles( Directory.GetCurrentDirectory(), szType);
				if( szFiles.Length>0 )
				{
					FileArray.AddRange( szFiles );
				}
			}			
			
			if( FileArray.Count>0 )
			{
				for(int i=previousLength;i<FileArray.Count;i++)
					listBoxImNames.Items.Add(FileArray[i].ToString());

				if(FileArray.Count>0)
					hasBeenInitialized=true;

				listBoxImNames.Update();			

				if( szRequestedFile.ToString()!="" )
				{
					nSelectedFile = FileArray.IndexOf(szRequestedFile);
				}
			}
			else
			{
				nSelectedFile = -1;
			}
		}

		private string GetFilePath()
		{
			if( nSelectedFile>FileArray.Count ) nSelectedFile = 0;
			return FileArray[nSelectedFile].ToString();
		}


		public void buttonDeleteImage_Click(object sender, System.EventArgs e)
		{
			if((0<listBoxImNames.Items.Count)&&(FileArray.Count>0)&&(listBoxImNames.SelectedIndex>=0))
			{
				nSelectedFile=listBoxImNames.SelectedIndex;

				this.listBoxImNames.Items.RemoveAt(nSelectedFile);//nSelectedFile	
				listBoxImNames.Invalidate();
				
				FileArray.RemoveAt(nSelectedFile);
				
				nSelectedFile--;
				if (nSelectedFile==-1 && FileArray.Count>0)
					listBoxImNames.SelectedIndex=0;
				else
					listBoxImNames.SelectedIndex=nSelectedFile;
			}

			updateImageList();
			writeImageNamesToTxt();

			if(FileArray.Count<=0)
				hasBeenInitialized=false;			
		}

		private void listBoxImNames_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			if(listBoxImNames.SelectedIndex!=-1)
			{
					nSelectedFile=listBoxImNames.SelectedIndex;
					viewMode=0;
			}
			if(nSelectedFile>=0)
			{
				updateImageList();
			}
		}

		private void updateImageList()
		{	

			if(nSelectedFile>=0)
			{
				Bitmap MyBitmap = new Bitmap( FileArray[nSelectedFile].ToString() );
				pictureBoxImageSelected.Width=MyBitmap.Width;
				pictureBoxImageSelected.Height=MyBitmap.Height;
				pictureBoxImageSelected.Image=MyBitmap;

				pictureBoxImageSelected.Update();				
			}
		}

		private string returnImNames()
		{
			imNameListLength=0;
			
			string imTotal="";			
			for(int i=0;i<FileArray.Count;i++)
			{
					imNameListLength+=FileArray[i].ToString().Length;
					imTotal+=FileArray[i].ToString();
				
			}
			return imTotal;
		}

		private void writeImageNamesToTxt()
		{
		
		

			if(FileArray.Count>0)
			{				
				
//				// Create a reader that can read characters from the FileStream.
//				
//				fileName=rootDirectory+"\\imNames.txt";
//				FileStream sr = new FileStream(fileName,FileMode.OpenOrCreate, FileAccess.ReadWrite);
//				StreamWriter sw = new StreamWriter(sr);
//				
//
//				// While not at the end of the file, read lines from the file.		
//				for(int i=0;i<FileArray.Count;i++)
//				{
//					sw.WriteLine(FileArray[i].ToString());						
//				}
//
//				sr.Flush();
//				sw.Flush();
//				sw.Close();//CLOSE THE STREAM			
//
//						


			}		

		}

		private void loadImageNamesFromTxt()
		{

//			if(File.Exists("imNames.txt"))
//			{
//				TextReader tr = new StreamReader("imNames.txt");			
//
//				
//				int i=0;
//				string name=tr.ReadLine();
//				while(name!=null)
//				{
//					FileArray.Add(name);
//					listBoxImNames.Items.Add(name);
//
//					name=tr.ReadLine();
//					i++;                	
//				}
//				listBoxImNames.Invalidate();
//				nSelectedFile=0;
//				tr.Close();
//				hasBeenInitialized=true;
//				updateImageList();				
//
//			}
			
		}


		private void buttonAddImage_Click(object sender, System.EventArgs e)
		{
			addSingleImage();		
		}

		private void comboBoxGaussSize_SelectedIndexChanged(object sender, System.EventArgs e)
		{			
			sigmaW=comboBoxGaussSize.SelectedIndex+1;			
		}

		private void comboBoxMagnificationFactor_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			Factor=comboBoxMagnificationFactor.SelectedIndex+1;
		}

		private void Form1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
		{		
		}

		private void openFile()
		{
			Bitmap	MyBitmap;
			// Show the openfiledialog
			// if user presses ok, set the current dir to that of the requested file
			// process that directory
			// set scale to normal
			// show the image

			//Clear the previous FileArray and ImageList
			listBoxImNames.Items.Clear();
			FileArray.Clear();
			listBoxImNames.Invalidate();
					
			if( openFileDialog1.ShowDialog()==DialogResult.OK )
			{
				szRequestedFile = openFileDialog1.FileName;
						
				imageFolder=Directory.GetParent(szRequestedFile).FullName.ToString();

				//Directory.SetCurrentDirectory( Directory.GetParent(szRequestedFile).FullName.ToString() );
						
				ProcessDirectory();
				writeImageNamesToTxt();

				//fScale = 1.00F;
				if( nSelectedFile!=-1 )
				{	//SetPicture();
				}

				MyBitmap = new Bitmap( GetFilePath() );
				pictureBoxImageSelected.Width=MyBitmap.Width;
				pictureBoxImageSelected.Height=MyBitmap.Height;
				pictureBoxImageSelected.Image=MyBitmap;
				pictureBoxImageSelected.Update();
				MyBitmap.Dispose();				
			}
		}

		private void addSingleImage()
		{
			if( openFileDialog1.ShowDialog()==DialogResult.OK )
			{
				szRequestedFile = openFileDialog1.FileName;
						
				imageFolder=Directory.GetParent(szRequestedFile).FullName.ToString();

				//Directory.SetCurrentDirectory( Directory.GetParent(szRequestedFile).FullName.ToString() );
						
				if(imageFolder!=null)
				{
					FileArray.Add(szRequestedFile);
					listBoxImNames.Items.Add(szRequestedFile);
					listBoxImNames.Update();
					
					if (!hasBeenInitialized)
					{
						nSelectedFile=0;
						hasBeenInitialized=true;
					}
					else 
					{
						nSelectedFile++;

					}
				}				
			}
		}

		private void menuItem1_Click(object sender, System.EventArgs e)
		{
			openFile();
		}

		private void menuItem2_Click(object sender, System.EventArgs e)
		{
			addSingleImage();
		}


		private void saveResult(int choice)
		{
			string imName;
			if(choice==1)
				imName=rootDirectory+ "\\SRafter.jpg";
			else
				imName=rootDirectory+ "\\SRbefore.jpg";		

			try
			{
				saveFileDialog1.ShowDialog();

				if( saveFileDialog1.FileName != "")
				{
					System.IO.FileStream fs = 
						(System.IO.FileStream)saveFileDialog1.OpenFile();
				
					
					switch(saveFileDialog1.FilterIndex)
					{
						
						case 1 : 
							Image.FromFile(imName).Save(fs,System.Drawing.Imaging.ImageFormat.Jpeg);
							Image.FromFile(imName).Dispose();
							break;

						case 2 : 
							Image.FromFile(imName).Save(fs,System.Drawing.Imaging.ImageFormat.Gif);
							Image.FromFile(imName).Dispose();
							break;

						case 3 : 
							Image.FromFile(imName).Save(fs,System.Drawing.Imaging.ImageFormat.Bmp);
							Image.FromFile(imName).Dispose();
							break;
						case 4 :						
							Image.FromFile(imName).Save(fs,System.Drawing.Imaging.ImageFormat.Tiff);
							Image.FromFile(imName).Dispose();
							break;
						case 5 : 
							Image.FromFile(imName).Save(fs,System.Drawing.Imaging.ImageFormat.Png);
							Image.FromFile(imName).Dispose();
							break;													
					}
				}
			}			
			catch(Exception ex)
			{
				MessageBox.Show("ERROR: " + ex.ToString());
			}		


	}

		

		private void buttonSaveImage_Click(object sender, System.EventArgs e)
		{
			saveResult(1);
		}

		private void buttonSaveInitial_Click(object sender, System.EventArgs e)
		{
			saveResult(2);
		}

		private void menuItemSaveSR_Click(object sender, System.EventArgs e)
		{
			saveResult(1);
		}

		private void menuItemSaveUpref_Click(object sender, System.EventArgs e)
		{
			saveResult(2);
		}

		private void loadThevenazDLL()
		{
		string imNameList=returnImNames();
		workingStatus=loadDLL.RetrieveTempFilename(FileArray.Count,FileArray[0].ToString().Length, imNameList.ToCharArray(),Factor,sigmaW,sigmaGauss,lambda,iterationNumber,useCG);
		}

		private bool checkImageSizes()
		{
			int m,n,mold,nold;

			if(FileArray.Count>1)
			{   
				mold=Image.FromFile(FileArray[0].ToString()).Height;
				nold=Image.FromFile(FileArray[0].ToString()).Width;
				Image.FromFile(FileArray[0].ToString()).Dispose();

				for(int i=1;i<FileArray.Count;i++)
				{
					m=Image.FromFile(FileArray[i].ToString()).Height;
					n=Image.FromFile(FileArray[i].ToString()).Width;
					Image.FromFile(FileArray[i].ToString()).Dispose();
					if (m!=mold || n!=nold)
						return false;
				}
			}
			return true;
	}

		private void Form1_Closed(object sender, System.EventArgs e)
		{
//		    //!!!!!Delete old files from the image directory--->may create problem			
//			if(File.Exists(SRafter))
//				File.Delete(SRafter);
//
//		
//				if(File.Exists(SRbefore))
//				File.Delete(SRbefore);					
		}

		private void radioButtonSD_CheckedChanged(object sender, System.EventArgs e)
		{
			textBoxLambda.Enabled=true;
			useCG=0;
			useSD=1;
		}

		private void radioButtonUseCG_CheckedChanged(object sender, System.EventArgs e)
		{
			useCG=1;
			useSD=0;
			textBoxLambda.Enabled=false;
		}
        
		private void startButton_Click(object sender, System.EventArgs e)
		{
			if(FileArray.Count>0 && checkImageSizes()==true)
			{
				try
				{
					startButton.Enabled = false;
					toolBar1.Buttons[3].Enabled=false;
					toolBar1.Buttons[4].Enabled=false;
					buttonSaveImage.Enabled=false;
					buttonSaveInitial.Enabled=false;

					progressBar.Value = 0;

					//------------------TAKE PARAMETERS ----------------------------
					iterationNumber=Convert.ToInt32(textBoxIterNum.Text);
					sigmaGauss=Convert.ToDouble(textBoxGaussSigma.Text);							
					lambda=Convert.ToDouble(textBoxLambda.Text);
					//--------------------------------------------------------------
			
					string imNameList=returnImNames();
					workingStatus=1;
					int r = StartTimerThread( callback,FileArray.Count,FileArray[0].ToString().Length, imNameList.ToCharArray(),Factor,sigmaW,sigmaGauss,lambda,iterationNumber,useCG );		// call to C++ DLL
			
					if( r != 0 )
					{
						MessageBox.Show( this, "failed to start unmanaged thread!" );
						startButton.Enabled = true;				
						return;			
					}
				}
				catch(System.Exception ex)
				{
					MessageBox.Show("ERROR: " + ex.ToString());
				}
			}
			else
			{
				if(checkImageSizes()!=true)
					statusBarPanelMessage.Text="One of the images have different size than others";
				else
					statusBarPanelMessage.Text="Please load input images for SR";
			}


		}

		#region GUI Update Handler
		private void OnUpdateGui(object sender, System.EventArgs e)
		{
			// indirectly called with .Invoke by GuiCallbackHandler 				
			progressBar.Step=1;
		
			progressBar.PerformStep();
		}		
		#endregion

		#region Communication with unmanaged code (C++ DLL)
		private EventHandler updateGuiHandler;
		
		// Warning : called in context of foreign thread! ...		
		private int GuiCallbackHandler( int mode, int val )
		{			
			// Mode 1  ---> Means Registering
			// Mode 2  ---> Means Reconstructing
			// Val=222 ---> Means Registration finished
			// Val=333 ---> Means Reconstruction finished

			// thus we can't access any forms/controls here! ...						
			if (useCG==0 && mode==2)
			{
					progressBar.Maximum=iterationNumber*FileArray.Count;
			}
			else
					progressBar.Maximum=FileArray.Count;

			
			if( this.updateGuiHandler != null)
				this.Invoke( this.updateGuiHandler );// so we HAVE to use Control.Invoke !
			
		    // alternative : this.BeginInvoke
			

			if (val!=222 && val!=333)
			{
				if(mode==1)
					statusBarPanelStatus.Text="Registering "+Convert.ToString(val);
				else
					statusBarPanelStatus.Text="Reconstructing "+Convert.ToString(val);
			}

			if(val==222)
			{				
				progressBar.Value = 0;
			}

			
			if (val==333)//Means dll finished reconstructing
			{
				Bitmap	MyBitmap;
				MyBitmap = new Bitmap(SRbefore);
				MyBitmap.Save(SRbeforeRoot);
				MyBitmap.Dispose();

				MyBitmap=new Bitmap(SRafter);
				MyBitmap.Save(SRafterRoot);
				MyBitmap.Dispose();

				toolBar1.Buttons[3].Enabled=true;
				toolBar1.Buttons[4].Enabled=true;
				buttonSaveImage.Enabled=true;
				buttonSaveInitial.Enabled=true;
				startButton.Enabled=true;

				statusBarPanelStatus.Text="Finished";

				progressBar.Value = 0;
				workingStatus=0;		//Change the working status
						
			}
			return 0;		// 0 : keep C++ thread looping
		}

		#endregion

	}

}
