Index: test/java/org/apache/fop/fotreetest/FOTreeTestSuite.java
===================================================================
--- test/java/org/apache/fop/fotreetest/FOTreeTestSuite.java	(revision 1040929)
+++ test/java/org/apache/fop/fotreetest/FOTreeTestSuite.java	(working copy)
@@ -37,11 +37,6 @@
 import org.apache.commons.io.filefilter.TrueFileFilter;
 
 import org.apache.fop.DebugHelper;
-import org.apache.fop.fo.flow.table.CollapsedConditionalBorderTestCase;
-import org.apache.fop.fo.flow.table.IllegalRowSpanTestCase;
-import org.apache.fop.fo.flow.table.RowGroupBuilderTestCase;
-import org.apache.fop.fo.flow.table.TableColumnColumnNumberTestCase;
-import org.apache.fop.fo.flow.table.TooManyColumnsTestCase;
 import org.apache.fop.layoutengine.LayoutEngineTestSuite;
 
 /**
@@ -118,11 +113,8 @@
     }
 
     private static void addUnitTestCases(TestSuite suite) {
-        suite.addTestSuite(TooManyColumnsTestCase.class);
-        suite.addTestSuite(IllegalRowSpanTestCase.class);
-        suite.addTestSuite(RowGroupBuilderTestCase.class);
-        suite.addTestSuite(TableColumnColumnNumberTestCase.class);
-        suite.addTestSuite(CollapsedConditionalBorderTestCase.class);
+        suite.addTest(org.apache.fop.fo.flow.table.AllTests.suite());
+        suite.addTest(org.apache.fop.fo.pagination.AllTests.suite());
     }
 
     private static class FOTreeTestCase extends TestCase {
Index: test/java/org/apache/fop/fo/flow/table/AllTests.java
===================================================================
--- test/java/org/apache/fop/fo/flow/table/AllTests.java	(revision 0)
+++ test/java/org/apache/fop/fo/flow/table/AllTests.java	(revision 0)
@@ -0,0 +1,46 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/* $Id$ */
+
+package org.apache.fop.fo.flow.table;
+
+import junit.framework.Test;
+import junit.framework.TestSuite;
+
+/**
+ * All test to be added in FOTreeTestSuite
+ *
+ */
+public final class AllTests {
+
+    private AllTests() { }
+
+    /**
+     *
+     * @return All test to be added in FOTreeTestSuite
+     */
+    public static Test suite() {
+        TestSuite suite = new TestSuite();
+        suite.addTestSuite(CollapsedConditionalBorderTestCase.class);
+        suite.addTestSuite(IllegalRowSpanTestCase.class);
+        suite.addTestSuite(RowGroupBuilderTestCase.class);
+        suite.addTestSuite(TableColumnColumnNumberTestCase.class);
+        suite.addTestSuite(TooManyColumnsTestCase.class);
+        return suite;
+    }
+}

Property changes on: test/java/org/apache/fop/fo/flow/table/AllTests.java
___________________________________________________________________
Added: svn:keywords
   + Revision Id
Added: svn:eol-style
   + native

Index: test/java/org/apache/fop/fo/pagination/AllTests.java
===================================================================
--- test/java/org/apache/fop/fo/pagination/AllTests.java	(revision 0)
+++ test/java/org/apache/fop/fo/pagination/AllTests.java	(revision 0)
@@ -0,0 +1,42 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/* $Id$ */
+
+package org.apache.fop.fo.pagination;
+
+import junit.framework.Test;
+import junit.framework.TestSuite;
+
+/**
+ * All test to be added in FOTreeTestSuite
+ *
+ */
+public final class AllTests {
+
+    private AllTests() { }
+
+    /**
+     *
+     * @return All test to be added in FOTreeTestSuite
+     */
+    public static Test suite() {
+        TestSuite suite = new TestSuite();
+        suite.addTestSuite(PageSequenceMasterTestCase.class);
+        return suite;
+    }
+}

Property changes on: test/java/org/apache/fop/fo/pagination/AllTests.java
___________________________________________________________________
Added: svn:keywords
   + Revision Id
Added: svn:eol-style
   + native

Index: test/java/org/apache/fop/fo/pagination/RepeatablePageMasterAlternativesTestCase.java
===================================================================
--- test/java/org/apache/fop/fo/pagination/RepeatablePageMasterAlternativesTestCase.java	(revision 0)
+++ test/java/org/apache/fop/fo/pagination/RepeatablePageMasterAlternativesTestCase.java	(revision 0)
@@ -0,0 +1,163 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/* $Id$ */
+
+package org.apache.fop.fo.pagination;
+
+import static org.mockito.Matchers.anyBoolean;
+import static org.mockito.Matchers.anyInt;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+import junit.framework.TestCase;
+
+import org.apache.fop.fo.Constants;
+import org.apache.fop.fo.PropertyList;
+import org.apache.fop.fo.expr.NumericProperty;
+import org.apache.fop.fo.properties.Property;
+
+/**
+ * Unit Test for RepeatablePageMasterAlternatives
+ *
+ */
+public class RepeatablePageMasterAlternativesTestCase extends TestCase
+implements Constants {
+
+    /**
+     *
+     * @throws Exception exception
+     */
+    public void testIsInfinite1() throws Exception {
+        //  Create fixture
+        Property maximumRepeats = mock(Property.class);
+        ConditionalPageMasterReference cpmr = createCPMR("empty");
+
+        when(maximumRepeats.getEnum()).thenReturn(EN_NO_LIMIT);
+
+        RepeatablePageMasterAlternatives objectUnderTest
+        = createRepeatablePageMasterAlternatives(cpmr, maximumRepeats);
+
+        assertTrue("is infinite", objectUnderTest.isInfinite());
+    }
+
+    /**
+     *
+     * @throws Exception exception
+     */
+    public void testIsInfinite2() throws Exception {
+        //  Create fixture
+        Property maximumRepeats = mock(Property.class);
+        ConditionalPageMasterReference cpmr = createCPMR("empty");
+
+        NumericProperty numericProperty = mock(NumericProperty.class);
+
+        final int maxRepeatNum = 0;
+        assertTrue(maxRepeatNum != EN_NO_LIMIT);
+
+        when(maximumRepeats.getEnum()).thenReturn(maxRepeatNum);
+        when(maximumRepeats.getNumeric()).thenReturn(numericProperty);
+
+        RepeatablePageMasterAlternatives objectUnderTest
+        = createRepeatablePageMasterAlternatives(createCPMR("empty"),
+                maximumRepeats);
+
+        assertTrue("is infinite", !objectUnderTest.isInfinite());
+    }
+
+    /**
+     * Test that an infinite sequence of empty page masters has
+     * willTerminiate() returning false
+     * @throws Exception exception
+     */
+    public void testCanProcess1() throws Exception {
+        //  Create fixture
+        Property maximumRepeats = mock(Property.class);
+        ConditionalPageMasterReference cpmr = createCPMR("empty");
+
+        when(maximumRepeats.getEnum()).thenReturn(EN_NO_LIMIT);
+        when(cpmr.isValid(anyBoolean(), anyBoolean(), anyBoolean(), anyBoolean()))
+        .thenReturn(true);
+
+        RepeatablePageMasterAlternatives objectUnderTest
+        = createRepeatablePageMasterAlternatives(cpmr, maximumRepeats);
+
+        //Fixture assertion
+        assertTrue("Should be infinite", objectUnderTest.isInfinite());
+
+        //Test assertion
+        assertTrue("Infinite sequences that do not process the main flow will "
+                + " not terminate",
+                !objectUnderTest.canProcess("main-flow"));
+    }
+    /**
+     * Test that a finite sequence of simple page masters has
+     * willTerminate() returning true
+     *
+     * @throws Exception exception
+     */
+    public void testCanProcess2() throws Exception {
+        //  Create fixture
+        Property maximumRepeats = mock(Property.class);
+        NumericProperty numericProperty = mock(NumericProperty.class);
+
+        final int maxRepeatNum = 0;
+
+        when(maximumRepeats.getEnum()).thenReturn(maxRepeatNum);
+        when(maximumRepeats.getNumeric()).thenReturn(numericProperty);
+
+        RepeatablePageMasterAlternatives objectUnderTest
+        = createRepeatablePageMasterAlternatives(createCPMR("empty"),
+                maximumRepeats);
+
+        //Fixture assertion
+        assertTrue("Should be finite sequence", !objectUnderTest.isInfinite());
+
+        //Test assertion
+        assertTrue("Finite sequences will terminate",
+                objectUnderTest.canProcess("main-flow"));
+    }
+
+    private ConditionalPageMasterReference createCPMR(String regionName) {
+        ConditionalPageMasterReference cpmr = mock(ConditionalPageMasterReference.class);
+        SimplePageMaster master = mock(SimplePageMaster.class);
+        Region region = mock(Region.class);
+        when(master.getRegion(anyInt())).thenReturn(region);
+        when(region.getRegionName()).thenReturn(regionName);
+        when(cpmr.getMaster()).thenReturn(master);
+
+        return cpmr;
+    }
+
+    private RepeatablePageMasterAlternatives createRepeatablePageMasterAlternatives(
+            ConditionalPageMasterReference cpmr, Property maximumRepeats) throws Exception {
+
+        PropertyList pList = mock(PropertyList.class);
+
+        when(pList.get(anyInt())).thenReturn(maximumRepeats);
+
+        PageSequenceMaster parent = mock(PageSequenceMaster.class);
+
+        RepeatablePageMasterAlternatives sut = new RepeatablePageMasterAlternatives(parent);
+
+        sut.startOfNode();
+        sut.bind(pList);
+        sut.addConditionalPageMasterReference(cpmr);
+        return sut;
+    }
+
+}
+

