using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;
using SevenZip;

namespace Sync
{
	public partial class frmSync : Form
	{
		private List<FileCompare> _CheckedOut;
		private bool IsLoading = false;
		private float _DPI=100;
		public frmSync()
		{
			InitializeComponent();
			using (Graphics gr = CreateGraphics())
				_DPI = gr.DpiX;
		}
		private void LoadSettings()
		{
			if (Properties.Settings.Default["Location"] != null)
				Location = Properties.Settings.Default.Location;
			if (Properties.Settings.Default["Size"] != null)
				Size = Properties.Settings.Default.Size;
			if (Properties.Settings.Default.DevelopmentFolder != "")
				tbDevelopment.Text = Properties.Settings.Default.DevelopmentFolder;
			if (Properties.Settings.Default.SourceSafeFolder != "")
				tbSourceSafe.Text = Properties.Settings.Default.SourceSafeFolder;
			if(Properties.Settings.Default.MailBoxDevelopmentFolder != "")
				tbMailBox.Text = Properties.Settings.Default.MailBoxDevelopmentFolder;
			if (Properties.Settings.Default.MailBoxSourceSafeFolder != "")
				tbSSMailBox.Text = Properties.Settings.Default.MailBoxSourceSafeFolder;
		}
		private void frmSync_Load(object sender, EventArgs e)
		{
			LoadSettings();
			Setup();
		}
		private void Setup()
		{
			// Setup Browse Buttons
			btnBrwsDev.Tag = this.tbDevelopment;
			btnBrwsSS.Tag = this.tbSourceSafe;
			btnBrwsMail.Tag = this.tbMailBox;
			btnBrwsSSMail.Tag = this.tbSSMailBox;

		}
		private void btnBrowse_Click(object sender, EventArgs e)
		{
			TextBox tb = (TextBox)((Button)sender).Tag;
			fbd.SelectedPath = tb.Text;
			if (fbd.ShowDialog() == DialogResult.OK)
				tb.Text = fbd.SelectedPath;
		}
		private void ClearResults()
		{
			_CheckedOut = new List<FileCompare>();
			dgv.DataSource = null;
			Application.DoEvents();
		}
		private void FindCheckedOut(DirectoryInfo di)
		{
			FindCheckedOut(di.GetFiles());
			FindCheckedOut(di.GetDirectories());
		}
		private void FindCheckedOut(DirectoryInfo[] directoryInfoList)
		{
			foreach (DirectoryInfo di in directoryInfoList)
				FindCheckedOut(di);
		}
		private void FindCheckedOut(FileInfo[] fileInfoList)
		{
			foreach (FileInfo fi in fileInfoList)
				FindCheckedOut(fi);
		}
		private void FindCheckedOut(FileInfo fi)
		{
			if (fi.Name.ToLower().EndsWith("scc")) return;
			if (fi.Name.ToLower().EndsWith("sln")) return;
			if (fi.Name.ToLower().EndsWith("csproj"))
			{
				// Find files that have been added to the new Project
				List<string> compileList = GetCompileList(fi.FullName);
				FileInfo fi1csproj = new FileInfo(fi.FullName.Replace(tbSourceSafe.Text, tbDevelopment.Text));
				if (fi1csproj.Exists)
				{
					List<string> compileList1 = GetCompileList(fi1csproj.FullName);
					CompareLists(compileList, compileList1, fi, fi1csproj);
				}
				return;
			}
			if (fi.Name.ToLower().EndsWith("licx")) return;
			FileInfo fi1 = new FileInfo(fi.FullName.Replace(tbSourceSafe.Text, tbDevelopment.Text));
			if ((fi1.Attributes & FileAttributes.ReadOnly) != FileAttributes.ReadOnly)
				AddToResults(fi, fi1);
		}

