Grimm's Fairy Tales (ABC Books rebuild guide) 24OCT2026

Book 10 of ABC Books: 15 Grimm tales in Margaret Hunt's 1884 translation, cut into 88 short parts, with Arthur Rackham's pictures

Posted on 24th Oct 2026

The tenth book in ABC Books is Grimm’s Fairy Tales, one dark red book on the home shelf that opens its own Fairy Tales page (one book per tale, each marked with its number in the whole collection, like “Tale 39 of 211”) at https://abcbooks.fyi/ (and https://games.503mail.com/abcbooks/). It has all 211 tales: The Elves, The Frog-King, Little Red-Cap, The Bremen Town-Musicians, Rumpelstiltskin, Mother Holle, Briar-Rose, Rapunzel, Cinderella and Hansel and Grethel, then (second batch, same day) The Wolf and the Seven Little Kids, Little Snow-white, The Golden Goose, The Shoes That Were Danced to Pieces (the twelve dancing princesses, called “The Dancing Shoes” in part titles) and Thumbling, then (third batch, 25 tales in the collection’s own order, filling the gaps from Tale 2) Cat and Mouse in Partnership, Our Lady’s Child, The Story of the Youth Who Went Forth to Learn What Fear Was (“The Youth Who Learned Fear” in part titles), Faithful John, The Good Bargain, The Wonderful Musician, The Twelve Brothers, The Pack of Ragamuffins, Little Brother and Little Sister, The Three Little Men in the Wood, The Three Spinners, The Three Snake-Leaves, The White Snake, The Straw, the Coal, and the Bean, The Fisherman and His Wife, The Valiant Little Tailor, The Riddle, The Mouse, the Bird, and the Sausage, The Seven Ravens, The Singing Bone, The Devil With the Three Golden Hairs, The Louse and the Flea, The Girl Without Hands, Clever Hans and The Three Languages, then (fourth batch, 50 tales, the next ones in the collection’s order) Tales 34 to 89, from Clever Elsie to The Goose-Girl (two long titles are shortened in part titles: “The Wishing-Table” and “Fundevogel”), then (fifth batch) all the rest from Tale 90 to Tale 211, with Tale 110, The Jew Among Thorns, added last and flagged for grown-ups (see Notes; “Master Pfriem (Master Cobbler’s Awl)” is “Master Pfriem” in part titles). Each tale is cut into parts of about 250 words, and each part is one lesson with the usual steps: new words, listen, your turn to read (with the reading check), tracing and the blackboard. For the first time a book has real pictures: Arthur Rackham’s plates. The app itself is rebuilt in the Primer post. Every block has a Copy button.

The book

  • Grimm’s Household Tales, translated by Margaret Hunt (1884), with pictures by Arthur Rackham (1900/1909). Both are public domain.
  • The text and pictures come from a PDF of the Maplewood Books Grimm’s Fairy Tales: Illustrated Edition (2013), which has all 211 tales (282,200 words) and 36 Rackham plates. Only the tales and plates are used; Maplewood’s own introduction, film list and notes are skipped.
  • The text is the original translation, not softened (“thou”, “thee”, the witch in the oven, the stepsisters and the doves are all still there). Grown-ups may want to read a tale first.
  • First batch: 10 tales, 56 parts, 938 lines, 14 pictures. Second batch: 5 more tales added after them (so the first 56 lessons keep their numbers and every kid keeps their stars), 32 parts. Third batch: 25 tales (Tales 2 to 33 that weren’t in yet), 147 parts. Fourth batch: 50 tales (Tales 34 to 89), 257 parts. Fifth batch: the other 121 tales, 493 parts; now 985 parts. The rest of the 211 tales can be added later by putting their titles at the END of the pick list.
  • About 45,000 things to say per speed (4,263 in the first batch, 7,193 new in the third, 11,521 new in the fourth, 20,355 new in the fifth), recorded in ETI-Eloquence, plus 7,653 sound-it-out words.

What’s new in the app

  • Tale parts: a lesson is one part of a tale, named “Rapunzel, part 2 of 5” on the map, in the “Go to lesson” list and in the spoken lesson title. Each lesson also carries tale, part and parts, so other games can tell when a whole tale is finished.
  • Fairy Tales page (added 24 Oct 2026, same day): the home shelf has one Grimm’s Fairy Tales book (“Tales: 15”, or “โ˜… 3 of 15 finished” for the reader). Tapping it opens the Fairy Tales page, where each tale is its own book, in the order of the whole collection, with its number: The Frog-King is “Tale 1 of 211”, The Elves “Tale 39 of 211”. A started tale shows “Part 2 of 7” and glows, a finished one “โ˜… Finished!”. The back button on a tale’s map goes back to the Fairy Tales page. Stars are still saved under the one book grimm1884, so nothing the kids already read is lost. The numbers come from make-book.ps1, which writes taleNo into every part and taleCount into the book file.
  • BlockCraft Fairy Tale Kingdom: when a kid finishes the last part of a tale, the stars screen says that its place in BlockCraft is open, and the app sends the kid’s finished tales to the BlockCraft server (games.503mail.com/blockcraft/api/tales, also from abcbooks.fyi; it sends every reader’s finished tales each time the app starts). See BlockCraft add-on: the Fairy Tale Kingdom.
  • Pictures: a lesson with img shows that picture at the top of Listen instead of an emoji. A tale’s pictures are spread over its parts, and a part without its own picture keeps the last one. The Elves and The Bremen Town-Musicians have no plates in this edition and show an emoji (๐Ÿ‘ž, ๐Ÿ“).
  • Shorter lines: Hunt’s sentences are long, so a line is one sentence, and a sentence over 28 words is cut at a semicolon or colon, then before “, and / but / then / when…”, then at a comma. That keeps each line short enough for “Your turn to read”.

How the text is made

Two scripts:

  1. split-grimm.ps1 reads the PDF with Poppler (pdftotext, pdfimages), finds each tale (a short title line at the top of a page, then a blank line), joins wrapped lines into paragraphs, and saves the plates (the 500x600 images; the 500x29 ones are divider lines). It writes source\grimm.txt ("= Title", “@ page”, “% picture”, then one paragraph per line) and source\grimm\pics\rackham-01.jpg to rackham-36.jpg.
  2. make-book.ps1 -Book grimm1884 (the new tales mode) takes the tales in its pick list and cuts each into parts: a part ends at the first paragraph end after 200 words, or at a sentence end after 330 words; a sub-heading (“SECOND STORY” in The Elves) starts a new part, and a tiny last piece joins the part before. New words are worked out like in the later Readers: words not met in any McGuffey book or an earlier part, 10 per part. It also copies the pictures it uses to public\pics\grimm\.

Add this book to ABC Books

You need the app from the Primer post and its C:\ABCBooks folder on the PC (with ETI-Eloquence installed). Copy the files below the same way as in the Primer post (the scp and arrange-rebuild.ps1 steps).

1. Tools

Poppler gives pdftotext and pdfimages. PC (PowerShell):

winget install oschwartz10612.Poppler

Save the Maplewood PDF as grimm_s_fairy_tales__complete_a_-_jacob_grimm.pdf in your Downloads folder (or pass -Pdf <path> to split-grimm.ps1).

2. Files

Proxmox host shell:

mkdir -p /root/abcbooks-rebuild

split-grimm.ps1: PDF to source\grimm.txt + the Rackham pictures.

cat > /root/abcbooks-rebuild/split-grimm.ps1 <<'EOF'
# Splits the Maplewood "Grimm's Fairy Tales: Illustrated Edition" (Margaret Hunt 1884 translation, Arthur Rackham pictures,
# both public domain) into source/grimm.txt: "= Title" starts a tale, "@ page" = PDF page it starts on, "% n" = a Rackham
# picture (source/grimm/pics/rackham-NN.jpg), then one paragraph per line (poem/song lines stay one per line).
# Usage: powershell -ExecutionPolicy Bypass -File ABCBooks\tools\split-grimm.ps1 [-Pdf <path>]
param([string]$Pdf = "$env:USERPROFILE\Downloads\grimm_s_fairy_tales__complete_a_-_jacob_grimm.pdf")
$root = Split-Path -Parent (Split-Path -Parent $MyInvocation.MyCommand.Path)
$bin = (Get-ChildItem "$env:LOCALAPPDATA\Microsoft\WinGet\Packages" -Recurse -Filter pdftotext.exe | Select-Object -First 1).DirectoryName
$work = "$root\source\grimm"; New-Item -ItemType Directory -Force "$work\pics" | Out-Null
& "$bin\pdftotext.exe" -enc UTF-8 $Pdf "$work\maplewood.txt"
$list = & "$bin\pdfimages.exe" -list $Pdf | Select-Object -Skip 2
# the real plates are 500x600 (the 500x29 ones are divider lines); extract each plate page by page
$plates = @($list | ForEach-Object { $c = -split $_; if ($c[3] -eq '500' -and $c[4] -eq '600') { [int]$c[0] } })
$n = 0
foreach ($p in $plates) {
  $n++; $f = "$work\pics\rackham-{0:D2}" -f $n
  if (-not (Test-Path "$f.jpg")) {
    & "$bin\pdfimages.exe" -j -f $p -l $p $Pdf "$work\pics\tmp"
    $big = Get-ChildItem "$work\pics\tmp*" | Sort-Object Length -Descending | Select-Object -First 1
    Move-Item $big.FullName "$f.jpg" -Force; Remove-Item "$work\pics\tmp*"
  }
}
$pages = ([IO.File]::ReadAllText("$work\maplewood.txt") -replace "`r", '') -split "`f"
$start = 0; for ($i = 0; $i -lt $pages.Count; $i++) { if ($pages[$i] -match '^The Frog-King, or Iron Henry\n') { $start = $i; break } }
$tales = @(); $t = $null; $legend = $false
for ($i = $start; $i -lt $pages.Count; $i++) {
  $pg = $pages[$i]
  if ($pg -match '^(?:Film Adaptations|Fan Resources)') { break }
  # a tale starts at the top of a page: a short title line, then a blank line
  if ($pg -match '^([A-Z][^\n]{1,70})\n\n') {
    $title = $Matches[1].Trim()
    if ($title -notmatch '[.,;:!?"]$' -or $title -match '^(?:Dr\.|Mr\.)') {
      if ($t) { $tales += $t }
      if ($title -eq "Children's Legends") { $legend = $true; continue }
      $t = [ordered]@{ title = $title; page = $i + 1; legend = $legend; pics = @(); lines = New-Object Collections.Generic.List[string] }
      $pg = $pg.Substring($Matches[0].Length)
    }
  }
  if (-not $t) { continue }
  for ($k = 0; $k -lt $plates.Count; $k++) { if ($plates[$k] -eq $i + 1) { $t.pics += ($k + 1) } }
  foreach ($ln in $pg -split "`n") { $t.lines.Add($ln.TrimEnd()) }
}
if ($t) { $tales += $t }
# join wrapped lines into paragraphs: a full-width line (>= 88 chars) runs on; a short one ends the paragraph
$sb = New-Object Text.StringBuilder
[void]$sb.AppendLine("# Grimm's Fairy Tales, Margaret Hunt translation (1884), from the Maplewood Books illustrated edition; made by tools/split-grimm.ps1")
foreach ($t in $tales) {
  [void]$sb.AppendLine("= $($t.title)"); [void]$sb.AppendLine("@ $($t.page)")
  if ($t.legend) { [void]$sb.AppendLine('! legend') }
  foreach ($p in $t.pics) { [void]$sb.AppendLine("% $p") }
  $para = ''
  foreach ($ln in $t.lines) {
    if (-not $ln.Trim()) { continue }
    $para = if ($para) { if ($para.EndsWith('-') -and $para -notmatch '\s\S+--?$') { $para + $ln.Trim() } else { $para + ' ' + $ln.Trim() } } else { $ln.Trim() }
    if ($ln.Length -lt 88) { [void]$sb.AppendLine($para); $para = '' }
  }
  if ($para) { [void]$sb.AppendLine($para) }
}
$out = $sb.ToString() -replace [char]0x2014, ' - ' -replace '  +', ' '
# pdftotext drops the hyphen of a compound word broken over two lines ("kitchen-" + "wench" -> "kitchenwench"):
# put it back where the book writes the same word with a hyphen elsewhere, plus a hand list for the ones it never does
$hy = @{}; foreach ($m in [regex]::Matches($out, '\b([A-Za-z]+)-([A-Za-z]+)\b')) { $hy[($m.Groups[1].Value + $m.Groups[2].Value).ToLower()] = $m.Value.ToLower() }
$extra = @{}; foreach ($h in 'oak-trees', 'window-ledge', 'town-musician', 'newly-coined', 'hazel-tree', 'doodle-doo', 'kitchen-wench', 'christ-child', 'bed-gown') { $extra[$h -replace '-', ''] = $h }
$fixed = @{}
$out = [regex]::Replace($out, '\b[A-Za-z]{6,}\b', {
  param($m) $w = $m.Value; $lw = $w.ToLower()
  if ($hy.ContainsKey($lw)) { $h = $hy[$lw] }
  elseif ($extra.ContainsKey($lw)) { $h = $extra[$lw] }
  else { return $w }
  $fixed[$lw] = $h
  $r = ''; $k = 0; foreach ($c in $h.ToCharArray()) { if ($c -eq '-') { $r += '-' } else { $r += $w[$k]; $k++ } }; $r   # keep the word's own capitals
})
"hyphens put back: $($fixed.Count) words: $(($fixed.Values | Sort-Object) -join ', ')"
[IO.File]::WriteAllText("$root\source\grimm.txt", $out, (New-Object Text.UTF8Encoding $false))
$words = ([regex]::Matches(($tales | ForEach-Object { $_.lines -join ' ' }) -join ' ', '\S+')).Count
"$($tales.Count) tales ($(@($tales | Where-Object legend).Count) legends), $words words, $($plates.Count) pictures"
$tales | ForEach-Object { "{0,4} {1,-50} {2,6} words {3}" -f $_.page, $_.title, ([regex]::Matches(($_.lines -join ' '), '\S+')).Count, $(if ($_.pics.Count) { 'pic ' + ($_.pics -join ',') } else { '' }) }
EOF

make-book.ps1: the converter, with the new grimm1884 book and tales mode.