Property changes on: test/java/org/apache/fop/fo/pagination/RepeatablePageMasterAlternativesTestCase.java
___________________________________________________________________
Added: svn:keywords
   + Revision Id
Added: svn:eol-style
   + native

Index: test/java/org/apache/fop/fo/pagination/PageSequenceMasterTestCase.java
===================================================================
--- test/java/org/apache/fop/fo/pagination/PageSequenceMasterTestCase.java	(revision 0)
+++ test/java/org/apache/fop/fo/pagination/PageSequenceMasterTestCase.java	(revision 0)
@@ -0,0 +1,90 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/* $Id$ */
+
+package org.apache.fop.fo.pagination;
+
+import static org.mockito.Matchers.anyBoolean;
+import static org.mockito.Matchers.anyInt;
+import static org.mockito.Matchers.anyString;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+import junit.framework.TestCase;
+
+import org.apache.fop.fo.FONode;
+import org.apache.fop.layoutmgr.BlockLevelEventProducer;
+
+/**
+ * Unit Test for PageSequenceMaster
+ *
+ */
+public class PageSequenceMasterTestCase extends TestCase {
+
+   /**
+    * Test that PageProductionException is thrown if the final simple-page-master
+    * cannot handle the main-flow of the page sequence
+    * @throws Exception exception
+    */
+    public void testGetNextSimplePageMasterException() throws Exception {
+
+        final String mainFlowRegionName = "main";
+        final String emptyFlowRegionName = "empty";
+        //  Create stubs
+
+        FONode mockParent = mock(FONode.class);
+        Root mockRoot = mock(Root.class);
+        LayoutMasterSet mockLayoutMasterSet = mock(LayoutMasterSet.class);
+
+        //  This will represent a page master that does not map to the main flow
+        //  of the page sequence
+        SimplePageMaster mockEmptySPM = mock(SimplePageMaster.class);
+        Region mockRegion = mock(Region.class);
+        SinglePageMasterReference mockSinglePageMasterReference
+                = mock(SinglePageMasterReference.class);
+        BlockLevelEventProducer mockBlockLevelEventProducer = mock(BlockLevelEventProducer.class);
+
+        //Stub behaviour
+        when(mockParent.getRoot()).thenReturn(mockRoot);
+        when(mockRoot.getLayoutMasterSet()).thenReturn(mockLayoutMasterSet);
+
+        //The layout master set should return the empty page master
+        when(mockLayoutMasterSet.getSimplePageMaster(anyString())).thenReturn(mockEmptySPM);
+        when(mockEmptySPM.getRegion(anyInt())).thenReturn(mockRegion);
+
+        when(mockRegion.getRegionName()).thenReturn(emptyFlowRegionName);
+
+        when(mockSinglePageMasterReference.getNextPageMaster(anyBoolean(), anyBoolean(),
+                anyBoolean(), anyBoolean()))
+                .thenReturn(null, mockEmptySPM);
+
+        PageSequenceMaster pageSequenceMaster = new PageSequenceMaster(mockParent,
+                mockBlockLevelEventProducer);
+        pageSequenceMaster.startOfNode();
+        pageSequenceMaster.addSubsequenceSpecifier(mockSinglePageMasterReference);
+
+        try {
+            pageSequenceMaster.getNextSimplePageMaster(false, false, false, false,
+                    mainFlowRegionName);
+            fail("The next simple page master does not refer to the main flow");
+       } catch (PageProductionException ppe) {
+           //Passed test
+       }
+    }
+
+}
+

Property changes on: test/java/org/apache/fop/fo/pagination/PageSequenceMasterTestCase.java
___________________________________________________________________
Added: svn:keywords
   + Revision Id
Added: svn:eol-style
   + native

Index: src/java/org/apache/fop/render/rtf/RTFHandler.java
===================================================================
--- src/java/org/apache/fop/render/rtf/RTFHandler.java	(revision 1040929)
+++ src/java/org/apache/fop/render/rtf/RTFHandler.java	(working copy)
@@ -32,7 +32,6 @@
 import java.util.Map;
 
 import org.w3c.dom.Document;
-
 import org.xml.sax.SAXException;
 
 import org.apache.commons.io.IOUtils;
@@ -116,13 +115,13 @@
 import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfHyperLink;
 import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfList;
 import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfListItem;
+import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfListItem.RtfListItemLabel;
 import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfPage;
 import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfSection;
 import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfTable;
 import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfTableCell;
 import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfTableRow;
 import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfTextrun;
-import org.apache.fop.render.rtf.rtflib.rtfdoc.RtfListItem.RtfListItemLabel;
 import org.apache.fop.render.rtf.rtflib.tools.BuilderContext;
 import org.apache.fop.render.rtf.rtflib.tools.PercentContext;
 import org.apache.fop.render.rtf.rtflib.tools.TableContext;
