Meckel diverticulum for 10 marks wifrom sabiston

Reading File
Finding Sources
Finding Sources
Reading File
Reading File
I now have the complete Sabiston content on Meckel diverticulum. Let me compile a comprehensive 10-mark answer.

Meckel Diverticulum

(Sabiston Textbook of Surgery)

1. Definition and Incidence

Meckel diverticulum is the most common congenital anomaly of the small intestine, occurring in approximately 2% of the population. It was first reported by Hildanus in 1598 and described in detail by Johann Meckel in 1809.

2. Embryology

It results from incomplete closure of the omphalomesenteric (vitelline) duct. The cells lining the vitelline duct are pluripotent, which explains why about half of all Meckel diverticula contain heterotopic (ectopic) tissue.

3. The "Rule of 2s"

FeatureDetail
Incidence~2% of the population
Location2 feet (45-60 cm) proximal to the ileocecal valve
Length~2 inches (3-6 cm)
SiteAntimesenteric border of the ileum
Ectopic tissue~50% contain it
Age of presentationMost before age 2
Sex predilectionMales more commonly symptomatic

4. Morphology

  • Located on the antimesenteric border of the ileum, 45-60 cm proximal to the ileocecal valve
  • It is a true diverticulum (contains all layers of the intestinal wall)
  • Ranges from a small bump to a long projection communicating with the umbilicus via a persistent fibrous cord, or (rarely) a patent fistula
  • Usual form: wide-mouthed diverticulum, 3-6 cm in length

5. Ectopic Tissue

  • ~50% contain heterotopic tissue
  • Most common: gastric mucosa (responsible for acid-induced ulceration and bleeding)
  • Followed by: pancreatic mucosa
  • Rare: colonic mucosa

6. Clinical Manifestations

A. Gastrointestinal Bleeding (Most common symptomatic presentation)

  • Most common in children ≤2 years of age
  • May present as acute massive hemorrhage, chronic anemia, or recurrent self-limited episodes
  • Source: acid-induced peptic ulcer in the adjacent ileum caused by ectopic gastric mucosa secreting acid

B. Intestinal Obstruction

Three main mechanisms:
  1. Volvulus - small bowel twists around the diverticulum attached to abdominal wall by a fibrotic band; may cause strangulation if untreated
  2. Intussusception - broad-based diverticulum invaginates and is carried forward by peristalsis; can be ileoileal or ileocolic; presents with obstruction, early vomiting, urge to defecate, and classic currant jelly stools; a palpable mass may be present
  3. Littre's hernia - incarceration of the diverticulum in an inguinal hernia

C. Meckel Diverticulitis

  • More common in adults
  • Clinically indistinguishable from appendicitis (right lower quadrant pain)
  • Should be in the differential when appendix is found normal during exploration
  • Can progress to perforation and peritonitis
  • Key rule: always inspect the distal ileum when the appendix is normal

D. Neoplasms (0.5%-3.2% of cases)

Tumor TypeFrequency
NET (neuroendocrine tumor)33%-44% - most common malignancy
Leiomyosarcoma18%-25%
Adenocarcinoma12%-16% (from gastric mucosa)
GIST12%
Lymphoma / Pancreatic malignanciesLess frequent

7. Diagnostic Studies

InvestigationComment
Plain X-ray, CT, UltrasoundRarely helpful
Tc-99m pertechnetate scintigraphy (Meckel scan)Most accurate test in children: sensitivity 85%, specificity 95%, accuracy 90%
Meckel scan in adultsSensitivity falls to ~63% (less gastric mucosa)
Cimetidine enhancementBlocks acid secretion without affecting radionuclide uptake → increases radionuclide concentration in diverticulum wall → improves sensitivity
Barium contrast / Mesenteric arteriography / Double-balloon endoscopyFor false-negative Meckel scans
AngiographyUseful in active acute hemorrhage
False negatives occur due to: absent gastric mucosa, inflammatory edema/necrosis, outlet obstruction of the diverticulum, or anemia.
Note: Surgical intervention should NOT be delayed for imaging in hemodynamically unstable patients with active hemorrhage.

8. Treatment

Symptomatic Meckel Diverticulum

Requires prompt surgical intervention:
  • Segmental small bowel resection - required for bleeding cases because the ulcer is adjacent to (not within) the diverticulum
  • Diverticulectomy - for non-bleeding cases; performed by hand-sewn technique or stapling across the base in a diagonal/transverse line to prevent stenosis
  • Laparoscopic resection has equivalent outcomes to open resection (retrospective studies)
For intussusception: even if reduced by air enema, diverticulum should still be resected to prevent recurrence.

Asymptomatic Incidental Meckel Diverticulum

  • Controversial in adults
  • Historical basis (Soltero & Bill): risk of becoming symptomatic in adults is ≤2%; morbidity of incidental removal was 12% → recommendation was to not resect in adults
  • Recent studies argue for resection due to risk of harboring malignancies
  • Children found to have Meckel diverticulum during laparotomy: resect
  • Factors favoring resection in adults:
    • Age <50 years
    • Male sex
    • Diverticulum length >2 cm
    • Ectopic tissue or palpable abnormalities
Decision must be individualized, weighing malignancy risk, age, and operative risk.

9. Summary Points for Exam

  • Most common congenital anomaly of the small intestine (2% of population)
  • True diverticulum on antimesenteric border, 45-60 cm from ileocecal valve
  • Rule of 2s (2%, 2 feet, 2 inches, 2 years peak age, 2 types of ectopic tissue)
  • Most common ectopic tissue = gastric mucosa
  • Most common symptom = GI bleeding (children); diverticulitis mimics appendicitis (adults)
  • Best diagnostic test = Tc-99m pertechnetate scan in children
  • Treatment of bleeding = segmental resection; non-bleeding = diverticulectomy

- Sabiston Textbook of Surgery: The Biological Basis of Modern Surgical Practice, Chapter 91

Classified stoma and colostomy with therapuetic uses and techqine with diagram amd from standard text books

Finding Sources
Finding Sources
Finding Sources
Reading File
Reading File
Reading File
Reading File
Reading File
Reading File
Reading File
Loading Image
Loading Image
Reading File
Loading Image
Loading Image
Excellent - I now have comprehensive content and all key diagrams. Here is the complete structured answer:

Stoma - Classification, Colostomy: Therapeutic Uses and Technique