cat > /root/abcbooks-rebuild/make-book.ps1 <<'EOF'
# Builds public/books/<book>.json from a Project Gutenberg text of a McGuffey Reader.
# Usage: powershell -ExecutionPolicy Bypass -File ABCBooks\tools\make-book.ps1 -Book primer1881
#        powershell -ExecutionPolicy Bypass -File ABCBooks\tools\make-book.ps1 -Book first1879
param([ValidateSet('primer1881', 'first1879', 'second1879', 'third1879', 'fourth1879', 'fifth1879', 'sixth1879', 'spell1867', 'grimm1884')] [string]$Book = 'primer1881')
$root = Split-Path -Parent (Split-Path -Parent $MyInvocation.MyCommand.Path)
$books = @{
  # Grimm's Fairy Tales: source/grimm.txt made by tools/split-grimm.ps1 from the Maplewood PDF (Hunt 1884 + Rackham pictures).
  # Only the tales in "pick" go in, in that order; each tale is cut into parts of about 250 words (one lesson each).
  grimm1884  = @{ tales = $true; file = 'grimm.txt'; title = "Grimm's Fairy Tales"; sub = 'Margaret Hunt translation, 1884'; color = '#9b2335'
                  source = "Grimm's Household Tales, translated by Margaret Hunt (1884), pictures by Arthur Rackham (1909), public domain"
                  pick = @('The Elves', 'The Frog-King, or Iron Henry', 'Little Red-Cap', 'The Bremen Town-Musicians', 'Rumpelstiltskin',
                           'Mother Holle', 'Briar-Rose', 'Rapunzel', 'Cinderella', 'Hansel and Grethel',
                           'The Wolf and the Seven Little Kids', 'Little Snow-white', 'The Golden Goose', 'The Shoes That Were Danced to Pieces', 'Thumbling',
                           'Cat and Mouse in Partnership', "Our Lady's Child", 'The Story of the Youth Who Went Forth to Learn What Fear Was', 'Faithful John', 'The Good Bargain',
                           'The Wonderful Musician', 'The Twelve Brothers', 'The Pack of Ragamuffins', 'Little Brother and Little Sister', 'The Three Little Men in the Wood',
                           'The Three Spinners', 'The Three Snake-Leaves', 'The White Snake', 'The Straw, the Coal, and the Bean', 'The Fisherman and His Wife',
                           'The Valiant Little Tailor', 'The Riddle', 'The Mouse, the Bird, and the Sausage', 'The Seven Ravens', 'The Singing Bone',
                           'The Devil With the Three Golden Hairs', 'The Louse and the Flea', 'The Girl Without Hands', 'Clever Hans', 'The Three Languages',
                           'Clever Elsie', 'The Tailor in Heaven', 'The Wishing-Table, the Gold-Ass, and the Cudgel in the Sack', 'The Wedding of Mrs. Fox', 'The Robber Bridegroom',
                           'Herr Korbes', 'The Godfather', 'Frau Trude', 'Godfather Death', 'Thumbling as Journeyman',
                           "Fitcher's Bird", 'The Juniper-Tree', 'Old Sultan', 'The Six Swans', 'Fundevogel (Bird-foundling)',
                           'King Thrushbeard', 'The Knapsack, the Hat, and the Horn', 'Sweetheart Roland', 'The Golden Bird', 'The Dog and the Sparrow',
                           'Frederick and Catherine', 'The Two Brothers', 'The Little Peasant', 'The Queen Bee', 'The Three Feathers',
                           'Allerleirauh', "The Hare's Bride", 'The Twelve Huntsmen', 'The Thief and his Master', 'Jorinda and Joringel',
                           'The Three Sons of Fortune', 'How Six Men Got on in the World', 'The Wolf and the Man', 'The Wolf and the Fox', 'The Fox and His Cousin',
                           'The Fox and the Cat', 'The Pink', 'Clever Grethel', 'The Old Man and His Grandson', 'The Water-Nix',
                           'The Death of the Little Hen', 'Brother Lustig', 'Gambling Hansel', 'Hans in Luck', 'Hans Married',
                           'The Gold-Children', 'The Fox and the Geese', 'The Poor Man and the Rich Man', 'The Singing, Springing Lark', 'The Goose-Girl',
                           'The Young Giant', 'The Gnome', 'The King of the Golden Mountain', 'The Raven', "The Peasant's Wise Daughter",
                           'Old Hildebrand', 'The Three Little Birds', 'The Water of Life', 'Doctor Knowall', 'The Spirit in the Bottle',
                           "The Devil's Sooty Brother", 'Bearskin', 'The Willow-Wren and the Bear', 'Sweet Porridge', 'Wise Folks',
                           'Stories about Snakes', "The Poor Miller's Boy and the Cat", 'The Two Travellers', 'Hans the Hedgehog', 'The Shroud',
                           'The Skilful Huntsman', 'The Flail From Heaven', "The Two Kings' Children", 'The Cunning Little Tailor', 'The Bright Sun Brings It to Light',
                           'The Blue Light', 'The Wilful Child', 'The Three Army-Surgeons', 'The Seven Swabians', 'The Three Apprentices',
                           "The King's Son Who Feared Nothing", 'Donkey Cabbages', 'The Old Woman in the Wood', 'The Three Brothers', 'The Devil and his Grandmother',
                           'Ferdinand the Faithful', 'The Iron Stove', 'The Lazy Spinner', 'The Four Skilful Brothers', 'One-eye, Two-eyes, and Three-eyes',
                           'Fair Katrinelje and Pif-Paf-Poltrie', 'The Fox and the Horse', 'The Six Servants', 'The White Bride and the Black One', 'Iron John',
                           'The Three Black Princesses', 'Knoist and his Three Sons', 'The Maid of Brakel', 'Domestic Servants', 'The Lambkin and the Little Fish',
                           'Simeli Mountain', 'Going A-Travelling', 'The Donkey', 'The Ungrateful Son', 'The Turnip',
                           'The Old Man Made Young Again', "The Lord's Animals and the Devil's", 'The Beam', 'The Old Beggar-Woman', 'The Three Sluggards',
                           'The Twelve Idle Servants', 'The Shepherd Boy', 'The Star-Money', 'The Stolen Farthings', 'Brides On Their Trial',
                           'Odds And Ends', 'The Sparrow And His Four Children', 'The Story of Schlauraffen Land', 'The Ditmarsch Tale of Wonders', 'A Riddling Tale',
                           'Snow-White and Rose-Red', 'The Wise Servant', 'The Glass Coffin', 'Lazy Harry', 'The Griffin',
                           'Strong Hans', 'The Peasant in Heaven', 'Lean Lisa', 'The Hut in the Forest', 'Sharing Joy and Sorrow',
                           'The Willow-Wren', 'The Sole', 'The Bittern and the Hoopoe', 'The Owl', 'The Moon',
                           'The Duration of Life', "Death's Messengers", "Master Pfriem (Master Cobbler's Awl)", 'The Goose-Girl at the Well', "Eve's Various Children",
                           'The Nix of the Mill-Pond', "The Little Folks' Presents", 'The Giant and the Tailor', 'The Nail', 'The Poor Boy in the Grave',
                           'The True Sweethearts', 'The Hare and the Hedgehog', 'The Spindle, The Shuttle, and the Needle', 'The Peasant and the Devil', 'The Crumbs on the Table',
                           'The Sea-Hare', 'The Master-Thief', 'The Drummer', 'The Ear of Corn', 'The Grave-Mound',
                           'Old Rinkrank', 'The Crystal Ball', 'Maid Maleen', 'The Boots of Buffalo-Leather', 'The Golden Key',
                           'St. Joseph in the Forest', 'The Twelve Apostles', 'The Rose', 'Poverty and Humility Lead to Heaven', "God's Food",
                           'The Three Green Twigs', "Our Lady's Little Glass", 'The Aged Mother', 'The Heavenly Wedding', 'The Hazel-Branch',
                           'The Jew Among Thorns')
                  emoji = @{ 'The Elves' = '๐Ÿ‘ž'; 'The Frog-King, or Iron Henry' = '๐Ÿธ'; 'Little Red-Cap' = '๐Ÿบ'; 'The Bremen Town-Musicians' = '๐Ÿ“'
                             'Rumpelstiltskin' = '๐Ÿงต'; 'Mother Holle' = 'โ„๏ธ'; 'Briar-Rose' = '๐ŸŒน'; 'Rapunzel' = '๐Ÿ—ผ'; 'Cinderella' = '๐Ÿ‘ '; 'Hansel and Grethel' = '๐Ÿฌ'
                             'The Wolf and the Seven Little Kids' = '๐Ÿ'; 'Little Snow-white' = '๐ŸŽ'; 'The Golden Goose' = '๐Ÿฆข'; 'The Shoes That Were Danced to Pieces' = '๐Ÿ‘‘'; 'Thumbling' = '๐Ÿ‘'
                             'Cat and Mouse in Partnership' = '๐Ÿฑ'; "Our Lady's Child" = '๐Ÿ”‘'; 'The Story of the Youth Who Went Forth to Learn What Fear Was' = '๐Ÿ˜จ'; 'Faithful John' = '๐Ÿค'; 'The Good Bargain' = '๐Ÿ„'
                             'The Wonderful Musician' = '๐ŸŽป'; 'The Twelve Brothers' = '๐ŸŒท'; 'The Pack of Ragamuffins' = '๐Ÿ”'; 'Little Brother and Little Sister' = '๐ŸฆŒ'; 'The Three Little Men in the Wood' = '๐Ÿ“'
                             'The Three Spinners' = '๐Ÿงถ'; 'The Three Snake-Leaves' = '๐Ÿ'; 'The White Snake' = '๐Ÿ’'; 'The Straw, the Coal, and the Bean' = '๐ŸŒฑ'; 'The Fisherman and His Wife' = '๐ŸŸ'
                             'The Valiant Little Tailor' = 'โœ‚๏ธ'; 'The Riddle' = 'โ“'; 'The Mouse, the Bird, and the Sausage' = '๐Ÿญ'; 'The Seven Ravens' = '๐Ÿฆ'; 'The Singing Bone' = '๐Ÿฆด'
                             'The Devil With the Three Golden Hairs' = '๐Ÿ˜ˆ'; 'The Louse and the Flea' = '๐Ÿž'; 'The Girl Without Hands' = '๐Ÿ'; 'Clever Hans' = '๐Ÿงบ'; 'The Three Languages' = '๐Ÿ•'
                             'Clever Elsie' = '๐Ÿบ'; 'The Tailor in Heaven' = 'โ˜๏ธ'; 'The Wishing-Table, the Gold-Ass, and the Cudgel in the Sack' = '๐Ÿฝ๏ธ'; 'The Wedding of Mrs. Fox' = '๐ŸฆŠ'; 'The Robber Bridegroom' = '๐Ÿš๏ธ'
                             'Herr Korbes' = '๐Ÿ'; 'The Godfather' = '๐Ÿท'; 'Frau Trude' = '๐Ÿ”ฅ'; 'Godfather Death' = '๐Ÿ’€'; 'Thumbling as Journeyman' = '๐ŸŽ’'
                             "Fitcher's Bird" = '๐Ÿฅš'; 'The Juniper-Tree' = '๐ŸŒฒ'; 'Old Sultan' = '๐Ÿถ'; 'The Six Swans' = '๐Ÿ•Š๏ธ'; 'Fundevogel (Bird-foundling)' = '๐Ÿฃ'
                             'King Thrushbeard' = '๐Ÿคด'; 'The Knapsack, the Hat, and the Horn' = '๐ŸŽฉ'; 'Sweetheart Roland' = '๐ŸŒธ'; 'The Golden Bird' = '๐Ÿค'; 'The Dog and the Sparrow' = '๐Ÿž'
                             'Frederick and Catherine' = '๐Ÿง€'; 'The Two Brothers' = '๐Ÿ‰'; 'The Little Peasant' = '๐Ÿฎ'; 'The Queen Bee' = '๐Ÿ'; 'The Three Feathers' = '๐Ÿƒ'
                             'Allerleirauh' = '๐Ÿ‘—'; "The Hare's Bride" = '๐Ÿ‡'; 'The Twelve Huntsmen' = '๐Ÿน'; 'The Thief and his Master' = '๐ŸŽ“'; 'Jorinda and Joringel' = '๐ŸŒบ'
                             'The Three Sons of Fortune' = '๐Ÿˆ'; 'How Six Men Got on in the World' = '๐Ÿ’ช'; 'The Wolf and the Man' = '๐Ÿ—ก๏ธ'; 'The Wolf and the Fox' = '๐Ÿฅฉ'; 'The Fox and His Cousin' = '๐Ÿ‘'
                             'The Fox and the Cat' = '๐ŸŒณ'; 'The Pink' = '๐Ÿ’'; 'Clever Grethel' = '๐Ÿ–'; 'The Old Man and His Grandson' = '๐Ÿ‘ด'; 'The Water-Nix' = '๐ŸŒŠ'
                             'The Death of the Little Hen' = '๐Ÿฅ'; 'Brother Lustig' = '๐Ÿ˜‡'; 'Gambling Hansel' = '๐Ÿƒ'; 'Hans in Luck' = '๐Ÿ€'; 'Hans Married' = '๐Ÿ '
                             'The Gold-Children' = '๐ŸŒŸ'; 'The Fox and the Geese' = '๐Ÿฆ†'; 'The Poor Man and the Rich Man' = '๐Ÿ’ฐ'; 'The Singing, Springing Lark' = '๐Ÿฆ'; 'The Goose-Girl' = '๐Ÿด'
                             'The Young Giant' = '๐Ÿ—ฟ'; 'The Gnome' = '๐Ÿ•ณ๏ธ'; 'The King of the Golden Mountain' = 'โ›ฐ๏ธ'; 'The Raven' = '๐Ÿ–ค'; "The Peasant's Wise Daughter" = '๐Ÿ’ก'
                             'Old Hildebrand' = 'โ›ช'; 'The Three Little Birds' = '๐ŸŽถ'; 'The Water of Life' = '๐Ÿ’ง'; 'Doctor Knowall' = '๐Ÿ’Š'; 'The Spirit in the Bottle' = '๐Ÿพ'
                             "The Devil's Sooty Brother" = '๐Ÿ‘น'; 'Bearskin' = '๐Ÿป'; 'The Willow-Wren and the Bear' = 'โš”๏ธ'; 'Sweet Porridge' = '๐Ÿฒ'; 'Wise Folks' = '๐Ÿค”'
                             'Stories about Snakes' = '๐Ÿฅ›'; "The Poor Miller's Boy and the Cat" = '๐Ÿ˜บ'; 'The Two Travellers' = '๐Ÿšถ'; 'Hans the Hedgehog' = '๐Ÿ–'; 'The Shroud' = '๐Ÿ•ฏ๏ธ'
                             'The Skilful Huntsman' = '๐ŸŽฏ'; 'The Flail From Heaven' = '๐ŸŒง๏ธ'; "The Two Kings' Children" = '๐Ÿ’’'; 'The Cunning Little Tailor' = '๐Ÿ‘”'; 'The Bright Sun Brings It to Light' = 'โ˜€๏ธ'
                             'The Blue Light' = '๐Ÿ’™'; 'The Wilful Child' = '๐Ÿ‘ถ'; 'The Three Army-Surgeons' = 'โš•๏ธ'; 'The Seven Swabians' = '๐Ÿ”ฑ'; 'The Three Apprentices' = '๐Ÿ“œ'
                             "The King's Son Who Feared Nothing" = '๐Ÿ›ก๏ธ'; 'Donkey Cabbages' = '๐Ÿ'; 'The Old Woman in the Wood' = '๐Ÿ‚'; 'The Three Brothers' = '๐Ÿ‡'; 'The Devil and his Grandmother' = '๐Ÿ‘ต'
                             'Ferdinand the Faithful' = '๐Ÿ“'; 'The Iron Stove' = 'โ™จ๏ธ'; 'The Lazy Spinner' = '๐Ÿ˜ด'; 'The Four Skilful Brothers' = '๐Ÿ”ญ'; 'One-eye, Two-eyes, and Three-eyes' = '๐Ÿ‘๏ธ'
                             'Fair Katrinelje and Pif-Paf-Poltrie' = '๐Ÿ’ƒ'; 'The Fox and the Horse' = '๐ŸŽ'; 'The Six Servants' = '๐Ÿ‘‚'; 'The White Bride and the Black One' = 'โšช'; 'Iron John' = 'โ›“๏ธ'
                             'The Three Black Princesses' = 'โšซ'; 'Knoist and his Three Sons' = '๐ŸŽญ'; 'The Maid of Brakel' = '๐Ÿ™'; 'Domestic Servants' = '๐Ÿก'; 'The Lambkin and the Little Fish' = '๐Ÿ '
                             'Simeli Mountain' = 'โ›๏ธ'; 'Going A-Travelling' = '๐Ÿ—บ๏ธ'; 'The Donkey' = '๐ŸŽธ'; 'The Ungrateful Son' = '๐Ÿ˜ '; 'The Turnip' = '๐Ÿฅ•'
                             'The Old Man Made Young Again' = 'โณ'; "The Lord's Animals and the Devil's" = '๐Ÿ‚'; 'The Beam' = '๐Ÿ—๏ธ'; 'The Old Beggar-Woman' = 'โ˜‚๏ธ'; 'The Three Sluggards' = '๐Ÿ›Œ'
                             'The Twelve Idle Servants' = '๐Ÿ’ค'; 'The Shepherd Boy' = '๐Ÿ'; 'The Star-Money' = 'โญ'; 'The Stolen Farthings' = '๐Ÿ’ฒ'; 'Brides On Their Trial' = '๐Ÿ‘ฐ'
                             'Odds And Ends' = '๐ŸŽ€'; 'The Sparrow And His Four Children' = '๐Ÿ’'; 'The Story of Schlauraffen Land' = '๐Ÿฐ'; 'The Ditmarsch Tale of Wonders' = '๐Ÿ™ƒ'; 'A Riddling Tale' = '๐ŸŒผ'
                             'Snow-White and Rose-Red' = 'โ›„'; 'The Wise Servant' = '๐Ÿ™‹'; 'The Glass Coffin' = '๐Ÿบ'; 'Lazy Harry' = '๐Ÿ›‹๏ธ'; 'The Griffin' = '๐Ÿฆ…'
                             'Strong Hans' = '๐Ÿ‹๏ธ'; 'The Peasant in Heaven' = '๐ŸŒˆ'; 'Lean Lisa' = '๐Ÿฅ–'; 'The Hut in the Forest' = 'โ›บ'; 'Sharing Joy and Sorrow' = '๐Ÿ˜ข'
                             'The Willow-Wren' = '๐ŸŽ‹'; 'The Sole' = '๐Ÿก'; 'The Bittern and the Hoopoe' = '๐Ÿž๏ธ'; 'The Owl' = '๐Ÿฆ‰'; 'The Moon' = '๐ŸŒ™'
                             'The Duration of Life' = 'โŒ›'; "Death's Messengers" = '๐Ÿ“ฏ'; "Master Pfriem (Master Cobbler's Awl)" = '๐Ÿ”จ'; 'The Goose-Girl at the Well' = '๐Ÿ’Ž'; "Eve's Various Children" = '๐Ÿ‘ช'
                             'The Nix of the Mill-Pond' = '๐ŸŒ€'; "The Little Folks' Presents" = '๐ŸŽ'; 'The Giant and the Tailor' = '๐Ÿ‘ฃ'; 'The Nail' = '๐Ÿ“Œ'; 'The Poor Boy in the Grave' = 'โšฐ๏ธ'
                             'The True Sweethearts' = '๐Ÿ’•'; 'The Hare and the Hedgehog' = '๐Ÿƒ'; 'The Spindle, The Shuttle, and the Needle' = '๐Ÿ“'; 'The Peasant and the Devil' = '๐ŸŒฝ'; 'The Crumbs on the Table' = '๐Ÿช'
                             'The Sea-Hare' = '๐Ÿš'; 'The Master-Thief' = '๐Ÿ•ต๏ธ'; 'The Drummer' = '๐Ÿฅ'; 'The Ear of Corn' = '๐ŸŒพ'; 'The Grave-Mound' = '๐ŸŒš'
                             'Old Rinkrank' = '๐Ÿ”๏ธ'; 'The Crystal Ball' = '๐Ÿ”ฎ'; 'Maid Maleen' = '๐Ÿฐ'; 'The Boots of Buffalo-Leather' = '๐Ÿ‘ข'; 'The Golden Key' = '๐Ÿ—๏ธ'
                             'St. Joseph in the Forest' = 'โœจ'; 'The Twelve Apostles' = 'โœ๏ธ'; 'The Rose' = '๐Ÿต๏ธ'; 'Poverty and Humility Lead to Heaven' = '๐ŸŒ…'; "God's Food" = '๐Ÿฏ'
                             'The Three Green Twigs' = '๐ŸŒฟ'; "Our Lady's Little Glass" = '๐Ÿฅ‚'; 'The Aged Mother' = '๐Ÿ•ฐ๏ธ'; 'The Heavenly Wedding' = '๐Ÿ””'; 'The Hazel-Branch' = '๐ŸŒฐ'
                             'The Jew Among Thorns' = '๐ŸŒต' }
                  # flagged tales stay in the book with their original text, but the app leaves them out until a grown-up includes them
                  flag = @{ 'The Jew Among Thorns' = 'antisemitic: a Jewish man is the villain, beaten and hanged' }
                  short = @{ 'The Frog-King, or Iron Henry' = 'The Frog-King'; 'The Shoes That Were Danced to Pieces' = 'The Dancing Shoes'
                             'The Story of the Youth Who Went Forth to Learn What Fear Was' = 'The Youth Who Learned Fear'
                             'The Wishing-Table, the Gold-Ass, and the Cudgel in the Sack' = 'The Wishing-Table'; 'Fundevogel (Bird-foundling)' = 'Fundevogel'; "Master Pfriem (Master Cobbler's Awl)" = 'Master Pfriem' }
                  after = @('primer1881', 'first1879', 'second1879', 'third1879', 'fourth1879', 'fifth1879', 'sixth1879') }
  # Spell & Read: the 1867 Pictorial Primer, hand-corrected from a scan into source/spell1867.txt (no Gutenberg text exists)
  spell1867  = @{ hand = $true; file = 'spell1867.txt'; title = 'Spell & Read'; sub = 'Pictorial Primer, 1867'; color = '#5b6f3a'
                  source = 'McGuffey''s Pictorial Eclectic Primer, 1867 (archive.org mcguffeyspictori00mcgu, public domain), hand-corrected' }
  primer1881 = @{ gutenberg = 14642; file = 'primer.txt'; title = "McGuffey's Eclectic Primer"; sub = 'Revised Edition, 1881'; color = '#b5562c'
                  end = 'SLATE EXERCISES'; pics = @{ 27 = '๐Ÿž๏ธ'; 46 = 'โœ๏ธ' } }
  first1879  = @{ gutenberg = 14640; file = 'first.txt'; title = "McGuffey's First Eclectic Reader"; sub = 'Revised Edition, 1879'; color = '#2c6fb5'
                  end = 'PHONIC CHART.'; pics = @{} }
  second1879 = @{ gutenberg = 14668; file = 'second.txt'; title = "McGuffey's Second Eclectic Reader"; sub = 'Revised Edition, 1879'; color = '#3f8f4f'
                  end = '*** END OF THE PROJECT GUTENBERG'; pics = @{} }
  # prose = later Readers: no word lists in Gutenberg's copy (new words are worked out), printed page headers to remove,
  # numbered paragraphs that run on without blank lines, plays ("Rose. ...") and an author line under poems
  third1879  = @{ gutenberg = 14766; file = 'third.txt'; title = "McGuffey's Third Eclectic Reader"; sub = 'Revised Edition, 1879'; color = '#7b4fb5'
                  end = '*** END OF THE PROJECT GUTENBERG'; pics = @{}; prose = $true; pageRx = 'ECLECTIC SERIES|THIRD READER'
                  after = @('primer1881', 'first1879', 'second1879') }
  # Fourth Reader: headings carry the title ("I. PERSEVERANCE. (25)"), and each lesson ends with DEFINITIONS (the book's
  # own new words, with meanings), EXERCISES (questions to talk about) and sometimes NOTES
  fourth1879 = @{ gutenberg = 14880; file = 'fourth.txt'; title = "McGuffey's Fourth Eclectic Reader"; sub = 'Revised Edition, 1879'; color = '#b5892c'
                  end = '*** END OF THE PROJECT GUTENBERG'; pics = @{}; prose = $true; pageRx = 'ECLECTIC SERIES|FOURTH READER'
                  start = 'I. PERSEVERANCE. (25)'; tocStart = 'SELECTIONS IN PROSE AND POETRY.'; tocEnd = 'LIST OF ILLUSTRATIONS'
                  headRx = '(?m)^([IVXLCl]+)[.:][ \t]+([A-Z][^a-z\n]*?(?:\((?:Concluded|Continued)\.?\))?[^a-z\n]*?)[ \t]*(?:\(\d+\))?[ \t]*$'
                  after = @('primer1881', 'first1879', 'second1879', 'third1879') }
  # Fifth Reader: like the Fourth, but headings have no page number ("II. THE BLUEBELL.") and the first one is scanned as "1."
  fifth1879  = @{ gutenberg = 15040; file = 'fifth.txt'; title = "McGuffey's Fifth Eclectic Reader"; sub = 'Revised Edition, 1879'; color = '#2c9bb5'
                  end = '*** END OF THE PROJECT GUTENBERG'; pics = @{}; prose = $true; pageRx = 'ECLECTIC SERIES|FIFTH READER'
                  start = '1. THE GOOD READER.'
                  headRx = '(?m)^(\d+|[IVXLCl]+)[.:][ \t]+(["\u201c]?[A-Z][^a-z\n]*?(?:\((?:Concluded|Continued)\.?\))?[^a-z\n]*?)[ \t]*(?:\(\d+\))?[ \t]*$'
                  tocEnd = 'LIST OF ILLUSTRATIONS'
                  after = @('primer1881', 'first1879', 'second1879', 'third1879', 'fourth1879') }
  # Sixth Reader: headings with page numbers like the Fourth; the lessons start after the chapters on reading aloud
  sixth1879  = @{ gutenberg = 16751; file = 'sixth.txt'; title = "McGuffey's Sixth Eclectic Reader"; sub = 'Revised Edition, 1879'; color = '#8f3f5f'
                  end = '*** END OF THE PROJECT GUTENBERG'; pics = @{}; prose = $true; pageRx = 'ECLECTIC SERIES|SIXTH READER'
                  start = 'I. ANECDOTE OF THE DUKE OF NEWCASTLE.'
                  headRx = '(?m)^(\d+|[IVXLCl]+)[.:][ \t]+(["\u201c]?[A-Z][^a-z\n]*?(?:\((?:Concluded|Continued)\.?\))?[^a-z\n]*?)[ \t]*(?:\(\d+\))?[ \t]*$'
                  tocEnd = 'LIST OF ILLUSTRATIONS'
                  after = @('primer1881', 'first1879', 'second1879', 'third1879', 'fourth1879', 'fifth1879') }
}
$cfg = $books[$Book]
$pics = [ordered]@{ 'rat'='๐Ÿ€'; 'cat'='๐Ÿˆ'; 'kitten'='๐Ÿฑ'; 'dog'='๐Ÿ•'; 'frog'='๐Ÿธ'; 'chick'='๐Ÿค'; 'hen'='๐Ÿ”'; 'fox'='๐ŸฆŠ'; 'duck'='๐Ÿฆ†'; 'owl'='๐Ÿฆ‰'; 'bird'='๐Ÿฆ'; 'cow'='๐Ÿ„';
  'rabbit'='๐Ÿ‡'; 'pig'='๐Ÿ–'; 'lamb'='๐Ÿ‘'; 'kite'='๐Ÿช'; 'sled'='๐Ÿ›ท'; 'top'='๐ŸŽฉ'; 'ball'='โšฝ'; 'squirrel'='๐Ÿฟ๏ธ'; 'bee'='๐Ÿ'; 'boat'='โ›ต';
  'ship'='โ›ต'; 'skat'='โ›ธ๏ธ'; 'horse'='๐ŸŽ'; 'train'='๐Ÿš‚'; 'goat'='๐Ÿ'; 'burning'='๐Ÿ”ฅ'; 'school'='๐Ÿซ'; 'quail'='๐Ÿฆ'; 'baby'='๐Ÿ‘ถ'; 'lighthouse'='๐Ÿ—ผ';
  'sheep'='๐Ÿ‘'; 'snow'='โ˜ƒ๏ธ'; 'fishing'='๐ŸŽฃ'; 'doll'='๐Ÿช†'; 'sawing'='๐Ÿชš'; 'lamp'='๐Ÿช”'; 'seashore'='๐Ÿ–๏ธ'; 'blind'='๐Ÿฆฏ'; 'mill'='๐Ÿž๏ธ';
  'sunset'='๐ŸŒ…'; 'woman'='๐Ÿ‘ฉ'; 'wagon'='๐ŸŽ'; 'acorn'='๐ŸŒฐ'; 'drum'='๐Ÿฅ'; 'lake'='๐ŸŒŠ'; 'writing'='โœ๏ธ'; 'man'='๐Ÿ‘ด'; 'girl'='๐Ÿ‘ง'; 'boy'='๐Ÿ‘ฆ'; 'children'='๐Ÿ‘ง' }
