Explain the anatomy of pelvis and perineum

Reading File
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Reading File
Reading File
Reading File
Reading File
Searching Images

pelvis anatomy bony structure pelvic inlet outlet

Searching Images

perineum triangles urogenital anal anatomy

Loading Image
Loading Image
Reading File
Loading Image
Loading Image
Reading File
Finding Sources
Finding Sources
Reading File
Loading Image
I now have comprehensive material from Gray's Anatomy for Students, the THIEME Atlas, and supporting images. Let me compile the full, well-structured answer.

Anatomy of the Pelvis and Perineum

Based on Gray's Anatomy for Students, THIEME General Anatomy & Musculoskeletal System, and Campbell-Walsh-Wein Urology

1. The Bony Pelvis

The pelvis is a basin-shaped ring of bone formed by four bones:
  • Two hip (coxal) bones — each comprising the ilium, ischium, and pubis, fused at the acetabulum
  • The sacrum — formed by the 5 fused sacral vertebrae
  • The coccyx — 4 fused coccygeal vertebrae

Key Bony Landmarks

LandmarkRelevance
Iliac crestHighest point of the ilium; palpable along the full length
Anterior superior iliac spine (ASIS)Origin of inguinal ligament; clinical landmark
Posterior superior iliac spine (PSIS)Overlies the sacroiliac joint
Ischial tuberosityWeight-bearing when seated; corner of the diamond-shaped perineum
Ischial spineAttachment of sacrospinous ligament; landmark for pudendal nerve block
Pubic symphysisFibrocartilaginous joint anteriorly; anterior limit of perineum
Pubic tubercleAttachment of inguinal ligament
Sacral promontoryUpper anterior edge of sacrum; posterior limit of pelvic inlet

Pelvic Inlet and Outlet

  • Pelvic inlet (superior pelvic aperture): bounded by the sacral promontory posteriorly, the arcuate line of the ilium laterally, and the pubic symphysis anteriorly. The inlet faces anterosuperiorly.
  • Pelvic outlet (inferior pelvic aperture): bounded by the coccyx posteriorly, ischial tuberosities laterally, and pubic symphysis anteriorly. It is closed by the pelvic floor.

True vs. False Pelvis

  • False (greater) pelvis: above the pelvic inlet; part of the abdominal cavity, contains lower abdominal viscera
  • True (lesser) pelvis: below the pelvic inlet; contains the pelvic viscera (bladder, rectum, reproductive organs)

Sexual Dimorphism

FeatureFemaleMale
Pelvic inletRound/oval (gynecoid)Heart-shaped
Pelvic outletWiderNarrower
Subpubic angle>80° (often ~100°)~70°
SacrumShorter, broader, less curvedLonger, narrower, more curved
Overall shapeShallow and wideDeep and narrow
Lateral view of the pelvic area showing the pelvic inlet, urogenital triangle, and anal triangle in female (A) and male (B)
Lateral view showing the pelvic inlet, urogenital triangle, and anal triangle (A: female, B: male) — Gray's Anatomy for Students, p.600

2. Joints of the Pelvis

  • Pubic symphysis: secondary cartilaginous (fibrocartilaginous) joint; slightly mobile, especially in pregnancy
  • Sacroiliac (SI) joints: synovial joints anteriorly, syndesmosis posteriorly; transmit trunk weight to the lower limbs
  • Sacrococcygeal joint: fibrocartilaginous; slight flexion/extension

Ligaments

  • Sacrotuberous ligament: sacrum/coccyx → ischial tuberosity; converts the greater and lesser sciatic notches into foramina
  • Sacrospinous ligament: sacrum → ischial spine; landmark for pudendal nerve block
  • Iliolumbar ligament: L4–L5 transverse processes → iliac crest; stabilises the lumbosacral junction

3. Pelvic Walls and Floor

Lateral Wall Muscles

MuscleOriginInsertionAction
Obturator internusInner surface of obturator membraneGreater trochanterLateral rotation of thigh
PiriformisAnterior sacrumGreater trochanterLateral rotation; abduction of flexed thigh
Both help form the lateral walls of the pelvic cavity and serve as important landmarks for pelvic nerves and vessels.

Pelvic Diaphragm (Pelvic Floor)

The pelvic diaphragm is a hammock-shaped musculofascial sheet that closes the pelvic outlet (except for the urogenital hiatus anteriorly). It consists of:
Levator ani — the most important component, made of three parts:
  • Puborectalis: origin — superior pubic ramus on both sides; insertion — loops around the anorectal junction, forming the anorectal angle (~90°); critical for fecal continence; innervation — pudendal nerve and sacral plexus (S2–S4)
  • Pubococcygeus: pubis → anococcygeal ligament and coccyx; innervation — pudendal nerve (S2–S4)
  • Iliococcygeus: tendinous arch of the obturator fascia → iliococcygeal raphe and coccyx; innervation — pudendal nerve (S2–S4)
Coccygeus (ischiococcygeus): ischial spine → inferior sacrum and coccyx; innervation — sacral plexus (S4–S5); completes the pelvic diaphragm posteriorly
Function of the pelvic diaphragm: supports pelvic organs against intra-abdominal pressure; controls urinary/fecal continence; contributes to the birth canal during labour.

4. Pelvic Viscera

Urinary Bladder

  • Lies in the retropubic space (space of Retzius) posterosuperior to the pubic symphysis
  • Has four parts: apex, body, fundus, and neck
  • The neck is continuous with the urethra; in males, it is closely related to the prostate
  • Peritoneum covers the superior surface; the posterior surface is separated from the rectum (in males) by the rectovesical pouch or from the uterus (in females) by the vesicouterine pouch

Urethra

  • Female urethra: ~4 cm long; short, straight course inferiorly through the pelvic floor directly into the perineum (vestibule)
  • Male urethra: ~20 cm long; divided into prostatic, membranous, and spongy portions; passes through the prostate, the deep perineal pouch/perineal membrane, and then through the erectile tissues of the penis. Has a fixed anterior angle at the perineal membrane and a mobile angle in the penile shaft

Rectum and Anal Canal

  • The rectum begins at the rectosigmoid junction (S3 level) and follows the sacral curve
  • Three lateral flexures create the Houston's valves
  • The rectum becomes the anal canal as it passes through the pelvic floor; the anorectal angle (~90°) maintained by puborectalis is key for continence
  • The anal canal has an internal anal sphincter (smooth muscle; involuntary) and external anal sphincter (striated; voluntary; innervated by pudendal nerve S2–S4)

Reproductive Organs

Male:
  • Prostate: sits at the neck of the bladder, encircles the urethra; ~3 cm long; has three zones (peripheral, central, transitional); surrounded by a fascial capsule; closely related to the rectum posteriorly (basis of digital rectal exam)
  • Seminal vesicles: lie posterior to the bladder, superior to the prostate; join with the vas deferens to form the ejaculatory ducts which pass through the prostate to open into the prostatic urethra at the verumontanum
  • Vas deferens: enters the pelvis via the deep inguinal ring, crosses the ureter ("water under the bridge"), and joins the seminal vesicle
