Index: Scheduling/trunk/cs/bsdx0200GUISourceCode/CGSchedLib.cs
===================================================================
--- Scheduling/trunk/cs/bsdx0200GUISourceCode/CGSchedLib.cs	(revision 1011)
+++ 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
 					}
 				}