if ($cfg.tales) {
  # Tale book (source/<file> from split-grimm.ps1): "= Title", "@ page", "% n" picture, "! legend", one paragraph per line.
  # Lesson = one part of a tale: L.tale / L.part / L.parts (BlockCraft unlocks a tale's place when its last part is done),
  # L.img = a Rackham picture (pics/grimm/rackham-NN.jpg), shown over the text in Listen.
  $tales = [ordered]@{}; $t = $null
  foreach ($ln in [IO.File]::ReadAllLines("$root\source\$($cfg.file)")) {
    if (-not $ln.Trim() -or $ln.StartsWith('#')) { continue }
    if ($ln -match '^= (.+)$') { $t = @{ pics = @(); paras = New-Object Collections.Generic.List[string] }; $tales[$Matches[1]] = $t; continue }
    if ($ln -match '^@ \d+$' -or $ln -match '^! ') { continue }
    if ($ln -match '^% (\d+)$') { $t.pics += [int]$Matches[1]; continue }
    # a line that starts in lowercase goes on from the one before (a paragraph that wrapped short, or "she said" after a song)
    if ($t.paras.Count -and $ln -cmatch '^[a-z]' -and $t.paras[$t.paras.Count - 1] -cnotmatch '^[A-Z][A-Z ]+$') { $t.paras[$t.paras.Count - 1] += ' ' + $ln.Trim() }
    else { $t.paras.Add($ln.Trim()) }
  }
  function TaleSentences($para) {
    # one line per sentence (a quote that holds several sentences is split too, so a line stays short enough to read
    # aloud); a sentence over 28 words is cut again at "; " so the mic check doesn't time out
    $p = ($para -replace '\s+', ' ').Trim()
    foreach ($s in [regex]::Split($p, '(?<!\b(?:Mr|Mrs|Dr|St))(?<=[.!?][''"]?)\s+(?=[''"]?[A-Z])')) {
      if (-not $s) { continue }
      Chop $s 0
    }
  }
  function Chop($s, $level) {
    # cut a long sentence at ; or :, then at ", and/but/then...", then at any comma; pieces of at least 10 words
    if (($s -split ' ').Count -le 28 -or $level -gt 2) { return $s }
    $rx = @('(?<=[;:]) ', '(?<=,) (?=(?:and|but|or|so|then|when|while|which|who|that|for|as|until|because)\b)', '(?<=,) ')[$level]
    $buf = ''; $outp = @()
    foreach ($piece in [regex]::Split($s, $rx)) {
      $nb = if ($buf) { "$buf $piece" } else { $piece }
      if ($buf -and ($nb -split ' ').Count -gt 28 -and ($buf -split ' ').Count -ge 10) { $outp += $buf; $buf = $piece } else { $buf = $nb }
    }
    if ($buf) { if ($outp.Count -and ($buf -split ' ').Count -lt 6) { $outp[$outp.Count - 1] += " $buf" } else { $outp += $buf } }
    foreach ($x in $outp) { Chop $x ($level + 1) }
  }
  $lessons = @(); $n = 0; $taleKeys = @($tales.Keys)   # taleNo = the tale's number in the whole collection (book order), shown as "Tale 39 of 211"
  foreach ($name in $cfg.pick) {
    $t = $tales[$name]; if (-not $t) { throw "Tale not found in $($cfg.file): $name" }
    # cut into parts: end a part at the first paragraph end after 200 words, or at a sentence end after 330 words;
    # a sub-heading ("SECOND STORY") always starts a new part
    $parts = @(); $cur = @(); $wc = 0
    foreach ($para in $t.paras) {
      if ($para -cmatch '^[A-Z][A-Z ]+$') {
        if ($cur.Count) { if ($wc -lt 80 -and $parts.Count) { $parts[$parts.Count - 1] += $cur } else { $parts += ,$cur } }
        $cur = @(); $wc = 0; continue
      }
      foreach ($s in (TaleSentences $para)) {
        $cur += $s; $wc += ($s -split ' ').Count
        if ($wc -ge 330) { $parts += ,$cur; $cur = @(); $wc = 0 }
      }
      if ($wc -ge 200) { $parts += ,$cur; $cur = @(); $wc = 0 }
    }
    if ($cur.Count) { if ($wc -lt 80 -and $parts.Count) { $parts[$parts.Count - 1] += $cur } else { $parts += ,$cur } }   # a tiny last piece joins the part before
    $short = if ($cfg.short[$name]) { $cfg.short[$name] } else { $name }
    # spread the tale's pictures over its parts (picture 1 on part 1)
    $imgAt = @{}; for ($k = 0; $k -lt $t.pics.Count; $k++) { $imgAt[[int][math]::Floor($k * $parts.Count / $t.pics.Count)] = 'pics/grimm/rackham-{0:D2}.jpg' -f $t.pics[$k] }
    for ($i = 0; $i -lt $parts.Count; $i++) {
      $n++
      $o = [ordered]@{ n = $n; pic = $cfg.emoji[$name]; picText = ''; words = @(); letters = @(); lines = @($parts[$i])
                       title = $(if ($parts.Count -gt 1) { "$short, part $($i + 1) of $($parts.Count)" } else { $short }); tale = $name; taleNo = [array]::IndexOf($taleKeys, $name) + 1; part = $i + 1; parts = $parts.Count }
      if ($imgAt.ContainsKey($i)) { $img = $imgAt[$i] } elseif ($i -eq 0) { $img = $null }
      if ($img) { $o.img = $img }   # a part without its own picture keeps the tale's last one
      if ($cfg.flag -and $cfg.flag[$name]) { $o.flag = $cfg.flag[$name] }   # grown-ups decide on the home screen whether a flagged tale shows
      $lessons += $o
    }
  }
  # New words = words not met in the McGuffey books or earlier parts, up to 10 per part (same rule as the prose Readers)
  $seen = New-Object 'System.Collections.Generic.HashSet[string]' ([StringComparer]::OrdinalIgnoreCase)
  $wordRx = "[A-Za-z]+(?:'[A-Za-z]+)?"
  foreach ($prev in $cfg.after) {
    $pj = Get-Content "$root\public\books\$prev.json" -Raw -Encoding UTF8 | ConvertFrom-Json
    foreach ($PL in $pj.lessons) { foreach ($s in @($PL.lines) + @($PL.words) + @($PL.script)) { foreach ($m in [regex]::Matches("$s", $wordRx)) { [void]$seen.Add($m.Value) } } }
  }
  foreach ($o in $lessons) {
    $text = $o.lines -join ' '; $new = @()
    foreach ($m in [regex]::Matches($text, $wordRx)) {
      $w = $m.Value
      if ($w.Length -lt 2 -or -not $seen.Add($w)) { continue }
      if (-not ($text -cmatch "[a-z]\s+$([regex]::Escape($w))\b") -or ($text -cmatch "\b$([regex]::Escape($w.ToLower()))\b")) { $w = $w.ToLower() }
      $new += $w
    }
    $o.words = @($new | Select-Object -First 10)
  }
  # copy the pictures these lessons use from source/grimm/pics (split-grimm.ps1) into public/pics/grimm
  New-Item -ItemType Directory -Force "$root\public\pics\grimm" | Out-Null
  foreach ($u in ($lessons | Where-Object { $_.img } | ForEach-Object { $_.img } | Sort-Object -Unique)) { Copy-Item "$root\source\grimm\pics\$(Split-Path $u -Leaf)" "$root\public\$u" -Force }
  $out = [ordered]@{ title = $cfg.title; sub = $cfg.sub; color = $cfg.color; source = $cfg.source; taleCount = $taleKeys.Count; lessons = $lessons }
  [IO.File]::WriteAllText("$root\public\books\$Book.json", ($out | ConvertTo-Json -Depth 6), (New-Object Text.UTF8Encoding $false))
  "$($lessons.Count) lessons, $(($lessons | ForEach-Object { $_.lines.Count } | Measure-Object -Sum).Sum) lines"
  $lessons | ForEach-Object { "{0,3} {1} {2,-40} lines={3,2} words={4,3} max={5,2} {6} w[{7}]" -f $_.n, $_.pic, $_.title, $_.lines.Count, (($_.lines -join ' ') -split ' ').Count, (($_.lines | ForEach-Object { ($_ -split ' ').Count }) | Measure-Object -Maximum).Maximum, $_.img, ($_.words -join ' ') }
  return
}
if ($cfg.hand) {
  # Hand-corrected book (source/<file>): "= n" starts a lesson, "words:" is its spelling list, "?" lines are notes, "#" comments
  $lessons = @(); $o = $null
  foreach ($ln in [IO.File]::ReadAllLines("$root\source\$($cfg.file)")) {
    $l = $ln.Trim()
    if (-not $l -or $l.StartsWith('#')) { continue }
    if ($l -match '^=\s*(\d+)') { if ($o) { $lessons += $o }; $o = [ordered]@{ n = [int]$Matches[1]; pic = '๐Ÿ“–'; picText = ''; words = @(); letters = @(); lines = @() }; continue }
    if ($l -match '^words:\s*(.*)$') { $o.words = @($Matches[1] -split '\s+' | Where-Object { $_ }); continue }
    if ($l.StartsWith('?')) { $o.note = $l.TrimStart('?', ' '); continue }
    $o.lines += $l
  }
  if ($o) { $lessons += $o }
  foreach ($o in $lessons) {
    if (-not $o.words.Count) {   # no list printed: spell the lesson's own words
      $w = @(); foreach ($m in [regex]::Matches(($o.lines -join ' '), "[A-Za-z]+(?:'[A-Za-z]+)?")) { $x = if ($m.Value -ceq 'I') { 'I' } else { $m.Value.ToLower() }; if ($w -notcontains $x) { $w += $x } }
      $o.words = @($w | Select-Object -First 12)
    }
    $txt0 = $o.lines -join ' '
    foreach ($key in $pics.Keys) { if ($txt0 -match "(?i)\b$key(?:s|es)?\b") { $o.pic = $pics[$key]; break } }
  }
  $out = [ordered]@{ title = $cfg.title; sub = $cfg.sub; color = $cfg.color; spell = $true; source = $cfg.source; lessons = $lessons }
  [IO.File]::WriteAllText("$root\public\books\$Book.json", ($out | ConvertTo-Json -Depth 6), (New-Object Text.UTF8Encoding $false))
  "$($lessons.Count) lessons"
  $lessons | ForEach-Object { "{0,2} {1} w[{2}] lines={3} {4}" -f $_.n, $_.pic, ($_.words -join ' '), $_.lines.Count, $(if ($_.note) { '? ' + $_.note } else { '' }) }
  return
}
if (-not (Test-Path "$root\source\$($cfg.file)")) {
  New-Item -ItemType Directory -Force "$root\source" | Out-Null
  Invoke-WebRequest "https://www.gutenberg.org/cache/epub/$($cfg.gutenberg)/pg$($cfg.gutenberg).txt" -OutFile "$root\source\$($cfg.file)" -UseBasicParsing
}
$txt = [IO.File]::ReadAllText("$root\source\$($cfg.file)") -replace "`r", ''
$headRx = '(?m)^(?:Lesson 1|LESSON [IVXLC]+\.{0,2}(?:\s*-*\s*REVIEW\.?)?)\s*$'   # Third Reader has one "LESSON XXX.."
if ($cfg.headRx) { $headRx = $cfg.headRx }
$body = if ($cfg.start) { $txt.Substring($txt.LastIndexOf($cfg.start)) } else { $txt.Substring([regex]::Match($txt, $headRx).Index) }
$body = $body.Substring(0, $body.IndexOf($cfg.end))
$body = $body -replace '(?m)^SLATE WORK\.?\s*$', ''
if ($cfg.prose) {
  # printed page headers ("18  ECLECTIC SERIES.") and page numbers, with the blank lines around them, so sentences join across pages
  $body = [regex]::Replace($body, "\n[ \t]*\n?[ \t]*\d*[ \t]*(?:$($cfg.pageRx))\.?[ \t]*\d*[ \t]*\n(?:[ \t]*\n)*", "`n")
  $body = $body -replace '(?m)^[ \t]*\(\d+\)[ \t]*\n', '' -replace '(?m)^[ \t]*\d+[,.]?(?:[ \t]*\d+[,.]?)*[ \t]*\n', ''
  $body = $body -creplace "(?m)^[ \t]*\d*[ \t]*(?:$($cfg.pageRx))[.,]?[ \t]*\d*[ \t]*\n", ''           # leftover headers ("62  ECLECTIC SERIES,")
  $body = $body -creplace "(\w) n't\b", '$1n''t' -creplace "'T is\b", "'Tis"                    # old spelling: "do n't" -> "don't"
}
$heads = [regex]::Matches($body, $headRx)
# the text of each lesson runs from the end of its heading to the next heading (Regex.Split would also return captured groups)
$parts = @($body.Substring(0, $heads[0].Index))
for ($i = 0; $i -lt $heads.Count; $i++) { $s = $heads[$i].Index + $heads[$i].Length; $e = if ($i + 1 -lt $heads.Count) { $heads[$i + 1].Index } else { $body.Length }; $parts += $body.Substring($s, $e - $s) }
$sounds = 'th','sh','ch','ng','ew','oy','ow','wh','ou','oo','sk','qu','oi','gh','ck'
$romanVal = @{ I=1; V=5; X=10; L=50; C=100 }
# scanned "LVll." = LVII, so a lowercase l counts as I
function Roman($r) { if ($r -match '^\d+$') { return [int]$r }; $r = $r -creplace 'l', 'I'; $t = 0; for ($i = 0; $i -lt $r.Length; $i++) { $v = $romanVal["$($r[$i])"]; if ($i + 1 -lt $r.Length -and $romanVal["$($r[$i+1])"] -gt $v) { $t -= $v } else { $t += $v } }; $t }
function Sentences($para) {
  # split a paragraph into kid-sized sentences; keep quotes and "--" asides with their sentence
  $p = (($para -replace '\s+', ' ').Trim()) -creplace '^(?:\d+|I)\.\s+(?=["A-Z])', ''
  $out = [regex]::Split($p, '(?<!\b(?:Mr|Mrs|Dr|St)\.)(?<=[.!?]"?)\s+(?=["A-Z])') | Where-Object { $_ }
  # re-join pieces that split inside a quotation
  $merged = @(); $buf = ''
  foreach ($s in $out) { $buf = if ($buf) { "$buf $s" } else { $s }; if ((($buf -split '"').Count - 1) % 2 -eq 0) { $merged += $buf; $buf = '' } }
  if ($buf) { $merged += $buf }
  $merged | ForEach-Object { $s = $_.Trim(); if ($s -match '[A-Za-z]$') { $s += '.' }; $s }
}
# vocabulary words carry accent marks and syllable breaks in the later lessons: cun'ning, be cause', did n't
function IsPoem($para) {
  $ls = @($para.Trim() -split '\n' | Where-Object { $_.Trim() })
  # poem lines are short and each starts with a capital; wrapped prose goes on in lowercase
  if ($para -match '\n\s+\S') { return $true }
  if ($ls.Count -lt 2 -or ($ls | Measure-Object -Property Length -Maximum).Maximum -gt 55) { return $false }
  $low = @($ls | Where-Object { $_.Trim() -cnotmatch '^["''\u2018\u201c(]{0,2}[A-Z]' }).Count
  ($low -eq 0) -or ($ls.Count -ge 4 -and $low -le 1)
}
function CleanWord($t) {
  $t = $t -replace '\s+', ''
  if ($t -match "(n't|'s|'ll|'ve|'re|'d|'m)$" -or $t -match "^'tis$") { return ($t -replace "'(?=.*')", '') }   # keep a real contraction's apostrophe
  $keep = $t.TrimEnd("'")
  if ($keep -match "^(o'clock|o'er|ne'er|e'er|e'en)$") { return $keep }   # old poetic words keep their apostrophe
  $t -replace "'", ''
}
function VocabTokens($ln) {
  $ln = $ln -replace '\s*\([^)]*\)', ''                                         # pronunciation notes: (wuns), (a gen'), (as f)
  $cols = if ($ln -match '\S\s{2,}\S') { $ln.Trim() -split '\s{2,}' } else { $ln.Trim() -split '\s+' }
  foreach ($c in $cols) {
    if (-not $c) { continue }
    if ($c -match '\s') {
      if ($c -match "'") { CleanWord $c }                                         # syllables of one word: be cause'
      elseif ($c -match '^(a|an|the)\s') { }                                      # phrase like "a black hen": not a new word
      else { $c -split '\s+' | ForEach-Object { CleanWord $_ } }                  # two words in one column: night owl
    } else { CleanWord $c }
  }
}
$nums = @()
if ($cfg.headRx) {
  # A real lesson heading has a page number ("(74)") or is the next number in order. That skips a lesson's own
  # numbered parts ("II. SUMMER.") and survives misprinted numerals ("XVV.", a second "LXX."): lessons are numbered in order.
  $keep = @(); $prev = 0
  # up to 2 lessons may be missing between two headings; a heading with a page number but a misprinted numeral is the next lesson
  foreach ($m in $heads) {
    $v = Roman $m.Groups[1].Value
    if ($v -ge $prev + 1 -and $v -le $prev + 3) { $keep += $m; $prev = $v; $nums += $v }
    # a misprinted numeral is still near its place (XVV for XXV); a lesson's own small parts ("III. A GOOD NAME. (95)" inside lesson 12) are not
    elseif ($m.Value -match '\(\d+\)\s*$' -and $v -ge $prev - 5) { $keep += $m; $prev++; $nums += $prev }
  }
  $heads = $keep
  $parts = @($body.Substring(0, $heads[0].Index))
  for ($i = 0; $i -lt $heads.Count; $i++) { $s = $heads[$i].Index + $heads[$i].Length; $e = if ($i + 1 -lt $heads.Count) { $heads[$i + 1].Index } else { $body.Length }; $parts += $body.Substring($s, $e - $s) }
}
# authors from the table of contents: "87.  The Best Capital      Louisa M. Alcott     245"
$tocAuthors = @{}
# (page column optional: the Fifth Reader's contents have none); the first entry for a number wins, which is the contents page
$tocText = $txt.Substring(0, $txt.LastIndexOf($(if ($cfg.start) { $cfg.start } else { 'x' })) + 1)
if ($cfg.tocEnd) { $ci = $tocText.IndexOf($(if ($cfg.tocStart) { $cfg.tocStart } else { 'CONTENTS' })); $tocText = $tocText.Substring($ci, $tocText.IndexOf($cfg.tocEnd, $ci) - $ci) }   # only the contents page, not the chapters on reading aloud
foreach ($m in [regex]::Matches($tocText, '(?m)^\s*(\d+)\.\s+(\S.*?\S)\s{2,}(\S.*?\S)(?:\s{2,}(\d+))?\s*$')) {
  $a = (($m.Groups[3].Value -split '\s{2,}')[-1] -replace '\.?\s*\d+$', '').TrimEnd('.')   # "Longfellow.290": page number stuck to the name
  if ($a -notmatch '^\d' -and -not $tocAuthors.ContainsKey([int]$m.Groups[1].Value)) { $tocAuthors[[int]$m.Groups[1].Value] = $a }   # skip a line that holds two entries
}
$lessons = @()
for ($k = 0; $k -lt $heads.Count; $k++) {
  $h = $heads[$k].Value.Trim()
  $n = if ($h -eq 'Lesson 1') { 1 } else { Roman(([regex]::Match($h, 'LESSON ([IVXLC]+)')).Groups[1].Value) }
  $headTitle = ''
  if ($cfg.headRx) {
    $hm = [regex]::Match($h, $cfg.headRx); $n = $nums[$k]
    $headTitle = (Get-Culture).TextInfo.ToTitleCase($hm.Groups[2].Value.Trim().TrimEnd('.').Trim('"', [char]0x201c, [char]0x201d).TrimEnd('.').ToLower()) -creplace "(\w) N't", '$1n''t' -replace '\(Concluded\.?\)', '(concluded)' -replace '\(Continued\.?\)', '(continued)'
  }
  $review = $h -match 'REVIEW'
  $block = $parts[$k + 1]
  $block = $block -replace '\[Footnote:[^\]]*\]', '' -replace '(?m)^\s*(\d+|[IVX]+)\.\s*$', ''
  # a title line glued to its poem ("ALICE'S SUPPER." then the verses) gets its own paragraph
  $block = $block -creplace '(?m)^([A-Z][A-Z .,''\u2019!-]{3,})$\n(?=\S)', "`$1`n`n"
  $author = ''; $defs = @(); $questions = @()
  # DEFINITIONS / EXERCISES / NOTES at the end of a lesson (Fourth Reader)
  $tm = [regex]::Match($block, '(?m)^[ \t]*(?:DEFINITIONS|EXERCISES|NOTES?)\b')
  if ($tm.Success) {
    $tail = $block.Substring($tm.Index); $block = $block.Substring(0, $tm.Index)
    foreach ($sec in [regex]::Matches($tail, '(?s)(DEFINITIONS|EXERCISES|NOTES?)\.?\s*-*(.*?)(?=(?:\n[ \t]*(?:DEFINITIONS|EXERCISES|NOTES?)\b)|\z)')) {
      $txt2 = ($sec.Groups[2].Value -replace '\s+', ' ').Trim()
      if ($sec.Groups[1].Value -eq 'DEFINITIONS') {
        $txt2 = $txt2 -replace '^In defining words, that meaning is given which is appropriate to them in the connection in which they are used\.\s*', ''
        foreach ($ln in (($txt2 -replace '(?:^|\s)\d+\.\s+', "`n") -split "`n")) {
          foreach ($entry in [regex]::Split($ln.Trim(), '(?<=\.)\s+(?=[A-Z][\w''/\-]*(?: [\w''/\-]+){0,2},\s)')) {
            $cm = [regex]::Match($entry, '^([A-Z][\w''/\-]*(?: [\w''/\-]+){0,2}),\s+(.+?)\.?\s*$')
            if ($cm.Success) {
              $w = $cm.Groups[1].Value -replace '[''/\-]', ''
              $d = ($cm.Groups[2].Value -replace '(?<=[a-z])-(?=[a-z])', '').Trim()
              $defs += ,@($w, $d)
            }
          }
        }
      } elseif ($sec.Groups[1].Value -eq 'EXERCISES') {
        $questions += @([regex]::Split($txt2, '(?<=\?)\s+') | ForEach-Object { $_.Trim() } | Where-Object { $_ -match '\?$' })
      }
    }
  }
  if ($cfg.prose) {
    # the author's name under a poem: "John G. Whittier.", "Mrs. Follen."
    $am = [regex]::Match($block, '\n[ \t]*((?:Mrs?\.\s+)?(?:[A-Z]\.\s*|[A-Z][a-z]+\s+){0,3}[A-Z][a-z]+\.)\s*$')
    if ($am.Success) { $author = $am.Groups[1].Value.TrimEnd('.'); $block = $block.Substring(0, $am.Index) }
    $block = $block -creplace '(?m)^(?=[ \t]*\d+\.\s+\S)', "`n"                                   # each numbered paragraph is its own paragraph
    foreach ($sp in ([regex]::Matches($block, '(?m)^([A-Z][a-z]+)\.\s+(?=["A-Z])') | Group-Object { $_.Groups[1].Value } | Where-Object { $_.Count -ge 2 -and $_.Name -notmatch '^(Mr|Mrs|Dr|St)$' })) {
      $block = $block -creplace "(?m)^$($sp.Name)\.\s+", "`n$($sp.Name): "                       # a play: "Rose. See how..." -> "Rose: See how..."
    }
  }
  # pull out illustrations (may span lines); script exercises become the cursive copy work
  $script = @(); $picText = ''
  foreach ($m in [regex]::Matches($block, '\[Illustration:([^\]]*)\]')) {
    $c = $m.Groups[1].Value
    if ($c -match '^\s*Script [Ee]xercise:') {
      $c = $c -replace '^\s*Script [Ee]xercise:', ''
      $paras = [regex]::Split($c.Trim(), '\n\s*\n')
      foreach ($pp in $paras) {
        if (IsPoem $pp) { $script += ($pp -split '\n' | ForEach-Object { $_.Trim() } | Where-Object { $_ }) }   # poem: keep lines
        else { $script += Sentences $pp }
      }
    } elseif (-not $picText) { $picText = ($c -replace '\s+', ' ').Trim().TrimEnd('.') }
  }
  $block = [regex]::Replace($block, '\[Illustration:[^\]]*\]', "`n`n@@PIC@@`n`n")
  $paras = [regex]::Split($block.Trim(), '\n\s*\n') | ForEach-Object { $_.TrimEnd() } | Where-Object { $_.Trim() }
  $words = @(); $letters = @(); $lines = @(); $inText = $false; $first = $true; $title = ''; $about = ''
  foreach ($p0 in $paras) {
    if ($p0.Trim() -eq '@@PIC@@') { if ($words.Count -or $letters.Count) { $inText = $true }; continue }
    $p = $p0 -replace '\s*\([^)]*\)', ''
    $isVocab = -not $cfg.prose -and -not $inText -and (($p -replace '\b(Mr|Mrs|Dr|St)\.', '$1') -notmatch '[.!?;,"]') -and ($first -or $p -match '\S\s{2,}\S' -or $p -match '^\S+$')
    # phrase rows like "a rat    a cat" come after the picture, not before it
    if ($isVocab -and $words.Count -and $p -match '^\s*(a|the|an)\s\w+\s{3,}') { $isVocab = $false }
    if ($isVocab) {
      foreach ($ln in ($p0 -split '\n')) {
        foreach ($t in (VocabTokens $ln)) {
          if (-not $t) { continue }
          $isSound = ($sounds -contains $t) -or ($t.Length -eq 1 -and -not ($first -and ($t -ceq 'a' -or $t -cmatch '^[A-Z]$')) -and $t -cne 'I')
          if ($isSound) { if ($letters -notcontains $t) { $letters += $t } } elseif ($words -notcontains $t) { $words += $t }
        }
        $first = $false
      }
      continue
    }
    $inText = $true
    # a note about the author before the selection ("By Celia Thaxter, who was born...", "Hester Lynch Thrale. 1739--1821, ...")
    if ($cfg.headRx -and -not $lines.Count -and -not $about -and $p -match '\bborn\b|\d{4}\s*-{1,2}\s*\d{2,4}') {
      $ta = if ($tocAuthors.ContainsKey([int]$n)) { ($tocAuthors[[int]$n] -split '\s+')[-1] } else { '' }
      if ($p -match '^\s*By\s' -or ($ta -and $p -match "\b$([regex]::Escape($ta))\b")) { $about = ($p -replace '\s+', ' ').Trim(); continue }
    }
    if ($p.Trim() -cmatch '^[A-Z][A-Za-z'' ]{2,40}$' -and -not $lines.Count -and $p.Trim() -cmatch '^(?:(?:[A-Z][a-z'']*|a|an|and|the|of|in|on|at|to|for|with|by)\s?)+$' -and $p.Trim() -match '\s') { $title = $p.Trim(); continue }
    if ($p.Trim() -cmatch '^[A-Z][A-Z .,''\u2019!?-]+$' -and ($cfg.prose -or $p -notmatch '\?')) { $title = (Get-Culture).TextInfo.ToTitleCase($p.Trim().TrimEnd('.').ToLower()); continue }   # story title: THE WHITE KITTEN.
    if (IsPoem $p) { $lines += ($p -split '\n' | ForEach-Object { ($_.Trim()) -replace '^\d+\.\s+', '' } | Where-Object { $_ }) }          # poem
    elseif ($p -notmatch '[.!?;,"]' -and $p -match '\S\s{3,}\S') { $lines += ($p.Trim() -split '\s{3,}') }                 # phrase row
    else { $lines += Sentences $p }
  }
  if (-not $lines.Count) { $lines = $script }
  $pic = ''; foreach ($key in $pics.Keys) { if ($picText -match "(?i)$key") { $pic = $pics[$key]; break } }
  if ($cfg.pics.ContainsKey([int]$n)) { $pic = $cfg.pics[[int]$n] }
  if (-not $pic -and $cfg.prose) { foreach ($key in $pics.Keys) { if ("$title $(($lines | Select-Object -First 3) -join ' ')" -match "(?i)\b$key(?:s|es)?\b") { $pic = $pics[$key]; break } } }   # no picture notes: guess from the title
  if (-not $pic) { $pic = if ($review -or $cfg.prose) { '๐Ÿ“–' } else { '๐Ÿ–ผ๏ธ' } }
  $o = [ordered]@{ n = $n; pic = $pic; picText = $(if ($picText) { $picText } elseif ($review) { 'Review' } else { '' }); words = @($words); letters = @($letters); lines = @($lines) }
  if ($review) { $o.review = $true }
  if ($headTitle) { $title = $headTitle }   # the heading's title wins over part titles inside the lesson ("IV. WINTER.")
  if ($defs.Count) {
    # the book's own new words: shown in lowercase unless the lesson only ever writes them with a capital (names)
    $alltext = $lines -join ' '
    $o.defs = [ordered]@{}
    foreach ($dd in $defs) {
      $w = $dd[0]; if ($alltext -cmatch "\b$([regex]::Escape($w.ToLower()))\b" -or -not ($alltext -cmatch "\b$([regex]::Escape($w))\b")) { $w = $w.ToLower() }
      if (-not $o.defs.Contains($w)) { $o.defs[$w] = $dd[1] }
    }
    $o.words = @($o.defs.Keys | Select-Object -First 12)
  }
  if ($questions.Count) { $o.questions = @($questions) }
  if ($title) { $o.title = $title }
  if ($cfg.headRx -and $tocAuthors.ContainsKey([int]$n)) { $author = $tocAuthors[[int]$n] }   # the contents page knows best
  if ($author -match 'Reader|EXAMPLES') { $author = '' }
  if ($author) { $o.author = $author }
  if ($about) { $o.about = $about }
  if ($script.Count) { $o.script = @($script) }
  if (-not $lines.Count) { Write-Host "Lesson $n has no text in Gutenberg's copy ($title), skipped" -ForegroundColor Yellow; continue }
  $lessons += $o
}
if ($cfg.prose) {
  # New words = words not met in the earlier books or earlier lessons, in reading order, up to 10 per lesson
  $seen = New-Object 'System.Collections.Generic.HashSet[string]' ([StringComparer]::OrdinalIgnoreCase)
  $wordRx = "[A-Za-z]+(?:'[A-Za-z]+)?"
  foreach ($prev in $cfg.after) {
    $pj = Get-Content "$root\public\books\$prev.json" -Raw -Encoding UTF8 | ConvertFrom-Json
    foreach ($PL in $pj.lessons) { foreach ($s in @($PL.lines) + @($PL.words) + @($PL.script)) { foreach ($m in [regex]::Matches("$s", $wordRx)) { [void]$seen.Add($m.Value) } } }
  }
  foreach ($o in $lessons) {
    $text = (@($o.lines) + @($o.script)) -join ' '
    $new = @()
    foreach ($m in [regex]::Matches($text, $wordRx)) {
      $w = $m.Value
      if ($w.Length -lt 2 -or $w -match "^n'" -or -not $seen.Add($w)) { continue }
      # names keep their capital (capitalized in the middle of a line); other words are shown in lowercase
      if (-not ($text -cmatch "(?:[a-z]|\b(?:Mr|Mrs|Miss|Dr)\.)\s+$([regex]::Escape($w))\b") -or ($text -cmatch "\b$([regex]::Escape($w.ToLower()))\b")) { $w = $w.ToLower() }
      $new += $w
    }
    if (-not @($o.words).Count) { $o.words = @($new | Select-Object -First 10) }   # the book's own word list wins when it has one
  }
}
# Last clean-up of every line: printed page headers that ended up inside a sentence ("... ECLECTIC SERIES. ..."),
# footnote/section marks (#, *, [ ]), and scanned digits ("l0" = 10, "I1" = 11)
function CleanLine($s) {
  $s = $s -creplace '\d*\s*\b(?:ECLECTIC (?:SERIES|READER)|(?:FIRST|SECOND|THIRD|FOURTH|FIFTH|SIXTH) READER)\b[.,]?\s*\d*', ' ' -replace '[#*\[\]]', ''
  $s = $s -creplace '\bI1\b', 'I' -creplace '(?<=\d)l|l(?=\d)', '1' -creplace '^\d+\s+(?=[a-z])', '' -creplace '(?<=[a-z]{3})\d\b', ''   # footnote number on a word ("orthography1"); "I1 will" = I; "l0" = 10; a page number before the text
  ($s -replace '\s{2,}', ' ').Trim()
}
foreach ($o in $lessons) {
  $o.lines = @($o.lines | ForEach-Object { CleanLine $_ } | Where-Object { $_ -match '[A-Za-z]' })
  if ($o.script) { $o.script = @($o.script | ForEach-Object { CleanLine $_ } | Where-Object { $_ -match '[A-Za-z]' }) }
}
$out = [ordered]@{ title = $cfg.title; sub = $cfg.sub; color = $cfg.color; source = "Project Gutenberg #$($cfg.gutenberg) (public domain)"; lessons = $lessons }
$json = $out | ConvertTo-Json -Depth 6
New-Item -ItemType Directory -Force "$root\public\books" | Out-Null
[IO.File]::WriteAllText("$root\public\books\$Book.json", $json, (New-Object Text.UTF8Encoding $false))
"$($lessons.Count) lessons"
$lessons | ForEach-Object { "{0,2} {1} w[{2}] l[{3}] lines={4} script={5} | {6}" -f $_.n, $_.pic, ($_.words -join ' '), ($_.letters -join ' '), $_.lines.Count, $(if ($_.script) { $_.script.Count } else { 0 }), $_.lines[0] }
EOF