Female:
  • Uterus: lies in the lesser pelvis between the bladder and rectum; consists of fundus, body, isthmus, and cervix; normally anteverted and anteflexed; supported by the broad, round, uterosacral, and cardinal ligaments
  • Broad ligament: a double layer of peritoneum flanking the uterus; contains the fallopian tube (in the mesosalpinx), the round ligament (in the mesometrium), and the ovary (attached by the mesovarium)
  • Uterosacral ligaments: uterine cervix → sacrum; maintain cervical position
  • Cardinal ligaments (Mackenrodt's): cervix/upper vagina → lateral pelvic wall; main support against uterine prolapse
  • Ovaries: lie in the ovarian fossa (lateral pelvic wall, below the bifurcation of the common iliac artery); attached to the uterus by the ovarian ligament and to the pelvic wall by the suspensory ligament of the ovary (infundibulopelvic ligament), which carries the ovarian vessels

5. Pelvic Blood Supply

Arteries

The internal iliac artery (hypogastric artery) is the main supply to the pelvic viscera and walls. It arises from the common iliac artery at the level of the sacroiliac joint (L4–L5 disc level) and divides into:
Anterior division:
  • Superior vesical artery → upper bladder, proximal ureter
  • Inferior vesical artery (males) / vaginal artery (females) → bladder base, prostate/vagina
  • Obturator artery → medial thigh muscles
  • Internal pudendal artery → perineum (crosses through lesser sciatic foramen, runs in Alcock's canal)
  • Inferior gluteal artery → gluteal muscles
  • Uterine artery (females) → uterus; crosses the ureter at the base of the broad ligament ("water under the bridge")
  • Middle rectal artery → middle rectum
Posterior division:
  • Iliolumbar artery
  • Lateral sacral arteries
  • Superior gluteal artery (largest branch)
The ovarian/testicular arteries arise directly from the aorta (L2 level) and enter the pelvis via the infundibulopelvic ligament.

Venous Drainage

  • Pelvic venous plexuses (vesical, prostatic, uterovaginal, rectal) drain into the internal iliac veins
  • The prostatic venous plexus (of Santorini) connects with the vertebral venous plexus — a route for prostate cancer metastasis

6. Pelvic Nerves

Lumbosacral Plexus

Formed by anterior rami of L4–S3; gives rise to:
  • Femoral nerve (L2–L4) — exits through greater sciatic foramen
  • Obturator nerve (L2–L4) — exits through obturator canal
  • Sciatic nerve (L4–S3) — largest nerve; exits below piriformis through greater sciatic foramen
  • Superior gluteal nerve (L4–S1) — above piriformis
  • Inferior gluteal nerve (L5–S2) — below piriformis
  • Posterior cutaneous nerve of the thigh (S1–S3)

Pudendal Nerve (S2–S4)

The principal nerve of the perineum:
  1. Exits the pelvic cavity through the greater sciatic foramen (below piriformis)
  2. Crosses the ischial spine (landmark for pudendal block)
  3. Re-enters through the lesser sciatic foramen
  4. Runs in the pudendal canal (Alcock's canal) on the lateral wall of the ischiorectal fossa
  5. Branches: inferior rectal nerve, perineal nerve (superficial and deep branches), dorsal nerve of the penis/clitoris

Autonomic Innervation

  • Sympathetic: presacral nerve (superior hypogastric plexus) → hypogastric nerves → inferior hypogastric plexus; controls ejaculation, vasoconstriction
  • Parasympathetic: pelvic splanchnic nerves (S2–S4, "nervi erigentes") → inferior hypogastric plexus; controls erection, bladder detrusor contraction, rectal emptying
  • Inferior hypogastric (pelvic) plexus: paired plexuses on the lateral pelvic wall integrating sympathetic + parasympathetic input to all pelvic viscera

7. The Perineum

The perineum is the region inferior to the pelvic floor, between the thighs and buttocks. It is diamond-shaped and bounded by:
  • Anteriorly: pubic symphysis
  • Laterally: ischiopubic rami and ischial tuberosities
  • Posteriorly: tip of the coccyx
A transverse line between the two ischial tuberosities divides it into two triangles.
Diamond-shaped perineum in lithotomy position, showing urogenital and anal triangles with landmarks (pubic symphysis, ischial tuberosities, coccyx, perineal body) in male (A) and female (B)
Inferior view of the perineum (lithotomy position) showing the diamond shape divided into urogenital and anal triangles — Gray's Anatomy for Students, p.601

7a. Anal Triangle

  • Boundaries: transverse line between ischial tuberosities (base), coccyx (apex), sacrotuberous ligaments (sides)
  • Contents: anal aperture (anal canal), ischioanal (ischiorectal) fossa on each side
  • Ischioanal fossa: fat-filled wedge-shaped space bounded medially by the pelvic diaphragm, laterally by the obturator internus fascia. Contains the pudendal canal (with pudendal nerve and internal pudendal vessels). The fat allows expansion of the anal canal during defecation. Infections here → perianal abscess/fistula.

7b. Urogenital Triangle

  • Boundaries: pubic symphysis (apex), ischial tuberosities (base), ischiopubic rami (sides)
  • Contains the perineal membrane and the perineal pouches

Perineal Membrane

A tough fibromuscular sheet that spans the anterior perineum. It is pierced in males by the urethra; in females by the urethra and vagina.

Superficial Perineal Pouch (below the perineal membrane)

Contains the superficial perineal muscles and the erectile tissues:
StructureMaleFemale
IschiocavernosusCovers crura of penis; maintains erectionCovers crura of clitoris
BulbospongiosusSurrounds corpus spongiosum; assists ejaculationCovers vestibular bulb; narrows vaginal introitus
Superficial transverse perinealIschial tuberosity → perineal bodyIschial tuberosity → perineal body
Erectile tissueCorpora cavernosa + corpus spongiosumClitoris + vestibular bulbs
GlandsBulbourethral (Cowper's) glands (in deep pouch)Greater vestibular (Bartholin's) glands
All superficial perineal muscles are innervated by the perineal branch of the pudendal nerve (S2–S4).

Deep Perineal Pouch (above the perineal membrane, within the urogenital diaphragm)

Contains:
  • Deep transverse perineal muscle: stabilises the perineal body
  • Sphincter urethrae (external urethral sphincter): voluntary control of micturition
  • In males: bulbourethral (Cowper's) glands open into the spongy urethra
  • In females: sphincter urethrovaginalis surrounds both urethra and vagina
  • Urethra (and vagina in females) pass through this space
Inferior view of the female pelvis showing the perineal muscles: bulbospongiosus, ischiocavernosus, superficial transverse perineal, levator ani, external anal sphincter, and perineal body
Inferior view of the female pelvis showing perineal musculature — Gray's Anatomy for Students

7c. Perineal Body (Central Tendon of the Perineum)

A poorly defined fibromuscular node at the midpoint of the transverse line between the ischial tuberosities. It is the critical structural crossroads of the perineum where the following converge:
  • Levator ani (pelvic diaphragm)
  • Bulbospongiosus
  • Superficial and deep transverse perineal muscles
  • External anal sphincter
  • (in females) perineal fibers of the rectovaginal septum
The perineal body is critical for pelvic floor integrity. Its disruption during childbirth (perineal tear or episiotomy) can lead to pelvic organ prolapse and fecal/urinary incontinence.

7d. External Genitalia

Male:
  • Penis: composed of two corpora cavernosa (dorsal; erectile) and corpus spongiosum (ventral; contains urethra); covered by skin
  • Scrotum: contains testes, epididymides, spermatic cords; temperature regulation via the cremaster muscle
  • Root of the penis: anchored in the perineum (crura, attached to ischiopubic rami; bulb, attached to perineal membrane)
Female (Vulva):
  • Mons pubis: fatty elevation over the pubic symphysis
  • Labia majora: homologous to the male scrotum
  • Labia minora: enclose the vestibule
  • Vestibule: space into which the urethra and vagina open; contains the openings of the greater vestibular (Bartholin's) glands
  • Clitoris: erectile structure (two crura + glans); homologous to the penis; highly innervated by the dorsal nerve of the clitoris

8. Dissection Image — Superficial Perineal Muscles (Male)

Anatomical dissection of the male perineum showing bulbospongiosus (Bs), ischiocavernosus (Ic), superficial transverse perineal muscle (STP), ischial tuberosity (IT), ischiopubic ramus (IPR), and external anal sphincter (EAS)
Cadaveric dissection of the male perineum showing bulbospongiosus (Bs), ischiocavernosus (Ic), superficial transverse perineal muscle (STP), ischial tuberosity (IT), and external anal sphincter (EAS)

Summary: Pelvic Floor Muscles at a Glance

MuscleOriginInsertionInnervationFunction
PuborectalisSuperior pubic ramus (bilateral)Loop around anorectal junctionPudendal / S2–S4Maintains anorectal angle; continence
PubococcygeusPubis (lateral)Anococcygeal ligament, coccyxPudendal / S2–S4Supports pelvic floor
IliococcygeusTendinous arch of obturator fasciaIliococcygeal raphe, coccyxPudendal / S2–S4Supports pelvic floor
CoccygeusIschial spineInferior sacrum, coccyxS4–S5Flexes coccyx; supports floor
Ext. anal sphincterAnococcygeal ligamentPerineal bodyPudendal / S2–S4Voluntary fecal continence
Ext. urethral sphincterPerineal membraneEncircles urethraPudendal / S2–S4Voluntary urinary continence
BulbospongiosusPerineal bodyPenile raphe / clitorisPudendal / S2–S4Ejaculation; narrows introitus
IschiocavernosusIschiopubic ramusCorpus cavernosumPudendal / S2–S4Maintains erection
Superficial transverse perinealIschial tuberosityPerineal bodyPudendal / S2–S4Stabilises perineal body
Deep transverse perinealIschiopubic ramusPerineal bodyPudendal / S2–S4Stabilises perineal body

Clinical Correlates

ConditionAnatomical Basis
Pudendal nerve blockInjection near sacrospinous ligament at the ischial spine; anesthetises the entire perineum
EpisiotomyIncision of the perineal body during childbirth; must avoid injuring the external anal sphincter
Pelvic organ prolapseWeakness of levator ani and cardinal/uterosacral ligaments; uterus, bladder, or rectum may herniate into vagina
Benign prostatic hyperplasiaEnlargement of the transitional zone of prostate; compresses urethra
Ectopic ureterUreter opens distal to the internal urethral sphincter → incontinence
Perianal abscessInfection of the ischioanal fat pad
Ureteric injury in surgeryMost common site: where uterine artery crosses over the ureter near the cervix ("water under the bridge")

Sources: Gray's Anatomy for Students (Elsevier, 9780323934237), THIEME Atlas of Anatomy: General Anatomy & Musculoskeletal System (9781626237186), Campbell-Walsh-Wein Urology (9780323546423)

Convert it into hand written notes or downloadable file format

Reading File
Running Command

ls /home/daytona/workspace/ 2>/dev/null || echo "workspace empty or not found"

Running Command

mkdir -p /home/daytona/workspace/pelvis-notes && python3 -c "import reportlab; print('reportlab ok')" && python3 -c "from reportlab.lib.pagesizes import A4; print('A4 ok')"

Running Command

python3 -c " import urllib.request, os # Try to download a free handwriting font url = 'https://github.com/google/fonts/raw/main/ofl/caveat/Caveat-Regular.ttf' try: urllib.request.urlretrieve(url, '/home/daytona/workspace/pelvis-notes/Caveat-Regular.ttf') print('font downloaded') except Exception as e: print('font download failed:', e) "

Running Command

# Try multiple font sources python3 -c " import urllib.request fonts = [ ('https://github.com/googlefonts/caveat/raw/main/fonts/ttf/Caveat-Regular.ttf', '/home/daytona/workspace/pelvis-notes/Caveat-Regular.ttf'), ('https://github.com/googlefonts/caveat/raw/main/fonts/ttf/Caveat-Bold.ttf', '/home/daytona/workspace/pelvis-notes/Caveat-Bold.ttf'), ] for url, path in fonts: try: urllib.request.urlretrieve(url, path) print(f'Downloaded: {path}') except Exception as e: print(f'Failed {url}: {e}') "

Writing File

~/pelvis-notes/generate_notes.py


from reportlab.lib.pagesizes import A4
from reportlab.lib.units import cm, mm
from reportlab.lib import colors
from reportlab.pdfgen import canvas
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
import os, textwrap

# Register handwriting fonts
pdfmetrics.registerFont(TTFont('Caveat', '/home/daytona/workspace/pelvis-notes/Caveat-Regular.ttf'))
pdfmetrics.registerFont(TTFont('CaveatBold', '/home/daytona/workspace/pelvis-notes/Caveat-Bold.ttf'))

PAGE_W, PAGE_H = A4
MARGIN_L = 2.8 * cm
MARGIN_R = 1.5 * cm
MARGIN_T = 2.2 * cm
MARGIN_B = 2.0 * cm
LINE_H = 0.72 * cm          # ruled-line spacing
CONTENT_W = PAGE_W - MARGIN_L - MARGIN_R

# Cream paper background
PAPER_COLOR  = colors.HexColor('#FEFAE8')
LINE_COLOR   = colors.HexColor('#A8C4E0')   # soft blue ruled lines
MARGIN_LINE  = colors.HexColor('#F4A0A0')   # red margin line
INK_COLOR    = colors.HexColor('#1A1A2E')   # dark navy "ink"
HEAD_COLOR   = colors.HexColor('#1B4F72')   # section heading colour
BOX_COLOR    = colors.HexColor('#D6EAF8')   # light-blue highlight boxes
STAR_COLOR   = colors.HexColor('#E74C3C')   # red stars / bullets
TAG_COLOR    = colors.HexColor('#27AE60')   # green tags

OUTPUT = '/home/daytona/workspace/pelvis-notes/Pelvis_and_Perineum_Notes.pdf'

c = canvas.Canvas(OUTPUT, pagesize=A4)
c.setTitle("Anatomy of the Pelvis & Perineum – Handwritten Notes")
c.setAuthor("Orris Medical Notes")

page_num = [0]
y_pos    = [0.0]

# ── helpers ────────────────────────────────────────────────────────────────

def draw_page_background():
    """Draw paper background + ruled lines + margin line."""
    c.setFillColor(PAPER_COLOR)
    c.rect(0, 0, PAGE_W, PAGE_H, fill=1, stroke=0)

    # Ruled horizontal lines
    c.setStrokeColor(LINE_COLOR)
    c.setLineWidth(0.3)
    y = PAGE_H - MARGIN_T
    while y > MARGIN_B:
        c.line(MARGIN_L - 0.5*cm, y, PAGE_W - MARGIN_R + 0.3*cm, y)
        y -= LINE_H

    # Red margin vertical line
    c.setStrokeColor(MARGIN_LINE)
    c.setLineWidth(0.8)
    c.line(MARGIN_L - 0.6*cm, MARGIN_B, MARGIN_L - 0.6*cm, PAGE_H - MARGIN_T)

    # Page number
    page_num[0] += 1
    c.setFont('Caveat', 10)
    c.setFillColor(colors.HexColor('#888888'))
    c.drawCentredString(PAGE_W / 2, MARGIN_B - 0.6*cm, f'— {page_num[0]} —')

    # Corner fold
    c.setFillColor(colors.HexColor('#EDE8D0'))
    c.setStrokeColor(colors.HexColor('#C8C0A0'))
    c.setLineWidth(0.4)
    fold = 0.6*cm
    path = c.beginPath()
    path.moveTo(PAGE_W - fold, PAGE_H)
    path.lineTo(PAGE_W, PAGE_H - fold)
    path.lineTo(PAGE_W, PAGE_H)
    path.close()
    c.drawPath(path, fill=1, stroke=1)

def new_page():
    c.showPage()
    draw_page_background()
    y_pos[0] = PAGE_H - MARGIN_T - LINE_H * 0.5

def ensure_space(needed_cm):
    if y_pos[0] - needed_cm * cm < MARGIN_B + 0.3*cm:
        new_page()

def move_down(lines=1):
    y_pos[0] -= LINE_H * lines

# ── text writers ───────────────────────────────────────────────────────────

def write_title(text, size=22, extra_before=0, extra_after=0.5):
    ensure_space((extra_before + extra_after + 1) * LINE_H / cm + 0.8)
    move_down(extra_before)
    c.setFillColor(HEAD_COLOR)
    c.setFont('CaveatBold', size)
    c.drawString(MARGIN_L, y_pos[0], text)
    # underline
    tw = c.stringWidth(text, 'CaveatBold', size)
    c.setStrokeColor(HEAD_COLOR)
    c.setLineWidth(1.2)
    c.line(MARGIN_L, y_pos[0] - 2, MARGIN_L + tw, y_pos[0] - 2)
    move_down(1 + extra_after)

def write_h1(text):
    """Big section heading with coloured banner."""
    ensure_space(1.5)
    move_down(0.6)
    # banner
    c.setFillColor(colors.HexColor('#D6EAF8'))
    c.rect(MARGIN_L - 0.3*cm, y_pos[0] - 0.18*cm,
           CONTENT_W + 0.6*cm, 0.65*cm, fill=1, stroke=0)
    c.setFillColor(HEAD_COLOR)
    c.setFont('CaveatBold', 15)
    c.drawString(MARGIN_L, y_pos[0], text)
    move_down(1.2)

def write_h2(text):
    ensure_space(1.2)
    move_down(0.4)
    c.setFillColor(colors.HexColor('#1E8449'))
    c.setFont('CaveatBold', 13)
    c.drawString(MARGIN_L, y_pos[0], '▸  ' + text)
    # small underline
    tw = c.stringWidth('▸  ' + text, 'CaveatBold', 13)
    c.setStrokeColor(colors.HexColor('#82E0AA'))
    c.setLineWidth(0.6)
    c.line(MARGIN_L, y_pos[0] - 2, MARGIN_L + tw, y_pos[0] - 2)
    move_down(1.1)

def write_h3(text):
    ensure_space(1.0)
    move_down(0.3)
    c.setFillColor(colors.HexColor('#7D3C98'))
    c.setFont('CaveatBold', 12)
    c.drawString(MARGIN_L + 0.2*cm, y_pos[0], '◆ ' + text)
    move_down(1.0)

def write_body(text, indent=0, size=11.5, color=INK_COLOR, bold=False):
    font = 'CaveatBold' if bold else 'Caveat'
    c.setFont(font, size)
    max_w = CONTENT_W - indent * cm
    # wrap
    avg_char = size * 0.55
    chars_per_line = int(max_w / avg_char)
    lines = []
    for para in text.split('\n'):
        if para.strip() == '':
            lines.append('')
        else:
            wrapped = textwrap.wrap(para, width=max(30, chars_per_line))
            lines.extend(wrapped if wrapped else [''])
    for line in lines:
        ensure_space(LINE_H / cm + 0.1)
        c.setFillColor(color)
        c.setFont(font, size)
        c.drawString(MARGIN_L + indent * cm, y_pos[0], line)
        move_down(1)

def write_bullet(text, level=0, symbol='•', color=INK_COLOR, bold=False):
    indent_base = 0.3 + level * 0.5
    sym_x = MARGIN_L + indent_base * cm
    text_x = sym_x + 0.45 * cm
    font = 'CaveatBold' if bold else 'Caveat'
    size = 11.5
    c.setFont(font, size)
    max_w = CONTENT_W - indent_base * cm - 0.45 * cm
    avg_char = size * 0.55
    chars_per_line = max(30, int(max_w / avg_char))
    wrapped = textwrap.wrap(text, width=chars_per_line)
    if not wrapped:
        wrapped = ['']
    # first line with symbol
    ensure_space(LINE_H / cm + 0.1)
    c.setFillColor(STAR_COLOR if symbol in ('★','✦','→') else colors.HexColor('#2471A3'))
    c.setFont('CaveatBold', size)
    c.drawString(sym_x, y_pos[0], symbol)
    c.setFillColor(color)
    c.setFont(font, size)
    c.drawString(text_x, y_pos[0], wrapped[0])
    move_down(1)
    for cont_line in wrapped[1:]:
        ensure_space(LINE_H / cm + 0.1)
        c.setFillColor(color)
        c.setFont(font, size)
        c.drawString(text_x, y_pos[0], cont_line)
        move_down(1)

def write_note_box(lines_list, box_color=BOX_COLOR, title=None):
    """Highlighted sticky-note style box."""
    needed = (len(lines_list) + (1 if title else 0) + 1) * LINE_H + 0.4*cm
    ensure_space(needed / cm + 0.2)
    move_down(0.3)
    box_h = needed
    box_y = y_pos[0] - box_h + LINE_H
    c.setFillColor(box_color)
    c.setStrokeColor(colors.HexColor('#85C1E9'))
    c.setLineWidth(0.8)
    c.roundRect(MARGIN_L - 0.2*cm, box_y, CONTENT_W + 0.4*cm, box_h, 4, fill=1, stroke=1)
    if title:
        c.setFillColor(HEAD_COLOR)
        c.setFont('CaveatBold', 12)
        c.drawString(MARGIN_L + 0.1*cm, y_pos[0], '📌 ' + title)
        move_down(1)
    for line in lines_list:
        c.setFillColor(INK_COLOR)
        c.setFont('Caveat', 11)
        c.drawString(MARGIN_L + 0.3*cm, y_pos[0], line)
        move_down(1)
    move_down(0.5)

def write_table(headers, rows, col_widths=None):
    """Simple hand-drawn-style table."""
    n_cols = len(headers)
    if col_widths is None:
        col_widths = [CONTENT_W / n_cols] * n_cols

    row_h = LINE_H * 1.15
    header_h = LINE_H * 1.3
    total_h = header_h + row_h * len(rows) + 0.3*cm
    ensure_space(total_h / cm + 0.5)
    move_down(0.3)

    tbl_x = MARGIN_L
    tbl_y = y_pos[0]

    # Header row background
    c.setFillColor(colors.HexColor('#2E86C1'))
    c.rect(tbl_x, tbl_y - header_h + 0.05*cm,
           CONTENT_W, header_h, fill=1, stroke=0)

    # Header text
    x = tbl_x
    c.setFillColor(colors.white)
    c.setFont('CaveatBold', 11)
    for i, h in enumerate(headers):
        c.drawString(x + 0.15*cm, tbl_y - header_h + 0.25*cm, h)
        x += col_widths[i]

    cur_y = tbl_y - header_h

    # Data rows
    for r_idx, row in enumerate(rows):
        bg = colors.HexColor('#EBF5FB') if r_idx % 2 == 0 else colors.white
        c.setFillColor(bg)
        c.rect(tbl_x, cur_y - row_h + 0.05*cm, CONTENT_W, row_h, fill=1, stroke=0)
        x = tbl_x
        c.setFillColor(INK_COLOR)
        c.setFont('Caveat', 10.5)
        for i, cell in enumerate(row):
            # truncate if too wide
            max_chars = max(10, int(col_widths[i] / (10.5 * 0.52)))
            display = str(cell)
            if len(display) > max_chars:
                display = display[:max_chars-1] + '…'
            c.drawString(x + 0.12*cm, cur_y - row_h + 0.22*cm, display)
            x += col_widths[i]
        cur_y -= row_h

    # Outer border
    c.setStrokeColor(colors.HexColor('#2E86C1'))
    c.setLineWidth(1.0)
    c.rect(tbl_x, cur_y, CONTENT_W, tbl_y - cur_y, fill=0, stroke=1)

    # Column dividers
    c.setLineWidth(0.4)
    x = tbl_x
    for w in col_widths[:-1]:
        x += w
        c.line(x, tbl_y, x, cur_y)

    # Horizontal dividers
    c.setLineWidth(0.3)
    c.setStrokeColor(colors.HexColor('#A9CCE3'))
    tmp_y = tbl_y - header_h
    for _ in rows:
        tmp_y -= row_h
        c.line(tbl_x, tmp_y, tbl_x + CONTENT_W, tmp_y)

    y_pos[0] = cur_y - 0.4*cm

def divider():
    ensure_space(0.6)
    move_down(0.3)
    c.setStrokeColor(colors.HexColor('#AED6F1'))
    c.setLineWidth(0.5)
    c.setDash([3, 4])
    c.line(MARGIN_L, y_pos[0], PAGE_W - MARGIN_R, y_pos[0])
    c.setDash([])
    move_down(0.5)

# ═══════════════════════════════════════════════════════════════════════════
# START BUILDING PDF
# ═══════════════════════════════════════════════════════════════════════════

draw_page_background()
y_pos[0] = PAGE_H - MARGIN_T

# ── COVER / TITLE ──────────────────────────────────────────────────────────
move_down(1)
c.setFillColor(colors.HexColor('#154360'))
c.setFont('CaveatBold', 28)
c.drawCentredString(PAGE_W / 2, y_pos[0], 'Anatomy of the Pelvis')
move_down(1.3)
c.setFont('CaveatBold', 24)
c.drawCentredString(PAGE_W / 2, y_pos[0], '& Perineum')
move_down(0.8)
c.setStrokeColor(colors.HexColor('#2E86C1'))
c.setLineWidth(2)
c.line(MARGIN_L, y_pos[0], PAGE_W - MARGIN_R, y_pos[0])
move_down(0.6)
c.setFillColor(colors.HexColor('#5D6D7E'))
c.setFont('Caveat', 13)
c.drawCentredString(PAGE_W / 2, y_pos[0], 'Comprehensive Handwritten Study Notes')
move_down(0.7)
c.setFont('Caveat', 11)
c.drawCentredString(PAGE_W / 2, y_pos[0], 'Source: Gray\'s Anatomy for Students | THIEME Atlas | Campbell-Walsh-Wein Urology')
move_down(2)

# Quick-reference box
write_note_box([
    '① Bony Pelvis & Joints',
    '② Pelvic Walls & Pelvic Floor (Diaphragm)',
    '③ Pelvic Viscera (Bladder, Rectum, Reproductive Organs)',
    '④ Blood Supply & Venous Drainage',
    '⑤ Nerves of the Pelvis',
    '⑥ The Perineum – Triangles, Pouches & Muscles',
    '⑦ External Genitalia (Male & Female)',
    '⑧ Clinical Correlates',
], title='Contents at a Glance')

# ══════════════════════════════════════════════════════════════════════════
# SECTION 1 – BONY PELVIS
# ══════════════════════════════════════════════════════════════════════════
write_h1('1. The Bony Pelvis')

write_body('The pelvis is a bony ring formed by FOUR bones:', bold=False)
write_bullet('Two hip (coxal) bones – each made of ilium + ischium + pubis (fused at acetabulum)', symbol='①', bold=True)
write_bullet('Sacrum – 5 fused sacral vertebrae', symbol='②', bold=True)
write_bullet('Coccyx – 4 fused coccygeal vertebrae', symbol='③', bold=True)
move_down(0.4)

write_h2('Key Bony Landmarks')
write_table(
    ['Landmark', 'Clinical Relevance'],
    [
        ['Iliac crest', 'Palpable; L4 vertebral level'],
        ['ASIS', 'Origin of inguinal ligament; landmark'],
        ['PSIS', 'Overlies sacroiliac joint'],
        ['Ischial tuberosity', 'Weight-bearing; perineum corner'],
        ['Ischial spine', 'Pudendal nerve block landmark'],
        ['Pubic symphysis', 'Anterior limit of perineum'],
        ['Sacral promontory', 'Posterior limit of pelvic inlet'],
        ['Pubic tubercle', 'Attachment of inguinal ligament'],
    ],
    col_widths=[CONTENT_W * 0.42, CONTENT_W * 0.58]
)

write_h2('Pelvic Inlet & Outlet')
write_bullet('Pelvic INLET (superior aperture): sacral promontory → arcuate line → pubic symphysis. Faces anterosuperiorly.', symbol='→')
write_bullet('Pelvic OUTLET (inferior aperture): coccyx → ischial tuberosities → pubic symphysis. Closed by pelvic floor.', symbol='→')
write_bullet('FALSE pelvis: above inlet – part of abdominal cavity; contains lower abdominal viscera.', symbol='→')
write_bullet('TRUE pelvis: below inlet – contains bladder, rectum, reproductive organs.', symbol='→')

write_h2('True vs. False Pelvis & Sexual Dimorphism')
write_table(
    ['Feature', 'Female', 'Male'],
    [
        ['Pelvic inlet', 'Round / oval (gynecoid)', 'Heart-shaped'],
        ['Pelvic outlet', 'Wider', 'Narrower'],
        ['Subpubic angle', '>80° (~100°)', '~70°'],
        ['Sacrum', 'Shorter, broader, less curved', 'Longer, narrower, more curved'],
        ['Overall shape', 'Shallow & wide', 'Deep & narrow'],
    ],
    col_widths=[CONTENT_W * 0.32, CONTENT_W * 0.34, CONTENT_W * 0.34]
)

# ══════════════════════════════════════════════════════════════════════════
# SECTION 2 – JOINTS & LIGAMENTS
# ══════════════════════════════════════════════════════════════════════════
write_h1('2. Joints & Ligaments of the Pelvis')

write_h2('Joints')
write_bullet('Pubic symphysis – secondary cartilaginous (fibrocartilaginous); slightly mobile, especially in pregnancy', symbol='•')
write_bullet('Sacroiliac joints – synovial anteriorly + syndesmosis posteriorly; transmit trunk weight to lower limbs', symbol='•')
write_bullet('Sacrococcygeal joint – fibrocartilaginous; slight flexion / extension', symbol='•')

write_h2('Major Ligaments')
write_table(
    ['Ligament', 'From → To', 'Key Function'],
    [
        ['Sacrotuberous', 'Sacrum/coccyx → ischial tuberosity', 'Forms lesser sciatic foramen'],
        ['Sacrospinous', 'Sacrum → ischial spine', 'Landmark for pudendal block'],
        ['Iliolumbar', 'L4–L5 transverse proc. → iliac crest', 'Stabilises lumbosacral jxn'],
    ],
    col_widths=[CONTENT_W * 0.28, CONTENT_W * 0.42, CONTENT_W * 0.30]
)

# ══════════════════════════════════════════════════════════════════════════
# SECTION 3 – PELVIC WALLS & FLOOR
# ══════════════════════════════════════════════════════════════════════════
write_h1('3. Pelvic Walls & Floor')

write_h2('Lateral Wall Muscles')
write_bullet('Obturator internus: inner surface of obturator membrane → greater trochanter. Lateral rotation of thigh.', symbol='•')
write_bullet('Piriformis: anterior sacrum → greater trochanter. Lateral rotation; abduction of flexed thigh.', symbol='•')
write_body('Both form the lateral walls and are important landmarks for nerves/vessels (sciatic, pudendal).')

write_h2('Pelvic Diaphragm (Pelvic Floor) — ★ Most Clinically Important ★')
write_body('A hammock-shaped musculofascial sheet closing the pelvic outlet (except the urogenital hiatus anteriorly).')
move_down(0.3)
write_h3('Levator Ani (three parts)')
write_table(
    ['Part', 'Origin', 'Insertion', 'Innervation'],
    [
        ['Puborectalis', 'Superior pubic ramus (bilateral)', 'Loop around anorectal junction', 'Pudendal / S2–S4'],
        ['Pubococcygeus', 'Pubis (lateral)', 'Anococcygeal lig. + coccyx', 'Pudendal / S2–S4'],
        ['Iliococcygeus', 'Tendinous arch of obturator fascia', 'Iliococcygeal raphe + coccyx', 'Pudendal / S2–S4'],
    ],
    col_widths=[CONTENT_W*0.22, CONTENT_W*0.28, CONTENT_W*0.28, CONTENT_W*0.22]
)
write_h3('Coccygeus')
write_bullet('Origin: ischial spine; Insertion: inferior sacrum + coccyx; Inn: S4–S5', symbol='•')
write_bullet('Completes the pelvic diaphragm posteriorly; flexes coccyx', symbol='•')

write_note_box([
    'Functions of the Pelvic Floor:',
    '  1. Supports pelvic organs against intra-abdominal pressure',
    '  2. Maintains urinary & fecal continence',
    '  3. Contributes to birth canal during labour',
    '  4. Puborectalis creates the anorectal angle (~90°) — KEY for continence',
], box_color=colors.HexColor('#EAFAF1'), title='Remember!')

# ══════════════════════════════════════════════════════════════════════════
# SECTION 4 – PELVIC VISCERA
# ══════════════════════════════════════════════════════════════════════════
write_h1('4. Pelvic Viscera')

write_h2('Urinary Bladder')
write_bullet('Lies in retropubic space (Space of Retzius), posterosuperior to pubic symphysis', symbol='•')
write_bullet('Parts: apex, body, fundus, neck (continuous with urethra)', symbol='•')
write_bullet('Peritoneum covers superior surface only', symbol='•')
write_bullet('Male: rectovesical pouch between bladder & rectum', symbol='•')
write_bullet('Female: vesicouterine pouch between bladder & uterus', symbol='•')

write_h2('Urethra')
write_table(
    ['', 'Female', 'Male'],
    [
        ['Length', '~4 cm', '~20 cm'],
        ['Course', 'Short, straight → vestibule', 'Prostatic → membranous → spongy'],
        ['Angles', 'None', 'Fixed angle at perineal membrane + mobile penile angle'],
        ['Clinical', 'Short → easier UTI', 'Catheterisation must respect angles'],
    ],
    col_widths=[CONTENT_W*0.22, CONTENT_W*0.39, CONTENT_W*0.39]
)

write_h2('Rectum & Anal Canal')
write_bullet('Rectum begins at rectosigmoid junction (S3 level); follows the sacral curve', symbol='•')
write_bullet('Three lateral flexures → Houston\'s valves', symbol='•')
write_bullet('Anorectal angle (~90°) maintained by puborectalis — critical for continence', symbol='★', color=HEAD_COLOR, bold=True)
write_bullet('Internal anal sphincter (smooth muscle; involuntary; ANS)', symbol='•')
write_bullet('External anal sphincter (striated; voluntary; pudendal nerve S2–S4)', symbol='•')

write_h2('Prostate (Male)')
write_bullet('Sits at bladder neck, encircles the urethra; ~3 cm length', symbol='•')
write_bullet('Three zones: Peripheral (70% of gland, most Ca), Central (25%), Transitional (BPH site)', symbol='•')
write_bullet('Closely related to rectum posteriorly — basis of digital rectal exam (DRE)', symbol='•')
write_bullet('Seminal vesicles + vas deferens → ejaculatory ducts → open at verumontanum in prostatic urethra', symbol='•')

write_h2('Uterus & Supports (Female)')
write_bullet('Position: anteverted + anteflexed (normal); between bladder and rectum', symbol='•')
write_bullet('Parts: fundus, body, isthmus, cervix', symbol='•')
move_down(0.2)
write_h3('Uterine Ligaments')
write_table(
    ['Ligament', 'Attachment', 'Function'],
    [
        ['Broad', 'Uterus → lateral pelvic wall', 'Contains tubes, ovary, vessels'],
        ['Round', 'Uterine fundus → labia majora', 'Maintains anteversion'],
        ['Uterosacral', 'Cervix → sacrum', 'Maintains cervical position'],
        ['Cardinal (Mackenrodt)', 'Cervix/vagina → pelvic wall', 'MAIN support vs. prolapse'],
    ],
    col_widths=[CONTENT_W*0.30, CONTENT_W*0.38, CONTENT_W*0.32]
)

write_h2('Ovaries')
write_bullet('Lie in ovarian fossa (lateral pelvic wall, below bifurcation of common iliac artery)', symbol='•')
write_bullet('Attached to uterus by ovarian ligament; to pelvic wall by suspensory (infundibulopelvic) ligament', symbol='•')
write_bullet('Suspensory ligament carries the ovarian artery, vein, and lymphatics', symbol='★', color=HEAD_COLOR, bold=True)

# ══════════════════════════════════════════════════════════════════════════
# SECTION 5 – BLOOD SUPPLY
# ══════════════════════════════════════════════════════════════════════════
write_h1('5. Pelvic Blood Supply')

write_h2('Internal Iliac Artery (Hypogastric)')
write_body('Main supply to pelvic viscera and walls. Arises from common iliac artery at L4–L5 disc level.', bold=True)
move_down(0.2)

write_h3('Anterior Division')
write_bullet('Superior vesical a. → upper bladder, proximal ureter', symbol='•')
write_bullet('Inferior vesical a. (M) / Vaginal a. (F) → bladder base, prostate/vagina', symbol='•')
write_bullet('Uterine a. (F) → uterus; CROSSES URETER at base of broad ligament (★ "water under the bridge")', symbol='★', color=STAR_COLOR, bold=True)
write_bullet('Obturator a. → medial thigh muscles', symbol='•')
write_bullet('Internal pudendal a. → entire perineum (via Alcock\'s canal)', symbol='•')
write_bullet('Inferior gluteal a. → gluteal muscles', symbol='•')
write_bullet('Middle rectal a. → middle rectum', symbol='•')

write_h3('Posterior Division')
write_bullet('Iliolumbar a., Lateral sacral aa., Superior gluteal a. (largest branch)', symbol='•')

write_h2('Venous Drainage')
write_bullet('Pelvic venous plexuses (vesical, prostatic, uterovaginal, rectal) → internal iliac veins', symbol='•')
write_bullet('Prostatic plexus (of Santorini) connects with vertebral venous plexus → route for prostate cancer mets to spine', symbol='★', color=STAR_COLOR, bold=True)
write_bullet('Ovarian/testicular veins: right → IVC directly; left → left renal vein', symbol='•')

# ══════════════════════════════════════════════════════════════════════════
# SECTION 6 – NERVES
# ══════════════════════════════════════════════════════════════════════════
write_h1('6. Pelvic Nerves')

write_h2('Lumbosacral Plexus (L4–S3)')
write_table(
    ['Nerve', 'Roots', 'Exit / Course'],
    [
        ['Femoral', 'L2–L4', 'Exits below inguinal ligament'],
        ['Obturator', 'L2–L4', 'Through obturator canal'],
        ['Sciatic', 'L4–S3', 'Below piriformis, greater sciatic foramen'],
        ['Sup. gluteal', 'L4–S1', 'Above piriformis'],
        ['Inf. gluteal', 'L5–S2', 'Below piriformis'],
        ['Post. cut. thigh', 'S1–S3', 'Below piriformis → posterior thigh'],
    ],
    col_widths=[CONTENT_W*0.30, CONTENT_W*0.18, CONTENT_W*0.52]
)

write_h2('Pudendal Nerve (S2–S4) — THE Nerve of the Perineum ★')
write_body('Course:', bold=True)
write_bullet('1. Exits pelvis through greater sciatic foramen (below piriformis)', symbol='①')
write_bullet('2. Crosses ischial spine (landmark for pudendal nerve block)', symbol='②')
write_bullet('3. Re-enters through lesser sciatic foramen', symbol='③')
write_bullet('4. Runs in Alcock\'s canal on the lateral wall of the ischioanal fossa', symbol='④')
write_body('Branches:')
write_bullet('Inferior rectal nerve → external anal sphincter', symbol='→')
write_bullet('Perineal nerve (superficial + deep branches) → perineal muscles, scrotum/labia', symbol='→')
write_bullet('Dorsal nerve of penis / clitoris → penile/clitoral sensation', symbol='→')

write_h2('Autonomic Innervation')
write_table(
    ['System', 'Nerves', 'Function'],
    [
        ['Sympathetic', 'Presacral nerve → hypogastric nn. → inf. hypogastric plexus', 'Ejaculation; vasoconstriction'],
        ['Parasympathetic', 'Pelvic splanchnic nn. (S2–S4, "nervi erigentes") → inf. hypogastric plexus', 'Erection; bladder contraction; rectal emptying'],
    ],
    col_widths=[CONTENT_W*0.22, CONTENT_W*0.50, CONTENT_W*0.28]
)
write_note_box([
    '"Point and Shoot" mnemonic:',
    '  POINT = Parasympathetic → erection (S2–S4)',
    '  SHOOT = Sympathetic → ejaculation (L1–L2)',
], box_color=colors.HexColor('#FEF9E7'), title='Memory Aid')

# ══════════════════════════════════════════════════════════════════════════
# SECTION 7 – THE PERINEUM
# ══════════════════════════════════════════════════════════════════════════
write_h1('7. The Perineum')

write_body('Region INFERIOR to the pelvic floor, between the thighs and buttocks.', bold=True)
write_h2('Boundaries (Diamond-Shaped)')
write_bullet('Anterior: pubic symphysis', symbol='•')
write_bullet('Lateral: ischiopubic rami + ischial tuberosities', symbol='•')
write_bullet('Posterior: tip of coccyx', symbol='•')
write_bullet('Transverse line between ischial tuberosities divides it into TWO TRIANGLES', symbol='★', bold=True)

write_h2('Anal Triangle (Posterior)')
write_bullet('Contents: anal aperture + ischioanal fossa (fat-filled) on each side', symbol='•')
write_bullet('Ischioanal fossa: bounded medially by levator ani, laterally by obturator internus fascia', symbol='•')
write_bullet('Contains pudendal canal (Alcock\'s canal) with pudendal nerve + internal pudendal vessels', symbol='•')
write_bullet('Fat allows expansion of anal canal during defecation; abscess → fistula if infected', symbol='•')

write_h2('Urogenital Triangle (Anterior)')
write_bullet('Contains the perineal membrane and perineal pouches', symbol='•')
move_down(0.3)

write_h3('Perineal Membrane')
write_bullet('Tough fibromuscular sheet spanning anterior perineum', symbol='•')
write_bullet('Pierced by urethra (males) or urethra + vagina (females)', symbol='•')
move_down(0.3)

write_h3('Superficial Perineal Pouch (below perineal membrane)')
write_table(
    ['Structure', 'Male', 'Female'],
    [
        ['Ischiocavernosus', 'Covers crura of penis', 'Covers crura of clitoris'],
        ['Bulbospongiosus', 'Encircles corpus spongiosum; ejaculation', 'Covers vestibular bulb; narrows introitus'],
        ['Sup. transverse perineal', 'Ischial tuberosity → perineal body', 'Ischial tuberosity → perineal body'],
        ['Erectile tissue', 'Corpora cavernosa + corpus spongiosum', 'Clitoris + vestibular bulbs'],
        ['Glands', 'Bulbourethral (Cowper\'s) — in deep pouch', 'Greater vestibular (Bartholin\'s) glands'],
    ],
    col_widths=[CONTENT_W*0.30, CONTENT_W*0.35, CONTENT_W*0.35]
)

write_h3('Deep Perineal Pouch (above perineal membrane)')
write_bullet('Deep transverse perineal muscle – stabilises perineal body', symbol='•')
write_bullet('External urethral sphincter (sphincter urethrae) – voluntary micturition control', symbol='•')
write_bullet('In males: bulbourethral (Cowper\'s) glands', symbol='•')
write_bullet('In females: sphincter urethrovaginalis surrounds both urethra and vagina', symbol='•')
write_bullet('Innervation of ALL perineal muscles: Pudendal nerve (S2–S4)', symbol='★', bold=True, color=HEAD_COLOR)

write_h2('Perineal Body (Central Tendon) ★')
write_body('Poorly defined fibromuscular node at the MIDPOINT of the interischial line.')
write_body('Structures converging here:')
write_bullet('Levator ani (pelvic diaphragm)', symbol='→')
write_bullet('Bulbospongiosus', symbol='→')
write_bullet('Superficial + deep transverse perineal mm.', symbol='→')
write_bullet('External anal sphincter', symbol='→')
write_bullet('In females: rectovaginal septum fibres', symbol='→')
write_note_box([
    '★ Clinical importance: The perineal body provides pelvic floor integrity.',
    '   Its disruption during childbirth (tear or episiotomy) can cause:',
    '   • Pelvic organ prolapse (uterus, bladder, rectum)',
    '   • Fecal incontinence (external anal sphincter damage)',
    '   • Urinary incontinence',
], box_color=colors.HexColor('#FDEDEC'), title='Clinical Pearl')

# ══════════════════════════════════════════════════════════════════════════
# SECTION 8 – EXTERNAL GENITALIA
# ══════════════════════════════════════════════════════════════════════════
write_h1('8. External Genitalia')

write_h2('Male')
write_bullet('Penis: 2 corpora cavernosa (dorsal, erectile) + 1 corpus spongiosum (contains urethra)', symbol='•')
write_bullet('Root of penis: crura (attached to ischiopubic rami) + bulb (attached to perineal membrane)', symbol='•')
write_bullet('Scrotum: homologous to labia majora; cremaster muscle for thermoregulation', symbol='•')

write_h2('Female (Vulva)')
write_bullet('Mons pubis: fatty elevation over pubic symphysis', symbol='•')
write_bullet('Labia majora: homologous to scrotum', symbol='•')
write_bullet('Labia minora: enclose the VESTIBULE', symbol='•')
write_bullet('Vestibule: urethra + vaginal orifice open here; Bartholin\'s glands open laterally', symbol='•')
write_bullet('Clitoris: two crura + glans; homologous to penis; highly innervated (dorsal nerve of clitoris)', symbol='•')

# ══════════════════════════════════════════════════════════════════════════
# SECTION 9 – MUSCLE SUMMARY TABLE
# ══════════════════════════════════════════════════════════════════════════
write_h1('9. Pelvic Floor & Perineal Muscles — Master Table')

write_table(
    ['Muscle', 'Origin', 'Insertion', 'Innervation', 'Function'],
    [
        ['Puborectalis', 'Sup. pubic ramus', 'Anorectal junction (loop)', 'Pudendal S2–S4', 'Anorectal angle; continence'],
        ['Pubococcygeus', 'Pubis (lateral)', 'Anococcygeal lig.', 'Pudendal S2–S4', 'Pelvic floor support'],
        ['Iliococcygeus', 'Tendinous arch', 'Iliococcygeal raphe', 'Pudendal S2–S4', 'Pelvic floor support'],
        ['Coccygeus', 'Ischial spine', 'Inf. sacrum/coccyx', 'S4–S5', 'Flexes coccyx'],
        ['Ext. anal sphincter', 'Anococcygeal lig.', 'Perineal body', 'Pudendal S2–S4', 'Fecal continence'],
        ['Ext. urethral sphincter', 'Perineal membrane', 'Encircles urethra', 'Pudendal S2–S4', 'Urinary continence'],
        ['Bulbospongiosus', 'Perineal body', 'Penile raphe / clitoris', 'Pudendal S2–S4', 'Ejaculation / introitus'],
        ['Ischiocavernosus', 'Ischiopubic ramus', 'Corpus cavernosum', 'Pudendal S2–S4', 'Maintains erection'],
        ['Sup. transverse perineal', 'Ischial tuberosity', 'Perineal body', 'Pudendal S2–S4', 'Stabilises perineal body'],
        ['Deep transverse perineal', 'Ischiopubic ramus', 'Perineal body', 'Pudendal S2–S4', 'Stabilises perineal body'],
    ],
    col_widths=[CONTENT_W*0.22, CONTENT_W*0.18, CONTENT_W*0.18, CONTENT_W*0.18, CONTENT_W*0.24]
)

# ══════════════════════════════════════════════════════════════════════════
# SECTION 10 – CLINICAL CORRELATES
# ══════════════════════════════════════════════════════════════════════════
write_h1('10. Clinical Correlates')

write_table(
    ['Condition', 'Anatomical Basis'],
    [
        ['Pudendal nerve block', 'Injection near sacrospinous lig. at ischial spine; anaesthetises entire perineum'],
        ['Episiotomy', 'Incision of perineal body; avoid external anal sphincter'],
        ['Pelvic organ prolapse', 'Weakness of levator ani + cardinal/uterosacral ligaments'],
        ['BPH', 'Transitional zone of prostate enlarges → compresses urethra'],
        ['Ureteric injury in surgery', 'Uterine artery crosses over ureter near cervix ("water under the bridge")'],
        ['Perianal abscess', 'Infection of ischioanal fat pad; may → fistula-in-ano'],
        ['Prostate Ca metastasis', 'Via prostatic venous plexus (Santorini) → vertebral venous plexus → spine'],
        ['Ectopic ureter', 'Opens distal to internal sphincter → continuous incontinence'],
    ],
    col_widths=[CONTENT_W * 0.38, CONTENT_W * 0.62]
)

# ══════════════════════════════════════════════════════════════════════════
# FINAL PAGE – Quick Memory Aids
# ══════════════════════════════════════════════════════════════════════════
write_h1('Quick Memory Aids & Key Facts')

write_note_box([
    '✦ "Water under the bridge": Uterine artery CROSSES OVER the ureter near the cervix',
    '   (risk in hysterectomy!)',
    '✦ "Point and Shoot": Para = Point = Erection (S2-4); Sympa = Shoot = Ejaculation (L1-2)',
    '✦ Anorectal angle (~90°) maintained by PUBORECTALIS — loss → incontinence',
    '✦ The pudendal nerve (S2-S4) is THE nerve of the perineum',
    '✦ Perineal body: convergence point of ALL perineal structures',
    '✦ Left ovarian/testicular vein → left renal vein (not directly to IVC)',
    '✦ Peripheral zone of prostate: most prostate carcinomas arise here',
    '✦ Transitional zone of prostate: BPH occurs here',
], box_color=colors.HexColor('#EAF2FF'), title='★ High-Yield Points ★')

move_down(1)
divider()
move_down(0.3)
c.setFillColor(colors.HexColor('#7F8C8D'))
c.setFont('Caveat', 10)
c.drawCentredString(PAGE_W/2, y_pos[0],
    'Sources: Gray\'s Anatomy for Students (Elsevier) | THIEME Atlas of Anatomy | Campbell-Walsh-Wein Urology')
move_down(0.7)
c.setFont('Caveat', 10)
c.drawCentredString(PAGE_W/2, y_pos[0], 'Generated by Orris Medical Notes — May 2026')

# Save
c.save()
print(f'PDF created: {OUTPUT}')
print(f'Pages: {page_num[0]}')
You've run out of free credits. Sign up for a free account to continue using Orris.
This is a shared conversation. Sign in to Orris to start your own chat.