using System;
using System.Collections.Generic;
using System.Text;
using VEPROMS.CSLA.Library;
using Volian.Base.Library;
using iTextSharp.text.pdf;
using Volian.Svg.Library;
namespace Volian.Print.Library
{
	public partial class vlnParagraph
	{
		private string _PageBreakReason = null;
		public string PageBreakReason
		{
			get { return _PageBreakReason; }
			set { _PageBreakReason = value; }
		}
		private bool _CompressPartOfStep = false;
		public bool CompressPartOfStep
		{
			get { return _CompressPartOfStep; }
			set { _CompressPartOfStep = value; }
		}
		private bool _CompressFirstPartOfStep = false;
		public bool CompressFirstPartOfStep
		{
			get { return _CompressFirstPartOfStep; }
			set { _CompressFirstPartOfStep = value; }
		}
		private bool _BreakHighLevelStepWithSection = false;
		public bool BreakHighLevelStepWithSection
		{
			get { return _BreakHighLevelStepWithSection; }
			set { _BreakHighLevelStepWithSection = value; }
		}
		/// 
		/// This variable is used to match 16 bit pagination
		/// 
		private bool _Match16BitPagination = false;
		private bool _CompressFoldout = false;
		public bool CompressFoldout
		{
			get { return _CompressFoldout; }
			set { _CompressFoldout = value; }
		}
		/// 
		/// Dtermines if the current step is preceded by a Page Break
		/// 
		/// 
		/// 
		/// 
		/// 
		/// 0 - No page break
		/// 1 - Break on High Level Step
		/// 2 - Break within a Step
		/// 3 - Break on High Level Step (SevenLinesPerInch)
		/// 
		private int Paginate(float yLocation, float yTopMargin, float yBottomMargin)
		{
			// Check if paginate on a separate section, if within a section.  Top level section pagination happens in PromsPrinter
			float yPageSize = yTopMargin - yBottomMargin;
			bool ManualPageBreak = false;
			float yWithinMargins = CalculateYLocation(yLocation, yTopMargin) - yBottomMargin; // -SixLinesPerInch;
			if (MyItemInfo.IsSection && MyParent != null && MyParent.MyItemInfo.IsSection && (MyItemInfo as SectionInfo).IsSeparatePagination())
			{
			    ShowPageBreak(1, "Page Break between separate sections", "Yes", YSize, yPageSize, yWithinMargins, ManualPageBreak);
				
				// if parent was continuous & this is separate, need to paginate to get subsection on
				// its own page.  This occurred in BGE/OI3 set/OI-7 procedure/10.0 Attachments.
				if (!(MyParent.MyItemInfo as SectionInfo).IsSeparatePagination()) return 1;
				if (MyItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.WCNTraining && (MyItemInfo as SectionInfo).IsSeparatePagination()) return 1;
				if (MyItemInfo.MyPrevious != null) // add if statement to fix Westinghouse print issue 3-21-2014
				  return 1;
			}
			if (MyItemInfo.IsSection && _ChildrenBelow == null && YSize > (yLocation-yBottomMargin))
			{
				ShowPageBreak(1, "Page Break before empty section", "Yes", YSize, yPageSize, yWithinMargins, ManualPageBreak);
				return 1;
			}
			// If printing a supinfo pdf, see if there is a page break at this supinfo paragraph, i.e. an entry will
			// exist in the list that contains the supinfo paragraph pagebreaks that was generated in the first pagebreak pass
			if (MyPromsPrinter.SupInfoPrintType == E_SupInfoPrintType.SupInfoPdfPrint)
			{
				int retval = 0;
				SectionInfo supInfoSect = MyItemInfo.MyActiveSection as SectionInfo;
				if (supInfoSect.StepSectPageBreaksForSupInfo != null && supInfoSect.StepSectPageBreaksForSupInfo.Contains(MyItemInfo.ItemID))
				{
					MyPromsPrinter.SupInfoPdfPageCount++;
					retval = 1;
				}
				// Printing the supplemental information pages to a pdf: add an item to the dictionary that says what page in the supinfo pdf
				// this item can be found on.
				if (MyItemInfo.IsSupInfoPart)
				{
					MyPromsPrinter.SupInfoPdfPage.Add(MyItemInfo.ItemID, MyPromsPrinter.SupInfoPdfPageCount);
				}
				return retval;
			}
			else if (MyItemInfo.MyDocStyle.SupplementalInformation && MyItemInfo.IsStep)
			{
				// if this is the first caution or note from a substep, if the substep has preferred page break, break at the first caution or note:
				if ((MyItemInfo.IsCaution || MyItemInfo.IsNote) && MyItemInfo.MyParent.IsSubStep)
				{
					StepConfig scs = MyItemInfo.MyParent.MyConfig as StepConfig;
					if (MyItemInfo.MyPrevious == null && scs.Step_PreferredPagebreak) return 2;
				}
				// Now see if there is a preferred page break on this step.
				StepConfig sci = MyItemInfo.MyConfig as StepConfig;
				if (sci.Step_PreferredPagebreak)
				{
					if (MyItemInfo.IsHigh) return 1;
					// if this is the top caution/note return 1 also.  Cautions always are first, that is why the check does not need to know if on a 
					// caution that there are notes, but check does need if on a note, are there cautions:
					if (MyItemInfo.MyParent.IsHigh && MyItemInfo.IsCaution && MyItemInfo.MyPrevious == null) return 1;
					if (MyItemInfo.MyParent.IsHigh && MyItemInfo.IsNote && (MyItemInfo.MyParent.Cautions == null || MyItemInfo.MyParent.Cautions.Count == 0) && MyItemInfo.MyPrevious == null) return 1;
					// if this is a substep that has a preferredpage break, and it has caution/note that is where the page break had to go
					if (MyItemInfo.IsSubStep && ChildrenAbove != null && ChildrenAbove.Count > 0) return 0;
					// B2017-228: The following flags a break within the step.  Before returning a '2' (flags break within step), clear it out of the
					// ParaBreaks.  Without the 'RemoveAt', a page break will occur after this step also.
					string reason = "Unknown";
					if (MyPageHelper.ParaBreaks != null && MyPageHelper.ParaBreaks.Count > 0 && this == MyPageHelper.ParaBreaks[0])
					{
						MyPageHelper.ParaBreaks.RemoveAt(0);
						reason = AddReason("Partial Step - Case 1");
						ShowPageBreak(1, reason, "Yes", YSize, yPageSize, yWithinMargins, ManualPageBreak);
					}
					return 2;
				}
			}
			// if the EndForSingle format flag is set to false, then we do not print an End message if the section
			// is a single column section.
			//bool _skipEndMessage = MyPageHelper.MySection.SectionConfig.Section_ColumnMode == SectionConfig.SectionColumnMode.One && !MyItemInfo.ActiveFormat.MyStepSectionLayoutData.EndForSingle;
			SectionInfo si = MyItemInfo.MyActiveSection as SectionInfo;
			bool _skipEndMessage = si != null && si.SectionConfig.Section_ColumnMode == SectionConfig.SectionColumnMode.One && !MyItemInfo.ActiveFormat.MyStepSectionLayoutData.EndForSingle;
			// TODO: This does not account for a long step as the last step that would exceed more than one page and
			// that has an end message that needs to be accounted for in determining pagination.  To do that the last
			// child should be the only paragraph that accounts for the End message.
			//
			// If last step & there should be an end message, pagination tests need to account for the 3 lines the end
			// message uses. The 3 is for a line above, the end message line & the line below (in case there is a border/box line).
			// The 3 was changed to 2 for the end line & the line below. The blank line below the step gives the blank
			// line above the end message, thus 2 not 3. This change was made on July 20, 2011 by RHM & KBR. The 
			// procedure in questions was VEWCNEMG\EMGAPP.PRC, ES-01, Step 8. 
			float yEndMsg = !_skipEndMessage && !MyItemInfo.IsSection && MyItemInfo.MyHLS != null && MyItemInfo.MyHLS.NextItem == null && (MyItemInfo.MyDocStyle.End.Message ?? "") != "" ? 2 * SixLinesPerInch : 0;
			// also consider if there is a phone list at the bottom of the page, add the amount of space the phone
			// list requires onto yEndMsg to make it easier to figure out pagination (include an extra line for the
			// horizonal line above the phone list.
			if (MyItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.PrintPhoneList && MyPageHelper.PhoneListHeight != 0)
				yEndMsg += (MyPageHelper.PhoneListHeight - vlnPrintObject.SixLinesPerInch);
			// The following code is to fix a pagination issue in SHE.  It was decided to not put it into development
			// because some of the pagination logic may be redesigned.  Without this fix, some pages had a page break 
			// before they should.   I did not want to lose this code, in case at some point we want to revisit this.
			// if doing an end message & we already are ending with a blank line, add one line for the end message
			// otherwise, we need to add two lines, i.e.  ((2 * SixLinesPerInch) - yEndsWithBlankLine)
			// this change was necessary to fix a pagination problem in Shearon Harris, EOPs, User Guide, Attachment 2.
			//float yEndsWithBlankLine = AdjustForBlankLines();
			//KBR debug: if (yEndsWithBlankLine != 0) Console.WriteLine("*** yEndsWithBlankLine = {0}", yEndsWithBlankLine);
			//float yEndMsg = !MyItemInfo.IsSection && MyItemInfo.MyHLS.NextItem == null && (MyItemInfo.MyDocStyle.End.Message ?? "") != "" ? ((2 * SixLinesPerInch) - yEndsWithBlankLine) : 0;
			bool isFirstChild = MyItemInfo.MyPrevious == null;
			bool nearTheTop =  (yWithinMargins < yPageSize) && (yWithinMargins > (yPageSize - 5 * SixLinesPerInch));
			// if step is breaking over a number of pages, determine if the current step is the
			// location of a pagebreak.  ParaBreaks contains the paragraphs that break within a step.
			if (MyPageHelper.ParaBreaks.Count > 0)
			{
				string reason = "Unknown";
				// if on current step and it is also the substep that will cause a pagebreak, i.e. the top substep in pagebreaks[[0]:
				if (this == MyPageHelper.ParaBreaks[0])
				{
					MyPageHelper.ParaBreaks.RemoveAt(0);
					reason = AddReason("Partial Step - Case 1");
					ShowPageBreak(1,reason, "Yes", YSize, yPageSize, yWithinMargins, ManualPageBreak);
					return 2;		// break on this item within a step
				}
				// check for rnos:
				else if (MyPageHelper.ParaBreaks[0].CheckAlternates(this))
				{
					MyPageHelper.ParaBreaks.RemoveAt(0);
					reason = AddReason("Partial Step - Case 2");
					ShowPageBreak(1, reason, "Yes", YSize, yPageSize, yWithinMargins, ManualPageBreak);
					return 2;		// break on this item within a step
				}
				// PageBreakOnStep flags break for cautions/notes/HLS in backgrounds & deviations.
				else if (!MyPageHelper.ParaBreaks[0].PageBreakOnStep && this.YTopMost > MyPageHelper.ParaBreaks[0].YTopMost)
				{
					MyPageHelper.ParaBreaks.RemoveAt(0);
					reason = AddReason("Partial Step - Case 3");
					ShowPageBreak(1, reason, "Yes", YSize, yPageSize, yWithinMargins, ManualPageBreak);
					return 2;		// break on this item within a step
				}
				return 0;			// this is not an item with a break
			}
			float mySize = YSize * MyPageHelper.YMultiplier;
			vlnParagraph firstChild =  ChildrenBelow.Count > 0 ? ChildrenBelow[0] : null;
			// Steps that have the smart template (the WCNCKL format for example), always include two children.
			if (MyItemInfo.IsHigh && MyItemInfo.FormatStepData.UseSmartTemplate) //
			{
				if (ChildrenBelow.Count > 1)
					firstChild = ChildrenBelow[1];
			}
			else if (!MyItemInfo.IsSection && firstChild != null && firstChild.MyItemInfo != null && !firstChild.MyItemInfo.IsNumbered) // If not numbered get the last child
				firstChild = firstChild.MyParent.ChildrenBelow[firstChild.MyParent.ChildrenBelow.Count - 1];
			float ySizeIncludingFirst = firstChild == null ? YSize : firstChild.YSize + (firstChild.YTopMost - YTopMost);
			bool KeepStepsOnPage = MyItemInfo.ActiveFormat.MyStepSectionLayoutData.KeepStepsOnPage;
			if (MyItemInfo.IsStepSection)
			{
				if (yLocation < yTopMargin)  // continuous section
				{
					if (ChildrenBelow == null || ChildrenBelow.Count == 0)
					{
						// see if there is an end message.  This is stored in the helper - if there is,
						// we need to be sure that there is room for it.
						if (MyPageHelper.BottomMessage != null && MyPageHelper.BottomMessage.Count != 0)
						{
							if (mySize + yEndMsg <= yWithinMargins) return 1;
						}
						return 0;
					}
					// This is a continuous section.  There may be cases where the user put a manual page
					// break on the first step (child) in the section. if so, break on the section.  The
					// flag SectionPageBreak is set to true to flag that a pagebreak should not be done
					// on that first step.
					StepConfig sc = firstChild.MyItemInfo.MyConfig as StepConfig;
					ManualPageBreak = MyPageHelper.OriginalPageBreak ? (sc == null ? false : sc.Step_ManualPagebreak) :
						sc == null ? false : 
						MyPageHelper.MyPromsPrinter.RemoveTrailingHardReturnsAndManualPageBreaks ? false : sc.Step_NewManualPagebreak;
					
					if (ManualPageBreak)
					{
						SectionPageBreak = true;
						ShowPageBreak(2, "Section Page Break", "Yes", YSize, yPageSize, yWithinMargins, ManualPageBreak);
						return 1;
					}
					// can the title and the first step fit?
					// add the first child's size + (the section title's size)
					//if (ySizeIncludingFirst > (yLocation - yBottomMargin - SixLinesPerInch)) return 1;
					//if (ySizeIncludingFirst > (yLocation - yBottomMargin) && ySizeIncludingFirst < yPageSize)
					vlnParagraph firstStepChild = firstChild;
					//while (firstStepChild.MyItemInfo.IsSection && firstStepChild.ChildrenBelow.Count > 0) firstStepChild = firstStepChild.ChildrenBelow[0];
					if (firstStepChild.MyItemInfo.IsNumbered)
						while (firstStepChild.ChildrenBelow.Count > 0 && (firstStepChild.MyItemInfo.IsSection || firstStepChild.MyItemInfo.IsHigh))
						{
							firstStepChild = firstStepChild.ChildrenBelow[0];
							if (!firstStepChild.MyItemInfo.IsNumbered)
							{
								firstStepChild = firstStepChild.MyParent.ChildrenBelow[firstStepChild.MyParent.ChildrenBelow.Count - 1];
								break;
							}
						}
					else
						firstStepChild = firstStepChild.MyParent.ChildrenBelow[firstStepChild.MyParent.ChildrenBelow.Count - 1];
					float ySizeIncludingFirstStep = firstStepChild.YSize + (firstStepChild.YTopMost - YTopMost);
					float ySizeBtmCtnMess = GetBottomContinueMessageSize(MyItemInfo.MyDocStyle);
					float ySizeBtmEndMess = GetBottomEndMessageSize(MyItemInfo.MyDocStyle);
					bool firstSubstepExceedsSpaceAvailable = ySizeIncludingFirstStep > (yWithinMargins - ySizeBtmCtnMess -ySizeBtmEndMess);
					if (KeepStepsOnPage && firstSubstepExceedsSpaceAvailable && !isFirstChild)
						KeepStepsOnPage = false;
					if (ySizeIncludingFirst == YSize) KeepStepsOnPage = false;
					float ySectionEndMsg = !_skipEndMessage && MyItemInfo.IsSection && MyItemInfo.Steps != null && MyItemInfo.Steps.Count == 1 && (MyItemInfo.MyDocStyle.End.Message ?? "") != "" ? 2 * SixLinesPerInch : 0;
					if (MyPageHelper.NotesToFootNotes != null && MyPageHelper.NotesToFootNotes.Count > 0)
					{
						float vpHeight = SixLinesPerInch;
						foreach (vlnParagraph vp in MyPageHelper.NotesToFootNotes) vpHeight += vp.Height;
						ySectionEndMsg += vpHeight;
					}
					if (ySizeIncludingFirstStep < yWithinMargins && ySizeIncludingFirst > yWithinMargins && yWithinMargins > (yPageSize / 2))
						ySizeIncludingFirst = ySizeIncludingFirstStep;
					if (!KeepStepsOnPage && (ySizeIncludingFirst + ySectionEndMsg) >
						(yLocation - (MyItemInfo.MyDocStyle.Layout.FooterLength + yBottomMargin)) && !nearTheTop)
					{
						if (!MyItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvert ||
							(ySizeIncludingFirst < yPageSize || yWithinMargins < (yPageSize - (2 * 72))))
						{
							//    .oooooo.                             .    o8o                                                             .oooooo..o                         .    o8o                                 
							//   d8P'  `Y8b                          .o8    `"'                                                            d8P'    `Y8                       .o8    `"'                                 
							//  888           .ooooo.  ooo. .oo.   .o888oo oooo  ooo. .oo.   oooo  oooo   .ooooo.  oooo  oooo   .oooo.o    Y88bo.       .ooooo.   .ooooo.  .o888oo oooo   .ooooo.  ooo. .oo.    .oooo.o 
							//  888          d88' `88b `888P"Y88b    888   `888  `888P"Y88b  `888  `888  d88' `88b `888  `888  d88(  "8     `"Y8888o.  d88' `88b d88' `"Y8   888   `888  d88' `88b `888P"Y88b  d88(  "8 
							//  888          888   888  888   888    888    888   888   888   888   888  888   888  888   888  `"Y88b.          `"Y88b 888ooo888 888         888    888  888   888  888   888  `"Y88b.  
							//  `88b    ooo  888   888  888   888    888 .  888   888   888   888   888  888   888  888   888  o.  )88b    oo     .d8P 888    .o 888   .o8   888 .  888  888   888  888   888  o.  )88b 
							//   `Y8bood8P'  `Y8bod8P' o888o o888o   "888" o888o o888o o888o  `V88V"V8P' `Y8bod8P'  `V88V"V8P' 8""888P'    8""88888P'  `Y8bod8P' `Y8bod8P'   "888" o888o `Y8bod8P' o888o o888o 8""888P' 
							ShowPageBreak(4, "Page Break Before Continuous Step Section", "Yes", YSize, yPageSize, yWithinMargins, ManualPageBreak);
							return 1;
						}
					}
					if (ChildrenBelow.Count > 0)
					{
						vlnParagraph firstHLS = ChildrenBelow[0];
						if (firstHLS.MyItemInfo.IsHigh)
							firstHLS.BreakHighLevelStepWithSection = true;
					}
				}
				// Compress Foldout
				//
				//   .oooooo.                                                                                  oooooooooooo           oooo        .o8                            .   
				//  d8P'  `Y8b                                                                                 `888'     `8           `888       "888                          .o8   
				// 888           .ooooo.  ooo. .oo.  .oo.   oo.ooooo.  oooo d8b  .ooooo.   .oooo.o  .oooo.o     888          .ooooo.   888   .oooo888   .ooooo.  oooo  oooo  .o888oo 
				// 888          d88' `88b `888P"Y88bP"Y88b   888' `88b `888""8P d88' `88b d88(  "8 d88(  "8     888oooo8    d88' `88b  888  d88' `888  d88' `88b `888  `888    888   
				// 888          888   888  888   888   888   888   888  888     888ooo888 `"Y88b.  `"Y88b.      888    "    888   888  888  888   888  888   888  888   888    888   
				// `88b    ooo  888   888  888   888   888   888   888  888     888    .o o.  )88b o.  )88b     888         888   888  888  888   888  888   888  888   888    888 . 
				//  `Y8bood8P'  `Y8bod8P' o888o o888o o888o  888bod8P' d888b    `Y8bod8P' 8""888P' 8""888P'    o888o        `Y8bod8P' o888o `Y8bod88P" `Y8bod8P'  `V88V"V8P'   "888" 
				//                                           888                                                                                                                     
				//                                          o888o                                                                                                                    
				// This is a foldout pages
				// The format supports compression
				// The contents exceeds the length of the page
				// The Contents fit at seven lines per inch
				if (MyItemInfo.DisplayText.ToUpper().StartsWith("FOLDOUT")
					&& MyItemInfo.ActiveFormat.MyStepSectionLayoutData.CompressSteps
					&& mySize > yPageSize 
					&& mySize <= yPageSize * SixLinesPerInch / _SevenLinesPerInch)
					CompressFoldout = true;
				return 0; // Don't Paginate (page break) on a Step Section if it's first thing on page
			}
			if (!MyItemInfo.IsHigh) return 0;		// Don't Paginate on a Substep level
			bool  doSectionTitleContinued = false;
			if (MyPageHelper.NotesToFootNotes != null && MyPageHelper.NotesToFootNotes.Count > 0)
			{
				float vpHeight = SixLinesPerInch;
				foreach (vlnParagraph vp in MyPageHelper.NotesToFootNotes) vpHeight += vp.Height;
				yEndMsg += vpHeight;
			}
			if (MyItemInfo.MyPrevious != null && !MyItemInfo.IsSection && MyItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.ContinueSectionHeader)
			{
				SectionConfig sch = MyItemInfo.ActiveSection.MyConfig as SectionConfig;
				doSectionTitleContinued = (sch == null || sch.Section_PrintHdr == "Y") && !MyItemInfo.MyDocStyle.CancelSectTitle;
			}
			// Document style: DSS_PageBreakHLS breaks on hls.
			if (MyItemInfo.IsHigh && (MyItemInfo.MyDocStyle.StructureStyle.Style & E_DocStructStyle.DSS_PageBreakHLS) == E_DocStructStyle.DSS_PageBreakHLS)
			{
				BuildPageBreakList(yPageSize, yPageSize, KeepStepsOnPage, yEndMsg, doSectionTitleContinued & SectionShowTitles, true);
				ShowPageBreak(1, "Page Break on DSS_PageBreakHLS", "Yes", YSize, yPageSize, yWithinMargins, ManualPageBreak);
				return 1;
			}
			// if this is a step, see if it has the 'PageBreakOnStep' format flag set to true, if so, break here.
			if (MyItemInfo.FormatStepData != null && MyItemInfo.FormatStepData.PageBreakOnStep)
			{
				// if this step contains Cautions or Notes page breaks have to be added for those.
				if (TopMostChild != this) PageBreakOnStep = true;
				BuildPageBreakList(yPageSize, yPageSize, KeepStepsOnPage, yEndMsg, doSectionTitleContinued & SectionShowTitles, true);			// Case 1 :Works for ES05 Step 15 SubStep 7
				ShowPageBreak(1, "Page Break on Steps, Cautions or Notes", "Yes", YSize, yPageSize, yWithinMargins, ManualPageBreak);
				return 1;
			}
			
			//MyPageHelper.HLSText = MyItemInfo.DisplayText; // save the High Level Step Text
			//Console.WriteLine("{0} Paginate", MyPageHelper.HLSText);
			StepConfig sc1 = MyItemInfo.MyConfig as StepConfig;
			ManualPageBreak = MyPageHelper.OriginalPageBreak ? (sc1 == null ? false : sc1.Step_ManualPagebreak) :
				sc1 == null ? false : MyPageHelper.MyPromsPrinter.RemoveTrailingHardReturnsAndManualPageBreaks ? false : sc1.Step_NewManualPagebreak;
			if (MyItemInfo.FirstSibling == MyItemInfo && ManualPageBreak)
			{
				// if parent/section used this pagebreak, skip it.
				if (MyParent.SectionPageBreak)
				{
					ManualPageBreak = false;
					MyParent.SectionPageBreak = false;
				}
			}
			if (_Match16BitPagination) mySize = YSize;
			string firstStep = "No";
			if (MyItemInfo.IsHigh && MyItemInfo.MyPrevious == null)
				firstStep = "Yes";
			//if (!ManualPageBreak && mySize + yEndMsg <= yWithinMargins)			// Don't Paginate if there is enough room, will fit on page
			// Pagination Fix - Break1LineShort1
			float yExtra = (yWithinMargins == yPageSize ? 0 : SixLinesPerInch - MyItemInfo.MyDocStyle.Layout.FooterLength) ?? 0;
			// Adjust yExtra and mySize for Component List items. 
			if (MyItemInfo.ActiveSection.MyDocStyle.ComponentList && yExtra > 0)
			{
				yExtra = 0;
				if (mySize < Height) mySize = Height * MyPageHelper.YMultiplier;
			}
			float yExtra2 = (SixLinesPerInch - MyItemInfo.MyDocStyle.Layout.FooterLength) ?? 0;
			if (KeepStepsOnPage && !MyItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.StepSectionLayoutData.PaginateOnLowerStepLevel && ySizeIncludingFirst > yWithinMargins)
				KeepStepsOnPage = false;
			bool KeepWithHeader = isFirstChild && nearTheTop;
			if (BreakHighLevelStepWithSection) KeepWithHeader = true;
			// for a HLS that has an asterisk box with the rno separator IN the box, adjust the size by 2 lines to account for box.
			if (MyItemInfo.IsStep && MyItemInfo.MyHLS.FormatStepData.StepLayoutData.STBoxindex != null && MyItemInfo.MyHLS.FormatStepData.StepLayoutData.STBoxindex >= 0 &&
				(MyItemInfo.RNOs==null ||MyItemInfo.RNOs.Count==0))
				mySize += (2*SixLinesPerInch);
			// mySize is the size of this step and includes an extra blank line. For HLS, if this is the last step in section & there is room in footer to keep
 			// step on the page, do so by eliminating the blank line before doing the test to see if it fits.
			if (MyItemInfo.IsHigh && mySize >= (2 * SixLinesPerInch) && MyItemInfo.MyDocStyle.Layout.FooterLength > 0 && (MyItemInfo.MyDocStyle.End.Message == null || MyItemInfo.MyDocStyle.End.Message == "") && MyItemInfo.NextItem != null && (MyItemInfo.Steps == null || MyItemInfo.Steps.Count == 0) && (MyItemInfo.RNOs == null || MyItemInfo.RNOs.Count == 0))
				mySize -= SixLinesPerInch;
			//// Account for extra lines in the end message (flag < 0)
			float adjMsgY = 0;
			if (MyItemInfo.IsHigh && MyItemInfo.NextItem == null && MyItemInfo.MyDocStyle.End.Flag < 0)		// Adjust this many lines down the page.
			{
				adjMsgY = (float)-MyItemInfo.MyDocStyle.End.Flag * SixLinesPerInch;
				if (yEndMsg != 0) yEndMsg += adjMsgY;
			}
			if (!ManualPageBreak && (mySize + yEndMsg <= yWithinMargins + yExtra) || // Don't Paginate if there is enough room, will fit on page
				(mySize <= yWithinMargins + yExtra && SpecialCaseForRobinson()))			
			//if (!ManualPageBreak && mySize + yEndMsg <= yWithinMargins + SixLinesPerInch)			// Don't Paginate if there is enough room, will fit on page
			{
				//  ooooo   ooooo ooooo         .oooooo..o                      o8o  oooo  oooo      .o88o.  o8o      .   
				//  `888'   `888' `888'        d8P'    `Y8                      `"'  `888  `888      888 `"  `"'    .o8   
				//   888     888   888         Y88bo.         oooo oooo    ooo oooo   888   888     o888oo  oooo  .o888oo 
				//   888ooooo888   888          `"Y8888o.      `88. `88.  .8'  `888   888   888      888    `888    888   
				//   888     888   888              `"Y88b      `88..]88..8'    888   888   888      888     888    888   
				//   888     888   888       o oo     .d8P       `888'`888'     888   888   888      888     888    888 . 
				//  o888o   o888o o888ooooood8 8""88888P'         `8'  `8'     o888o o888o o888o    o888o   o888o   "888" 
				//Console.WriteLine("'PageBreak',1,'No','HLS will fit on page',{0},{1},{2}, {3}, {4},'{5}'", MyItemInfo.ItemID, YSize, yPageSize, yWithinMargins, (int)(100 * yWithinMargins / yPageSize), MyItemInfo.ShortPath);
				ShowPageBreak(-1, "HLS will fit on page", firstStep, YSize, yPageSize, yWithinMargins,ManualPageBreak);
				return 0;
			}
			// !MyItemInfo.IsHigh - if (MyItemInfo.IsRNOPart && MyParent.XOffset < XOffset) return 0; // Don't paginate on an RNO to the right
			// YSize includes a blank line after the step which we don't want to include in the page break test, thus the
			// YSize - SixLinesPerInch:
			// yPageSizeNextPage is the page size of the 'next' page.  A format variable exists off of the docstyle
			// For UseOnFirstPage vs UseOnAllButFirstPage.  If this is set for this format, and processing the FIRST
			// page, the size of next page, which may be different, is used in pagination calculationstop.
			// If this format flag is not set, or not printing the first page of the section with this flag,
			// this next page size is the same as current page size.
			float yPageSizeNextPage = yPageSize;
			mySize = YSize;   // reset in case mySize changed for current page is compressed
			// for a HLS that has an asterisk box with the rno separator IN the box, adjust the size by 2 lines to account for box.
			if (MyItemInfo.IsStep && MyItemInfo.MyHLS.FormatStepData.StepLayoutData.STBoxindex != null && MyItemInfo.MyHLS.FormatStepData.StepLayoutData.STBoxindex >= 0 &&
				(MyItemInfo.RNOs == null || MyItemInfo.RNOs.Count == 0))
				mySize += (2 * SixLinesPerInch);
			//if (firstStep == "No")
			//  ResetDocStyleAndValues(ref yTopMargin, ref yBottomMargin);
			if (MyPageHelper.DidFirstPageDocStyle && (MyItemInfo.MyActiveSection.MyDocStyle.StructureStyle.Where & E_DocStyleUse.UseOnAllButFirstPage) > 0)
				yPageSizeNextPage = GetYPageSizeUseOnAllButFirstPage();
			if (KeepStepsOnPage 
				&& !MyItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.StepSectionLayoutData.PaginateOnLowerStepLevel 
				&& YSize == ySizeIncludingFirst 
				&& YSize + yEndMsg > yWithinMargins) 
			{
				// If the first step is the size of the entire step and the step has an end message then don't try to break the step
				KeepStepsOnPage = false;
				//_MyLog.WarnFormat("Kick Step to Next Page {0},{1}", MyItemInfo.ItemID, MyItemInfo.ShortPath);
			}
			if (yWithinMargins < SixLinesPerInch) KeepStepsOnPage = false;  // if there is no room to print, don't keep steps on the page
			// The following was added for IP2 background printing.  There were situations where there was a HLS and its paragraph was
			// put on next page (IP2 bck: E-3/References), and a paragraph was writing into the footer (FR-H.1 step 2.2.3.1.  KBR 10/14/14)
			if (KeepStepsOnPage
				&& MyItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.StepSectionLayoutData.PaginateOnLowerStepLevel
				&& YSize == ySizeIncludingFirst
				&& ((ChildrenBelow.Count >= 1 && ChildrenBelow[0].MyItemInfo.IsParagraph && ChildrenBelow[0].ChildrenBelow.Count == 0)
					|| ChildrenBelow.Count == 0))
			{
				KeepStepsOnPage = false;
			}
			// Keep figure (the only figure, i.e. count==1) with its parent.
			if (ChildrenBelow.Count == 1 && ChildrenBelow[0].MyItemInfo.IsFigure) KeepStepsOnPage = false;
			float sectionSpace = 0;
			if (doSectionTitleContinued)
			{
				if (SectionShowTitles)
				{
					vlnParagraph paraSect = MyParent;
					while (!paraSect.MyItemInfo.IsSection) paraSect = paraSect.MyParent;
					if (paraSect.ContinueHeight > 24)
						sectionSpace = paraSect.ContinueHeight;
					else
						sectionSpace = 2 * SixLinesPerInch;
					//	sectionSpace = 3 * SixLinesPerInch;// this should actuall use the physical size of the continue messsage.
					// Fixing this caused problems with pagination ex Calvert Unit 2 IO-1l section 6.1.B step 2
					//if (MyItemInfo.ActiveSection.DisplayText.Length < 40) sectionSpace = SixLinesPerInch;
					yPageSizeNextPage -= sectionSpace;
					yExtra -= sectionSpace;
					//yExtra2 -= sectionSpace; // This was removed for Calvert STP O-73H-2 Section 6.3.O.4 and 6.3.R.3
				}
			}
			if (MyItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvert && yPageSizeNextPage < yWithinMargins + 3*72 && MyItemInfo.MyPrevious == null)
				KeepStepsOnPage = true;
			float mySize7LPI = mySize; // +SixLinesPerInch;
			if (_Match16BitPagination) mySize7LPI += SixLinesPerInch;
			float tableSpaceAvailable = TableSpaceAvailable;// RHM20150525 - Table Scrunch
			float ySizeBtmCtnMess1 = GetBottomContinueMessageSize(MyItemInfo.MyDocStyle);
			float ySizeBtmEndMess1 = GetBottomEndMessageSize(MyItemInfo.MyDocStyle);
			// B2017-154 Don't leave an orphan on the next page if the high level step and first sub-step will fit on the current page
			if (MyItemInfo.ActiveFormat.MyStepSectionLayoutData.NoOrphans1 &&  KeepStepsOnPage && ChildrenBelow.Count == 2)// Handle Orphans when there are two sub-steps and only one will fit.
			{
				vlnParagraph orphan = ChildrenBelow[1];// Verify that the orphan has no children
				if (orphan.ChildrenBelow.Count == 0 && orphan.ChildrenAbove.Count == 0 && orphan.ChildrenLeft.Count == 0 && orphan.ChildrenRight.Count == 0)
				{
					//_MyLog.WarnFormat("Orphan Found {0},{1}", MyItemInfo.ItemID, MyItemInfo.ShortPath);
					KeepStepsOnPage = false;
				}
			}
			if (KeepStepsOnPage && ySizeIncludingFirst > (yWithinMargins - ySizeBtmCtnMess1 - ySizeBtmEndMess1)) KeepStepsOnPage = false;
			if (!KeepWithHeader && !KeepStepsOnPage && mySize - SixLinesPerInch + yEndMsg - tableSpaceAvailable <= yPageSizeNextPage)	// if the entire step can fit on one page, do a page break
			{
				// Don't want extra line before step
				//Console.WriteLine("'PageBreak',2,'Yes','HLS will fit on 1 Page',{0},{1},{2}, {3}, {4},'{5}'", MyItemInfo.ItemID, YSize, yPageSize, yWithinMargins, (int)(100 * yWithinMargins / yPageSize), MyItemInfo.ShortPath);
				// A page break will occur before the step is put out.  ShowPageBreak with first argument of -1 is NOT a page break.
				//      .ooo   ooooo        ooooooooo.   ooooo 
				//    .88'     `888'        `888   `Y88. `888' 
				//   d88'       888          888   .d88'  888  
				//  d888P"Ybo.  888          888ooo88P'   888  
				//  Y88[   ]88  888          888          888  
				//  `Y88   88P  888       o  888          888  
				//   `88bod8'  o888ooooood8 o888o        o888o 
				ShowPageBreak(5, "HLS will fit on 1 Page at 6 LPI", "Yes", YSize, yPageSizeNextPage, yWithinMargins, ManualPageBreak);
				return 1;
			}
			// TODO - yEndMsg - compressed size?
				// ySize7LPI includes a blank line after the step which we don't want to include in the page break test.
			else if (!KeepStepsOnPage && MyItemInfo.ActiveFormat.MyStepSectionLayoutData.CompressSteps 
				//&& (mySize7LPI - SixLinesPerInch + yEndMsg - tableSpaceAvailable) < (yPageSizeNextPage * SixLinesPerInch / _SevenLinesPerInch))// RHM20150525 - Table Scrunch
				// if this is the first step, then the step has to fit in the space that remains on the page
				// otherwise it needs to fit on a blank page
				// This was originally (10/12/2015) added for Farley Shared AOP 79 but was found to be unnecessary
				// jsj 5-17-2016 B2015-090 - Turns out that Wolf Creek needs this logic to properly print
				//                           the Purpose, Symptoms or Entry Conditions, and References and Commitments sections which are set to print continuous.
				//                           Without this logic, the first step of section 2.0 print on top of the section text in OFN BB-007
				&& (mySize7LPI - SixLinesPerInch + yEndMsg - tableSpaceAvailable) < ((MyItemInfo.MyPrevious == null ? yWithinMargins : yPageSizeNextPage) * SixLinesPerInch / _SevenLinesPerInch))// RHM20150525 - Table Scrunch
			{
				//   ooooooooo ooooo        ooooooooo.   ooooo 
				//  d"""""""8' `888'        `888   `Y88. `888' 
				//        .8'   888          888   .d88'  888  
				//       .8'    888          888ooo88P'   888  
				//      .8'     888          888          888  
				//     .8'      888       o  888          888  
				//    .8'      o888ooooood8 o888o        o888o 
				//Console.WriteLine("'PageBreak',3,'Yes','HLS will fit on 1 Page at 7 LPI',{0},{1},{2}, {3}, {4},'{5}'", MyItemInfo.ItemID, YSize, yPageSize, yWithinMargins, (int)(100 * yWithinMargins / yPageSize), MyItemInfo.ShortPath);
				ShowPageBreak(7, "HLS will fit on 1 Page at 7 LPI", "Yes", YSize, yPageSizeNextPage, yWithinMargins, ManualPageBreak);
				//Console.WriteLine("'7LPI',{0},{1}", MyItemInfo.DBSequence, YSize);
				return 3; // High Level Step can fit at SevenLinesPerInch
			}
			else // The entire step cannot fit on a blank page or KeepStepsOnPage is true.
			{
				// if there is more than half a page left, then start to print on the current page
				float myFirstPieceSize = GetFirstPieceSize();		//Case 0
				if (_Match16BitPagination) myFirstPieceSize += 2 * SixLinesPerInch;
				// TODO:  Put this line back to case 0, i.e. previous line.  This fixes a 16-bit vs 32-bit pagination diff in EO30 Step 20.
				//float myFirstPieceSize = GetFirstPieceSize() + 2 * SixLinesPerInch;		//Case 10 - this is to match 16bit
				//is the amount of space left (yWithinMargins) is greater than 1/2 of the current page (yPageSize / 2):
				// VCS EOP-4.3 Step 15
				// ***** Adjust yWithinMargins for the bottom continue message
				//DocStyle docstyle = MyItemInfo.MyDocStyle;
				//string myBottomMsg = docstyle.Continue.Bottom.Message;
				//float myBottomMsgSpace = ((myBottomMsg ?? "") != "") ? 2 * SixLinesPerInch : 0;
				//switch (docstyle.Continue.Bottom.Location)
				//{
				//  case E_ContBottomLoc.BottomOfPage:				// place continue message at bottom of page
				//    // The following format flag was added for FNP, without the flag (which stops the reset of BottomMsgSpace)
				//    //  a number of FNP procedures had overwritten steps/bottom continue message.  An example can be
				//    //  found in FNP = SAMGS;FNP-1-SACRG-2, step 1.
				//    if (!docstyle.Continue.Bottom.NoOverrideSpace)
				//      myBottomMsgSpace = 0;
				//    break;
				//}
				//float yWithinMarginsCM = yWithinMargins - myBottomMsgSpace;
				//// **** Adjust yWithinMargins for the bottom continue message
				if (KeepWithHeader ||( !ManualPageBreak && ((MyItemInfo.ActiveFormat.MyStepSectionLayoutData.SpecialPageBreakFlag && yWithinMargins > yPageSize / 2 &&
					myFirstPieceSize < yWithinMargins) || KeepStepsOnPage)))
				{
					//Console.WriteLine("'PageBreak',4,'No','HLS will have to split anyway',{0},{1},{2}, {3}, {4},'{5}'", MyItemInfo.ItemID, YSize, yPageSize, yWithinMargins, (int)(100 * yWithinMargins / yPageSize), MyItemInfo.ShortPath);
					// yPageSize is space on next page. This may be different if the format flag 'UseOnAllButFirst' is
					// set.
					// yWithinMargins is space available on current page.
					// if the HLS is part of a Smart Template (i.e. WCNCKL table), don't add in an extra line because
					// that makes pagination work incorrectly because the Smart Template has a 'table' line after the
					// text.
					float	ySpaceOnFirstPage = yWithinMargins + (MyItemInfo.FormatStepData.UseSmartTemplate ? 0 : SixLinesPerInch);
					if (firstStep == "Yes")
					//{
						ySpaceOnFirstPage = yWithinMargins; // Accounts for Section Title Line
						//ShowPageBreak(8, CheckForCompression("First HLS has to split on current page"), firstStep, YSize, yPageSizeNextPage, yWithinMargins, ManualPageBreak);
					//}
					//else
					//	ShowPageBreak(6, CheckForCompression("HLS will have to split on current page"), "Special", YSize, yPageSizeNextPage, yWithinMargins, ManualPageBreak);
					//BuildPageBreakList(yWithinMargins + SixLinesPerInch, yPageSizeNextPage + yExtra2, KeepStepsOnPage);	// Case 5 - Determine items where page break(s) occur
					BuildPageBreakList(ySpaceOnFirstPage, yPageSize + yExtra2, KeepStepsOnPage, yEndMsg, doSectionTitleContinued & SectionShowTitles, false);	// Case 5 - Determine items where page break(s) occur
					//  ooooo   ooooo ooooo         .oooooo..o     .oooooo..o            oooo   o8o      .        .oooooo.                                                           .   
					//  `888'   `888' `888'        d8P'    `Y8    d8P'    `Y8            `888   `"'    .o8       d8P'  `Y8b                                                        .o8   
					//   888     888   888         Y88bo.         Y88bo.      oo.ooooo.   888  oooo  .o888oo    888          oooo  oooo  oooo d8b oooo d8b  .ooooo.  ooo. .oo.   .o888oo 
					//   888ooooo888   888          `"Y8888o.      `"Y8888o.   888' `88b  888  `888    888      888          `888  `888  `888""8P `888""8P d88' `88b `888P"Y88b    888   
					//   888     888   888              `"Y88b         `"Y88b  888   888  888   888    888      888           888   888   888      888     888ooo888  888   888    888   
					//   888     888   888       o oo     .d8P    oo     .d8P  888   888  888   888    888 .    `88b    ooo   888   888   888      888     888    .o  888   888    888 . 
					//  o888o   o888o o888ooooood8 8""88888P'     8""88888P'   888bod8P' o888o o888o   "888"     `Y8bood8P'   `V88V"V8P' d888b    d888b    `Y8bod8P' o888o o888o   "888" 
					//                                                         888                                                                                                       
					//                                                        o888o                                                                                                      
					if (firstStep == "Yes")
					{
						//ySpaceOnFirstPage = yWithinMargins; // Accounts for Section Title Line
						ShowPageBreak(8, CheckForFirstCompression("First HLS has to split on current page"), firstStep, YSize, yPageSizeNextPage, yWithinMargins, ManualPageBreak);
					}
					else
						ShowPageBreak(6, CheckForFirstCompression("HLS will have to split on current page"), "Special", YSize, yPageSizeNextPage, yWithinMargins, ManualPageBreak);
					return 0;	// Stay on this page
				}
				// Less than half a page left, start printing on a new page.
				//Console.WriteLine("'PageBreak',5,'Yes','HLS will have to split',{0},{1},{2}, {3}, {4},'{5}'", MyItemInfo.ItemID, YSize, yPageSize, yWithinMargins, (int)(100 * yWithinMargins / yPageSize), MyItemInfo.ShortPath);
				// Determine items where page break(s) occur
				//BuildPageBreakList(yPageSize, yPageSize - 2 * SixLinesPerInch);		// Case Base
				//BuildPageBreakList(yPageSize, yPageSize);			// Case 1 :Works for ES05 Step 15 SubStep 7
				// Pagination Fix Break1LineShort2	
				//BuildPageBreakList(yPageSize + yExtra, yPageSize);			// Case 1 :Works for ES05 Step 15 SubStep 7
				// Pagination Fix Break1LineShort4	
				BuildPageBreakList(yPageSize + yExtra, yPageSizeNextPage + yExtra2, KeepStepsOnPage, yEndMsg, doSectionTitleContinued & SectionShowTitles, true);			// Case 1 :Works for ES05 Step 15 SubStep 7
				//  ooooo   ooooo ooooo         .oooooo..o     .oooooo..o            oooo   o8o      .      ooooo      ooo                            
				//  `888'   `888' `888'        d8P'    `Y8    d8P'    `Y8            `888   `"'    .o8      `888b.     `8'                            
				//   888     888   888         Y88bo.         Y88bo.      oo.ooooo.   888  oooo  .o888oo     8 `88b.    8   .ooooo.  oooo oooo    ooo 
				//   888ooooo888   888          `"Y8888o.      `"Y8888o.   888' `88b  888  `888    888       8   `88b.  8  d88' `88b  `88. `88.  .8'  
				//   888     888   888              `"Y88b         `"Y88b  888   888  888   888    888       8     `88b.8  888ooo888   `88..]88..8'   
				//   888     888   888       o oo     .d8P    oo     .d8P  888   888  888   888    888 .     8       `888  888    .o    `888'`888'    
				//  o888o   o888o o888ooooood8 8""88888P'     8""88888P'   888bod8P' o888o o888o   "888"    o8o        `8  `Y8bod8P'     `8'  `8'     
				//                                                         888                                                                        
				//                                                        o888o                                                                       
				if (firstStep == "Yes")
					ShowPageBreak(9, CheckForFirstCompression("First HLS will have to split on new page"), "Yes", YSize, yPageSizeNextPage, yWithinMargins, ManualPageBreak);
				else
					ShowPageBreak(3, CheckForFirstCompression("HLS will have to split on new page"), "Yes", YSize, yPageSizeNextPage, yWithinMargins, ManualPageBreak);
				return 1;		// Paginate on High Level Steps
			}
			//if (yWithinMargins > yPageSize / 2)
			//{
			//    Console.WriteLine("'PageBreak',4,'No','Not Half way down the page',{0},{1},{2}, {3}, {4},'{5}'", MyItemInfo.ItemID, YSize, yPageSize, yWithinMargins, (int)(100 * yWithinMargins / yPageSize), MyItemInfo.ShortPath);
			//    return 0; // More than half way down the page 
			//}
			//if (ChildrenBelow.Count > 0 &&  ChildrenBelow[0].YSize < yWithinMargins)
			//  return 0;
			//Console.WriteLine("'PageBreak',5,'Yes','At least half the page is filled',{0},{1},{2},{3}, {4},'{5}'", MyItemInfo.ItemID, YSize, yPageSize, yWithinMargins, (int)(100 * yWithinMargins / yPageSize), MyItemInfo.ShortPath);
			//return 2;
			throw new Exception("PageBreak Logic Missing, vlnParagraph.cs");
		}
		private float GetBottomEndMessageSize(DocStyle docstyle)
		{
			float myBottomMsgSpace = 0;
			if (MyItemInfo.IsHigh && MyItemInfo.NextItem == null && MyItemInfo.MyDocStyle.End.Flag < 0)		// Adjust this many lines down the page.
			{
				docstyle = MyItemInfo.MyDocStyle;
				string myBottomMsg = docstyle.End.Message;
				myBottomMsgSpace = ((myBottomMsg ?? "") != "") ? 2 * SixLinesPerInch : 0;
				if (myBottomMsg != null && docstyle.End.Flag < 0) myBottomMsgSpace += (-(float)docstyle.End.Flag * SixLinesPerInch);
			}
			return myBottomMsgSpace;
		}
		private string CheckForFirstCompression(string reason)
		{
			if (MyPageHelper.ParaBreaks.Count > 0 && MyPageHelper.ParaBreaks[0].CompressFirstPartOfStep)
				return reason + " - 7 LPI";
			return reason;
		}
		private string CheckForCompression(string reason)
		{
			if (CompressPartOfStep)
				return reason + " - 7 LPI";
			return reason;
		}
		private string AddReason(string prefix)
		{
			string retval = prefix;
			if (PageBreakReason != null)
				retval += " - " + PageBreakReason;
			return retval;
		}
		private bool SectionShowTitles
		{
			get
			{
				vlnParagraph parent = MyParent;
				while (!parent.MyItemInfo.IsSection)
					parent = parent.MyParent;
				return parent.ShowSectionTitles;
			}
		}
		private bool SpecialCaseForRobinson()
		{
			if (MyItemInfo.ActiveFormat.Name.StartsWith("CPL") &&
				MyItemInfo.MyPrevious == null &&
				MyItemInfo.NextItem == null &&
				MyItemInfo.Tables != null &&
				MyItemInfo.Cautions == null &&
				MyItemInfo.Notes == null &&
				MyItemInfo.Steps == null) return true;
			return false;
		}
		private float GetYPageSizeUseOnAllButFirstPage()
		{
			float _PointsPerPage = 792;
			int indx = (int)MyItemInfo.MyDocStyle.IndexOtherThanFirstPage;
			foreach (DocStyle ds in MyItemInfo.ActiveFormat.PlantFormat.DocStyles.DocStyleList)
			{
				if (ds.Index == indx)
				{
					float yTopMargin = _PointsPerPage - (float)ds.Layout.TopMargin;
					float yBottomMargin = Math.Max(0, yTopMargin - (float)ds.Layout.PageLength);
					return yTopMargin - yBottomMargin;
				}
			}
			return 0;
		}
		private void ForcePagination(PdfContentByte cb, ref float yPageStart, float yTopMargin, float yBottomMargin, ref float yLocation, ref float retval)
		{
			MyPromsPrinter.NewPage();
			DebugText.WriteLine("*****PaginateError");
			yPageStart = yTopMargin + YVeryTop;
			yLocation = yPageStart - YOffset;
			//MyItemInfo.ItemID, YSize, yPageSize, yLocation
			//_MyLog.ErrorFormat("<<< ERROR >>> Forced Pagination - ItemID = {0}\r\nLocation = '{1}'", MyItemInfo.ItemID, MyItemInfo.ShortPath);
			_MyLog.ErrorFormat("<<< ERROR >>> Forced Pagination\r\n==>'Forced Pagination',{0},'{1}','{2}'"
				, MyItemInfo.ItemID, MyItemInfo.MyDocVersion.MyFolder.Name, MyItemInfo.ShortPath);
			if(DebugPagination.IsOpen) DebugPagination.WriteLine("=====>,'Yes','Forced Pagination',{0},{1},,{3},'{4}'", MyItemInfo.ItemID, YSize, 0, yLocation, MyItemInfo.ShortPath);
			if (MyPromsPrinter.SupInfoPrintType == E_SupInfoPrintType.Merge && MyPageHelper.CreatingSupInfoPage)
				MyPromsPrinter.SupInfoPdfPageCount++; // this adjusts the page count offset when Forced Pagination occures in a SupInfo page
			retval = Rtf2Pdf.TextAt(cb, IParagraph, XOffset, yLocation, Width, 100, DebugInfo, yBottomMargin);
		}
		private void ShowPageBreak(int instance, string message, string breakOrNot, float YSize, float yPageSize, float yWithinMargins, bool manualPageBreak)
		{
			if (breakOrNot != "No")
			{
				bool hasBox = MyItemInfo.IsStep && MyItemInfo.MyHLS.FormatStepData.StepLayoutData.STBoxindex != null && MyItemInfo.MyHLS.FormatStepData.StepLayoutData.STBoxindex >= 0;
				bool rnoSepIn = (MyItemInfo.RNOs==null ||MyItemInfo.RNOs.Count==0);
				// DebugPagination.WriteLine("{0}", MyItemInfo.DBSequence); //,instance);
				if (DebugPagination.IsOpen) DebugPagination.WriteLine("{0:D6},'{1}',{2},'{3}','{4}',{5},{6},{7},{8},{9},{10},{11}", 
					MyPageHelper.MyPdfContentByte.PdfWriter.CurrentPageNumber - (breakOrNot == "Yes" ? 0 : 1), 
					MyItemInfo.ShortPath, instance,
					(manualPageBreak ? "Manual " : "") + message, breakOrNot,
					MyItemInfo.ItemID, YSize, yPageSize, yWithinMargins, (int)(100 * yWithinMargins / yPageSize),
					hasBox, rnoSepIn
					);
			}
			// Console.WriteLine("{0},{1}", MyItemInfo.DBSequence, IsFirstSubStep(MyItemInfo)); //,instance);
		}
		private bool ParentHasCalvertMacro
		{
			get
			{
				if (HasCalvertMacro) return true;
				if (MyParent != null) return MyParent.ParentHasCalvertMacro;
				return false;
			}
		}
		private List _AlternateBreaks = null;
		public List AlternateBreaks
		{
			get 
			{
				if (_AlternateBreaks == null)
					_AlternateBreaks = new List();
				return _AlternateBreaks; 
			}
		}
		private void AddAlternateBreak(vlnParagraph vp)
		{
			AlternateBreaks.Add(vp);
		}
		private bool CheckAlternates(vlnParagraph vpBrk)
		{
			if (_AlternateBreaks == null) return false;
			foreach(vlnParagraph vp in AlternateBreaks)
				if (vp.MyItemInfo.ItemID == vpBrk.MyItemInfo.ItemID)
				{
//					_MyLog.WarnFormat("alternate used '{0}'-'{1}'",vpBrk.MyItemInfo.ShortPath,vp.MyItemInfo.ShortPath);
					return true;
				}
			return false;
		}
		private vlnParagraph FirstCRParagraph(vlnParagraph pg)
		{
			if (pg.HasCalvertMacro) return null;
			while ( !pg.MyParent.HasCalvertMacro)
				pg = pg.MyParent;
			if(pg.MyItemInfo.MyPrevious == null) 
				return pg;
			return pg.MyParent.ChildrenBelow[0];
		}
		private void BuildPageBreakList(float ySpaceOnCurPage, float yPageSize, bool KeepStepsOnPage, float yEndMsg, bool doSectionTitleContinued, bool onNewPage)
		{
			float topContinueHeight=2 * SixLinesPerInch;
			int profileDepth = ProfileTimer.Push(">>>> BuildPageBreakList");
			// if this paragraph is flagged to pagebreakonstep (i.e. these are used by background documents
			// to get each hls/caution/note to be on its own page), then any of the children above should
			// also have the flag set and be added to the pagebreakonsteplist so that a break occurs.
			List PageBreakOnStepList = new List();
			if (PageBreakOnStep)
			{
				foreach (vlnParagraph chldAbove in _ChildrenAbove)
				{
					if (TopMostChild != chldAbove)
					{
						chldAbove.PageBreakOnStep = true;
						PageBreakOnStepList.Add(chldAbove);
					}
				}
				PageBreakOnStepList.Add(this);
			}
			ParagraphLocations myLocations = new ParagraphLocations();
			BuildLocationList(YTopMost, myLocations);
			StepLevelList myList = myLocations.BuildStepLevelList(KeepStepsOnPage);
			SortedList myPreferredBreaks = GetMyPreferredBreaks(myList);
			// Find Break Locations in the list based upon StepLevel and yLocation
			float yTop = 0;
			float yLowerLimit = (yPageSize - 2 * SixLinesPerInch) / 2;
			float yStart = Math.Max(0, (yPageSize - 2 * SixLinesPerInch) - ySpaceOnCurPage);
			//Console.WriteLine("'yStart',{0},{1}", MyItemInfo.DBSequence, yStart);
			// The following three lines make page breaking match 16-bit:
			if (_Match16BitPagination)
			{
				yLowerLimit = yStart - SixLinesPerInch + ySpaceOnCurPage / 2;
				if ((yStart + MyItemInfo.MyDocStyle.Layout.TopMargin + 2 * SixLinesPerInch) > ((MyItemInfo.MyDocStyle.Layout.TopMargin + yPageSize - 2 * SixLinesPerInch) / 2))
					yLowerLimit = yStart + 2 * SixLinesPerInch;
			}
			// Make sure that the FirstPiece (Caution Note HLS and First Substeps) fit
			float myFirstPieceSize = GetFirstPieceSize();		//Case 0
			// the following logic was added to fix Pagination for VCS BDMG1 Step 4
			if (ChildrenRight.Count > 0 && ChildrenRight[0].YOffset == YOffset)
			{
				float myFirstPieceRNOSize = 0;
				myFirstPieceRNOSize = ChildrenRight[0].GetFirstPieceSize();
				if(myFirstPieceRNOSize < ySpaceOnCurPage)
					if (ChildrenBelow.Count > 0)
					{
						float myFirstPieceAERSize = ChildrenBelow[0].GetFirstPieceSize() + ChildrenBelow[0].YOffset - YOffset;
						if (myFirstPieceAERSize < myFirstPieceRNOSize)
							myFirstPieceSize = myFirstPieceAERSize;
					}
			}
			if (myFirstPieceSize < ySpaceOnCurPage) yLowerLimit = Math.Max(myFirstPieceSize + yStart, yLowerLimit);
			//while ((YSize - yTop) >= ySpaceOnCurPage)
			// Pagination Fix Break1LineShort3b
			DocStyle docstyle = MyItemInfo.MyDocStyle;
			float myBottomMsgSpace = GetBottomContinueMessageSize(docstyle);
			switch (docstyle.Continue.Bottom.Location)
			{
				case E_ContBottomLoc.BottomOfPage:				// place continue message at bottom of page
					// The following format flag was added for FNP, without the flag (which stops the reset of BottomMsgSpace)
					//  a number of FNP procedures had overwritten steps/bottom continue message.  An example can be
					//  found in FNP = SAMGS;FNP-1-SACRG-2, step 1.
					if (!docstyle.Continue.Bottom.NoOverrideSpace)
						myBottomMsgSpace = 0;	
					break;
			}
			// also account for phonelist for locating bottom continue message:
			if (MyItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.PrintPhoneList && MyPageHelper.PhoneListHeight != 0)
				myBottomMsgSpace += (MyPageHelper.PhoneListHeight - vlnPrintObject.SixLinesPerInch);
			string myTopMsg = docstyle.Continue.Top.Message;
			float myTopMsgSpace = ((myTopMsg ?? "") != "") ? 2 * SixLinesPerInch : 0;
			// For B2016-157 & B2015-211: myTopMsgSpace is 1 line, not 2.  Note that this may be a more generic solution, but
			// it was found during print testing for BGE and flag is used to minimize impact on other formats
			if (MyItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvertPagination) myTopMsgSpace = ((myTopMsg ?? "") != "") ? SixLinesPerInch : 0;
			if (myTopMsgSpace > 0 && doSectionTitleContinued)
			{
				vlnParagraph parSection = this.MyParent;
				while (!parSection.MyItemInfo.IsSection) parSection = parSection.MyParent;
				topContinueHeight = parSection.ContinueHeight;
				if (topContinueHeight > myTopMsgSpace)
				{
					myTopMsgSpace = topContinueHeight;
				}
			}
			// while the amount to print is larger than one page, i.e. ((YSize - yTop) > ySpaceOnCurPage))
			//   OR there are page breaks for HLS/cautions/notes remaining, typically for backgrounds (PageBreakOnStepList.Count > 0)
			vlnParagraph paraBreak = null;
			float accountForCalvertAlarmConditionResponseFooter = 0;
			// The following code determines space required by the Checklist header (Wolf Creek) if a break occurs
			// Their 2 HLS that define the checklists have 'UseSmartTemplate'.
			float accountForSmartTemplateHeader = 0;
			//if (MyItemInfo.InList(878)) Console.WriteLine("Here");
			if (MyItemInfo.FormatStepData.UseSmartTemplate)
			{
				if (((MyItemInfo.MyDocStyle.End.Message ?? "") == "") || MyItemInfo.MyHLS.NextItem != null)
					ySpaceOnCurPage += SixLinesPerInch;
				accountForSmartTemplateHeader = Height - (2 * SixLinesPerInch);
			}
			// This was added so that if a page break was immediately necessary the code would use the current step.
			// However, a better solution was found and put in Paginate()
			//if (YSize == Height + SixLinesPerInch && YSize + yEndMsg >= ySpaceOnCurPage)
			//{
			//  _MyLog.WarnFormat("Would have been unable to break {0},{1}",MyItemInfo.ItemID, MyItemInfo.ShortPath);
			//  MyPageHelper.ParaBreaks.Add(this);
			//  return;
			//}
			//  ooooo      ooo                           .      oooooooooo.                               oooo        
			//  `888b.     `8'                         .o8      `888'   `Y8b                              `888        
			//   8 `88b.    8   .ooooo.  oooo    ooo .o888oo     888     888 oooo d8b  .ooooo.   .oooo.    888  oooo  
			//   8   `88b.  8  d88' `88b  `88b..8P'    888       888oooo888' `888""8P d88' `88b `P  )88b   888 .8P'   
			//   8     `88b.8  888ooo888    Y888'      888       888    `88b  888     888ooo888  .oP"888   888888.    
			//   8       `888  888    .o  .o8"'88b     888 .     888    .88P  888     888    .o d8(  888   888 `88b.  
			//  o8o        `8  `Y8bod8P' o88'   888o   "888"    o888bood8P'  d888b    `Y8bod8P' `Y888""8o o888o o888o 
			// For B2016-157 & B2015-211.  Note that this may be a more generic solution, but
			// it was found during print testing for BGE and flag is used to minimize impact on other formats
			float yAccountForBottomMsg = (MyItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvertPagination) ? myBottomMsgSpace : 0;
			while (((YSize - yTop) > (ySpaceOnCurPage - (accountForCalvertAlarmConditionResponseFooter + yEndMsg))) || PageBreakOnStepList.Count > 0)
			{
				float ySpaceOnCurPageSave = ySpaceOnCurPage;
				if (((YSize - yTop) <= (ySpaceOnCurPage - accountForCalvertAlarmConditionResponseFooter)) || PageBreakOnStepList.Count > 0)
					ySpaceOnCurPage -= yEndMsg;
				ySpaceOnCurPage -= myBottomMsgSpace;
				vlnParagraph lastBreak = paraBreak;
				// PageBreakOnStepList contains steps where a page break needs to occur based on format, for example backgrounds require cautions/notes/HLS
				// to have page breaks.  As each of these are processed (after this code) the topmost item in PageBreakOnStepList is removed.
				// The following checks if the entire step will fit for these types of steps and if so return the next break, i.e. [0], from the PageBreakOnStepList.
				// The if was changed to fix B2017-161.
				if (PageBreakOnStepList.Count > 0 && (PageBreakOnStepList[0].YTop - (lastBreak == null ? ((TopMostChild != null) ? TopMostChild.YTop : 0) : lastBreak.YTop) <= ySpaceOnCurPage))
					paraBreak = PageBreakOnStepList[0];
				else
				{
					paraBreak = FindPageBreak(yStart, ySpaceOnCurPage - accountForCalvertAlarmConditionResponseFooter - yAccountForBottomMsg, yLowerLimit,
						myList, lastBreak, yPageSize - (myTopMsgSpace + SixLinesPerInch) - myBottomMsgSpace,
						myBottomMsgSpace, MyItemInfo.ActiveFormat.PlantFormat.FormatData.StepDataList[40].ContinueOnly);
					// B2017-109: for supplemental information, if there is a preferred page break, account for it.  
					if (myPreferredBreaks != null && myPreferredBreaks.Count > 0 && myPreferredBreaks.Keys[0] < paraBreak.YOffset)
					{
						// B2017-122: don't use preferred break if the last break was before this break 
						vlnParagraph prefBreak = myPreferredBreaks[myPreferredBreaks.Keys[0]];
						if (lastBreak == null || lastBreak.MyItemInfo.ShortPath.CompareTo(prefBreak.MyItemInfo.ShortPath) == -1)
							paraBreak = prefBreak;
						myPreferredBreaks.RemoveAt(0);
					}
				}
				yAccountForBottomMsg = 0;
				// Do Not Remove: The following is used for debug - useful place to debug
				//if (paraBreak.MyItemInfo.InList(207, 211, 214, 219, 221, 216, 197)) Console.WriteLine("BUILD2: Break at {0}", paraBreak.MyItemInfo.ShortPath);//Comment Out before release
				//if (lastBreak != null &&  lastBreak.MyItemInfo.InList(80091, 1985)) 
				//    Console.WriteLine("After 80091 {0}",paraBreak.ToString());
				//if (paraBreak.MyItemInfo.InList(981,996)) Console.WriteLine("Here");
				if (paraBreak == null)
				{
					if (DebugPagination.IsOpen) DebugPagination.WriteLine("<<< ERROR >>> Cannot find a place to break ==>,{0},'{1}','{2}',{3},{4}"
						, MyItemInfo.ItemID, MyItemInfo.MyDocVersion.MyFolder.Name, MyItemInfo.ShortPath, YSize - yTop, ySpaceOnCurPageSave);
					_MyLog.ErrorFormat("<<< ERROR >>> Cannot find a place to break\r\n==>'Cannot Find Place to Break',{0},'{1}','{2}'"
						, MyItemInfo.ItemID, MyItemInfo.MyDocVersion.MyFolder.Name, MyItemInfo.ShortPath);
					break;
				}
				//if (paraBreak.MyItemInfo.InList(54615, 54620) || MyItemInfo.InList(54573))
				//{
				//	Console.WriteLine("{0}\t{1}", MyItemInfo.ItemID, paraBreak);
				//	Console.WriteLine("Here");
				//}
				if (paraBreak.MyItemInfo.IsStep && ((paraBreak.MyItemInfo.MyActiveSection.MyDocStyle.StructureStyle.Style & E_DocStructStyle.DSS_PageListSpBckgrnd) == E_DocStructStyle.DSS_PageListSpBckgrnd) &&
				paraBreak.MyItemInfo.FormatStepData != null && paraBreak.MyItemInfo.MyParent.MyPrevious != null && paraBreak.MyItemInfo.MyParent.IsStep && paraBreak.MyItemInfo.MyParent.MyPrevious.FormatStepData.Type == "TitleWithTextBelow")
				{
					if (lastBreak != null && lastBreak != paraBreak.MyParent) paraBreak = paraBreak.MyParent;
				}
				float yLoc = ySpaceOnCurPage - (paraBreak.YOffset - (YTopMost + yTop));
				if (yLoc <= 0) // Check where it would break if the space on the page was one line shorter
				{
					vlnParagraph paraBreak2 = FindPageBreak(yStart, ySpaceOnCurPage - (SixLinesPerInch + accountForCalvertAlarmConditionResponseFooter), yLowerLimit,
						myList, lastBreak, yPageSize - (myTopMsgSpace + SixLinesPerInch) - myBottomMsgSpace,
						myBottomMsgSpace, MyItemInfo.ActiveFormat.PlantFormat.FormatData.StepDataList[40].ContinueOnly);
					if (paraBreak2 != null && paraBreak != paraBreak2)
					{
						yLoc = ySpaceOnCurPage - (paraBreak2.YOffset - (YTopMost + yTop - paraBreak2.Height));
						if (paraBreak.YOffset == paraBreak2.YOffset + paraBreak2.Height)
						{
							//_MyLog.WarnFormat("Fix Break when no blank line {0},{1},{2}", paraBreak2.MyItemInfo.ShortPath, paraBreak2.MyItemInfo.ItemID,yLoc);
							paraBreak = paraBreak2;
						}
					}
				}
				// If the page break is close to the lower limit and the paraBreak is bigger than the upper limit
				// and increasing the lower limit by two lines
				// Causes a significant increase (at least 2 inches) in the amount of text placed on the page and 
				// the StepLevel only increases by 1 then use the paraBreak3
				else if (yLoc <= yLowerLimit + 24)
				{
					if (paraBreak.YSize > (yPageSize - (myTopMsgSpace + SixLinesPerInch) - myBottomMsgSpace))
					{
						vlnParagraph paraBreak3 = FindPageBreak(yStart, ySpaceOnCurPage - accountForCalvertAlarmConditionResponseFooter, yLowerLimit + 144,
							myList, lastBreak, yPageSize - (myTopMsgSpace + SixLinesPerInch) - myBottomMsgSpace,
							myBottomMsgSpace, MyItemInfo.ActiveFormat.PlantFormat.FormatData.StepDataList[40].ContinueOnly);
						if (paraBreak3 != null)
						{
							float yLoc3 = ySpaceOnCurPage - (paraBreak3.YOffset - (YTopMost + yTop));
							if (paraBreak.MyItemInfo.StepLevel + 1 >= paraBreak3.MyItemInfo.StepLevel && (yLoc - yLoc3) > 144)//144 is 2 inches
								paraBreak = paraBreak3;
						}
					}
				}
				if (MyItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.WolfcreekCKLFormat)
				{
					if (!paraBreak.MyItemInfo.IsHigh				// not a high level step
						&& paraBreak.MyParent.MyItemInfo.IsHigh		// my parent is a hls
						&& paraBreak.MyItemInfo.MyPrevious == null	// first substep
						&& paraBreak.MyParent.MyItemInfo.FormatStepData.UseSmartTemplate)   // my parent has the checklist header
					{
						if (DebugPagination.IsOpen) DebugPagination.WriteLine("Breaking at parent of {0}", paraBreak.MyItemInfo.DisplayText);
						paraBreak = paraBreak.MyParent;
					}
				}
				if (MyItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvertAlarm) // only do the following for Calvert Alarms
				{
					//if (lastBreak != null && lastBreak.MyItemInfo.InList(42656,42923)) Console.WriteLine("here");
					// Or Step whose parent fits on a page should break at the parent step
					//if (MyItemInfo.InList(119826)) Console.WriteLine("here");
					//if (paraBreak.MyItemInfo.InList(40339))
					float ySpaceOnNextPage = yPageSize - (myTopMsgSpace + SixLinesPerInch) - myBottomMsgSpace;
					if (paraBreak.MyItemInfo.IsOr && paraBreak.MyParent.YSize < ySpaceOnNextPage)
					{
						vlnParagraph paraBreakParent = paraBreak.MyParent;
						while (paraBreakParent.MyParent.YSize < ySpaceOnNextPage)
							paraBreakParent = paraBreakParent.MyParent;
						//_MyLog.WarnFormat("Or Step PageBreak '{0}','{1}','{2}'",paraBreak.MyItemInfo.ShortPath ,paraBreak.MyItemInfo.MyProcedure.DisplayNumber, paraBreak.MyItemInfo.MyHLS.DisplayText);
						paraBreak = paraBreakParent;
					}
					if (!paraBreak.ParentHasCalvertMacro)
					{
						foreach (int lev in myList.Keys)
						{
							foreach (float y in myList[lev].Keys)
							{
								vlnParagraph p = myList[lev][y];
								if (p.YOffset == paraBreak.YOffset && p.MyItemInfo.ItemID != paraBreak.MyItemInfo.ItemID)
									paraBreak.AddAlternateBreak(p);
							}
						}
					}
					// if first condition/response and the parent has caution, notes or warnings then move the break to the caution, note or warning
					if (!paraBreak.MyItemInfo.IsCautionPart && !paraBreak.MyItemInfo.IsNotePart && paraBreak.ParentHasCalvertMacro && paraBreak.MyParent.HasCalvertMacro && paraBreak.MyItemInfo.MyPrevious == null)
					{
						if (paraBreak.MyParent.ChildrenAbove.Count > 0)
							paraBreak = paraBreak.MyParent.ChildrenAbove[0];
						else
							paraBreak = paraBreak.MyParent;
					}
					// If the lastbreak was part of a condition response and the location is part of a condition response account for the size of the footer.
					else if (!paraBreak.MyItemInfo.IsCautionPart && !paraBreak.MyItemInfo.IsNotePart && paraBreak.ParentHasCalvertMacro && accountForCalvertAlarmConditionResponseFooter == 0)
					{
						paraBreak = FindPageBreak(yStart, ySpaceOnCurPage - vlnPrintObject.SixLinesPerInch * 4, yLowerLimit, myList, lastBreak, yPageSize - (myTopMsgSpace + SixLinesPerInch) - myBottomMsgSpace,
							myBottomMsgSpace, MyItemInfo.ActiveFormat.PlantFormat.FormatData.StepDataList[40].ContinueOnly);
						if (paraBreak.MyItemInfo.MyPrevious == null)
							if (paraBreak.MyParent.ChildrenAbove.Count > 0)
								paraBreak = paraBreak.MyParent.ChildrenAbove[0];
							else
								paraBreak = paraBreak.MyParent;
						//_MyLog.WarnFormat("Keep notes and cautions with CR text {0},'{1}','{2}','{3}'", paraBreak.MyItemInfo.ItemID, paraBreak.MyItemInfo.ShortPath, paraBreak.MyItemInfo.MyProcedure.DisplayNumber, paraBreak.MyParent.MyParent.MyItemInfo.DisplayText);
					}
					if (!paraBreak.MyItemInfo.IsCautionPart && !paraBreak.MyItemInfo.IsNotePart && paraBreak.ParentHasCalvertMacro)
					{
						vlnParagraph pTop = FirstCRParagraph(paraBreak);
						if (pTop != null && paraBreak.YOffset > pTop.YOffset && paraBreak.YOffset <= pTop.YOffset + 2 * SixLinesPerInch && pTop.MyParent != lastBreak)
						{
							if (pTop.MyItemInfo.MyPrevious == null && pTop.MyParent.ChildrenAbove.Count > 0)
							{
								paraBreak = pTop.MyParent.ChildrenAbove[0];
								//_MyLog.WarnFormat("Break at First CR Paragraph w/Notes {0},'{1}','{2}','{3}'", paraBreak.MyItemInfo.ItemID, paraBreak.MyItemInfo.ShortPath, paraBreak.MyItemInfo.MyProcedure.DisplayNumber, pTop.MyParent.MyParent.MyItemInfo.DisplayText);
							}
							else
							{
								paraBreak = pTop.MyParent;
								//_MyLog.WarnFormat("Break at First CR Paragraph {0},'{1}','{2}','{3}'", paraBreak.MyItemInfo.ItemID, paraBreak.MyItemInfo.ShortPath, paraBreak.MyItemInfo.MyProcedure.DisplayNumber, pTop.MyParent.MyParent.MyItemInfo.DisplayText);
							}
						}
					}
					if (!paraBreak.MyItemInfo.IsCautionPart && !paraBreak.MyItemInfo.IsNotePart && paraBreak.ParentHasCalvertMacro)
						accountForCalvertAlarmConditionResponseFooter = 5 * SixLinesPerInch;
					else
						accountForCalvertAlarmConditionResponseFooter = 0;
					//if (lastBreak != null && paraBreak.MyItemInfo.Ordinal == 1 && !paraBreak.MyItemInfo.IsCautionOrNotePart)
					//_MyLog.WarnFormat("'Strange Break',{0},'{1}','{2}','{3}',{4}", paraBreak.MyItemInfo.ItemID, paraBreak.MyItemInfo.ShortPath, paraBreak.MyItemInfo.MyProcedure.DisplayNumber, paraBreak.MyItemInfo.MyHLS.DisplayText,lastBreak.MyItemInfo.ItemID);
				}
				if (lastBreak == paraBreak)
				{
					throw (new Exception(string.Format("Pagination Infinite Loop {0}", lastBreak.MyItemInfo.ShortPath)));
				}
				// If the paraBreak is in an RNO and the location of the RNO is within the range of the AER parent, then break on the AER.
				if (paraBreak.MyItemInfo.IsInRNO)
				{
					vlnParagraph aerParent = paraBreak.MyParent;
					while (aerParent.MyItemInfo.IsInRNO) aerParent = aerParent.MyParent;
					if (aerParent.YOffset + aerParent.Height > paraBreak.YOffset)
					{
						if (aerParent.ChildrenAbove != null && aerParent.ChildrenAbove.Count > 0) // If the aerParent has caution or note
							aerParent = aerParent.ChildrenAbove[0];//, break on the caution or note.
						if (aerParent != lastBreak) paraBreak = aerParent;
					}
				}
				// MNS Pagination - Mike Weiner Case 1b to keep substeps together on one page
				if (MyItemInfo.ActiveFormat.MyStepSectionLayoutData.PutOnPageByItself && !paraBreak.MyParent.MyItemInfo.IsHigh && !paraBreak.MyItemInfo.IsHigh)
				{
					vlnParagraph firstLevel = paraBreak.MyParent;
					while (firstLevel.MyItemInfo.IsInRNO) firstLevel = firstLevel.MyParent;
					if (!firstLevel.MyItemInfo.IsHigh)
					{
						while (!firstLevel.MyParent.MyItemInfo.IsHigh) firstLevel = firstLevel.MyParent;
						if (firstLevel.MyParent.ChildrenBelow != null && firstLevel.MyParent.ChildrenBelow.Count > 0 && firstLevel.MyParent.ChildrenBelow[0] != firstLevel &&
							firstLevel.YSize < yPageSize - (myTopMsgSpace + SixLinesPerInch))
						{
							vlnParagraph firstLevel1 = firstLevel;
							if (firstLevel.ChildrenAbove != null && firstLevel.ChildrenAbove.Count > 0) // If the aerParent has caution or note
								firstLevel = firstLevel.ChildrenAbove[0];//, break on the caution or note.
							if (firstLevel != lastBreak && paraBreak != firstLevel)
							{
								//Console.WriteLine("'{0}','{1}','{2}'", firstLevel1.MyParent.MyItemInfo.ShortPath, firstLevel1.MyItemInfo.MyTab.Text, firstLevel1.MyItemInfo.ShortPath);
								paraBreak = firstLevel;
							}
						}
					}
				}
				// If the break is going to happen on a table, and the tables parent would fit on a page with the table 
				// and the text in the parent includes the word table, then break on the parent
				//if (lastBreak != paraBreak.MyParent && paraBreak.MyItemInfo.IsTable && paraBreak.YSize < ySpaceOnCurPage && paraBreak.MyParent.MyItemInfo.DisplayText.ToUpper().Contains("TABLE"))
				//	paraBreak = paraBreak.MyParent;
				//paraBreak.ShowPageBreak(999, paraBreak.MyItemInfo.ShortPath, "Yes",paraBreak.YTop, paraBreak.YSize, paraBreak.Height, false);
				//_MyLog.InfoFormat("Place to break\r\n==>'Place to Break',{0},'{1}','{2}'"
				//, paraBreak.MyItemInfo.ItemID, paraBreak.MyItemInfo.MyDocVersion.MyFolder.Name, paraBreak.MyItemInfo.ShortPath);
				// yTopNew is y Location of this page break.  YTopMost is top of HLS, including any Cautions/Notes/Boxes/etc
				//float yTopNew = paraBreak.YVeryTop - YTopMost;
				//float yTopNew = paraBreak.YTopMost - YTopMost;
				if (JustATableThatWillFit(paraBreak, yPageSize - (myTopMsgSpace + yEndMsg)))
					paraBreak = paraBreak.ChildrenBelow[0];
				float ySpaceOnNextPage1 = yPageSize - (myTopMsgSpace + (yEndMsg == 0 ? SixLinesPerInch : 0));  // Allow for continue message and blank line.
				ySpaceOnNextPage1 -= accountForSmartTemplateHeader;
				// This fixes B2016-174:
				// Added the check to not go into this code if on a step that needs to break.  If the conditions were met, this
				// code was not putting a page break on a step that needed to break, i.e. PageBreakOnStep = true. 
				if ((MyItemInfo.IsStep && !MyItemInfo.FormatStepData.PageBreakOnStep) && MyItemInfo.ActiveFormat.MyStepSectionLayoutData.PartialStepCompression && onNewPage) // ySpaceOnNextPage1 == ySpaceOnCurPage+myBottomMsgSpace)
				{
					float ySpaceAt7LPI = ((ySpaceOnCurPage - accountForCalvertAlarmConditionResponseFooter) * SixLinesPerInch / _SevenLinesPerInch) -  _SevenLinesPerInch;
					vlnParagraph paraBreak7 = FindPageBreak(yStart, ySpaceAt7LPI, yLowerLimit,
						myList, lastBreak, yPageSize - (myTopMsgSpace + SixLinesPerInch) - myBottomMsgSpace,
						myBottomMsgSpace, MyItemInfo.ActiveFormat.PlantFormat.FormatData.StepDataList[40].ContinueOnly);
					if (paraBreak7 != null && paraBreak7.YOffset > paraBreak.YOffset && paraBreak.MyItemInfo.StepLevel >= paraBreak7.MyItemInfo.StepLevel)
					{
						paraBreak = paraBreak7;
						// Compress Part of Step
						//    .oooooo.                                                                                  ooooooooo.                          .   
						//   d8P'  `Y8b                                                                                 `888   `Y88.                      .o8   
						//  888           .ooooo.  ooo. .oo.  .oo.   oo.ooooo.  oooo d8b  .ooooo.   .oooo.o  .oooo.o     888   .d88'  .oooo.   oooo d8b .o888oo 
						//  888          d88' `88b `888P"Y88bP"Y88b   888' `88b `888""8P d88' `88b d88(  "8 d88(  "8     888ooo88P'  `P  )88b  `888""8P   888   
						//  888          888   888  888   888   888   888   888  888     888ooo888 `"Y88b.  `"Y88b.      888          .oP"888   888       888   
						//  `88b    ooo  888   888  888   888   888   888   888  888     888    .o o.  )88b o.  )88b     888         d8(  888   888       888 . 
						//   `Y8bood8P'  `Y8bod8P' o888o o888o o888o  888bod8P' d888b    `Y8bod8P' 8""888P' 8""888P'    o888o        `Y888""8o d888b      "888" 
						//                                            888                                                                                       
						//                                           o888o                                                                                      
						//
						// |                          Step over a Number of Pages                             |
						// |     First Page        |             Second Page            |      Third Page     |
						//--------------------------------------------------------------------------------------
						//                         |paraBreak[0]                        |paraBreak[1]
						//                         |                                    |
						//                         |CompressPartOfStep                  |CompressPartOfStep
						//                         |   Flags compression for 2nd page   |   Flags compression for 2nd page
						//                         |   of step starting at paraBreak[0] |   of step starting at paraBreak[1]
						//                         |                                    |   See code below for 'Compress Rest of Step'
						//                      <==|CompressFirstPartOfStep             |                                                    
						//                         |   Flags compression for 1st page   |
						//                         |   (1st page doesn't use paraBreak) |
						//
						if (lastBreak != null)		// not on first page of step
						{
							lastBreak.PageBreakReason = "More of Step at 7 LPI";
							lastBreak.CompressPartOfStep = true;
						}
						else
						{
							paraBreak.CompressFirstPartOfStep = true;
						}
					}
				}
				onNewPage = true;
				float yTopNew = Math.Min(paraBreak.YTopMost, paraBreak.YVeryTop) - YTopMost;
				// B2017-161: unnecessary PageBreak for background documents: use the 'usedPageBreakOnStepList' flag when using the PageBreakOnStepList, don't adjust space on page to account
				//  for continue message, if there is not one.
				bool usedPageBreakOnStepList = false;
				// This is for formats that break on all HLS, Cautions & Notes (often backgrounds):
				if (PageBreakOnStepList.Count > 0)
				{
					// If the next page break is beyond the next hls/caution/note, use the next
					// hls/caution/note.
					if (PageBreakOnStepList[0].YTop <= paraBreak.YTop)
					{
						PageBreakOnStepList[0].CompressFirstPartOfStep = paraBreak.CompressFirstPartOfStep;
						paraBreak = PageBreakOnStepList[0];
						PageBreakOnStepList.RemoveAt(0);
						yTopNew = paraBreak.YTop - YTopMost;
						usedPageBreakOnStepList = true;
					}
					// The following code caused forced pagination for Catawba EOP BG - EP/1/A/5000/FR-C.1.SC..S16..N2..S4..S1.
					//else if(PageBreakOnStepList[0].YSize - yTop <= ySpaceOnCurPage)
					//{
					//	DebugPagination.WriteLine("======>>>>> Other Condition");
					//	paraBreak = PageBreakOnStepList[0];
					//	PageBreakOnStepList.RemoveAt(0);
					//	yTopNew = paraBreak.YTop - YTopMost;
					//}
				}
				RemoveProcessedParagraphs(myList, yTopNew - yTop);
				yTop = yTopNew;
				MyPageHelper.ParaBreaks.Add(paraBreak);
				ySpaceOnNextPage1 -= paraBreak.GetSectionTopMessageSize();	// B2016-134: Account for wcntraining section top continue on substep containers (notes/cautions)
				SectionConfig sch = MyItemInfo.ActiveSection.MyConfig as SectionConfig;
				// B2016-266 Only set SectionTitleContinued1 if the format supports section continue messages 
				bool doSectionTitleContinued1 = (sch == null || sch.Section_PrintHdr == "Y") && !MyItemInfo.MyDocStyle.CancelSectTitle && MyItemInfo.ActiveFormat.PlantFormat.FormatData.SectData.StepSectionData.ContinueSectionHeader;
				if (doSectionTitleContinued1 && MyItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvert)
				{ // B2017-036 BGE Unit 1 STP-073A-1 6.5.B.5 in the Approved Procedures did not print properly
					string myMsg = MyItemInfo.MyDocStyle.Continue.Top.Message;
					if (myMsg != null && myMsg != "")
						doSectionTitleContinued1 = false;
				}
				if (doSectionTitleContinued1) ySpaceOnNextPage1 -= 2 * SixLinesPerInch; // B2016-195: Account for Section Continue Message
				if (!usedPageBreakOnStepList) ySpaceOnCurPage = ySpaceOnNextPage1;
				//ySpaceOnCurPage = yPageSize - (myTopMsgSpace + SixLinesPerInch);  // Allow for continue message and blank line.
				//if (paraBreak.YTopMost != paraBreak.YVeryTop && MyPageHelper.TopMessage == null && MyPageHelper.BottomMessage == null)
				//	ySpaceOnCurPage = yPageSize;
				//ySpaceOnCurPage = yPageSize;  // Allow for continue message and blank line.
				//DocStyle docstyle = MyItemInfo.MyDocStyle;
				//string myMsg = docstyle.Continue.Bottom.Message;
				//if ((myMsg ?? "") != "") ySpaceOnCurPage -= 2 * SixLinesPerInch;  // Allow for continue message and blank line.
				yLowerLimit = ySpaceOnCurPage / 2;
				if (_Match16BitPagination) yLowerLimit -= 1.5F * SixLinesPerInch; // 276 for HLP
				yStart = 0;
				// This fixes B2016-174:
				// Added the check to not go into this code if on a step that needs to break.  If the conditions were met, this
				// code was not putting a page break on a step that needed to break, i.e. PageBreakOnStep = true. 
				if ((MyItemInfo.IsStep && !MyItemInfo.FormatStepData.PageBreakOnStep) && MyItemInfo.ActiveFormat.MyStepSectionLayoutData.PartialStepCompression)
				{
					float ySpaceAt7LPI = (ySpaceOnCurPage - (accountForCalvertAlarmConditionResponseFooter + yEndMsg)) * SixLinesPerInch / _SevenLinesPerInch;
					if ((YSize - yTop) > (ySpaceOnCurPage - (accountForCalvertAlarmConditionResponseFooter + yEndMsg))
						&& (YSize - yTop) < ySpaceAt7LPI )
					{
						// Compress Rest of Step
						//    .oooooo.                                                                                  ooooooooo.                          .   
						//   d8P'  `Y8b                                                                                 `888   `Y88.                      .o8   
						//  888           .ooooo.  ooo. .oo.  .oo.   oo.ooooo.  oooo d8b  .ooooo.   .oooo.o  .oooo.o     888   .d88'  .ooooo.   .oooo.o .o888oo 
						//  888          d88' `88b `888P"Y88bP"Y88b   888' `88b `888""8P d88' `88b d88(  "8 d88(  "8     888ooo88P'  d88' `88b d88(  "8   888   
						//  888          888   888  888   888   888   888   888  888     888ooo888 `"Y88b.  `"Y88b.      888`88b.    888ooo888 `"Y88b.    888   
						//  `88b    ooo  888   888  888   888   888   888   888  888     888    .o o.  )88b o.  )88b     888  `88b.  888    .o o.  )88b   888 . 
						//   `Y8bood8P'  `Y8bod8P' o888o o888o o888o  888bod8P' d888b    `Y8bod8P' 8""888P' 8""888P'    o888o  o888o `Y8bod8P' 8""888P'   "888" 
						//                                            888                                                                                       
						//                                           o888o                                                                                      
						paraBreak.PageBreakReason = "Rest of Step fits at 7 LPI";
						paraBreak.CompressPartOfStep = true;
						break;
					}
				}
			}
			if (paraBreak != null && paraBreak.PageBreakReason == null)
				paraBreak.PageBreakReason = "Rest of Step fits at 6 LPI";
			ProfileTimer.Pop(profileDepth);
		}
		// The following finds all of the preferred page breaks for this step & if found adds them to a
		// list of the location & the paragraph it is on.  This is used so that pagination calculations
		// occur for steps following the preferred page break rather than starting on the page after
		// substep with preferred page break (B2017-109)
		private SortedList GetMyPreferredBreaks(StepLevelList myList)
		{
			if (!MyItemInfo.MyDocStyle.SupplementalInformation) return null;
			SortedList sdpara = null;
			foreach (int stepLevel in myList.Keys)				// loop thru StepLevels, starting with lowest.
			{
				foreach (float yLocation in myList[stepLevel].Keys)		// loop thru yLocation
				{
					vlnParagraph myPara = myList[stepLevel][yLocation];
					StepConfig sci = myPara.MyItemInfo.MyConfig as StepConfig;
					if (sci != null && sci.Step_PreferredPagebreak)
					{
						if (sdpara == null) sdpara = new SortedList();
						if (myPara.ChildrenAbove != null && myPara.ChildrenAbove.Count > 0) sdpara.Add(-yLocation, myPara.ChildrenAbove[0]);
						else sdpara.Add(-yLocation, myPara);
					}
				}
			}
			return sdpara;
		}
		private float GetBottomContinueMessageSize(DocStyle docstyle)
		{
			float myBottomMsgSpace = 0;
			docstyle = MyItemInfo.MyDocStyle;
			string myBottomMsg = docstyle.Continue.Bottom.Message;
			myBottomMsgSpace = ((myBottomMsg ?? "") != "") ? 2 * SixLinesPerInch : 0;
			if (myBottomMsg != null && myBottomMsg.Contains("par")) myBottomMsgSpace += SixLinesPerInch;
			return myBottomMsgSpace;
		}
		private bool JustATableThatWillFit(vlnParagraph paraBreak, float ypagesize)
		{
			if (paraBreak.MyItemInfo.MyContent.Text.Replace(" ", "").Replace(@"\u160?", "").Replace(@"\'A0", "") != "") return false;
			if (paraBreak.YSize < ypagesize) return false;
			if (paraBreak.ChildrenAbove.Count > 0) return false;
			if (paraBreak.ChildrenLeft.Count > 0) return false;
			if (paraBreak.ChildrenRight.Count > 0) return false;
			if (paraBreak.ChildrenBelow.Count != 1) return false;
			if (!paraBreak.ChildrenBelow[0].MyItemInfo.IsTable) return false;
			vlnParagraph paraTable = paraBreak.ChildrenBelow[0];
			if (paraTable.YSize < ypagesize)
				return true;
			return false;
		}
		/// 
		/// Finds the highest StepLevel (lowest StepLevel number, 0 = HLS, 1 = first substep) that
		/// fills the page sufficiently (more than half-full)
		/// 
		/// 
		/// 
		/// 
		/// 
		private static vlnParagraph FindPageBreak(float yStart, float yUpperLimit, float yLowerLimit, StepLevelList myList, vlnParagraph lastBreak, float fullPage,
			float myBottomMsgSpace,bool RNOContinueOnly)
		{
			vlnParagraph minPara = null;
			//StringBuilder minBuff = new StringBuilder();
			float? yLocationMin=null;
			vlnParagraph minPara2 = null;
			float? yLocationMin2=null;
			float yAddForBtmMsg = 0;
			foreach (int stepLevel in myList.Keys)				// loop thru StepLevels, starting with lowest.
			{
				foreach (float yLocation in myList[stepLevel].Keys)		// loop thru yLocation
				{
					float spaceOnPage = yUpperLimit + yLocation;
					vlnParagraph myPara = myList[stepLevel][yLocation];
					bool IsIP3Format = myPara.MyItemInfo.ActiveFormat.Name.StartsWith("IP3");
					int maxLev = stepLevel;
					if (spaceOnPage > 0 && (maxLev = MaxBreakLevel(yLocation, myList, stepLevel, myPara)) > stepLevel)
					{
						//DebugPagination.WriteLine("'Adjust for Max StepLevel',{0},{1},{2},'{3}'",myPara.MyItemInfo.ItemID,stepLevel,maxLev, myPara.MyItemInfo.ShortPath);
						//break;
					}
					else
					{
						if (RNOContinueOnly && !myPara.MyItemInfo.IsInRNO)
							yAddForBtmMsg = myBottomMsgSpace;
						else
							yAddForBtmMsg = 0;
						spaceOnPage += yAddForBtmMsg;
						if (!IsIP3Format)
						{
							// The following lines were added for Comanche Peak ECA-TP-11-001A.SProcedure Steps.S17 (Printed as Step 12)
							if (spaceOnPage > 0 && myPara.YSize > fullPage && myPara.ChildrenRight != null && myPara.ChildrenRight.Count > 0
								&& myPara.ChildrenRight[0].YSize <= fullPage && myPara.ChildrenRight[0].YSize > spaceOnPage)
							{
								//_MyLog.WarnFormat("\r\nMyParaBreak {0},{1},{2},{3},{4}", myPara, myPara.YSize, yUpperLimit, myPara.ChildrenRight[0].YSize, spaceOnPage);
								if (myPara != lastBreak)
									return myPara;
							}
							// The following lines were added for Comanche Peak ECA-0.1A.SProcedure Steps.S17 (Printed as Step 12)
							vlnParagraph myParent = myPara.MyParent;
							spaceOnPage = yAddForBtmMsg + yUpperLimit + myPara.YTop + yLocation - myParent.YTop;
							if (spaceOnPage > 0 && myParent != lastBreak && myParent.YSize > fullPage && myParent.ChildrenRight != null && myParent.ChildrenRight.Count > 0
								&& myParent.ChildrenRight[0].YSize <= fullPage && myParent.ChildrenRight[0].YSize > spaceOnPage)
							{
								//_MyLog.WarnFormat("\r\nMyParentBreak {0},{1},{2},{3},{4}", myParent, myParent.YSize, yUpperLimit, myParent.ChildrenRight[0].YSize, spaceOnPage);
								if (myParent != lastBreak)
									return myParent;
							}
						}
						// The top of this step will fit onto page (-yLocation < yWithinMargins)
						float wcnChkLstBorder = myPara.MyItemInfo.MyHLS != null && myPara.MyItemInfo.MyHLS.FormatStepData.UseSmartTemplate &&
								(myPara.MyItemInfo.MyHLS.FormatStepData.Suffix ?? "") != "" ? 2 * SixLinesPerInch : 0;
						if (myPara != lastBreak)
						{
							if ((-yLocation + yStart) >= yLowerLimit) // More than the lower limit
							{
								if (yLocationMin == null) // No old location
								{
									//minBuff.AppendLine(string.Format("OLD1  >>>>> '{0}',{1},{2}", myPara.MyItemInfo.ShortPath, -yLocation, yUpperLimit));
									yLocationMin = yLocation;
									minPara = myPara;
								}
								else if (-yLocation < -yLocationMin && -yLocationMin >= yUpperLimit) // New location is smaller and old location excedes limit
								{
									//minBuff.AppendLine(string.Format("NEW1A >>>>> '{0}',{1},{2}", myPara.MyItemInfo.ShortPath, -yLocation, yUpperLimit));
									yLocationMin = yLocation;
									minPara = myPara;
								}
								else if (-yLocation > -yLocationMin && -yLocation <= yUpperLimit) // New location is larger and new location is less than limit
								{
									//minBuff.AppendLine(string.Format("NEWB1 >>>>> '{0}',{1},{2}", myPara.MyItemInfo.ShortPath, -yLocation, yUpperLimit));
									yLocationMin = yLocation;
									minPara = myPara;
								}
							}
							else // Less than the lower limit
							{
								if (yLocationMin2 == null)
								{
									//minBuff.AppendLine(string.Format("OLD2  >>>>> '{0}',{1},{2}", myPara.MyItemInfo.ShortPath, -yLocation, yUpperLimit));
									yLocationMin2 = yLocation;
									minPara2 = myPara;
								}
								else if (-yLocation < -yLocationMin2 && -yLocationMin2 >= yUpperLimit) // New location is smaller and old location excedes limit
								{
									//minBuff.AppendLine(string.Format("NEW2A >>>>> '{0}',{1},{2}", myPara.MyItemInfo.ShortPath, -yLocation, yUpperLimit));
									yLocationMin2 = yLocation;
									minPara2 = myPara;
								}
								else if (-yLocation > -yLocationMin2 && -yLocation <= yUpperLimit) // New location is larger and new location is less than limit
								{
									//minBuff.AppendLine(string.Format("NEW2B >>>>> '{0}',{1},{2}", myPara.MyItemInfo.ShortPath, -yLocation, yUpperLimit));
									yLocationMin2 = yLocation;
									minPara2 = myPara;
								}
							}
						}
						//while (myPara.MyParent.YTop == myPara.YTop) myPara = myPara.MyParent;
						while (myPara.MyParent != null && myPara.MyParent.YTop == myPara.YTop) myPara = myPara.MyParent;
						int everyNLines = myPara.MyItemInfo.MyPrevious != null && myPara.MyItemInfo.FormatStepData == null ? 1 : myPara.MyItemInfo.FormatStepData.StepLayoutData.EveryNLines ?? 1;
						bool inSameBox = InSameBox(myPara, minPara2);		// if this note/caution is in same box as the break, don't break within the notes/cautions in the same box
						if (!inSameBox && myPara.ChildrenAbove.Count == 0 && wcnChkLstBorder - yLocation < yUpperLimit + yAddForBtmMsg || (everyNLines != 99 && (wcnChkLstBorder - yLocation == yUpperLimit + yAddForBtmMsg))) // Fix for OFN-RJ-23
						//if (-yLocation < yUpperLimit) // Before
						//if (-yLocation < yWithinMargins && myList[stepLevel][yLocation].MyItemInfo.MyPrevious != null)
						{
							//ItemInfo prev = myList[stepLevel][yLocation].MyItemInfo.MyPrevious;
							//if (myList[stepLevel][yLocation].MyItemInfo.ItemID == 5609) Console.WriteLine("aer");
							//if (myList[stepLevel][yLocation].MyItemInfo.ItemID == 4312) Console.WriteLine("rno");
							// The top of this step is more than 1/2 way down the page
							if ((-yLocation + yStart) >= yLowerLimit)
								if (myPara != lastBreak)
									if ((-yLocation + yStart) >= yLowerLimit) // Only if it is more than the lower limit
										return myPara;
							// If this item will not fit on the current page, put a page break
							if (myPara.YBottom - myPara.YTop > (yUpperLimit + yLocation))
								if (myPara != lastBreak)
									if ((-yLocation + yStart) >= yLowerLimit) // Only if it is more than the lower limit	
										return myPara;
							// if is a caution or note & parent is a substep and entire substep doesn't fit, break.
							if ((myPara.MyItemInfo.IsNote || myPara.MyItemInfo.IsCaution) &&
								!myPara.MyParent.MyItemInfo.IsHigh &&
								myPara.MyParent.YSize > (yUpperLimit + yLocation))
							{
								//McGuire Unit 1 AOPs - AP/1/A/5500/07.SEnclosure 7.S31..S1..C1
								if ((-yLocation + yStart) >= yLowerLimit) // Only if it is more than the lower limit
									return myPara;
							}
						}
					}
				}
			}
			//DebugPagination.Write(minBuff.ToString());
			if (-yLocationMin  > yUpperLimit && minPara2 != null) minPara = null;
			// if breaking at a note/caution - don't break within the same box. Clear minPara (like code above)
			// so that minPara2 is used.
			if (minPara != null && minPara2 != null && ((minPara2.MyItemInfo.IsCautionPart && minPara.MyItemInfo.IsCaution) || (minPara2.MyItemInfo.IsNotePart && minPara.MyItemInfo.IsNote))
				&& minPara.MyItemInfo.FirstSibling.ItemID == minPara2.MyItemInfo.ItemID) minPara = null;
			//if (minPara != null) DebugPagination.WriteLine("### 111111 {0}", minPara);
			//if(minPara2 != null) DebugPagination.WriteLine("### n222222 {0}", minPara2);
			return minPara ?? minPara2;
		}
		private static bool InSameBox(vlnParagraph myPara, vlnParagraph minPara2)
		{
			// see if this paragraph is a note/caution or in a note/caution where its 1st sibling is the input minPara2 (this
			// is the next best-case page break location.  This was added for Calvert's OI3/OI-1A/Section 5/Step H.3.  Without it
			// the page break occurred in the middle of the list of notes.
			if (minPara2 == null) return false;
			if ((myPara.MyItemInfo.IsCaution || myPara.MyItemInfo.IsNote || myPara.MyItemInfo.MyParent.IsCaution || myPara.MyItemInfo.MyParent.IsNote) && minPara2 != null)
			{
				ItemInfo mync = (myPara.MyItemInfo.IsNote || myPara.MyItemInfo.IsCaution) ? myPara.MyItemInfo : myPara.MyItemInfo.MyParent;
				if (mync == null) return false;
				if (mync.FirstSibling.ItemID == minPara2.MyItemInfo.ItemID) return true;
			}
			return false;
		}
		private static int MaxBreakLevel(float yLocation, StepLevelList myList, int maxLevel, vlnParagraph myParaBreak)
		{
			foreach (int stepLevel in myList.Keys)
				foreach (float yLoc in myList[stepLevel].Keys)
				{
					vlnParagraph myPara = myList[stepLevel][yLoc];
					if (Overlap(myPara, myParaBreak))
						if (stepLevel > maxLevel)
						{
							//DebugPagination.WriteLine("'MaxBreakLevel',{0},{1},'{2}'", myPara.MyItemInfo.ItemID, stepLevel, myPara.MyItemInfo.ShortPath);
							//Console.WriteLine("'MaxBreakLevel',{0},{1},'{2}'", myPara.MyItemInfo.ItemID, stepLevel, myPara.MyItemInfo.ShortPath);
							if (!myPara.HasAncestor(myParaBreak))
								maxLevel = stepLevel;
						}
				}
			return maxLevel;
		}
		private static bool Overlap(vlnParagraph myPara, vlnParagraph myParaBreak)
		{
			// Fix for B2016-166: Calvert pagination-splitting a Note in AER from its associated step
			if (myPara.MyItemInfo.ActiveFormat.PlantFormat.FormatData.PrintData.SpecialCaseCalvertPagination)
				return (myPara.YOffset <= myParaBreak.YOffset &&
					(myPara.YOffset + myPara.Height) >= myParaBreak.YOffset);
			return(myPara.YOffset == myParaBreak.YOffset);
		}
		private bool HasAncestor(vlnParagraph myParaBreak)
		{
			if (myParaBreak == MyParent) return true;
			if (MyParent == null || MyParent.MyItemInfo.IsHigh) return false;
			return MyParent.HasAncestor(myParaBreak);
		}
		//private void WalkStepLevel(float yTopMost)
		//{
		//  foreach (vlnParagraph child in ChildrenAbove)
		//    child.WalkStepLevel(yTopMost);
		//  foreach (vlnParagraph child in ChildrenLeft)
		//    child.WalkStepLevel(yTopMost);
		//  ShowStepLevel(yTopMost);
		//  foreach (vlnParagraph child in ChildrenRight)
		//    child.WalkStepLevel(yTopMost);
		//  foreach (vlnParagraph child in ChildrenBelow)
		//    child.WalkStepLevel(yTopMost);
		//}
		//private void ShowStepLevel(float yTopMost)
		//{
		//  ItemInfo item = MyItemInfo;
		//  ItemInfo parent = item.ActiveParent as ItemInfo;
		//  //if (para.MyItemInfo.ItemID == 205)
		//  //  Console.Write("");
		//  DebugPagination.WriteLine("'StepLevel',{0},{1},{2},{3},{4},{5},{6},{7},{8},{9}", YVeryTop - yTopMost, YSize, YBottomMost - yTopMost, item.ItemID, item.DBSequence, item.StepLevel, item.MyContent.Type % 10000,
		//    parent.MyContent.Type % 10000, item.HasCautionOrNote ? 1 : 0, parent.Cautions == null ? 0 : 1);
		//}
		public float TableSpaceAvailable// RHM20150525 - Table Scrunch
		{
			get
			{
				float retval = 0;
				if(_ChildrenBelow!= null)
					foreach (vlnParagraph pgh in _ChildrenBelow)
						retval = pgh.TableSpaceAvailable;
				if (MyGrid != null)
					retval = MyGrid.SpaceAvailable;
				return retval;
			}
		}
	}
	public partial class VlnSvgPageHelper : SvgPageHelper
	{
		private bool _OriginalPageBreak;		// use 16bit page breaks.
		public bool OriginalPageBreak
		{
			get { return _OriginalPageBreak; }
			set { _OriginalPageBreak = value; }
		}
		// This handles Page Breaks within a Step
		private List _ParaBreaks = new List();
		public List ParaBreaks
		{
			get { return _ParaBreaks; }
			set { _ParaBreaks = value; }
		}
	}
}