(Sources: Sabiston Textbook of Surgery, Bailey & Love's Short Practice of Surgery 28th Edition)

PART 1: CLASSIFICATION OF STOMAS

A stoma is a surgically created opening of the bowel (or urinary tract) onto the abdominal wall surface. Stomas can be classified across several axes:

A. By Content Drained

TypeOrganEffluent
IleostomySmall bowel (ileum)Liquid, green, enzyme-rich
ColostomyLarge bowel (colon)Semi-formed to solid
Urostomy / Ileal conduitUrinary tractUrine

B. By Duration

TypeDescriptionCommon Indication
Temporary (diverting)Closed at a later date once indication resolvesProtect anastomosis, trauma, diverticulitis
PermanentNever reversedAPR, total proctocolectomy, incontinence

C. By Configuration

FIGURE 95.18 (Sabiston) - Different types of intestinal stoma:
Types of intestinal stoma - End (A), Loop (B), End-loop (C), Continent ileostomy (D), Double-barrel (E)
ConfigurationDescription
End stomaOne limb of divided bowel brought out; distal bowel removed or closed as Hartmann's pouch
Loop stomaLoop of bowel exteriorised over a rod/bridge; both limbs open (proximal functional, distal non-functional)
End-loop stomaEnd of bowel brought through aperture with adjacent loop sutured alongside
Double-barrel (Paul-Mikulicz)Both cut ends brought out side by side when patient too ill for anastomosis
Continent stomaInternal pouch (Kock pouch/ileoanal) with valve mechanism - catheterised to empty

D. By Site of Colostomy

SiteEffluentNotes
Caecostomy / AscendingLiquidMore electrolyte disturbance
Transverse colostomySemi-liquidSeldom used now (prone to prolapse, difficult to pouch)
Descending colostomySemi-formedPreferred over transverse
Sigmoid colostomyFormedBest formed stool; most common permanent colostomy

PART 2: COLOSTOMY - THERAPEUTIC USES

Indications (Bailey & Love + Sabiston)

1. Protective / Defunctioning Colostomy
  • To protect a distal anastomosis (usually after anterior resection of rectum)
  • After traumatic rectal injury
  • To allow healing of a high anal fistula or complex perineal wound
  • To defunction an obstructing low rectal cancer prior to long-course chemoradiotherapy
2. Emergency Colostomy
  • Acute left-sided colonic obstruction (e.g. sigmoid volvulus, obstructing carcinoma) - as Hartmann's procedure
  • Perforated diverticulitis with peritonitis
  • Gunshot/stab wound to rectum/colon
3. Permanent Colostomy
  • After abdominoperineal resection (APR) for low rectal/anal canal carcinoma - left iliac fossa end-colostomy
  • Total proctocolectomy for ulcerative colitis / FAP (when ileal pouch not feasible)
  • Severe faecal incontinence in patients unfit for or refusing other procedures
  • Bedridden/neurologically compromised patients
4. Palliative Colostomy (Bailey & Love)
  • Unresectable rectal cancer causing obstruction
  • To prevent obstruction during downstaging chemoradiotherapy in advanced cancers
  • Pelvic malignancies invading rectum
5. Other Indications
  • Hirschsprung's disease (in children, as a staged procedure)
  • Anorectal malformations
  • Radiation proctitis with stricture
  • Anal stricture complicating Crohn's disease

PART 3: SURGICAL TECHNIQUE

Pre-operative

  • Stoma siting by stoma nurse: Patient assessed in standing, sitting, and bending positions; avoiding skin folds, scars, bony prominences, and the belt line. Site marked on the infraumbilical fat mound within the rectus abdominis.
  • Bowel preparation and antibiotic prophylaxis as appropriate

Technique 1: END COLOSTOMY (Permanent - e.g., after APR)

Steps:
  1. After bowel resection, the cut end of the sigmoid/descending colon is prepared with adequate mesenteric mobilisation to ensure it reaches the skin without tension
  2. A circular disc of skin (2-3 cm diameter) is excised at the pre-marked left iliac fossa site
  3. The subcutaneous fat is divided down to the anterior rectus sheath
  4. The rectus muscle is split longitudinally (muscle-splitting incision) - NOT cut across
  5. The posterior rectus sheath and peritoneum are sharply divided
  6. The aperture should admit two fingers comfortably (see figure below)
  7. The bowel is delivered through the trephine, ensuring no twisting of the mesentery
  8. The colostomy is sutured flush or with slight eversion to the skin (not a spout like ileostomy)
  9. End colostomy typically protrudes 0.5-1 cm above skin level
FIGURE 95.20 - Stoma aperture creation: rectus muscle is split, rectus sheath is sharply divided:
Stoma aperture technique - rectus muscle splitting and sharp division of rectus sheath

Technique 2: LOOP COLOSTOMY (Temporary - usually transverse or sigmoid)

Steps:
  1. A loop of colon (most commonly sigmoid; occasionally transverse) is mobilised and brought out through a transverse incision on the anterior abdominal wall (usually right upper or left lower quadrant)
  2. The abdomen is closed first
  3. A rod or bridge is passed beneath the loop to prevent retraction in the early postoperative period; removed after a few days once adhesions form
FIGURE - Loop colostomy with bridge:
Loop colostomy with bridge preventing retraction - anterior view showing two lumina after opening
  1. The colon is incised transversely on the antimesenteric border (about 2/3 of the circumference)
  2. The edges of the colonic incision are sutured to the adjacent skin margin (mucocutaneous anastomosis)
  3. This creates two openings - proximal (active, efferent) and distal (inactive, afferent)
  4. Colostomy function expected within 2-7 days postoperatively
Closure of loop colostomy: Once indication resolves, confirmed by water-soluble contrast enema of distal bowel. Can usually be closed without a formal laparotomy by local mobilisation. Note: approximately 25% of temporary stomas are never closed due to complications or changes in comorbidity.

Technique 3: DOUBLE-BARREL COLOSTOMY (Paul-Mikulicz)

  • Used when bowel resection has occurred but patient is too ill for anastomosis
  • Both cut ends of the divided colon are brought out as adjacent stomas on the abdominal wall
  • Advantage: subsequent closure is easier as ends can be locally mobilised and reanastomosed without full laparotomy

Key Technical Principles (Sabiston)

  • Aperture in abdominal wall must be within rectus muscle (reduces parastomal herniation)
  • Large enough to admit two fingers, but not so large as to predispose to hernia
  • No tension on the mesentery - for obese patients, full central vascular ligation may be required
  • Viability can be assessed intraoperatively with indocyanine green perfusion assessment
  • If viability is in question, use a more proximal, well-perfused segment
  • Prophylactic mesh around the stoma aperture may reduce parastomal hernia risk by ~40% (recent meta-analysis), though benefit in trials from the last 5 years is less clear

Post-operative: Colostomy in Left Iliac Fossa

Colostomy in left iliac fossa with appliance bag applied

PART 4: COMPLICATIONS OF STOMA

ComplicationNotes
Ischaemia / NecrosisInspect day 1 postop; use proctoscope to assess viability below fascia; urgent surgery if below fascia
Mucocutaneous separationUsually managed conservatively with stoma care
ProlapseMore common with loop stomas, especially transverse; treatment is reversal or conversion to end-stoma
RetractionMainly in obese patients; may require revision
StenosisMinor - dilatation; severe - revision surgery
Parastomal herniaUp to 50% long-term; simple repair has ~100% recurrence; needs mesh repair or stoma relocation
Skin irritationMost common; managed by stoma nurses

Summary

FeatureIleostomyColostomy
SiteRight iliac fossaLeft iliac fossa (end); variable (loop)
SpoutYes (3 cm above skin)Flush or slightly everted
EffluentLiquid, greenFormed / semi-formed
Electrolyte riskHigherLower
Key surgical teaching: "It is imperative that every stoma must be well made. Proper stoma construction as a prophylactic measure is vastly superior to any therapeutic options to improve upon a suboptimally constructed stoma." - Sabiston

Sources:
  • Sabiston Textbook of Surgery: The Biological Basis of Modern Surgical Practice, Chapter 95 (Stoma Types, Colostomy)
  • Bailey & Love's Short Practice of Surgery, 28th Edition, Chapter 77 (Types of colostomy, Stoma complications)

Add stoma marking in this and prars stoma hernia management and causes also

Finding Sources
Finding Sources
Finding Sources
Reading File
Reading File
Reading File
Reading File
Finding Sources
Reading File
Loading Image
Reading File
Loading Image
Loading Image
Loading Image
All key images and content secured. Here is the complete updated answer with stoma marking and parastomal hernia sections added:

Stoma Marking, Classification, Colostomy, and Parastomal Hernia

(Sources: Sabiston Textbook of Surgery, Bailey & Love's Short Practice of Surgery 28th Edition, Fischer's Mastery of Surgery 8th Edition)

SECTION A: STOMA SITING AND MARKING

Preoperative stoma marking is one of the most important steps in stoma surgery. A poorly sited stoma leads to appliance leakage, skin excoriation, and severe quality-of-life impairment - complications that are almost entirely preventable.

Who Marks the Stoma?

  • Ideally performed by a trained enterostomal therapy (ET) / stoma care nurse preoperatively
  • In the absence of an ET nurse, the operating surgeon must perform siting (Fischer's Mastery of Surgery)
  • Every gastrointestinal surgeon should be familiar with stoma siting principles

Principles of Stoma Siting

FIGURE 95.17 (Sabiston) - Stoma siting methodology: (A) Avoid areas not visible to the patient; (B) Identify abdominal folds and creases; (C) Locate rectus abdominis muscle; (D) Final stoma sites within patient's line of sight, avoiding folds
Stoma siting methodology - avoid non-visible areas, identify creases, locate rectus muscle, mark final sites

Step-by-Step Stoma Marking

1. Assess the patient in three positions: supine, sitting, and standing/bending - the abdomen changes shape significantly between positions
2. Identify areas to AVOID:
  • Skin creases and folds (especially in obese patients)
  • Bony prominences (anterior superior iliac spine, costal margin)
  • Previous scars or skin grafts
  • The belt line and waistband area
  • The umbilicus
  • Areas not visible to the patient when they look down (patient must be able to see and manage the stoma)
3. Identify the ideal zone:
  • Within the rectus abdominis muscle - reduces risk of parastomal hernia
  • On the infraumbilical fat mound - provides a flat, broad surface for bag adherence (see Sabiston Fig. 95.15 below)
  • For ileostomy: right iliac fossa, right paramedian infraumbilical
  • For end colostomy: left iliac fossa, left paramedian infraumbilical
  • General landmark: midpoint between the anterior superior iliac spine and umbilicus, adjusted for body habitus
4. Mark the site with a permanent marker. At the time of surgery, a needle scratch is made on the skin to prevent the mark being washed off during skin preparation.
FIGURE 95.15 (Sabiston) - Infraumbilical fat mound: the ideal stoma site, shown here marked for a descending colostomy
Infraumbilical fat mound marking for descending colostomy - cross-hair diagram on torso
FIGURE 95.16 (Sabiston) - Consequence of no preoperative marking: colostomy "disappears" in abdominal fold when patient sits up, making pouching extremely difficult
Patient without preoperative stoma marking - colostomy lost in abdominal fold when sitting
Preoperative ileostomy site marking photo (Fischer's Mastery of Surgery):
Preoperative ileostomy site marked in right lower quadrant, right paramedian infraumbilical position

Special Considerations

  • In obese patients: creases may shift dramatically with position; marking while seated is particularly important
  • Clothing preferences (belts, waistbands, religious garments) should be discussed with the patient - stoma must not be under the belt line
  • In emergency surgery where marking is not possible: standard landmark of 5 cm lateral to the midline and 4 cm below the umbilicus within the rectus muscle is generally suitable

SECTION B: CLASSIFICATION OF STOMAS

By Organ/Content

TypeEffluentSite
IleostomyLiquid, green, causticRight iliac fossa
ColostomySemi-formed to solidLeft iliac fossa (end); variable (loop)
Urostomy/Ileal conduitUrineRight iliac fossa

By Duration

TemporaryPermanent
Protect anastomosisAPR for low rectal cancer
TraumaUlcerative colitis / FAP
DiverticulitisSevere incontinence
Downstaging CRTBedridden patients

By Configuration (Sabiston Fig. 95.18)

Types of intestinal stoma - End (A), Loop (B), End-loop (C), Continent ileostomy (D), Double-barrel (E)
ConfigurationDescription
End stomaSingle limb; distal bowel removed or closed (Hartmann's)
Loop stomaLoop brought out over a rod; two openings (proximal = functional)
End-loop stomaEnd of bowel with adjacent loop sutured to it
Double-barrelBoth cut ends brought out side-by-side (Paul-Mikulicz)
Continent stomaInternal pouch with valve; emptied by catheter

SECTION C: COLOSTOMY - TYPES, THERAPEUTIC USES AND TECHNIQUE

(Covered in full in the previous response - see above. Summary:)
TypeUseSite
Loop colostomyTemporary diversion, protect anastomosis, traumaSigmoid or transverse
End colostomyAfter APR, Hartmann's; permanentLeft iliac fossa
Double-barrelEmergency resection, too ill for anastomosisVariable
Palliative colostomyUnresectable rectal cancer, obstructionSigmoid

SECTION D: PARASTOMAL HERNIA

Definition

A parastomal hernia is a hernia of the abdominal wall adjacent to a stoma. When a stoma is created, a defect is deliberately made in all layers of the abdominal wall - this is effectively a hernia by design. The fascial defect tends to enlarge over time, allowing loops of bowel or intra-abdominal fat to protrude around the stoma. The rate is over 50% in long-term follow-up. (Bailey & Love)

Causes and Risk Factors

Technical / Surgical Factors:
  • Aperture made too large at the time of creation - the most preventable cause
  • Stoma placed outside the rectus abdominis muscle (lateral placement dramatically increases hernia risk)
  • Tension on the bowel - causes stomal retraction and subsequent enlargement of the defect
  • Failure to anchor the bowel to the abdominal wall
Patient Factors: (Fischer's Mastery)
  • Obesity / high BMI - increases intra-abdominal pressure and makes tissue weaker
  • Smoking - impairs collagen synthesis and wound healing
  • Poorly controlled medical comorbidities (diabetes, malnutrition, immunosuppression, steroids)
  • Weight gain after surgery
  • Chronic cough or straining (raised intra-abdominal pressure)
  • Previous abdominal wall surgery / scarring
Time-related:
  • Risk is directly proportional to length of time the patient has the stoma (Fischer's)
  • Rate can reach 50% or more at 5 years

Clinical Presentation

  • A bulge or swelling around the stoma, most visible when the patient coughs or strains
  • Difficulty fitting / maintaining the stoma appliance - most common functional complaint
  • Appliance bags fit poorly, leading to leakage and peristomal skin excoriation
  • Intermittent obstruction of the stoma
  • Pain or discomfort around the stoma
  • Rarely: acute obstruction or strangulation (surgical emergency)

Management

Conservative (Non-operative)

  • Hernia support belt - reduces symptoms and aids appliance adherence
  • Revision of pouching system to accommodate the changed stoma morphology
  • Weight loss, smoking cessation, optimisation of comorbidities
  • In temporary stomas: conservative management until the stoma can be reversed, with simultaneous repair of the fascial defect at the time of reversal (Fischer's)

Surgical - Indications for Repair

Surgery is reserved for:
  • Significant symptoms (pain, difficulty with appliance)
  • Inability to adequately pouch the stoma
  • Obstruction, ischaemia, or incarceration of the hernia (emergency)

Surgical Options

1. Primary Suture Repair
  • Simple fascial repair around the stoma
  • Associated with near 100% recurrence rate - rarely used alone (Bailey & Love)
  • Appropriate only as a bridge or in emergency settings
2. Stoma Relocation / Re-siting
  • Stoma is moved to the opposite side of the abdomen
  • Previously common, now no longer recommended as parastomal hernia occurs at the same rate at the new site (Bailey & Love)
  • The original defect still requires closure
3. Mesh Repair - Preferred Surgical Option Mesh repair is associated with significantly lower recurrence rates than suture repair alone. Three mesh repair techniques exist:
TechniqueDescriptionRecurrence
Keyhole / Slit meshMesh placed with central aperture to accommodate bowel; mesh can be placed in onlay, retromuscular, or intraperitoneal positions21-73%
Sugarbaker techniqueLarge underlay mesh placed intraperitoneally; stoma limb exits the mesh lateral to the fascial defect (no central hole); bowel is sandwiched between mesh and abdominal wall7-15% - best results
Modified laparoscopic SugarbakerLaparoscopic version of Sugarbaker; equivalent recurrence to open repair7-15%
  • Mesh infection rate in reported series: only 2-2.6%, and only one case of bowel erosion in 16 studies - much lower than historically feared (Fischer's)
  • Retromuscular (sublay) mesh placement is generally preferred over onlay to reduce infection risk
  • No RCT has directly compared laparoscopic vs. open repair
4. Stoma Reversal
  • The ideal solution - remove the stoma and restore bowel continuity
  • Obliterates the hernia defect and removes the problem entirely
  • Not always possible (e.g., permanent colostomy after APR, sphincter deficiency)

Prophylaxis of Parastomal Hernia

Correct technique at creation is the most important preventive measure:
  • Place stoma through the rectus abdominis muscle
  • Appropriate aperture size (admit two fingers, but no larger)
  • Ensure bowel reaches skin without tension
Prophylactic mesh at time of stoma creation:
  • Large-pore polypropylene mesh placed in the retromuscular space with bowel passing through central hole
  • A meta-analysis of 12 RCTs (cited in Sabiston): prophylactic mesh reduces parastomal hernia risk by ~40%
  • However, RCTs from the past 5 years show no significant advantage, with comparable complication and mortality rates
  • Decision to use prophylactic mesh should be individualised (Sabiston)

Summary: Parastomal Hernia at a Glance

FeatureDetail
Incidence>50% at 5 years
Most common symptomAppliance leakage / difficulty pouching
Best investigationCT abdomen (defines anatomy, detects obstruction)
ConservativeHernia belt, appliance revision
Best surgical optionSugarbaker mesh (lowest recurrence 7-15%)
AvoidSimple suture repair alone (~100% recurrence)
PreventCorrect siting + rectus passage + mesh at creation

Sources:
  • Sabiston Textbook of Surgery, Chapter 95 (Stoma siting, Fig. 95.15, 95.16, 95.17, 95.18, 95.19, 95.20)
  • Bailey & Love's Short Practice of Surgery, 28th Edition, Chapter 64 (Parastomal hernia), Chapter 77 (Types of colostomy)
  • Fischer's Mastery of Surgery, 8th Edition (Ostomy Marking, Parastomal Hernia)

Add stoma care also in this

Finding Sources
Finding Sources
Reading File
Finding Sources
Reading File
Reading File
Reading File
Loading Image
Reading File
Finding Sources
Reading File
Loading Image
I now have all the content needed. Here is the full Stoma Care section to add:

SECTION E: STOMA CARE

(Sources: Pye's Surgical Handicraft 22nd Ed, Bailey & Love 28th Ed, Fischer's Mastery of Surgery 8th Ed)

1. The Stoma Care Nurse (Enterostomal Therapist / ET Nurse)

The stoma care nurse is the cornerstone of stoma management. Their role spans the entire patient journey:
PhaseRole
PreoperativeCounselling, explanation, reassurance; stoma siting and marking
IntraoperativeAdvises on site if marking not done
Early postoperativeAppliance fitting, monitoring stoma viability, patient teaching
Long-termTroubleshooting complications, appliance advice, psychological support, liaison with support groups
  • "A stoma is compatible with a normal life" - patients should be told this explicitly preoperatively (Pye's)
  • Ileostomy and Colostomy patient associations offer peer support; members meet new patients preoperatively

2. Preoperative Counselling

All patients should ideally be seen by the stoma nurse before surgery:
  • Full explanation of what the stoma is, how it functions, what to expect
  • Reassurance regarding body image, relationships, and daily activities
  • Introduction to appliance types
  • Contact with patient support groups if desired
  • Psychological preparation is as important as physical preparation - adapting to life with a stoma can be emotionally taxing

3. Stoma Appliances

All stoma appliances consist of two components: a bag and a flange (skin barrier/baseplate) which attaches to the peristomal skin.
Figure 20.11 - Sites for stoma placement: ileostomy (lower, right), transverse colostomy (upper right) (Pye's)
Stoma siting diagram - ileostomy lower right paramedian, transverse colostomy upper right

Types of Appliance

TypeDescriptionUsed For
One-pieceBag and flange are inseparable; non-irritant adhesive back; hole cut to fit stomaSimple, disposable
Two-pieceFlange (baseplate) and bag are separable; bag can be removed and replaced without disturbing the skin sealBetter for skin protection; bag changed more frequently than baseplate
Drainable bagOpen bottom with clip/tie; emptied when half-fullIleostomy (liquid output), transverse colostomy
Non-drainable bagClosed end; disposed after each useSigmoid colostomy (formed stool)
Figure 20.10 - Stoma care accessories: cover bags, waist belt, skin barrier mini-blankets, karaya paste, odour filter (Pye's)
Stoma care accessories - karaya paste, Stomahesive, skin gel, filters, appliance bags, waist belt

Key Points on Appliance Selection

  • Bag gasket sizes: 25-100 mm diameter; the aperture is cut to fit snugly around the stoma
  • Ileostomy - always use a drainable appliance (liquid, enzyme-rich effluent)
  • Sigmoid colostomy - non-drainable bag is suitable (formed faeces)
  • Transverse loop colostomy - requires a larger drainable appliance (more liquid output, like an ileostomy)
  • Stoma shrinks over the first few weeks; appliance size must be revised accordingly
  • Bag should be emptied when half-full to prevent weight detaching the flange

4. Accessories for Stoma Care

AccessoryPurpose
Karaya gum / Karaya pasteSkin protectant; fills skin irregularities between flange and stoma to prevent leakage; applied on the skin side of the gasket
Stomahesive paste (sodium carboxymethyl cellulose + gelatin + pectin + polyisobutylene)Non-reactive barrier; sticks to moist surfaces; moulded to skin contours; cuts with scissors; used as baseplate material
Barrier creamsProtect peristomal skin from effluent excoriation
Charcoal filter / FiltrodorPunctured into the bag; allows flatus to escape while trapping odour
DeodorantsReduce odour from stoma effluent
Waist beltProvides additional security to prevent bag detachment
Hernia support beltUsed when parastomal hernia is present; reduces bulging and aids appliance adhesion
Plastic capUsed by patients on the natural or irrigation method of colostomy management between evacuations

5. Postoperative Stoma Care - First 24-48 Hours

  • Apply a translucent (clear) drainable bag immediately at the end of surgery - allows stoma inspection without bag removal
  • Inspect the stoma daily in the first 24-48 hours through the translucent bag for:
    • Colour: healthy stoma should be pink/red and moist
    • Necrosis: black/dusky colour - use a paediatric proctoscope to assess depth of necrosis
    • Bleeding: a viable stoma bleeds when pricked with a needle
    • Retraction: stoma receding below skin level
    • Oedema: common in first week; settles spontaneously
  • Colostomy usually acts within 3-5 days (flatus first, then stool)
  • Ileostomy acts within 24-48 hours; high output (>1000 ml/day) common initially - monitor electrolytes
  • Mucocutaneous sutures (even absorbable) should be removed after day 10

6. Long-Term Colostomy Management

Three methods are used for sigmoid colostomy management (Pye's):

A. Natural Method

  • Some patients develop a predictable, once-daily action (often triggered by a stimulus like tea/coffee)
  • Between actions: a simple plastic cap with a belt maintains cleanliness - no bag needed
  • Dietary adjustment and antimotility drugs (codeine, loperamide, Lomotil) help establish this routine

B. Appliance Method

  • Most common method
  • One- or two-piece non-drainable bags used; changed after each action
  • One-piece bags can be applied to a Stomahesive base which remains in place for several days

C. Irrigation Method (Colostomy Irrigation)

The most controlled method; gives the patient freedom from a bag between irrigations.
Technique (Pye's):
  1. Started 2-4 weeks postoperatively under stoma therapist supervision
  2. Patient sits on the toilet
  3. A short plastic cone is gently inserted into the stoma (cone prevents perforation risk)
  4. The cone is connected to a plastic reservoir suspended at head height
  5. 750-1000 ml of water at room temperature are instilled from the reservoir
  6. A long plastic sleeve backed by an adhesive flange is applied to the stoma; its open end directed into the toilet bowl
  7. The colon evacuates in 10-30 minutes
  8. Sleeve is folded and clipped - patient can walk around during residual evacuation
  9. Sleeve removed, stoma cleaned, and an adhesive stoma seal applied
  10. Repeated every 24-48 hours
Advantages: Freedom from a permanent bag between irrigations; cost savings; greater control Disadvantages: Time-consuming; requires motivation and dexterity; not suitable for all patients; not used for transverse/right-sided colostomies

7. Ileostomy-Specific Care

FeatureDetail
Output~500 ml/day (normal); >1000 ml/day = high output
Electrolyte contentNa 110-120 mmol/L; K 6-12 mmol/L
HazardProteolytic enzymes in effluent digest skin rapidly - bag must not leak
Flange changeEvery 4-5 days; not more often to avoid skin trauma
Bag emptyingWhen half-full - prevents weight detaching flange
Spout2-3 cm above skin - directs effluent into bag without skin contact
High output ileostomy (>1000 ml/day) - causes: subacute obstruction, Crohn's disease, short bowel syndrome, antibiotics, certain foods (onions, vegetables, fruits, alcohol). Treatment: loperamide, codeine, Lomotil, dietary adjustment.

8. Peristomal Skin Care

Skin problems are the most common complication encountered in stoma care.
ProblemCauseManagement
Excoriation / chemical dermatitisEffluent contact with skin (leakage); most severe with ileostomyEnsure correct appliance size; use Stomahesive or karaya as barrier; barrier creams
Allergic contact dermatitisAllergy to adhesive in applianceSkin reaction matches the shape of the appliance; remove appliance; use Stomahesive; may need steroid cream
Mechanical traumaOverly frequent appliance changes; rough skin cleaningGentle cleaning with warm water; reduce frequency of flange changes
Fungal infectionSecondary candidal infection in moist, excoriated skinAntifungal powder applied to skin under the flange
MacerationMoisture from leakageImprove bag seal; use Stomahesive paste to fill contour gaps
LeakagePoorly fitting appliance; irregular skin contour; stoma retraction; ulcerationCorrect appliance size; karaya/Stomahesive paste; revise stoma if retracted

9. Dietary Guidance for Stoma Patients

Type of StomaDietary Advice
ColostomyRegular meals; avoid gas-producing foods (beans, cabbage, onions, carbonated drinks) if bothersome; avoid foods causing diarrhoea
IleostomyAvoid large boluses of fibrous/high-residue food (risk of food bolus obstruction at fascia); ensure adequate fluid and salt intake to compensate for losses; restrict high-oxalate foods (spinach, leafy greens) to reduce renal stone risk
BothChew food thoroughly; avoid dehydration; reintroduce foods one at a time postoperatively

10. Psychological and Social Care

  • Body image: Patients commonly experience depression, anxiety, and altered body image - particularly young patients and those with permanent stomas
  • Sexual function: APR-related nerve damage and stoma placement can impair sexual function; must be discussed preoperatively
  • Return to activities: Patients can swim, exercise, travel, and work normally with a well-managed stoma
  • Support groups: Ileostomy Association, Colostomy UK - peer-to-peer support is invaluable
  • Regular follow-up: Monitor for skin problems, appliance issues, herniation, prolapse, and stenosis

Summary: Stoma Care at a Glance

PhaseKey Action
PreoperativeCounselling + stoma siting by ET nurse
Day 0-1Translucent drainable bag; inspect stoma viability
Day 1-10Monitor output; electrolyte balance; remove mucocutaneous sutures day 10
Weeks 1-4Teach appliance management; stoma shrinks - resize appliance
Long-term (colostomy)Natural / appliance / irrigation method
Long-term (ileostomy)Drainable bag; flange every 4-5 days; skin protection
OngoingSkin care, diet, psychological support, surveillance for complications

Sources:
  • Pye's Surgical Handicraft, 22nd Edition, Chapter 20 (Stoma care nurses, Appliances, Ileostomy, Colostomy management, Irrigation)
  • Bailey & Love's Short Practice of Surgery, 28th Edition, Chapter 77 (Stoma bags and appliances, Stoma complications)
  • Fischer's Mastery of Surgery, 8th Edition (Ostomy Marking, Stoma Complications)
  • Sabiston Textbook of Surgery, Chapter 95 (Stoma Types, Stoma nurse role)

Create a summary document of stoma marking, classification and care for study

Reading File
Running Command

mkdir -p /home/daytona/workspace/stoma-study && ls /home/daytona/workspace/stoma-study

Writing File

~/stoma-study/generate.js

const {
  Document, Packer, Paragraph, TextRun, Table, TableRow, TableCell,
  HeadingLevel, AlignmentType, BorderStyle, WidthType, ShadingType,
  VerticalAlign, PageNumber, Header, Footer, PageBreak,
  TableOfContents, StyleLevel
} = require('docx');
const fs = require('fs');

// ── Colour palette ──────────────────────────────────────────────────
const TEAL      = "1B6CA8";   // heading 1
const STEEL     = "2E86AB";   // heading 2
const SLATE     = "3D5A80";   // heading 3
const LIGHT_BG  = "E8F4FD";   // table header fill
const ALT_ROW   = "F5FAFE";   // alternate table row
const WHITE     = "FFFFFF";
const DARK_TXT  = "1A1A2E";

// ── Helpers ──────────────────────────────────────────────────────────
function h1(text) {
  return new Paragraph({
    heading: HeadingLevel.HEADING_1,
    spacing: { before: 360, after: 120 },
    children: [new TextRun({
      text, bold: true, size: 32, color: WHITE,
      font: "Calibri"
    })],
    shading: { type: ShadingType.SOLID, color: TEAL },
    indent: { left: 120, right: 120 },
  });
}

function h2(text) {
  return new Paragraph({
    heading: HeadingLevel.HEADING_2,
    spacing: { before: 280, after: 80 },
    children: [new TextRun({
      text, bold: true, size: 26, color: WHITE, font: "Calibri"
    })],
    shading: { type: ShadingType.SOLID, color: STEEL },
    indent: { left: 80 },
  });
}

function h3(text) {
  return new Paragraph({
    heading: HeadingLevel.HEADING_3,
    spacing: { before: 200, after: 60 },
    children: [new TextRun({
      text, bold: true, size: 22, color: WHITE, font: "Calibri"
    })],
    shading: { type: ShadingType.SOLID, color: SLATE },
    indent: { left: 60 },
  });
}

function para(text, { bold = false, italic = false, size = 20, indent = 0, spacing = 160 } = {}) {
  return new Paragraph({
    spacing: { before: 60, after: spacing },
    indent: indent ? { left: indent } : {},
    children: [new TextRun({ text, bold, italic, size, color: DARK_TXT, font: "Calibri" })]
  });
}

function bullet(text, level = 0) {
  return new Paragraph({
    bullet: { level },
    spacing: { before: 40, after: 40 },
    indent: { left: 360 + level * 360 },
    children: [new TextRun({ text, size: 20, color: DARK_TXT, font: "Calibri" })]
  });
}

function divider() {
  return new Paragraph({
    spacing: { before: 40, after: 40 },
    border: { bottom: { style: BorderStyle.SINGLE, size: 6, color: TEAL } },
    children: []
  });
}

function keyBox(label, value) {
  return new Paragraph({
    spacing: { before: 60, after: 60 },
    indent: { left: 200 },
    shading: { type: ShadingType.SOLID, color: LIGHT_BG },
    children: [
      new TextRun({ text: `${label}:  `, bold: true, size: 20, color: TEAL, font: "Calibri" }),
      new TextRun({ text: value, size: 20, color: DARK_TXT, font: "Calibri" })
    ]
  });
}

function pageBreak() {
  return new Paragraph({ children: [new PageBreak()] });
}

// ── Table builder ─────────────────────────────────────────────────────
function makeTable(headers, rows, colWidths) {
  const totalWidth = colWidths.reduce((a, b) => a + b, 0);
  const makeBorder = () => ({ style: BorderStyle.SINGLE, size: 4, color: "AACCE0" });

  const headerCells = headers.map((h, i) =>
    new TableCell({
      width: { size: colWidths[i], type: WidthType.DXA },
      shading: { type: ShadingType.SOLID, color: TEAL },
      verticalAlign: VerticalAlign.CENTER,
      borders: { top: makeBorder(), bottom: makeBorder(), left: makeBorder(), right: makeBorder() },
      children: [new Paragraph({
        alignment: AlignmentType.CENTER,
        children: [new TextRun({ text: h, bold: true, size: 18, color: WHITE, font: "Calibri" })]
      })]
    })
  );

  const dataRows = rows.map((row, ri) =>
    new TableRow({
      children: row.map((cell, ci) =>
        new TableCell({
          width: { size: colWidths[ci], type: WidthType.DXA },
          shading: { type: ShadingType.SOLID, color: ri % 2 === 0 ? WHITE : ALT_ROW },
          verticalAlign: VerticalAlign.CENTER,
          borders: { top: makeBorder(), bottom: makeBorder(), left: makeBorder(), right: makeBorder() },
          children: [new Paragraph({
            children: [new TextRun({ text: cell, size: 18, color: DARK_TXT, font: "Calibri" })]
          })]
        })
      )
    })
  );

  return new Table({
    width: { size: totalWidth, type: WidthType.DXA },
    rows: [new TableRow({ children: headerCells, tableHeader: true }), ...dataRows]
  });
}

// ── Cover Page ───────────────────────────────────────────────────────
function coverPage() {
  return [
    new Paragraph({ spacing: { before: 2000 }, children: [] }),
    new Paragraph({
      alignment: AlignmentType.CENTER,
      spacing: { before: 200, after: 200 },
      shading: { type: ShadingType.SOLID, color: TEAL },
      children: [new TextRun({ text: "STOMA", bold: true, size: 72, color: WHITE, font: "Calibri" })]
    }),
    new Paragraph({
      alignment: AlignmentType.CENTER,
      spacing: { before: 80, after: 80 },
      children: [new TextRun({ text: "Classification • Marking • Care • Parastomal Hernia", bold: true, size: 28, color: STEEL, font: "Calibri" })]
    }),
    new Paragraph({
      alignment: AlignmentType.CENTER,
      spacing: { before: 120, after: 120 },
      children: [new TextRun({ text: "A Comprehensive Surgical Study Guide", italic: true, size: 24, color: SLATE, font: "Calibri" })]
    }),
    divider(),
    new Paragraph({
      alignment: AlignmentType.CENTER,
      spacing: { before: 200, after: 40 },
      children: [new TextRun({ text: "Sources:", bold: true, size: 22, color: TEAL, font: "Calibri" })]
    }),
    new Paragraph({
      alignment: AlignmentType.CENTER,
      spacing: { before: 20, after: 20 },
      children: [new TextRun({ text: "Sabiston Textbook of Surgery", italic: true, size: 20, color: DARK_TXT, font: "Calibri" })]
    }),
    new Paragraph({
      alignment: AlignmentType.CENTER,
      spacing: { before: 20, after: 20 },
      children: [new TextRun({ text: "Bailey & Love's Short Practice of Surgery, 28th Ed.", italic: true, size: 20, color: DARK_TXT, font: "Calibri" })]
    }),
    new Paragraph({
      alignment: AlignmentType.CENTER,
      spacing: { before: 20, after: 20 },
      children: [new TextRun({ text: "Fischer's Mastery of Surgery, 8th Ed.", italic: true, size: 20, color: DARK_TXT, font: "Calibri" })]
    }),
    new Paragraph({
      alignment: AlignmentType.CENTER,
      spacing: { before: 20, after: 20 },
      children: [new TextRun({ text: "Pye's Surgical Handicraft, 22nd Ed.", italic: true, size: 20, color: DARK_TXT, font: "Calibri" })]
    }),
    pageBreak()
  ];
}

// ─────────────────────────────────────────────────────────────────────
// CONTENT SECTIONS
// ─────────────────────────────────────────────────────────────────────

function section1_definition() {
  return [
    h1("SECTION 1: DEFINITION & OVERVIEW"),
    para("A stoma (Greek: 'mouth') is a surgically created opening between a hollow organ and the body surface. In colorectal surgery, it most commonly refers to an opening of the bowel (intestinal stoma) or urinary tract (urostomy) onto the anterior abdominal wall."),
    para("Key principle: Every stoma must be well made. Proper stoma construction as a prophylactic maneuver is vastly superior to any therapeutic options to attempt to improve upon a suboptimally constructed stoma. (Sabiston)", { italic: true }),
    divider()
  ];
}

function section2_classification() {
  return [
    h1("SECTION 2: CLASSIFICATION OF STOMAS"),
    h2("A. By Content Drained"),
    makeTable(
      ["Type", "Organ Used", "Effluent", "Site"],
      [
        ["Ileostomy", "Ileum (small bowel)", "Liquid, green, enzyme-rich", "Right iliac fossa"],
        ["Colostomy", "Colon (large bowel)", "Semi-formed to solid", "Left iliac fossa (end)"],
        ["Urostomy / Ileal conduit", "Urinary tract via ileal segment", "Urine", "Right iliac fossa"],
      ],
      [2000, 2200, 2400, 2200]
    ),
    new Paragraph({ spacing: { before: 120 }, children: [] }),

    h2("B. By Duration"),
    makeTable(
      ["Temporary", "Permanent"],
      [
        ["Protect distal anastomosis", "APR for low rectal / anal canal cancer"],
        ["Traumatic bowel/rectal injury", "Total proctocolectomy (UC, FAP)"],
        ["Acute diverticulitis / Hartmann's", "Faecal incontinence, unfit for repair"],
        ["Downstaging chemoradiotherapy", "Hirschsprung's (staged - later made permanent)"],
        ["High anal fistula treatment", "Bedridden / neurologically compromised patients"],
      ],
      [4400, 4400]
    ),
    new Paragraph({ spacing: { before: 120 }, children: [] }),

    h2("C. By Configuration (Sabiston Fig. 95.18)"),
    makeTable(
      ["Type", "Description", "Key Use"],
      [
        ["End stoma", "Single limb exteriorised; distal bowel removed or closed as Hartmann's pouch", "Permanent colostomy after APR; permanent ileostomy"],
        ["Loop stoma", "Loop of bowel brought out over a rod/bridge; two openings - proximal (active) and distal (inactive)", "Temporary diversion; protect anastomosis"],
        ["End-loop stoma", "Cut end of bowel with adjacent loop sutured alongside it", "When end stoma has insufficient length to reach skin"],
        ["Double-barrel (Paul-Mikulicz)", "Both cut ends brought out side by side as two adjacent stomas", "Emergency resection; patient too ill for anastomosis"],
        ["Continent stoma (Kock pouch)", "Internal reservoir with nipple valve; emptied by catheter", "Avoids external bag; requires motivated patient"],
      ],
      [2000, 4000, 2800]
    ),
    new Paragraph({ spacing: { before: 120 }, children: [] }),

    h2("D. Colostomy - By Site"),
    makeTable(
      ["Site", "Effluent Consistency", "Notes"],
      [
        ["Caecostomy / Ascending", "Liquid, enzyme-rich", "High electrolyte loss; rarely used"],
        ["Transverse", "Semi-liquid", "Seldom used now - prone to prolapse; difficult to pouch (belt line)"],
        ["Descending", "Semi-formed", "Better than transverse; more of colon in circuit"],
        ["Sigmoid", "Formed", "Best formed stool; ideal for permanent end colostomy"],
      ],
      [2200, 2400, 4200]
    ),
    new Paragraph({ spacing: { before: 120 }, children: [] }),

    h2("Ileostomy vs Colostomy - Quick Comparison"),
    makeTable(
      ["Feature", "Ileostomy", "Colostomy"],
      [
        ["Position", "Right iliac fossa", "Left iliac fossa (end); variable (loop)"],
        ["Spout", "YES - 2-3 cm above skin (prevents skin contact)", "Flush or slightly everted only"],
        ["Effluent", "Liquid, green, caustic enzymes", "Formed / semi-formed"],
        ["Electrolyte risk", "HIGH (sodium, potassium loss)", "Lower"],
        ["Skin risk", "HIGH - proteolytic enzymes destroy skin on contact", "Lower"],
        ["Bag type", "Always drainable bag", "Non-drainable (sigmoid); drainable (transverse/right)"],
        ["Output", "~500 ml/day (normal)", "1-3 actions/day"],
      ],
      [2400, 2800, 2800]
    ),
    new Paragraph({ spacing: { before: 120 }, children: [] }),
    pageBreak()
  ];
}

function section3_marking() {
  return [
    h1("SECTION 3: STOMA SITING AND MARKING"),
    para("Preoperative stoma marking is one of the most critical steps. A poorly sited stoma causes appliance leakage, skin excoriation, and severely impaired quality of life - complications that are largely preventable."),

    h2("Who Marks the Stoma?"),
    bullet("Ideally: trained Enterostomal Therapy (ET) nurse / Stoma Care Nurse - preoperatively"),
    bullet("If no ET nurse available: the operating surgeon must perform siting"),
    bullet("Every GI surgeon must know stoma siting principles (Fischer's Mastery)"),
    new Paragraph({ spacing: { before: 120 }, children: [] }),

    h2("Four-Step Siting Process"),
    h3("Step 1 - Assess in Three Positions"),
    bullet("Supine (lying)", 0),
    bullet("Sitting (most important - folds change dramatically)", 0),
    bullet("Standing and bending", 0),

    h3("Step 2 - Areas to AVOID"),
    makeTable(
      ["Avoid", "Reason"],
      [
        ["Skin creases and folds", "Appliance will not seal; leakage inevitable"],
        ["Bony prominences (ASIS, costal margin)", "Appliance will not lie flat"],
        ["Belt line / waistband area", "Appliance dislodged by clothing"],
        ["Previous scars, skin grafts", "Poor adhesion, irregular contour"],
        ["The umbilicus", "Irregular surface"],
        ["Areas patient cannot see", "Patient cannot manage stoma independently"],
      ],
      [3000, 5800]
    ),
    new Paragraph({ spacing: { before: 120 }, children: [] }),

    h3("Step 3 - The Ideal Zone"),
    bullet("Within the RECTUS ABDOMINIS MUSCLE - single most important principle (reduces parastomal hernia)"),
    bullet("On the INFRAUMBILICAL FAT MOUND - flat surface for bag adherence (Sabiston Fig. 95.15)"),
    bullet("Ileostomy: right paramedian, infraumbilical (right iliac fossa)"),
    bullet("End colostomy: left paramedian, infraumbilical (left iliac fossa)"),
    bullet("General landmark: midpoint between anterior superior iliac spine (ASIS) and umbilicus"),
    new Paragraph({ spacing: { before: 80 }, children: [] }),
    keyBox("Emergency fallback (no marking done)", "5 cm lateral to midline + 4 cm below umbilicus, within rectus muscle"),
    new Paragraph({ spacing: { before: 80 }, children: [] }),

    h3("Step 4 - Marking Technique"),
    bullet("Mark with waterproof/permanent ink marker"),
    bullet("Apply a disposable appliance over the marked site - patient tests it by sitting, bending, walking"),
    bullet("At surgery: scratch the skin with a needle over the mark (prevents washoff during skin prep)"),
    new Paragraph({ spacing: { before: 120 }, children: [] }),

    h2("Special Patient Considerations"),
    makeTable(
      ["Patient Type", "Special Consideration"],
      [
        ["Obese patient", "Creases shift with position - assess sitting is critical; may need higher placement"],
        ["Elderly", "Assess manual dexterity - stoma must be reachable and visible"],
        ["Visually impaired", "May need carer involvement; tactile landmarks important"],
        ["Wheelchair user", "Assess in seated position primarily; avoid sites compressed by chair"],
        ["Athletes / Active patients", "Avoid belt line; discuss waterproof appliances, sport covers"],
        ["Religious considerations", "Discuss clothing requirements (e.g. sari, dhoti, habits)"],
      ],
      [2400, 6400]
    ),
    new Paragraph({ spacing: { before: 120 }, children: [] }),
    pageBreak()
  ];
}

function section4_technique() {
  return [
    h1("SECTION 4: COLOSTOMY - THERAPEUTIC USES AND OPERATIVE TECHNIQUE"),
    h2("Indications for Colostomy"),
    makeTable(
      ["Indication Type", "Specific Situations"],
      [
        ["Protective / Defunctioning", "Protect distal anastomosis; healing of high anal fistula; defunction obstructing rectal cancer prior to chemoradiotherapy"],
        ["Emergency", "Left colonic obstruction (sigmoid volvulus, carcinoma); perforated diverticulitis; rectal trauma"],
        ["Permanent", "APR for low rectal/anal canal carcinoma; total proctocolectomy; severe faecal incontinence"],
        ["Palliative", "Unresectable rectal cancer with obstruction; advanced pelvic malignancy; during downstaging CRT"],
        ["Other", "Hirschsprung's disease (staged); anorectal malformations; radiation proctitis stricture; Crohn's anal stricture"],
      ],
      [2400, 6400]
    ),
    new Paragraph({ spacing: { before: 120 }, children: [] }),

    h2("Operative Technique - End Colostomy (Permanent)"),
    para("Used after APR or Hartmann's procedure. Site: left iliac fossa."),
    bullet("1. Mobilise sigmoid/descending colon with adequate mesenteric length - must reach skin WITHOUT tension"),
    bullet("2. Excise circular disc of skin (~2-3 cm) at pre-marked LIF site"),
    bullet("3. Divide subcutaneous fat to anterior rectus sheath"),
    bullet("4. SPLIT rectus muscle longitudinally (muscle-splitting incision - preserves function)"),
    bullet("5. Sharply divide posterior rectus sheath and peritoneum"),
    bullet("6. Aperture must admit TWO FINGERS comfortably"),
    bullet("7. Deliver bowel through trephine; check no mesenteric twisting"),
    bullet("8. Suture colon margin FLUSH or with slight eversion to skin (mucocutaneous anastomosis)"),
    bullet("9. End colostomy protrudes only 0.5-1 cm above skin (unlike ileostomy spout)"),
    new Paragraph({ spacing: { before: 80 }, children: [] }),
    keyBox("Key principle", "Rectus muscle SPLIT (not cut across) + aperture within rectus = reduces parastomal hernia"),
    new Paragraph({ spacing: { before: 120 }, children: [] }),

    h2("Operative Technique - Loop Colostomy (Temporary)"),
    bullet("1. Mobilise loop of sigmoid (or transverse) colon"),
    bullet("2. Bring loop out through abdominal wall incision (transverse incision in wall)"),
    bullet("3. Close the abdomen first"),
    bullet("4. Pass a ROD or BRIDGE beneath the loop - prevents retraction; removed after a few days"),
    bullet("5. Incise colon transversely on antimesenteric border (~2/3 circumference)"),
    bullet("6. Suture colonic edges to adjacent skin (mucocutaneous anastomosis)"),
    bullet("7. Two openings created: PROXIMAL (functional/active) + DISTAL (inactive/efferent)"),
    bullet("8. Function expected within 2-7 days postoperatively"),
    new Paragraph({ spacing: { before: 80 }, children: [] }),
    keyBox("Closure note", "~25% of temporary stomas are NEVER closed due to complications or change in comorbidity"),
    new Paragraph({ spacing: { before: 120 }, children: [] }),

    h2("Double-Barrel Colostomy (Paul-Mikulicz)"),
    bullet("Used when bowel resection done but patient too ill for primary anastomosis"),
    bullet("Both cut ends brought out as two adjacent stomas on abdominal wall"),
    bullet("Advantage: subsequent closure by local mobilisation and reanastomosis without full laparotomy"),
    new Paragraph({ spacing: { before: 120 }, children: [] }),
    pageBreak()
  ];
}

function section5_stomaCare() {
  return [
    h1("SECTION 5: STOMA CARE"),
    h2("A. Stoma Care Nurse Role"),
    makeTable(
      ["Phase", "Role"],
      [
        ["Preoperative", "Counselling + reassurance + stoma siting and marking"],
        ["Intraoperative", "Available for advice if marking not pre-done"],
        ["Early postoperative (Day 0-10)", "Appliance fitting; stoma inspection; patient teaching; electrolyte monitoring"],
        ["Long-term", "Troubleshooting; appliance updates; psychological support; support group liaison"],
      ],
      [2400, 6400]
    ),
    new Paragraph({ spacing: { before: 120 }, children: [] }),

    h2("B. Stoma Appliances"),
    makeTable(
      ["Component", "Description"],
      [
        ["Flange / Baseplate", "Adhesive plate that sticks to peristomal skin; has central aperture cut to fit stoma size; made of Stomahesive material"],
        ["Bag", "Collects output; attached to flange"],
        ["One-piece appliance", "Flange and bag inseparable; simpler to apply; change whole unit each time"],
        ["Two-piece appliance", "Flange and bag separable; bag changed more frequently; flange stays 3-5 days; better for skin protection"],
        ["Drainable bag", "Open bottom with clip; emptied when half-full; MANDATORY for ileostomy"],
        ["Non-drainable bag", "Closed bottom; disposed after each use; used for sigmoid colostomy (formed stool)"],
      ],
      [2800, 6000]
    ),
    new Paragraph({ spacing: { before: 120 }, children: [] }),

    h2("C. Key Accessories"),
    makeTable(
      ["Accessory", "Purpose / Use"],
      [
        ["Karaya gum / paste", "Fills skin irregularities between flange and stoma; excellent skin protectant"],
        ["Stomahesive paste", "Na carboxymethyl cellulose + gelatin + pectin; non-reactive; sticks to moist skin; cut to shape"],
        ["Barrier creams", "Protect peristomal skin from enzymatic excoriation"],
        ["Charcoal / Filtrodor filter", "Punctured into bag; releases flatus silently while trapping odour"],
        ["Waist belt", "Additional security to prevent bag detachment"],
        ["Hernia support belt", "Used when parastomal hernia present; reduces bulge; aids appliance adhesion"],
        ["Deodorants", "Reduce odour from stoma effluent"],
        ["Plastic cap + belt", "Used by natural/irrigation method patients between evacuations (no bag needed)"],
      ],
      [2800, 6000]
    ),
    new Paragraph({ spacing: { before: 120 }, children: [] }),

    h2("D. Immediate Postoperative Care (Day 0-10)"),
    bullet("Apply TRANSLUCENT drainable bag at end of surgery - allows inspection without removal"),
    bullet("Inspect stoma daily through transparent bag for:"),
    bullet("Colour: healthy = pink/red and moist", 1),
    bullet("Necrosis: dark/dusky/black colour - assess depth with paediatric proctoscope", 1),
    bullet("Viability check: viable stoma BLEEDS when gently pricked with needle", 1),
    bullet("Retraction, prolapse, oedema (oedema common in first week; settles spontaneously)", 1),
    bullet("Ileostomy acts within 24-48 h; high output (>1000 ml/day) common initially - monitor Na+, K+"),
    bullet("Colostomy acts within 3-5 days (flatus appears first, then stool)"),
    bullet("Remove mucocutaneous sutures at Day 10 (even absorbable ones)"),
    bullet("Stoma shrinks over weeks 1-6 - resize the appliance aperture accordingly"),
    new Paragraph({ spacing: { before: 120 }, children: [] }),

    h2("E. Long-Term Colostomy Management Methods"),
    h3("1. Natural Method"),
    bullet("Relies on predictable daily action (often stimulus-triggered, e.g. morning coffee)"),
    bullet("Between actions: plastic cap with belt - no bag required"),
    bullet("Dietary adjustment + antimotility drugs (codeine, loperamide, Lomotil) to regulate timing"),
    new Paragraph({ spacing: { before: 60 }, children: [] }),
    h3("2. Appliance Method (most common)"),
    bullet("One- or two-piece non-drainable bags changed after each action"),
    bullet("One-piece bags applied over Stomahesive base (base stays in place several days)"),
    new Paragraph({ spacing: { before: 60 }, children: [] }),
    h3("3. Colostomy Irrigation Method"),
    para("Gives freedom from permanent bag between irrigations. Technique:"),
    bullet("Start 2-4 weeks postoperatively under stoma therapist supervision"),
    bullet("Patient sits on toilet; plastic cone connected to reservoir suspended at head height"),
    bullet("750-1000 ml of room-temperature water run into stoma via cone"),
    bullet("Long plastic sleeve applied to stoma; directed into toilet bowl"),
    bullet("Colon evacuates in 10-30 minutes; sleeve folded and clipped"),
    bullet("Patient ambulates normally while residual evacuation occurs"),
    bullet("Sleeve removed; stoma cleaned; adhesive stoma seal applied"),
    bullet("Repeat every 24-48 hours"),
    bullet("NOT suitable for transverse/right-sided colostomies or incontinent bowel"),
    new Paragraph({ spacing: { before: 120 }, children: [] }),

    h2("F. Peristomal Skin Care"),
    makeTable(
      ["Problem", "Cause", "Management"],
      [
        ["Chemical excoriation", "Effluent contact with skin (leakage or oversized aperture)", "Correct appliance size; Stomahesive / karaya barrier"],
        ["Allergic dermatitis", "Allergy to adhesive (rash matches exact appliance shape)", "Remove; use Stomahesive; steroid cream if needed"],
        ["Mechanical trauma", "Frequent flange changes; rough cleaning", "Gentle warm water cleaning; reduce change frequency"],
        ["Fungal infection (Candida)", "Moist excoriated skin under flange", "Antifungal powder applied under flange"],
        ["Maceration", "Moisture from effluent leakage", "Improve seal; Stomahesive paste to fill gaps"],
        ["Leakage causes", "Wrong size; irregular contour; retraction; ulceration; poor tuition", "Address specific cause; revise stoma if retracted"],
      ],
      [2000, 2800, 4000]
    ),
    new Paragraph({ spacing: { before: 120 }, children: [] }),

    h2("G. Dietary Guidance"),
    makeTable(
      ["Stoma Type", "Advice"],
      [
        ["Ileostomy", "Avoid large fibrous boluses (obstruction risk); adequate fluid + salt intake; restrict high-oxalate foods (spinach, leafy greens) to reduce renal stones; chew food thoroughly"],
        ["Colostomy", "Avoid gas-producing foods if bothersome (beans, cabbage, onions, carbonated drinks); regular mealtimes help regularity"],
        ["Both", "Reintroduce foods one at a time; avoid dehydration; alcohol increases ileostomy output"],
      ],
      [2000, 6800]
    ),
    new Paragraph({ spacing: { before: 120 }, children: [] }),

    h2("H. Ileostomy Physiology and High Output"),
    keyBox("Normal output", "~500 ml/day"),
    keyBox("High output (abnormal)", ">1000 ml/day - risk of Na/K depletion"),
    keyBox("Electrolyte composition", "Na 110-120 mmol/L | K 6-12 mmol/L | Cl 40-70 mmol/L"),
    new Paragraph({ spacing: { before: 80 }, children: [] }),
    para("Causes of high output ileostomy:", { bold: true }),
    bullet("Subacute small bowel obstruction"),
    bullet("Crohn's disease / IBD flare"),
    bullet("Short bowel syndrome"),
    bullet("Drugs: laxatives, antibiotics"),
    bullet("Diet: onions, vegetables, fruits, alcohol"),
    para("Treatment: Loperamide, codeine, Lomotil; bulk agents; dietary modification; oral rehydration solutions"),
    new Paragraph({ spacing: { before: 120 }, children: [] }),
    pageBreak()
  ];
}

function section6_paraHernia() {
  return [
    h1("SECTION 6: PARASTOMAL HERNIA"),
    h2("Definition"),
    para("A parastomal hernia is herniation of abdominal contents (bowel loops or fat) through the fascial defect adjacent to the stoma. Creating a stoma inherently creates a potential hernia - the defect tends to enlarge over time."),
    keyBox("Incidence", "Over 50% at 5 years (Bailey & Love)"),
    keyBox("Most preventable by", "Correct siting within rectus muscle + appropriate aperture size"),
    new Paragraph({ spacing: { before: 120 }, children: [] }),

    h2("Causes and Risk Factors"),
    h3("Technical (Surgical) Factors"),
    makeTable(
      ["Factor", "Detail"],
      [
        ["Aperture too large", "Most direct preventable cause - opens up space for herniation"],
        ["Stoma outside rectus muscle", "Lateral placement has dramatically higher hernia rates"],
        ["Excessive tension on bowel", "Leads to retraction → enlargement of defect"],
        ["Failure to anchor bowel to abdominal wall", "Allows movement and gradual defect widening"],
      ],
      [3000, 5800]
    ),
    new Paragraph({ spacing: { before: 80 }, children: [] }),
    h3("Patient Factors"),
    makeTable(
      ["Factor", "Mechanism"],
      [
        ["Obesity / high BMI", "Raised intra-abdominal pressure + weak tissue + technical difficulty"],
        ["Smoking", "Impairs collagen synthesis and wound healing"],
        ["Poorly controlled diabetes", "Impaired wound healing"],
        ["Malnutrition / hypoalbuminaemia", "Poor fascial healing"],
        ["Chronic steroid use / immunosuppression", "Impaired healing"],
        ["Chronic cough or straining", "Persistently raised intra-abdominal pressure"],
        ["Weight gain after surgery", "Increases abdominal wall strain"],
        ["Duration of stoma", "Risk directly proportional to time stoma present"],
      ],
      [3000, 5800]
    ),
    new Paragraph({ spacing: { before: 120 }, children: [] }),

    h2("Clinical Features"),
    bullet("Bulge / swelling adjacent to the stoma (most noticeable on coughing or straining)"),
    bullet("MOST COMMON COMPLAINT: difficulty fitting and maintaining the stoma appliance"),
    bullet("Appliance bag leakage, poor adhesion, peristomal skin excoriation"),
    bullet("Intermittent stoma obstruction"),
    bullet("Pain or discomfort around the stoma site"),
    bullet("EMERGENCY: acute obstruction or strangulation of herniated bowel"),
    new Paragraph({ spacing: { before: 120 }, children: [] }),

    h2("Investigations"),
    bullet("Clinical diagnosis (examination with patient standing / straining)"),
    bullet("CT abdomen/pelvis: defines anatomy, detects obstruction, identifies strangulation"),
    new Paragraph({ spacing: { before: 120 }, children: [] }),

    h2("Management"),
    h3("1. Conservative (Non-operative)"),
    bullet("Hernia support / stoma belt"),
    bullet("Appliance revision (larger aperture, convex baseplate, different system)"),
    bullet("Lifestyle: weight loss, smoking cessation, control of cough"),
    bullet("Temporary ileostomies: conservative management until stoma reversal (with simultaneous fascial repair)"),
    new Paragraph({ spacing: { before: 80 }, children: [] }),
    h3("2. Surgical - Indications"),
    bullet("Significant symptoms or inability to adequately pouch the stoma"),
    bullet("Acute obstruction, strangulation, or incarceration (emergency surgery)"),
    bullet("Intractable appliance problems despite conservative measures"),
    new Paragraph({ spacing: { before: 80 }, children: [] }),
    h3("3. Surgical Options"),
    makeTable(
      ["Technique", "Description", "Recurrence Rate"],
      [
        ["Primary suture repair", "Simple fascial closure around stoma", "~100% - NOT recommended alone"],
        ["Stoma relocation / re-siting", "Move stoma to opposite side of abdomen", "Same rate at new site - no longer recommended (Bailey & Love)"],
        ["Keyhole / Slit mesh", "Mesh with central aperture accommodating bowel; placed as onlay, retromuscular, or intraperitoneal", "21-73%"],
        ["Sugarbaker technique (BEST)", "Large mesh underlay placed intraperitoneally; stoma exits LATERAL to defect (no central hole; bowel sandwiched between mesh and wall)", "7-15% (best results)"],
        ["Laparoscopic Sugarbaker", "Laparoscopic version; equivalent outcomes to open", "7-15%"],
        ["Stoma reversal", "Restore bowel continuity; eliminates the problem entirely; IDEAL if feasible", "N/A"],
      ],
      [2400, 4000, 2400]
    ),
    new Paragraph({ spacing: { before: 80 }, children: [] }),
    para("Mesh safety note: mesh infection rate only 2-2.6% in large series; bowel erosion extremely rare - previously overestimated risk. (Fischer's Mastery)", { italic: true }),
    new Paragraph({ spacing: { before: 120 }, children: [] }),

    h2("Prevention of Parastomal Hernia"),
    makeTable(
      ["Prevention Strategy", "Evidence / Comment"],
      [
        ["Site stoma through rectus abdominis muscle", "Single most important technical step"],
        ["Correct aperture size (two-finger rule)", "Large enough for tension-free passage; small enough to prevent hernia"],
        ["Ensure no tension on mesentery", "Prevents defect enlargement from retraction forces"],
        ["Prophylactic mesh at stoma creation", "Meta-analysis of 12 RCTs: reduces hernia by ~40%; however, RCTs in last 5 years show no clear advantage (Sabiston)"],
        ["Laparoscopic stoma creation", "Some evidence of lower hernia rates vs open"],
        ["Patient optimisation", "Weight loss, smoking cessation, glucose control before elective surgery"],
      ],
      [3200, 5600]
    ),
    new Paragraph({ spacing: { before: 120 }, children: [] }),
    pageBreak()
  ];
}

function section7_complications() {
  return [
    h1("SECTION 7: COMPLICATIONS OF STOMAS - QUICK REFERENCE"),
    makeTable(
      ["Complication", "Timing", "Features", "Management"],
      [
        ["Ischaemia / Necrosis", "Early (Day 0-2)", "Dusky/black stoma; inspect daily; use proctoscope to assess depth below fascia", "If superficial: observe; If below fascia: urgent reoperation"],
        ["Mucocutaneous separation", "Early", "Mucocutaneous sutures pull through; raw area around stoma", "Usually conservative with intensive stoma care"],
        ["High output (ileostomy)", "Early", ">1000 ml/day; electrolyte depletion", "Loperamide; codeine; dietary adjustment; ORS"],
        ["Skin excoriation", "Early/Late", "Erythema/ulceration around stoma", "Correct fit; barrier products; stoma nurse review"],
        ["Retraction", "Early/Late", "Stoma retracts below skin; leakage", "Karaya paste; convex appliance; surgical refashioning if severe"],
        ["Prolapse", "Late", "Stoma protrudes excessively; more common in loop stomas", "Hernia belt; convert to end stoma; resect redundant bowel"],
        ["Stenosis", "Late", "Narrowing; obstruction", "Dilatation; surgical revision"],
        ["Parastomal hernia", "Late", "Bulge around stoma; appliance difficulties; obstruction risk", "Belt; mesh repair (Sugarbaker preferred); reversal if feasible"],
        ["Food bolus obstruction", "Any", "Ileostomy more common; high fibrous food intake", "NGT decompression; hydration; stoma catheterisation; surgery if needed"],
      ],
      [2000, 1500, 3000, 2500]
    ),
    new Paragraph({ spacing: { before: 120 }, children: [] }),
    pageBreak()
  ];
}

function section8_examTips() {
  return [
    h1("SECTION 8: EXAM REVISION - KEY POINTS"),
    h2("Must-Know Facts"),
    bullet("A stoma is sited within the RECTUS ABDOMINIS MUSCLE - reduces parastomal hernia"),
    bullet("Ileostomy HAS a spout (2-3 cm); colostomy is FLUSH or slightly everted only"),
    bullet("Loop stoma has a ROD/BRIDGE to prevent retraction - removed after a few days"),
    bullet("~25% of temporary stomas are NEVER reversed"),
    bullet("Parastomal hernia rate: >50% at 5 years"),
    bullet("Best repair for parastomal hernia: SUGARBAKER technique (7-15% recurrence)"),
    bullet("Simple suture repair of parastomal hernia: ~100% recurrence - do NOT use alone"),
    bullet("Transverse loop colostomy: AVOID - prone to prolapse, difficult to site, poor adhesion"),
    bullet("Colostomy irrigation: 750-1000 ml water, every 24-48 h, sigmoid colostomy only"),
    bullet("High output ileostomy: >1000 ml/day (normal ~500 ml/day)"),
    new Paragraph({ spacing: { before: 120 }, children: [] }),

    h2("Ileostomy Electrolytes (Memorise)"),
    keyBox("Sodium", "110-120 mmol/L"),
    keyBox("Potassium", "6-12 mmol/L"),
    keyBox("Chloride", "40-70 mmol/L"),
    keyBox("Bicarbonate", "30-40 mmol/L"),
    new Paragraph({ spacing: { before: 120 }, children: [] }),

    h2("Appliance Summary"),
    makeTable(
      ["Stoma", "Appliance Type"],
      [
        ["Ileostomy", "Drainable bag - ALWAYS (liquid, enzymatic output)"],
        ["Sigmoid colostomy", "Non-drainable bag (formed stool)"],
        ["Transverse colostomy", "Drainable bag (semi-liquid, like ileostomy)"],
        ["Colostomy irrigation", "No bag needed between irrigations - plastic cap only"],
      ],
      [2800, 6000]
    ),
    new Paragraph({ spacing: { before: 120 }, children: [] }),

    h2("Parastomal Hernia Repair - Recurrence Rates"),
    makeTable(
      ["Technique", "Recurrence"],
      [
        ["Primary suture repair", "~100% - NOT recommended"],
        ["Stoma relocation", "Same rate at new site - NOT recommended"],
        ["Keyhole mesh", "21-73%"],
        ["Sugarbaker (BEST)", "7-15%"],
        ["Laparoscopic Sugarbaker", "7-15%"],
      ],
      [4000, 4800]
    ),
    new Paragraph({ spacing: { before: 120 }, children: [] }),

    h2("Sources"),
    bullet("Sabiston Textbook of Surgery - Chapter 95 (Stoma Types, Colostomy, Stoma Marking)"),
    bullet("Bailey & Love's Short Practice of Surgery, 28th Ed. - Chapter 64 (Parastomal Hernia), Chapter 77 (Stoma types, complications)"),
    bullet("Fischer's Mastery of Surgery, 8th Ed. - Chapter 129 (Ostomy Marking), Chapter 143 (Stoma Complications, Parastomal Hernia)"),
    bullet("Pye's Surgical Handicraft, 22nd Ed. - Chapter 20 (Stoma Care, Appliances, Irrigation)"),
  ];
}

// ─────────────────────────────────────────────────────────────────────
// ASSEMBLE DOCUMENT
// ─────────────────────────────────────────────────────────────────────
const doc = new Document({
  styles: {
    default: {
      document: {
        run: { font: "Calibri", size: 20, color: DARK_TXT }
      }
    }
  },
  sections: [{
    properties: {
      page: {
        margin: { top: 900, bottom: 900, left: 900, right: 900 }
      }
    },
    headers: {
      default: new Header({
        children: [
          new Table({
            width: { size: 100, type: WidthType.PERCENTAGE },
            borders: {
              top: { style: BorderStyle.NONE }, bottom: { style: BorderStyle.SINGLE, size: 6, color: TEAL },
              left: { style: BorderStyle.NONE }, right: { style: BorderStyle.NONE },
              insideH: { style: BorderStyle.NONE }, insideV: { style: BorderStyle.NONE }
            },
            rows: [new TableRow({
              children: [
                new TableCell({
                  borders: { top: { style: BorderStyle.NONE }, bottom: { style: BorderStyle.NONE }, left: { style: BorderStyle.NONE }, right: { style: BorderStyle.NONE } },
                  children: [new Paragraph({
                    children: [new TextRun({ text: "STOMA - Surgical Study Guide", bold: true, size: 18, color: TEAL, font: "Calibri" })]
                  })]
                }),
                new TableCell({
                  borders: { top: { style: BorderStyle.NONE }, bottom: { style: BorderStyle.NONE }, left: { style: BorderStyle.NONE }, right: { style: BorderStyle.NONE } },
                  children: [new Paragraph({
                    alignment: AlignmentType.RIGHT,
                    children: [new TextRun({ text: "Sabiston • Bailey & Love • Fischer's • Pye's", size: 16, color: SLATE, font: "Calibri", italic: true })]
                  })]
                })
              ]
            })]
          })
        ]
      })
    },
    footers: {
      default: new Footer({
        children: [new Paragraph({
          alignment: AlignmentType.CENTER,
          children: [
            new TextRun({ text: "Page ", size: 16, color: SLATE, font: "Calibri" }),
            new TextRun({ children: [PageNumber.CURRENT], size: 16, color: SLATE, font: "Calibri" }),
            new TextRun({ text: " of ", size: 16, color: SLATE, font: "Calibri" }),
            new TextRun({ children: [PageNumber.TOTAL_PAGES], size: 16, color: SLATE, font: "Calibri" }),
          ]
        })]
      })
    },
    children: [
      ...coverPage(),
      ...section1_definition(),
      ...section2_classification(),
      ...section3_marking(),
      ...section4_technique(),
      ...section5_stomaCare(),
      ...section6_paraHernia(),
      ...section7_complications(),
      ...section8_examTips(),
    ]
  }]
});

Packer.toBuffer(doc).then(buffer => {
  fs.writeFileSync("/home/daytona/workspace/stoma-study/Stoma_Study_Guide.docx", buffer);
  console.log("SUCCESS: Document written.");
}).catch(err => {
  console.error("ERROR:", err);
  process.exit(1);
});
Running Command

cd /home/daytona/workspace/stoma-study && node generate.js 2>&1

Running Command

python /home/daytona/skills/docx/scripts/office/validate.py /home/daytona/workspace/stoma-study/Stoma_Study_Guide.docx 2>&1

Running Command

cd /home/daytona/workspace/stoma-study && python -c "import zipfile; z = zipfile.ZipFile('Stoma_Study_Guide.docx'); print('Files in docx:', z.namelist()[:10]); print('File size:', __import__('os').path.getsize('Stoma_Study_Guide.docx'), 'bytes')"

Your study document is ready:

Stoma Study Guide

Word Document · DOCX


What's inside (8 sections):
SectionContent
1Definition & Overview
2Classification - by content, duration, configuration, site (with full comparison tables)
3Stoma Siting & Marking - 4-step process, areas to avoid, special patient considerations
4Colostomy - Indications, end colostomy technique, loop colostomy technique, double-barrel
5Stoma Care - Nurse role, appliances, accessories, postoperative care, irrigation method, skin care, diet, ileostomy physiology
6Parastomal Hernia - Definition, causes, clinical features, management (all repair techniques with recurrence rates)
7Complications Quick Reference Table
8Exam Revision - Key facts, must-memorise electrolytes, appliance summary, repair recurrence rates
Formatting: Colour-coded headings (teal/steel/slate), alternating-row tables, key fact boxes, page numbers, running header with sources, and a formatted cover page. Sourced from Sabiston, Bailey & Love, Fischer's Mastery, and Pye's Surgical Handicraft.

In this i am only able to one page only

Running Command

cd /home/daytona/workspace/stoma-study && python3 -c " import zipfile, re with zipfile.ZipFile('Stoma_Study_Guide.docx') as z: xml = z.read('word/document.xml').decode('utf-8') # Count page breaks pb = xml.count('lastRenderedPageBreak') + xml.count('pageBreak') + xml.count('w:br w:type=\"page\"') + xml.count('w:type=\"page\"') print('Page break markers found:', pb) print('Document XML size:', len(xml), 'bytes') # Check for sectPr print('Section properties (sectPr):', xml.count('sectPr')) print('First 2000 chars of body:') body_start = xml.find('<w:body>') print(xml[body_start:body_start+500]) "

Running Command

cd /home/daytona/workspace/stoma-study && python3 -c " import zipfile, re with zipfile.ZipFile('Stoma_Study_Guide.docx') as z: xml = z.read('word/document.xml').decode('utf-8') # Find actual page break XML idx = xml.find('PageBreak') print('PageBreak at:', idx) print('Context:', xml[max(0,idx-100):idx+200]) # Check w:br type page idx2 = xml.find('w:type=\"page\"') print('w:type=page at:', idx2) if idx2 > 0: print('Context:', xml[max(0,idx2-100):idx2+200]) "

Running Command

cd /home/daytona/workspace/stoma-study && python /home/daytona/skills/docx/scripts/office/soffice.py --headless --convert-to pdf Stoma_Study_Guide.docx 2>&1

Running Command

libreoffice --headless --convert-to pdf --outdir /home/daytona/workspace/stoma-study/ /home/daytona/workspace/stoma-study/Stoma_Study_Guide.docx 2>&1

Running Command

ls -la /home/daytona/workspace/stoma-study/ && df -h /home/daytona/workspace/

Running Command

# Try converting to PDF using a temp directory cp /home/daytona/workspace/stoma-study/Stoma_Study_Guide.docx /tmp/Stoma_Study_Guide.docx libreoffice --headless --convert-to pdf --outdir /tmp/ /tmp/Stoma_Study_Guide.docx 2>&1 ls -la /tmp/Stoma_Study_Guide.pdf 2>/dev/null && echo "PDF created" || echo "PDF not created"

Running Command

# Check page count and copy to workspace python3 -c " import subprocess result = subprocess.run(['pdfinfo', '/tmp/Stoma_Study_Guide.pdf'], capture_output=True, text=True) print(result.stdout) " cp /tmp/Stoma_Study_Guide.pdf /home/daytona/workspace/stoma-study/Stoma_Study_Guide.pdf ls -lh /home/daytona/workspace/stoma-study/Stoma_Study_Guide.pdf

14 pages confirmed. Here are both formats:
PDF (opens fully on any device - 14 pages):

Stoma Study Guide

PDF Document · PDF

Word document (for editing):

Stoma Study Guide

Word Document · DOCX

The DOCX was showing only one page because the file was being previewed in a limited viewer (browser inline preview). The PDF version will open all 14 pages correctly in any PDF reader. The content is identical - all 8 sections are there:
  1. Definition & Overview
  2. Classification tables (by content, duration, configuration, site)
  3. Stoma Siting & Marking (4-step process + special patients table)
  4. Colostomy - Indications & Operative Technique
  5. Stoma Care (appliances, accessories, postop care, irrigation, skin care, diet)
  6. Parastomal Hernia (causes, management, all repair techniques with recurrence rates)
  7. Complications Quick Reference
  8. Exam Revision Key Points

Stoma care

Based on everything we've already covered from the textbooks, here is a complete, exam-ready write-up on Stoma Care:

Stoma Care

(Pye's Surgical Handicraft 22nd Ed, Bailey & Love 28th Ed, Fischer's Mastery of Surgery 8th Ed, Sabiston)

1. The Stoma Care Nurse (Enterostomal Therapist / ET Nurse)

The stoma care nurse is the central figure in stoma management. Their role covers the entire patient journey:
PhaseResponsibilities
PreoperativeCounselling, reassurance, explanation; stoma siting and marking
IntraoperativeAvailable to advise if pre-marking not done
Early postoperativeAppliance fitting; stoma viability checks; patient education
Long-termTroubleshooting complications; appliance updates; psychological support; liaison with patient associations
"A stoma is compatible with a normal life" - patients must be told this explicitly before surgery.

2. Preoperative Counselling

All patients should be seen by the stoma nurse before surgery (even in semi-elective cases):
  • Full explanation of what the stoma is, how it functions, what output to expect
  • Reassurance about body image, relationships, bathing, work, travel, sex
  • Introduction to appliance types and demonstration
  • Contact with Ileostomy Association / Colostomy UK - peer support from members who have lived with stomas
  • Psychological preparation is as important as physical preparation

3. Stoma Appliances

Every appliance has two parts: the bag (collects output) and the flange/baseplate (adheres to skin around the stoma).

One-Piece vs Two-Piece

FeatureOne-PieceTwo-Piece
Bag + flangeInseparableSeparable (click/lock mechanism)
Skin traumaHigher (whole unit changed)Lower (bag changed; base stays 3-5 days)
Ease of useSimplerBetter skin protection
UseSimple, active patientsSensitive peristomal skin

Drainable vs Non-Drainable

TypeDescriptionUsed For
DrainableOpen bottom with clip/tie; emptied when half-fullIleostomy (MANDATORY); transverse colostomy
Non-drainableClosed end; disposed after each useSigmoid colostomy (formed stool)
Key rule: Empty the bag when half-full - a heavier bag detaches the flange from the skin.

Choosing the Right Aperture Size

  • Hole in the flange cut to fit snugly around the stoma
  • Too small = pressure on stoma → ischaemia
  • Too large = effluent contacts skin → excoriation
  • Sizes available: 25-100 mm diameter
  • Stoma shrinks over the first 4-6 weeks - aperture must be re-measured and resized

4. Accessories for Stoma Care

Stoma care accessories - karaya paste, Stomahesive, skin gel, filters, appliance bags, waist belt
AccessoryPurpose
Karaya gum / pasteFills skin irregularities between flange and stoma; excellent skin protectant; applied on skin side of gasket
Stomahesive pasteNa-carboxymethyl cellulose + gelatin + pectin + polyisobutylene; sticks to moist skin; non-reactive; cut to any shape
Barrier creamsProtect peristomal skin from enzymatic excoriation
Charcoal filter / FiltrodorPunctured into the bag; gas escapes silently; odour trapped
DeodorantsAdded inside the bag to reduce odour
Waist beltExtra security; prevents bag detachment
Hernia support beltReduces parastomal hernia bulge; aids appliance adhesion
Plastic cap + beltUsed by natural/irrigation method patients between evacuations - no bag needed

5. Postoperative Stoma Care

Immediate (Day 0-2)

  • Apply a translucent (clear) drainable bag at the end of surgery
  • Allows daily inspection without removing the bag
  • Inspect through the bag for:
What to CheckNormalAbnormal - Act
ColourPink/red, moistDusky/black = ischaemia
Viability testBleeds when gently prickedNo bleeding = necrosis
Depth of necrosis-Use paediatric proctoscope: if viable below fascia = observe; if necrotic below fascia = urgent surgery
OedemaMild (common in week 1, settles)Massive/worsening = review
RetractionStoma at or above skin levelSinking below skin = appliance problem

Days 3-10

  • Colostomy acts within 3-5 days (flatus first, then stool)
  • Ileostomy acts within 24-48 hours; initial output often >1000 ml/day - monitor fluid/electrolytes closely
  • Water and electrolyte balance must be maintained until output settles
  • Remove mucocutaneous sutures at Day 10 (even if absorbable)

Weeks 1-6

  • Stoma shrinks progressively - re-measure and resize the appliance aperture regularly
  • Aim to change the flange as infrequently as possible (ileostomists: every 4-5 days)
  • Teach the patient self-care step by step

6. Ileostomy-Specific Care

Physiology

ParameterValue
Normal daily output~500 ml
High output (abnormal)>1000 ml/day
Sodium110-120 mmol/L
Potassium6-12 mmol/L
Chloride40-70 mmol/L
Bicarbonate30-40 mmol/L
EnzymesProteolytic - digest skin rapidly on contact
The effluent must not contact the skin - the enzyme content causes rapid excoriation. Hence the spout (2-3 cm above skin) is essential.

High Output Ileostomy Management

Causes:
  • Subacute small bowel obstruction
  • Crohn's disease / IBD flare
  • Short bowel syndrome
  • Drugs: laxatives, antibiotics
  • Diet: onions, vegetables, fruits, alcohol
Treatment:
  • Loperamide (first line), codeine, diphenoxylate + atropine (Lomotil)
  • Oral rehydration solution (high Na content)
  • Dietary modification
  • Restrict high-oxalate foods (spinach, leafy greens) - reduces renal stone risk

7. Long-Term Colostomy Management

Three methods exist for sigmoid colostomy patients:

A. Natural Method

  • Relies on a predictable, once-daily action (often stimulus-triggered, e.g. morning tea/coffee)
  • Between actions: a plastic cap with a belt maintains cleanliness - no bag needed
  • Dietary adjustment + antimotility drugs (codeine, loperamide, Lomotil) help establish regularity

B. Appliance Method (most common)

  • One- or two-piece non-drainable bags changed after each action
  • One-piece bags applied over a Stomahesive base (base stays in place several days; only the bag is changed)

C. Colostomy Irrigation Method

The most controlled method - gives freedom from a permanent bag between irrigations.
When started: 2-4 weeks postoperatively, under stoma therapist supervision
Technique (step by step):
  1. Patient sits on the toilet
  2. Attach short plastic cone to the reservoir bag suspended at head height
  3. Gently insert the cone into the stoma (cone design eliminates perforation risk)
  4. Run 750-1000 ml of water at room temperature from reservoir into the colon
  5. Apply a long plastic sleeve (backed by adhesive flange) over the stoma; direct open end into the toilet
  6. Colon evacuates over 10-30 minutes
  7. Fold and clip the sleeve - patient walks around normally during residual evacuation
  8. Remove the sleeve; clean the stoma; apply an adhesive stoma seal
  9. Repeat every 24-48 hours
Advantages: Freedom from a bag between irrigations; lower cost; greater patient control
Disadvantages: Time-consuming; requires motivation and manual dexterity; not suitable for right-sided or transverse colostomies or those with incontinent colon

8. Peristomal Skin Care

Skin problems are the most common complication of stoma management.
ProblemCauseManagement
Chemical excoriationEffluent contacts skin (leakage or oversized aperture)Correct appliance size; karaya / Stomahesive barrier; barrier cream
Allergic contact dermatitisAllergy to adhesive - rash matches exact shape of applianceRemove appliance; use Stomahesive sheet; steroid cream if needed
Mechanical traumaExcessive frequency of flange changes; rough cleaningGentle warm water cleaning; reduce change frequency
Candidal (fungal) infectionMoist, excoriated skin under the flangeAntifungal powder applied under flange before application
MacerationChronic moisture from leakageImprove bag seal; Stomahesive paste to fill skin contour irregularities
Leakage (cause of most skin problems)Wrong aperture size; irregular contour; retraction; ulceration; poor patient education; lack of dexterityAddress specific cause; revise stoma if retracted

9. Dietary Guidance

Stoma TypeKey Advice
IleostomyChew food thoroughly; avoid large fibrous boluses (obstruction risk at fascia); adequate fluid + salt intake; restrict high-oxalate foods; avoid alcohol (increases output)
Sigmoid colostomyRegular meals for regularity; avoid gas-producing foods if troublesome (beans, cabbage, onions, fizzy drinks)
BothReintroduce foods one at a time postoperatively; avoid dehydration; maintain normal mealtimes

10. Psychological and Social Care

ConcernApproach
Body image / self-esteemPre- and postoperative counselling; normalise stoma as compatible with full life
Sexual functionDiscuss APR-related nerve injury preoperatively; address concerns openly
RelationshipsInvolve partner in stoma education if patient wishes
Return to activitiesSwimming, sport, exercise, travel all possible with appropriate appliances
Support groupsColostomy UK, IA (Ileostomy Association) - peer support invaluable
Emotional impactCounselling referral if needed; stoma care nurse ongoing support

11. Complications of Stoma Care

ComplicationFeaturesManagement
Ischaemia / NecrosisDusky/black stoma - Day 0-2; assess depth with proctoscopeSuperficial: observe; Below fascia: urgent surgery
Mucocutaneous separationSutures pull through; raw peri-stomal ringConservative intensive care; stoma nurse
RetractionStoma sinks below skin; major leakage problemConvex appliance; karaya; surgical refashioning
ProlapseExcessive protrusion; common in loop stomasHernia belt; convert to end stoma; resect redundant bowel
StenosisNarrowing; obstructionDilatation; surgical revision
Parastomal herniaBulge around stoma; appliance difficultiesBelt; mesh repair (Sugarbaker); reversal if feasible
High output>1000 ml/day (ileostomy)Loperamide; codeine; dietary change; rehydration
Skin excoriationRedness, ulceration, painCorrect size; barrier products; antifungal if candida

Summary Table: Ileostomy vs Colostomy Care

FeatureIleostomyColostomy (sigmoid)
Bag typeDrainable (always)Non-drainable
Empty bag whenHalf fullAfter each action
Flange changeEvery 4-5 daysEvery few days
Output~500 ml/day (liquid)1-3 times/day (solid)
Main skin riskHIGH (proteolytic enzymes)Lower
Spout neededYES - 2-3 cmNo - flush or slightly everted
Irrigation possibleNoYes (sigmoid only)
Electrolyte lossSignificant - monitor Na+/K+Minimal

Sources: Pye's Surgical Handicraft 22nd Ed (Chapter 20), Bailey & Love 28th Ed (Chapter 77), Fischer's Mastery of Surgery 8th Ed (Chapter 143), Sabiston (Chapter 95)

Generate flashcards for appliance types and complications

Reading File
Reading File
Writing File

~/stoma-study/flashcards.js

const pptxgen = require("pptxgenjs");

const pres = new pptxgen();
pres.layout = "LAYOUT_16x9";
pres.title = "Stoma Appliances & Complications - Flashcards";

// ── Colour palette ──────────────────────────────────────────────────
const C = {
  teal:      "0D7377",
  darkTeal:  "14A085",
  lightTeal: "D4F1EE",
  navy:      "1A2550",
  red:       "C0392B",
  lightRed:  "FDECEA",
  orange:    "E67E22",
  lightOrange: "FEF0E4",
  green:     "1A7A4A",
  lightGreen:"E8F8F0",
  purple:    "6C3483",
  lightPurple:"F4ECF7",
  white:     "FFFFFF",
  offWhite:  "F8FAFB",
  dark:      "1C2833",
  gray:      "566573",
  lightGray: "EBF5FB",
};

// ── Helpers ──────────────────────────────────────────────────────────
function cardBg(slide, bgColor) {
  slide.addShape(pres.ShapeType.rect, {
    x: 0, y: 0, w: "100%", h: "100%",
    fill: { color: bgColor || C.white },
    line: { color: bgColor || C.white },
  });
}

function topBanner(slide, text, color, textColor) {
  slide.addShape(pres.ShapeType.rect, {
    x: 0, y: 0, w: "100%", h: 1.1,
    fill: { color: color },
    line: { color: color },
  });
  slide.addText(text, {
    x: 0, y: 0, w: "100%", h: 1.1,
    fontSize: 22, bold: true, color: textColor || C.white,
    align: "center", valign: "middle", fontFace: "Calibri",
  });
}

function sectionLabel(slide, label, color) {
  slide.addShape(pres.ShapeType.roundRect, {
    x: 0.3, y: 0.15, w: 1.8, h: 0.4,
    fill: { color: color },
    line: { color: color },
    rectRadius: 0.05,
  });
  slide.addText(label, {
    x: 0.3, y: 0.15, w: 1.8, h: 0.4,
    fontSize: 11, bold: true, color: C.white,
    align: "center", valign: "middle", fontFace: "Calibri",
  });
}

function questionBox(slide, question, color) {
  slide.addShape(pres.ShapeType.rect, {
    x: 0.4, y: 1.25, w: 9.2, h: 1.5,
    fill: { color: color },
    line: { color: color },
    shadow: { type: "outer", color: "999999", blur: 6, offset: 2, angle: 45, opacity: 0.3 },
  });
  slide.addText("Q: " + question, {
    x: 0.4, y: 1.25, w: 9.2, h: 1.5,
    fontSize: 20, bold: true, color: C.white,
    align: "center", valign: "middle", fontFace: "Calibri",
    margin: 15,
  });
}

function answerBox(slide, answerLines, y, h, bgColor, textColor) {
  slide.addShape(pres.ShapeType.rect, {
    x: 0.4, y: y, w: 9.2, h: h,
    fill: { color: bgColor },
    line: { color: bgColor },
  });
  const items = answerLines.map((line, i) => ({
    text: line,
    options: { bullet: line.startsWith("•") ? false : true, breakLine: i < answerLines.length - 1, fontSize: 16, color: textColor || C.dark, fontFace: "Calibri" }
  }));
  slide.addText(items, {
    x: 0.5, y: y, w: 9.0, h: h,
    valign: "middle", fontFace: "Calibri", margin: 12,
  });
}

function cardNumber(slide, num, total) {
  slide.addText(`${num} / ${total}`, {
    x: 8.8, y: 5.2, w: 1.1, h: 0.3,
    fontSize: 10, color: C.gray, align: "right", fontFace: "Calibri",
  });
}

function sourceTag(slide) {
  slide.addText("Source: Pye's • Bailey & Love • Fischer's • Sabiston", {
    x: 0.3, y: 5.2, w: 7, h: 0.3,
    fontSize: 9, color: C.gray, italic: true, fontFace: "Calibri",
  });
}

// ────────────────────────────────────────────────────────────────────
// COVER SLIDE
// ────────────────────────────────────────────────────────────────────
function coverSlide() {
  const s = pres.addSlide();
  // Dark gradient background
  s.addShape(pres.ShapeType.rect, { x: 0, y: 0, w: "100%", h: "100%", fill: { color: C.navy }, line: { color: C.navy } });
  // Accent bar
  s.addShape(pres.ShapeType.rect, { x: 0, y: 4.2, w: "100%", h: 1.425, fill: { color: C.teal }, line: { color: C.teal } });
  // Title
  s.addText("STOMA CARE", {
    x: 0.5, y: 0.7, w: 9, h: 1.2,
    fontSize: 54, bold: true, color: C.white,
    align: "center", fontFace: "Calibri", charSpacing: 8,
  });
  // Subtitle
  s.addText("Appliance Types & Complications", {
    x: 0.5, y: 1.9, w: 9, h: 0.8,
    fontSize: 26, color: C.darkTeal, bold: false,
    align: "center", fontFace: "Calibri",
  });
  // Divider
  s.addShape(pres.ShapeType.line, {
    x: 3, y: 2.85, w: 4, h: 0,
    line: { color: C.teal, width: 2 },
  });
  s.addText("Flashcard Study Set", {
    x: 0.5, y: 3.0, w: 9, h: 0.5,
    fontSize: 14, color: "AABBCC", italic: true,
    align: "center", fontFace: "Calibri",
  });
  // Bottom bar text
  s.addText("28 Cards   |   Sabiston • Bailey & Love • Fischer's Mastery • Pye's Surgical Handicraft", {
    x: 0, y: 4.2, w: "100%", h: 1.425,
    fontSize: 14, color: C.white, align: "center", valign: "middle", fontFace: "Calibri",
  });
}

// ────────────────────────────────────────────────────────────────────
// SECTION DIVIDER
// ────────────────────────────────────────────────────────────────────
function sectionDivider(title, subtitle, color) {
  const s = pres.addSlide();
  s.addShape(pres.ShapeType.rect, { x: 0, y: 0, w: "100%", h: "100%", fill: { color: color }, line: { color: color } });
  s.addShape(pres.ShapeType.rect, { x: 0, y: 2.2, w: "100%", h: 0.08, fill: { color: C.white }, line: { color: C.white } });
  s.addText(title, {
    x: 0.5, y: 1.2, w: 9, h: 1.0,
    fontSize: 40, bold: true, color: C.white,
    align: "center", fontFace: "Calibri", charSpacing: 4,
  });
  s.addText(subtitle, {
    x: 0.5, y: 2.5, w: 9, h: 0.8,
    fontSize: 18, color: C.white, italic: true,
    align: "center", fontFace: "Calibri",
  });
}

// ────────────────────────────────────────────────────────────────────
// FLASHCARD BUILDER - standard Q&A
// ────────────────────────────────────────────────────────────────────
function flashcard({ num, total, section, sectionColor, question, answers, qColor, answerBg, textColor }) {
  const s = pres.addSlide();
  cardBg(s, C.offWhite);
  // Top banner
  topBanner(s, section, sectionColor);
  // Question box
  questionBox(s, question, qColor || sectionColor);
  // Answer area
  answerBox(s, answers, 2.85, 2.0, answerBg || C.lightGray, textColor || C.dark);
  cardNumber(s, num, total);
  sourceTag(s);
}

// ────────────────────────────────────────────────────────────────────
// COMPARISON CARD - two columns
// ────────────────────────────────────────────────────────────────────
function compCard({ num, total, section, sectionColor, question, leftTitle, leftItems, rightTitle, rightItems }) {
  const s = pres.addSlide();
  cardBg(s, C.offWhite);
  topBanner(s, section, sectionColor);
  questionBox(s, question, sectionColor);

  // Left column
  s.addShape(pres.ShapeType.rect, {
    x: 0.4, y: 2.85, w: 4.4, h: 2.0,
    fill: { color: C.lightTeal }, line: { color: C.lightTeal },
  });
  s.addText(leftTitle, {
    x: 0.4, y: 2.85, w: 4.4, h: 0.35,
    fontSize: 13, bold: true, color: C.teal,
    align: "center", valign: "middle", fontFace: "Calibri",
  });
  s.addText(leftItems.map((t, i) => ({
    text: t,
    options: { bullet: true, breakLine: i < leftItems.length - 1, fontSize: 14, color: C.dark, fontFace: "Calibri" }
  })), { x: 0.5, y: 3.2, w: 4.2, h: 1.6, valign: "top", margin: 8 });

  // Right column
  s.addShape(pres.ShapeType.rect, {
    x: 5.2, y: 2.85, w: 4.4, h: 2.0,
    fill: { color: C.lightOrange }, line: { color: C.lightOrange },
  });
  s.addText(rightTitle, {
    x: 5.2, y: 2.85, w: 4.4, h: 0.35,
    fontSize: 13, bold: true, color: C.orange,
    align: "center", valign: "middle", fontFace: "Calibri",
  });
  s.addText(rightItems.map((t, i) => ({
    text: t,
    options: { bullet: true, breakLine: i < rightItems.length - 1, fontSize: 14, color: C.dark, fontFace: "Calibri" }
  })), { x: 5.3, y: 3.2, w: 4.2, h: 1.6, valign: "top", margin: 8 });

  cardNumber(s, num, total);
  sourceTag(s);
}

// ────────────────────────────────────────────────────────────────────
// TABLE CARD
// ────────────────────────────────────────────────────────────────────
function tableCard({ num, total, section, sectionColor, question, headers, rows }) {
  const s = pres.addSlide();
  cardBg(s, C.offWhite);
  topBanner(s, section, sectionColor);
  questionBox(s, question, sectionColor);

  const colW = 9.2 / headers.length;
  const startX = 0.4, startY = 2.88;
  const rowH = 1.7 / rows.length;

  // Header row
  headers.forEach((h, ci) => {
    s.addShape(pres.ShapeType.rect, {
      x: startX + ci * colW, y: startY, w: colW, h: 0.38,
      fill: { color: sectionColor }, line: { color: C.white },
    });
    s.addText(h, {
      x: startX + ci * colW, y: startY, w: colW, h: 0.38,
      fontSize: 12, bold: true, color: C.white,
      align: "center", valign: "middle", fontFace: "Calibri",
    });
  });

  // Data rows
  rows.forEach((row, ri) => {
    row.forEach((cell, ci) => {
      const bg = ri % 2 === 0 ? C.lightGray : C.white;
      s.addShape(pres.ShapeType.rect, {
        x: startX + ci * colW, y: startY + 0.38 + ri * rowH, w: colW, h: rowH,
        fill: { color: bg }, line: { color: "CCDDEE" },
      });
      s.addText(cell, {
        x: startX + ci * colW + 0.05, y: startY + 0.38 + ri * rowH, w: colW - 0.1, h: rowH,
        fontSize: 12, color: C.dark,
        align: "center", valign: "middle", fontFace: "Calibri",
      });
    });
  });

  cardNumber(s, num, total);
  sourceTag(s);
}

// ════════════════════════════════════════════════════════════════════
// BUILD ALL CARDS
// ════════════════════════════════════════════════════════════════════
coverSlide();

// ─── SECTION 1: APPLIANCE TYPES ──────────────────────────────────
sectionDivider("SECTION 1", "Stoma Appliances", C.teal);
const SA = "SECTION 1 · Appliance Types";
const total = 28;

flashcard({
  num: 1, total, section: SA, sectionColor: C.teal,
  question: "What are the TWO main components of every stoma appliance?",
  answers: [
    "1. FLANGE / BASEPLATE - adhesive plate that sticks to peristomal skin; has a central aperture cut to fit the stoma",
    "2. BAG - collects stoma output (stool or urine)",
    "Together they form either a one-piece or two-piece system",
  ],
  answerBg: C.lightTeal,
});

compCard({
  num: 2, total, section: SA, sectionColor: C.teal,
  question: "One-piece vs Two-piece appliance - key differences?",
  leftTitle: "ONE-PIECE",
  leftItems: ["Bag + flange are inseparable", "Simpler to apply", "Entire unit changed each time", "Higher skin trauma from frequent removal", "Better for active patients"],
  rightTitle: "TWO-PIECE",
  rightItems: ["Bag separates from baseplate (click/lock)", "Baseplate stays 3-5 days on skin", "Only bag is changed frequently", "Less skin trauma - better for sensitive skin", "More expensive but skin-friendly"],
});

compCard({
  num: 3, total, section: SA, sectionColor: C.teal,
  question: "Drainable vs Non-drainable bag - when to use each?",
  leftTitle: "DRAINABLE BAG",
  leftItems: ["Open bottom with clip/tie", "Emptied when HALF-FULL", "Used for: Ileostomy (MANDATORY)", "Also: transverse colostomy", "Also: right-sided colostomy", "Reason: liquid/semi-liquid output"],
  rightTitle: "NON-DRAINABLE BAG",
  rightItems: ["Closed end, disposed after use", "Used for: sigmoid colostomy", "Reason: formed solid stool", "Changed after each action", "Cannot be emptied - replace whole bag"],
});

flashcard({
  num: 4, total, section: SA, sectionColor: C.teal,
  question: "Why must the bag be emptied when HALF-FULL?",
  answers: [
    "A bag that is more than half-full becomes TOO HEAVY",
    "The excess weight detaches the flange from the peristomal skin",
    "This causes LEAKAGE → skin excoriation and appliance failure",
    "Rule: Empty drainable bags when half-full; replace non-drainable bags after each action",
  ],
  answerBg: C.lightTeal,
});

flashcard({
  num: 5, total, section: SA, sectionColor: C.teal,
  question: "How do you choose the correct aperture (hole) size for the flange?",
  answers: [
    "Measure stoma diameter carefully with measuring guide",
    "Cut aperture to fit SNUGLY around stoma (1-2 mm clearance only)",
    "TOO SMALL → pressure on stoma → ischaemia / ulceration",
    "TOO LARGE → effluent contacts skin → excoriation / chemical dermatitis",
    "IMPORTANT: Stoma shrinks over 4-6 weeks → re-measure and resize regularly",
    "Sizes available: 25-100 mm diameter",
  ],
  answerBg: C.lightTeal,
});

flashcard({
  num: 6, total, section: SA, sectionColor: C.teal,
  question: "What is Stomahesive and what is it made of?",
  answers: [
    "A skin barrier material used in flanges and as a standalone protective sheet",
    "Composition: Sodium carboxymethyl cellulose + gelatin + pectin + polyisobutylene",
    "Properties: Non-reactive to skin; sticks to MOIST surfaces; mouldable to skin contours; easily cut with scissors",
    "Uses: As flange baseplate material; as paste to fill skin irregularities; as protective sheet around stoma",
  ],
  answerBg: C.lightTeal,
});

flashcard({
  num: 7, total, section: SA, sectionColor: C.teal,
  question: "Name 6 key stoma care accessories and their purposes",
  answers: [
    "Karaya gum/paste → fills skin irregularities; excellent protectant",
    "Stomahesive paste → barrier; sticks to moist skin; mouldable",
    "Barrier creams → protect skin from enzymatic excoriation",
    "Charcoal filter (Filtrodor) → gas escapes silently; odour trapped",
    "Waist belt → extra security to prevent bag detachment",
    "Hernia support belt → reduces parastomal hernia bulge; aids bag adhesion",
    "Plastic cap → used by irrigation/natural method patients between evacuations",
  ],
  answerBg: C.lightTeal,
});

tableCard({
  num: 8, total, section: SA, sectionColor: C.teal,
  question: "Which appliance type for which stoma? Quick reference",
  headers: ["Stoma Type", "Bag Type", "Why"],
  rows: [
    ["Ileostomy", "Drainable (ALWAYS)", "Liquid output; enzyme-rich"],
    ["Sigmoid colostomy", "Non-drainable", "Formed stool"],
    ["Transverse colostomy", "Drainable (large)", "Semi-liquid; near belt line"],
    ["Right/Ascending colostomy", "Drainable", "Liquid, enzyme-rich like ileostomy"],
    ["Urostomy / Ileal conduit", "Drainable (urostomy bag)", "Continuous urine output"],
  ],
});

flashcard({
  num: 9, total, section: SA, sectionColor: C.teal,
  question: "How often should the flange be changed for an ileostomy?",
  answers: [
    "EVERY 4-5 DAYS (not more frequently - reduces skin trauma)",
    "The bag is DRAINED (emptied) whenever half-full - independent of flange change",
    "Two-piece: bag changed more frequently; baseplate (flange) every 4-5 days",
    "AVOID changing the flange too often - each removal strips the skin barrier and causes trauma",
    "Stoma shrinks over weeks 1-6 → re-measure and resize aperture each flange change during this period",
  ],
  answerBg: C.lightTeal,
});

flashcard({
  num: 10, total, section: SA, sectionColor: C.teal,
  question: "What are the THREE methods of long-term sigmoid colostomy management?",
  answers: [
    "1. NATURAL METHOD - relies on predictable daily action (stimulus-triggered); plastic cap between actions; no bag needed",
    "2. APPLIANCE METHOD (most common) - non-drainable bags changed after each action; Stomahesive base stays in place",
    "3. IRRIGATION METHOD - 750-1000 ml water instilled every 24-48 h; colon evacuates in 10-30 min; no bag needed between irrigations",
  ],
  answerBg: C.lightTeal,
});

flashcard({
  num: 11, total, section: SA, sectionColor: C.teal,
  question: "Describe the colostomy irrigation technique step by step",
  answers: [
    "1. Patient sits on toilet; plastic cone connected to reservoir at head height",
    "2. Gently insert cone into stoma (cone design = NO perforation risk)",
    "3. Run 750-1000 ml room-temperature water into colon",
    "4. Apply long plastic sleeve over stoma; direct into toilet bowl",
    "5. Colon evacuates in 10-30 minutes",
    "6. Fold and clip sleeve; patient ambulates; residual evacuation continues",
    "7. Remove sleeve; clean stoma; apply adhesive stoma seal",
    "Frequency: Every 24-48 hours | Start: 2-4 weeks postop under stoma therapist supervision",
  ],
  answerBg: C.lightTeal,
});

// ─── SECTION 2: COMPLICATIONS ─────────────────────────────────────
sectionDivider("SECTION 2", "Stoma Complications", C.red);
const SC = "SECTION 2 · Complications";

flashcard({
  num: 12, total, section: SC, sectionColor: C.red,
  question: "How do you assess stoma viability in the immediate postoperative period?",
  answers: [
    "Apply TRANSLUCENT bag at end of surgery → allows inspection without removal",
    "Inspect DAILY through transparent bag for first 48 hours",
    "COLOUR: pink/red + moist = healthy",
    "ISCHAEMIA: dusky/dark → use PAEDIATRIC PROCTOSCOPE to assess depth below fascia",
    "VIABILITY TEST: viable stoma BLEEDS when gently pricked with a needle",
    "If necrosis ABOVE fascia → observe (may slough; worst result = stenosis)",
    "If necrosis BELOW fascia → URGENT SURGICAL REVISION",
  ],
  answerBg: C.lightRed,
  textColor: C.dark,
});

flashcard({
  num: 13, total, section: SC, sectionColor: C.red,
  question: "Stoma ISCHAEMIA - causes, features, and management",
  answers: [
    "CAUSES: Inadequate blood supply at creation; excessive tension; too-small aperture compressing mesentery; twisting of mesentery",
    "FEATURES: Dusky, dark, or black coloured mucosa (vs healthy pink); usually evident Day 0-2",
    "ASSESSMENT: Paediatric proctoscope to check viability below fascia level",
    "Mx if SUPERFICIAL (above fascia): observe; will slough → may stenose later",
    "Mx if BELOW FASCIA: urgent reoperation and stoma refashioning",
  ],
  answerBg: C.lightRed,
});

flashcard({
  num: 14, total, section: SC, sectionColor: C.red,
  question: "Stoma RETRACTION - causes, features, management",
  answers: [
    "DEFINITION: Stoma recedes below the skin surface",
    "CAUSES: Obesity (subcutaneous fat too thick); tension at creation; ischaemia/necrosis; weight gain postop",
    "FEATURES: Leakage (effluent pools around retracted stoma); skin excoriation; appliance failure",
    "Mx CONSERVATIVE: Convex baseplate/flange; karaya paste to build up skin contour; stoma nurse review",
    "Mx SURGICAL: Stoma refashioning/revision if conservative measures fail",
  ],
  answerBg: C.lightRed,
});

flashcard({
  num: 15, total, section: SC, sectionColor: C.red,
  question: "Stoma PROLAPSE - causes, features, management",
  answers: [
    "DEFINITION: Bowel protrudes excessively above skin level",
    "CAUSES: Loop stomas (especially transverse loop colostomy); obesity; increased intra-abdominal pressure; parastomal hernia; pregnancy",
    "FEATURES: Unsightly; appliance difficulties; risk of ischaemia if tightly prolapsed",
    "Mx CONSERVATIVE: Hernia belt with prolapse cover; revised pouching system",
    "Mx SURGICAL: Convert to end stoma; local resection of redundant bowel",
    "EMERGENCY: Obstruction, ischaemia, incarceration → urgent surgery",
    "Reduction: gentle pressure supine; sugar applied to mucosa draws out oedema to aid reduction",
  ],
  answerBg: C.lightRed,
});

flashcard({
  num: 16, total, section: SC, sectionColor: C.red,
  question: "Stoma STENOSIS - causes, features, management",
  answers: [
    "DEFINITION: Narrowing of the stoma lumen",
    "CAUSES: Ischaemia at original creation; Crohn's disease recurrence; mucocutaneous separation with fibrotic healing",
    "FEATURES: Difficulty passing stool; ribbon-like stools; obstruction",
    "Mx: Minor degrees → regular dilatation with finger or dilator",
    "Mx: Severe or recurrent → surgical revision/refashioning",
  ],
  answerBg: C.lightRed,
});

flashcard({
  num: 17, total, section: SC, sectionColor: C.red,
  question: "Mucocutaneous separation - causes and management",
  answers: [
    "DEFINITION: Separation of the mucocutaneous suture line around the stoma",
    "CAUSES: Ischaemia; wound infection; malnutrition; steroid use; sutures cutting through tissue",
    "FEATURES: Raw, exposed area around the stoma; appliance sealing becomes difficult",
    "MANAGEMENT: Usually conservative with intensive stoma care; barrier products to protect exposed tissue; wound packing if deep; allow to heal by secondary intention",
    "Worst outcome: fibrotic healing → stenosis",
  ],
  answerBg: C.lightRed,
});

flashcard({
  num: 18, total, section: SC, sectionColor: C.red,
  question: "HIGH OUTPUT ILEOSTOMY - definition, causes, management",
  answers: [
    "DEFINITION: Output >1000 ml/day (normal ~500 ml/day)",
    "RISK: Sodium + potassium depletion; dehydration; renal stones (uric acid + oxalate)",
    "CAUSES: Subacute SBO; Crohn's disease; short bowel syndrome; antibiotics; laxatives; diet (onions, vegetables, alcohol)",
    "Mx: Loperamide (first line); codeine; Lomotil (diphenoxylate + atropine)",
    "Mx: Oral rehydration solution (high sodium); dietary modification",
    "Mx: Restrict high-oxalate foods (spinach, leafy greens) → reduces renal stone risk",
    "Mx: Treat underlying cause (obstruction, Crohn's flare)",
  ],
  answerBg: C.lightRed,
});

flashcard({
  num: 19, total, section: SC, sectionColor: C.red,
  question: "PERISTOMAL SKIN EXCORIATION - causes and management",
  answers: [
    "CAUSE: Effluent contacts peristomal skin (ileostomy worst - proteolytic enzymes)",
    "Usually due to: wrong aperture size (too large); leakage; poor adhesion",
    "FEATURES: Erythema, ulceration, pain, weeping skin around stoma",
    "Mx: Correct aperture size (snug fit); karaya paste / Stomahesive paste to fill gaps",
    "Mx: Barrier creams; protective Stomahesive sheet under flange",
    "Mx: Stoma nurse review; may need convex baseplate if skin contour irregular",
  ],
  answerBg: C.lightRed,
});

flashcard({
  num: 20, total, section: SC, sectionColor: C.red,
  question: "ALLERGIC CONTACT DERMATITIS around a stoma - how to diagnose and treat",
  answers: [
    "DIAGNOSIS: Rash and erythema corresponds EXACTLY to the shape/outline of the appliance",
    "→ This pattern distinguishes allergy from chemical excoriation (which is around the stoma itself)",
    "CAUSE: Allergy to adhesive component of the flange; uncommon but important",
    "MANAGEMENT:",
    "Remove appliance; gently clean skin",
    "Apply Stomahesive sheet or karaya sheet to skin before reapplying bag",
    "May need steroid cream for severe reactions",
    "Switch to hypoallergenic appliance if available",
  ],
  answerBg: C.lightRed,
});

flashcard({
  num: 21, total, section: SC, sectionColor: C.red,
  question: "FUNGAL INFECTION (Candida) around a stoma - features and management",
  answers: [
    "SETTING: Occurs in moist, excoriated peristomal skin under the flange",
    "FEATURES: Satellite lesions; erythematous rash with papules; itching; classic candidal appearance",
    "Predisposed by: antibiotics; diabetes; immunosuppression; prolonged skin moisture",
    "MANAGEMENT: Antifungal powder (e.g. nystatin or clotrimazole) applied to the skin under the flange before application",
    "Treat underlying cause (e.g. hyperglycaemia); address moisture/leakage causing maceration",
  ],
  answerBg: C.lightRed,
});

// ─── SECTION 3: PARASTOMAL HERNIA ────────────────────────────────
sectionDivider("SECTION 3", "Parastomal Hernia", C.purple);
const PH = "SECTION 3 · Parastomal Hernia";

flashcard({
  num: 22, total, section: PH, sectionColor: C.purple,
  question: "Define parastomal hernia and give its incidence",
  answers: [
    "DEFINITION: Herniation of abdominal contents (bowel or fat) through the fascial defect ADJACENT to the stoma",
    "Creating a stoma inherently creates a potential hernia - the fascia defect tends to enlarge over time",
    "INCIDENCE: >50% at 5 years (Bailey & Love)",
    "Most common complaint: difficulty fitting and maintaining the stoma appliance",
    "Risk directly proportional to length of time the stoma has been present (Fischer's)",
  ],
  answerBg: C.lightPurple,
});

flashcard({
  num: 23, total, section: PH, sectionColor: C.purple,
  question: "What are the CAUSES and RISK FACTORS for parastomal hernia?",
  answers: [
    "TECHNICAL: Aperture too large; stoma outside rectus muscle (most preventable); excessive tension; failed bowel anchoring",
    "PATIENT: Obesity/high BMI; smoking; poorly controlled diabetes; malnutrition; steroids/immunosuppression",
    "MECHANICAL: Chronic cough or straining (raised IAP); weight gain after surgery",
    "TIME: Risk directly proportional to duration of stoma",
    "KEY PREVENTION: Site within rectus abdominis + correct aperture size (two-finger rule)",
  ],
  answerBg: C.lightPurple,
});

flashcard({
  num: 24, total, section: PH, sectionColor: C.purple,
  question: "Clinical features of parastomal hernia",
  answers: [
    "Bulge or swelling ADJACENT to the stoma (visible on coughing/straining/standing)",
    "Most common complaint: DIFFICULTY FITTING/MAINTAINING APPLIANCE",
    "Leakage due to poor bag adhesion over the bulge",
    "Peristomal skin excoriation secondary to leakage",
    "Intermittent stoma obstruction",
    "Pain or discomfort around the stoma",
    "EMERGENCY: acute obstruction or strangulation of herniated bowel",
  ],
  answerBg: C.lightPurple,
});

tableCard({
  num: 25, total, section: PH, sectionColor: C.purple,
  question: "Parastomal hernia repair options - techniques and recurrence rates",
  headers: ["Technique", "Description", "Recurrence"],
  rows: [
    ["Primary suture", "Simple fascial closure", "~100% - AVOID alone"],
    ["Stoma relocation", "Move to opposite side", "Same rate - NOT recommended"],
    ["Keyhole mesh", "Mesh with central aperture; onlay/sublay/intraperitoneal", "21-73%"],
    ["Sugarbaker (BEST)", "Underlay mesh; stoma exits LATERAL to defect (no hole)", "7-15%"],
    ["Lap. Sugarbaker", "Laparoscopic version; equivalent outcomes", "7-15%"],
    ["Stoma reversal", "Restore bowel continuity; eliminates problem", "N/A - IDEAL"],
  ],
});

flashcard({
  num: 26, total, section: PH, sectionColor: C.purple,
  question: "Why is the Sugarbaker technique preferred over the keyhole mesh technique?",
  answers: [
    "KEYHOLE: Mesh has central aperture through which bowel passes → weak point; recurrence 21-73%",
    "SUGARBAKER: Large underlay mesh placed intraperitoneally; the stoma limb exits LATERAL to the fascial defect",
    "→ No central hole = mesh covers the entire defect",
    "→ Bowel sandwiched between mesh and anterior abdominal wall",
    "→ Recurrence only 7-15%",
    "Mesh infection rate: only 2-2.6% in large series (much lower than historically feared)",
    "Laparoscopic Sugarbaker achieves equivalent recurrence rates to open",
  ],
  answerBg: C.lightPurple,
});

flashcard({
  num: 27, total, section: PH, sectionColor: C.purple,
  question: "How do you PREVENT a parastomal hernia at the time of stoma creation?",
  answers: [
    "1. SITE within the RECTUS ABDOMINIS MUSCLE (single most important step)",
    "2. Correct aperture - TWO-FINGER RULE (not so large as to cause hernia)",
    "3. NO TENSION on the mesentery - mobilise bowel adequately",
    "4. Prophylactic MESH at creation: large-pore polypropylene in retromuscular space",
    "   → Meta-analysis of 12 RCTs: reduces hernia by ~40%",
    "   → BUT: recent 5-year RCTs show NO clear advantage (Sabiston)",
    "5. Patient optimisation: weight loss, smoking cessation, glucose control",
  ],
  answerBg: C.lightPurple,
});

// ─── FINAL SUMMARY CARD ──────────────────────────────────────────
sectionDivider("RAPID REVIEW", "Complications at a Glance", C.navy);

tableCard({
  num: 28, total, section: "RAPID REVIEW · All Complications",
  sectionColor: C.navy,
  question: "All stoma complications - timing, key feature, key action",
  headers: ["Complication", "Timing", "Key Feature", "Key Action"],
  rows: [
    ["Ischaemia", "Day 0-2", "Dusky/black stoma", "Proctoscope → if below fascia: urgent surgery"],
    ["Mucocutaneous separation", "Early", "Raw ring around stoma", "Conservative care; wound packing"],
    ["High output (ileo)", "Early", ">1000 ml/day", "Loperamide; rehydrate; diet"],
    ["Retraction", "Early/Late", "Stoma sinks below skin", "Convex appliance → refashion if fails"],
    ["Prolapse", "Late", "Bowel protrudes excessively", "Belt; convert to end stoma"],
    ["Stenosis", "Late", "Narrowing, obstruction", "Dilatation → revision"],
    ["Parastomal hernia", "Late", "Bulge; appliance failure", "Belt → Sugarbaker mesh repair"],
    ["Skin excoriation", "Any", "Erythema/ulceration", "Correct aperture; barrier products"],
  ],
});

// ── Write file ───────────────────────────────────────────────────────
pres.writeFile({ fileName: "/home/daytona/workspace/stoma-study/Stoma_Flashcards.pptx" })
  .then(() => console.log("SUCCESS: Stoma_Flashcards.pptx created"))
  .catch(e => { console.error("ERROR:", e); process.exit(1); });
Running Command

cd /home/daytona/workspace/stoma-study && node flashcards.js 2>&1

Running Command

ls -lh /home/daytona/workspace/stoma-study/Stoma_Flashcards.pptx && python3 -c " import zipfile z = zipfile.ZipFile('/home/daytona/workspace/stoma-study/Stoma_Flashcards.pptx') slides = [f for f in z.namelist() if f.startswith('ppt/slides/slide') and f.endswith('.xml')] print(f'Total slides: {len(slides)}') "

Your flashcard deck is ready - 33 slides total:

Stoma Flashcards

Presentation · PPTX


What's inside (28 flashcards across 3 sections):

Section 1 - Appliance Types (Cards 1-11) (Teal theme)
#Topic
1Two main components of every appliance
2One-piece vs Two-piece comparison
3Drainable vs Non-drainable - when to use each
4Why empty when half-full
5Choosing correct aperture size
6What is Stomahesive (composition + properties)
76 key accessories and their purposes
8Which appliance for which stoma (table)
9Flange change frequency for ileostomy
10Three methods of long-term colostomy management
11Colostomy irrigation technique - step by step
Section 2 - Complications (Cards 12-21) (Red theme)
  • Ischaemia assessment, retraction, prolapse, stenosis, mucocutaneous separation, high output ileostomy, skin excoriation, allergic dermatitis, fungal infection
Section 3 - Parastomal Hernia (Cards 22-27) (Purple theme)
  • Definition, causes/risk factors, clinical features, repair techniques with recurrence rates, Sugarbaker vs keyhole, prevention
Rapid Review (Card 28) (Navy theme)
  • Master summary table of all complications
This is a shared conversation. Sign in to Orris to start your own chat.