Index: Scheduling/trunk/cs/bsdx0200GUISourceCode/CGAVDocument.cs
===================================================================
--- Scheduling/trunk/cs/bsdx0200GUISourceCode/CGAVDocument.cs	(revision 1091)
+++ Scheduling/trunk/cs/bsdx0200GUISourceCode/CGAVDocument.cs	(revision 1095)
@@ -375,5 +375,5 @@
 
 			rAppointmentSchedule = CGSchedLib.CreateAssignedSlotSchedule(m_DocManager, (string) m_sResourcesArray[0], this.m_dStartDate, this.m_dEndDate, apptTypeIDs,/* */ this.m_ScheduleType, "0");
-			CGSchedLib.OutputArray(rAppointmentSchedule, "rAppointmentSchedule");
+
 			foreach (DataRow r in rAppointmentSchedule.Rows) 
 			{
Index: Scheduling/trunk/cs/bsdx0200GUISourceCode/CGAppointments.cs
===================================================================
--- Scheduling/trunk/cs/bsdx0200GUISourceCode/CGAppointments.cs	(revision 1091)
+++ Scheduling/trunk/cs/bsdx0200GUISourceCode/CGAppointments.cs	(revision 1095)
@@ -4,7 +4,9 @@
     using System.Collections;
     /// <summary>
-    /// This class was regenerated from Calendargrid.dll using Reflector.exe
-    /// by Sam Habiel for WorldVista. The original source code is lost.
+    /// Managers Appointment objects CGAppointment using an array list internally.
     /// </summary>
+    /// <remarks>
+    /// Really needs to be refactored to use generics
+    /// </remarks>
     [Serializable]
     public class CGAppointments : IEnumerable, ICloneable
@@ -58,4 +60,8 @@
 
  
+        /// <summary>
+        /// Returns a deep copy of CGAppointments
+        /// </summary>
+        /// <returns></returns>
         public object Clone()
         {
Index: Scheduling/trunk/cs/bsdx0200GUISourceCode/CGDocument.cs
===================================================================
--- Scheduling/trunk/cs/bsdx0200GUISourceCode/CGDocument.cs	(revision 1091)
+++ Scheduling/trunk/cs/bsdx0200GUISourceCode/CGDocument.cs	(revision 1095)
@@ -173,4 +173,5 @@
         /// <summary>
         /// Update schedule based on info in RPMS
+        /// <returns>Clears and repopluates m_appointments</returns>
         /// </summary>
         private bool RefreshDaysSchedule()
@@ -200,4 +201,5 @@
                 m_dLastRefresh = DateTime.Now;
 
+                //Clear appointments associated with this document
                 this.m_appointments.ClearAllAppointments();
 
@@ -205,8 +207,5 @@
                 rAppointmentSchedule = CGSchedLib.CreateAppointmentSchedule(m_DocManager, m_sResourcesArray, this.m_dStartDate, this.m_dEndDate);
 
-                // Datatable dumper into Debug Log (nice to know that this exists)
-                CGSchedLib.OutputArray(rAppointmentSchedule, "rAppointmentSchedule");
-
-
+                // loop through datatable: Create CGAppointment and add to CGAppointments
                 foreach (DataRow r in rAppointmentSchedule.Rows)
                 {
@@ -422,17 +421,46 @@
             try
             {
-                if (this.m_DocManager.ConnectInfo.Connected == false)
-                {
-                    m_DocManager.ConnectInfo.LoadConnectInfo();
-                }
-
                 ArrayList saryApptTypes = new ArrayList();
-                int nApptTypeID = 0;
-
+                
                 //Refresh Availability schedules
                 DataTable rAvailabilitySchedule;
                 rAvailabilitySchedule = CGSchedLib.CreateAvailabilitySchedule(m_DocManager, m_sResourcesArray, this.m_dStartDate, this.m_dEndDate, saryApptTypes,/**/ m_ScheduleType, "0");
-                CGSchedLib.OutputArray(rAvailabilitySchedule, "rAvailabilitySchedule");
-
+
+                ////NEW
+                //NOTE: This lock makes sure that availabilities aren't queried for slots when the array is an intermediate
+                //state. The other place that has this lock is SlotsAvailable function.
+                lock (this.m_pAvArray)
+                {
+                    m_pAvArray.Clear();
+                    foreach (DataRow rTemp in rAvailabilitySchedule.Rows)
+                    {
+                        DateTime dStart = (DateTime)rTemp["START_TIME"];
+                        DateTime dEnd = (DateTime)rTemp["END_TIME"];
+
+                        //TODO: Fix this slots datatype problem
+                        string sSlots = rTemp["SLOTS"].ToString();
+                        int nSlots = Convert.ToInt16(sSlots);
+
+                        string sResourceList = rTemp["RESOURCE"].ToString();
+                        string sAccessRuleList = rTemp["ACCESS_TYPE"].ToString();
+                        string sNote = rTemp["NOTE"].ToString();
+
+                        int nApptTypeID;
+
+                        if ((nSlots < -1000) || (sAccessRuleList == ""))
+                        {
+                            nApptTypeID = 0;
+                        }
+                        else
+                        {
+                            nApptTypeID = Int32.Parse(rTemp["ACCESS_TYPE"].ToString());
+                        }
+
+                        AddAvailability(dStart, dEnd, nApptTypeID, nSlots, sResourceList, sAccessRuleList, sNote);
+                    }
+                }
+                return true;
+                
+                /* NOT USED
                 //Refresh Type Schedule
                 string sResourceName = "";
@@ -442,5 +470,5 @@
                     sResourceName = m_sResourcesArray[j].ToString();
                     DataTable dtTemp = CGSchedLib.CreateAssignedTypeSchedule(m_DocManager, sResourceName, this.m_dStartDate, this.m_dEndDate, m_ScheduleType);
-                    CGSchedLib.OutputArray(dtTemp, "dtTemp");
+
                     if (j == 0)
                     {
@@ -452,5 +480,4 @@
                     }
                 }
-                CGSchedLib.OutputArray(rTypeSchedule, "rTypeSchedule");
 
                 DateTime dStart;
@@ -523,8 +550,9 @@
 
 
-                        AddAvailability(dStart, dEnd, nApptTypeID, nSlots, false, sResourceList, sAccessRuleList, sNote);
+                        //AddAvailability(dStart, dEnd, nApptTypeID, nSlots, sResourceList, sAccessRuleList, sNote);
                     }//end foreach datarow rTemp
                 }//end lock
                 return true;
+             */
             }
             catch (Exception ex)
@@ -552,5 +580,5 @@
         /// <param name="sNote"></param>
         /// <returns></returns>
-        public int AddAvailability(DateTime StartTime, DateTime EndTime, int nType, int nSlots, bool UpdateView, string sResourceList, string sAccessRuleList, string sNote)
+        public int AddAvailability(DateTime StartTime, DateTime EndTime, int nType, int nSlots, string sResourceList, string sAccessRuleList, string sNote)
         {
             //adds it to the object array
@@ -588,8 +616,5 @@
             int nIndex = 0;
             nIndex = m_pAvArray.Add(pNewAv);
-            if (UpdateView == true)
-            {
-                this.UpdateAllViews();
-            }
+
             return nIndex;
         }
Index: Scheduling/trunk/cs/bsdx0200GUISourceCode/CGDocumentManager.cs
===================================================================
--- Scheduling/trunk/cs/bsdx0200GUISourceCode/CGDocumentManager.cs	(revision 1091)
+++ Scheduling/trunk/cs/bsdx0200GUISourceCode/CGDocumentManager.cs	(revision 1095)
@@ -170,5 +170,5 @@
         /// Encoding decision is complex. This is the order of priority:
         /// - If the M DB runs in UTF-8, that's what we are going to use.
-        /// - If that's not so, /e sets the default encoding. If /e is a non-existent encoding, move forward.
+        /// - If that's not so, /e sets the default encoding. If /e is a non-existent encoding, move to next step.
         /// - If /e is not supplied or is not recognized, the default encoding is the Windows default Encoding for the user.
         /// </remarks>
@@ -606,5 +606,5 @@
                 m_dsGlobal.Tables["ResourceGroup"].Columns["RESOURCE_GROUP"],	//Parent
                 m_dsGlobal.Tables["GroupResources"].Columns["RESOURCE_GROUP"]);	//Child
-            CGSchedLib.OutputArray(m_dsGlobal.Tables["GroupResources"], "GroupResources");
+
             m_dsGlobal.Relations.Add(dr);
 
Index: Scheduling/trunk/cs/bsdx0200GUISourceCode/CGSchedLib.cs
===================================================================
--- Scheduling/trunk/cs/bsdx0200GUISourceCode/CGSchedLib.cs	(revision 1091)
+++ Scheduling/trunk/cs/bsdx0200GUISourceCode/CGSchedLib.cs	(revision 1095)
@@ -19,11 +19,6 @@
 	/// scheduling application.
 	/// </summary>
-	public class CGSchedLib
+	public static class CGSchedLib
 	{
-		public CGSchedLib()
-		{
-
-		}
-
         /// <summary>
         /// Gets appointments from VISTA to display in Grid
@@ -53,28 +48,16 @@
 		}
 
-		public static void OutputArray(DataTable dt, string sName)
-		{
-#if (DEBUG && OUTPUTARRAY)
-			Debug.Write("\n " + sName + " OutputArray:\n");
-			if (dt == null)
-				return;
-
-			foreach (DataColumn c in dt.Columns)
-			{
-				Debug.Write(c.ToString());
-			}
-			Debug.Write("\n");
-			foreach (DataRow r in dt.Rows) 
-			{
-				foreach (DataColumn c in dt.Columns)
-				{
-					Debug.Write(r[c].ToString());
-				}
-				Debug.Write("\n");
-			}			
-			Debug.Write("\n");
-#endif
-		}
-
+
+        /// <summary>
+        /// Gets all Availabilities and Appointments, then substracts Appointments from availabilities.
+        /// </summary>
+        /// <param name="docManager">God Class</param>
+        /// <param name="saryResourceNames">Resource Array (ArrayList)</param>
+        /// <param name="StartTime">Self-Explanatory</param>
+        /// <param name="EndTime">Self-Explanatory</param>
+        /// <param name="saryApptTypes">Array of Access Type IDs</param>
+        /// <param name="stType"></param>
+        /// <param name="sSearchInfo"></param>
+        /// <returns></returns>
 		public static DataTable CreateAvailabilitySchedule(CGDocumentManager docManager, 
 			ArrayList saryResourceNames, DateTime StartTime, DateTime EndTime, 
@@ -95,11 +78,12 @@
 			
 			string sResName;
+            //TODO: Optimize: no need to keep looping through resources.
             // for each resource
 			for (int i = 0; i < nSize; i++) 
 			{
 				sResName = saryResourceNames[i].ToString();
-                //Gets all the slots (or Availabities, if you like)
+                //Gets all the slots (or Availabities, or AV Blocks if you like)
 				rsSlotSchedule = CGSchedLib.CreateAssignedSlotSchedule(docManager, sResName, StartTime, EndTime, saryApptTypes,/**/ stType, sSearchInfo);
-				OutputArray(rsSlotSchedule, "rsSlotSchedule");
+				
                 //if we have slots
 				if (rsSlotSchedule.Rows.Count > 0 ) 
@@ -107,24 +91,26 @@
                     // Get appointment count to substract from the slots
 					rsApptSchedule = CGSchedLib.CreateAppointmentSlotSchedule(docManager, sResName, StartTime, EndTime, stType);
-					OutputArray(rsApptSchedule, "rsApptSchedule");
+
                     // Perform the substraction
 					rsTemp1 = CGSchedLib.SubtractSlotsRS2(rsSlotSchedule, rsApptSchedule, sResName);
-					OutputArray(rsTemp1, "rsTemp1");
-				}
+
+				}
+                //otherwise, just return the slot schedule we have.
 				else 
 				{
 					rsTemp1 = rsSlotSchedule;
-					OutputArray(rsTemp1, "rsTemp1");
-				}
+
+				}
+
                 // if only one resource was passed in, its availablility is what we want
 				if (i == 0) 
 				{
 					rsOut = rsTemp1;
-					OutputArray(rsOut, "rsOut");
-				}
+
+				} 
+                // if more than one resource, merge them together
 				else 
 				{
 					rsOut = CGSchedLib.UnionBlocks(rsTemp1, rsOut);
-					OutputArray(rsOut, "United rsOut");
 				}
 			}