make-audio.ps1: records everything; for tale books the spoken lesson title is the part name.

cat > /root/abcbooks-rebuild/make-audio.ps1 <<'EOF'
# Records every spoken text of a book with the PC's ETI-Eloquence (Reed) at each speed, then
# builds public/audio/<book>.json (text -> clip id + word start times). WAVs land in tools/out/<book>/s<speed>/.
# Usage: powershell -ExecutionPolicy Bypass -File ABCBooks\tools\make-audio.ps1 [-Book primer1881]
# Then: ABCBooks\tools\push-audio.ps1 converts to MP3 on CT 306.
param([string]$Book = 'primer1881', [int[]]$Speeds = @(60, 75))
$root = Split-Path -Parent (Split-Path -Parent $MyInvocation.MyCommand.Path)
$data = Get-Content "$root\public\books\$Book.json" -Raw -Encoding UTF8 | ConvertFrom-Json
$kids = 'Layla', 'Lavon', 'Lilly'

# key = what the app asks for; value = what Eloquence should say
$say = New-Object System.Collections.Specialized.OrderedDictionary ([StringComparer]::Ordinal)   # case matters: "a cat" and "A cat" are different lines
function Add($key, $spoken) { if ($key -and -not $say.Contains($key)) { $say[$key] = $(if ($spoken) { $spoken } else { $key }) } }
# letter cards say the phonics sound (public/phonics.json, Eloquence phonetic code), not the letter name
$phonics = Get-Content "$root\public\phonics.json" -Raw -Encoding UTF8 | ConvertFrom-Json
function LetterName($t) {
  $p = $phonics.PSObject.Properties[$t.ToLower()]
  if ($p) { return ('`[.1' + $p.Value[0] + ']') }   # single quotes: keep Eloquence's backquote
  (($t.ToCharArray() | ForEach-Object { "$_".ToUpper() }) -join ', ') + '.'
}
foreach ($p in $phonics.PSObject.Properties) { if ($p.Name -notlike '_*') { Add "letter:$($p.Name)" (LetterName $p.Name); Add "example:$($p.Name)" $p.Value[1] } }   # for phonics.html
foreach ($p in 'Tap each card to hear it.', 'Good! Now play the game.', 'Yes!', 'Good try!', 'Listen to the red words, then try again.',
               'I did not hear you. Try again!', 'Start at the green dot!', 'Follow the arrow all the way.', 'Great job!', 'Write it on the board first!') { Add $p }
foreach ($k in $kids) { Add "Great job, $k!" }
# spoken instructions shared with the app (public/prompts.json)
$prompts = Get-Content "$root\public\prompts.json" -Raw -Encoding UTF8 | ConvertFrom-Json
foreach ($pr in $prompts.PSObject.Properties) {
  if ($pr.Value -like '*{kid}*') { foreach ($k in $kids) { Add ($pr.Value -replace '\{kid\}', $k) } } else { Add $pr.Value }
}
foreach ($L in $data.lessons) { Add "lesson:$($L.n)" $(if ($L.tale) { "$($L.title)." } elseif ($L.review) { "Review. Lesson $($L.n)." } else { "Lesson $($L.n)." }) }   # tale books: "Rapunzel, part 2 of 5."
foreach ($L in $data.lessons) {
  foreach ($t in $L.letters) { Add "letter:$t" (LetterName $t) }
  foreach ($w in $L.words) { Add $w; Add "Find $w" "Find the word, $w." }
  $copy = @()
  if ($L.letters.Count) { $copy += ($L.letters -join ' '); Add ($L.letters -join ' ') ((($L.letters | ForEach-Object { LetterName $_ }) -join ', ')) }
  if ($L.words.Count) { $copy += ($L.words -join ' ') }
  $wl = @($L.words); for ($i = 0; $i -lt $wl.Count; $i += 6) { $copy += ($wl[$i..([Math]::Min($i + 5, $wl.Count - 1))] -join ' ') }   # tracing pages, 6 words each (app.js WORDS_PER_PAGE)
  foreach ($ln in $L.lines) {
    Add $ln
    foreach ($w in ($ln -split '\s+')) { $c = $w -replace '[^A-Za-z'']', ''; if ($c) { Add $c } }   # single words for tap-to-hear + retries
    if (($ln -split ' ').Count -gt 2) { Add "Write: $ln" }
  }
  foreach ($ln in $L.script) { Add $ln }
  if ($L.defs) { foreach ($d in $L.defs.PSObject.Properties) { Add "def:$($d.Name)" "$($d.Name). $($d.Value)." } }   # word + its meaning (Fourth Reader)
  foreach ($q in @($L.questions)) { if ($q) { Add $q } }
  if ($data.spell) {   # Spell & Read: each word spelled with letter names, then said: "I, S. is."
    foreach ($m in [regex]::Matches(($L.lines -join ' '), "[A-Za-z]+(?:'[A-Za-z]+)?")) {
      $w = if ($m.Value -ceq 'I') { 'I' } else { $m.Value.ToLower() }
      Add "spell:$w" ((($w.ToCharArray() | Where-Object { $_ -ne [char]39 } | ForEach-Object { "$_".ToUpper() }) -join ', ') + ". $w.")
    }
  }                                                    # Talk about it questions
  foreach ($c in $copy) { Add $c }
}
"$($say.Count) clips per speed"

$sha = [Security.Cryptography.SHA1]::Create()
function Id($s) { (($sha.ComputeHash([Text.Encoding]::UTF8.GetBytes($s)) | Select-Object -First 6 | ForEach-Object { $_.ToString('x2') }) -join '') }
$items = New-Object System.Collections.Specialized.OrderedDictionary ([StringComparer]::Ordinal)
$ps32 = 'C:\Windows\SysWOW64\WindowsPowerShell\v1.0\powershell.exe'
foreach ($sp in $Speeds) {
  $dir = "$root\tools\out\$Book\s$sp"; New-Item -ItemType Directory -Force $dir | Out-Null
  $jobs = @()
  foreach ($k in $say.Keys) {
    $id = Id $say[$k]
    if (-not $items.Contains($k)) { $items[$k] = [ordered]@{ id = $id } }
    if (-not (Test-Path "$dir\$id.wav.json")) { $jobs += [ordered]@{ text = $say[$k]; out = "$dir\$id.wav" } }
  }
  "speed $sp : $($jobs.Count) to record"
  if ($jobs.Count) {
    $jf = "$dir\jobs.json"; ConvertTo-Json @($jobs) | Set-Content -Encoding utf8 $jf
    & $ps32 -NoProfile -ExecutionPolicy Bypass -File "$root\tools\eloq-render.ps1" -Jobs $jf -Speed $sp | Out-Null
  }
  foreach ($k in $say.Keys) {
    $j = Get-Content "$dir\$($items[$k].id).wav.json" -Raw | ConvertFrom-Json
    $items[$k]["t$sp"] = @($j.words)
  }
}
$out = [ordered]@{ speeds = $Speeds; items = $items }
New-Item -ItemType Directory -Force "$root\public\audio" | Out-Null
[IO.File]::WriteAllText("$root\public\audio\$Book.json", ($out | ConvertTo-Json -Depth 5 -Compress), (New-Object Text.UTF8Encoding $false))
"manifest: $root\public\audio\$Book.json"
EOF

app.js: the app, with the Fairy Tales page (one book per tale, “Tale 39 of 211”) and pictures in Listen.