		private void CompareLists(List<string> compileList, List<string> compileList1, FileInfo fi, FileInfo fi1)
		{
			// If anything is in compileList1 and not in CompileList add it to the results
			foreach (string filename in compileList1)
				if (!compileList.Contains(filename))
					AddToResults(fi, fi1, filename);
		}
		private void AddToResults(FileInfo fi, FileInfo fi1, string filename)
		{
			FileInfo newfi = new FileInfo(fi.DirectoryName + "/" + filename);
			FileInfo newfi1 = new FileInfo(fi1.DirectoryName + "/" + filename);
			if(!newfi.Exists)AddToResults(newfi, newfi1); // Only add if the file does not exist
		}
		private List<string> GetCompileList(string fileName)
		{
			List<string> retval = new List<string>();
			XmlDocument doc = new XmlDocument();
			doc.Load(fileName);
			XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
			foreach (XmlAttribute attrib in doc.DocumentElement.Attributes)
				if (attrib.Name == "xmlns")
					nsmgr.AddNamespace("ns", attrib.Value);
			XmlNodeList xl = doc.DocumentElement.SelectNodes(@"//ns:Compile/@Include",nsmgr);
			foreach (XmlAttribute xa in xl)
				retval.Add(xa.Value);
			xl = doc.DocumentElement.SelectNodes(@"//ns:Content/@Include", nsmgr);
			foreach (XmlAttribute xa in xl)
			{
				if (xa.Value.ToUpper().EndsWith("DLL"))
					retval.Add(xa.Value);
				if (xa.Value.ToUpper().EndsWith("XML"))
					retval.Add(xa.Value);
				if (xa.Value.ToUpper().EndsWith("SVG"))
					retval.Add(xa.Value);
				if (xa.Value.ToUpper().EndsWith("BAS"))
					retval.Add(xa.Value);
			}
			xl = doc.DocumentElement.SelectNodes(@"//ns:EmbeddedResource/@Include", nsmgr);
			foreach (XmlAttribute xa in xl)
				if (!xa.Value.ToUpper().EndsWith("LICX"))
					retval.Add(xa.Value);
			xl = doc.DocumentElement.SelectNodes(@"//ns:None/@Include", nsmgr);
			foreach (XmlAttribute xa in xl)
			{
				if(xa.Value.ToUpper().EndsWith("SQL"))
					retval.Add(xa.Value);
				if (xa.Value.ToUpper().EndsWith("FRM"))
					retval.Add(xa.Value);
				if (xa.Value.ToUpper().EndsWith("FRX"))
					retval.Add(xa.Value);
			}
			return retval;
		}
		private void AddToResults(FileInfo fiSS,FileInfo fiDev)
		{
			FileCompare fc = new FileCompare(fiDev, fiSS);
			FileInfo fiMB = new FileInfo(fc.FileName.Replace(tbDevelopment.Text, tbSSMailBox.Text));
			if (fiMB.Exists && fiSS.LastWriteTimeUtc != fiMB.LastWriteTimeUtc)
					fc.Merge = true;			
			//if(!_OnlyContentDifferent || (fc.Different && (fc.DevModified != null)))
					if (!_OnlyContentDifferent || (fc.Different))
					_CheckedOut.Add(fc);
			//if (tbResults.Text == "") tbResults.Text = "Found:";
			//tbResults.Text += "\r\n" + fiDev.FullName + " - " + ((fiDev.Attributes & FileAttributes.ReadOnly) != FileAttributes.ReadOnly ? "" : "ReadOnly");
		}
		private void ClearMailBox()
		{
			DeleteFolder(new DirectoryInfo(tbMailBox.Text));
			DeleteFolder(new DirectoryInfo(tbSSMailBox.Text));
		}
		private void DeleteFolder(DirectoryInfo directoryInfo)
		{
			if (directoryInfo.Exists)
			{
				AdjustAttributes(directoryInfo);
				directoryInfo.Delete(true);
			}
		}
		private void AdjustAttributes(DirectoryInfo directoryInfo)
		{
			foreach (DirectoryInfo di in directoryInfo.GetDirectories())
				AdjustAttributes(di);
			foreach (FileInfo fi in directoryInfo.GetFiles())
				AdjustAttribute(fi);
		}
		private void AdjustAttribute(FileInfo fi)
		{
			fi.Attributes &= (fi.Attributes ^ FileAttributes.ReadOnly);// Turn-Off ReadOnly Attribute
			fi.Attributes &= (fi.Attributes ^ FileAttributes.Hidden);// Turn-Off Hidden Attribute
		}
		private void frmSync_FormClosing(object sender, FormClosingEventArgs e)
		{
			Properties.Settings.Default.Location = Location;
			Properties.Settings.Default.Size = Size;
			Properties.Settings.Default.DevelopmentFolder = tbDevelopment.Text;
			Properties.Settings.Default.SourceSafeFolder = tbSourceSafe.Text;
			Properties.Settings.Default.MailBoxDevelopmentFolder = tbMailBox.Text;
			Properties.Settings.Default.MailBoxSourceSafeFolder = tbSSMailBox.Text;
			Properties.Settings.Default.Save();
		}
		private void exitToolStripMenuItem_Click(object sender, EventArgs e)
		{
			this.Close();
		}
		private void clearToolStripMenuItem_Click(object sender, EventArgs e)
		{
			ClearMailBox();
		}
		private void buildToolStripMenuItem_Click(object sender, EventArgs e)
		{
			dgv.EndEdit();
			ClearMailBox();
			if (_CheckedOut == null)
				checkedOutToolStripMenuItem_Click(sender, e);
			foreach (FileCompare fc in _CheckedOut)
			{
				if (fc.ToProcess)
				{
					fc.MoveDevToMailBox(tbDevelopment.Text, tbMailBox.Text);
					fc.MoveSSToMailBox(tbSourceSafe.Text, tbSSMailBox.Text);
				}
			}
			BuildZipOfMailBox(tbMailBox.Text);
		}
		private string _RTFFile = null;
		public string RTFFile
		{
			get { return _RTFFile; }
			set { _RTFFile = value; }
		}
		private void BuildZipOfMailBox(string mailbox)
		{
			SevenZipCompressor.SetLibraryPath(Application.StartupPath + @"\7z.dll");
			SevenZipCompressor cmpr = new SevenZipCompressor();
			cmpr.PreserveDirectoryRoot = true;
			string fileDate = DateTime.Now.ToString("yyyyMMdd HHmm");
			RTFFile = string.Format("{0} To SS {1}.Rtf", mailbox, fileDate);
			string zipName = string.Format("{0} To SS {1}.7z", mailbox, fileDate);
			cmpr.CompressDirectory(mailbox, zipName, "*.*", true);
			MessageBox.Show(string.Format("{0} created!", zipName), "Mailbox Zip Created", MessageBoxButtons.OK, MessageBoxIcon.Information);

			//if (System.IO.File.Exists(@"c:\program files\7-zip\7z.exe"))
			//{
			//  string args = string.Format(@"a -t7z ""{0} To SS {1}.7z"" ""{0}\*.*"" -r", mailbox, DateTime.Now.ToString("yyyyMMdd HHmm"));
			//  System.Diagnostics.Process p = System.Diagnostics.Process.Start(@"c:\program files\7-zip\7z", args);
			//  p.WaitForExit();
			//}
			//"c:\program files\7-zip\7z" a -t7z "C:\Development\MailBox\Proms To SS 20120424 1850.7z" "C:\Development\MailBox\Proms\*.*" -r
		}
		private void checkedOutToolStripMenuItem_Click(object sender, EventArgs e)
		{
			dgv.EndEdit();
			ClearResults();
			// Walk though Source Safe and check to see if the files in the Development folder are read-only
			FindCheckedOut(new DirectoryInfo(tbSourceSafe.Text));
			dgv.DataSource = _CheckedOut;
			SetColumnWidth();
		}
		private void syncAllToolStripMenuItem_Click(object sender, EventArgs e)
		{
			dgv.EndEdit();
			foreach (FileCompare fc in _CheckedOut)
			{
				fc.MoveToDevelopment();
			}
		}
		private void restoreUnchangedToolStripMenuItem_Click(object sender, EventArgs e)
		{
			dgv.EndEdit();
			foreach (FileCompare fc in _CheckedOut)
			{
				if(!fc.Different || fc.DevModified == null)
					fc.MoveToDevelopment();
			}
		}
		private void restoreSelectedToolStripMenuItem_Click(object sender, EventArgs e)
		{
			dgv.EndEdit();
			foreach (FileCompare fc in _CheckedOut)
			{
				if (fc.ToProcess) fc.MoveToDevelopment();
			}
		}
		private void restoreAllToolStripMenuItem_Click(object sender, EventArgs e)
		{
			dgv.EndEdit();
			foreach (FileCompare fc in _CheckedOut)
			{
				fc.MoveToDevelopment();
			}
		}
		private List<FileCompare> SelectedList
		{
			get
			{
				dgv.EndEdit();
				List<FileCompare> fcList = new List<FileCompare>();
				foreach (DataGridViewCell dgc in dgv.SelectedCells)
				{
					FileCompare fc = dgv.Rows[dgc.RowIndex].DataBoundItem as FileCompare;
					if (fc != null && fcList.Contains(fc) == false)
						fcList.Add(fc);
				}
				return fcList;
			}
		}
		private void compareToolStripMenuItem_Click(object sender, EventArgs e)
		{
			dgv.EndEdit();
			// This should launch UltraCompare with the two files
			// Which Item am I on
			List<FileCompare> fcList = SelectedList;
			foreach (FileCompare fc in fcList)
			{
				CompareOneFile(fc.FileName, fc.SSFileName);
			}
		}
		private static void CompareOneFile(string fileDev, string fileSS)
		{
			Console.WriteLine("Compare {0} and {1}", fileDev, fileSS);
			string progname = string.Empty;
			if (System.IO.File.Exists(@"C:\Program Files\IDM Computer Solutions\UltraCompare\UC.exe"))
				progname = @"C:\Program Files\IDM Computer Solutions\UltraCompare\UC.exe";
			if (System.IO.File.Exists(@"C:\Program Files (x86)\IDM Computer Solutions\UltraCompare\UC.exe"))
				progname = @"C:\Program Files (x86)\IDM Computer Solutions\UltraCompare\UC.exe";
			//				string cmd = string.Format("\"{0}\" -t \"{1}\" \"{2}\"", progname, fc.FileName, fc.SSFileName);
			System.Diagnostics.ProcessStartInfo psi =
				new System.Diagnostics.ProcessStartInfo(progname, string.Format(@" -t ""{0}"" ""{1}""", fileDev, fileSS));
			System.Diagnostics.Process prc = System.Diagnostics.Process.Start(psi);
		}
		private void restoreToolStripMenuItem_Click(object sender, EventArgs e)
		{
			dgv.EndEdit();
			List<FileCompare> fcList = SelectedList;
			foreach (FileCompare fc in fcList)
			{
				fc.MoveToDevelopment();
			}
		}
		private bool _ExcludeSolutions = true;
		private void differentAllToolStripMenuItem_Click(object sender, EventArgs e)
		{
			_ExcludeSolutions = false;
			dgv.EndEdit();
			ClearResults();
			// Walk though Source Safe and check to see if the files in the Development folder are read-only
			FindDifferent(new DirectoryInfo(tbSourceSafe.Text));
			dgv.DataSource = _CheckedOut;
			SetColumnWidth();
			_ExcludeSolutions = true;
		}
		private void differentToolStripMenuItem_Click(object sender, EventArgs e)
		{
			dgv.EndEdit();
			ClearResults();
			// Walk though Source Safe and check to see if the files in the Development folder are read-only
			FindDifferent(new DirectoryInfo(tbSourceSafe.Text));
			dgv.DataSource = _CheckedOut;
			SetColumnWidth();
		}
		private void SetColumnWidth()
		{
			IsLoading = true;
			if (Properties.Settings.Default["Widths"] == null)
			{
				dgv.Columns[0].Width = 60;
				dgv.Columns[1].Visible = false;
				dgv.Columns[2].Width = 125;
				dgv.Columns[3].Width = 125;
				dgv.Columns[4].Width = 50;
				dgv.Columns[5].Width = 500;
			}
			else
			{
				for (int i = 0; i < Properties.Settings.Default.Widths.Count; i++)
				{
					string sWidth = Properties.Settings.Default.Widths[i];
					if (sWidth == "Invisible")
						dgv.Columns[i].Visible = false;
					else
						dgv.Columns[i].Width = int.Parse(sWidth);
				}
			}
			dgv.Columns[1].Visible = false;
			IsLoading = false;
		}
		private void FindDifferent(DirectoryInfo di)
		{
			FindDifferent(di.GetFiles());
			FindDifferent(di.GetDirectories());
		}
		private void FindDifferent(DirectoryInfo[] directoryInfoList)
		{
			foreach (DirectoryInfo di in directoryInfoList)
				FindDifferent(di);
		}
		private void FindDifferent(FileInfo[] fileInfoList)
		{
			foreach (FileInfo fi in fileInfoList)
				FindDifferent(fi);
		}
		private void FindDifferent(FileInfo fi)
		{
			if (fi.Name.ToLower().EndsWith("scc")) return;
			if (_ExcludeSolutions && fi.Name.ToLower().EndsWith("sln")) return;
			if (_ExcludeSolutions && fi.Name.ToLower().EndsWith("csproj"))
			{
				// Find files that have been added to the new Project
				List<string> compileList = GetCompileList(fi.FullName);
				FileInfo fi1csproj = new FileInfo(fi.FullName.Replace(tbSourceSafe.Text, tbDevelopment.Text));
				if (fi1csproj.Exists)
				{
					List<string> compileList1 = GetCompileList(fi1csproj.FullName);
					CompareLists(compileList, compileList1, fi, fi1csproj);
				}
				if(_ExcludeSolutions ) return;
			}
			if (fi.Name.ToLower().EndsWith("licx")) return;
			FileInfo fiD = new FileInfo(fi.FullName.Replace(tbSourceSafe.Text, tbDevelopment.Text));
			FileInfo fiS = fi;
			// Only check Read-Only flag, other attributes are unimportant
			if (fiS.LastWriteTimeUtc != fiD.LastWriteTimeUtc || (fiS.Attributes & FileAttributes.ReadOnly ) != (fiD.Attributes & FileAttributes.ReadOnly ))
				AddToResults(fi, fiD);
		}
		private void dgv_ColumnWidthChanged(object sender, DataGridViewColumnEventArgs e)
		{
			if (!IsLoading)
			{
				System.Collections.Specialized.StringCollection widths = new System.Collections.Specialized.StringCollection();
				foreach (DataGridViewColumn col in dgv.Columns)
					widths.Add(col.Visible ? col.Width.ToString() : "Invisible");
				Properties.Settings.Default.Widths = widths;
				Properties.Settings.Default.Save();
			}
		}
		private bool _OnlyContentDifferent = false;
		private void contentDifferentToolStripMenuItem_Click(object sender, EventArgs e)
		{
			dgv.EndEdit();
			ClearResults();
			_OnlyContentDifferent = true;
			// Walk though Source Safe and check to see if the files in the Development folder are read-only
			FindDifferent(new DirectoryInfo(tbSourceSafe.Text));
			_OnlyContentDifferent = false;
			dgv.DataSource = _CheckedOut;
			SetColumnWidth();
		}
		private void frmSync_LocationChanged(object sender, EventArgs e)
		{
			Rectangle rec = Screen.GetWorkingArea(this);
			int newLeft = Left;
			int newTop = Top;
			if (Math.Abs(Left - rec.X) < 10) newLeft = rec.X;
			if (Math.Abs(Top - rec.Y) < 10) newTop = rec.Y;
			if (Math.Abs(rec.X + rec.Width - Right) < 10) newLeft = rec.X + rec.Width - Width;
			if (Math.Abs(rec.Y + rec.Height - Bottom) < 10) newTop = rec.Y + rec.Height - Height;
			if (newTop != Top || newLeft != Left)
				Location = new Point(newLeft, newTop);
		}
		private void restoreReadOnlyToolStripMenuItem_Click(object sender, EventArgs e)
		{
			dgv.EndEdit();
			foreach (FileCompare fc in _CheckedOut)
			{
				if (fc.ReadOnly) fc.MoveToDevelopment();
			}
		}
		private void listToClipboardToolStripMenuItem_Click(object sender, EventArgs e)
		{
			RichTextBox rtb = new RichTextBox();
			Font fntNormal = new Font("Arial", 10, FontStyle.Regular);
			rtb.Font = fntNormal;
			Font fntBold = new Font("Arial", 12, FontStyle.Bold);
			Font fntWing = new Font("Wingdings 2", 11, FontStyle.Regular);
			Font fntItalic = new Font("Arial", 11, FontStyle.Italic);
			Font fntBoldItalic = new Font("Arial", 14, FontStyle.Bold | FontStyle.Italic);
			StringBuilder sb = new StringBuilder();
			dgv.EndEdit();
			sb.Append("Applicability:\r\n\r\n");
			AddText(rtb, fntBold, "Applicability:");
			AddText(rtb, fntNormal, "\r\n\r\n\r\n\r\n");
			if (HasFmtXML(_CheckedOut))
			{
				sb.Append("* This change includes format changes which must be loaded into the databases.\r\n\r\n");
				AddText(rtb, fntBoldItalic, "*\tThis change includes format changes\r\n\twhich must be loaded into the databases.",Color.Orange);
				AddText(rtb, fntNormal, "\r\n\r\n",Color.Black);
			}
			if (HasFormats(_CheckedOut))
			{
				sb.Append("* This change includes format changes which must be loaded into the databases.\r\n\r\n");
				AddText(rtb, fntBoldItalic, "*\tThis change includes format changes\r\n\twhich must be loaded into the databases.", Color.Orange);
				AddText(rtb, fntNormal, "\r\n\r\n", Color.Black);
			}
			if (HasPromsFixes(_CheckedOut))
			{
				sb.Append("* This change includes changes to PROMSFixes.SQL which must be loaded into the databases.\r\n\r\n");
				AddText(rtb, fntBoldItalic, "*\tThis change includes changes to PROMSFixes.SQL\r\n\twhich must be loaded into the databases.\r\n\r\n", Color.Red);
				AddText(rtb, fntNormal, "\r\n\r\n", Color.Black);
			}
			sb.Append("\r\nInternal Data Fixes:\r\n\r\n");
			AddText(rtb, fntBold, "Internal Data Fixes:");
			AddText(rtb, fntNormal, "\r\n\r\n\r\n\r\n",Color.Magenta);
			sb.Append("Code Changes:\r\n\r\n");
			AddText(rtb, fntBold, "Code Changes:");
			AddText(rtb, fntNormal, "\r\n\r\n");
			int lenFolder = tbDevelopment.Text.Length;
			string lastFolder = "";
			foreach (FileCompare fc in _CheckedOut)
			{
				if (fc.ToProcess)
				{
					FileInfo fi = new FileInfo(fc.FileName);
					FileInfo fis = new FileInfo(fc.SSFileName);
					string folder = fi.Directory.FullName.Substring(lenFolder + 1);
					if (folder != lastFolder)
					{
						sb.Append(folder + ":\r\n");
						AddText(rtb, fntItalic, folder + ":\r\n");
						lastFolder = folder;
					}
					sb.Append((fis.Exists ? "" : " =>NEW") + "\t" + fi.Name  + "\r\n");
					AddText(rtb, fntNormal, (fis.Exists ? "" : " =>NEW") + "\t" + fi.Name + "\r\n");
					AddIndent(rtb);
				}
			}
			sb.Append("\r\nInternal Release:\r\n\r\n");
			sb.Append("\r\nGeneric External Release:\r\n\r\n");
			sb.Append("\r\nPlant Specific Information for Release Letter:\r\n\r\n");
			sb.Append("\r\nTesting Performed:\r\n\r\n");
			sb.Append("\r\nTesting Requirements:\r\n\r\n");
			sb.Append("\r\nChanges/Additions to User Documentation:\r\n\r\n");

			AddText(rtb, fntNormal, "\r\n");
			AddText(rtb, fntBold, "Internal Release:");
			AddText(rtb, fntNormal, "\r\n\r\n\r\n\r\n");
			AddText(rtb, fntBold, "Generic External Release:");
			AddText(rtb, fntNormal, "\r\n\r\n\r\n\r\n");
			AddText(rtb, fntBold, "Plant Specific Information for Release Letter:");
			AddText(rtb, fntNormal, "\r\n\r\n\r\n\r\n");
			AddText(rtb, fntBold, "Testing Performed:");
			AddText(rtb, fntNormal, "\r\n\r\n\r\n\r\n");
			AddText(rtb, fntBold, "Testing Requirements:");
			AddText(rtb, fntNormal, "\r\n\r\n");
			AddText(rtb, fntWing, "\x51\x52\xA3");
			AddText(rtb, fntNormal, " Sample Checkboxes");
			AddText(rtb, fntNormal, "\r\n\r\n");
			AddText(rtb, fntBold, "Changes/Additions to User Documentation:");
			AddText(rtb, fntNormal, "\r\n\r\n");
			try
			{
				Clipboard.Clear();
				DataObject dao = new DataObject();
				dao.SetData(DataFormats.Text,sb.ToString());
				dao.SetData(DataFormats.Rtf, rtb.Rtf);
				Clipboard.SetDataObject(dao, true, 10, 500);
				if (RTFFile != null)
				{
					rtb.SaveFile(RTFFile);
					System.Diagnostics.Process.Start(RTFFile);
				}
				else
					MessageBox.Show(sb.ToString(), "Copied to Clipboard", MessageBoxButtons.OK, MessageBoxIcon.Information);
			}
			catch (Exception ex)
			{
				StringBuilder sb2 = new StringBuilder();
				string prefix = "";
				while (ex != null)
				{
					sb2.AppendLine(string.Format("{0}{1} - {2}",prefix, ex.GetType().Name, ex.Message));
					prefix += "  ";
				}
				MessageBox.Show(sb2.ToString(), "Error saving Clipboard", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}
		private bool HasPromsFixes(List<FileCompare> _CheckedOut)
		{
			foreach (FileCompare fc in _CheckedOut)
			{
				if (fc.ToProcess && fc.FileName.ToLower().Contains("promsfixes.sql"))
					return true;
			}
			return false;
		}

		private bool HasFmtXML(List<FileCompare> _CheckedOut)
		{
			foreach (FileCompare fc in _CheckedOut)
			{
				if (fc.ToProcess && fc.FileName.ToLower().Contains("\\fmtxml\\"))
					return true;
			}
			return false;
		}
		private bool HasFormats(List<FileCompare> _CheckedOut)
		{
			foreach (FileCompare fc in _CheckedOut)
			{
				if (fc.ToProcess && fc.FileName.ToLower().Contains("\\formats\\"))
					return true;
			}
			return false;
		}
		private void AddIndent(RichTextBox rtb)
		{
			rtb.Select(rtb.TextLength, 0);
			rtb.SelectionIndent = (int) _DPI;
			rtb.SelectedText = "\r\n";
			rtb.Select(rtb.TextLength, 0);
			rtb.SelectionIndent = 0;
		}
		private static void AddText(RichTextBox rtb, Font font, string txt)
		{
			rtb.Select(rtb.TextLength, 0);
			rtb.SelectionFont = font;
			rtb.SelectedText = txt;
		}
		private static void AddText(RichTextBox rtb, Font font, string txt, Color myColor)
		{
			rtb.Select(rtb.TextLength, 0);
			rtb.SelectionFont = font;
			rtb.SelectionColor = myColor;
			rtb.SelectedText = txt;
			rtb.Select(rtb.TextLength, 0);
			rtb.SelectionColor = Color.Black;
		}
		private void dgv_MouseDown(object sender, MouseEventArgs e)
		{
			dgv.ClearSelection();
			DataGridView.HitTestInfo info = dgv.HitTest(e.X, e.Y);
			if (info.RowIndex < 0) return;
			dgv.CurrentCell = dgv[0, info.RowIndex];
			dgv.Rows[info.RowIndex].Selected = true;
		}

		private void selectAllToolStripMenuItem_Click(object sender, EventArgs e)
		{
			if (_CheckedOut == null || _CheckedOut.Count == 0)
			{
				MessageBox.Show("Don't you really think you should get a list first!", "Hey Moron!", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Stop);
				return;
			}
			foreach (FileCompare fc in _CheckedOut) fc.ToProcess = true;
			dgv.Refresh();
		}

		private void selectNoneToolStripMenuItem_Click(object sender, EventArgs e)
		{
			if (_CheckedOut == null || _CheckedOut.Count == 0)
			{
				MessageBox.Show("Don't you really think you should get a list first!", "Hey Moron!", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Stop);
				return;
			}
			foreach (FileCompare fc in _CheckedOut) fc.ToProcess = false;
			dgv.Refresh();
		}

		private void compareSourceSafeToolStripMenuItem_Click(object sender, EventArgs e)
		{
			// Compare SS version with SS version from Mailbox
			dgv.EndEdit();
			// This should launch UltraCompare with the two files
			// Which Item am I on
			List<FileCompare> fcList = SelectedList;
			foreach (FileCompare fc in fcList)
			{
				CompareOneFile(fc.SSFileName, fc.SSFileName.Replace(tbSourceSafe.Text, tbSSMailBox.Text));
			}
		}

		private void compareMailboxToolStripMenuItem_Click(object sender, EventArgs e)
		{
			// Compare MailBox version with Mailbox Source Safe version
			dgv.EndEdit();
			// This should launch UltraCompare with the two files
			// Which Item am I on
			List<FileCompare> fcList = SelectedList;
			foreach (FileCompare fc in fcList)
			{
				CompareOneFile(fc.FileName, fc.FileName.Replace(tbDevelopment.Text, tbSSMailBox.Text));
			}
		}
	}
}