@@ -133,15 +119,11 @@
 
 
+        /* NOT USED ANYMORE!!!
 		public static DataTable CreateAssignedTypeSchedule(CGDocumentManager docManager, string sResourceName, DateTime StartTime, DateTime EndTime, ScheduleType stType)
 		{
 
-			string sStart;
-			string sEnd;
-			//sStart = StartTime.ToString("M-d-yyyy");
-            sStart = FMDateTime.Create(StartTime).DateOnly.FMDateString;
-			//sEnd = EndTime.ToString("M-d-yyyy");
-            sEnd = FMDateTime.Create(EndTime).DateOnly.FMDateString;
-//			string sSource = (stType == ScheduleType.Resource ? "ST_RESOURCE" : "ST_CLINIC");
-			string sSql = "BSDX TYPE BLOCKS OVERLAP^" + sStart + "^" + sEnd + "^" + sResourceName ;//+ "^" + sSource;
+            string sStart = FMDateTime.Create(StartTime).DateOnly.FMDateString;
+			string sEnd = FMDateTime.Create(EndTime).DateOnly.FMDateString;
+            string sSql = "BSDX TYPE BLOCKS OVERLAP^" + sStart + "^" + sEnd + "^" + sResourceName;
 
 			DataTable rs = docManager.RPMSDataTable(sSql, "AssignedTypeSchedule");
@@ -176,6 +158,5 @@
 
 			dCol = new DataColumn();
-			//dCol.DataType = Type.GetType("System.Int16");
-            dCol.DataType = Type.GetType("System.Int32"); //MJL 11/17/2006
+            dCol.DataType = Type.GetType("System.Int32");
             dCol.ColumnName = "AvailabilityID";
 			dCol.ReadOnly = true;
@@ -196,9 +177,10 @@
 			DateTime dStart;
 			DateTime dEnd;
-//			DataRow r;
-			DataRow rNew;
-
+			DataRow rNew; //Temporary Holding place for first or last row
+
+            // Get Last Date from final row
 			rNew = rs.Rows[rs.Rows.Count - 1];
 			dLastEnd = (DateTime) rNew["EndTime"];
+            // Get First Date from first row
 			rNew = rs.Rows[0];
 			dStart = (DateTime) rNew["StartTime"];
@@ -210,4 +192,6 @@
 			// then pad with a new block
 
+            // if First Row time is later than the StartTime param (should always be true)
+            // then make a new row whose time starts from StartTime and ends with dStart
 			if (dStart > StartTime) 
 			{
@@ -222,5 +206,5 @@
 			}	
 			
-			//if first block start time is < StartTime then trim
+			//if first block start time is < StartTime then trim (shouldn't happen)
 			if (dStart < StartTime) 
 			{
@@ -233,4 +217,5 @@
 			int nAvailabilityID;
 
+            //dStart holds the first date for the availabilities returned from RPMS
 			dEnd = dStart;
 			foreach (DataRow rEach in rs.Rows)
@@ -248,8 +233,11 @@
 				}
 
+                //dEnd now EndTime for AV Block
 				dEnd = (DateTime) rEach["EndTime"];
 
-				if (dEnd > EndTime) 
-					dEnd = EndTime;
+                // if dEnd is greater than endime, set dEnd to be the same as EndTime.
+                if (dEnd > EndTime) { dEnd = EndTime; }
+
+
 				nAppointmentTypeID = (int) rEach["AppointmentTypeID"];
 				nAvailabilityID = (int) rEach["AvailabilityID"];
@@ -275,19 +263,30 @@
 				rsCopy.Rows.Add(rNew);		
 			}
-			OutputArray(rsCopy, "CreateAssignedTypeSchedule");
+			
 			return rsCopy;
 		}
-
-		public static DataTable CreateAssignedSlotSchedule(CGDocumentManager docManager, string sResourceName, DateTime StartTime, DateTime EndTime, ArrayList rsaryApptTypeIDs, /**/ ScheduleType stType, string sSearchInfo) 
-		{
-
-			//Appointment type ids is now always "" so that all appointment types are returned.
+        */
+
+        /// <summary>
+        /// Gets the Availability Slots from the Server
+        /// </summary>
+        /// <param name="docManager">God Class</param>
+        /// <param name="sResourceName">Resource for which to get slots</param>
+        /// <param name="StartTime"></param>
+        /// <param name="EndTime"></param>
+        /// <param name="rsaryApptTypeIDs">Access Type IDs to retrieve</param>
+        /// <param name="stType">Not used</param>
+        /// <param name="sSearchInfo">If performing a slot search (i.e. for empty appointments), has search info here. Used by Find Appointments</param>
+        /// <returns>DataTable with the following Columns:
+        /// D00030START_TIME^D00030END_TIME^I00010SLOTS^T00030RESOURCE^T00010ACCESS_TYPE^T00250NOTE^I00030AVAILABILITYID
+        /// </returns>
+		public static DataTable CreateAssignedSlotSchedule(CGDocumentManager docManager, string sResourceName, DateTime StartTime, 
+            DateTime EndTime, ArrayList rsaryApptTypeIDs, /**/ ScheduleType stType, string sSearchInfo) 
+		{
+            //Appointment type ids is now always "" so that all appointment types are returned.
 			string sApptTypeIDs = "";
 			
-			//The following code block is not used now, but keep for possible later use:
-			//Unpack the Appointment Type IDs
-			/*
-			*/
-			int nSize = rsaryApptTypeIDs.Count;
+            //flatten types by '|'
+			int nSize = rsaryApptTypeIDs.Count;  //nSize is used to decide where to put the '|' sent in the RPC as we flatten sApptTypeIDs
 			for (int i=0; i < nSize; i++) 
 			{
@@ -297,20 +296,10 @@
 			}	
 	
-			string sStart;
-			string sEnd;
-			//sStart = StartTime.ToString("M-d-yyyy"); smh
-            sStart = FMDateTime.Create(StartTime).DateOnly.FMDateString;
-			//sEnd = EndTime.ToString("M-d-yyyy@H:mm"); smh
-            sEnd = FMDateTime.Create(EndTime).FMDateString;
+            string sStart = FMDateTime.Create(StartTime).DateOnly.FMDateString;
+            string sEnd = FMDateTime.Create(EndTime).FMDateString;
 			string sSql = "BSDX CREATE ASGND SLOT SCHED^" + sResourceName + "^" + sStart + "^" + sEnd + "^" + sApptTypeIDs + "^" + sSearchInfo; //+ "^" + sSTType ;
-
 			DataTable dtRet = docManager.RPMSDataTable(sSql, "AssignedSlotSchedule");
 
-			if (sResourceName == "")
-			{
-				return dtRet; 
-			}
-
-			return dtRet;
+            return dtRet;
 		}
 
@@ -370,18 +359,24 @@
 		}
 