cat > /root/abcbooks-rebuild/app.js <<'EOF'
// ABC Books: gamified McGuffey lessons. All progress is saved per kid in localStorage ('abcbooks').
const BOOKS = {};
const App = (() => {
  const $ = id => document.getElementById(id);
  // Anonymous funnel counts (/account/stats.js, abcbooks.fyi only): never names, only book/lesson/step.
  const track = (url, data) => { try { window.abcStats && window.abcStats.step(url, data); } catch (e) {} };
  // Readers are added by a grown-up on the home screen. Devices that used ABC Books before that existed
  // keep the first family's three readers.
  const LEGACY_KIDS = ['Layla', 'Lavon', 'Lilly'];
  let P = {};   // spoken instructions (prompts.json, also recorded by tools/make-audio.ps1)
  const SHELF = [
    { id: 'primer1881' },
    { id: 'first1879' },
    { id: 'second1879' },
    { id: 'third1879' },
    { id: 'fourth1879' },
    { id: 'fifth1879' },
    { id: 'sixth1879' },
    { id: 'spell1867' },
    { id: 'grimm1884', tales: true },   // Grimm's Fairy Tales (Hunt 1884): one lesson = one part of a tale, L.tale/L.part/L.parts, Rackham pictures in L.img.
                                        // tales: shown as one book per tale on the Fairy Tales shelf (progress stays under this book id)
    { id: 'silabario1861' }   // Spanish (Puerto Rico, 1861): book.lang 'es', words shown with syllable hyphens
  ];
  const STEPS = [
    { id: 'words', name: 'New words', icon: 'A' },
    { id: 'spell', name: 'Spell it', icon: '๐Ÿ”ค' },
    { id: 'listen', name: 'Listen', icon: '๐Ÿ‘‚' },
    { id: 'read', name: 'Your turn to read', icon: '๐ŸŽค' },
    { id: 'talk', name: 'Talk about it', icon: '๐Ÿ’ฌ' },
    { id: 'print', name: 'Trace: print', icon: 'a' },
    { id: 'script', name: 'Trace: cursive', icon: '๐’ถ' },
    { id: 'board', name: 'Blackboard', icon: 'โœŽ' }
  ];

  // ---------- storage ----------
  let S = load();
  function load() {
    let s = null; try { s = JSON.parse(localStorage.getItem('abcbooks')); } catch (e) {}
    s = s || { kid: null, progress: {}, boards: {} };
    if (!s.speed) s.speed = 60;
    if (!Array.isArray(s.readers)) {
      s.readers = (s.kid || Object.keys(s.progress).length) ? LEGACY_KIDS.slice() : [];
      for (const n of Object.keys(s.progress)) if (!s.readers.includes(n)) s.readers.push(n);
    }
    if (!s.kid) { try { const c = JSON.parse(localStorage.getItem('blockcraft_cfg')); if (c && s.readers.includes(c.name)) s.kid = c.name; } catch (e) {} }
    return s;
  }
  function save() { try { localStorage.setItem('abcbooks', JSON.stringify(S)); } catch (e) { trimBoards(); try { localStorage.setItem('abcbooks', JSON.stringify(S)); } catch (e2) {} } }
  function trimBoards() { for (const k in S.boards) S.boards[k] = S.boards[k].slice(-12); }
  const prog = (book) => ((S.progress[S.kid] = S.progress[S.kid] || {})[book] = (S.progress[S.kid] || {})[book] || {});

  // ---------- sound + voice ----------
  let AC;
  function beep(good) {
    try {
      AC = AC || new (window.AudioContext || window.webkitAudioContext)();
      const o = AC.createOscillator(), g = AC.createGain(), t = AC.currentTime;
      o.type = 'triangle'; o.connect(g); g.connect(AC.destination);
      const notes = good ? [523, 659, 784] : [220, 180];
      notes.forEach((f, i) => o.frequency.setValueAtTime(f, t + i * 0.1));
      g.gain.setValueAtTime(0.25, t); g.gain.exponentialRampToValueAtTime(0.001, t + notes.length * 0.1 + 0.2);
      o.start(t); o.stop(t + notes.length * 0.1 + 0.25);
    } catch (e) {}
  }
  const hasTTS = 'speechSynthesis' in window;
  let voice = null;
  function pickVoice() {
    if (!hasTTS) return;
    const v = speechSynthesis.getVoices().filter(v => /^en/i.test(v.lang));
    voice = v.find(v => /female|samantha|zira|aria|jenny|google us/i.test(v.name)) || v[0] || null;
  }
  if (hasTTS) { pickVoice(); speechSynthesis.onvoiceschanged = pickVoice; }
  // Recorded Eloquence clips (tools/make-audio.ps1): audio/<book>.json maps text -> clip id + word start times per speed.
  const AUDIO = {};
  const clip = new Audio(); clip.preload = 'auto';
  let clipDone = null, clipRaf = 0, unlocked = false, seqTok = 0, playTok = 0;
  function stopAll() { seqTok++; stopSpeech(); }   // stop anything playing, including a word-by-word sequence

  // ---------- sound it out (phonics chunks, recorded by tools/make-soundouts.ps1) ----------
  // The word big on screen, letter teams (st, sh, igh, ing...) in red, a silent e grey; Eloquence says the word, then each
  // chunk's phonics sound while the highlight moves slowly from chunk to chunk.
  const SO = {};
  const loadSO = b => (b in SO) ? SO[b] : (SO[b] = fetch(`audio/${b}.soundout.json`).then(r => r.ok ? r.json() : null).catch(() => null));
  // a word as the recordings know it: letters (any language) and apostrophes; hyphens kept for the Spanish syllable books
  const isEs = () => !!(book && book.lang === 'es');
  const clean = w => w.replace(isEs() ? /[^\p{L}'-]/gu : /[^A-Za-z']/g, '').replace(/^-+|-+$/g, '');
  // Spanish (the 1861 Silabario): the word, then one syllable at a time, like the book teaches (ca... sa... casa)
  async function soundOutEs(word) {
    const w = clean(word), key = w.replace(/-/g, '').toLowerCase(); if (!key) return;
    const parts = (book.syl && book.syl[key]) || w.toLowerCase().split('-');
    stopAll();
    const ov = el('div', 'so'), row = el('div', 'sow'); ov.appendChild(row);
    const spans = parts.map(t => { const s = el('span', '', esc(t)); row.appendChild(s); return s; });
    ov.appendChild(el('div', 'hint', 'Listen: one syllable at a time, then the word. Tap to close.'));
    document.body.appendChild(ov);
    const my = seqTok; let stop = false; ov.onclick = () => { stop = true; stopAll(); };
    try {
      for (let i = 0; i < parts.length && !stop && my === seqTok; i++) {
        spans.forEach((s, k) => s.classList.toggle('on', k === i));
        const c = clipFor('syl:' + parts[i]); if (c) await playClip(c); else await ttsSpeak(parts[i]);
        await new Promise(r => setTimeout(r, 350));
      }
      spans.forEach(s => s.classList.add('on'));
      if (!stop && my === seqTok) { const c = clipFor(w) || clipFor(key); if (c) await playClip(c); }
    } finally { setTimeout(() => ov.remove(), 400); }
  }
  // ---------- instructions in the Spanish book: English, then Spanish (or one of them; a grown-up's switch, S.ins) ----------
  // instructions-es.json maps the app's English text to Spanish; the Spanish clips are recorded as 'es:<English text>'.
  // Only for books with lang 'es': the English books never change.
  let ES = {};
  const insMode = () => isEs() ? (S.ins || 'both') : 'en';
  const fill = (t, v) => v ? t.replace(/\{(\w+)\}/g, (m, k) => (k in v ? v[k] : m)) : t;
  function hint(key, v) {
    const en = fill(key, v), es = ES[key] && fill(ES[key], v), m = insMode(), h = $('hint');
    if (m === 'en' || !es) h.textContent = en;
    else if (m === 'es') h.textContent = es;
    else h.innerHTML = esc(en) + '<br><span class="es">' + esc(es) + '</span>';
  }
  function toastI(key, ms) {
    const es = ES[key], m = insMode();
    if (m === 'en' || !es) return toast(key, ms);
    toast(m === 'es' ? es : key, ms);
    if (m === 'both') $('toast').innerHTML = esc(key) + '<br>' + esc(es);
  }
  const titleI = name => { const es = ES[name], m = insMode(); return m === 'en' || !es ? name : m === 'es' ? es : `${name} ยท ${es}`; };
  // say an instruction: English, a short pause, then Spanish; stops if anything else starts speaking meanwhile
  async function sayIns(key) {
    const m = insMode(), esKey = 'es:' + key;
    if (m === 'en' || !clipFor(esKey)) return speak(key);
    if (m === 'es') return speak(esKey);
    await speak(key);
    const t = seqTok; await new Promise(r => setTimeout(r, 250));
    if (t === seqTok) return speak(esKey);
  }
  async function soundOut(word) {
    if (isEs()) return soundOutEs(word);
    const w = word.replace(/[^A-Za-z']/g, '').toLowerCase(); if (!w) return;
    const m = await loadSO(bookId), e = m && m.words[w];
    if (!e) return speak(word.replace(/[^A-Za-z']/g, ''), null, 0.7);
    stopAll();
    const ov = el('div', 'so'), row = el('div', 'sow'); ov.appendChild(row);
    const spans = e.ch.map(([t, k]) => { const s = el('span', (t.length > 1 ? 'multi' : '') + (k === 'S' ? ' silent' : ''), t); row.appendChild(s); return s; });
    ov.appendChild(el('div', 'hint', 'Listen: the word, then each sound. Tap to close.'));
    ov.onclick = () => stopAll();
    document.body.appendChild(ov);
    const my = ++playTok;
    try {
      const u = await clipURL(`audio/so/s${m.speed}/${e.id}.mp3`);
      if (my !== playTok) return;
      await new Promise(res => {
        clipDone = res; clip.muted = false; clip.src = u;
        const tick = () => {
          const ms = clip.currentTime * 1000; let cur = -1;
          e.ch.forEach(([, , t], i) => { if (t >= 0 && ms >= t - 80) cur = i; });
          spans.forEach((s, i) => s.classList.toggle('on', i === cur));
          clipRaf = setTimeout(tick, 60);   // a timer, not animation frames: keeps stepping even on a busy tablet
        };
        clip.onended = clip.onerror = () => { clearTimeout(clipRaf); if (clipDone) { const d = clipDone; clipDone = null; d(); } };
        clip.play().then(tick).catch(() => clip.onended());
      });
    } catch (err) { } finally { setTimeout(() => ov.remove(), 500); }
  }
  // press and hold a word (about half a second) to sound it out; a quick tap still does what it did before
  function holdToSound(node, word) {
    let t = 0, held = false;
    node.addEventListener('pointerdown', () => { held = false; clearTimeout(t); t = setTimeout(() => { held = true; soundOut(word); }, 550); });
    ['pointerup', 'pointerleave', 'pointercancel'].forEach(ev => node.addEventListener(ev, () => clearTimeout(t)));
    node.addEventListener('click', e => { if (held) { e.stopImmediatePropagation(); e.preventDefault(); held = false; } }, true);
    node.addEventListener('contextmenu', e => e.preventDefault());
  }
  function stopSpeech() {
    cancelAnimationFrame(clipRaf); clearTimeout(clipRaf); clip.pause();
    if (clipDone) { const d = clipDone; clipDone = null; d(); }
    if (hasTTS) speechSynthesis.cancel();
  }
  // look in the open book's recordings first, then any other book's (the home screen has no book open yet)
  function clipFor(key) {
    for (const b of [bookId, ...Object.keys(AUDIO)]) {
      const m = AUDIO[b]; if (!m) continue;
      const c = m.items[key] || (!/\s/.test(key) && m.items[key.toLowerCase()]);
      if (c) return { ...c, book: b };
    }
  }
  const speedOf = b => AUDIO[b].speeds.includes(S.speed) ? S.speed : AUDIO[b].speeds[0];
  function playClip(c, onWord) {
    stopSpeech();
    const sp = speedOf(c.book), t = c['t' + sp] || [];
    const my = ++playTok;
    return new Promise(res => {
      clipDone = () => { onWord && onWord(-1); res(); };
      clipURL(`audio/${c.book}/s${sp}/${c.id}.mp3`).then(u => {
      if (my !== playTok) return;
      clip.muted = false; clip.src = u;
      const tick = () => {
        const ms = clip.currentTime * 1000 + 40; let i = 0;
        for (let k = 0; k < t.length - 1; k++) if (t[k] >= 0 && ms >= t[k]) i = k;
        onWord(i); clipRaf = requestAnimationFrame(tick);
      };
      clip.onended = clip.onerror = () => { cancelAnimationFrame(clipRaf); if (clipDone) { const d = clipDone; clipDone = null; d(); } };
      clip.play().then(() => { if (onWord) tick(); }).catch(() => clip.onended());
      }).catch(() => { if (my === playTok && clipDone) { const d = clipDone; clipDone = null; d(); } });
    });
  }
  // Clips are fetched whole and played from memory: works with the offline cache on every browser (Safari needs this).
  const blobs = new Map();
  function clipURL(url) {
    if (!blobs.has(url)) blobs.set(url, fetch(url).then(r => { if (!r.ok) throw new Error(r.status); return r.blob(); }).then(b => URL.createObjectURL(b)));
    const p = blobs.get(url); p.catch(() => blobs.delete(url)); return p;
  }
  // warm up a lesson's clips so the first tap answers right away
  function preload(L) {
    if (!AUDIO[bookId]) return;
    [...L.lines, ...L.words, ...L.letters.map(t => 'letter:' + t)].forEach(k => { const c = clipFor(k); if (c) clipURL(`audio/${c.book}/s${speedOf(c.book)}/${c.id}.mp3`).catch(() => {}); });
  }
  // Safari/iOS only allows audio that starts inside a tap: play a muted clip on the first tap to unlock it.
  window.addEventListener('pointerdown', () => {
    const c = clipFor('Yes!'); if (unlocked || !c) return; unlocked = true;
    const src = `audio/${c.book}/s${AUDIO[c.book].speeds[0]}/${c.id}.mp3`;
    if (!clip.src) { clip.muted = true; clip.src = src; clip.play().then(() => { if (clip.src.endsWith(src)) { clip.pause(); } clip.muted = false; }).catch(() => { clip.muted = false; }); }
  }, { passive: true });
  // speak(text, onWord(i)) -> Promise: recorded clip if there is one, else one clip per word, else the device voice.
  async function speak(text, onWord, rate) {
    seqTok++;
    const c = clipFor(text);
    if (c) return playClip(c, onWord);
    const parts = text.split(/[\s,]+/).map(clean).filter(Boolean);
    if (parts.length && parts.every(w => clipFor(w))) {
      const my = seqTok;
      for (let i = 0; i < parts.length && my === seqTok; i++) { await playClip(clipFor(parts[i]), onWord ? j => onWord(j < 0 ? -1 : i) : null); }
      return;
    }
    return ttsSpeak(text, onWord, rate);
  }
  // device voice fallback. Word highlight uses boundary events, or a timing guess when the device has none.
  function ttsSpeak(text, onWord, rate) {
    return new Promise(res => {
      const words = text.split(/\s+/);
      if (!hasTTS) { // no voice: still step through the words so the highlight works
        let i = 0; const t = setInterval(() => { onWord && onWord(i); if (++i > words.length) { clearInterval(t); res(); } }, 550); return;
      }
      speechSynthesis.cancel();
      const u = new SpeechSynthesisUtterance(text.replace(/;/g, ','));
      if (voice) u.voice = voice; u.rate = rate || 0.8; u.pitch = 1.05;
      let gotBoundary = false, guess;
      const starts = []; let p = 0; for (const w of words) { starts.push(p); p += w.length + 1; }
      u.onboundary = e => {
        if (e.name && e.name !== 'word') return; gotBoundary = true; clearInterval(guess);
        let i = starts.findIndex((s, k) => e.charIndex >= s && (k === starts.length - 1 || e.charIndex < starts[k + 1]));
        onWord && i >= 0 && onWord(i);
      };
      u.onstart = () => {
        if (!onWord) return; let i = 0; onWord(0);
        guess = setInterval(() => { if (gotBoundary) return clearInterval(guess); if (++i < words.length) onWord(i); }, 620 / (rate || 0.8) * 0.8);
      };
      u.onend = u.onerror = () => { clearInterval(guess); onWord && onWord(-1); res(); };
      speechSynthesis.speak(u);
    });
  }

  // ---------- speech recognition ----------
  // First choice: record the line and let our Vosk server (CT 307, api/recognize) check it. It only
  // listens for the line's words, so misreads are caught instead of auto-corrected. Fallback: the browser's own.
  const SR = window.SpeechRecognition || window.webkitSpeechRecognition;
  const GUM = !!(window.isSecureContext && navigator.mediaDevices && navigator.mediaDevices.getUserMedia);
  let useMic = GUM || !!SR;   // turned off for good if the browser blocks the mic (Amazon Kids browser says not-allowed)
  let useServer = GUM, lastUnknown = [], stopListening = () => {};
  const SOUNDS_LIKE = { a: ['uh', 'ah', 'the'], ann: ['an', 'anne', 'and'], nat: ['gnat', 'matt', 'nate'], rat: ['ratt'], cat: ['kat'], rab: ['rob', 'rabb'] };
  // the speech checker answers without syllable hyphens and (Spanish) treats m, b and v alike
  const norm = w => { const n = w.toLowerCase().replace(/[^\p{L}']/gu, ''); return isEs() ? n.replace(/[mv]/g, 'b') : n; };
  function same(a, b) { return a === b || (SOUNDS_LIKE[a] || []).includes(b); }
  // which expected words were heard, in order (LCS alignment)
  function matchWords(expected, heard) {
    const E = expected.map(norm), H = heard.map(norm).filter(Boolean);
    const m = E.length, n = H.length, d = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(0));
    for (let i = m - 1; i >= 0; i--) for (let j = n - 1; j >= 0; j--) d[i][j] = same(E[i], H[j]) ? d[i + 1][j + 1] + 1 : Math.max(d[i + 1][j], d[i][j + 1]);
    const ok = new Array(m).fill(false); let i = 0, j = 0;
    while (i < m && j < n) { if (same(E[i], H[j])) { ok[i] = true; i++; j++; } else if (d[i + 1][j] >= d[i][j + 1]) i++; else j++; }
    return ok;
  }
  async function listen(timeoutMs, line) {
    lastUnknown = [];
    if (useServer) {
      try { return await listenServer(timeoutMs, line); }
      catch (e) { useServer = false; if (!SR) { useMic = false; return []; } }   // server down: browser recognizer if any
    }
    return listenBrowser(timeoutMs);
  }
  // Records until the kid stops talking (1.3 s quiet), the time runs out, or the mic is tapped again.
  async function listenServer(timeoutMs, line) {
    let stream;
    try { stream = await navigator.mediaDevices.getUserMedia({ audio: { echoCancellation: true, noiseSuppression: true } }); }
    catch (e) { useMic = false; return []; }
    const ctx = new (window.AudioContext || window.webkitAudioContext)();
    try { await ctx.resume(); } catch (e) {}
    const src = ctx.createMediaStreamSource(stream), proc = ctx.createScriptProcessor(4096, 1, 1);
    const chunks = []; let spoke = false, quiet = 0; const t0 = performance.now();
    await new Promise(res => {
      let done = false; const fin = () => { if (!done) { done = true; res(); } };
      stopListening = fin;
      proc.onaudioprocess = e => {
        const d = e.inputBuffer.getChannelData(0); chunks.push(new Float32Array(d));
        let s = 0; for (let i = 0; i < d.length; i++) s += d[i] * d[i];
        if (Math.sqrt(s / d.length) > 0.015) { spoke = true; quiet = 0; } else if (spoke) quiet += d.length / ctx.sampleRate * 1000;
        if ((spoke && quiet > 1300) || performance.now() - t0 > timeoutMs) fin();
      };
      src.connect(proc); proc.connect(ctx.destination);
    });
    stopListening = () => {};
    proc.disconnect(); src.disconnect(); stream.getTracks().forEach(t => t.stop());
    const rate = ctx.sampleRate; ctx.close();
    if (!spoke) return [];
    const r = await fetch('api/recognize?words=' + encodeURIComponent(line) + (isEs() ? '&lang=es' : ''), { method: 'POST', headers: { 'Content-Type': 'application/octet-stream' }, body: to16k(chunks, rate) });
    if (!r.ok) throw new Error('speech ' + r.status);
    const j = await r.json(); lastUnknown = j.unknown || [];
    return [j.words || []];
  }
  // Float32 at the device rate -> 16 kHz 16-bit PCM (what Vosk wants)
  function to16k(chunks, rate) {
    const n = chunks.reduce((a, c) => a + c.length, 0), all = new Float32Array(n); let o = 0;
    for (const c of chunks) { all.set(c, o); o += c.length; }
    const ratio = rate / 16000, m = Math.floor(n / ratio), out = new Int16Array(m);
    for (let i = 0; i < m; i++) {
      const a = Math.floor(i * ratio), b = Math.min(n, Math.max(a + 1, Math.floor((i + 1) * ratio))); let s = 0;
      for (let k = a; k < b; k++) s += all[k];
      out[i] = Math.max(-1, Math.min(1, s / (b - a))) * 32767;
    }
    return out.buffer;
  }
  function listenBrowser(timeoutMs) {
    return new Promise(res => {
      const r = new SR(); r.lang = isEs() ? 'es-US' : 'en-US'; r.interimResults = false; r.maxAlternatives = 3;
      let best = [], done = false;
      const fin = () => { if (done) return; done = true; try { r.stop(); } catch (e) {} res(best); };
      r.onresult = e => { const alts = [...e.results[0]].map(a => a.transcript.split(/\s+/)); best = alts; fin(); };
      r.onerror = e => { if (/not-allowed/.test(e.error || '')) useMic = false; fin(); };
      r.onend = fin;
      try { r.start(); } catch (e) { useMic = false; return fin(); }
      setTimeout(fin, timeoutMs || 9000);
    });
  }

  // ---------- helpers ----------
  function toast(t, ms) { const el = $('toast'); el.textContent = t; el.style.display = 'block'; clearTimeout(toast.t); toast.t = setTimeout(() => el.style.display = 'none', ms || 1200); }
  function el(tag, cls, html) { const e = document.createElement(tag); if (cls) e.className = cls; if (html != null) e.innerHTML = html; return e; }
  function btn(label, fn, cls) { const b = el('button', cls, label); b.onclick = fn; return b; }
  const shuffle = a => { a = a.slice(); for (let i = a.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [a[i], a[j]] = [a[j], a[i]]; } return a; };
  const starStr = n => 'โ˜…'.repeat(n) + 'โ˜†'.repeat(3 - n);
  function go(id) { document.querySelectorAll('.screen').forEach(s => s.classList.toggle('on', s.id === id)); if (id === 'home') home(); }

  // ---------- readers (who is reading) ----------
  // Names stay on this device only. "Edit" lets a grown-up remove a reader (two taps; their stars go too).
  let addingReader = false, editingReaders = false;
  const esc = t => t.replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
  // say a line with the kid's name if the voice can say the name, else the line without it
  const canSay = t => hasTTS || !!clipFor(t) || t.split(/[\s,]+/).map(clean).filter(Boolean).every(w => clipFor(w));
  const sayWithName = (withName, without) => speak(canSay(withName) ? withName : without);
  // Signed in to a family account (/account/sync.js): the names come from the account, so they are added
  // and removed on the account page instead.
  const acct = () => window.ABCAccount && window.ABCAccount.signedIn;
  function readerButtons() {
    const k = $('kids'); k.innerHTML = '';
    $('whoHint').textContent = S.readers.length ? '' : 'Grown-ups: add each learner (a first name or nickname).';
    if (acct()) {
      $('whoHint').innerHTML = S.readers.length ? '' : 'Grown-ups: add your learners on the <a href="/account/">account page</a>.';
      S.readers.forEach(n => k.appendChild(btn(esc(n), () => { S.kid = n; save(); track('/readers/picked'); home(); sayWithName(P.greet.replace('{kid}', n), P.greetAny); }, S.kid === n ? 'sel' : '')));
      if (S.readers.length) { const a = el('a', 'parent', 'Add or remove learners'); a.href = '/account/'; k.appendChild(a); }
      return;
    }
    S.readers.forEach(n => {
      const b = btn(esc(n), () => {
        if (!editingReaders) { S.kid = n; save(); track('/readers/picked'); home(); return sayWithName(P.greet.replace('{kid}', n), P.greetAny); }
        if (!b.dataset.sure) { b.dataset.sure = 1; b.textContent = `Remove ${n}? Tap again`; return; }
        S.readers = S.readers.filter(x => x !== n); delete S.progress[n]; delete S.boards[n];
        if (S.kid === n) S.kid = null;
        save(); home();
      }, (S.kid === n ? 'sel' : '') + (editingReaders ? ' edit' : ''));
      k.appendChild(b);
    });
    if (addingReader || !S.readers.length) {
      const inp = el('input'); inp.maxLength = 16; inp.placeholder = 'Name'; inp.autocomplete = 'off';
      const add = () => {
        const n = inp.value.trim().replace(/\s+/g, ' ');
        if (!/^\p{L}[\p{L}' .-]{0,15}$/u.test(n)) return toast('Letters only, please');
        if (S.readers.some(x => x.toLowerCase() === n.toLowerCase())) return toast(`${n} is already here`);
        S.readers.push(n); S.kid = n; addingReader = false; save(); track('/readers/added'); home();
      };
      inp.onkeydown = e => { if (e.key === 'Enter') add(); };
      k.append(inp, btn('Add', add, 'big'));
      if (S.readers.length) k.appendChild(btn('Cancel', () => { addingReader = false; home(); }, 'ghost parent'));
      setTimeout(() => inp.focus(), 50);
    } else if (!editingReaders && S.readers.length < 8) k.appendChild(btn('๏ผ‹', () => { addingReader = true; home(); }, 'add'));
    if (S.readers.length && !addingReader) k.appendChild(btn(editingReaders ? 'Done' : 'Edit', () => { editingReaders = !editingReaders; home(); }, 'ghost parent'));
  }

  // ---------- home + map ----------
  function home() {
    readerButtons();
    const sb = $('speedBtn'); sb.textContent = 'Voice: ' + (S.speed === 75 ? 'faster' : 'normal');
    sb.onclick = () => { S.speed = S.speed === 75 ? 60 : 75; save(); home(); bookId = bookId || 'primer1881'; speak('Great job!'); };
    // Grown-ups: the Spanish 1861 stories come with gentler words by default (a few unkind words and views of the
    // time were changed); this switches to the book's original wording.
    const ob = $('origBtn'), hasOrig = Object.values(BOOKS).some(b => b.lessons.some(L => L.linesOrig));
    ob.hidden = !hasOrig; ob.textContent = 'Spanish stories: ' + (S.orig ? 'original 1861 words' : 'gentle words');
    ob.onclick = () => { S.orig = !S.orig; save(); home(); toast(S.orig ? 'Original 1861 wording' : 'Gentle wording', 1600); };
    // Grown-ups: a flagged tale (L.flag from make-book, e.g. antisemitic content) is left out of the Fairy Tales page until a grown-up includes it
    const fb = $('flagBtn'), flagged = {};
    Object.values(BOOKS).forEach(b => b.lessons.forEach(L => { if (L.flag) flagged[L.tale] = L.flag; }));
    const fl = Object.keys(flagged); fb.hidden = !fl.length;
    fb.textContent = 'Flagged tales (' + fl.length + '): ' + (S.flagged ? 'included' : 'left out');
    fb.onclick = () => {
      if (!S.flagged && !confirm('Include the flagged tales on the Fairy Tales page?\n\n' + fl.map(n => n + ': ' + flagged[n]).join('\n'))) return;
      S.flagged = !S.flagged; save(); home(); toast(S.flagged ? 'Flagged tales included' : 'Flagged tales left out', 1600);
    };
    // Grown-ups: instructions in the Spanish book in English then Spanish, English only, or Spanish only (once kids know the routine)
    const ib = $('insBtn'), INS = { both: 'English + Spanish', en: 'English only', es: 'Spanish only' }, order = ['both', 'en', 'es'];
    ib.hidden = !Object.values(BOOKS).some(b => b.lang === 'es');
    ib.textContent = 'Spanish book instructions: ' + INS[S.ins || 'both'];
    ib.onclick = () => { S.ins = order[(order.indexOf(S.ins || 'both') + 1) % 3]; save(); home(); toast(INS[S.ins], 1600); };
    // The books follow the kids as they grow: each shows this kid's progress, and the one they're on glows.
    // Every book stays open, so an older kid can start at their own level.
    const sh = $('shelf'); sh.innerHTML = '';
    const doneIn = id => { const p = (S.progress[S.kid] || {})[id] || {}; return Object.values(p).filter(x => x && x.stars).length; };
    const open = SHELF.filter(b => !b.soon && !b.tales && BOOKS[b.id]);
    const cur = S.kid && (open.slice().reverse().find(b => doneIn(b.id) > 0 && doneIn(b.id) < BOOKS[b.id].lessons.length)
      || open.find(b => doneIn(b.id) < BOOKS[b.id].lessons.length));
    SHELF.filter(b => !b.tales || BOOKS[b.id]).forEach(b => {
      if (b.tales) { // the fairy tale collection is one book here; it opens its own Fairy Tales page
        const B = BOOKS[b.id], tales = taleList(b.id), fin = S.kid ? tales.filter(t => t.d >= t.n).length : 0;
        const e = btn(`<b>${esc(B.title)}</b><span class="bp">${S.kid && fin ? `โ˜… ${fin} of ${tales.length} finished` : `Tales: ${tales.length}`}</span><small>Brothers Grimm</small>`, () => {
          if (!S.kid) return toast('Pick your name first!');
          talesPage(b.id);
        }, 'book' + (S.kid && tales.some(t => t.d && t.d < t.n) ? ' cur' : ''));
        e.style.background = B.color; sh.appendChild(e); return;
      }
      const B = BOOKS[b.id] || b;
      const n = BOOKS[b.id] ? BOOKS[b.id].lessons.length : 0, d = S.kid && n ? doneIn(b.id) : 0;
      const prog = n && S.kid ? (d >= n ? 'โ˜… Finished!' : d ? `Lesson ${d + 1} of ${n}` : `Lessons: ${n}`) : '';
      const e = btn(`<b>${B.title}</b><span class="bp">${prog}</span><small>${B.sub}</small>`, () => {
        if (!S.kid) return toast('Pick your name first!');
        if (b.soon || !BOOKS[b.id]) return toast('Coming soon!');
        openBook(b.id);
      }, 'book' + (b.soon ? ' soon' : '') + (cur && cur.id === b.id ? ' cur' : ''));
      e.style.background = B.color; sh.appendChild(e);
    });
  }
  // The tales of a fairy tale collection (book with tales: true), in collection order: tale name, its number in the whole
  // collection (L.taleNo, "Tale 39 of 211"), how many parts, and how many of them this kid has stars for.
  function taleList(id) {
    const B = BOOKS[id], p = (S.progress[S.kid] || {})[id] || {}, by = {};
    for (const L of B.lessons) {
      if (!L.tale || (L.flag && !S.flagged)) continue;   // a flagged tale shows only if a grown-up included it (home screen)
      const t = by[L.tale] = by[L.tale] || { tale: L.tale, no: L.taleNo || 0, n: 0, d: 0, flag: L.flag };
      t.n++; if (S.kid && (p[L.n] || {}).stars) t.d++;
    }
    return Object.values(by).sort((a, b) => a.no - b.no);
  }
  // Fairy Tales page: each tale is its own book (only that tale's parts). Stars stay under the collection's id and lesson n,
  // so progress and the BlockCraft Fairy Tale Kingdom unlocks don't change. The tale being read glows.
  let talesId = null;
  function talesPage(id) {
    talesId = id = id || talesId;
    const B = BOOKS[id], ts = $('taleShelf'); ts.innerHTML = '';
    $('talesTitle').textContent = `${S.kid}: ${B.title}`;
    taleList(id).forEach(t => {
      const prog = t.d >= t.n ? 'โ˜… Finished!' : t.d ? `Part ${t.d + 1} of ${t.n}` : '';
      const e = btn(`<b>${esc(t.tale)}</b>${prog ? `<span class="bp">${prog}</span>` : ''}<small>${t.no ? `Tale ${t.no} of ${B.taleCount}` : 'Brothers Grimm'}${t.flag ? ' ยท Flagged for grown-ups' : ''}</small>`,
        () => openBook(id, t.tale), 'book' + (t.d && t.d < t.n ? ' cur' : ''));
      e.style.background = B.color; ts.appendChild(e);
    });
    go('tales');
  }
  let book, bookId, bookTale = null;   // bookTale: the fairy tale whose parts the map shows (null = the whole book)
  // A lesson's name for the "Go to lesson" list and the tiles: its title, else its first line.
  function lessonName(L) {
    const s = L.title || (L.lines && L.lines[0]) || (L.words || []).slice(0, 4).join(', ');
    return `${L.review ? 'Review' : 'Lesson'} ${L.n}` + (s ? ': ' + (s.length > 48 ? s.slice(0, 46) + 'โ€ฆ' : s) : '');
  }
  let skipArm = null;   // a locked tile tapped once: a 2nd tap within 4 s skips ahead to it
  function openBook(id, tale) {
    loadSO(id);
    bookId = id; book = BOOKS[id]; bookTale = tale || null;
    track('/readers/book', { book: id });
    $('mapTitle').textContent = `${S.kid}: ${bookTale || book.title}`;
    // A fairy tale opened from the Fairy Tales shelf shows only its own parts; i is still the lesson's place in the whole book.
    const list = book.lessons.map((L, i) => ({ L, i })).filter(x => !bookTale || x.L.tale === bookTale);
    const name = L => bookTale ? `Part ${L.part} of ${L.parts}` : lessonName(L);
    $('jumpLbl').textContent = bookTale ? 'Go to part' : 'Go to lesson';
    const t = $('tiles'); t.innerHTML = ''; const p = prog(id);
    // Lessons are open up to one past the furthest one finished, so after a skip the kid carries on from there.
    let far = -1; list.forEach(({ L }, k) => { if ((p[L.n] || {}).stars) far = k; });
    const paidAt = i => window.ABCAccount && window.ABCAccount.locked('readers', i);
    const begin = (L, i) => paidAt(i) ? window.ABCAccount.unlockScreen('readers') : startLesson(L);
    list.forEach(({ L, i }, k) => {
      const st = (p[L.n] || {}).stars || 0, open = k <= far + 1, isNext = k === far + 1;
      // past the free lessons without a subscription (only when the paywall is switched on)
      const paid = paidAt(i);
      const label = bookTale ? 'Part<br>' + L.part : L.review ? 'Review<br>' + L.n : L.n;
      const tile = btn(`${label}<span class="st">${st ? starStr(st) : paid ? '๐Ÿ”’' : ''}</span>`, () => {
        if (paid) return window.ABCAccount.unlockScreen('readers');
        if (!open && !st && !(skipArm && skipArm.i === i && Date.now() - skipArm.at < 4000)) {
          skipArm = { i, at: Date.now() };
          return toast(`${bookTale ? 'Part ' + L.part : (L.review ? 'Review ' : 'Lesson ') + L.n} is ahead. Tap it again to skip to it.`, 3500);
        }
        skipArm = null; startLesson(L);
      }, 'tile' + (isNext ? ' next' : '') + (!open && !st ? ' locked' : '') + (L.review ? ' rev' : ''));
      tile.title = name(L) + (st ? ', done' : !open ? ', ahead' : '');
      tile.setAttribute('aria-label', tile.title);
      t.appendChild(tile);
    });
    // "Go to lesson": every lesson by name, starting on the next one; Go starts it (skipping ahead is allowed).
    const sel = $('jumpSel'); sel.innerHTML = '';
    list.forEach(({ L, i }, k) => {
      const o = el('option'); o.textContent = name(L) + ((p[L.n] || {}).stars ? ' โ˜…' : '');
      o.value = i; if (k === Math.min(far + 1, list.length - 1)) o.selected = true; sel.appendChild(o);
    });
    $('jumpGo').onclick = () => { const i = +sel.value; begin(book.lessons[i], i); };
    go('map'); sayIns(P.map);
    const nx = t.querySelector('.next'); if (nx) nx.scrollIntoView({ block: 'center' });
  }

  // ---------- lesson flow ----------
  let L, stepIdx, scores, cleanup = null, sayAgain = null;
  function stepsFor(L) { return STEPS.filter(s => (s.id !== 'words' || (L.words.length + L.letters.length)) && (s.id !== 'talk' || (L.questions && L.questions.length)) && (s.id !== 'spell' || book.spell)); }
  function startLesson(lesson) {
    L = S.orig && lesson.linesOrig ? { ...lesson, lines: lesson.linesOrig } : lesson;   // original 1861 wording if a grown-up chose it
    scores = {}; stepIdx = 0; preload(L);
    track('/readers/lesson', { book: bookId, lesson: L.n });
    $('lesTitle').textContent = L.tale && L.title ? L.title : (L.review ? 'Review ' : 'Lesson ') + L.n;
    go('lesson'); runStep();
  }
  function leave() { stopStep(); openBook(bookId, bookTale); }
  function stopStep() { stopAll(); if (cleanup) { cleanup(); cleanup = null; } }
  function runStep() {
    stopStep();
    const steps = stepsFor(L), s = steps[stepIdx];
    const dots = $('steps'); dots.innerHTML = '';
    steps.forEach((x, i) => { const d = el('i', i < stepIdx ? 'done' : i === stepIdx ? 'cur' : '', x.icon); dots.appendChild(d); });
    if (!s) return finish();
    track('/readers/step/' + s.id, { book: bookId, lesson: L.n });
    $('stepTitle').textContent = titleI(s.name); $('stage').innerHTML = ''; $('controls').innerHTML = ''; $('hint').textContent = '';
    sayAgain = null; stepTok++;
    const instr = s.id === 'read' ? (useMic ? P.readMic : P.readHelper) : P[s.id];
    hint(instr);
    introP = (stepIdx === 0 ? sayIns('lesson:' + L.n) : Promise.resolve()).then(() => stepTok === myTok && sayIns(instr));
    const myTok = stepTok;
    $('sayBtn').onclick = () => sayIns(instr).then(() => sayAgain && sayAgain());
    ({ words: stepWords, listen: stepListen, read: stepRead, talk: stepTalk, spell: stepSpell, print: () => stepTrace('print'), script: () => stepTrace('script'), board: stepBoard })[s.id]();
  }
  let introP = Promise.resolve(), stepTok = 0;
  const afterIntro = fn => { const t = stepTok; introP.then(() => { if (t === stepTok) fn(); }); };
  function next(stars) { scores[stepsFor(L)[stepIdx].id] = stars; stepIdx++; runStep(); }

  // 1. New words: hear each card, then "find it" game
  function stepWords() {
    const items = [...L.letters.map(t => ({ t, letter: true })), ...L.words.map(t => ({ t }))];
    const box = el('div', 'cards'); $('stage').appendChild(box);
    const cards = items.map(it => { const c = btn(it.t, () => onTap(it, c), 'card' + (it.letter ? ' letter' : '')); if (!it.letter) holdToSound(c, it.t); box.appendChild(c); return c; });
    let mode = 'learn', heardAll = new Set(), target = null, round = 0, misses = 0, busy = false;
    const rounds = shuffle(L.words.length ? L.words : L.letters).concat(shuffle(L.words.length ? L.words : L.letters)).slice(0, 6);
    hint('Tap each card to hear it.');
    // a word with a meaning from the book (Fourth Reader DEFINITIONS) says the word and what it means
    const def = it => !it.letter && L.defs && L.defs[it.t];
    function say(it) { if (def(it)) $('hint').textContent = `${it.t}: ${def(it)}`; return speak(it.letter ? 'letter:' + it.t : def(it) ? 'def:' + it.t : it.t, null, 0.7); }
    function onTap(it, c) {
      if (mode === 'learn') { say(it); heardAll.add(it); c.classList.add('ok'); setTimeout(() => c.classList.remove('ok'), 500); if (heardAll.size === items.length) startGame(); return; }
      if (busy) return;
      if (it.t === target) { busy = true; beep(true); c.classList.add('ok'); setTimeout(() => { busy = false; c.classList.remove('ok'); nextRound(); }, 700); }
      else { beep(false); misses++; c.classList.remove('no'); void c.offsetWidth; c.classList.add('no'); }
    }
    function startGame() {
      $('controls').innerHTML = '';
      $('controls').appendChild(btn('Play: Find it!', () => { mode = 'game'; $('controls').innerHTML = ''; sayIns(P.game).then(nextRound); }, 'big'));
      hint('Good! Now play the game.'); sayIns('Good! Now play the game.');
    }
    function nextRound() {
      if (round >= rounds.length) { busy = true; toastI('Great job! โญ'); return setTimeout(() => next(misses === 0 ? 3 : misses < 3 ? 2 : 1), 900); }
      target = rounds[round++]; hint('Find the word ({a} of {b})', { a: round, b: rounds.length });
      sayAgain = () => sayIns('Find ' + target); sayAgain();
      shuffle(cards).forEach(c => box.appendChild(c));
    }
  }

  // 2. Listen: the book is read to you with each word lit up
  function stepListen() {
    const st = $('stage'); const wrap = el('div', 'text');
    // a real picture (Grimm: Arthur Rackham's plates) replaces the emoji
    wrap.appendChild(L.img ? el('div', 'pic', `<img class="plate" src="${L.img}" alt="Picture for ${esc(L.tale || L.title || '')}, by Arthur Rackham">`) : el('div', 'pic', `${L.pic}<small>${L.picText}</small>`));
    if (L.title) wrap.appendChild(el('h2', '', L.title));
    if (L.author) { const by = el('div', 'parent', 'by ' + L.author); if (L.about) by.title = L.about; wrap.appendChild(by); }
    if (L.en) wrap.appendChild(el('div', 'parent', 'In English: ' + esc(L.en)));   // Spanish book: what it means, for grown-ups
    if (L.note) wrap.appendChild(el('div', 'parent', 'Note for the teacher (1861): ' + esc(L.note)));
    const lines = L.lines.map(t => { const d = el('div', 'ln'); t.split(' ').forEach(w => { const s = el('span', 'w', w); s.onclick = () => speak(clean(w), null, 0.7); holdToSound(s, w); d.appendChild(s); d.append(' '); }); wrap.appendChild(d); return d; });
    st.appendChild(wrap);
    let stop = false;
    async function playAll() {
      playB.disabled = true; stop = false;
      for (const d of lines) {
        if (stop) break;
        d.classList.add('cur'); d.scrollIntoView({ block: 'nearest' });
        const ws = [...d.querySelectorAll('.w')];
        await speak(d.textContent.trim(), i => ws.forEach((w, k) => w.classList.toggle('hi', k === i)));
        d.classList.remove('cur'); await new Promise(r => setTimeout(r, 350));
      }
      if (stop) return;
      playB.disabled = false; nextB.disabled = false; hint('Tap a word to hear it. Press and hold a word to sound it out.');
    }
    const playB = btn('โ–ถ Read to me', playAll, 'big'), nextB = btn('Next โ–ถ', () => next(3));
    nextB.disabled = true; $('controls').append(playB, nextB);
    sayAgain = playAll; cleanup = () => { stop = true; stopAll(); };
    if (!AUDIO[bookId] && !hasTTS) hint('This device has no reading voice. A grown-up can read it.');
    afterIntro(playAll);
  }

  // 3. Your turn: kid reads each line; the app listens (or a grown-up marks it)
  function stepRead() {
    const st = $('stage'); const wrap = el('div', 'text'); st.appendChild(wrap);
    let li = 0, total = 0, right = 0, tries = 0;
    const lineEl = el('div', 'ln cur'); wrap.appendChild(lineEl);
    const mic = btn('๐ŸŽค', go, 'mic');
    function show() {
      lineEl.innerHTML = '';
      L.lines[li].split(' ').forEach(w => { const s = el('span', 'w', w); holdToSound(s, w); lineEl.append(s, ' '); });
      hint(useMic ? 'Line {a} of {b}: tap the microphone, then read it out loud.' : 'Line {a} of {b}: read it out loud. Grown-up: tap words that were missed, then โœ“.', { a: li + 1, b: L.lines.length });
      $('controls').innerHTML = '';
      if (useMic) $('controls').appendChild(mic);
      else {
        [...lineEl.querySelectorAll('.w')].forEach(w => { w.classList.add('ok'); w.onclick = () => { w.classList.toggle('ok'); w.classList.toggle('miss'); }; });
        $('controls').appendChild(btn('โœ“ Done', () => grade([...lineEl.querySelectorAll('.w')].map(w => w.classList.contains('ok'))), 'big'));
      }
      $('controls').appendChild(btn('๐Ÿ”Š Help', () => speak(L.lines[li])));
      $('controls').appendChild(btn('Skip', () => next(1), 'ghost parent'));
    }
    async function go() {
      if (mic.classList.contains('live')) return stopListening();   // second tap = "I'm done"
      mic.classList.add('live');
      const words = L.lines[li].split(' ');
      const alts = await listen(Math.min(25000, 4000 + 700 * words.length), L.lines[li]);
      mic.classList.remove('live');
      if (!useMic) { hint(P.micBlocked); sayIns(P.micBlocked); return show(); }
      let ok = new Array(words.length).fill(false);
      for (const a of alts) { const m = matchWords(words, a); if (m.filter(Boolean).length > ok.filter(Boolean).length) ok = m; }
      const unknown = lastUnknown.map(norm);
      if (alts.length) ok = ok.map((v, i) => v || unknown.includes(norm(words[i])));   // words the checker can't hear count as read
      // Spanish: the small Spanish checker misses some words a child reads right (tested with the book's own
      // recordings: about 84% heard), so a line where 3 of 4 words were heard counts as read
      if (isEs() && alts.length && ok.filter(Boolean).length >= 0.75 * ok.length) ok = ok.map(() => true);
      [...lineEl.querySelectorAll('.w')].forEach((w, i) => { w.classList.toggle('ok', ok[i]); w.classList.toggle('miss', !ok[i]); });
      if (!alts.length) { toastI('I did not hear you. Try again!', 1500); return; }
      grade(ok);
    }
    function grade(ok) {
      const n = ok.filter(Boolean).length; tries++;
      if (n === ok.length || tries >= 2) {
        total += ok.length; right += n; tries = 0;
        if (n === ok.length) { beep(true); toastI('Yes! โญ', 900); } else toastI('Good try!', 900);
        setTimeout(() => { if (++li >= L.lines.length) next(right / total > 0.9 ? 3 : right / total > 0.7 ? 2 : 1); else show(); }, 1000);
      } else {
        beep(false); hint('Listen to the red words sounded out, then try again.');
        const words = L.lines[li].split(' ').filter((w, i) => !ok[i]);
        (async () => {   // each missed word sounded out, the phonics way
          for (const w of words) { await soundOut(w); await new Promise(r => setTimeout(r, 400)); }
          if (!useMic) show();
        })();
      }
    }
    sayAgain = () => speak(L.lines[li]);
    show();
  }

  // 1b. Spell it (Spell & Read, 1867): "Let the child spell each word in the line, then read the line."
  // Tapping a word plays its spelling ("I, S. is.") so a grown-up can check.
  function stepSpell() {
    const wrap = el('div', 'text'); $('stage').appendChild(wrap);
    const box = el('div', 'cards'); box.style.height = 'auto'; wrap.appendChild(box);
    let i = 0;
    function show() {
      box.innerHTML = '';
      L.lines[i].split(' ').forEach(w => {
        // a joined word ("new-cut", "lap-dog") is spelled one part after the other
        const parts = w.split('-').map(p => p.replace(/[^A-Za-z']/g, '')).filter(Boolean);
        if (!parts.length) return;
        const sb = btn(w, async () => { for (const p of parts) await speak('spell:' + (p === 'I' ? p : p.toLowerCase()), null, 0.7); }, 'card');
        holdToSound(sb, w); box.appendChild(sb);
      });
      $('hint').textContent = `Line ${i + 1} of ${L.lines.length}: spell each word out loud, then read the line.`;
    }
    $('controls').append(btn('๐Ÿ”Š Line', () => speak(L.lines[i])), btn('Next line โ–ถ', () => { if (++i < L.lines.length) show(); else next(3); }, 'big'));
    sayAgain = () => speak(L.lines[i]);
    show();
  }

  // 3b. Talk about it: the book's own questions (Fourth Reader EXERCISES), read one at a time; the kid answers out loud
  function stepTalk() {
    const wrap = el('div', 'text'); $('stage').appendChild(wrap);
    const q = el('div', 'ln cur'); wrap.appendChild(q);
    let i = 0;
    function show() {
      q.textContent = L.questions[i];
      $('hint').textContent = `Question ${i + 1} of ${L.questions.length}: answer it out loud.`;
      sayAgain = () => speak(L.questions[i]); sayAgain();
    }
    $('controls').append(btn('Next question โ–ถ', () => { if (++i < L.questions.length) show(); else next(3); }, 'big'));
    afterIntro(show);
  }

  // 4/5. Tracing pages: letters, words, then each sentence
  // Copy work stays a sensible length in the long Readers: new words 6 to a page, up to 6 short sentences
  // (tools/make-audio.ps1 records the same word pages).
  const WORDS_PER_PAGE = 6;
  function copySentences(max) {
    if (L.board) return L.board.slice(0, max);   // the Spanish book lists its own pages (no syllable hyphens)
    const seen = new Set(), all = [];
    L.lines.filter(t => t.split(' ').length > 2).forEach(t => { const k = t.toLowerCase(); if (!seen.has(k)) { seen.add(k); all.push(t); } });
    const short = all.filter(t => t.length <= 70);
    return (short.length ? short : all.slice(0, 1)).slice(0, max);
  }
  function copyItems(style) {
    if (L.copy) return L.copy.slice();
    if (style === 'script' && L.script) return L.script.slice(0, 6);
    const out = [];
    if (L.letters.length) out.push(L.letters.join(' '));
    for (let i = 0; i < L.words.length; i += WORDS_PER_PAGE) out.push(L.words.slice(i, i + WORDS_PER_PAGE).join(' '));
    return out.concat(copySentences(6));
  }
  function stepTrace(style) {
    const items = copyItems(style); let i = 0, misses = 0, tracer;
    const box = el('div', 'grow paper'); box.style.height = '100%'; $('stage').appendChild(box);
    const cv = el('canvas'); box.appendChild(cv);
    ABCTrace.Tracer.onMiss = why => { misses++; beep(false); hint(why === 'start' ? 'Start at the green dot!' : 'Follow the arrow all the way.'); };
    function page() {
      if (tracer) tracer.stop();
      hint('Page {a} of {b}: start at the green dot and follow the arrow.', { a: i + 1, b: items.length });
      sayAgain = () => speak(items[i]); cv.dataset.text = items[i];
      if (i === 0) afterIntro(sayAgain); else sayAgain();
      tracer =ABCTrace.Tracer(cv, items[i], style, () => {
        beep(true); toast('โญ', 700);
        setTimeout(() => { if (++i < items.length) page(); else next(misses < 3 ? 3 : misses < 8 ? 2 : 1); }, 800);
      });
    }
    $('controls').appendChild(btn('Skip page', () => { if (++i < items.length) page(); else next(1); }, 'ghost parent'));
    setTimeout(page, 50);
    const onRes = () => page(); window.addEventListener('resize', onRes);
    cleanup = () => { tracer && tracer.stop(); window.removeEventListener('resize', onRes); };
  }

  // 6. Blackboard: write it yourself in chalk
  function stepBoard() {
    const items = copySentences(3);
    if (!items.length) items.push(L.lines[0]);
    let i = 0, style = 'print', bb, total = 0;
    const box = el('div', 'grow'); box.style.height = '100%'; $('stage').appendChild(box);
    const cv = el('canvas'); cv.style.background = 'var(--board)'; box.appendChild(cv);
    const styleB = btn('Print', () => { style = style === 'print' ? 'script' : 'print'; styleB.textContent = style === 'print' ? 'Print' : 'Cursive'; page(); });
    $('controls').append(styleB, btn('๐Ÿ‘€ Peek', () => bb.peek(2500)), btn('โ†ถ', () => bb.undo()), btn('Erase', () => bb.erase()), btn('Done โœ“', done, 'big'));
    function page() {
      if (bb) bb.stop();
      bb = ABCTrace.Blackboard(cv, items[i], style);
      hint('Write: "{t}" ({a} of {b})', { t: items[i], a: i + 1, b: items.length });
      sayAgain = () => sayIns('Write: ' + items[i]);
      if (i === 0) afterIntro(sayAgain); else sayAgain();
    }
    function done() {
      if (bb.empty()) return toastI('Write it on the board first!');
      const s = bb.score(); total += s;
      const list = (S.boards[S.kid] = S.boards[S.kid] || []);
      list.push({ book: bookId, n: L.n, text: items[i], style, img: bb.snapshot(), at: Date.now() });
      if (list.length > 40) list.splice(0, list.length - 40);
      save(); beep(true); toast(starStr(s), 1100);
      setTimeout(() => { if (++i < items.length) page(); else next(Math.round(total / items.length)); }, 1200);
    }
    setTimeout(page, 50);
    cleanup = () => bb && bb.stop();
  }

  function finish() {
    const vals = Object.values(scores), stars = Math.max(1, Math.round(vals.reduce((a, b) => a + b, 0) / vals.length));
    const p = prog(bookId), old = (p[L.n] || {}).stars || 0;
    p[L.n] = { stars: Math.max(old, stars), steps: scores, at: Date.now() }; save();
    track('/readers/done', { book: bookId, lesson: L.n, stars });
    $('stepTitle').textContent = `${S.kid}, you finished ${L.review ? 'Review' : 'Lesson'} ${L.n}!`;
    $('stage').innerHTML = `<div class="text"><div class="stars">${starStr(stars)}</div></div>`;
    $('hint').textContent = ''; $('controls').innerHTML = '';
    if (L.tale && talesDone(S.kid, bookId).includes(L.tale) && !old) { // the last part of a fairy tale: its BlockCraft place opens
      $('stage').firstChild.append(el('p', 'tale-open', `You read all of ${L.tale}!` + (KINGDOM.includes(L.tale) ? ' Its place in the BlockCraft Fairy Tale Kingdom is open for you now.' : '')));
    }
    syncTales(S.kid);
    $('controls').append(btn(bookTale ? 'Parts' : 'Lessons', () => openBook(bookId, bookTale), 'big'));
    beep(true); (insMode() === 'en' ? sayWithName(`Great job, ${S.kid}!`, 'Great job!') : sayIns(clipFor('es:Great job, ' + S.kid + '!') ? `Great job, ${S.kid}!` : 'Great job!')).then(() => sayIns(P.done));
  }

  // ---------- BlockCraft Fairy Tale Kingdom ----------
  // Tales that have a place in the BlockCraft Fairy Tale Kingdom (BlockCraft public/engine.js TALES). Add a tale here when
  // BlockCraft gets its place; the others are still sent, BlockCraft just has nothing to open for them yet.
  const KINGDOM = [
    'The Elves', 'The Frog-King, or Iron Henry', 'Little Red-Cap', 'The Bremen Town-Musicians', 'Rumpelstiltskin', 'Mother Holle',
    'Briar-Rose', 'Rapunzel', 'Cinderella', 'Hansel and Grethel', 'The Wolf and the Seven Little Kids', 'Little Snow-white',
    'The Golden Goose', 'The Shoes That Were Danced to Pieces', 'Thumbling', 'Cat and Mouse in Partnership', "Our Lady's Child",
    'The Story of the Youth Who Went Forth to Learn What Fear Was', 'Faithful John', 'The Good Bargain', 'The Wonderful Musician',
    'The Twelve Brothers', 'The Pack of Ragamuffins', 'Little Brother and Little Sister', 'The Three Little Men in the Wood',
    'The Three Spinners', 'The Three Snake-Leaves', 'The White Snake', 'The Straw, the Coal, and the Bean',
    'The Fisherman and His Wife', 'The Valiant Little Tailor', 'The Riddle', 'The Mouse, the Bird, and the Sausage',
    'The Seven Ravens', 'The Singing Bone', 'The Devil With the Three Golden Hairs', 'The Louse and the Flea',
    'The Girl Without Hands', 'Clever Hans', 'The Three Languages', 'Clever Elsie', 'The Tailor in Heaven',
    'The Wishing-Table, the Gold-Ass, and the Cudgel in the Sack', 'The Wedding of Mrs. Fox', 'The Robber Bridegroom',
    'Herr Korbes', 'The Godfather', 'Frau Trude', 'Godfather Death', 'Thumbling as Journeyman', "Fitcher's Bird",
    'The Juniper-Tree', 'Old Sultan', 'The Six Swans', 'Fundevogel (Bird-foundling)', 'King Thrushbeard',
    'The Knapsack, the Hat, and the Horn', 'Sweetheart Roland', 'The Golden Bird', 'The Dog and the Sparrow',
    'Frederick and Catherine', 'The Two Brothers', 'The Little Peasant', 'The Queen Bee', 'The Three Feathers', 'Allerleirauh',
    "The Hare's Bride", 'The Twelve Huntsmen', 'The Thief and his Master', 'Jorinda and Joringel', 'The Three Sons of Fortune',
    'How Six Men Got on in the World', 'The Wolf and the Man', 'The Wolf and the Fox', 'The Fox and His Cousin',
    'The Fox and the Cat', 'The Pink', 'Clever Grethel', 'The Old Man and His Grandson', 'The Water-Nix',
    'The Death of the Little Hen', 'Brother Lustig', 'Gambling Hansel', 'Hans in Luck', 'Hans Married', 'The Gold-Children',
    'The Fox and the Geese', 'The Poor Man and the Rich Man', 'The Singing, Springing Lark', 'The Goose-Girl', 'The Young Giant',
    'The Gnome', 'The King of the Golden Mountain', 'The Raven', "The Peasant's Wise Daughter", 'Old Hildebrand',
    'The Three Little Birds', 'The Water of Life', 'Doctor Knowall', 'The Spirit in the Bottle', "The Devil's Sooty Brother",
    'Bearskin', 'The Willow-Wren and the Bear', 'Sweet Porridge', 'Wise Folks', 'Stories about Snakes',
    "The Poor Miller's Boy and the Cat", 'The Two Travellers', 'Hans the Hedgehog', 'The Shroud', 'The Skilful Huntsman',
    'The Flail From Heaven', "The Two Kings' Children", 'The Cunning Little Tailor', 'The Bright Sun Brings It to Light',
    'The Blue Light', 'The Wilful Child', 'The Three Army-Surgeons', 'The Seven Swabians', 'The Three Apprentices',
    "The King's Son Who Feared Nothing", 'Donkey Cabbages', 'The Old Woman in the Wood', 'The Three Brothers',
    'The Devil and his Grandmother', 'Ferdinand the Faithful', 'The Iron Stove', 'The Lazy Spinner', 'The Four Skilful Brothers',
    'One-eye, Two-eyes, and Three-eyes', 'Fair Katrinelje and Pif-Paf-Poltrie', 'The Fox and the Horse', 'The Six Servants',
    'The White Bride and the Black One', 'Iron John', 'The Three Black Princesses', 'Knoist and his Three Sons',
    'The Maid of Brakel', 'Domestic Servants', 'The Lambkin and the Little Fish', 'Simeli Mountain', 'Going A-Travelling',
    'The Donkey', 'The Ungrateful Son', 'The Turnip', 'The Old Man Made Young Again', "The Lord's Animals and the Devil's",
    'The Beam', 'The Old Beggar-Woman', 'The Three Sluggards', 'The Twelve Idle Servants', 'The Shepherd Boy', 'The Star-Money',
    'The Stolen Farthings', 'Brides On Their Trial', 'Odds And Ends', 'The Sparrow And His Four Children',
    'The Story of Schlauraffen Land', 'The Ditmarsch Tale of Wonders', 'A Riddling Tale', 'Snow-White and Rose-Red',
    'The Wise Servant', 'The Glass Coffin', 'Lazy Harry', 'The Griffin', 'Strong Hans', 'The Peasant in Heaven', 'Lean Lisa',
    'The Hut in the Forest', 'Sharing Joy and Sorrow', 'The Willow-Wren', 'The Sole', 'The Bittern and the Hoopoe', 'The Owl',
    'The Moon', 'The Duration of Life', "Death's Messengers", "Master Pfriem (Master Cobbler's Awl)",
    'The Goose-Girl at the Well', "Eve's Various Children", 'The Nix of the Mill-Pond', "The Little Folks' Presents",
    'The Giant and the Tailor', 'The Nail', 'The Poor Boy in the Grave', 'The True Sweethearts', 'The Hare and the Hedgehog',
    'The Spindle, The Shuttle, and the Needle', 'The Peasant and the Devil', 'The Crumbs on the Table', 'The Sea-Hare',
    'The Master-Thief', 'The Drummer', 'The Ear of Corn', 'The Grave-Mound', 'Old Rinkrank', 'The Crystal Ball', 'Maid Maleen',
    'The Boots of Buffalo-Leather', 'The Golden Key', 'St. Joseph in the Forest', 'The Twelve Apostles', 'The Rose',
    'Poverty and Humility Lead to Heaven', "God's Food", 'The Three Green Twigs', "Our Lady's Little Glass", 'The Aged Mother',
    'The Heavenly Wedding', 'The Hazel-Branch'];
  // A fairy tale (lessons with L.tale) is done when every part has stars. Finished tales are sent to the BlockCraft server,
  // so the tale's place opens in BlockCraft on any tablet, also when ABC Books runs on abcbooks.fyi. Only BlockCraft
  // player names count there; for other names the server just answers with an empty list.
  function talesDone(kid, id) {
    const b = BOOKS[id], p = ((S.progress[kid] || {})[id]) || {}, all = {};
    if (!b) return [];
    for (const l of b.lessons) if (l.tale) all[l.tale] = (all[l.tale] !== false) && !!(p[l.n] && p[l.n].stars);
    return Object.keys(all).filter(t => all[t]);
  }
  function syncTales(kid) {
    if (!kid) return;
    const tales = Object.keys(BOOKS).reduce((a, id) => a.concat(talesDone(kid, id)), []);
    if (!tales.length) return;
    const url = location.hostname === 'games.503mail.com' ? '/blockcraft/api/tales' : 'https://games.503mail.com/blockcraft/api/tales';
    fetch(url, { method: 'POST', headers: { 'Content-Type': 'text/plain' }, body: JSON.stringify({ name: kid, tales }) }).catch(() => {});
  }

  // ---------- gallery ----------
  $('toGallery').onclick = () => {
    const g = $('gal'); g.innerHTML = '';
    const list = (S.boards[S.kid] || []).slice().reverse();
    if (!list.length) g.innerHTML = '<p>No blackboard pictures yet.</p>';
    list.forEach(b => { const f = el('figure'); f.style.margin = 0; const im = el('img'); im.src = b.img; f.append(im, el('figcaption', 'parent', `Lesson ${b.n} ยท ${b.style} ยท ${new Date(b.at).toLocaleDateString()}`)); g.appendChild(f); });
    go('gallery');
  };

  // books + their recorded voice are JSON files, so the same lesson data feeds the app and the audio recorder
  Promise.all([fetch('prompts.json').then(r => r.json()).then(j => { P = j; }),
    fetch('instructions-es.json').then(r => r.ok ? r.json() : null).then(j => { if (j) ES = j.text; }).catch(() => {})].concat(SHELF.filter(b => !b.soon).map(b => Promise.all([
    fetch(`books/${b.id}.json`).then(r => r.json()).then(j => { BOOKS[b.id] = j; }),
    fetch(`audio/${b.id}.json`).then(r => r.ok ? r.json() : null).then(j => { if (j) AUDIO[b.id] = j; }).catch(() => {})
  ])))).then(() => { home(); S.readers.forEach(syncTales); }, () => toast('Could not load the books. Check the internet.', 4000));
  // the account answer can arrive after the first draw (signed in or out on another page): redraw the home screen
  if (window.ABCAccount) window.ABCAccount.ready.then(() => { if ($('home').classList.contains('on') && Object.keys(BOOKS).length) { home(); S.readers.forEach(syncTales); } });
  window.addEventListener('pointerdown', () => { if (AC && AC.state === 'suspended') AC.resume(); }, { passive: true });
  // the lesson map's back button: a fairy tale goes back to the Fairy Tales page, a book to the home screen
  const back = () => bookTale && talesId ? talesPage() : go('home');
  return { go, leave, back, debug: () => ({ S, L, stepIdx, scores }) };
})();
EOF

index.html: the page and styles (the picture size is the .pic .plate rule; the Fairy Tales page is #tales with the shelf #taleShelf).

cat > /root/abcbooks-rebuild/index.html <<'EOF'
<!doctype html>
<html lang="en"><head>
<meta charset="utf-8">
<script>
// The readers live at abcbooks.fyi/readers/ (the welcome page is at /). This page opened at the old address
// (an old offline copy or bookmark of abcbooks.fyi/index.html): go to the new one.
if (location.hostname === 'abcbooks.fyi' && !location.pathname.startsWith('/readers/')) location.replace('/readers/');
</script>
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">
<meta name="theme-color" content="#121212">
<title>ABC Books</title>
<link rel="icon" type="image/png" sizes="192x192" href="icon-192.png">
<link rel="manifest" href="manifest.webmanifest">
<link rel="apple-touch-icon" href="icon-192.png">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-title" content="ABC Books">
<style>
:root{color-scheme:dark;--paper:#121212;--ink:#ececec;--soft:#a8a8a8;--accent:#d9733f;--good:#3fae6e;--bad:#ff6b5e;--board:#1d3527;--card:#1e1e1e;--line:#6a6a6a;--hi:#3a3220}
*{box-sizing:border-box;-webkit-tap-highlight-color:transparent}
html,body{margin:0;height:100%;background:var(--paper);color:var(--ink);font-family:Georgia,"Times New Roman",serif;overflow:hidden;user-select:none;-webkit-user-select:none}
.screen{position:absolute;inset:0;display:none;flex-direction:column;padding:12px 16px}
.screen.on{display:flex}
h1{margin:4px 0 10px;font-size:clamp(26px,6vmin,44px);text-align:center;letter-spacing:.04em}
h2{margin:6px 0;font-size:clamp(20px,4.5vmin,32px);text-align:center}
button{font:inherit;font-size:clamp(18px,4vmin,26px);border:3px solid var(--line);background:var(--card);color:var(--ink);border-radius:14px;padding:10px 18px;min-height:52px;cursor:pointer}
button:active{transform:scale(.96)}
button.big{background:var(--accent);color:#fff;border-color:#6b2e14;font-size:clamp(22px,5vmin,32px);padding:14px 28px}
button.ghost{border-color:transparent;background:transparent}
button:disabled{opacity:.35}
.row{display:flex;gap:10px;justify-content:center;flex-wrap:wrap;align-items:center}
.grow{flex:1;min-height:0;position:relative}
.kids button{min-width:30vmin;font-size:clamp(24px,6vmin,40px)}
.kids button.sel{background:var(--accent);border-color:var(--accent);color:#fff}
.kids button.add,.kids button.ghost,.kids button.big{min-width:0}
.kids button.edit{border-style:dashed}
.kids input{font:inherit;font-size:clamp(22px,5vmin,34px);width:min(60vw,320px);padding:8px 14px;border-radius:14px;border:3px solid var(--line);background:var(--card);color:var(--ink)}
.shelf{display:flex;gap:3vmin;justify-content:center;flex-wrap:wrap;margin-top:3vmin;padding:8px}
#home{overflow-y:auto}
.book{width:min(42vw,40vmin,190px);min-height:min(56vw,53vmin,253px);aspect-ratio:auto;border-radius:6px 14px 14px 6px;color:#fff;padding:14px;display:flex;flex-direction:column;justify-content:space-between;box-shadow:inset 10px 0 0 rgba(0,0,0,.18),0 4px 10px rgba(0,0,0,.25);border:none;text-align:left}
.book b{font-size:clamp(17px,4vmin,26px);hyphens:auto;overflow-wrap:break-word}.book small{font-size:clamp(13px,2.6vmin,17px);opacity:.9}
.book.soon{filter:grayscale(.7);opacity:.6}
.book .bp{font-size:clamp(14px,3vmin,19px);font-weight:bold;background:rgba(0,0,0,.35);border-radius:8px;padding:4px 8px;align-self:flex-start}
.book.cur{outline:5px solid #ffd166;outline-offset:3px;animation:pulse 1.6s infinite}
.map{display:grid;grid-template-columns:repeat(auto-fill,minmax(min(22vmin,120px),1fr));grid-auto-rows:min(24vmin,120px);gap:12px;overflow-y:auto;padding:6px;align-content:start}
.tile{height:100%;min-height:0;border-radius:18px;display:flex;flex-direction:column;align-items:center;justify-content:center;font-size:clamp(22px,6vmin,38px);padding:4px}
.tile .st{font-size:clamp(14px,3vmin,20px);color:#e0a000;letter-spacing:2px}
.tile.next{background:var(--hi);border-color:var(--accent);animation:pulse 1.4s infinite}
.tile.locked{opacity:.35}
.jump{display:flex;align-items:center;gap:8px;flex-wrap:wrap;margin:6px 0;font-size:clamp(16px,3.4vmin,22px)}
.jump select{flex:1;min-width:0;max-width:100%;font:inherit;padding:8px;background:var(--card);color:var(--ink);border:2px solid var(--line);border-radius:12px}
.tile.rev{font-size:clamp(16px,3.6vmin,24px)}
@keyframes pulse{50%{transform:scale(1.05)}}
.top{display:flex;align-items:center;gap:8px}
.top .t{flex:1;text-align:center;font-size:clamp(18px,4vmin,28px)}
.steps{display:flex;gap:6px;justify-content:center;margin:4px 0}
.steps i{width:clamp(18px,4vmin,28px);height:clamp(18px,4vmin,28px);border-radius:50%;border:3px solid var(--soft);font-style:normal;font-size:12px;display:flex;align-items:center;justify-content:center}
.steps i.done{background:var(--good);border-color:var(--good)}.steps i.cur{border-color:var(--accent);background:var(--hi)}
.cards{display:flex;flex-wrap:wrap;gap:12px;justify-content:center;align-content:center;height:100%}
.card{min-width:20vmin;font-size:clamp(34px,10vmin,72px);padding:8px 18px;border-radius:16px;background:var(--card)}
.card.letter{color:var(--accent)}
.card.ok{background:var(--good);color:#fff;border-color:var(--good)}.card.no{animation:shake .4s}
@keyframes shake{25%{transform:translateX(-8px)}75%{transform:translateX(8px)}}
.pic{font-size:clamp(40px,12vmin,90px);text-align:center;line-height:1.1}
.pic small{display:block;font-size:14px;color:var(--soft)}
.pic .plate{display:block;margin:0 auto;max-width:min(92%,380px);max-height:42vh;border-radius:8px}
.text{display:flex;flex-direction:column;align-items:center;gap:1.4vmin;overflow-y:auto;height:100%;justify-content:center}
.ln{font-size:clamp(26px,7vmin,52px);line-height:1.2;padding:2px 10px;border-radius:10px}
.ln.cur{background:var(--hi)}
.w{display:inline-block;padding:0 4px;border-radius:8px}
.w.hi{background:var(--accent);color:#fff}.w.ok{color:var(--good);text-decoration:underline 4px}.w.miss{color:var(--bad);text-decoration:underline wavy 3px}
canvas{position:absolute;inset:0;width:100%;height:100%;touch-action:none;border-radius:14px}
.paper{background:#1a1a1a;border:3px solid var(--line);border-radius:14px}
.hint{font-size:clamp(15px,3.2vmin,20px);color:var(--soft);text-align:center;min-height:1.4em}
.hint .es{color:#e9b872}
.toast{position:fixed;left:50%;top:40%;transform:translate(-50%,-50%);background:#2a2a2a;border:3px solid var(--accent);color:#fff;padding:18px 28px;border-radius:18px;font-size:clamp(24px,6vmin,40px);display:none;z-index:9;text-align:center}
.stars{font-size:clamp(40px,12vmin,90px);color:#e0a000;text-align:center;letter-spacing:6px}
.tale-open{text-align:center;font-size:clamp(16px,3.6vmin,24px);color:#9ad;margin:1em auto;max-width:34em}
.gallery{display:flex;flex-wrap:wrap;gap:8px;justify-content:center;overflow-y:auto}
.gallery img{width:min(44vw,260px);border-radius:8px;border:3px solid var(--board)}
.mic{width:clamp(80px,20vmin,130px);height:clamp(80px,20vmin,130px);border-radius:50%;font-size:clamp(36px,9vmin,60px);background:var(--card)}
.mic.live{background:var(--bad);color:#fff;animation:pulse 1s infinite}
.parent{font-size:15px;color:var(--soft)}
.so{position:fixed;inset:0;background:rgba(10,10,10,.92);display:flex;flex-direction:column;align-items:center;justify-content:center;z-index:30;gap:4vmin}
.sow{display:flex;gap:1.5vmin;flex-wrap:wrap;justify-content:center}
.sow span{font-size:clamp(56px,16vmin,140px);font-family:Georgia,serif;color:var(--ink);padding:0 .12em;border-radius:14px;border:4px solid transparent;transition:background .45s,border-color .45s,transform .45s}
.sow span.multi{color:#ff5a5a}
.sow span.silent{color:#777}
.sow span.on{background:var(--hi);border-color:#ffd166;transform:scale(1.12)}
.w{-webkit-touch-callout:none}
</style>
</head><body>

<section id="home" class="screen on">
  <h1>ABC Books</h1>
  <h2>Who is reading?</h2>
  <div class="row kids" id="kids"></div>
  <div class="hint" id="whoHint"></div>
  <div class="shelf" id="shelf"></div>
  <div class="row" style="margin-top:auto"><button class="ghost parent" id="speedBtn">Voice: normal</button><button class="ghost parent" id="origBtn" hidden>Spanish stories: gentle words</button><button class="ghost parent" id="flagBtn" hidden>Flagged tales: left out</button><button class="ghost parent" id="insBtn" hidden>Spanish book instructions: English + Spanish</button><button class="ghost parent" id="toGallery">Blackboard pictures</button><a class="parent" href="check.html">Tablet check</a><a class="parent" href="/account/">Grown-ups: account</a><a class="parent" href="/math/">Math</a><a class="parent" href="/">About</a></div>
</section>

<section id="tales" class="screen">
  <div class="top"><button onclick="App.go('home')" aria-label="Back to the books">โ—€</button><div class="t" id="talesTitle">Fairy Tales</div></div>
  <div class="shelf grow" id="taleShelf"></div>
</section>

<section id="map" class="screen">
  <div class="top"><button onclick="App.back()">โ—€</button><div class="t" id="mapTitle"></div></div>
  <div class="jump"><label for="jumpSel" id="jumpLbl">Go to lesson</label><select id="jumpSel"></select><button id="jumpGo">Go</button></div>
  <div class="map grow" id="tiles"></div>
</section>

<section id="lesson" class="screen">
  <div class="top"><button onclick="App.leave()">โ—€</button><div class="t" id="lesTitle"></div><button id="sayBtn" title="Say it again">๐Ÿ”Š</button></div>
  <div class="steps" id="steps"></div>
  <h2 id="stepTitle"></h2>
  <div class="grow" id="stage"></div>
  <div class="hint" id="hint"></div>
  <div class="row" id="controls"></div>
</section>

<section id="gallery" class="screen">
  <div class="top"><button onclick="App.go('home')">โ—€</button><div class="t">Blackboard pictures</div></div>
  <div class="gallery grow" id="gal"></div>
</section>

<div class="toast" id="toast"></div>
<script src="hershey.js"></script>
<script src="trace.js"></script>
<script src="/account/stats.js"></script>
<script src="/account/sync.js"></script>
<script src="app.js"></script>
<script>if ('serviceWorker' in navigator) navigator.serviceWorker.register('sw.js').catch(() => {});</script>
</body></html>
EOF

sw.js: offline support, now also keeps the Grimm book.

cat > /root/abcbooks-rebuild/sw.js <<'EOF'
// Offline support. App files: network first (so updates show), cached copy when offline.
// Voice clips (audio/*.mp3) never change for a given name: cache first, saved the first time they play.
// Other apps share this origin (Ray's Arithmetic at /math/ with its own 'rays-*' caches and its own SW),
// so only touch 'abc-' caches and leave /rays/ requests alone.
// The readers moved from abcbooks.fyi/ to abcbooks.fyi/readers/ (the welcome page is at / now). This same file still
// answers at /sw.js, so a device with the old whole-site worker gets this one there, and it removes itself.
const SHELL = 'abc-shell-v58', CLIPS = 'abc-clips-v1';
const RETIRED = location.hostname === 'abcbooks.fyi' && new URL(self.registration.scope).pathname === '/';
if (RETIRED) {
  self.addEventListener('install', () => self.skipWaiting());
  self.addEventListener('activate', e => e.waitUntil(self.registration.unregister()));
} else {
  const FILES = ['./', 'index.html', 'app.js', 'prompts.json', 'trace.js', 'hershey.js', 'books/primer1881.json', 'audio/primer1881.json', 'books/first1879.json', 'audio/first1879.json', 'books/second1879.json', 'audio/second1879.json', 'books/third1879.json', 'audio/third1879.json', 'books/fourth1879.json', 'audio/fourth1879.json', 'books/fifth1879.json', 'audio/fifth1879.json', 'books/sixth1879.json', 'audio/sixth1879.json', 'books/spell1867.json', 'audio/spell1867.json', 'books/grimm1884.json', 'audio/grimm1884.json', 'books/silabario1861.json', 'audio/silabario1861.json', 'instructions-es.json', 'phonics.json', 'icon-192.png', 'manifest.webmanifest'];
  // one file at a time: a book that isn't on this server (a rebuild without the Spanish book) mustn't stop the rest
  self.addEventListener('install', e => { e.waitUntil(caches.open(SHELL).then(c => Promise.all(FILES.map(f => c.add(f).catch(() => {})))).then(() => self.skipWaiting())); });
  self.addEventListener('activate', e => {
    e.waitUntil(caches.keys().then(ks => Promise.all(ks.filter(k => k.startsWith('abc-') && k !== SHELL && k !== CLIPS).map(k => caches.delete(k)))).then(() => self.clients.claim()));
  });
  self.addEventListener('fetch', e => {
    const r = e.request, u = new URL(r.url);
    // the account service (/account/, CT 308) and the reading check (/api/) always go to the network; only sync.js is kept for offline
    if (r.method !== 'GET' || u.origin !== location.origin || /\/(rays|math)(\/|$)/.test(u.pathname)) return;
    if (/^\/api\//.test(u.pathname) || (/^\/account(\/|$)/.test(u.pathname) && u.pathname !== '/account/sync.js')) return;
    if (r.url.endsWith('.mp3')) {
      e.respondWith(caches.open(CLIPS).then(c => c.match(r).then(hit => hit || fetch(r).then(res => { if (res.ok && res.status === 200) c.put(r, res.clone()); return res; }))));
      return;
    }
    e.respondWith(fetch(r).then(res => { if (res.ok) caches.open(SHELL).then(c => c.put(r, res.clone())); return res; }).catch(() => caches.match(r)));
  });
}
EOF

3. Make the lesson file

PC (PowerShell). It prints “211 tales (0 legends), 282200 words, 36 pictures” and the list of tales:

powershell -ExecutionPolicy Bypass -File C:\ABCBooks\tools\split-grimm.ps1

It prints the lesson and line count (985 lessons after the fifth batch) and one row per part (words, longest line, picture):

powershell -ExecutionPolicy Bypass -File C:\ABCBooks\tools\make-book.ps1 -Book grimm1884

4. Record it with Eloquence

PC (PowerShell). The first batch was about 8,600 recordings (both speeds), about 15 minutes (sound-outs 1 minute, sending them to CT 306 (abc-web) about 3 minutes). The second batch only recorded what was new: 1,726 per speed in 4 minutes, 71 sound-out words in half a minute, sent in under 2 minutes. The third batch: 7,193 new per speed and 298 new sound-out words, in one longer run (start it and come back later). The fourth: 11,521 new per speed and 476 new sound-out words, about 40 minutes; the audio for 90 tales is about 1 GB on CT 306. The fifth: 20,355 new per speed and 778 sound-out words, about 2 hours; all 211 tales are about 1.9 GB, so CT 306’s disk was grown from 8 to 12 GB first (pct resize 306 rootfs +4G on the Proxmox host).

powershell -ExecutionPolicy Bypass -File C:\ABCBooks\tools\make-audio.ps1 -Book grimm1884

Sound-it-out clips for the new words (press and hold a word):

powershell -ExecutionPolicy Bypass -File C:\ABCBooks\tools\make-soundouts.ps1 -Book grimm1884

Send them to CT 306 (abc-web), then check nothing is missing:

powershell -ExecutionPolicy Bypass -File C:\ABCBooks\tools\push-audio.ps1 -Book grimm1884
powershell -ExecutionPolicy Bypass -File C:\ABCBooks\tools\check-audio.ps1 -Book grimm1884

5. Put it on the server

PC (PowerShell):

powershell -ExecutionPolicy Bypass -File C:\ABCBooks\deploy.ps1

Open https://abcbooks.fyi/readers/, pick a name, and tap the dark red Grimm’s Fairy Tales book: the Fairy Tales page shows 210 dark red books (211 when a grown-up includes the flagged tale), one per tale, from “Tale 1 of 211” to “Tale 211 of 211”. The Frog-King, or Iron Henry opens a map of its 5 parts; Part 1 shows the first Rackham picture in Listen.

Troubleshooting

The logs and the Tablet check page are the same as in the Primer post.

  • “pdftotext” not found: install Poppler (step 1) and open a new PowerShell window. split-grimm.ps1 looks for pdftotext.exe under %LOCALAPPDATA%\Microsoft\WinGet\Packages.
  • Fewer than 211 tales: a title the script didn’t see as a heading. Read the list it prints, then look at that page in source\grimm\maplewood.txt (pages are split by form feeds).
  • Words stuck together (“kitchenwench”): pdftotext drops the hyphen of a word broken over two lines. split-grimm.ps1 puts it back when the book writes the word with a hyphen elsewhere, or when it is in its short hand list ($extra); add the word there and run it again.
  • “Tale not found in grimm.txt”: a title in pick doesn’t match the “= Title” line in source\grimm.txt exactly (hyphens matter: “The Frog-King, or Iron Henry”).
  • No picture: the tale has no plate in this edition, or public\pics\grimm\ wasn’t deployed; check https://abcbooks.fyi/readers/pics/grimm/rackham-01.jpg.
  • A tale missing from the Fairy Tales page: the page lists every different tale in public\books\grimm1884.json. Check the tale is in pick, rebuild (step 3) and deploy; on the tablet, close and reopen the app so the new service worker (sw.js SHELL version) takes over.

Notes

  • All 211 tales. Tale 110 (The Jew Among Thorns) is antisemitic, so it is flagged: flag in make-book.ps1 puts L.flag on its lessons, and the app leaves flagged tales off the Fairy Tales page until a grown-up taps Flagged tales (1): left out on the home screen (next to the Spanish wording switch). It asks first, naming the tale and why, then says included; tap again to leave it out. The setting is per device, like the other grown-up switches. Its card then says “Flagged for grown-ups”. More go in by adding titles to the END of pick in make-book.ps1 (in the middle would renumber the lessons after it and move kids’ stars), plus an emoji in emoji, then steps 3 to 5 again (only new clips are recorded and sent). The BlockCraft Fairy Tale Kingdom has a place for every tale but 110 (210 places, the last 195 built from templates on 25 October). The KINGDOM list in app.js (tales whose stars screen promises a place) now holds all 210 titles, copied from BlockCraft’s TALES; Tale 110 is not in it.
  • Book cards on phones (25 October): long titles like “The Story of the Youth Who Went Forth to Learn What Fear Was” (and the McGuffey book names) did not fit the small cards on an upright phone. In index.html, .book is now width:min(42vw,40vmin,190px) with a min-height instead of a fixed aspect-ratio, so on a phone the cards are wider and a card grows taller when its title needs it; tablet and PC sizes did not change. Checked: no card overflows on a phone upright or sideways, a tablet or a PC.
  • BlockCraft side: done, see the Fairy Tale Kingdom: finishing a whole tale here opens that tale’s place, with a story stone, a quest, a keepsake and a place kit.
  • The Children’s Legends (the last 10 pieces in the PDF, Tales 202 to 211) are in the book like the other tales; they aren’t marked as legends.