protected function _buildStories() {
        $storiesByPageNumber    = array();
        $storiesByTag           = array();
        $pagesCount             = count($this->pages);

        // Build an array with all textframe positions, divided into the accompanying story XML tags
        foreach ($this->textFrames as $textFrame) {
            $story = new Garp_Adobe_InDesign_Story($textFrame->storyId, $this->_workingDir);
            if ($tag = $story->getTag()) {
                $storiesByTag[$tag][] = array(
                    'storyId' => $textFrame->storyId,
                    'x' => $textFrame->x
                );
            }
        }

        //  sort the stories by horizontal position
        $sortFunction = function ($storyA, $storyB) {
            if ($storyA['x'] == $storyB['x']) {
                return 0;
            }
            return $storyA['x'] > $storyB['x'] ? 1 : -1;
        };

        foreach ($storiesByTag as &$stories) {
            usort($stories, $sortFunction);
        }

        //  now divide the stories in pages
        foreach ($storiesByTag as $tagStories) {
            $tagStoriesCount    = count($tagStories);
            $tagStoriesPerPage  = $tagStoriesCount / $pagesCount;

            foreach ($tagStories as $s => $tagStory) {
                $page           = floor($s / $tagStoriesPerPage);
                $pageNumber     = $this->pages[$page]->index;
                $storiesByPageNumber[$pageNumber][] = $tagStory['storyId'];
            }
        }

        return $storiesByPageNumber;
    }