@@ -222,7 +221,7 @@
                     PageSequenceMaster master
                         = pageSeq.getRoot().getLayoutMasterSet().getPageSequenceMaster(reference);
                     this.pagemaster = master.getNextSimplePageMaster(
-                            false, false, false, false);
+                            false, false, false, false, pageSeq.getMainFlow().getFlowName());
                 }
             }
 
Index: src/java/org/apache/fop/layoutmgr/PageSequenceLayoutManager.java
===================================================================
--- src/java/org/apache/fop/layoutmgr/PageSequenceLayoutManager.java	(revision 1040929)
+++ src/java/org/apache/fop/layoutmgr/PageSequenceLayoutManager.java	(working copy)
@@ -100,7 +100,7 @@
             log.debug("Starting layout");
         }
 
-        curPage = makeNewPage(false, false);
+        curPage = makeNewPage(false);
 
         PageBreaker breaker = new PageBreaker(this);
         int flowBPD = getCurrentPV().getBodyRegion().getRemainingBPD();
@@ -140,6 +140,18 @@
                 pageNumber, PageProvider.RELTO_PAGE_SEQUENCE);
     }
 
+    @Override
+    protected Page makeNewPage(boolean isBlank) {
+        Page newPage;
+
+        do {
+            newPage = super.makeNewPage(isBlank);
+        } while (!getPageSequence().getMainFlow().getFlowName()
+                .equals(newPage.getSimplePageMaster().getRegion(FO_REGION_BODY).getRegionName()));
+
+        return newPage;
+    }
+
     private void layoutSideRegion(int regionID) {
         SideRegion reg = (SideRegion)curPage.getSimplePageMaster().getRegion(regionID);
         if (reg == null) {
Index: src/java/org/apache/fop/layoutmgr/ExternalDocumentLayoutManager.java
===================================================================
--- src/java/org/apache/fop/layoutmgr/ExternalDocumentLayoutManager.java	(revision 1040929)
+++ src/java/org/apache/fop/layoutmgr/ExternalDocumentLayoutManager.java	(working copy)
@@ -168,7 +168,7 @@
 
     private void makePageForImage(ImageInfo info, ImageLayout layout) {
         this.imageLayout = layout;
-        curPage = makeNewPage(false, false);
+        curPage = makeNewPage(false);
         fillPage(info.getOriginalURI());
         finishPage();
     }
Index: src/java/org/apache/fop/layoutmgr/PageProvider.java
===================================================================
--- src/java/org/apache/fop/layoutmgr/PageProvider.java	(revision 1040929)
+++ src/java/org/apache/fop/layoutmgr/PageProvider.java	(working copy)
@@ -27,7 +27,6 @@
 import org.apache.fop.area.AreaTreeHandler;
 import org.apache.fop.fo.Constants;
 import org.apache.fop.fo.pagination.PageSequence;
-import org.apache.fop.fo.pagination.Region;
 import org.apache.fop.fo.pagination.SimplePageMaster;
 
 /**
@@ -52,7 +51,7 @@
     private int startPageOfCurrentElementList;
     private int startColumnOfCurrentElementList;
     private boolean spanAllForCurrentElementList;
-    private List cachedPages = new java.util.ArrayList();
+    private List<Page> cachedPages = new java.util.ArrayList<Page>();
 
     private int lastPageIndex = -1;
     private int indexOfCachedLastPage = -1;
@@ -298,7 +297,7 @@
             }
             cacheNextPage(index, isBlank, isLastPage, this.spanAllForCurrentElementList);
         }
-        Page page = (Page)cachedPages.get(intIndex);
+        Page page = cachedPages.get(intIndex);
         boolean replace = false;
         if (page.getPageViewport().isBlank() != isBlank) {
             log.debug("blank condition doesn't match. Replacing PageViewport.");
@@ -332,15 +331,6 @@
         SimplePageMaster spm = pageSeq.getNextSimplePageMaster(
                 index, isFirstPage, isLastPage, isBlank);
 
-        Region body = spm.getRegion(FO_REGION_BODY);
-        if (!pageSeq.getMainFlow().getFlowName().equals(body.getRegionName())) {
-            // this is fine by the XSL Rec (fo:flow's flow-name can be mapped to
-            // any region), but we don't support it yet.
-            BlockLevelEventProducer eventProducer = BlockLevelEventProducer.Provider.get(
-                    pageSeq.getUserAgent().getEventBroadcaster());
-            eventProducer.flowNotMappingToRegionBody(this,
-                    pageSeq.getMainFlow().getFlowName(), spm.getMasterName(), spm.getLocator());
-        }
         Page page = new Page(spm, index, pageNumberString, isBlank, spanAll);
         //Set unique key obtained from the AreaTreeHandler
         page.getPageViewport().setKey(areaTreeHandler.generatePageViewportKey());
Index: src/java/org/apache/fop/layoutmgr/PageBreaker.java
===================================================================
--- src/java/org/apache/fop/layoutmgr/PageBreaker.java	(revision 1040929)
+++ src/java/org/apache/fop/layoutmgr/PageBreaker.java	(working copy)
@@ -411,7 +411,7 @@
                 addAreas(alg, restartPoint, partCount - restartPoint, originalList, effectiveList);
                 //...and add a blank last page
                 pageProvider.setLastPageIndex(currentPageNum + 1);
-                pslm.setCurrentPage(pslm.makeNewPage(true, true));
+                pslm.setCurrentPage(pslm.makeNewPage(true));
                 return;
             }
         }
@@ -529,14 +529,14 @@
 
             if (forceNewPageWithSpan) {
                 log.trace("Forcing new page with span");
-                curPage = pslm.makeNewPage(false, false);
+                curPage = pslm.makeNewPage(false);
                 curPage.getPageViewport().createSpan(true);
             } else if (pv.getCurrentSpan().hasMoreFlows()) {
                 log.trace("Moving to next flow");
                 pv.getCurrentSpan().moveToNextFlow();
             } else {
                 log.trace("Making new page");
-                /*curPage = */pslm.makeNewPage(false, false);
+                /*curPage = */pslm.makeNewPage(false);
             }
             return;
         default:
@@ -544,11 +544,11 @@
                 + " breakVal=" + getBreakClassName(breakVal));
             if (needBlankPageBeforeNew(breakVal)) {
                 log.trace("Inserting blank page");
-                /*curPage = */pslm.makeNewPage(true, false);
+                /*curPage = */pslm.makeNewPage(true);
             }
             if (needNewPage(breakVal)) {
                 log.trace("Making new page");
-                /*curPage = */pslm.makeNewPage(false, false);
+                /*curPage = */pslm.makeNewPage(false);
             }
         }
     }
Index: src/java/org/apache/fop/layoutmgr/AbstractPageSequenceLayoutManager.java
===================================================================
--- src/java/org/apache/fop/layoutmgr/AbstractPageSequenceLayoutManager.java	(revision 1040929)
+++ src/java/org/apache/fop/layoutmgr/AbstractPageSequenceLayoutManager.java	(working copy)
@@ -276,10 +276,9 @@
      * Makes a new page
      *
      * @param isBlank whether this page is blank or not