+        /// <summary>
+        /// This gets a datatable which shows the appointments between start and end time, one row per appointment
+        /// </summary>
+        /// <param name="docManager"></param>
+        /// <param name="sResourceName"></param>
+        /// <param name="StartTime"></param>
+        /// <param name="EndTime"></param>
+        /// <param name="stType"></param>
+        /// <returns>DataTable with 4 columns: START_TIME, END_TIME, SLOTS, RESOURCE </returns>
 		public static DataTable CreateAppointmentSlotSchedule(CGDocumentManager docManager, string sResourceName, DateTime StartTime, DateTime EndTime, ScheduleType stType)
 		{
-
-
-			string sStart;
-			string sEnd;
-			//sStart = StartTime.ToString("M-d-yyyy");
-            sStart = FMDateTime.Create(StartTime).DateOnly.FMDateString;
-			//sEnd = EndTime.ToString("M-d-yyyy");
-            sEnd = FMDateTime.Create(EndTime).DateOnly.FMDateString;
-
-			string sSTType = (stType == ScheduleType.Resource ? "ST_RESOURCE" : "ST_CLINIC");
+            //Change Dates to FM Format
+            string sStart = FMDateTime.Create(StartTime).DateOnly.FMDateString;
+			string sEnd = FMDateTime.Create(EndTime).DateOnly.FMDateString;
+			
+            string sSTType = (stType == ScheduleType.Resource ? "ST_RESOURCE" : "ST_CLINIC");
 			string sSql = "BSDX APPT BLOCKS OVERLAP^" + sStart + "^" + sEnd + "^" + sResourceName ;//+ "^"  + sSTType;
 
+            //This gets you a table with 2 columns containing start and end time for each appt
+            //Each appt gets its own row
 			DataTable dtRet = docManager.RPMSDataTable(sSql, "AppointmentSlotSchedule");
 			
@@ -390,12 +385,12 @@
 			
 			//Create CDateTimeArray & load records from rsOut
-			int nRC;
-			nRC = dtRet.Rows.Count;
+			int nRC = dtRet.Rows.Count;     // nRC is row count from Appointments table just retrieved
 			ArrayList cdtArray = new ArrayList();
-			cdtArray.Capacity = (nRC * 2);
+			cdtArray.Capacity = (nRC * 2); //new ArrayList has capacity double that of appointment table
 			DateTime v;
 			int i = 0;
 
-			foreach (DataRow r in dtRet.Rows) 
+			//for each row in the Appointment Table, ArrayList cdtArray gets 2 entries: Start and End times
+            foreach (DataRow r in dtRet.Rows) 
 			{
 				v = (DateTime) r[dtRet.Columns["START_TIME"]];
@@ -404,11 +399,15 @@
 				cdtArray.Add(v);
 			}
+
+            //Sort start and end times (for use in ScheduleFromArray method)
 			cdtArray.Sort();
 
 			//Create a CTimeBlockArray and load it from rsOut
 		
+            //Now, create a new ArrayList with the size of the appointment table to hold availabilities
 			ArrayList ctbAppointments = new ArrayList(nRC);
 			CGAvailability cTB;
 			i = 0;
+            //For each appointment, create an availability
 			foreach (DataRow r in dtRet.Rows) 
 			{
@@ -421,15 +420,27 @@
 			//Create a TimeBlock Array from the data in the DateTime array
 			ArrayList ctbApptSchedule = new ArrayList();
+
+            //Convert Appointments to Availabilities, where all appointments become squeezed together.
 			ScheduleFromArray(cdtArray, StartTime, EndTime, ref ctbApptSchedule);
-			
-			//Find number of TimeBlocks in ctbApptSchedule that
-			//overlap the TimeBlocks in ctbAppointments
+
+            /*So far, we have the following:
+             * dtRet -> List of Appointments Start and End times, one row per appointment
+             * cdtArray -> Linear 1 dimensional Array of dtRet Start and End times, sorted
+             * ctbAppointments -> Arraylist of dtRet as Availabilities
+             * ctbApptSchedule -> Arraylist of dtRet as Availabilities with no overlapping boundaries
+             *      (overlaps in appointments get converted into availabilties themselves: so
+             *      2 appts as 10:10-10:30 and 10:20-10:40 get converted into 10:10-10:20,
+             *      10:20-10:30, 10:30-10:40).
+            */
+
+            //Find number of TimeBlocks in ctbApptSchedule that overlap the TimeBlocks in ctbAppointments
 			ArrayList ctbApptSchedule2 = new ArrayList();
 			CGAvailability cTB2;
 			int nSlots = 0;
-			for (i=0; i< ctbApptSchedule.Count; i++) 
+			for (i=0; i< ctbApptSchedule.Count; i++)    //for each non-overlapping appts as availabilities
 			{
 				cTB = (CGAvailability) ctbApptSchedule[i];
-				nSlots = BlocksOverlap(cTB, ctbAppointments);
+                //How many times does the non-overlapping part show up in an appointment slot?
+				nSlots = BlocksOverlap(cTB, ctbAppointments);   
 				cTB2 = new CGAvailability();
 				cTB2.Create(cTB.StartTime, cTB.EndTime, nSlots);
@@ -532,5 +543,13 @@
 		}
 
-		//BOOL CResourceLink::TimesOverlap(COleDateTime dStart1, COleDateTime dEnd1, COleDateTime dStart2, COleDateTime dEnd2)
+		/// <summary>
+		/// Does an appointment overlap with another appointment in the same day?
+		/// </summary>
+		/// <param name="dStart1">Start Time of First Appt</param>
+		/// <param name="dEnd1">End Time of First Appt</param>
+        /// <param name="dStart2">Start Time of Second Appt</param>
+		/// <param name="dEnd2">End Time of Second Appt</param>
+		/// <returns>true or false</returns>
+        /// <remarks>Draws 2 rectangles and sees if they overlap using minutes from 1980 as the start point</remarks>
 		public static bool TimesOverlap(DateTime dStart1, DateTime dEnd1, DateTime dStart2, DateTime dEnd2)
 		{
@@ -667,6 +686,4 @@
 			Debug.Assert(rs1 != null);
 			Debug.Assert(rs2 != null);
-			CGSchedLib.OutputArray(rs1, "UnionBlocks rs1");
-			CGSchedLib.OutputArray(rs2, "UnionBlocks rs2");
 			
 			DataTable rsCopy;
@@ -798,5 +815,17 @@
 		}
 
-		public static void ScheduleFromArray(ArrayList cdtArray, DateTime dStartTime, DateTime dEndTime, ref ArrayList rTBArray)
+        /// <summary>
+        /// Converts an Array of Times like this:
+        /// 10:00 10:00 10:20 10:20 10:30 10:30 10:30 10:40
+        /// To an array of availabilities like this:
+        /// 12:00-10:00 10:00-10:20 10:20-10:30 10:30-10:40
+        /// Where the 12:00 comes from the start time
+        /// </summary>
+        /// <param name="cdtArray">ArrayList containing start and end times of Appointments combmined and sorted</param>
+        /// <param name="dStartTime">Start Time for Schedule</param>
+        /// <param name="dEndTime">End Time for Schedule</param>
+        /// <param name="rTBArray">Output of Availabilities: Pass Empty</param>
+		public static void ScheduleFromArray(ArrayList cdtArray, DateTime dStartTime, DateTime dEndTime, 
+            ref ArrayList rTBArray)
 		{
 			int j = 0;
@@ -812,5 +841,8 @@
 			if (dStartTime.Ticks > 0) 
 			{
-				if ((DateTime) cdtArray[0] > dStartTime) 
+				// if first Array Entry greater than start time, then create an availability
+                // with the start time as dStartTime, and end time as the first array entry, and 0 slots
+                // then add this to the output array
+                if ((DateTime) cdtArray[0] > dStartTime) 
 				{
 					cTB = new CGAvailability();
@@ -818,4 +850,7 @@
 					rTBArray.Add(cTB);
 				}
+
+                // if first Array Entry less than start time (shouldn't happen),
+                // convert all input array's times less than the start time to all be the start time
 				if ((DateTime) cdtArray[0] < dStartTime) 
 				{
@@ -829,4 +864,6 @@
 
 			//Trim the end if necessary
+            //If end time is passed, set all the times in the original array greater
+            //than the end time to be the end time (Shouldn't happen).
 			if (dEndTime.Ticks > 0) 
 			{
@@ -839,9 +876,10 @@
 
 			//build the schedule in rTBArray
-			DateTime dTemp = new DateTime();
+			DateTime dTemp = new DateTime(); //hold previous appt time.
 			DateTime dStart;
 			DateTime dEnd;
 			int k = 0;
-			for (j = 0; j < (cdtArray.Count -1); j++) //TODO: why minus 1?
+            //for each time in appointment array
+			for (j = 0; j < (cdtArray.Count -1); j++) // -1 b/c k below starts with j+1.
 			{
 				if ((DateTime) cdtArray[j] != dTemp) 
@@ -849,12 +887,14 @@
 					dStart =(DateTime) cdtArray[j];
 					dTemp = dStart;
+                    
+                    //for each time in appointment array, starting with the next one
 					for (k = j+1; k < cdtArray.Count; k++) 
 					{
 						dEnd = new DateTime();
-						if ((DateTime) cdtArray[k] != dStart) 
+						if ((DateTime) cdtArray[k] != dStart) //if the next time isn't the same
 						{
-							dEnd = (DateTime) cdtArray[k];
+							dEnd = (DateTime) cdtArray[k]; // set the end to be the next time
 						}
-						if (dEnd.Ticks > 0) 
+						if (dEnd.Ticks > 0) //make a new availability and add it to the output array.
 						{
 							cTB = new CGAvailability();
@@ -863,4 +903,5 @@
 							break;
 						}
+                        // if the end time is still empty, loop
 					}
 				}
Index: Scheduling/trunk/cs/bsdx0200GUISourceCode/CGView.cs
===================================================================
--- Scheduling/trunk/cs/bsdx0200GUISourceCode/CGView.cs	(revision 1091)
+++ Scheduling/trunk/cs/bsdx0200GUISourceCode/CGView.cs	(revision 1095)
@@ -2329,9 +2329,15 @@
         private void OnUpdateScheduleCallback(IAsyncResult itfAR)
         {
-            // if the view meanwhile closed, just return
-            if (this == null) return;
-
             OnUpdateScheduleDelegate d = new OnUpdateScheduleDelegate(UpdateArrays);
-            this.Invoke(d);
+            
+            //try catch just in case that the view closed in the meantime.
+            try
+            {
+                this.Invoke(d);
+            }
+            catch (InvalidOperationException)
+            {
+                return;
+            }
         }
 
Index: Scheduling/trunk/cs/bsdx0200GUISourceCode/CalendarGrid.cs
===================================================================
--- Scheduling/trunk/cs/bsdx0200GUISourceCode/CalendarGrid.cs	(revision 1091)
+++ Scheduling/trunk/cs/bsdx0200GUISourceCode/CalendarGrid.cs	(revision 1095)
@@ -799,5 +799,5 @@
             foreach (CGAvailability availability in this.m_pAvArray)
             {
-                if (this.TimesOverlap(availability.StartTime, availability.EndTime, timeFromCell, time2))
+                if (TimesOverlap(availability.StartTime, availability.EndTime, timeFromCell, time2))
                 {
                     nAccessTypeID = availability.AvailabilityType;
@@ -842,5 +842,5 @@
             foreach (CGAvailability availability in this.m_pAvArray)
             {
-                if (this.TimesOverlap(availability.StartTime, availability.EndTime, timeFromCell, time2))
+                if (TimesOverlap(availability.StartTime, availability.EndTime, timeFromCell, time2))
                 {
                     nAccessTypeID = availability.AvailabilityType;
@@ -894,5 +894,5 @@
         }
 
-        private int MinSince80(DateTime d)
+        private static int MinSince80(DateTime d)
         {
             DateTime time = new DateTime(1980, 1, 1, 0, 0, 0);
@@ -1153,5 +1153,13 @@
         }
 
-        private bool TimesOverlap(DateTime dStart1, DateTime dEnd1, DateTime dStart2, DateTime dEnd2)
+        /// <summary>
+        /// Do 2 time ranges overlap each other?
+        /// </summary>
+        /// <param name="dStart1">First Start Time</param>
+        /// <param name="dEnd1">First End Time</param>
+        /// <param name="dStart2">Second Start Time</param>
+        /// <param name="dEnd2">Second End Time</param>
+        /// <returns>True or False</returns>
+        public static bool TimesOverlap(DateTime dStart1, DateTime dEnd1, DateTime dStart2, DateTime dEnd2)
         {
             long ticks = dEnd1.Ticks - dStart1.Ticks;
@@ -1165,8 +1173,8 @@
             rect.Width = 1;
             rectangle2.Width = 1;
-            rect.Y = this.MinSince80(dStart1);
-            rect.Height = this.MinSince80(dEnd1) - rect.Y;
-            rectangle2.Y = this.MinSince80(dStart2);
-            rectangle2.Height = this.MinSince80(dEnd2) - rectangle2.Y;
+            rect.Y = MinSince80(dStart1);
+            rect.Height = MinSince80(dEnd1) - rect.Y;
+            rectangle2.Y = MinSince80(dStart2);
+            rectangle2.Height = MinSince80(dEnd2) - rectangle2.Y;
             return rectangle2.IntersectsWith(rect);
         }
Index: Scheduling/trunk/cs/bsdx0200GUISourceCode/ClinicalScheduling.csproj.user
===================================================================
--- Scheduling/trunk/cs/bsdx0200GUISourceCode/ClinicalScheduling.csproj.user	(revision 1091)
+++ Scheduling/trunk/cs/bsdx0200GUISourceCode/ClinicalScheduling.csproj.user	(revision 1095)
@@ -37,5 +37,5 @@
     </RemoteDebugMachine>
     <StartAction>Project</StartAction>
-    <StartArguments>/s=172.16.16.108 /p=9250 /a=abeer12 /v=abc,4321</StartArguments>
+    <StartArguments>/s=192.168.56.101 /p=9260 /a=shabiel12 /v=catdog.77</StartArguments>
     <StartPage>
     </StartPage>
Index: Scheduling/trunk/cs/bsdx0200GUISourceCode/ClinicalScheduling.sln
===================================================================
--- Scheduling/trunk/cs/bsdx0200GUISourceCode/ClinicalScheduling.sln	(revision 1091)
+++ Scheduling/trunk/cs/bsdx0200GUISourceCode/ClinicalScheduling.sln	(revision 1095)
@@ -11,10 +11,10 @@
 	EndGlobalSection
 	GlobalSection(ProjectConfigurationPlatforms) = postSolution
-		{8C05C4F7-FE81-479F-87A0-44E04C7F6E0F}.Debug|Any CPU.ActiveCfg = Release|Any CPU
-		{8C05C4F7-FE81-479F-87A0-44E04C7F6E0F}.Debug|Any CPU.Build.0 = Release|Any CPU
+		{8C05C4F7-FE81-479F-87A0-44E04C7F6E0F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+		{8C05C4F7-FE81-479F-87A0-44E04C7F6E0F}.Debug|Any CPU.Build.0 = Debug|Any CPU
 		{8C05C4F7-FE81-479F-87A0-44E04C7F6E0F}.Release|Any CPU.ActiveCfg = Release|Any CPU
 		{8C05C4F7-FE81-479F-87A0-44E04C7F6E0F}.Release|Any CPU.Build.0 = Release|Any CPU
-		{DE8E4CC9-4F3A-4E32-8DFE-EE5692E8FC45}.Debug|Any CPU.ActiveCfg = Release|Any CPU
-		{DE8E4CC9-4F3A-4E32-8DFE-EE5692E8FC45}.Debug|Any CPU.Build.0 = Release|Any CPU
+		{DE8E4CC9-4F3A-4E32-8DFE-EE5692E8FC45}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+		{DE8E4CC9-4F3A-4E32-8DFE-EE5692E8FC45}.Debug|Any CPU.Build.0 = Debug|Any CPU
 		{DE8E4CC9-4F3A-4E32-8DFE-EE5692E8FC45}.Release|Any CPU.ActiveCfg = Release|Any CPU
 		{DE8E4CC9-4F3A-4E32-8DFE-EE5692E8FC45}.Release|Any CPU.Build.0 = Release|Any CPU
Index: Scheduling/trunk/cs/bsdx0200GUISourceCode/DApptSearch.cs
===================================================================
--- Scheduling/trunk/cs/bsdx0200GUISourceCode/DApptSearch.cs	(revision 1091)
+++ Scheduling/trunk/cs/bsdx0200GUISourceCode/DApptSearch.cs	(revision 1095)
@@ -97,5 +97,4 @@
 				//Build AccessGroup table containing *active* AccessTypes and their Groups
 				m_dtTypes = m_dsGlobal.Tables["AccessGroupType"];
-				CGSchedLib.OutputArray(m_dtTypes, "Access Group Type");
 				//Create a view that is filterable on Access Group
 				m_dvTypes = new DataView(m_dtTypes);
@@ -657,5 +656,5 @@
 			int nAccessTypeID;
 			string sAccessType;
-			CGSchedLib.OutputArray(m_dtResult, "Result Grid");
+
 			foreach (DataRow dr in m_dtResult.Rows)
 			{
@@ -674,5 +673,5 @@
 				}
 			}
-			CGSchedLib.OutputArray(m_dtResult, "Result Grid");
+
 
 			m_dvResult = new DataView(m_dtResult);