-     * @param isLast whether this page is the last page or not
      * @return a new page
      */
-    protected Page makeNewPage(boolean isBlank, boolean isLast) {
+    protected Page makeNewPage(boolean isBlank) {
         if (curPage != null) {
             finishPage();
         }
@@ -359,19 +358,19 @@
 
         if (forcePageCount == Constants.EN_EVEN) {
             if ((currentPageNum - startPageNum + 1) % 2 != 0) { // we have an odd number of pages
-                curPage = makeNewPage(true, false);
+                curPage = makeNewPage(true);
             }
         } else if (forcePageCount == Constants.EN_ODD) {
             if ((currentPageNum - startPageNum + 1) % 2 == 0) { // we have an even number of pages
-                curPage = makeNewPage(true, false);
+                curPage = makeNewPage(true);
             }
         } else if (forcePageCount == Constants.EN_END_ON_EVEN) {
             if (currentPageNum % 2 != 0) { // we are now on an odd page
-                curPage = makeNewPage(true, false);
+                curPage = makeNewPage(true);
             }
         } else if (forcePageCount == Constants.EN_END_ON_ODD) {
             if (currentPageNum % 2 == 0) { // we are now on an even page
-                curPage = makeNewPage(true, false);
+                curPage = makeNewPage(true);
             }
         } else if (forcePageCount == Constants.EN_NO_FORCE) {
             // i hope: nothing special at all
Index: src/java/org/apache/fop/fo/FOElementMapping.java
===================================================================
--- src/java/org/apache/fop/fo/FOElementMapping.java	(revision 1040929)
+++ src/java/org/apache/fop/fo/FOElementMapping.java	(working copy)
@@ -24,6 +24,8 @@
 
 import org.apache.xmlgraphics.util.QName;
 
+import org.apache.fop.layoutmgr.BlockLevelEventProducer;
+
 /**
  * Element mapping class for all XSL-FO elements.
  */
@@ -44,7 +46,7 @@
      */
     protected void initialize() {
         if (foObjs == null) {
-            foObjs = new HashMap();
+            foObjs = new HashMap<String, Maker>();
 
             // Declarations and Pagination and Layout Formatting Objects
             foObjs.put("root", new RootMaker());
@@ -205,7 +207,9 @@
 
     static class PageSequenceMasterMaker extends ElementMapping.Maker {
         public FONode make(FONode parent) {
-            return new org.apache.fop.fo.pagination.PageSequenceMaster(parent);
+            return new org.apache.fop.fo.pagination.PageSequenceMaster(parent,
+                    BlockLevelEventProducer.Provider.get(
+                            parent.getUserAgent().getEventBroadcaster()));
         }
     }
 
Index: src/java/org/apache/fop/fo/ElementMapping.java
===================================================================
--- src/java/org/apache/fop/fo/ElementMapping.java	(revision 1040929)
+++ src/java/org/apache/fop/fo/ElementMapping.java	(working copy)
@@ -38,7 +38,7 @@
     public static final String DEFAULT = "<default>";
 
     /** The HashMap table of formatting objects defined by the ElementMapping */
-    protected HashMap foObjs = null;
+    protected HashMap<String, Maker> foObjs = null;
     //Please don't change that to java.util.Map as that can break extensions.
 
     /** The namespace for the ElementMapping */
Index: src/java/org/apache/fop/fo/pagination/RepeatablePageMasterAlternatives.java
===================================================================
--- src/java/org/apache/fop/fo/pagination/RepeatablePageMasterAlternatives.java	(revision 1040929)
+++ src/java/org/apache/fop/fo/pagination/RepeatablePageMasterAlternatives.java	(working copy)
@@ -20,6 +20,7 @@
 package org.apache.fop.fo.pagination;
 
 // Java
+import java.util.ArrayList;
 import java.util.List;
 
 import org.xml.sax.Locator;
@@ -48,7 +49,7 @@
 
     private int numberConsumed = 0;
 
-    private List conditionalPageMasterRefs;
+    private List<ConditionalPageMasterReference> conditionalPageMasterRefs;
     private boolean hasPagePositionLast = false;
     private boolean hasPagePositionOnly = false;
 
@@ -68,7 +69,7 @@
 
     /** {@inheritDoc} */
     protected void startOfNode() throws FOPException {
-        conditionalPageMasterRefs = new java.util.ArrayList();
+        conditionalPageMasterRefs = new java.util.ArrayList<ConditionalPageMasterReference>();
 
         assert parent.getName().equals("fo:page-sequence-master"); //Validation by the parent
         PageSequenceMaster pageSequenceMaster = (PageSequenceMaster)parent;
@@ -114,27 +115,24 @@
     }
 
     /** {@inheritDoc} */
-    public String getNextPageMasterName(boolean isOddPage,
+    public SimplePageMaster getNextPageMaster(boolean isOddPage,
                                         boolean isFirstPage,
                                         boolean isLastPage,
                                         boolean isBlankPage) {
-        if (getMaximumRepeats() != INFINITE) {
-            if (numberConsumed < getMaximumRepeats()) {
-                numberConsumed++;
-            } else {
-                return null;
-            }
-        } else {
-            numberConsumed++;
+
+        if (!isInfinite() && numberConsumed >= getMaximumRepeats()) {
+            return null;
         }
 
-        for (int i = 0; i < conditionalPageMasterRefs.size(); i++) {
-            ConditionalPageMasterReference cpmr
-                = (ConditionalPageMasterReference)conditionalPageMasterRefs.get(i);
+        numberConsumed++;
+
+        for (ConditionalPageMasterReference cpmr : conditionalPageMasterRefs) {
             if (cpmr.isValid(isOddPage, isFirstPage, isLastPage, isBlankPage)) {
-                return cpmr.getMasterReference();
+                return cpmr.getMaster();
             }
         }
+
+
         return null;
     }
 
@@ -191,4 +189,50 @@
         return FO_REPEATABLE_PAGE_MASTER_ALTERNATIVES;
     }
 
+
+
+    /** {@inheritDoc} */
+    public void resolveReferences(LayoutMasterSet layoutMasterSet) throws ValidationException {
+        for (ConditionalPageMasterReference conditionalPageMasterReference
+                : conditionalPageMasterRefs) {
+            conditionalPageMasterReference.resolveReferences(layoutMasterSet);
+        }
+
+    }
+
+    /** {@inheritDoc} */
+    public boolean canProcess(String flowName) {
+
+        boolean willTerminate = true;
+
+
+        //Look for rest spm that cannot terminate
+        ArrayList<ConditionalPageMasterReference> rest
+                = new ArrayList<ConditionalPageMasterReference>();
+        for (ConditionalPageMasterReference cpmr
+                : conditionalPageMasterRefs) {
+            if (cpmr.isValid(true, false, false, false)
+                    || cpmr.isValid(false, false, false, false)) {
+                rest.add(cpmr);
+            }
+        }
+        if (!rest.isEmpty()) {
+            willTerminate = false;
+            for (ConditionalPageMasterReference cpmr : rest) {
+                willTerminate |= cpmr.getMaster().getRegion(FO_REGION_BODY).getRegionName()
+                        .equals(flowName);
+            }
+        }
+
+
+        return willTerminate;
+    }
+
+    /** {@inheritDoc} */
+    public boolean isInfinite() {
+        return getMaximumRepeats() == INFINITE;
+    }
+
+
+
 }
Index: src/java/org/apache/fop/fo/pagination/SimplePageMaster.java
===================================================================
--- src/java/org/apache/fop/fo/pagination/SimplePageMaster.java	(revision 1040929)
+++ src/java/org/apache/fop/fo/pagination/SimplePageMaster.java	(working copy)
@@ -21,7 +21,6 @@
 
 // Java
 import java.util.HashMap;
-import java.util.Iterator;
 import java.util.Map;
 
 import org.xml.sax.Locator;
@@ -29,8 +28,8 @@
 import org.apache.fop.apps.FOPException;
 import org.apache.fop.datatypes.Length;
 import org.apache.fop.datatypes.Numeric;
-import org.apache.fop.datatypes.SimplePercentBaseContext;
 import org.apache.fop.datatypes.PercentBaseContext;
+import org.apache.fop.datatypes.SimplePercentBaseContext;
 import org.apache.fop.fo.FONode;
 import org.apache.fop.fo.FObj;
 import org.apache.fop.fo.PropertyList;
@@ -56,7 +55,7 @@
     /**
      * Page regions (regionClass, Region)
      */
-    private Map regions;
+    private Map<String, Region> regions;
 
      // used for node validation
     private boolean hasRegionBody = false;
@@ -99,7 +98,7 @@
         }
 
         //Well, there are only 5 regions so we can save a bit of memory here
-        regions = new HashMap(5);
+        regions = new HashMap<String, Region>(5);
     }
 
     /** {@inheritDoc} */
@@ -240,14 +239,14 @@
      * @return the region, null if it doesn't exist
      */
     public Region getRegion(int regionId) {
-        return (Region) regions.get(String.valueOf(regionId));
+        return regions.get(String.valueOf(regionId));
     }
 
     /**
      * Returns a Map of regions associated with this simple-page-master
      * @return the regions
      */
-    public Map getRegions() {
+    public Map<String, Region> getRegions() {
         return regions;
     }
 
@@ -258,9 +257,7 @@
      * @return True if a region with this name exists
      */
     protected boolean regionNameExists(String regionName) {
-        for (Iterator regenum = regions.values().iterator();
-                regenum.hasNext();) {
-            Region r = (Region) regenum.next();
+        for (Region r : regions.values()) {
             if (r.getRegionName().equals(regionName)) {
                 return true;
             }
Index: src/java/org/apache/fop/fo/pagination/PageProductionException.java
===================================================================
--- src/java/org/apache/fop/fo/pagination/PageProductionException.java	(revision 1040929)
+++ src/java/org/apache/fop/fo/pagination/PageProductionException.java	(working copy)
@@ -25,8 +25,8 @@
 import org.xml.sax.helpers.LocatorImpl;
 
 import org.apache.fop.events.Event;
+import org.apache.fop.events.EventExceptionManager.ExceptionFactory;
 import org.apache.fop.events.EventFormatter;
-import org.apache.fop.events.EventExceptionManager.ExceptionFactory;
 
 /**
  * Exception thrown by FOP if there is a problem while producing new pages.
@@ -38,9 +38,18 @@
     private String localizedMessage;
     private Locator locator;
 
+
     /**
      * Creates a new PageProductionException.
      * @param message the message
+     */
+    public PageProductionException(String message) {
+        super(message);
+    }
+
+    /**
+     * Creates a new PageProductionException.
+     * @param message the message
      * @param locator the optional locator that points to the error in the source file
      */
     public PageProductionException(String message, Locator locator) {
@@ -48,12 +57,13 @@
         setLocator(locator);
     }
 
+
     /**
      * Set a location associated with the exception.
      * @param locator the locator holding the location.
      */
     public void setLocator(Locator locator) {
-        this.locator = new LocatorImpl(locator);
+        this.locator = locator != null ? new LocatorImpl(locator) : null;
     }
 
 
Index: src/java/org/apache/fop/fo/pagination/LayoutMasterSet.java
===================================================================
--- src/java/org/apache/fop/fo/pagination/LayoutMasterSet.java	(revision 1040929)
+++ src/java/org/apache/fop/fo/pagination/LayoutMasterSet.java	(working copy)
@@ -20,7 +20,6 @@
 package org.apache.fop.fo.pagination;
 
 // Java
-import java.util.Iterator;
 import java.util.Map;
 
 import org.xml.sax.Locator;
@@ -44,8 +43,8 @@
  */
 public class LayoutMasterSet extends FObj {
 
-    private Map simplePageMasters;
-    private Map pageSequenceMasters;
+    private Map<String, SimplePageMaster> simplePageMasters;
+    private Map<String, PageSequenceMaster> pageSequenceMasters;
 
     /**
      * Create a LayoutMasterSet instance that is a child of the given
@@ -65,8 +64,8 @@
     /** {@inheritDoc} */
     protected void startOfNode() throws FOPException {
         getRoot().setLayoutMasterSet(this);
-        simplePageMasters = new java.util.HashMap();
-        pageSequenceMasters = new java.util.HashMap();
+        simplePageMasters = new java.util.HashMap<String, SimplePageMaster>();
+        pageSequenceMasters = new java.util.HashMap<String, PageSequenceMaster>();
     }
 
     /** {@inheritDoc} */
@@ -75,6 +74,7 @@
             missingChildElementError("(simple-page-master|page-sequence-master)+");
         }
         checkRegionNames();
+        resolveSubSequenceReferences();
     }
 
     /**
@@ -98,18 +98,14 @@
      */
     private void checkRegionNames() throws ValidationException {
         // (user-entered) region-name to default region map.
-        Map allRegions = new java.util.HashMap();
-        for (Iterator spm = simplePageMasters.values().iterator();
-                spm.hasNext();) {
-            SimplePageMaster simplePageMaster
-                = (SimplePageMaster)spm.next();
-            Map spmRegions = simplePageMaster.getRegions();
-            for (Iterator e = spmRegions.values().iterator();
-                    e.hasNext();) {
-                Region region = (Region) e.next();
+        Map<String, String> allRegions = new java.util.HashMap<String, String>();
+
+        for (SimplePageMaster simplePageMaster : simplePageMasters.values()) {
+
+            for (Region region : simplePageMaster.getRegions().values()) {
                 if (allRegions.containsKey(region.getRegionName())) {
                     String defaultRegionName
-                        = (String) allRegions.get(region.getRegionName());
+                        =  allRegions.get(region.getRegionName());
                     if (!defaultRegionName.equals(region.getDefaultRegionName())) {
                         getFOValidationEventProducer().regionNameMappedToMultipleRegionClasses(this,
                                 region.getRegionName(),
@@ -123,6 +119,14 @@
         }
     }
 
+    private void resolveSubSequenceReferences() throws ValidationException {
+        for (PageSequenceMaster psm : pageSequenceMasters.values()) {
+            for (SubSequenceSpecifier subSequenceSpecifier : psm.getSubSequenceSpecifier()) {
+                subSequenceSpecifier.resolveReferences(this);
+            }
+        }
+    }
+
     /**
      * Add a simple page master.
      * The name is checked to throw an error if already added.
@@ -155,7 +159,7 @@
      * @return the requested simple-page-master
      */
     public SimplePageMaster getSimplePageMaster(String masterName) {
-        return (SimplePageMaster)this.simplePageMasters.get(masterName);
+        return simplePageMasters.get(masterName);
     }
 
     /**
@@ -185,7 +189,7 @@
      * @return the requested PageSequenceMaster instance
      */
     public PageSequenceMaster getPageSequenceMaster(String masterName) {
-        return (PageSequenceMaster)this.pageSequenceMasters.get(masterName);
+        return this.pageSequenceMasters.get(masterName);
     }
 
     /**
@@ -194,9 +198,8 @@
      * @return true when the region name specified has a region in this LayoutMasterSet
      */
     public boolean regionNameExists(String regionName) {
-        for (Iterator e = simplePageMasters.values().iterator();
-                e.hasNext();) {
-            if (((SimplePageMaster)e.next()).regionNameExists(regionName)) {
+        for (SimplePageMaster spm : simplePageMasters.values()) {
+            if (spm.regionNameExists(regionName)) {
                 return true;
             }
         }
Index: src/java/org/apache/fop/fo/pagination/PageSequence.java
===================================================================
--- src/java/org/apache/fop/fo/pagination/PageSequence.java	(revision 1040929)
+++ src/java/org/apache/fop/fo/pagination/PageSequence.java	(working copy)
@@ -48,7 +48,7 @@
     // the set of flows includes StaticContent flows also
 
     /** Map of flows to their flow name (flow-name, Flow) */
-    private Map/*<String, Flow>*/ flowMap;
+    private Map<String, FONode> flowMap;
 
     /**
      * The currentSimplePageMaster is either the page master for the
@@ -96,7 +96,7 @@
     /** {@inheritDoc} */
     protected void startOfNode() throws FOPException {
         super.startOfNode();
-        flowMap = new java.util.HashMap/*<String, Flow>*/();
+        flowMap = new java.util.HashMap<String, FONode>();
 
         this.simplePageMaster
             = getRoot().getLayoutMasterSet().getSimplePageMaster(masterReference);
@@ -270,7 +270,7 @@
                     + " isBlank=" + isBlank + ")");
         }
         return pageSequenceMaster.getNextSimplePageMaster(isOddPage,
-            isFirstPage, isLastPage, isBlank);
+            isFirstPage, isLastPage, isBlank, getMainFlow().getFlowName());
     }
 
     /**
Index: src/java/org/apache/fop/fo/pagination/SinglePageMasterReference.java
===================================================================
--- src/java/org/apache/fop/fo/pagination/SinglePageMasterReference.java	(revision 1040929)
+++ src/java/org/apache/fop/fo/pagination/SinglePageMasterReference.java	(working copy)
@@ -27,6 +27,7 @@
 import org.apache.fop.fo.FObj;
 import org.apache.fop.fo.PropertyList;
 import org.apache.fop.fo.ValidationException;
+import org.apache.fop.layoutmgr.BlockLevelEventProducer;
 
 /**
  * Class modelling the <a href="http://www.w3.org/TR/xsl/#fo_single-page-master-reference">
@@ -39,6 +40,10 @@
 
     // The value of properties relevant for fo:single-page-master-reference.
     private String masterReference;
+
+    // The simple page master referenced
+    private SimplePageMaster master;
+
     // End of property values
 
     private static final int FIRST = 0;
@@ -83,13 +88,13 @@
     }
 
     /** {@inheritDoc} */
-    public String getNextPageMasterName(boolean isOddPage,
+    public SimplePageMaster getNextPageMaster(boolean isOddPage,
                                         boolean isFirstPage,
                                         boolean isLastPage,
                                         boolean isBlankPage) {
         if (this.state == FIRST) {
             this.state = DONE;
-            return masterReference;
+            return master;
         } else {
             return null;
         }
@@ -133,5 +138,25 @@
         return FO_SINGLE_PAGE_MASTER_REFERENCE;
     }
 
+    /** {@inheritDoc} */
+    public void resolveReferences(LayoutMasterSet layoutMasterSet) throws ValidationException {
+        master = layoutMasterSet.getSimplePageMaster(masterReference);
+        if (master == null) {
+            BlockLevelEventProducer.Provider.get(
+                getUserAgent().getEventBroadcaster())
+                .noMatchingPageMaster(this, parent.getName(), masterReference, getLocator());
+        }
+    }
+
+    /** {@inheritDoc} */
+    public boolean canProcess(String flowName) {
+        return master.getRegion(FO_REGION_BODY).getRegionName().equals(flowName);
+    }
+
+    /** {@inheritDoc} */
+    public boolean isInfinite() {
+        return false;
+    }
+
 }
 
Index: src/java/org/apache/fop/fo/pagination/SubSequenceSpecifier.java
===================================================================
--- src/java/org/apache/fop/fo/pagination/SubSequenceSpecifier.java	(revision 1040929)
+++ src/java/org/apache/fop/fo/pagination/SubSequenceSpecifier.java	(working copy)
@@ -19,6 +19,7 @@
 
 package org.apache.fop.fo.pagination;
 
+import org.apache.fop.fo.ValidationException;
 
 /**
  * Classes that implement this interface can be added to a {@link PageSequenceMaster},
@@ -35,7 +36,7 @@
      * @return the page master name
      * @throws PageProductionException if there's a problem determining the next page master
      */
-    String getNextPageMasterName(boolean isOddPage,
+    SimplePageMaster getNextPageMaster(boolean isOddPage,
                                  boolean isFirstPage,
                                  boolean isLastPage,
                                  boolean isBlankPage)
@@ -59,5 +60,26 @@
     /** @return true if the subsequence has a page master for page-position "only" */
     boolean hasPagePositionOnly();
 
+    /**
+     * called by the parent LayoutMasterSet to resolve object references
+     * from simple page master reference names
+     * @param layoutMasterSet the layout-master-set
+     * @throws ValidationException when a named reference cannot be resolved
+     * */
+    void resolveReferences(LayoutMasterSet layoutMasterSet) throws ValidationException;
+
+    /**
+     *
+     * @param flowName name of the main flow
+     * @return true iff page sequence is a finite sequence or can process the entire main flow
+     */
+    boolean canProcess(String flowName);
+
+    /**
+     * Test that this is a finite sequence
+     * @return true iff this is a finite sequence
+     */
+    boolean isInfinite();
+
 }
 
Index: src/java/org/apache/fop/fo/pagination/PageSequenceMaster.java
===================================================================
--- src/java/org/apache/fop/fo/pagination/PageSequenceMaster.java	(revision 1040929)
+++ src/java/org/apache/fop/fo/pagination/PageSequenceMaster.java	(working copy)
@@ -20,6 +20,7 @@
 package org.apache.fop.fo.pagination;
 
 // Java
+import java.util.Collections;
 import java.util.List;
 
 import org.xml.sax.Locator;
@@ -44,9 +45,10 @@
     // End of property values
 
     private LayoutMasterSet layoutMasterSet;
-    private List subSequenceSpecifiers;
+    private List<SubSequenceSpecifier> subSequenceSpecifiers;
     private SubSequenceSpecifier currentSubSequence;
     private int currentSubSequenceNumber = -1;
+    private BlockLevelEventProducer blockLevelEventProducer;
 
     // The terminology may be confusing. A 'page-sequence-master' consists
     // of a sequence of what the XSL spec refers to as
@@ -60,9 +62,11 @@
      * given {@link FONode}.
      *
      * @param parent {@link FONode} that is the parent of this object
+     * @param blockLevelEventProducer event producer
      */
-    public PageSequenceMaster(FONode parent) {
+    public PageSequenceMaster(FONode parent, BlockLevelEventProducer blockLevelEventProducer) {
         super(parent);
+        this.blockLevelEventProducer = blockLevelEventProducer;
     }
 
     /** {@inheritDoc} */
@@ -76,7 +80,7 @@
 
     /** {@inheritDoc} */
     protected void startOfNode() throws FOPException {
-        subSequenceSpecifiers = new java.util.ArrayList();
+        subSequenceSpecifiers = new java.util.ArrayList<SubSequenceSpecifier>();
         layoutMasterSet = parent.getRoot().getLayoutMasterSet();
         layoutMasterSet.addPageSequenceMaster(masterName, this);
     }
@@ -121,12 +125,15 @@
         currentSubSequenceNumber++;
         if (currentSubSequenceNumber >= 0
                 && currentSubSequenceNumber < subSequenceSpecifiers.size()) {
-            return (SubSequenceSpecifier)subSequenceSpecifiers
-              .get(currentSubSequenceNumber);
+            return subSequenceSpecifiers.get(currentSubSequenceNumber);
         }
         return null;
     }
 
+    List<SubSequenceSpecifier> getSubSequenceSpecifier() {
+        return Collections.unmodifiableList(subSequenceSpecifiers);
+    }
+
     /**
      * Resets the subsequence specifiers subsystem.
      */
@@ -134,8 +141,8 @@
         currentSubSequenceNumber = -1;
         currentSubSequence = null;
         if (subSequenceSpecifiers != null) {
-            for (int i = 0; i < subSequenceSpecifiers.size(); i++) {
-                ((SubSequenceSpecifier)subSequenceSpecifiers.get(i)).reset();
+            for (SubSequenceSpecifier subSequenceSpecifier : subSequenceSpecifiers) {
+                subSequenceSpecifier.reset();
             }
         }
     }
@@ -150,7 +157,7 @@
             if (!success) {
                 if (currentSubSequenceNumber > 0) {
                     currentSubSequenceNumber--;
-                    currentSubSequence = (SubSequenceSpecifier)subSequenceSpecifiers
+                    currentSubSequence = subSequenceSpecifiers
                         .get(currentSubSequenceNumber);
                 } else {
                     currentSubSequence = null;
@@ -178,52 +185,58 @@
      * @param isFirstPage True if the next page is the first
      * @param isLastPage True if the next page is the last
      * @param isBlankPage True if the next page is blank
+     * @param mainFlowName the name of the main flow of the page sequence
      * @return the requested page master
      * @throws PageProductionException if there's a problem determining the next page master
      */
     public SimplePageMaster getNextSimplePageMaster(boolean isOddPage,
                                                     boolean isFirstPage,
                                                     boolean isLastPage,
-                                                    boolean isBlankPage)
+                                                    boolean isBlankPage,
+                                                    String mainFlowName)
                                                       throws PageProductionException {
         if (currentSubSequence == null) {
             currentSubSequence = getNextSubSequence();
             if (currentSubSequence == null) {
-                BlockLevelEventProducer eventProducer = BlockLevelEventProducer.Provider.get(
-                        getUserAgent().getEventBroadcaster());
-                eventProducer.missingSubsequencesInPageSequenceMaster(this,
+                blockLevelEventProducer.missingSubsequencesInPageSequenceMaster(this,
                         masterName, getLocator());
             }
+            if (currentSubSequence.isInfinite() && !currentSubSequence.canProcess(mainFlowName)) {
+                throw new PageProductionException(
+                "The current sub-sequence will not terminate whilst processing then main flow");
+            }
         }
-        String pageMasterName = currentSubSequence
-            .getNextPageMasterName(isOddPage, isFirstPage, isLastPage, isBlankPage);
+
+        SimplePageMaster pageMaster = currentSubSequence
+            .getNextPageMaster(isOddPage, isFirstPage, isLastPage, isBlankPage);
+
         boolean canRecover = true;
-        while (pageMasterName == null) {
+
+        while (pageMaster == null) {
             SubSequenceSpecifier nextSubSequence = getNextSubSequence();
+
             if (nextSubSequence == null) {
-                BlockLevelEventProducer eventProducer = BlockLevelEventProducer.Provider.get(
-                        getUserAgent().getEventBroadcaster());
-                eventProducer.pageSequenceMasterExhausted(this,
+                //Sub-sequence exhausted so attempt to reuse it
+                blockLevelEventProducer.pageSequenceMasterExhausted(this,
                         masterName, canRecover, getLocator());
                 currentSubSequence.reset();
+                if (!currentSubSequence.canProcess(mainFlowName)) {
+                    throw new PageProductionException(
+                    "The last simple-page-master does not reference the main flow");
+                }
                 canRecover = false;
             } else {
                 currentSubSequence = nextSubSequence;
             }
-            pageMasterName = currentSubSequence
-                .getNextPageMasterName(isOddPage, isFirstPage, isLastPage, isBlankPage);
+
+            pageMaster = currentSubSequence
+                .getNextPageMaster(isOddPage, isFirstPage, isLastPage, isBlankPage);
         }
-        SimplePageMaster pageMaster = this.layoutMasterSet
-            .getSimplePageMaster(pageMasterName);
-        if (pageMaster == null) {
-            BlockLevelEventProducer eventProducer = BlockLevelEventProducer.Provider.get(
-                    getUserAgent().getEventBroadcaster());
-            eventProducer.noMatchingPageMaster(this,
-                    masterName, pageMasterName, getLocator());
-        }
+
         return pageMaster;
     }
 
+
     /** {@inheritDoc} */
     public String getLocalName() {
         return "page-sequence-master";
@@ -236,5 +249,7 @@
     public int getNameId() {
         return FO_PAGE_SEQUENCE_MASTER;
     }
+
+
 }
 
Index: src/java/org/apache/fop/fo/pagination/ConditionalPageMasterReference.java
===================================================================
--- src/java/org/apache/fop/fo/pagination/ConditionalPageMasterReference.java	(revision 1040929)
+++ src/java/org/apache/fop/fo/pagination/ConditionalPageMasterReference.java	(working copy)
@@ -27,6 +27,7 @@
 import org.apache.fop.fo.FObj;
 import org.apache.fop.fo.PropertyList;
 import org.apache.fop.fo.ValidationException;
+import org.apache.fop.layoutmgr.BlockLevelEventProducer;
 
 /**
  * Class modelling the <a href="http://www.w3.org/TR/xsl/#fo_conditional-page-master-reference">
@@ -41,6 +42,8 @@
 public class ConditionalPageMasterReference extends FObj {
     // The value of properties relevant for fo:conditional-page-master-reference.
     private String masterReference;
+    // The simple page master referenced
+    private SimplePageMaster master;
     private int pagePosition;
     private int oddOrEven;
     private int blankOrNotBlank;
@@ -127,8 +130,8 @@
      * Get the value for the <code>master-reference</code> property.
      * @return the "master-reference" property
      */
-    public String getMasterReference() {
-        return masterReference;
+    public SimplePageMaster getMaster() {
+        return master;
     }
 
     /**
@@ -151,4 +154,19 @@
     public int getNameId() {
         return FO_CONDITIONAL_PAGE_MASTER_REFERENCE;
     }
+
+    /**
+     * called by the parent RepeatablePageMasterAlternatives to resolve object references
+     * from  simple page master reference names
+     * @param layoutMasterSet the layout-master-set
+     * @throws ValidationException when a named reference cannot be resolved
+     * */
+    public void resolveReferences(LayoutMasterSet layoutMasterSet) throws ValidationException {
+        master = layoutMasterSet.getSimplePageMaster(masterReference);
+        if (master == null) {
+            BlockLevelEventProducer.Provider.get(
+                getUserAgent().getEventBroadcaster())
+                .noMatchingPageMaster(this, parent.getName(), masterReference, getLocator());
+        }
+    }
 }
Index: src/java/org/apache/fop/fo/pagination/RepeatablePageMasterReference.java
===================================================================
--- src/java/org/apache/fop/fo/pagination/RepeatablePageMasterReference.java	(revision 1040929)
+++ src/java/org/apache/fop/fo/pagination/RepeatablePageMasterReference.java	(working copy)
@@ -28,6 +28,7 @@
 import org.apache.fop.fo.PropertyList;
 import org.apache.fop.fo.ValidationException;
 import org.apache.fop.fo.properties.Property;
+import org.apache.fop.layoutmgr.BlockLevelEventProducer;
 
 /**
  * Class modelling the <a href="http://www.w3.org/TR/xsl/#fo_repeatable-page-master-reference">
@@ -40,6 +41,8 @@
 
     // The value of properties relevant for fo:repeatable-page-master-reference.
     private String masterReference;
+    // The simple page master referenced
+    private SimplePageMaster master;
     private Property maximumRepeats;
     // End of property values
 
@@ -87,18 +90,15 @@
     }
 
     /** {@inheritDoc} */
-    public String getNextPageMasterName(boolean isOddPage,
+    public SimplePageMaster getNextPageMaster(boolean isOddPage,
                                         boolean isFirstPage,
                                         boolean isLastPage,
                                         boolean isEmptyPage) {
-        if (getMaximumRepeats() != INFINITE) {
-            if (numberConsumed < getMaximumRepeats()) {
-                numberConsumed++;
-            } else {
-                return null;
-            }
+        if (getMaximumRepeats() != INFINITE && numberConsumed >= getMaximumRepeats()) {
+           return null;
         }
-        return masterReference;
+        numberConsumed++;
+        return master;
     }
 
     /**
@@ -159,4 +159,27 @@
     }
 
 
+    /** {@inheritDoc} */
+    public void resolveReferences(LayoutMasterSet layoutMasterSet) throws ValidationException {
+        master = layoutMasterSet.getSimplePageMaster(masterReference);
+        if (master == null) {
+            BlockLevelEventProducer.Provider.get(
+                getUserAgent().getEventBroadcaster())
+                .noMatchingPageMaster(this, parent.getName(), masterReference, getLocator());
+        }
+
+    }
+
+    /** {@inheritDoc} */
+    public boolean canProcess(String flowName) {
+        return master.getRegion(FO_REGION_BODY).getRegionName().equals(flowName);
+    }
+
+    /** {@inheritDoc} */
+    public boolean isInfinite() {
+        return getMaximumRepeats() == INFINITE;
+    }
+
+
+
 }
Index: build.xml
===================================================================
--- build.xml	(revision 1040929)
+++ build.xml	(working copy)
@@ -87,7 +87,10 @@
   <patternset id="dist.src.lib.tools">
 	<include name="lib/build/asm*"/>
 	<include name="lib/build/backport-util-concurrent*"/>
+	<include name="lib/build/hamcrest*"/>
 	<include name="lib/build/jaxen*"/>
+	<include name="lib/build/mockito-core*"/>
+	<include name="lib/build/objenesis*"/>
 	<include name="lib/build/pmd*"/>
 	<include name="lib/build/qdox*"/>
         <include name="lib/build/xmlunit*"/>
@@ -877,6 +880,7 @@
       <classpath>
         <pathelement location="${build.dir}/test-classes"/>
         <path refid="libs-build-classpath"/>
+      	<path refid="libs-tools-build-classpath"/>
         <fileset dir="build">
           <include name="fop.jar"/>
         </fileset>
Index: lib/build/mockito-core-1.8.5.NOTICE.txt
===================================================================
--- lib/build/mockito-core-1.8.5.NOTICE.txt	(revision 0)
+++ lib/build/mockito-core-1.8.5.NOTICE.txt	(revision 0)
@@ -0,0 +1,11 @@
+Mockito license - MIT.
+
+Libraries used:
+
+Cglib - Apache License 2.0
+ASM - BSD license
+
+Mockito all distribution:
+
+Objenesis - MIT license
+Hamcrest - BSD license
\ No newline at end of file
Index: lib/build/mockito-core-1.8.5.LICENCE.txt
===================================================================
--- lib/build/mockito-core-1.8.5.LICENCE.txt	(revision 0)
+++ lib/build/mockito-core-1.8.5.LICENCE.txt	(revision 0)
@@ -0,0 +1,21 @@
+The MIT License
+
+Copyright (c) 2007 Mockito contributors
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
\ No newline at end of file
Index: lib/build/hamcrest.core-1.1.0.LICENSE.txt
===================================================================
--- lib/build/hamcrest.core-1.1.0.LICENSE.txt	(revision 0)
+++ lib/build/hamcrest.core-1.1.0.LICENSE.txt	(revision 0)
@@ -0,0 +1,27 @@
+BSD License
+
+Copyright (c) 2000-2006, www.hamcrest.org
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+Redistributions of source code must retain the above copyright notice, this list of
+conditions and the following disclaimer. Redistributions in binary form must reproduce
+the above copyright notice, this list of conditions and the following disclaimer in
+the documentation and/or other materials provided with the distribution.
+
+Neither the name of Hamcrest nor the names of its contributors may be used to endorse
+or promote products derived from this software without specific prior written
+permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
+EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
+SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
+TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
+BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
+WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
+DAMAGE.
\ No newline at end of file
Index: lib/build/objenesis-1.0.0.LICENSE.txt
===================================================================
--- lib/build/objenesis-1.0.0.LICENSE.txt	(revision 0)
+++ lib/build/objenesis-1.0.0.LICENSE.txt	(revision 0)
@@ -0,0 +1,18 @@
+Copyright (c) 2003-2008, Objenesis Team and all contributors
+
+Permission is hereby granted, free of charge, to any person obtaining a copy of 
+this software and associated documentation files (the "Software"), to deal in
+the Software without restriction, including without limitation the rights to
+use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
+the Software, and to permit persons to whom the Software is furnished to do so,
+subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
+FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR 
+COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER 
+IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN 
+CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
\ No newline at end of file
