C - Describe clinical features of diseases of various aetiology affecting all systems in the adult and geriatric population . Make a clinical discussion for elog book in simple docs or pdf format

Asking for Preferences
Reading File
Reading File
Running Command

mkdir -p /home/daytona/workspace/elog && ls /home/daytona/workspace/elog/

Writing File

~/elog/generate_elog.js

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

// ─── Helpers ──────────────────────────────────────────────────────────────────
function h1(text) {
  return new Paragraph({ heading: HeadingLevel.HEADING_1, children: [new TextRun({ text, bold: true, size: 32, font: "Arial", color: "1F3864" })] });
}
function h2(text) {
  return new Paragraph({ heading: HeadingLevel.HEADING_2, children: [new TextRun({ text, bold: true, size: 26, font: "Arial", color: "2E4057" })] });
}
function h3(text) {
  return new Paragraph({ heading: HeadingLevel.HEADING_3, children: [new TextRun({ text, bold: true, size: 24, font: "Arial", color: "1B4332" })] });
}
function bold(text) { return new TextRun({ text, bold: true, font: "Arial", size: 22 }); }
function normal(text) { return new TextRun({ text, font: "Arial", size: 22 }); }
function bullet(text, ref="bullets", lvl=0) {
  const parts = [];
  // support **bold** inline
  const segments = text.split(/(\*\*[^*]+\*\*)/);
  for (const seg of segments) {
    if (seg.startsWith("**") && seg.endsWith("**")) {
      parts.push(new TextRun({ text: seg.slice(2,-2), bold: true, font: "Arial", size: 22 }));
    } else {
      parts.push(new TextRun({ text: seg, font: "Arial", size: 22 }));
    }
  }
  return new Paragraph({ numbering: { reference: ref, level: lvl }, children: parts, spacing: { after: 60 } });
}
function para(text, spacing=120) {
  return new Paragraph({ children: [new TextRun({ text, font: "Arial", size: 22 })], spacing: { after: spacing } });
}
function pageBreak() {
  return new Paragraph({ children: [new PageBreak()] });
}
function spacer() { return new Paragraph({ children: [new TextRun("")], spacing: { after: 120 } }); }

function sectionLabel(label) {
  return new Paragraph({
    children: [new TextRun({ text: label, bold: true, color: "FFFFFF", font: "Arial", size: 22 })],
    shading: { type: ShadingType.SOLID, color: "2D6A4F" },
    spacing: { before: 200, after: 80 },
    indent: { left: 200, right: 200 },
  });
}

// ─── Disease block ─────────────────────────────────────────────────────────────
function diseaseBlock(name, etiology, clinicalFeatures, geriatricNotes, investigations, management) {
  const items = [];
  items.push(h3(name));
  items.push(sectionLabel("Aetiology"));
  for (const e of etiology) items.push(bullet(e));
  items.push(spacer());
  items.push(sectionLabel("Clinical Features"));
  for (const c of clinicalFeatures) items.push(bullet(c));
  items.push(spacer());
  if (geriatricNotes && geriatricNotes.length > 0) {
    items.push(sectionLabel("Geriatric Considerations"));
    for (const g of geriatricNotes) items.push(bullet(g));
    items.push(spacer());
  }
  items.push(sectionLabel("Investigations"));
  for (const i of investigations) items.push(bullet(i));
  items.push(spacer());
  items.push(sectionLabel("Management Overview"));
  for (const m of management) items.push(bullet(m));
  items.push(spacer());
  return items;
}

// ─── CONTENT DATA ──────────────────────────────────────────────────────────────
const content = [];

// TITLE PAGE
content.push(new Paragraph({
  children: [new TextRun({ text: "CLINICAL DISCUSSION E-LOG BOOK", bold: true, size: 52, font: "Arial", color: "1F3864" })],
  alignment: AlignmentType.CENTER,
  spacing: { before: 1200, after: 400 }
}));
content.push(new Paragraph({
  children: [new TextRun({ text: "Diseases of Various Aetiology — Adult & Geriatric Population", size: 28, font: "Arial", color: "2E4057", italics: true })],
  alignment: AlignmentType.CENTER,
  spacing: { after: 200 }
}));
content.push(new Paragraph({
  children: [new TextRun({ text: "Structured Clinical Discussions Across All Body Systems", size: 24, font: "Arial", color: "555555" })],
  alignment: AlignmentType.CENTER,
  spacing: { after: 400 }
}));
content.push(new Paragraph({
  children: [new TextRun({ text: "Date: June 2026", size: 22, font: "Arial", color: "888888" })],
  alignment: AlignmentType.CENTER,
  spacing: { after: 600 }
}));
content.push(pageBreak());

// INTRO
content.push(h1("Introduction"));
content.push(para("This e-log book documents clinical discussions of common and important diseases encountered in the adult and geriatric population, organized by body system. For each condition, the aetiology, clinical features (symptoms and signs), geriatric considerations, relevant investigations, and an overview of management are presented in a structured format suitable for clinical logging and revision."));
content.push(para("Geriatric patients often present atypically — with blunted febrile responses, absence of classic pain, cognitive changes, or falls as the only manifestation. These nuances are highlighted separately for each condition."));
content.push(spacer());
content.push(pageBreak());

// ══════════════════════════════════════════════════════════════════════════════
// 1. CARDIOVASCULAR SYSTEM
// ══════════════════════════════════════════════════════════════════════════════
content.push(h1("1. Cardiovascular System"));
content.push(spacer());

content.push(...diseaseBlock(
  "1.1  Acute Myocardial Infarction (AMI)",
  [
    "Coronary artery atherosclerosis with plaque rupture (most common — Type 1 MI)",
    "Coronary vasospasm (Prinzmetal angina — Type 2 MI)",
    "Supply-demand mismatch: severe anaemia, tachyarrhythmia, sepsis (Type 2 MI)",
    "Risk factors: hypertension, diabetes mellitus, dyslipidaemia, smoking, family history, obesity",
  ],
  [
    "**Symptoms:** Severe crushing central chest pain, radiating to left arm/jaw, onset at rest or exertion",
    "Associated: diaphoresis, nausea/vomiting, dyspnoea, sense of impending doom",
    "STEMI: ST elevation ≥1 mm in ≥2 contiguous limb leads or ≥2 mm in precordial leads",
    "NSTEMI / UA: ST depression, T-wave inversion, or dynamic ECG changes without elevation",
    "**Signs:** Tachycardia, hypotension (in cardiogenic shock), S3/S4 gallop, new mitral regurgitation murmur (papillary muscle rupture)",
    "Killip classification used to grade severity of heart failure post-MI",
  ],
  [
    "Atypical presentations common: epigastric pain, fatigue, syncope, confusion — chest pain may be absent",
    "Higher mortality in elderly; delayed presentation is frequent",
    "Polypharmacy interactions complicate antiplatelet and anticoagulant use",
    "Pre-existing renal impairment influences contrast use and dosing of renally-cleared drugs",
  ],
  [
    "12-lead ECG — serial recordings essential; look for reciprocal changes",
    "Troponin I/T (high-sensitivity): rises within 1–3 h, peaks at 12–24 h",
    "CK-MB: peaks earlier (~24 h); useful for re-infarction detection",
    "FBC, renal function, electrolytes, lipid profile, BNP/NT-proBNP",
    "Echo: wall motion abnormalities, EF assessment, mechanical complications",
    "Coronary angiography (gold standard for diagnosis and definitive therapy)",
  ],
  [
    "STEMI: Primary PCI within 90 min (door-to-balloon); fibrinolysis if PCI unavailable within 120 min",
    "NSTEMI/UA: Risk stratify (GRACE/TIMI score); early invasive strategy within 24–72 h for high-risk",
    "Dual antiplatelet therapy: Aspirin 300 mg loading + Ticagrelor 180 mg (or Clopidogrel 600 mg)",
    "Anticoagulation: Heparin (UFH/LMWH) or Fondaparinux",
    "Secondary prevention: Beta-blocker, ACE inhibitor/ARB, statin, spironolactone if EF <40%",
    "Cardiac rehabilitation and lifestyle modification",
  ]
));

content.push(...diseaseBlock(
  "1.2  Chronic Heart Failure (CHF)",
  [
    "Ischaemic heart disease (most common cause in developed world)",
    "Hypertensive heart disease, dilated cardiomyopathy, valvular disease",
    "HFrEF (EF <40%): dilated cardiomyopathy, post-MI; HFpEF (EF ≥50%): hypertension, DM, obesity",
    "Other: arrhythmias (AF), thyroid disease, alcohol, chemotherapy (cardiotoxicity)",
  ],
  [
    "**Left heart failure:** Dyspnoea (exertional → orthopnoea → PND), fatigue, reduced exercise tolerance",
    "**Right heart failure:** Peripheral pitting oedema (ankles→sacrum), hepatomegaly, raised JVP, ascites",
    "**Signs:** Displaced apex beat, S3 gallop (volume overload), basal crepitations, pleural effusion",
    "NYHA functional classification: I (no symptoms) to IV (symptoms at rest)",
    "Acute decompensation: acute pulmonary oedema — frothy pink sputum, severe orthopnoea, hypoxia",
  ],
  [
    "HFpEF predominates in elderly women; oedema and dyspnoea often attributed to other causes",
    "Falls, confusion, and anorexia can be presenting features rather than classic dyspnoea",
    "Diuretic-induced electrolyte imbalances (hyponatraemia, hypokalaemia) are frequent and dangerous",
    "Digoxin toxicity risk is higher due to reduced renal clearance",
  ],
  [
    "BNP/NT-proBNP: elevated; useful for diagnosis and monitoring",
    "ECG: LVH, LBBB, atrial fibrillation",
    "Chest X-ray: cardiomegaly, upper lobe diversion, Kerley B lines, pleural effusion",
    "Echocardiography: cornerstone — EF, wall motion, valvular function, diastolic parameters",
    "Renal function and electrolytes: serial monitoring essential",
    "Thyroid function, iron studies (reversible causes)",
  ],
  [
    "HFrEF: ACE inhibitor (or ARNI — sacubitril/valsartan), beta-blocker (carvedilol/bisoprolol), MRA (spironolactone/eplerenone), SGLT2 inhibitor (dapagliflozin/empagliflozin) — all shown to reduce mortality",
    "Diuretics (furosemide) for symptom control; titrate to dry weight",
    "HFpEF: blood pressure control, rate control in AF, SGLT2 inhibitors now recommended",
    "CRT for LBBB + EF <35%; ICD for EF <35% on optimal medical therapy",
    "Acute decompensation: IV diuresis, nitrates, oxygen; NIV in pulmonary oedema",
  ]
));

content.push(pageBreak());

// ══════════════════════════════════════════════════════════════════════════════
// 2. RESPIRATORY SYSTEM
// ══════════════════════════════════════════════════════════════════════════════
content.push(h1("2. Respiratory System"));
content.push(spacer());

content.push(...diseaseBlock(
  "2.1  Community-Acquired Pneumonia (CAP)",
  [
    "Bacterial: Streptococcus pneumoniae (most common), Haemophilus influenzae, Mycoplasma pneumoniae (atypical), Legionella pneumophila",
    "Viral: Influenza, RSV, SARS-CoV-2",
    "Aspiration pneumonia: anaerobes (in patients with dysphagia, reduced consciousness)",
    "Risk factors: extremes of age, immunosuppression, smoking, chronic lung/heart disease",
  ],
  [
    "**Symptoms:** Fever with rigors, productive cough (rust-coloured sputum in pneumococcal pneumonia), pleuritic chest pain, dyspnoea",
    "Atypical (walking pneumonia): dry cough, headache, myalgia, extrapulmonary features (rash, confusion)",
    "**Signs:** Tachypnoea, tachycardia, decreased breath sounds, dullness to percussion, bronchial breathing, coarse crepitations over affected lobe",
    "Severity: CURB-65 (Confusion, Urea >7, RR ≥30, BP <90/60, Age ≥65) — score ≥2 warrants admission",
  ],
  [
    "Classic fever may be absent; hypothermia can occur in severe infection",
    "Confusion and delirium may be the sole presenting feature (beware 'silent' pneumonia)",
    "Aspiration pneumonia more common due to dysphagia, poor dentition, reduced cough reflex",
    "Higher CURB-65 scores expected; functional decline post-pneumonia is significant",
  ],
  [
    "Chest X-ray: lobar/segmental consolidation; bilateral in atypical or COVID pneumonia",
    "FBC: neutrophilia (bacterial), lymphopenia (viral/atypical)",
    "CRP, procalcitonin (guides antibiotic decision)",
    "Sputum culture and sensitivity (before antibiotics if possible)",
    "Blood cultures (if CURB-65 ≥2 or hospitalised)",
    "Urinary antigen: Legionella, S. pneumoniae",
    "Arterial blood gas if SpO2 <94% or severe disease",
  ],
  [
    "Low severity (CURB-65 0–1): oral Amoxicillin 500 mg TDS for 5 days; add Clarithromycin for atypical cover",
    "Moderate/severe: IV co-amoxiclav + Clarithromycin; or Levofloxacin monotherapy",
    "Atypical/Legionella: Fluoroquinolone or Macrolide",
    "Supportive: oxygen to maintain SpO2 94–98%, IV fluids, analgesia for pleurisy",
    "ICU admission and ventilatory support for severe/refractory hypoxia",
    "Pneumococcal and influenza vaccination for prevention",
  ]
));

content.push(...diseaseBlock(
  "2.2  Chronic Obstructive Pulmonary Disease (COPD) — Acute Exacerbation",
  [
    "Smoking (primary cause — >80% of cases)",
    "Air pollution, occupational dust/fumes (coal, silica, cadmium)",
    "Alpha-1 antitrypsin deficiency (genetic — consider in non-smokers, early-onset)",
    "Exacerbation triggers: respiratory infections (Haemophilus influenzae, S. pneumoniae, viruses), air pollution, non-compliance with inhalers",
  ],
  [
    "**Stable COPD:** Progressive exertional dyspnoea, chronic productive cough, wheeze, reduced exercise tolerance",
    "**Acute exacerbation (AECOPD):** Worsening dyspnoea beyond normal day-to-day variation, increased sputum volume and purulence, wheeze",
    "**Signs:** Barrel chest (hyperinflation), use of accessory muscles, pursed-lip breathing, decreased air entry, prolonged expiration, wheeze",
    "Hypoxia: cyanosis; Hypercapnia: drowsiness, asterixis, bounding pulse (CO2 retention)",
    "GOLD classification (spirometry-based): I (mild, FEV1 ≥80%) to IV (very severe, FEV1 <30%)",
  ],
  [
    "Reduced perception of dyspnoea — patients may not report breathlessness accurately",
    "Cor pulmonale (RHF secondary to pulmonary hypertension) is a late complication more common in elderly",
    "Target oxygen saturation 88–92% to avoid hypoxic drive suppression",
    "Malnutrition and muscle wasting (sarcopenia) worsen prognosis",
  ],
  [
    "Spirometry: FEV1/FVC <0.70 post-bronchodilator (gold standard for diagnosis)",
    "Chest X-ray: hyperinflation, flat diaphragm, bullae; exclude pneumonia/pneumothorax",
    "ABG: type II respiratory failure (hypoxia + hypercapnia, raised bicarbonate)",
    "FBC: polycythaemia (chronic hypoxia), neutrophilia (infection)",
    "Sputum culture, CRP; ECG (RVH, right axis deviation in cor pulmonale)",
  ],
  [
    "Controlled oxygen: 24–28% Venturi mask, target SpO2 88–92%",
    "Nebulised bronchodilators: Salbutamol + Ipratropium (back-to-back or continuous)",
    "Systemic corticosteroids: Prednisolone 30–40 mg PO for 5 days",
    "Antibiotics if purulent sputum or 2/3 Anthonisen criteria: Amoxicillin/Doxycycline/Clarithromycin",
    "NIV (BiPAP): pH <7.35 with hypercapnia unresponsive to medical therapy",
    "Stable maintenance: LABA + LAMA (e.g., formoterol + tiotropium); add ICS if ≥2 exacerbations/year",
    "Pulmonary rehabilitation; smoking cessation; long-term oxygen therapy if PaO2 <7.3 kPa at rest",
  ]
));

content.push(pageBreak());

// ══════════════════════════════════════════════════════════════════════════════
// 3. GASTROINTESTINAL SYSTEM
// ══════════════════════════════════════════════════════════════════════════════
content.push(h1("3. Gastrointestinal System"));
content.push(spacer());

content.push(...diseaseBlock(
  "3.1  Upper GI Bleed (Peptic Ulcer Disease)",
  [
    "Helicobacter pylori infection (~70% of duodenal ulcers, ~50% of gastric ulcers)",
    "NSAID/aspirin use: disrupts mucosal prostaglandin-mediated cytoprotection",
    "Zollinger-Ellison syndrome: gastrinoma causing hypersecretion",
    "Stress ulcers: critically ill patients (mechanical ventilation, burns, sepsis)",
    "Other bleeds: oesophageal varices (portal hypertension), Mallory-Weiss tear, angiodysplasia",
  ],
  [
    "Epigastric pain: duodenal ulcer (relieved by food), gastric ulcer (worsened by food), burning character",
    "**Upper GI bleed:** Haematemesis (fresh blood or 'coffee-ground' vomit), melaena (tarry black stools)",
    "Symptoms of hypovolaemia: dizziness, syncope, palpitations, cold extremities",
    "**Signs:** Pallor, tachycardia, hypotension, epigastric tenderness; peritonism if perforation",
    "Rockall/Glasgow-Blatchford score used to stratify urgency of endoscopy",
  ],
  [
    "NSAID-induced ulcers often bleed silently without prior dyspepsia in elderly",
    "Haemodynamic compromise from smaller blood losses due to poor compensatory response",
    "Melaena may be the first symptom; haematemesis less common if on anticoagulants",
    "High risk of re-bleeding; PPI prophylaxis essential when NSAIDs required",
  ],
  [
    "FBC: anaemia (acute bleed: normocytic; chronic: microcytic iron-deficiency)",
    "Clotting studies, INR, LFTs (exclude varices / liver disease)",
    "Urea/creatinine ratio >100:1 suggests upper GI source",
    "Urgent OGD (within 24 h if haemodynamically stable; within 2 h if shocked/ongoing bleed)",
    "H. pylori: urea breath test, stool antigen, CLO test on biopsy",
  ],
  [
    "Resuscitation: IV access, fluid resuscitation, blood transfusion (target Hb ≥70–80 g/L)",
    "IV PPI: omeprazole 80 mg bolus → 8 mg/h infusion (pre- and post-endoscopy)",
    "Endoscopic haemostasis: adrenaline injection, thermal coagulation, haemoclips",
    "H. pylori eradication: triple therapy (PPI + Clarithromycin + Amoxicillin for 7–14 days)",
    "Stop NSAIDs; switch to COX-2 inhibitor + PPI cover if unavoidable",
    "Surgical intervention or interventional radiology if endoscopy fails",
  ]
));

content.push(...diseaseBlock(
  "3.2  Liver Cirrhosis and its Complications",
  [
    "Alcoholic liver disease (most common in Western countries)",
    "Non-alcoholic fatty liver disease (NAFLD/NASH) — increasingly prevalent with obesity/DM",
    "Viral hepatitis: Hepatitis B (cirrhosis risk ~15–25%), Hepatitis C",
    "Autoimmune hepatitis, primary biliary cholangitis (PBC), haemochromatosis, Wilson's disease",
  ],
  [
    "**Compensated cirrhosis:** Often asymptomatic; fatigue, malaise, spider naevi, palmar erythema",
    "**Decompensated cirrhosis (key features):**",
    "Ascites: abdominal distension, shifting dullness, fluid thrill; risk of spontaneous bacterial peritonitis (SBP)",
    "Hepatic encephalopathy: confusion, asterixis (flapping tremor), fetor hepaticus, altered sleep pattern",
    "Variceal bleeding: haematemesis, melaena — life-threatening",
    "Jaundice, coagulopathy (raised PT), hypoalbuminaemia (peripheral oedema, muscle wasting)",
    "Hepatorenal syndrome, hepatopulmonary syndrome (late complications)",
    "Child-Pugh and MELD scores used to assess severity and prognosis",
  ],
  [
    "Encephalopathy may be triggered by infection, constipation, GI bleed, or diuretics",
    "Hyponatraemia, renal impairment, and electrolyte disturbances are common",
    "Increased risk of osteoporosis and falls due to vitamin D deficiency and muscle wasting",
    "Drug metabolism significantly impaired — careful dose adjustment required",
  ],
  [
    "LFTs: elevated bilirubin, low albumin, raised ALT/AST (AST:ALT ratio >2:1 in alcoholic hepatitis)",
    "Clotting: prolonged PT/INR (marker of synthetic function)",
    "FBC: thrombocytopenia (hypersplenism), anaemia",
    "Ultrasound abdomen: nodular liver, splenomegaly, ascites; Doppler for portal vein thrombosis",
    "Upper endoscopy: oesophageal/gastric varices",
    "Ascitic tap (diagnostic): cell count, culture, albumin (SAAG >11 g/L confirms portal hypertension)",
    "AFP: hepatocellular carcinoma surveillance",
  ],
  [
    "Abstinence from alcohol; antiviral therapy for hepatitis B/C",
    "Ascites: sodium restriction, spironolactone ± furosemide; therapeutic paracentesis + albumin for refractory",
    "SBP: IV cefotaxime; prophylaxis with norfloxacin or co-trimoxazole",
    "Variceal bleeding: terlipressin + antibiotics; urgent OGD with band ligation; TIPSS for refractory",
    "Hepatic encephalopathy: lactulose, rifaximin; identify and treat precipitant",
    "Liver transplantation for end-stage disease (MELD ≥15)",
  ]
));

content.push(pageBreak());

// ══════════════════════════════════════════════════════════════════════════════
// 4. NEUROLOGICAL SYSTEM
// ══════════════════════════════════════════════════════════════════════════════
content.push(h1("4. Neurological System"));
content.push(spacer());

content.push(...diseaseBlock(
  "4.1  Ischaemic Stroke",
  [
    "Large artery atherosclerosis: stenosis of carotid or intracranial vessels",
    "Cardioembolic: atrial fibrillation (most common cardiac cause), intracardiac thrombus, infective endocarditis, cardiomyopathy",
    "Small vessel disease (lacunar infarcts): hypertension, DM causing lipohyalinosis of perforating arteries",
    "Other: vasculitis, dissection, hypercoagulable states (antiphospholipid syndrome)",
    "TOAST classification categorizes stroke subtype",
  ],
  [
    "Sudden onset focal neurological deficit — FAST: Face drooping, Arm weakness, Speech difficulty, Time to call emergency services",
    "**Anterior circulation (MCA territory):** Contralateral hemiplegia/hemiparesis, hemisensory loss, homonymous hemianopia, aphasia (dominant hemisphere), neglect (non-dominant)",
    "**Posterior circulation (vertebrobasilar):** Vertigo, diplopia, ataxia, dysarthria, dysphagia, crossed sensory signs",
    "**Lacunar syndromes:** Pure motor, pure sensory, sensorimotor, ataxic hemiparesis",
    "TIA: same deficits but resolve within 24 h (typically <1 h); high risk of stroke (ABCD2 score)",
  ],
  [
    "Stroke is the leading cause of disability in elderly; presentations can be atypical (confusion, falls)",
    "Pre-existing cognitive impairment complicates neurological assessment",
    "Dysphagia assessment is critical before any oral intake",
    "Post-stroke delirium, depression, and dementia are common",
    "Thrombolysis eligibility often limited by age-related comorbidities and anticoagulant use",
  ],
  [
    "CT head (non-contrast): IMMEDIATE — excludes haemorrhage (hyperdense lesion) before thrombolysis",
    "MRI brain with DWI: most sensitive for early infarction; identifies penumbra",
    "CT/MR angiography: identifies large vessel occlusion (LVO) — indicates thrombectomy",
    "12-lead ECG: atrial fibrillation",
    "FBC, clotting, glucose, lipids, renal function, LFTs",
    "Carotid Doppler/CT angio: stenosis in anterior circulation strokes",
    "Echocardiogram (bubble study for PFO in young/cryptogenic stroke)",
    "24–48 h cardiac monitoring: paroxysmal AF detection",
  ],
  [
    "Hyper-acute: IV Alteplase (0.9 mg/kg, max 90 mg) within 4.5 h of onset (if no haemorrhage, recent surgery)",
    "Mechanical thrombectomy: LVO within 24 h of onset (NIHSS ≥6)",
    "Aspirin 300 mg stat after haemorrhage excluded; switch to clopidogrel/DAPT for 21 days then monotherapy",
    "Anticoagulation: Apixaban/Rivaroxaban/Edoxaban if AF — delay 2–14 days based on infarct size",
    "Stroke unit care: MDT (physiotherapy, OT, SLT), early mobilisation, VTE prophylaxis",
    "Secondary prevention: antihypertensives (target BP <130/80), statin, antiplatelet/anticoagulant",
    "Carotid endarterectomy if stenosis 70–99% (ipsilateral to stroke, within 2 weeks)",
  ]
));

content.push(...diseaseBlock(
  "4.2  Parkinson's Disease",
  [
    "Idiopathic (primary PD): most common; loss of dopaminergic neurons in substantia nigra pars compacta",
    "Lewy body pathology: alpha-synuclein aggregation",
    "Secondary parkinsonism: drug-induced (antipsychotics, metoclopramide), vascular parkinsonism, PSP, MSA",
    "Genetic forms: LRRK2, PINK1, Parkin mutations (5–10%)",
  ],
  [
    "Cardinal motor features (TRAP): **T**remor (resting, 4–6 Hz 'pill-rolling', improves with movement), **R**igidity (cogwheel/leadpipe), **A**kinesia/bradykinesia, **P**ostural instability (late)",
    "Unilateral onset, asymmetric, slowly progressive",
    "Gait: shuffling, reduced arm swing, freezing, festination; Turning en bloc",
    "**Non-motor features:** Constipation, anosmia, REM sleep behaviour disorder (may precede motor symptoms by years), depression, cognitive decline, autonomic dysfunction (orthostatic hypotension, urinary urgency)",
    "Dementia (Parkinson's Disease Dementia) — develops in ~80% after 20 years",
    "Hypomimia (mask-like face), hypophonia (soft voice), micrographia",
  ],
  [
    "Increased risk of falls; freezing of gait and postural instability are major hazards",
    "Dementia more common and progresses faster with advancing age",
    "Swallowing dysfunction — aspiration pneumonia risk",
    "Orthostatic hypotension — syncope and falls; avoid antihypertensives if symptomatic",
    "Avoid haloperidol, prochlorperazine, metoclopramide — worsen parkinsonism",
    "Lewy body dementia must be distinguished (dementia precedes/accompanies motor features, fluctuating cognition, visual hallucinations)",
  ],
  [
    "Clinical diagnosis: UK Brain Bank criteria (bradykinesia + 1 of rest tremor/rigidity + asymmetric onset)",
    "No definitive blood/imaging test for idiopathic PD",
    "MRI brain: exclude structural causes, vascular lesions",
    "DaTscan (SPECT imaging): reduced dopamine transporter activity — distinguishes PD from ET and drug-induced parkinsonism",
    "Response to levodopa trial (supports diagnosis if dramatic improvement)",
    "Neuropsychological testing for cognitive assessment",
  ],
  [
    "Levodopa (co-careldopa/co-beneldopa): most effective dopaminergic therapy; complications with long-term use — motor fluctuations ('wearing off', 'on-off'), dyskinesias",
    "Dopamine agonists (pramipexole, ropinirole): used as initial therapy in younger patients to delay levodopa complications",
    "MAO-B inhibitors (rasagiline, selegiline): neuroprotective, mild symptomatic benefit",
    "COMT inhibitors (entacapone): extend levodopa effect",
    "Deep brain stimulation (STN or GPi): advanced PD with motor fluctuations, refractory tremor",
    "MDT: physiotherapy, OT, SLT, neurologist, Parkinson's disease nurse specialist",
  ]
));

content.push(pageBreak());

// ══════════════════════════════════════════════════════════════════════════════
// 5. ENDOCRINE SYSTEM
// ══════════════════════════════════════════════════════════════════════════════
content.push(h1("5. Endocrine System"));
content.push(spacer());

content.push(...diseaseBlock(
  "5.1  Diabetes Mellitus Type 2",
  [
    "Insulin resistance + progressive beta-cell failure",
    "Risk factors: obesity (central adiposity), physical inactivity, family history, ethnicity (South Asian, Afro-Caribbean), GDM",
    "Associated with metabolic syndrome: hypertension, dyslipidaemia, NAFLD, polycystic ovarian syndrome",
  ],
  [
    "**Classic osmotic symptoms (often mild or absent in T2DM):** Polyuria, polydipsia, polyphagia, unexplained weight loss",
    "Fatigue, recurrent infections (UTI, skin infections, candidiasis), blurred vision (osmotic lens changes)",
    "Acanthosis nigricans (skin crease darkening in insulin resistance)",
    "**Complications:**",
    "Macrovascular: IHD, stroke, peripheral arterial disease (diabetic foot — neuropathy + ischaemia)",
    "Microvascular: Retinopathy (leading cause of blindness in working-age adults), nephropathy (proteinuria → CKD), neuropathy (stocking-glove sensory loss, autonomic neuropathy — gastroparesis, erectile dysfunction)",
    "**Acute complications:** Hyperosmolar hyperglycaemic state (HHS) — severe hyperglycaemia, hyperosmolality, profound dehydration without significant ketosis",
  ],
  [
    "Hyperglycaemia may be less severe; HHS is more common than DKA",
    "Hypoglycaemia is particularly dangerous (increased falls, arrhythmias, cognitive impairment)",
    "Impaired hypoglycaemia awareness common — autonomic neuropathy blunts adrenergic warning symptoms",
    "Simplified glycaemic targets (HbA1c 53–64 mmol/mol) to reduce hypoglycaemia risk in frail elderly",
    "Deprescribing of multiple antidiabetic agents may be appropriate in frail patients",
  ],
  [
    "Fasting plasma glucose ≥7.0 mmol/L or random ≥11.1 mmol/L or HbA1c ≥48 mmol/mol (6.5%) on two occasions (or one if symptomatic)",
    "HbA1c: glycaemic control over preceding 3 months",
    "Urine albumin-creatinine ratio (ACR): nephropathy screening",
    "eGFR, LFTs, lipid profile",
    "Annual review: retinal photography (ophthalmology), foot examination (10-g monofilament, ABPI)",
    "Blood pressure monitoring",
  ],
  [
    "Lifestyle: diet (Mediterranean or low-carbohydrate), weight loss, exercise",
    "Metformin: first-line (reduce if eGFR <45, stop if <30); lactic acidosis risk with contrast/surgery",
    "SGLT2 inhibitors (empagliflozin, dapagliflozin): cardiovascular and renal protection — preferred in IHD/CKD",
    "GLP-1 receptor agonists (semaglutide, liraglutide): weight loss benefit; CV protection",
    "DPP-4 inhibitors (sitagliptin): weight-neutral, well-tolerated in elderly",
    "Insulin: when oral agents fail; basal insulin (glargine/detemir) added to oral agents",
    "Target HbA1c: 48–53 mmol/mol (6.5–7%); individualise for frail patients",
    "Annual screening for complications; BP and lipid control (ACE inhibitor/ARB, statin)",
  ]
));

content.push(...diseaseBlock(
  "5.2  Hypothyroidism",
  [
    "Primary (most common): Hashimoto's thyroiditis (autoimmune), post-thyroidectomy, post-radioiodine, iodine deficiency (worldwide)",
    "Drug-induced: amiodarone, lithium, interferon",
    "Secondary: pituitary failure (TSH deficiency)",
    "Transient: postpartum thyroiditis, subacute (de Quervain's) thyroiditis",
  ],
  [
    "Weight gain, fatigue, cold intolerance, constipation, dry skin, hair loss, bradycardia",
    "Menorrhagia (pre-menopausal women), infertility",
    "Depression, cognitive slowing, myalgia, carpal tunnel syndrome",
    "**Signs:** Bradycardia, hypertension (diastolic), periorbital/peripheral myxoedema, delayed relaxation of reflexes (hung-up reflexes), macroglossia, goitre (Hashimoto's)",
    "Myxoedema coma (severe hypothyroidism): hypothermia, bradycardia, hypotension, altered consciousness — medical emergency",
  ],
  [
    "Symptoms often dismissed as normal ageing: fatigue, constipation, cognitive decline",
    "Hypothyroidism exacerbates heart failure and hyponatraemia",
    "Amiodarone (commonly used in elderly AF patients) causes both hypothyroidism and hyperthyroidism",
    "Levothyroxine therapy: start with low dose (25–50 mcg) and titrate slowly to avoid precipitating angina or arrhythmia",
  ],
  [
    "TSH: elevated in primary hypothyroidism (best screening test)",
    "Free T4: low (confirms primary hypothyroidism); low TSH + low T4 = secondary hypothyroidism",
    "Anti-TPO antibodies: Hashimoto's thyroiditis",
    "FBC: macrocytic anaemia (associated with pernicious anaemia in autoimmune thyroiditis)",
    "Lipid profile: hypercholesterolaemia (secondary to hypothyroidism)",
    "ECG: bradycardia, low voltage, prolonged QT",
  ],
  [
    "Levothyroxine: 1.6 mcg/kg/day (start lower in elderly/IHD: 25–50 mcg, increase by 25 mcg every 6–8 weeks)",
    "Target TSH: 0.5–2.5 mIU/L (higher range acceptable in elderly to avoid over-replacement)",
    "Myxoedema coma: IV T3 (liothyronine) or T4 in HDU/ITU; hydrocortisone cover (adrenal insufficiency may coexist)",
    "Monitor: TSH every 6–12 months once stable; annually thereafter",
    "Drug interactions: calcium, iron, PPIs reduce levothyroxine absorption — take on empty stomach",
  ]
));

content.push(pageBreak());

// ══════════════════════════════════════════════════════════════════════════════
// 6. RENAL SYSTEM
// ══════════════════════════════════════════════════════════════════════════════
content.push(h1("6. Renal System"));
content.push(spacer());

content.push(...diseaseBlock(
  "6.1  Acute Kidney Injury (AKI)",
  [
    "Pre-renal (most common ~55%): hypovolaemia (haemorrhage, diarrhoea/vomiting, burns, sepsis), decreased cardiac output (heart failure, cardiogenic shock), renal artery stenosis",
    "Intrinsic renal (~40%): ATN (ischaemic or nephrotoxic — NSAIDs, aminoglycosides, contrast), glomerulonephritis (IgA nephropathy, ANCA vasculitis), interstitial nephritis (drugs, infection), rhabdomyolysis",
    "Post-renal (~5%): obstruction — BPH, pelvic malignancy, retroperitoneal fibrosis, bilateral ureteric stones",
    "AKIN/KDIGO criteria: rise in Cr ≥26.5 μmol/L within 48 h, or 1.5× baseline within 7 days, or urine output <0.5 ml/kg/h for ≥6 h",
  ],
  [
    "**Symptoms:** Oliguria/anuria, nausea/vomiting, lethargy, confusion (uraemia); frothy urine (proteinuria)",
    "**Signs of fluid overload:** Peripheral oedema, pulmonary oedema, raised JVP",
    "**Uraemic features (severe):** Asterixis, pericardial friction rub (uraemic pericarditis), Kussmaul respiration (metabolic acidosis)",
    "**Hyperkalaemia:** Muscle weakness, peaked T waves on ECG, life-threatening arrhythmias (sine-wave pattern, VF)",
    "**Post-renal features:** Urinary hesitancy, poor stream, distended bladder (BPH), loin pain (ureteric obstruction)",
  ],
  [
    "Baseline creatinine often elevated (reduced muscle mass → lower creatinine); AKI may be underestimated",
    "NSAIDs and ACE inhibitors/ARBs are major precipitants — review medication on admission",
    "Contrast nephropathy risk is higher — pre-hydration protocol essential",
    "Indwelling urinary catheter monitoring for accurate fluid balance is critical",
    "Frailty complicates renal replacement therapy decisions",
  ],
  [
    "Serum creatinine, eGFR, urea (urea:Cr ratio >100:1 suggests pre-renal)",
    "Electrolytes: hyperkalaemia, hyponatraemia, metabolic acidosis (low HCO3, high anion gap)",
    "Urinalysis and microscopy: casts (granular = ATN; RBC casts = glomerulonephritis), protein, blood",
    "Urine Na and fractional excretion of Na (FeNa <1% pre-renal, >2% intrinsic)",
    "Renal tract ultrasound: hydronephrosis (obstruction), kidney size",
    "ECG: hyperkalaemia changes",
    "Urine protein:creatinine ratio; ANA, ANCA, complement (if glomerulonephritis suspected)",
    "Renal biopsy: if intrinsic AKI of unclear cause (immune-mediated)",
  ],
  [
    "Pre-renal: IV fluid resuscitation (0.9% NaCl or Plasmalyte); treat underlying cause (sepsis, haemorrhage)",
    "Post-renal: urgent urological catheterisation (BPH), percutaneous nephrostomy (ureteric obstruction)",
    "Intrinsic (ATN): supportive — avoid nephrotoxins, careful fluid balance, treat hyperkalaemia",
    "Hyperkalaemia: calcium gluconate (cardiac membrane stabilisation), insulin + dextrose, salbutamol; sodium bicarbonate; Resonium (kayexalate) or patiromer for elimination",
    "Metabolic acidosis: sodium bicarbonate if pH <7.1 or HCO3 <15",
    "Indications for urgent dialysis (HD/CVVH): refractory hyperkalaemia, fluid overload, acidosis, uraemic encephalopathy/pericarditis",
    "Avoid ACE inhibitors/ARBs/NSAIDs/metformin until renal function recovered",
  ]
));

content.push(pageBreak());

// ══════════════════════════════════════════════════════════════════════════════
// 7. MUSCULOSKELETAL SYSTEM
// ══════════════════════════════════════════════════════════════════════════════
content.push(h1("7. Musculoskeletal System"));
content.push(spacer());

content.push(...diseaseBlock(
  "7.1  Rheumatoid Arthritis (RA)",
  [
    "Autoimmune disease: T-cell mediated synovitis; citrullinated peptide antibodies (ACPA/anti-CCP) and RF positive in seropositive disease",
    "HLA-DR4 association (genetic predisposition)",
    "Environmental triggers: smoking (strongly associated), silica, periodontal disease (Porphyromonas gingivalis)",
    "Seropositive RA more severe disease course than seronegative",
  ],
  [
    "Symmetrical inflammatory polyarthritis: MCP/PIP joints of hands, wrists, MTP joints of feet (spares DIP and first CMC in contrast to OA)",
    "Morning stiffness lasting >1 hour (hallmark of inflammatory arthritis)",
    "Systemic features: fatigue, weight loss, low-grade fever, anaemia of chronic disease",
    "**Deformities (late/advanced):** Swan-neck, Boutonniere, Z-deformity of thumb, ulnar deviation at MCPs, subluxation",
    "Extra-articular: rheumatoid nodules (subcutaneous), serositis (pleuritis/pericarditis), Felty's syndrome, vasculitis, Sjogren's overlap, RA-ILD (interstitial lung disease), scleritis, cervical cord compression (atlantoaxial subluxation — important pre-anaesthetic)",
    "DAS28 score used to assess disease activity (target: remission DAS28 <2.6)",
  ],
  [
    "RA typically less active but chronic damage accumulated; joint replacement often required",
    "Steroid use leads to significant complications: osteoporosis, infections, hyperglycaemia",
    "Increased infection risk with DMARDs and biologics — withhold prior to surgery/infection",
    "Methotrexate may need dose reduction in renal impairment (common in elderly)",
    "Atlantoaxial subluxation assessment mandatory before intubation for elective surgery",
  ],
  [
    "RF (rheumatoid factor): present in ~70%; non-specific (also positive in SLE, Sjogren's, infection)",
    "Anti-CCP (ACPA): highly specific (>95%) for RA; marker of erosive disease",
    "ESR, CRP: disease activity markers",
    "FBC: normochromic normocytic anaemia; thrombocytosis",
    "X-ray hands/feet: periarticular osteopenia, joint space narrowing, erosions (Larsen grading)",
    "MRI/Ultrasound: more sensitive for early synovitis and erosions",
    "LFTs, renal function: baseline before DMARD therapy",
  ],
  [
    "Treat-to-target strategy: aim for remission or low disease activity",
    "Conventional DMARDs: Methotrexate (first-line), Hydroxychloroquine, Sulfasalazine, Leflunomide",
    "Bridging therapy: short-course corticosteroids (oral/IM) for flares",
    "Biologics (if inadequate DMARD response): TNF inhibitors (etanercept, adalimumab), IL-6 inhibitors (tocilizumab), anti-CD20 (rituximab), CTLA4-Ig (abatacept)",
    "JAK inhibitors: Tofacitinib, Baricitinib (oral, alternative to biologics — monitor cardiovascular risk)",
    "NSAIDs for symptom relief; consider PPI co-prescription",
    "Physiotherapy, OT, podiatry; surgical joint replacement for severe disease",
  ]
));

content.push(...diseaseBlock(
  "7.2  Osteoporosis and Fragility Fractures",
  [
    "Primary (type I): post-menopausal (oestrogen deficiency → increased osteoclast activity)",
    "Primary (type II): age-related — reduced osteoblast activity",
    "Secondary: corticosteroid use (most common secondary cause), hypogonadism, hyperparathyroidism, hyperthyroidism, malabsorption (vitamin D/calcium deficiency), multiple myeloma, RA",
    "Risk factors: female sex, Caucasian/Asian ethnicity, low BMI, family history, smoking, alcohol, immobility",
  ],
  [
    "Often asymptomatic until fracture occurs",
    "**Fragility fractures:** Fracture from minimal trauma (fall from standing height or less)",
    "Common sites: vertebral (dorsal kyphosis, height loss, back pain — may be painless), distal radius (Colles' fracture), proximal femur (neck of femur fracture), ribs",
    "Vertebral fractures: progressive kyphosis ('dowager's hump'), height loss, chronic back pain, restrictive lung disease",
    "Neck of femur fracture: shortened externally rotated leg, inability to weight bear, hip pain after fall",
  ],
  [
    "Osteoporosis is predominantly a geriatric condition; NOF fractures carry 20–30% mortality at 1 year",
    "Fall prevention is as important as bone protection (multifactorial risk assessment)",
    "Delirium post-fracture/surgery is common and worsens outcomes",
    "Oral bisphosphonates may be poorly tolerated (oesophageal disease, swallowing difficulty) — IV zoledronate preferred",
    "Vitamin D deficiency extremely common; osteomalacia must be excluded before diagnosing osteoporosis",
  ],
  [
    "DEXA scan: BMD measurement at hip and lumbar spine; T-score ≤ -2.5 = osteoporosis; -1 to -2.5 = osteopenia",
    "FRAX tool: 10-year fracture probability including clinical risk factors",
    "Serum calcium, phosphate, vitamin D (25-OH), PTH, ALP (exclude osteomalacia, hyperparathyroidism)",
    "LFTs, TFTs, testosterone (in men), myeloma screen (serum/urine protein electrophoresis)",
    "X-ray of fractured site; MRI spine for vertebral fractures",
  ],
  [
    "Calcium (1000–1200 mg/day dietary) and Vitamin D supplementation (800–1000 IU/day) — foundation",
    "Bisphosphonates (alendronate weekly PO, zoledronate yearly IV, ibandronate): first-line anti-resorptive agents; dental hygiene counselling (osteonecrosis of jaw risk)",
    "Denosumab (SC 6-monthly): alternative to bisphosphonates especially in renal impairment — rebound fractures risk on cessation",
    "Raloxifene (SERM): post-menopausal women; reduces vertebral fracture risk; increases VTE risk",
    "Teriparatide/abaloparatide (PTH analogue): anabolic — for severe osteoporosis or bisphosphonate failure; max 2 years",
    "HRT: reduces bone loss in post-menopausal women; secondary benefit",
    "Fall prevention: strength/balance exercise (tai chi), home hazard assessment, medication review (deprescribe sedatives/antihypertensives), vision correction, hip protectors",
  ]
));

content.push(pageBreak());

// ══════════════════════════════════════════════════════════════════════════════
// 8. HAEMATOLOGICAL CONDITIONS
// ══════════════════════════════════════════════════════════════════════════════
content.push(h1("8. Haematological Conditions"));
content.push(spacer());

content.push(...diseaseBlock(
  "8.1  Anaemia — Clinical Approach",
  [
    "Iron deficiency anaemia: GI blood loss (peptic ulcer, malignancy, IBD), menorrhagia, malabsorption (coeliac disease, post-gastrectomy), poor dietary intake",
    "B12/Folate deficiency: pernicious anaemia (anti-intrinsic factor antibodies), malnutrition, metformin use (impairs B12 absorption), malabsorption",
    "Anaemia of chronic disease/inflammation: RA, chronic infection, CKD, malignancy — functional iron deficiency",
    "Haemolytic anaemia: autoimmune (warm/cold antibodies), hereditary (spherocytosis, G6PD deficiency, sickle cell, thalassaemia), microangiopathic (TTP, HUS)",
    "Aplastic anaemia, myelodysplastic syndrome, bone marrow infiltration",
  ],
  [
    "General: fatigue, exertional dyspnoea, pallor (conjunctival, palmar), tachycardia, flow murmur",
    "**Iron deficiency specific:** Koilonychia (spoon-shaped nails), angular cheilitis, glossitis, Plummer-Vinson syndrome (dysphagia due to post-cricoid web)",
    "**B12 deficiency specific:** Glossitis, subacute combined degeneration of spinal cord (posterior column + corticospinal tract: sensory ataxia, weakness, paraesthesia), peripheral neuropathy, cognitive impairment",
    "**Haemolytic anaemia:** Jaundice (unconjugated bilirubin), splenomegaly, dark urine (haemoglobinuria in intravascular haemolysis)",
    "**Pernicious anaemia:** Often middle-aged/older women; B12 deficiency + achlorhydria + antibodies",
  ],
  [
    "Common and often multifactorial; B12 deficiency may present as dementia-like syndrome",
    "Anaemia worsens cardiac function and cognitive impairment significantly",
    "Iron deficiency in elderly always demands investigation for GI malignancy",
    "Transfusion threshold higher if symptomatic/cardiac comorbidities",
  ],
  [
    "FBC: MCV (microcytic <80 in IDA; macrocytic >100 in B12/folate; normocytic in ACD, haemolysis, acute blood loss)",
    "Blood film: hypochromic microcytes (IDA), macro-ovalocytes + hypersegmented neutrophils (B12/folate), spherocytes (AIHA/hereditary spherocytosis), sickle cells",
    "Serum iron, ferritin (low in IDA; high in ACD), TIBC; reticulocyte count",
    "B12 and folate levels",
    "Reticulocyte count + LDH, bilirubin, haptoglobin (haemolysis screen)",
    "DAT (direct antiglobulin test): AIHA",
    "Colonoscopy/OGD: GI bleeding source in iron deficiency",
  ],
  [
    "Iron deficiency: oral ferrous sulphate 200 mg TDS (improve if intolerant — ferrous gluconate, IV iron sucrose/ferric carboxymaltose)",
    "B12 deficiency: IM hydroxocobalamin 1000 mcg alternate days for 6 doses → 3-monthly (if absorption defect); oral cyanocobalamin if dietary deficiency",
    "Folate: folic acid 5 mg daily (always supplement B12 first if both deficient to prevent subacute combined degeneration)",
    "Pernicious anaemia: lifelong B12 replacement",
    "AIHA: prednisolone first-line; rituximab/splenectomy for refractory",
    "Treat underlying cause (chronic disease, renal anaemia: EPO/erythropoiesis-stimulating agents)",
  ]
));

content.push(pageBreak());

// ══════════════════════════════════════════════════════════════════════════════
// 9. INFECTIONS / SEPSIS
// ══════════════════════════════════════════════════════════════════════════════
content.push(h1("9. Sepsis and Infectious Diseases"));
content.push(spacer());

content.push(...diseaseBlock(
  "9.1  Sepsis",
  [
    "Definition: Life-threatening organ dysfunction caused by a dysregulated host response to infection (Sepsis-3 definition)",
    "Common sources: Pneumonia (most common), UTI/urosepsis, intra-abdominal (peritonitis, cholangitis), skin/soft tissue (cellulitis, necrotising fasciitis), meningitis, line infection",
    "Causative organisms: E. coli/Klebsiella (UTI, abdominal), S. pneumoniae (pneumonia, meningitis), S. aureus (skin, endocarditis), Pseudomonas (immunocompromised, hospital-acquired)",
    "qSOFA criteria: RR ≥22, altered mentation, systolic BP ≤100 — bedside screen",
  ],
  [
    "**Sepsis:** Fever or hypothermia, tachycardia, tachypnoea, altered mental status, oliguria",
    "**Septic shock (subset of sepsis):** Vasopressor requirement to maintain MAP ≥65 mmHg + lactate >2 mmol/L despite adequate resuscitation",
    "Organ dysfunction markers: AKI (raised creatinine), coagulopathy (DIC: petechiae, prolonged clotting), liver dysfunction (raised bilirubin), respiratory failure (ARDS)",
    "Clinical signs: hypotension, mottled skin, prolonged capillary refill time, warm peripheries (early distributive shock) → cold shut-down peripheries (late)",
    "SOFA score used to assess organ dysfunction (score ≥2 = sepsis)",
  ],
  [
    "Presentation frequently atypical: hypothermia rather than fever, confusion/delirium, falls, functional decline",
    "Tachycardia may be absent (beta-blockers, pacemakers)",
    "Sources often occult: aspiration, decubitus ulcers, endocarditis, device infections",
    "Prognosis significantly worse in elderly; Sepsis in care home residents carries high mortality",
    "Fluid resuscitation must be carefully titrated to avoid pulmonary oedema",
  ],
  [
    "Blood cultures (×2 peripheral + line culture if CVC) — BEFORE antibiotics if no >1 hour delay",
    "Lactate: >2 mmol/L (sepsis-related hypoperfusion); >4 mmol/L (septic shock — poor prognosis)",
    "FBC, CRP, procalcitonin, coagulation screen (DIC: low fibrinogen, raised D-dimer, prolonged PT)",
    "Renal/hepatic function panel",
    "Urinalysis + culture; CXR; specific site cultures based on suspected source",
    "ABG: metabolic acidosis, hypoxia",
    "CT scan if intra-abdominal or spinal source suspected",
  ],
  [
    "Surviving Sepsis Bundle (within 1 hour): blood cultures → IV broad-spectrum antibiotics → IV fluid 30 ml/kg crystalloid → lactate measurement → vasopressors if MAP <65 despite fluids",
    "Antibiotics: tailored to suspected source; de-escalate within 48–72 h based on cultures",
    "Vasopressors: noradrenaline (first-line) via central access; vasopressin added if refractory",
    "Source control: drain abscess, remove infected device, debride necrotic tissue, biliary decompression",
    "Corticosteroids: hydrocortisone 200 mg/day in refractory septic shock",
    "Supportive: lung-protective ventilation for ARDS, DVT prophylaxis, blood glucose control (target 6–10 mmol/L)",
  ]
));

content.push(pageBreak());

// ══════════════════════════════════════════════════════════════════════════════
// 10. GERIATRIC SYNDROMES
// ══════════════════════════════════════════════════════════════════════════════
content.push(h1("10. Geriatric Syndromes"));
content.push(spacer());

content.push(...diseaseBlock(
  "10.1  Delirium (Acute Confusional State)",
  [
    "Multifactorial — commonly two or more precipitants in a vulnerable patient",
    "**Common precipitants (PINCH ME mnemonic):** Pain, Infection/Inflammation, Nutrition, Constipation, Hydration, Medication (anticholinergics, benzodiazepines, opioids, steroids), Environment (unfamiliar, poor lighting), Immobility",
    "Predisposing factors (vulnerability): advanced age, pre-existing dementia/cognitive impairment, frailty, sensory impairment, alcohol dependence",
    "Underlying medical causes: UTI, pneumonia, meningitis, AKI/electrolyte disturbances, myocardial infarction, pulmonary embolism, subdural haematoma, post-surgical",
  ],
  [
    "**Core features (DSM-5):** Disturbance of attention and awareness; develops acutely and fluctuates; additional cognitive disturbance (memory, orientation, perception); not explained by pre-existing neurocognitive disorder or coma",
    "**Hyperactive delirium (~25%):** Agitation, combativeness, hallucinations (visual), attempts to pull out lines/catheters — most recognised but least common",
    "**Hypoactive delirium (~50% — most common, most missed):** Withdrawal, somnolence, reduced responsiveness, mumbling speech — often misdiagnosed as depression or dementia",
    "Mixed delirium: alternating between both types (~25%)",
    "Screening tools: 4AT (Alert, AMT4, Attention, Acute change) — rapid bedside screen; CAM (Confusion Assessment Method) — gold standard",
  ],
  [
    "Hypoactive delirium is almost exclusively a geriatric condition and is frequently missed",
    "Delirium in elderly may be the sole presenting feature of serious illness (MI, PE, abdominal emergency)",
    "Delirium on background of dementia (most common scenario) is particularly challenging to assess",
    "Associated with increased mortality, longer hospital stay, institutionalisation, and accelerated cognitive decline",
    "Physical restraints increase agitation and complications — avoid",
  ],
  [
    "No diagnostic blood/imaging test for delirium itself — investigations directed at cause",
    "FBC, CRP, U&E, LFTs, TFTs, glucose, calcium, magnesium",
    "Urinalysis and culture; blood cultures (if febrile or sepsis suspected)",
    "ABG if respiratory cause suspected; ECG",
    "CT head if new focal neurological signs, head injury, or uncertain diagnosis",
    "Lumbar puncture if meningitis/encephalitis suspected",
    "Review medication list — drug chart is a diagnostic tool",
  ],
  [
    "**Non-pharmacological (first-line — prevent and treat):** Treat underlying cause; orientation cues (clocks, calendars, familiar faces); adequate lighting; minimise ward moves; ensure hearing aids and glasses; early mobilisation; avoid catheters unless essential; hydration and nutrition",
    "Adequate analgesia (unrecognised pain is a common cause)",
    "**Pharmacological (only for severe agitation with risk to patient/staff):** Haloperidol 0.5–1 mg PO/IM (avoid in Lewy body dementia — use quetiapine instead); lorazepam for alcohol withdrawal delirium",
    "Avoid benzodiazepines unless alcohol/benzodiazepine withdrawal — worsen most delirium",
    "Prevention: NICE recommends delirium prevention bundle in all at-risk patients on admission",
  ]
));

content.push(...diseaseBlock(
  "10.2  Falls in the Elderly",
  [
    "Multifactorial — intrinsic and extrinsic factors interact",
    "**Intrinsic (patient factors):** Muscle weakness (sarcopenia), balance/gait impairment, visual impairment, cognitive impairment, orthostatic hypotension, peripheral neuropathy (DM), Parkinson's disease, previous stroke",
    "**Extrinsic (environmental):** Poor lighting, loose rugs, wet floors, inappropriate footwear, inadequate walking aids",
    "**Medications (major modifiable cause):** Sedatives, antihypertensives (especially alpha-blockers), diuretics, antidiabetics (hypoglycaemia), antipsychotics, anticholinergics",
    "Acute precipitant: infection, ACS, arrhythmia, PE, dehydration, pain",
  ],
  [
    "**History:** Circumstances of fall (mechanical vs. syncope), prodrome (dizziness, palpitations, chest pain), number of falls in past year, injuries sustained",
    "**Gait/balance assessment:** Get Up and Go test (>12 seconds = fall risk); Berg Balance Scale",
    "**Consequences of fall:** NOF fracture (shortened externally rotated leg, unable to weight bear), subdural haematoma (in anticoagulated patients), soft tissue injury, hypothermia if prolonged time on floor, 'long lie' → rhabdomyolysis/pressure injury",
    "**Psychosocial impact:** Fear of falling (reduces activity, leads to further deconditioning and social isolation)",
  ],
  [
    "Falls are the leading cause of injury death in adults over 65",
    "30% of community-dwelling adults over 65 fall at least once per year",
    "Hip fractures carry 1-year mortality of 20–30%",
    "Unexplained falls always warrant investigation for serious underlying disease",
    "NICE recommends multifactorial risk assessment for all elderly with recurrent falls or those presenting to healthcare after a fall",
  ],
  [
    "ECG: arrhythmia, heart block (fall due to syncope)",
    "Orthostatic BP measurements (lying-to-standing): drop ≥20 mmHg systolic or ≥10 mmHg diastolic",
    "Blood glucose (hypoglycaemia)",
    "FBC, U&E, calcium, vitamin D",
    "X-rays of injured area; CT head if head injury or on anticoagulants",
    "Vision assessment, audiometry",
    "Holter monitor/implantable loop recorder if cardiac syncope suspected",
  ],
  [
    "Multifactorial intervention programme — most evidence-based approach",
    "Physiotherapy: strength and balance exercises (Otago programme, tai chi); gait re-education",
    "Medication review: deprescribe or reduce doses of high-fall-risk medications",
    "Treat orthostatic hypotension: morning fluids, compression stockings, fludrocortisone/midodrine if severe",
    "Vision correction (cataract surgery, glasses); hearing aid provision",
    "Home hazard assessment and modification (occupational therapy)",
    "Calcium + Vitamin D supplementation; treat osteoporosis (see 7.2)",
    "Hip protectors for highest-risk patients",
  ]
));

content.push(pageBreak());

// SUMMARY TABLE
content.push(h1("Quick Reference Summary Table"));
content.push(spacer());

const tableData = [
  ["System", "Disease", "Key Clinical Feature", "First Investigation", "First-Line Treatment"],
  ["Cardiovascular", "AMI (STEMI)", "Crushing chest pain, ST elevation", "12-lead ECG + Troponin", "Primary PCI within 90 min"],
  ["Cardiovascular", "Heart Failure", "Dyspnoea, oedema, S3 gallop", "BNP + Echocardiogram", "ACEi/ARNI + BB + MRA + SGLT2i"],
  ["Respiratory", "Pneumonia (CAP)", "Fever, cough, consolidation", "CXR + Blood cultures", "Amoxicillin ± Clarithromycin"],
  ["Respiratory", "COPD exacerbation", "Worsening dyspnoea, wheeze, sputum", "ABG + Spirometry", "Nebulisers + Steroids + Antibiotics"],
  ["GI", "Upper GI Bleed", "Haematemesis, melaena, haemodynamic instability", "OGD within 24 h", "IV PPI + Endoscopic haemostasis"],
  ["GI", "Liver Cirrhosis", "Ascites, encephalopathy, varices", "USS Abdomen + Ascitic tap", "Treat cause + Lactulose + Terlipressin"],
  ["Neurology", "Ischaemic Stroke", "Sudden focal deficit (FAST)", "CT head (non-contrast) STAT", "Thrombolysis/Thrombectomy within window"],
  ["Neurology", "Parkinson's Disease", "Rest tremor, rigidity, bradykinesia", "Clinical; ± DaTscan", "Levodopa / Dopamine agonist"],
  ["Endocrine", "Type 2 Diabetes", "Polyuria, fatigue, complications", "HbA1c + Fasting glucose", "Metformin + lifestyle; SGLT2i for CVD"],
  ["Endocrine", "Hypothyroidism", "Fatigue, cold intolerance, bradycardia", "TSH (elevated)", "Levothyroxine (low starting dose in elderly)"],
  ["Renal", "AKI", "Oliguria, uraemia, hyperkalaemia", "Creatinine + Renal USS", "Treat cause; IV fluids; dialysis if severe"],
  ["MSK", "Rheumatoid Arthritis", "Symmetrical MCP/PIP arthritis, morning stiffness", "Anti-CCP + X-ray hands", "Methotrexate (treat-to-target)"],
  ["MSK", "Osteoporosis", "Fragility fracture; kyphosis", "DEXA scan + FRAX", "Bisphosphonates + Ca/Vit D"],
  ["Haematology", "Anaemia (IDA)", "Fatigue, pallor, koilonychia", "FBC + Ferritin", "Iron supplementation; investigate cause"],
  ["Infection", "Sepsis", "Fever/hypothermia, organ dysfunction, ↑lactate", "Blood cultures + Lactate", "Hourly bundle: abx + fluids + vasopressors"],
  ["Geriatrics", "Delirium", "Acute confusion, fluctuating, hypoactive/hyperactive", "4AT screen + Root cause", "Treat cause; non-pharmacological measures"],
  ["Geriatrics", "Falls", "Recurrent falls, fear of falling, injuries", "ECG + Orthostatic BP + Gait test", "Multifactorial intervention + physio"],
];

const tableRows = tableData.map((row, rowIdx) => new TableRow({
  tableHeader: rowIdx === 0,
  children: row.map((cell, colIdx) => new TableCell({
    width: { size: colIdx === 0 ? 14 : (colIdx === 1 ? 18 : (colIdx === 2 ? 25 : 21)), type: WidthType.PERCENTAGE },
    shading: rowIdx === 0 ? { type: ShadingType.SOLID, color: "1F3864" } : (rowIdx % 2 === 0 ? { type: ShadingType.SOLID, color: "EBF4FF" } : { type: ShadingType.SOLID, color: "FFFFFF" }),
    verticalAlign: VerticalAlign.CENTER,
    children: [new Paragraph({
      children: [new TextRun({ text: cell, font: "Arial", size: 18, bold: rowIdx === 0, color: rowIdx === 0 ? "FFFFFF" : "000000" })],
      spacing: { before: 60, after: 60 },
    })]
  }))
}));

content.push(new Table({
  rows: tableRows,
  width: { size: 100, type: WidthType.PERCENTAGE },
}));
content.push(spacer());
content.push(pageBreak());

// FOOTER NOTE
content.push(h1("Clinical Notes for E-Log Entry"));
content.push(para("Each clinical encounter should be documented with the following structure in your elog system:"));
for (const item of [
  "Patient demographics: age, sex, relevant comorbidities",
  "Presenting complaint and history of presenting illness",
  "Relevant past medical/drug/allergy/social/family history",
  "Clinical examination findings (general, systemic)",
  "Differential diagnoses considered",
  "Investigations ordered and results",
  "Clinical discussion: reasoning, aetiology, significance of findings",
  "Management plan and patient education",
  "Outcome and follow-up",
  "Learning points and reflection",
]) {
  content.push(bullet(item));
}
content.push(spacer());
content.push(para("This elog book serves as a clinical reference and educational record. Always cross-reference clinical findings with current national guidelines (NICE, BHS, AHA/ACC, ESC, GOLD, GINA) and local trust protocols.", 200));

// ─── BUILD DOCUMENT ─────────────────────────────────────────────────────────
const doc = new Document({
  numbering: {
    config: [
      {
        reference: "bullets",
        levels: [{
          level: 0,
          format: LevelFormat.BULLET,
          text: "\u2022",
          alignment: AlignmentType.LEFT,
          style: { paragraph: { indent: { left: 720, hanging: 360 } } }
        }]
      }
    ]
  },
  styles: {
    default: {
      document: { run: { font: "Arial", size: 22 } }
    },
    paragraphStyles: [
      {
        id: "Heading1", name: "Heading 1", basedOn: "Normal", next: "Normal", quickFormat: true,
        run: { size: 36, bold: true, font: "Arial", color: "1F3864" },
        paragraph: { spacing: { before: 400, after: 200 }, outlineLevel: 0 }
      },
      {
        id: "Heading2", name: "Heading 2", basedOn: "Normal", next: "Normal", quickFormat: true,
        run: { size: 28, bold: true, font: "Arial", color: "2E4057" },
        paragraph: { spacing: { before: 300, after: 160 }, outlineLevel: 1 }
      },
      {
        id: "Heading3", name: "Heading 3", basedOn: "Normal", next: "Normal", quickFormat: true,
        run: { size: 26, bold: true, font: "Arial", color: "1B5E3B" },
        paragraph: { spacing: { before: 240, after: 120 }, outlineLevel: 2 }
      },
    ]
  },
  sections: [{
    children: content
  }]
});

Packer.toBuffer(doc).then(buffer => {
  fs.writeFileSync("/home/daytona/workspace/elog/Clinical_Discussion_Elog.docx", buffer);
  console.log("DONE");
});
Running Command

cd /home/daytona/workspace/elog && node generate_elog.js 2>&1

Running Command

python /home/daytona/skills/docx/scripts/office/validate.py /home/daytona/workspace/elog/Clinical_Discussion_Elog.docx 2>&1

Running Command

ls /home/daytona/workspace/elog/ && python /home/daytona/skills/docx/scripts/office/soffice.py --headless --convert-to pdf /home/daytona/workspace/elog/Clinical_Discussion_Elog.docx --outdir /home/daytona/workspace/elog/ 2>&1

Running Command

mkdir -p /home/daytona/workspace/elog/out && soffice --headless --convert-to pdf --outdir /home/daytona/workspace/elog/out /home/daytona/workspace/elog/Clinical_Discussion_Elog.docx 2>&1

Running Command

ls -la /home/daytona/workspace/elog/out/ && cp /home/daytona/workspace/elog/Clinical_Discussion_Elog.docx /tmp/test_elog.docx && soffice --headless --convert-to pdf --outdir /tmp/ /tmp/test_elog.docx 2>&1 && ls -la /tmp/test_elog.pdf

Running Command

cp /home/daytona/workspace/elog/Clinical_Discussion_Elog.docx /tmp/test_elog.docx && soffice --headless --convert-to pdf --outdir /tmp/ /tmp/test_elog.docx 2>&1 ; ls -la /tmp/test_elog.pdf 2>&1

Running Command

cp /tmp/test_elog.pdf /home/daytona/workspace/elog/Clinical_Discussion_Elog.pdf && ls -lh /home/daytona/workspace/elog/

Let me know if you'd like to:
  • Add more diseases or specific systems (e.g. oncology, haematological malignancies, psychiatric conditions)
  • Add a blank personal elog entry template section for logging individual patient cases
  • Change formatting, colours, or add your name/institution to the title page

C - Describe clinical features of diseases of various aetiology affecting all systems in the adult and geriatric population . Make a clinical discussion for elog book in simple docs or pdf format

I already created this document for you in the previous session! Here are your download links again:
  • Clinical Discussion Elog

    Word Document · DOCX

    (Word, 36 KB)
  • Clinical Discussion Elog

    PDF Document · PDF

    (PDF, 456 KB)

What's included

The document covers 10 body systems with 17 diseases, each with a structured clinical discussion:
SystemDiseases
CardiovascularAcute MI, Chronic Heart Failure
RespiratoryPneumonia (CAP), COPD Exacerbation
GastrointestinalUpper GI Bleed, Liver Cirrhosis
NeurologicalIschaemic Stroke, Parkinson's Disease
EndocrineType 2 Diabetes, Hypothyroidism
RenalAcute Kidney Injury
MusculoskeletalRheumatoid Arthritis, Osteoporosis
HaematologyAnaemia (IDA, B12, haemolytic)
InfectionsSepsis
Geriatric SyndromesDelirium, Falls in the Elderly
Each entry has: Aetiology - Clinical Features - Geriatric Considerations - Investigations - Management Overview, plus a quick-reference summary table at the end.
If you'd like me to add more conditions, a personal patient log template, or your name/institution on the title page, just let me know!

Make a simple pdf without colored columns and heading in straight line

Writing File

~/elog/generate_elog_plain.js

const {
  Document, Packer, Paragraph, TextRun,
  HeadingLevel, AlignmentType, LevelFormat, PageBreak,
  Table, TableRow, TableCell, WidthType, BorderStyle, VerticalAlign
} = require('docx');
const fs = require('fs');

// ─── Helpers ───────────────────────────────────────────────────────────────
function h1(text) {
  return new Paragraph({
    children: [new TextRun({ text, bold: true, size: 32, font: "Arial" })],
    spacing: { before: 400, after: 160 },
    border: { bottom: { style: BorderStyle.SINGLE, size: 6, color: "000000", space: 4 } }
  });
}
function h2(text) {
  return new Paragraph({
    children: [new TextRun({ text, bold: true, size: 26, font: "Arial" })],
    spacing: { before: 280, after: 120 }
  });
}
function h3(text) {
  return new Paragraph({
    children: [new TextRun({ text, bold: true, size: 24, font: "Arial", underline: {} })],
    spacing: { before: 240, after: 100 }
  });
}
function sectionLabel(label) {
  return new Paragraph({
    children: [new TextRun({ text: label + ":", bold: true, size: 22, font: "Arial" })],
    spacing: { before: 160, after: 60 }
  });
}
function bullet(text) {
  const parts = [];
  const segments = text.split(/(\*\*[^*]+\*\*)/);
  for (const seg of segments) {
    if (seg.startsWith("**") && seg.endsWith("**")) {
      parts.push(new TextRun({ text: seg.slice(2, -2), bold: true, font: "Arial", size: 22 }));
    } else {
      parts.push(new TextRun({ text: seg, font: "Arial", size: 22 }));
    }
  }
  return new Paragraph({
    numbering: { reference: "bullets", level: 0 },
    children: parts,
    spacing: { after: 60 }
  });
}
function para(text) {
  return new Paragraph({
    children: [new TextRun({ text, font: "Arial", size: 22 })],
    spacing: { after: 120 }
  });
}
function spacer() {
  return new Paragraph({ children: [new TextRun("")], spacing: { after: 80 } });
}
function pageBreak() {
  return new Paragraph({ children: [new PageBreak()] });
}

// ─── Disease Block ──────────────────────────────────────────────────────────
function diseaseBlock(name, etiology, clinicalFeatures, geriatricNotes, investigations, management) {
  const items = [];
  items.push(h3(name));
  items.push(sectionLabel("Aetiology"));
  for (const e of etiology) items.push(bullet(e));
  items.push(sectionLabel("Clinical Features"));
  for (const c of clinicalFeatures) items.push(bullet(c));
  if (geriatricNotes && geriatricNotes.length > 0) {
    items.push(sectionLabel("Geriatric Considerations"));
    for (const g of geriatricNotes) items.push(bullet(g));
  }
  items.push(sectionLabel("Investigations"));
  for (const i of investigations) items.push(bullet(i));
  items.push(sectionLabel("Management Overview"));
  for (const m of management) items.push(bullet(m));
  items.push(spacer());
  return items;
}

// ─── CONTENT ────────────────────────────────────────────────────────────────
const content = [];

// TITLE
content.push(new Paragraph({
  children: [new TextRun({ text: "CLINICAL DISCUSSION E-LOG BOOK", bold: true, size: 48, font: "Arial" })],
  alignment: AlignmentType.CENTER,
  spacing: { before: 800, after: 300 }
}));
content.push(new Paragraph({
  children: [new TextRun({ text: "Diseases of Various Aetiology — Adult & Geriatric Population", size: 26, font: "Arial", italics: true })],
  alignment: AlignmentType.CENTER,
  spacing: { after: 160 }
}));
content.push(new Paragraph({
  children: [new TextRun({ text: "Structured Clinical Discussions Across All Body Systems", size: 22, font: "Arial" })],
  alignment: AlignmentType.CENTER,
  spacing: { after: 160 }
}));
content.push(new Paragraph({
  children: [new TextRun({ text: "June 2026", size: 22, font: "Arial" })],
  alignment: AlignmentType.CENTER,
  spacing: { after: 600 }
}));
content.push(pageBreak());

// INTRODUCTION
content.push(h1("Introduction"));
content.push(para("This e-log book documents clinical discussions of common and important diseases encountered in adult and geriatric patients, organised by body system. For each condition the aetiology, clinical features, geriatric-specific considerations, relevant investigations, and a management overview are presented in a structured format suitable for clinical logging and revision."));
content.push(para("Geriatric patients frequently present atypically — with blunted febrile responses, absence of classic pain, cognitive changes, or falls as the only manifestation. These nuances are highlighted under each condition."));
content.push(pageBreak());

// ── 1. CARDIOVASCULAR ──────────────────────────────────────────────────────
content.push(h1("1. Cardiovascular System"));

content.push(...diseaseBlock(
  "1.1  Acute Myocardial Infarction (AMI)",
  [
    "Coronary artery atherosclerosis with plaque rupture (Type 1 MI — most common)",
    "Coronary vasospasm: Prinzmetal angina (Type 2 MI)",
    "Supply-demand mismatch: severe anaemia, tachyarrhythmia, sepsis (Type 2 MI)",
    "Risk factors: hypertension, diabetes mellitus, dyslipidaemia, smoking, family history, obesity",
  ],
  [
    "**Symptoms:** Severe crushing central chest pain radiating to left arm/jaw; onset at rest or exertion",
    "Associated: diaphoresis, nausea/vomiting, dyspnoea, sense of impending doom",
    "STEMI: ST elevation ≥1 mm in ≥2 contiguous limb leads or ≥2 mm in precordial leads",
    "NSTEMI/UA: ST depression, T-wave inversion, or dynamic ECG changes without elevation",
    "**Signs:** Tachycardia, hypotension (cardiogenic shock), S3/S4 gallop, new MR murmur (papillary muscle rupture)",
    "Killip classification grades severity of heart failure post-MI",
  ],
  [
    "Atypical presentation common: epigastric pain, fatigue, syncope, confusion — chest pain may be absent",
    "Higher mortality; delayed presentation is frequent",
    "Pre-existing renal impairment influences contrast use and drug dosing",
    "Polypharmacy interactions complicate antiplatelet and anticoagulant therapy",
  ],
  [
    "12-lead ECG — serial recordings; look for reciprocal changes",
    "High-sensitivity Troponin I/T: rises within 1–3 h, peaks at 12–24 h",
    "CK-MB: peaks ~24 h; useful for re-infarction detection",
    "FBC, renal function, electrolytes, lipid profile, BNP/NT-proBNP",
    "Echo: wall motion abnormalities, EF, mechanical complications",
    "Coronary angiography (gold standard for definitive therapy)",
  ],
  [
    "STEMI: Primary PCI within 90 min (door-to-balloon); fibrinolysis if PCI unavailable within 120 min",
    "NSTEMI/UA: Risk stratify (GRACE/TIMI); early invasive strategy within 24–72 h for high-risk",
    "Dual antiplatelet: Aspirin 300 mg loading + Ticagrelor 180 mg (or Clopidogrel 600 mg)",
    "Anticoagulation: Heparin (UFH/LMWH) or Fondaparinux",
    "Secondary prevention: Beta-blocker, ACE inhibitor/ARB, statin, spironolactone if EF <40%",
    "Cardiac rehabilitation and lifestyle modification",
  ]
));

content.push(...diseaseBlock(
  "1.2  Chronic Heart Failure (CHF)",
  [
    "Ischaemic heart disease (most common cause)",
    "Hypertensive heart disease, dilated cardiomyopathy, valvular disease",
    "HFrEF (EF <40%): dilated cardiomyopathy, post-MI; HFpEF (EF ≥50%): hypertension, DM, obesity",
    "Other: atrial fibrillation, thyroid disease, alcohol, chemotherapy (cardiotoxicity)",
  ],
  [
    "**Left heart failure:** Dyspnoea (exertional → orthopnoea → PND), fatigue, reduced exercise tolerance",
    "**Right heart failure:** Peripheral pitting oedema, hepatomegaly, raised JVP, ascites",
    "**Signs:** Displaced apex beat, S3 gallop, basal crepitations, pleural effusion",
    "NYHA functional class I (no symptoms) to IV (symptoms at rest)",
    "Acute decompensation: acute pulmonary oedema — frothy pink sputum, severe orthopnoea, hypoxia",
  ],
  [
    "HFpEF predominates in elderly women; oedema and dyspnoea often wrongly attributed to other causes",
    "Falls, confusion, and anorexia can be the presenting features",
    "Diuretic-induced electrolyte imbalances (hyponatraemia, hypokalaemia) are frequent",
    "Digoxin toxicity risk increased due to reduced renal clearance",
  ],
  [
    "BNP/NT-proBNP: elevated; useful for diagnosis and monitoring",
    "ECG: LVH, LBBB, atrial fibrillation",
    "Chest X-ray: cardiomegaly, upper lobe diversion, Kerley B lines, pleural effusion",
    "Echocardiography: EF, wall motion, valvular function, diastolic parameters",
    "Renal function and electrolytes: serial monitoring",
    "Thyroid function, iron studies (reversible causes)",
  ],
  [
    "HFrEF: ACE inhibitor/ARNI (sacubitril/valsartan), beta-blocker (carvedilol/bisoprolol), MRA (spironolactone), SGLT2 inhibitor (dapagliflozin) — all reduce mortality",
    "Diuretics (furosemide) for symptom control; titrate to dry weight",
    "HFpEF: BP control, rate control in AF, SGLT2 inhibitors now recommended",
    "CRT for LBBB + EF <35%; ICD for EF <35% on optimal medical therapy",
    "Acute decompensation: IV diuresis, nitrates, oxygen; NIV in pulmonary oedema",
  ]
));

content.push(pageBreak());

// ── 2. RESPIRATORY ─────────────────────────────────────────────────────────
content.push(h1("2. Respiratory System"));

content.push(...diseaseBlock(
  "2.1  Community-Acquired Pneumonia (CAP)",
  [
    "Bacterial: Streptococcus pneumoniae (most common), Haemophilus influenzae, Mycoplasma pneumoniae (atypical), Legionella pneumophila",
    "Viral: Influenza, RSV, SARS-CoV-2",
    "Aspiration pneumonia: anaerobes (dysphagia, reduced consciousness)",
    "Risk factors: extremes of age, immunosuppression, smoking, chronic lung/heart disease",
  ],
  [
    "**Symptoms:** Fever with rigors, productive cough (rust-coloured sputum in pneumococcal), pleuritic chest pain, dyspnoea",
    "Atypical (walking pneumonia): dry cough, headache, myalgia, extrapulmonary features",
    "**Signs:** Tachypnoea, tachycardia, dullness to percussion, bronchial breathing, coarse crepitations over affected lobe",
    "Severity: CURB-65 (Confusion, Urea >7, RR ≥30, BP <90/60, Age ≥65) — score ≥2 warrants admission",
  ],
  [
    "Classic fever may be absent; hypothermia can occur in severe infection",
    "Confusion and delirium may be the sole presenting feature",
    "Aspiration pneumonia more common due to dysphagia and poor cough reflex",
    "Higher CURB-65 scores expected; functional decline post-pneumonia is significant",
  ],
  [
    "Chest X-ray: lobar/segmental consolidation",
    "FBC: neutrophilia (bacterial), lymphopenia (viral/atypical)",
    "CRP, procalcitonin",
    "Sputum culture and sensitivity; blood cultures if CURB-65 ≥2",
    "Urinary antigen: Legionella, S. pneumoniae",
    "ABG if SpO2 <94% or severe disease",
  ],
  [
    "Low severity (CURB-65 0–1): oral Amoxicillin 500 mg TDS 5 days; add Clarithromycin for atypical cover",
    "Moderate/severe: IV co-amoxiclav + Clarithromycin; or Levofloxacin monotherapy",
    "Supportive: controlled oxygen (SpO2 94–98%), IV fluids, analgesia for pleurisy",
    "ICU admission and ventilatory support for severe/refractory hypoxia",
    "Pneumococcal and influenza vaccination for prevention",
  ]
));

content.push(...diseaseBlock(
  "2.2  COPD — Acute Exacerbation (AECOPD)",
  [
    "Smoking (primary cause >80%)",
    "Air pollution, occupational dust/fumes (coal, silica, cadmium)",
    "Alpha-1 antitrypsin deficiency (genetic — non-smokers, early onset)",
    "Exacerbation triggers: respiratory infections (H. influenzae, S. pneumoniae, viruses), air pollution, inhaler non-compliance",
  ],
  [
    "**Stable COPD:** Progressive exertional dyspnoea, chronic productive cough, wheeze",
    "**AECOPD:** Worsening dyspnoea, increased sputum volume and purulence, wheeze",
    "**Signs:** Barrel chest, accessory muscle use, pursed-lip breathing, reduced air entry, prolonged expiration, wheeze",
    "Hypoxia: cyanosis; Hypercapnia: drowsiness, asterixis, bounding pulse",
    "GOLD classification (spirometry): I (mild, FEV1 ≥80%) to IV (very severe, FEV1 <30%)",
  ],
  [
    "Reduced perception of dyspnoea — patients may not report breathlessness accurately",
    "Cor pulmonale (RHF secondary to pulmonary hypertension) more common in elderly",
    "Target oxygen saturation 88–92% to avoid hypoxic drive suppression",
    "Malnutrition and sarcopenia worsen prognosis",
  ],
  [
    "Spirometry: FEV1/FVC <0.70 post-bronchodilator (diagnostic gold standard)",
    "Chest X-ray: hyperinflation, flat diaphragm, bullae; exclude pneumonia/pneumothorax",
    "ABG: type II respiratory failure (hypoxia + hypercapnia, raised bicarbonate)",
    "FBC: polycythaemia (chronic hypoxia), neutrophilia (infection)",
    "Sputum culture; ECG (RVH, right axis deviation in cor pulmonale)",
  ],
  [
    "Controlled oxygen: 24–28% Venturi mask, target SpO2 88–92%",
    "Nebulised bronchodilators: Salbutamol + Ipratropium (back-to-back)",
    "Systemic corticosteroids: Prednisolone 30–40 mg PO for 5 days",
    "Antibiotics if purulent sputum or 2/3 Anthonisen criteria: Amoxicillin/Doxycycline/Clarithromycin",
    "NIV (BiPAP): pH <7.35 with hypercapnia unresponsive to medical therapy",
    "Stable maintenance: LABA + LAMA (formoterol + tiotropium); add ICS if ≥2 exacerbations/year",
    "Pulmonary rehabilitation; smoking cessation; LTOT if PaO2 <7.3 kPa at rest",
  ]
));

content.push(pageBreak());

// ── 3. GASTROINTESTINAL ────────────────────────────────────────────────────
content.push(h1("3. Gastrointestinal System"));

content.push(...diseaseBlock(
  "3.1  Upper GI Bleed (Peptic Ulcer Disease)",
  [
    "Helicobacter pylori infection (~70% of duodenal ulcers, ~50% of gastric ulcers)",
    "NSAID/aspirin use: disrupts mucosal prostaglandin-mediated cytoprotection",
    "Zollinger-Ellison syndrome: gastrinoma causing hypersecretion",
    "Stress ulcers: critically ill patients (mechanical ventilation, burns, sepsis)",
    "Other bleeds: oesophageal varices (portal hypertension), Mallory-Weiss tear, angiodysplasia",
  ],
  [
    "Epigastric pain: duodenal (relieved by food), gastric (worsened by food)",
    "**Upper GI bleed:** Haematemesis (fresh blood or coffee-ground vomit), melaena (tarry black stools)",
    "Symptoms of hypovolaemia: dizziness, syncope, palpitations, cold extremities",
    "**Signs:** Pallor, tachycardia, hypotension, epigastric tenderness; peritonism if perforation",
    "Rockall/Glasgow-Blatchford score stratifies urgency of endoscopy",
  ],
  [
    "NSAID-induced ulcers often bleed silently without prior dyspepsia",
    "Haemodynamic compromise from smaller blood losses due to poor compensatory response",
    "Melaena may be the first symptom; haematemesis less common if on anticoagulants",
    "PPI prophylaxis essential when NSAIDs required",
  ],
  [
    "FBC: anaemia (acute: normocytic; chronic: microcytic iron-deficiency)",
    "Clotting studies, INR, LFTs",
    "Urea/creatinine ratio >100:1 suggests upper GI source",
    "Urgent OGD within 24 h (within 2 h if shocked/ongoing bleed)",
    "H. pylori: urea breath test, stool antigen, CLO test on biopsy",
  ],
  [
    "Resuscitation: IV access, fluid resuscitation, blood transfusion (target Hb ≥70–80 g/L)",
    "IV PPI: omeprazole 80 mg bolus → 8 mg/h infusion",
    "Endoscopic haemostasis: adrenaline injection, thermal coagulation, haemoclips",
    "H. pylori eradication: triple therapy (PPI + Clarithromycin + Amoxicillin for 7–14 days)",
    "Stop NSAIDs; switch to COX-2 inhibitor + PPI if unavoidable",
  ]
));

content.push(...diseaseBlock(
  "3.2  Liver Cirrhosis and Complications",
  [
    "Alcoholic liver disease (most common in Western countries)",
    "Non-alcoholic fatty liver disease (NAFLD/NASH) — increasing with obesity/DM",
    "Viral hepatitis: Hepatitis B (~15–25% cirrhosis risk), Hepatitis C",
    "Autoimmune hepatitis, primary biliary cholangitis, haemochromatosis, Wilson's disease",
  ],
  [
    "**Compensated:** Often asymptomatic; fatigue, spider naevi, palmar erythema",
    "**Decompensated:**",
    "Ascites: abdominal distension, shifting dullness, fluid thrill; risk of spontaneous bacterial peritonitis (SBP)",
    "Hepatic encephalopathy: confusion, asterixis (flapping tremor), fetor hepaticus",
    "Variceal bleeding: haematemesis, melaena — life-threatening",
    "Jaundice, coagulopathy (raised PT), hypoalbuminaemia (oedema, muscle wasting)",
    "Child-Pugh and MELD scores used to assess severity and prognosis",
  ],
  [
    "Encephalopathy triggered by infection, constipation, GI bleed, or diuretics",
    "Hyponatraemia, renal impairment, electrolyte disturbances are common",
    "Increased risk of osteoporosis and falls due to vitamin D deficiency and muscle wasting",
    "Drug metabolism significantly impaired — careful dose adjustment required",
  ],
  [
    "LFTs: elevated bilirubin, low albumin; AST:ALT ratio >2:1 in alcoholic hepatitis",
    "Clotting: prolonged PT/INR (marker of synthetic function)",
    "FBC: thrombocytopenia (hypersplenism), anaemia",
    "Ultrasound abdomen: nodular liver, splenomegaly, ascites; Doppler for portal vein thrombosis",
    "Upper endoscopy: oesophageal/gastric varices",
    "Ascitic tap: cell count, culture, albumin (SAAG >11 g/L confirms portal hypertension)",
    "AFP: hepatocellular carcinoma surveillance",
  ],
  [
    "Abstinence from alcohol; antiviral therapy for hepatitis B/C",
    "Ascites: sodium restriction, spironolactone ± furosemide; therapeutic paracentesis + albumin",
    "SBP: IV cefotaxime; prophylaxis with norfloxacin",
    "Variceal bleeding: terlipressin + antibiotics; urgent OGD band ligation; TIPSS for refractory",
    "Hepatic encephalopathy: lactulose, rifaximin; treat precipitant",
    "Liver transplantation for end-stage disease (MELD ≥15)",
  ]
));

content.push(pageBreak());

// ── 4. NEUROLOGICAL ────────────────────────────────────────────────────────
content.push(h1("4. Neurological System"));

content.push(...diseaseBlock(
  "4.1  Ischaemic Stroke",
  [
    "Large artery atherosclerosis: stenosis of carotid or intracranial vessels",
    "Cardioembolic: atrial fibrillation (most common cardiac cause), intracardiac thrombus",
    "Small vessel disease (lacunar infarcts): hypertension, DM causing lipohyalinosis",
    "Other: vasculitis, dissection, hypercoagulable states (antiphospholipid syndrome)",
  ],
  [
    "Sudden onset focal neurological deficit — FAST: Face drooping, Arm weakness, Speech difficulty, Time to call emergency",
    "**Anterior circulation (MCA):** Contralateral hemiplegia, hemisensory loss, homonymous hemianopia, aphasia (dominant), neglect (non-dominant)",
    "**Posterior circulation:** Vertigo, diplopia, ataxia, dysarthria, dysphagia, crossed signs",
    "**Lacunar:** Pure motor, pure sensory, sensorimotor, ataxic hemiparesis",
    "TIA: same deficits resolving within 24 h; high risk of stroke (ABCD2 score)",
  ],
  [
    "Presentations can be atypical: confusion, falls — classic deficits may be subtle",
    "Pre-existing cognitive impairment complicates neurological assessment",
    "Dysphagia assessment critical before any oral intake",
    "Post-stroke delirium, depression, and dementia are common",
    "Thrombolysis eligibility often limited by anticoagulant use and comorbidities",
  ],
  [
    "CT head (non-contrast): IMMEDIATE — excludes haemorrhage before thrombolysis",
    "MRI brain with DWI: most sensitive for early infarction",
    "CT/MR angiography: identifies large vessel occlusion for thrombectomy",
    "12-lead ECG: atrial fibrillation",
    "FBC, clotting, glucose, lipids, renal function",
    "Carotid Doppler/CTA: stenosis in anterior circulation strokes",
    "Echocardiogram; 24–48 h cardiac monitoring for paroxysmal AF",
  ],
  [
    "IV Alteplase (0.9 mg/kg, max 90 mg) within 4.5 h of onset (no haemorrhage, no contraindication)",
    "Mechanical thrombectomy: large vessel occlusion within 24 h of onset (NIHSS ≥6)",
    "Aspirin 300 mg stat after haemorrhage excluded; switch to clopidogrel/DAPT for 21 days",
    "Anticoagulation in AF: DOAC after 2–14 days based on infarct size",
    "Stroke unit care: MDT, early mobilisation, VTE prophylaxis",
    "Secondary prevention: antihypertensives (target <130/80), statin, antiplatelet/anticoagulant",
    "Carotid endarterectomy if stenosis 70–99% ipsilateral to stroke (within 2 weeks)",
  ]
));

content.push(...diseaseBlock(
  "4.2  Parkinson's Disease",
  [
    "Idiopathic (primary PD): loss of dopaminergic neurons in substantia nigra pars compacta; Lewy body (alpha-synuclein) pathology",
    "Secondary parkinsonism: drug-induced (antipsychotics, metoclopramide), vascular, PSP, MSA",
    "Genetic forms: LRRK2, PINK1, Parkin mutations (5–10%)",
  ],
  [
    "Cardinal motor features (TRAP): **T**remor (resting 4–6 Hz pill-rolling, improves with movement), **R**igidity (cogwheel), **A**kinesia/bradykinesia, **P**ostural instability (late)",
    "Unilateral onset, asymmetric, slowly progressive",
    "Gait: shuffling, reduced arm swing, freezing, festination; en bloc turning",
    "**Non-motor:** Constipation, anosmia, REM sleep behaviour disorder (may precede motor symptoms by years), depression, cognitive decline, orthostatic hypotension",
    "Hypomimia (mask-like face), hypophonia, micrographia",
    "Dementia (PDD) develops in ~80% after 20 years",
  ],
  [
    "Increased fall risk; freezing of gait and postural instability are major hazards",
    "Swallowing dysfunction — aspiration pneumonia risk",
    "Orthostatic hypotension — syncope and falls; avoid over-treating hypertension",
    "Avoid haloperidol, prochlorperazine, metoclopramide — worsen parkinsonism",
    "Lewy body dementia must be distinguished (dementia precedes/accompanies motor features, visual hallucinations, fluctuating cognition)",
  ],
  [
    "Clinical diagnosis: UK Brain Bank criteria (bradykinesia + rest tremor or rigidity + asymmetric onset)",
    "MRI brain: exclude structural causes, vascular lesions",
    "DaTscan (SPECT): reduced dopamine transporter — distinguishes PD from essential tremor",
    "Response to levodopa trial (supports diagnosis if dramatic improvement)",
    "Neuropsychological testing for cognitive assessment",
  ],
  [
    "Levodopa (co-careldopa/co-beneldopa): most effective; long-term complications — motor fluctuations, dyskinesias",
    "Dopamine agonists (pramipexole, ropinirole): initial therapy in younger patients",
    "MAO-B inhibitors (rasagiline, selegiline): mild symptomatic benefit",
    "COMT inhibitors (entacapone): extend levodopa effect",
    "Deep brain stimulation (STN/GPi): advanced PD with motor fluctuations",
    "MDT: physiotherapy, OT, SLT, Parkinson's disease nurse specialist",
  ]
));

content.push(pageBreak());

// ── 5. ENDOCRINE ───────────────────────────────────────────────────────────
content.push(h1("5. Endocrine System"));

content.push(...diseaseBlock(
  "5.1  Diabetes Mellitus Type 2",
  [
    "Insulin resistance + progressive beta-cell failure",
    "Risk factors: obesity (central adiposity), physical inactivity, family history, ethnicity (South Asian, Afro-Caribbean), gestational DM",
    "Associated: metabolic syndrome — hypertension, dyslipidaemia, NAFLD",
  ],
  [
    "Classic osmotic symptoms (often mild or absent in T2DM): polyuria, polydipsia, weight loss",
    "Fatigue, recurrent infections (UTI, skin, candidiasis), blurred vision",
    "Acanthosis nigricans (insulin resistance)",
    "**Macrovascular complications:** IHD, stroke, peripheral arterial disease (diabetic foot)",
    "**Microvascular complications:** Retinopathy (leading cause of blindness in working-age adults), nephropathy (proteinuria → CKD), neuropathy (stocking-glove sensory loss, autonomic dysfunction)",
    "**Acute HHS:** Severe hyperglycaemia, hyperosmolality, profound dehydration without significant ketosis",
  ],
  [
    "Hyperglycaemia may be less severe; HHS more common than DKA",
    "Hypoglycaemia particularly dangerous: falls, arrhythmias, cognitive impairment",
    "Impaired hypoglycaemia awareness common due to autonomic neuropathy",
    "Simplified glycaemic targets (HbA1c 53–64 mmol/mol) to reduce hypoglycaemia risk in frail elderly",
    "Deprescribing of multiple antidiabetic agents may be appropriate in frail patients",
  ],
  [
    "Fasting glucose ≥7.0 mmol/L or random ≥11.1 mmol/L or HbA1c ≥48 mmol/mol (6.5%)",
    "HbA1c: glycaemic control over preceding 3 months",
    "Urine albumin-creatinine ratio (ACR): nephropathy screening",
    "eGFR, LFTs, lipid profile",
    "Annual review: retinal photography, foot examination (monofilament, ABPI)",
  ],
  [
    "Lifestyle: diet, weight loss, exercise",
    "Metformin: first-line (reduce if eGFR <45, stop if <30)",
    "SGLT2 inhibitors (empagliflozin, dapagliflozin): cardiovascular and renal protection — preferred in IHD/CKD",
    "GLP-1 receptor agonists (semaglutide): weight loss benefit, CV protection",
    "DPP-4 inhibitors (sitagliptin): weight-neutral, well-tolerated in elderly",
    "Insulin: basal (glargine) added when oral agents fail",
    "Target HbA1c: 48–53 mmol/mol; individualise for frail patients",
  ]
));

content.push(...diseaseBlock(
  "5.2  Hypothyroidism",
  [
    "Primary (most common): Hashimoto's thyroiditis (autoimmune), post-thyroidectomy, post-radioiodine, iodine deficiency",
    "Drug-induced: amiodarone, lithium, interferon",
    "Secondary: pituitary failure (TSH deficiency)",
    "Transient: postpartum thyroiditis, subacute (de Quervain's) thyroiditis",
  ],
  [
    "Weight gain, fatigue, cold intolerance, constipation, dry skin, hair loss, bradycardia",
    "Depression, cognitive slowing, myalgia, carpal tunnel syndrome",
    "Menorrhagia (pre-menopausal women), infertility",
    "**Signs:** Bradycardia, periorbital/peripheral myxoedema, hung-up reflexes, macroglossia, goitre (Hashimoto's)",
    "Myxoedema coma: hypothermia, bradycardia, hypotension, altered consciousness — medical emergency",
  ],
  [
    "Symptoms often dismissed as normal ageing: fatigue, constipation, cognitive decline",
    "Hypothyroidism exacerbates heart failure and hyponatraemia",
    "Amiodarone (commonly used in elderly AF patients) causes both hypothyroidism and hyperthyroidism",
    "Levothyroxine: start with low dose (25–50 mcg) and titrate slowly to avoid precipitating angina/arrhythmia",
  ],
  [
    "TSH: elevated in primary hypothyroidism (best screening test)",
    "Free T4: low (confirms primary); low TSH + low T4 = secondary hypothyroidism",
    "Anti-TPO antibodies: Hashimoto's thyroiditis",
    "FBC: macrocytic anaemia; lipid profile: hypercholesterolaemia",
    "ECG: bradycardia, low voltage, prolonged QT",
  ],
  [
    "Levothyroxine: 1.6 mcg/kg/day; start lower in elderly/IHD (25–50 mcg), increase by 25 mcg every 6–8 weeks",
    "Target TSH: 0.5–2.5 mIU/L (higher acceptable in elderly to avoid over-replacement)",
    "Myxoedema coma: IV T3/T4 in HDU/ITU + hydrocortisone cover",
    "Drug interactions: calcium, iron, PPIs reduce absorption — take on empty stomach",
  ]
));

content.push(pageBreak());

// ── 6. RENAL ───────────────────────────────────────────────────────────────
content.push(h1("6. Renal System"));

content.push(...diseaseBlock(
  "6.1  Acute Kidney Injury (AKI)",
  [
    "Pre-renal (~55%): hypovolaemia, decreased cardiac output, renal artery stenosis",
    "Intrinsic renal (~40%): ATN (ischaemic/nephrotoxic — NSAIDs, aminoglycosides, contrast), glomerulonephritis, interstitial nephritis, rhabdomyolysis",
    "Post-renal (~5%): obstruction — BPH, pelvic malignancy, bilateral ureteric stones",
    "KDIGO criteria: rise in creatinine ≥26.5 μmol/L within 48 h, or 1.5× baseline within 7 days, or urine output <0.5 ml/kg/h for ≥6 h",
  ],
  [
    "Oliguria/anuria, nausea, lethargy, confusion (uraemia); frothy urine (proteinuria)",
    "**Fluid overload:** Peripheral oedema, pulmonary oedema, raised JVP",
    "**Uraemic features (severe):** Asterixis, pericardial friction rub, Kussmaul breathing",
    "**Hyperkalaemia:** Muscle weakness, peaked T waves, life-threatening arrhythmias",
    "**Post-renal features:** Urinary hesitancy, poor stream, distended bladder, loin pain",
  ],
  [
    "Baseline creatinine often elevated (reduced muscle mass); AKI may be underestimated",
    "NSAIDs and ACE inhibitors/ARBs are major precipitants — review on admission",
    "Contrast nephropathy risk higher — pre-hydration protocol essential",
    "Frailty complicates renal replacement therapy decisions",
  ],
  [
    "Serum creatinine, eGFR, urea (ratio >100:1 suggests pre-renal)",
    "Electrolytes: hyperkalaemia, hyponatraemia, metabolic acidosis",
    "Urinalysis and microscopy: casts (granular = ATN; RBC casts = glomerulonephritis)",
    "Urine Na and fractional excretion of Na (FeNa <1% pre-renal, >2% intrinsic)",
    "Renal tract ultrasound: hydronephrosis, kidney size",
    "ECG: hyperkalaemia changes",
  ],
  [
    "Pre-renal: IV fluid resuscitation; treat underlying cause",
    "Post-renal: urgent catheterisation (BPH) or nephrostomy (ureteric obstruction)",
    "Intrinsic (ATN): supportive — avoid nephrotoxins, fluid balance, treat hyperkalaemia",
    "Hyperkalaemia: calcium gluconate (membrane stabilisation), insulin + dextrose, salbutamol, patiromer",
    "Indications for urgent dialysis: refractory hyperkalaemia, fluid overload, acidosis, uraemic encephalopathy/pericarditis",
    "Avoid ACE inhibitors/ARBs/NSAIDs/metformin until renal function recovered",
  ]
));

content.push(pageBreak());

// ── 7. MUSCULOSKELETAL ─────────────────────────────────────────────────────
content.push(h1("7. Musculoskeletal System"));

content.push(...diseaseBlock(
  "7.1  Rheumatoid Arthritis (RA)",
  [
    "Autoimmune: T-cell mediated synovitis; ACPA (anti-CCP) and RF positive in seropositive disease",
    "HLA-DR4 genetic association",
    "Environmental triggers: smoking (strongly associated), silica, periodontal disease",
  ],
  [
    "Symmetrical inflammatory polyarthritis: MCP/PIP joints of hands, wrists, MTP joints of feet (spares DIP — contrast to OA)",
    "Morning stiffness >1 hour (hallmark of inflammatory arthritis)",
    "Systemic features: fatigue, weight loss, low-grade fever, anaemia of chronic disease",
    "**Late deformities:** Swan-neck, Boutonniere, Z-thumb, ulnar deviation at MCPs",
    "Extra-articular: rheumatoid nodules, serositis (pleuritis/pericarditis), RA-ILD, scleritis, Sjogren's overlap, vasculitis",
    "Atlantoaxial subluxation — important pre-anaesthetic assessment",
    "DAS28 score assesses disease activity (target: remission DAS28 <2.6)",
  ],
  [
    "Steroid use leads to significant complications: osteoporosis, infections, hyperglycaemia",
    "Increased infection risk with DMARDs and biologics — withhold prior to surgery/serious infection",
    "Methotrexate dose reduction needed in renal impairment",
    "Cervical spine X-ray mandatory before intubation for elective surgery",
  ],
  [
    "RF: ~70% positive; non-specific",
    "Anti-CCP (ACPA): highly specific (>95%) for RA; marker of erosive disease",
    "ESR, CRP: disease activity markers",
    "FBC: normochromic normocytic anaemia; thrombocytosis",
    "X-ray hands/feet: periarticular osteopenia, joint space narrowing, erosions",
    "MRI/Ultrasound: more sensitive for early synovitis and erosions",
  ],
  [
    "Treat-to-target strategy: aim for remission or low disease activity",
    "Conventional DMARDs: Methotrexate (first-line), Hydroxychloroquine, Sulfasalazine, Leflunomide",
    "Bridging: short-course corticosteroids for flares",
    "Biologics (if inadequate DMARD response): TNF inhibitors, IL-6 inhibitors, anti-CD20 (rituximab)",
    "JAK inhibitors: Tofacitinib, Baricitinib — oral alternatives",
    "Physiotherapy, OT, podiatry; surgical joint replacement for severe disease",
  ]
));

content.push(...diseaseBlock(
  "7.2  Osteoporosis and Fragility Fractures",
  [
    "Primary type I: post-menopausal (oestrogen deficiency → increased osteoclast activity)",
    "Primary type II: age-related — reduced osteoblast activity",
    "Secondary: corticosteroid use (most common secondary cause), hypogonadism, hyperparathyroidism, malabsorption, multiple myeloma",
    "Risk factors: female sex, Caucasian/Asian ethnicity, low BMI, family history, smoking, alcohol, immobility",
  ],
  [
    "Often asymptomatic until fracture occurs",
    "**Fragility fractures:** From minimal trauma (fall from standing height or less)",
    "Common sites: vertebral (kyphosis, height loss, back pain — may be painless), distal radius (Colles'), proximal femur (NOF fracture), ribs",
    "Neck of femur fracture: shortened externally rotated leg, inability to weight bear",
  ],
  [
    "Predominantly a geriatric condition; NOF fractures carry 20–30% 1-year mortality",
    "Fall prevention equally important as bone protection",
    "Delirium post-fracture/surgery is common and worsens outcomes",
    "Oral bisphosphonates may be poorly tolerated — IV zoledronate preferred",
    "Vitamin D deficiency extremely common; exclude osteomalacia before treating osteoporosis",
  ],
  [
    "DEXA scan: BMD at hip and lumbar spine; T-score ≤ -2.5 = osteoporosis",
    "FRAX tool: 10-year fracture probability",
    "Serum calcium, phosphate, vitamin D (25-OH), PTH, ALP",
    "LFTs, TFTs, testosterone (men), myeloma screen",
  ],
  [
    "Calcium (1000–1200 mg/day) and Vitamin D supplementation (800–1000 IU/day) — foundation",
    "Bisphosphonates (alendronate weekly PO, zoledronate yearly IV): first-line anti-resorptive",
    "Denosumab (SC 6-monthly): alternative in renal impairment — rebound fracture risk on cessation",
    "Teriparatide (PTH analogue): anabolic — severe osteoporosis or bisphosphonate failure; max 2 years",
    "Fall prevention: strength/balance exercise (Otago/tai chi), home hazard assessment, medication review (deprescribe sedatives), vision correction",
  ]
));

content.push(pageBreak());

// ── 8. HAEMATOLOGY ─────────────────────────────────────────────────────────
content.push(h1("8. Haematological Conditions"));

content.push(...diseaseBlock(
  "8.1  Anaemia — Clinical Approach",
  [
    "Iron deficiency: GI blood loss (peptic ulcer, malignancy, IBD), menorrhagia, malabsorption (coeliac), poor dietary intake",
    "B12/Folate deficiency: pernicious anaemia, malnutrition, metformin use, malabsorption",
    "Anaemia of chronic disease/inflammation: RA, chronic infection, CKD, malignancy",
    "Haemolytic: autoimmune (warm/cold antibodies), hereditary (spherocytosis, G6PD, sickle cell), microangiopathic (TTP, HUS)",
    "Aplastic anaemia, myelodysplastic syndrome, bone marrow infiltration",
  ],
  [
    "General: fatigue, exertional dyspnoea, pallor (conjunctival, palmar), tachycardia, flow murmur",
    "**Iron deficiency:** Koilonychia, angular cheilitis, glossitis, Plummer-Vinson syndrome (dysphagia)",
    "**B12 deficiency:** Glossitis, subacute combined degeneration of cord (sensory ataxia, weakness, paraesthesia), peripheral neuropathy, cognitive impairment",
    "**Haemolytic:** Jaundice (unconjugated bilirubin), splenomegaly, dark urine (intravascular haemolysis)",
  ],
  [
    "Common and often multifactorial; B12 deficiency may mimic dementia",
    "Anaemia worsens cardiac function and cognitive impairment",
    "Iron deficiency in elderly always demands investigation for GI malignancy",
    "Transfusion threshold: Hb <70 g/L (80 g/L in cardiac patients)",
  ],
  [
    "FBC: MCV (microcytic <80 in IDA; macrocytic >100 in B12/folate; normocytic in ACD/haemolysis)",
    "Blood film: hypochromic microcytes, macro-ovalocytes + hypersegmented neutrophils, spherocytes, sickle cells",
    "Serum iron, ferritin (low in IDA), TIBC; reticulocyte count",
    "B12, folate; LDH, bilirubin, haptoglobin (haemolysis screen)",
    "DAT (direct antiglobulin test): AIHA",
    "Colonoscopy/OGD: GI bleeding source in iron deficiency",
  ],
  [
    "Iron deficiency: oral ferrous sulphate 200 mg TDS; IV iron (ferric carboxymaltose) if oral intolerant",
    "B12: IM hydroxocobalamin 1000 mcg alternate days × 6 → 3-monthly (absorption defect); oral if dietary deficiency",
    "Folate: folic acid 5 mg daily — always supplement B12 first if both deficient",
    "Pernicious anaemia: lifelong B12 replacement",
    "AIHA: prednisolone first-line; rituximab/splenectomy for refractory",
    "Treat underlying cause; EPO for renal anaemia",
  ]
));

content.push(pageBreak());

// ── 9. SEPSIS ──────────────────────────────────────────────────────────────
content.push(h1("9. Sepsis and Infectious Diseases"));

content.push(...diseaseBlock(
  "9.1  Sepsis",
  [
    "Life-threatening organ dysfunction caused by a dysregulated host response to infection (Sepsis-3 definition)",
    "Common sources: pneumonia (most common), UTI/urosepsis, intra-abdominal (peritonitis, cholangitis), skin/soft tissue, meningitis",
    "Causative organisms: E. coli/Klebsiella (UTI/abdominal), S. pneumoniae (pneumonia/meningitis), S. aureus (skin/endocarditis), Pseudomonas (immunocompromised)",
    "qSOFA screen: RR ≥22, altered mentation, systolic BP ≤100",
  ],
  [
    "**Sepsis:** Fever or hypothermia, tachycardia, tachypnoea, altered mental status, oliguria",
    "**Septic shock:** Vasopressor requirement to maintain MAP ≥65 mmHg + lactate >2 mmol/L despite fluids",
    "Organ dysfunction: AKI, coagulopathy (DIC), liver dysfunction (raised bilirubin), respiratory failure (ARDS)",
    "Signs: hypotension, mottled skin, prolonged capillary refill, warm peripheries early → cold/shut-down late",
    "SOFA score assesses organ dysfunction (score ≥2 = sepsis)",
  ],
  [
    "Presentation frequently atypical: hypothermia rather than fever, confusion/delirium, falls, functional decline",
    "Tachycardia may be absent (beta-blockers, pacemakers)",
    "Sources often occult: aspiration, decubitus ulcers, endocarditis, device infections",
    "Prognosis significantly worse; sepsis in care home residents carries high mortality",
    "Fluid resuscitation must be carefully titrated to avoid pulmonary oedema",
  ],
  [
    "Blood cultures (×2) before antibiotics",
    "Lactate: >2 mmol/L (hypoperfusion); >4 mmol/L (septic shock — poor prognosis)",
    "FBC, CRP, procalcitonin, coagulation screen (DIC: low fibrinogen, raised D-dimer)",
    "Renal/hepatic function, ABG",
    "Urinalysis + culture; CXR; CT if intra-abdominal source suspected",
  ],
  [
    "Surviving Sepsis Bundle (within 1 hour): blood cultures → IV broad-spectrum antibiotics → IV fluid 30 ml/kg → lactate measurement → vasopressors if MAP <65",
    "Antibiotics: tailored to suspected source; de-escalate within 48–72 h based on cultures",
    "Vasopressors: noradrenaline (first-line) via central access; vasopressin added if refractory",
    "Source control: drain abscess, remove infected device, debride necrotic tissue",
    "Corticosteroids: hydrocortisone 200 mg/day in refractory septic shock",
    "Supportive: lung-protective ventilation for ARDS, DVT prophylaxis, glucose control (6–10 mmol/L)",
  ]
));

content.push(pageBreak());

// ── 10. GERIATRIC SYNDROMES ────────────────────────────────────────────────
content.push(h1("10. Geriatric Syndromes"));

content.push(...diseaseBlock(
  "10.1  Delirium (Acute Confusional State)",
  [
    "Multifactorial — commonly two or more precipitants in a vulnerable patient",
    "Common precipitants (PINCH ME): Pain, Infection/Inflammation, Nutrition, Constipation, Hydration, Medication, Environment, Immobility",
    "Predisposing factors: advanced age, pre-existing dementia, frailty, sensory impairment, alcohol dependence",
    "Underlying causes: UTI, pneumonia, meningitis, AKI, electrolyte disturbances, MI, PE, subdural haematoma, post-surgical",
  ],
  [
    "**Core features (DSM-5):** Acute disturbance of attention and awareness; fluctuating course; additional cognitive disturbance",
    "**Hyperactive (~25%):** Agitation, combativeness, visual hallucinations, attempts to pull out lines",
    "**Hypoactive (~50% — most common, most missed):** Withdrawal, somnolence, reduced responsiveness — often misdiagnosed as depression or dementia",
    "Mixed delirium: alternating both types (~25%)",
    "Screening tools: 4AT (rapid bedside screen); CAM (Confusion Assessment Method) — gold standard",
  ],
  [
    "Hypoactive delirium is almost exclusively a geriatric condition and is frequently missed",
    "May be the sole presenting feature of serious illness (MI, PE, abdominal emergency)",
    "Delirium on background of dementia is particularly challenging",
    "Associated with increased mortality, longer stay, institutionalisation, and accelerated cognitive decline",
  ],
  [
    "FBC, CRP, U&E, LFTs, TFTs, glucose, calcium, magnesium",
    "Urinalysis/culture; blood cultures if febrile or sepsis suspected",
    "ABG if respiratory cause; ECG",
    "CT head if new focal signs, head injury, or uncertain diagnosis",
    "LP if meningitis/encephalitis suspected",
    "Medication list review — drug chart is a diagnostic tool",
  ],
  [
    "Treat underlying cause: this is the priority",
    "Non-pharmacological (first-line): orientation cues (clocks, calendars, familiar faces); adequate lighting; early mobilisation; ensure hearing aids and glasses; hydration and nutrition; avoid catheters and ward moves",
    "Adequate analgesia (unrecognised pain is a common precipitant)",
    "Pharmacological (only for severe agitation with risk to patient/staff): haloperidol 0.5–1 mg PO/IM (avoid in Lewy body dementia — use quetiapine); lorazepam for alcohol withdrawal delirium",
    "Avoid benzodiazepines unless alcohol/benzo withdrawal delirium",
    "NICE delirium prevention bundle for all at-risk patients on admission",
  ]
));

content.push(...diseaseBlock(
  "10.2  Falls in the Elderly",
  [
    "Multifactorial — intrinsic and extrinsic factors interact",
    "Intrinsic: muscle weakness (sarcopenia), balance/gait impairment, visual impairment, cognitive impairment, orthostatic hypotension, peripheral neuropathy, Parkinson's disease, stroke",
    "Extrinsic (environmental): poor lighting, loose rugs, wet floors, inappropriate footwear",
    "Medications (major modifiable cause): sedatives, antihypertensives, diuretics, antidiabetics (hypoglycaemia), antipsychotics",
    "Acute precipitant: infection, ACS, arrhythmia, PE, dehydration, pain",
  ],
  [
    "History: circumstances of fall (mechanical vs. syncope), prodrome (dizziness, palpitations, chest pain), number of falls in past year",
    "Gait/balance: Get Up and Go test (>12 seconds = fall risk); Berg Balance Scale",
    "Consequences: NOF fracture (shortened externally rotated leg), subdural haematoma (on anticoagulants), hypothermia if prolonged time on floor, rhabdomyolysis",
    "Psychosocial: fear of falling — reduces activity, leading to deconditioning and social isolation",
  ],
  [
    "Falls are the leading cause of injury death in adults over 65",
    "30% of community-dwelling adults over 65 fall at least once per year",
    "NOF fractures carry 1-year mortality of 20–30%",
    "Unexplained falls always warrant investigation for serious underlying disease",
    "NICE recommends multifactorial risk assessment for all elderly with recurrent falls",
  ],
  [
    "ECG: arrhythmia, heart block",
    "Orthostatic BP measurements (lying-to-standing): drop ≥20 mmHg systolic",
    "Blood glucose (hypoglycaemia); FBC, U&E, calcium, vitamin D",
    "X-rays of injured area; CT head if head injury or on anticoagulants",
    "Holter monitor/implantable loop recorder if cardiac syncope suspected",
  ],
  [
    "Multifactorial intervention programme (most evidence-based approach)",
    "Physiotherapy: strength and balance exercises (Otago programme, tai chi)",
    "Medication review: deprescribe or reduce high-fall-risk medications",
    "Treat orthostatic hypotension: morning fluids, compression stockings, fludrocortisone/midodrine if severe",
    "Vision correction (cataract surgery, glasses); hearing aid provision",
    "Home hazard assessment and modification (occupational therapy)",
    "Calcium + Vitamin D supplementation; treat osteoporosis",
    "Hip protectors for highest-risk patients",
  ]
));

content.push(pageBreak());

// ── SUMMARY TABLE ──────────────────────────────────────────────────────────
content.push(h1("Quick Reference Summary Table"));
content.push(spacer());

const noBorder = { style: BorderStyle.SINGLE, size: 4, color: "AAAAAA" };
const tableData = [
  ["System", "Disease", "Key Clinical Feature", "First Investigation", "First-Line Treatment"],
  ["Cardiovascular", "Acute MI (STEMI)", "Crushing chest pain, ST elevation", "ECG + Troponin", "Primary PCI within 90 min"],
  ["Cardiovascular", "Heart Failure", "Dyspnoea, oedema, S3 gallop", "BNP + Echo", "ACEi + BB + MRA + SGLT2i"],
  ["Respiratory", "Pneumonia (CAP)", "Fever, cough, consolidation", "CXR + Cultures", "Amoxicillin ± Clarithromycin"],
  ["Respiratory", "COPD Exacerbation", "Worsening dyspnoea, wheeze", "ABG + Spirometry", "Nebulisers + Steroids + Abx"],
  ["GI", "Upper GI Bleed", "Haematemesis, melaena", "OGD within 24 h", "IV PPI + Endoscopic haemostasis"],
  ["GI", "Liver Cirrhosis", "Ascites, encephalopathy, varices", "USS + Ascitic tap", "Treat cause + Lactulose + Terlipressin"],
  ["Neurology", "Ischaemic Stroke", "Sudden focal deficit (FAST)", "CT head STAT", "Thrombolysis / Thrombectomy"],
  ["Neurology", "Parkinson's Disease", "Rest tremor, rigidity, bradykinesia", "Clinical ± DaTscan", "Levodopa / Dopamine agonist"],
  ["Endocrine", "Type 2 Diabetes", "Polyuria, fatigue, complications", "HbA1c + Fasting glucose", "Metformin + SGLT2i (CVD)"],
  ["Endocrine", "Hypothyroidism", "Fatigue, cold intolerance, bradycardia", "TSH (elevated)", "Levothyroxine"],
  ["Renal", "AKI", "Oliguria, uraemia, hyperkalaemia", "Creatinine + Renal USS", "Treat cause; fluids; dialysis if severe"],
  ["MSK", "Rheumatoid Arthritis", "Symmetrical MCP/PIP arthritis, AM stiffness", "Anti-CCP + X-ray hands", "Methotrexate (treat-to-target)"],
  ["MSK", "Osteoporosis", "Fragility fracture, kyphosis", "DEXA scan + FRAX", "Bisphosphonates + Ca/Vit D"],
  ["Haematology", "Anaemia (IDA)", "Fatigue, pallor, koilonychia", "FBC + Ferritin", "Iron supplementation; investigate cause"],
  ["Infection", "Sepsis", "Fever, organ dysfunction, raised lactate", "Blood cultures + Lactate", "Hourly bundle: Abx + Fluids + Vasopressors"],
  ["Geriatrics", "Delirium", "Acute confusion, fluctuating, hypoactive/hyperactive", "4AT screen + Root cause", "Treat cause + non-pharmacological measures"],
  ["Geriatrics", "Falls", "Recurrent falls, fear of falling, injuries", "ECG + Orthostatic BP + Gait test", "Multifactorial intervention + physio"],
];

const tableRows = tableData.map((row, rowIdx) => new TableRow({
  tableHeader: rowIdx === 0,
  children: row.map((cell) => new TableCell({
    width: { size: 20, type: WidthType.PERCENTAGE },
    borders: { top: noBorder, bottom: noBorder, left: noBorder, right: noBorder },
    verticalAlign: VerticalAlign.TOP,
    children: [new Paragraph({
      children: [new TextRun({
        text: cell,
        font: "Arial",
        size: rowIdx === 0 ? 20 : 18,
        bold: rowIdx === 0
      })],
      spacing: { before: 60, after: 60 }
    })]
  }))
}));

content.push(new Table({
  rows: tableRows,
  width: { size: 100, type: WidthType.PERCENTAGE },
  borders: {
    top: noBorder, bottom: noBorder, left: noBorder, right: noBorder,
    insideH: noBorder, insideV: noBorder
  }
}));

content.push(spacer());
content.push(pageBreak());

// ── ELOG ENTRY TEMPLATE ────────────────────────────────────────────────────
content.push(h1("E-Log Entry Template"));
content.push(para("Use the following structure for each patient encounter documented in your elog:"));
for (const item of [
  "Patient demographics: age, sex, relevant comorbidities",
  "Presenting complaint and history of presenting illness",
  "Relevant past medical, drug, allergy, social, and family history",
  "Clinical examination findings (general and systemic)",
  "Differential diagnoses considered",
  "Investigations ordered and results",
  "Clinical discussion: reasoning, aetiology, significance of findings",
  "Management plan and patient education provided",
  "Outcome and follow-up plan",
  "Learning points and personal reflection",
]) {
  content.push(bullet(item));
}
content.push(spacer());
content.push(para("Always cross-reference clinical findings with current national guidelines (NICE, BHS, AHA/ACC, ESC, GOLD, GINA) and local trust protocols."));

// ─── BUILD DOCUMENT ─────────────────────────────────────────────────────────
const doc = new Document({
  numbering: {
    config: [{
      reference: "bullets",
      levels: [{
        level: 0,
        format: LevelFormat.BULLET,
        text: "\u2022",
        alignment: AlignmentType.LEFT,
        style: { paragraph: { indent: { left: 720, hanging: 360 } } }
      }]
    }]
  },
  styles: {
    default: {
      document: { run: { font: "Arial", size: 22 } }
    },
    paragraphStyles: [
      {
        id: "Heading1", name: "Heading 1", basedOn: "Normal", next: "Normal", quickFormat: true,
        run: { size: 36, bold: true, font: "Arial" },
        paragraph: { spacing: { before: 400, after: 200 }, outlineLevel: 0 }
      },
      {
        id: "Heading2", name: "Heading 2", basedOn: "Normal", next: "Normal", quickFormat: true,
        run: { size: 28, bold: true, font: "Arial" },
        paragraph: { spacing: { before: 300, after: 160 }, outlineLevel: 1 }
      },
      {
        id: "Heading3", name: "Heading 3", basedOn: "Normal", next: "Normal", quickFormat: true,
        run: { size: 26, bold: true, font: "Arial" },
        paragraph: { spacing: { before: 240, after: 120 }, outlineLevel: 2 }
      },
    ]
  },
  sections: [{ children: content }]
});

Packer.toBuffer(doc).then(buffer => {
  fs.writeFileSync("/home/daytona/workspace/elog/Clinical_Elog_Plain.docx", buffer);
  console.log("DONE");
});
Running Command

cd /home/daytona/workspace/elog && node generate_elog_plain.js 2>&1

Running Command

cp /home/daytona/workspace/elog/Clinical_Elog_Plain.docx /tmp/elog_plain.docx && soffice --headless --convert-to pdf --outdir /tmp/ /tmp/elog_plain.docx 2>&1 && ls -lh /tmp/elog_plain.pdf

Running Command

cp /tmp/elog_plain.pdf /home/daytona/workspace/elog/Clinical_Elog_Plain.pdf && ls -lh /home/daytona/workspace/elog/

Done! Here are your plain-style files:

Download links:
  • Clinical Elog Plain

    PDF Document · PDF

    (PDF, 411 KB)
  • Clinical Elog Plain

    Word Document · DOCX

    (Word, 32 KB)

What changed in this version:
  • No coloured section boxes or backgrounds
  • Headings are plain black, bold, straight underline style
  • Section labels (Aetiology, Clinical Features, etc.) are simple bold inline text with a colon
  • Summary table uses plain thin borders only — no shading
  • Clean, minimal look throughout — easy to print in black and white

Use this two as reference for further docs no page break just simple title and the discussion

Reading File
Running Command

python3 -c " import pdfplumber for path in [ '/home/daytona/workspace/attachments/b7ea4a55-97e9-43e4-a53c-c2a4eecb96d8/e-log%20book%20c-3%20.pdf.pdf', '/home/daytona/workspace/attachments/b7ea4a55-97e9-43e4-a53c-c2a4eecb96d8/C-1 Geriatric.pdf' ]: print('=== FILE:', path, '===') with pdfplumber.open(path) as pdf: for i, page in enumerate(pdf.pages[:6]): print(f'--- PAGE {i+1} ---') print(page.extract_text()) print() "

Running Command

python3 -c " import pdfplumber path = '/home/daytona/workspace/attachments/b7ea4a55-97e9-43e4-a53c-c2a4eecb96d8/e-log%20book%20c-3%20.pdf.pdf' with pdfplumber.open(path) as pdf: print('Total pages:', len(pdf.pages)) # show page 1 full print(pdf.pages[0].extract_text()) "

Apply the basic sciences knowledge in understanding and managing common diseases. Make docs

Running Command

python3 -c " import pdfplumber path = '/home/daytona/workspace/attachments/b7ea4a55-97e9-43e4-a53c-c2a4eecb96d8/C-1 Geriatric.pdf' with pdfplumber.open(path) as pdf: print('Pages:', len(pdf.pages)) for i, page in enumerate(pdf.pages[:3]): print(f'--- PAGE {i+1} ---') print(page.extract_text()) " 2>&1

Writing File

~/elog/generate_B_basic_sciences.js

const {
  Document, Packer, Paragraph, TextRun,
  AlignmentType, LevelFormat, BorderStyle, WidthType,
  Table, TableRow, TableCell, VerticalAlign
} = require('docx');
const fs = require('fs');

// ── Helpers matching reference style ─────────────────────────────────────────
function title(text) {
  return new Paragraph({
    children: [new TextRun({ text, bold: true, size: 30, font: "Arial" })],
    spacing: { before: 0, after: 200 }
  });
}
function intro(text) {
  return new Paragraph({
    children: [new TextRun({ text, font: "Arial", size: 22 })],
    spacing: { after: 200 }
  });
}
function h1(text) {
  return new Paragraph({
    children: [new TextRun({ text, bold: true, size: 26, font: "Arial" })],
    spacing: { before: 280, after: 100 }
  });
}
function h2(text) {
  return new Paragraph({
    children: [new TextRun({ text, bold: true, size: 24, font: "Arial" })],
    spacing: { before: 200, after: 80 }
  });
}
function sectionLabel(label) {
  // Bold label + colon, matching reference exactly
  return new Paragraph({
    children: [new TextRun({ text: label + ":", bold: true, font: "Arial", size: 22 })],
    spacing: { before: 120, after: 40 }
  });
}
function bullet(text) {
  const parts = [];
  const segs = text.split(/(\*\*[^*]+\*\*)/);
  for (const s of segs) {
    if (s.startsWith("**") && s.endsWith("**"))
      parts.push(new TextRun({ text: s.slice(2,-2), bold: true, font: "Arial", size: 22 }));
    else
      parts.push(new TextRun({ text: s, font: "Arial", size: 22 }));
  }
  return new Paragraph({
    numbering: { reference: "bullets", level: 0 },
    children: parts,
    spacing: { after: 60 }
  });
}
function sp() { return new Paragraph({ children: [new TextRun("")], spacing: { after: 60 } }); }

// ── Disease block matching reference format ───────────────────────────────────
function block(name, sections) {
  // sections = [ { label, bullets: [] }, ... ]
  const out = [];
  out.push(h2(name));
  for (const sec of sections) {
    out.push(sectionLabel(sec.label));
    for (const b of sec.bullets) out.push(bullet(b));
  }
  out.push(sp());
  return out;
}

// ══════════════════════════════════════════════════════════════════════════════
// CONTENT
// ══════════════════════════════════════════════════════════════════════════════
const content = [];

content.push(title("Basic Sciences Applied to Understanding and Managing Common Diseases"));
content.push(intro(
  "Basic sciences — anatomy, physiology, biochemistry, pathology, microbiology, pharmacology, and immunology — form the " +
  "foundation for understanding why diseases occur, how they present, and why specific treatments work. " +
  "This document applies core basic science concepts directly to the clinical management of common diseases encountered in " +
  "adult and geriatric medicine, using the same structured format as the clinical e-log reference."
));

// ════════════════════════════════════════════════════════
content.push(h1("1. Cardiovascular Diseases"));
// ════════════════════════════════════════════════════════

content.push(...block("1.1  Acute Myocardial Infarction (AMI)", [
  {
    label: "Anatomy Basis",
    bullets: [
      "Left coronary artery (LCA) divides into left anterior descending (LAD) and left circumflex (LCx): LAD supplies anterior LV wall and septum; LCx supplies lateral wall",
      "Right coronary artery (RCA) supplies inferior LV wall, posterior descending artery, and SA/AV nodes in most individuals (right-dominant circulation)",
      "LAD occlusion → anterior STEMI (V1–V4); RCA occlusion → inferior STEMI (II, III, aVF); LCx occlusion → lateral STEMI (I, aVL, V5–V6)",
      "Papillary muscles (posteromedial > anterolateral) are supplied by single coronary vessels — vulnerable to ischaemia → mitral regurgitation post-MI"
    ]
  },
  {
    label: "Physiology Basis",
    bullets: [
      "Myocardial oxygen demand = heart rate × contractility × wall stress (Laplace: pressure × radius / 2 × wall thickness)",
      "Coronary blood flow occurs mainly in diastole — tachycardia shortens diastole and reduces coronary perfusion time",
      "Cardiac output = stroke volume × heart rate; stroke volume determined by preload (EDV), afterload (SVR), and contractility",
      "Autonomic innervation: sympathetic (beta-1 adrenoceptors) increases HR and contractility; parasympathetic (vagal, M2 receptors) slows HR — explains Bezold-Jarisch reflex in inferior MI (bradycardia, hypotension)"
    ]
  },
  {
    label: "Pathophysiology",
    bullets: [
      "Atherosclerosis: endothelial injury → LDL oxidation → foam cell (macrophage) accumulation → fibrous plaque → vulnerable plaque with thin fibrous cap and lipid core",
      "Plaque rupture → exposure of subendothelial collagen → platelet adhesion (GPIb-vWF), activation (ADP, TXA2), aggregation (GPIIb/IIIa-fibrinogen) → thrombus",
      "Thrombus → total occlusion (STEMI) or subtotal/embolism (NSTEMI/UA)",
      "Ischaemia cascade: diastolic dysfunction → systolic dysfunction → ECG changes → chest pain (in that order)",
      "Zone of ischaemia (reversible) surrounds zone of injury (ST elevation) surrounds zone of infarction (Q waves) — basis of ECG changes",
      "Reperfusion injury: calcium overload, reactive oxygen species, neutrophil activation — paradoxical cell death on restoring blood flow (justifies PCI over prolonged thrombolysis delay)"
    ]
  },
  {
    label: "Biochemistry of Cardiac Markers",
    bullets: [
      "Troponin I/T: regulatory proteins of the actin-myosin interaction; released when sarcolemma disrupted; cardiac-specific isoforms (cTnI, cTnT) rise within 1–3 h, peak 12–24 h, persist 7–14 days",
      "CK-MB: cytoplasmic isoenzyme; rises 3–6 h, peaks 24 h, returns to baseline at 48–72 h — useful for detecting reinfarction",
      "BNP/NT-proBNP: released by ventricular myocytes in response to wall stretch; mirrors filling pressure elevation — used to diagnose heart failure and guide diuretic therapy",
      "LDH-1 isoenzyme: historically used; now replaced by high-sensitivity troponin"
    ]
  },
  {
    label: "Pharmacology of Management",
    bullets: [
      "Aspirin: irreversibly inhibits COX-1 → prevents TXA2 synthesis → reduces platelet aggregation (antiplatelet effect lasts platelet lifetime ~7–10 days)",
      "Ticagrelor/Clopidogrel: P2Y12 receptor antagonists → block ADP-mediated platelet aggregation; ticagrelor is reversible and faster-acting than clopidogrel (prodrug requiring hepatic activation via CYP2C19)",
      "Heparin (UFH/LMWH): binds antithrombin III → inhibits thrombin (IIa) and factor Xa; LMWH (enoxaparin) has greater anti-Xa activity and more predictable pharmacokinetics",
      "Beta-blockers (metoprolol, bisoprolol): block beta-1 receptors → reduce HR, contractility, myocardial O2 demand; reduce mortality post-MI by preventing remodelling and arrhythmias",
      "ACE inhibitors (ramipril, lisinopril): block conversion of angiotensin I → II → reduce afterload and prevent ventricular remodelling; reduce mortality in post-MI LV dysfunction",
      "Statins (atorvastatin): inhibit HMG-CoA reductase → reduce LDL synthesis; pleiotropic effects — plaque stabilisation, anti-inflammatory, improved endothelial function"
    ]
  }
]));

content.push(...block("1.2  Hypertension and Its Complications", [
  {
    label: "Physiology Basis",
    bullets: [
      "Blood pressure = cardiac output × total peripheral resistance (TPR)",
      "TPR regulated by: arteriolar smooth muscle tone, autonomic nervous system (sympathetic alpha-1 vasoconstriction), RAAS (angiotensin II → vasoconstriction + aldosterone release → Na/water retention → increased CO)",
      "Baroreceptor reflex (carotid sinus, aortic arch) normally buffers acute BP changes — attenuated in hypertension and ageing",
      "Renin released by juxtaglomerular cells (JGA) in response to: low renal perfusion pressure, sympathetic stimulation, hyponatraemia → angiotensin I → ACE → angiotensin II"
    ]
  },
  {
    label: "Pathophysiology of Organ Damage",
    bullets: [
      "Blood vessels: sustained high pressure → endothelial shear stress → LDL oxidation → accelerated atherosclerosis; hyaline arteriolosclerosis (small vessels — retina, kidney)",
      "Heart: increased afterload → concentric LVH → diastolic dysfunction → HFpEF; LVH predisposes to arrhythmias and sudden death",
      "Kidney: hypertensive nephrosclerosis — afferent arteriolar thickening → ischaemic glomerulosclerosis → proteinuria → CKD (also a cause and consequence of hypertension — self-perpetuating cycle)",
      "Brain: lacunar infarcts (small vessel disease — lipohyalinosis), haemorrhagic stroke (Charcot-Bouchard microaneurysms — lenticulostriate arteries), hypertensive encephalopathy (loss of cerebrovascular autoregulation)"
    ]
  },
  {
    label: "Pharmacology of Antihypertensives",
    bullets: [
      "ACE inhibitors/ARBs: block RAAS — first-line in CKD, diabetes, heart failure, post-MI; ARBs used when ACEi cause bradykinin-mediated cough (increased bradykinin → substance P → cough reflex)",
      "Calcium channel blockers (amlodipine — dihydropyridine): block L-type Ca2+ channels in vascular smooth muscle → vasodilation; preferred in elderly, isolated systolic hypertension",
      "Thiazide diuretics (indapamide): inhibit Na-Cl cotransporter (NCC) in distal convoluted tubule → initial volume depletion → sustained vasodilation (long-term mechanism); cause hypokalaemia, hyperuricaemia, hyperglycaemia",
      "Beta-blockers: reduce CO by blocking beta-1; second-line for hypertension; first-line if concurrent angina, tachyarrhythmia, or heart failure",
      "Spironolactone: aldosterone antagonist — useful in resistant hypertension (Conn's syndrome), heart failure; causes hyperkalaemia"
    ]
  }
]));

// ════════════════════════════════════════════════════════
content.push(h1("2. Respiratory Diseases"));
// ════════════════════════════════════════════════════════

content.push(...block("2.1  Community-Acquired Pneumonia (CAP)", [
  {
    label: "Microbiology Basis",
    bullets: [
      "Streptococcus pneumoniae (gram-positive, lancet-shaped diplococci): capsule prevents phagocytosis — basis of polysaccharide capsule typing (>90 serotypes); virulence from pneumolysin, neuraminidase, IgA protease",
      "Haemophilus influenzae (gram-negative coccobacillus): non-typeable strains cause CAP in COPD patients; type b (Hib) causes invasive disease — prevented by Hib vaccine",
      "Atypical pathogens (Mycoplasma, Chlamydophila, Legionella): lack cell wall — intrinsically resistant to beta-lactams; cell wall deficiency explains why they stain poorly on Gram stain and need macrolide/fluoroquinolone therapy",
      "Legionella pneumophila: found in water systems (cooling towers, hospital water); survives inside alveolar macrophages (intracellular pathogen); detected by urinary antigen"
    ]
  },
  {
    label: "Immunology / Pathophysiology",
    bullets: [
      "Normal pulmonary defence: mucociliary escalator (goblet cells + ciliated epithelium), alveolar macrophages (first-line phagocytes), IgA in secretions, cough reflex",
      "Breach of defences → bacterial entry → alveolar macrophage activation → TNF-alpha, IL-1, IL-6, IL-8 release → neutrophil recruitment → inflammatory exudate fills alveolar spaces → consolidation",
      "Consolidation: alveoli fill with neutrophils, fibrin, red cells → lobar pneumonia histological stages: congestion → red hepatisation → grey hepatisation → resolution",
      "V/Q mismatch: consolidated lung continues to be perfused but not ventilated → intrapulmonary shunt → hypoxaemia",
      "Systemic sepsis response: cytokine storm → hypothalamic temperature dysregulation (fever), hepatic acute phase proteins (CRP, fibrinogen, complement activation)"
    ]
  },
  {
    label: "Pharmacology of Antibiotics",
    bullets: [
      "Amoxicillin (aminopenicillin): inhibits transpeptidase (PBP) → prevents peptidoglycan cross-linking → bacterial cell wall lysis; active against S. pneumoniae, H. influenzae (ampicillin-sensitive)",
      "Clarithromycin (macrolide): binds 50S ribosomal subunit → inhibits translocation → bacteriostatic; active against atypical pathogens; CYP3A4 inhibitor — drug interactions",
      "Co-amoxiclav: amoxicillin + clavulanic acid (beta-lactamase inhibitor) → overcomes beta-lactamase producing H. influenzae and Klebsiella",
      "Levofloxacin (fluoroquinolone): inhibits DNA gyrase (topoisomerase II) and topoisomerase IV → prevents DNA supercoiling → bactericidal; covers all CAP pathogens including atypicals — 'pneumonia monotherapy'",
      "Antibiotic stewardship: procalcitonin-guided therapy — rises selectively in bacterial infection (cytokine stimulation of calcitonin precursor); guides start and stop decisions, reducing antibiotic duration"
    ]
  }
]));

content.push(...block("2.2  Chronic Obstructive Pulmonary Disease (COPD)", [
  {
    label: "Anatomy and Physiology Basis",
    bullets: [
      "Bronchial tree: trachea → main bronchi → lobar → segmental bronchi → bronchioles (no cartilage, <1 mm) → terminal bronchioles → respiratory bronchioles → alveolar ducts → alveoli",
      "Type I pneumocytes (95% of surface area): gas exchange; Type II pneumocytes: secrete surfactant (phosphatidylcholine/DPPC) — reduces surface tension, prevents alveolar collapse",
      "Spirometry: FEV1 = forced expired volume in 1 second; FVC = forced vital capacity; normal FEV1/FVC ratio ≥0.70; obstructive pattern: FEV1/FVC <0.70 (airflow limitation)",
      "Hypoxic pulmonary vasoconstriction (HPV): local reflex diverts blood from poorly ventilated to better ventilated segments — maintains V/Q matching; in COPD, generalised hypoxia → global HPV → pulmonary hypertension → cor pulmonale"
    ]
  },
  {
    label: "Pathophysiology",
    bullets: [
      "Tobacco smoke → reactive oxygen species (ROS) + nicotine → airway epithelial injury → mucus gland hypertrophy (chronic bronchitis: productive cough ≥3 months/year for ≥2 years) + goblet cell metaplasia",
      "Protease-antiprotease imbalance: smoke activates neutrophils and macrophages → release neutrophil elastase, MMP-9 → destruction of alveolar walls (emphysema); alpha-1 antitrypsin (AAT) inhibits elastase — AAT deficiency causes premature emphysema",
      "Emphysema: permanent enlargement of air spaces distal to terminal bronchioles — centrilobular (smoking-related, upper lobe predominant) vs. panlobular (AAT deficiency, lower lobe predominant)",
      "Air trapping: dynamic hyperinflation → increased RV and FRC → barrel chest; pursed-lip breathing creates back pressure (intrinsic PEEP) to prevent expiratory collapse",
      "Hypercapnic respiratory failure (type II): chronic CO2 retention → bicarbonate retention (renal compensation — metabolic alkalosis) → blunted central chemoreceptor response → ventilatory drive shifts to peripheral O2 receptors (carotid bodies) — basis for controlled oxygen therapy at 88–92%"
    ]
  },
  {
    label: "Pharmacology of Bronchodilators",
    bullets: [
      "Salbutamol (SABA — short-acting beta-2 agonist): activates beta-2 receptors → adenylyl cyclase → cAMP → PKA → smooth muscle relaxation (phosphorylates MLCK, reducing Ca2+ sensitivity); also stimulates mucociliary clearance",
      "Tiotropium (LAMA — long-acting muscarinic antagonist): blocks M3 receptors on airway smooth muscle → prevents ACh-mediated bronchoconstriction; dissociates slowly from M3 → 24-h duration; also reduces mucus secretion",
      "Salmeterol/Formoterol (LABA): long-acting beta-2 agonists; formoterol has rapid onset (useful for rescue) + long duration; used with LAMA for additive bronchodilation via different receptors",
      "Inhaled corticosteroids (ICS — budesonide, fluticasone): suppress airway inflammation (reduce eosinophilic inflammation in blood eosinophilia phenotype); reduce exacerbations; systemic absorption minimal (first-pass metabolism if swallowed)",
      "Roflumilast (PDE4 inhibitor): selective phosphodiesterase-4 inhibition → increased cAMP in inflammatory cells → reduced neutrophil/macrophage activity; reduces exacerbations in severe COPD with chronic bronchitis phenotype"
    ]
  }
]));

// ════════════════════════════════════════════════════════
content.push(h1("3. Gastrointestinal and Hepatic Diseases"));
// ════════════════════════════════════════════════════════

content.push(...block("3.1  Peptic Ulcer Disease", [
  {
    label: "Anatomy and Physiology Basis",
    bullets: [
      "Gastric mucosal defence: mucus-bicarbonate layer (goblet cells secrete HCO3-), tight junctions between epithelial cells, rapid cell turnover (3–5 days), prostaglandin E2 (PGE2) and PGI2 stimulate mucus and bicarbonate secretion and maintain mucosal blood flow",
      "Acid secretion: parietal cells (gastric body/fundus) secrete HCl via H+/K+-ATPase (proton pump); stimulated by histamine (H2 receptors), ACh (M3 receptors), gastrin (CCK-B receptors); inhibited by somatostatin",
      "Duodenal mucosa protected by: Brunner's glands (alkaline mucus), bile and pancreatic bicarbonate neutralising gastric acid",
      "Gastric emptying regulated by: vagal tone, CCK (delays emptying), motilin (accelerates) — relevant to understanding gastroparesis in diabetes"
    ]
  },
  {
    label: "Pathophysiology",
    bullets: [
      "H. pylori (gram-negative, microaerophilic spiral rod): produces urease → converts urea to ammonia (NH3) → neutralises local pH → allows survival in gastric mucus; VacA toxin disrupts epithelial tight junctions; CagA (virulence marker) activates NF-kB → chronic inflammation",
      "H. pylori disrupts the mucus layer, stimulates gastrin (hypersecretion), and induces neutrophil/T-cell infiltration → gastritis → ulceration; predominantly antral gastritis → duodenal ulcer (increased acid delivery); corpus gastritis → reduced acid → gastric ulcer",
      "NSAIDs: inhibit COX-1 (constitutive) → reduce PGE2 and PGI2 → impaired mucus/bicarbonate secretion + reduced mucosal blood flow → ulceration; also direct topical toxicity at low pH",
      "Zollinger-Ellison syndrome: gastrin-secreting tumour (gastrinoma) → massive acid hypersecretion → multiple refractory ulcers + diarrhoea (acid inactivates pancreatic lipase)"
    ]
  },
  {
    label: "Pharmacology",
    bullets: [
      "Proton pump inhibitors (omeprazole, lansoprazole): prodrugs — absorbed systemically, concentrated in acid canaliculi of parietal cells where low pH activates them to sulphenamide form → irreversibly bind H+/K+-ATPase → block acid pump; most effective when taken before meals (maximal number of active pumps)",
      "H2 receptor antagonists (ranitidine, famotidine): competitive block of H2 receptors on parietal cells → reduce histamine-stimulated acid; less complete suppression than PPIs (cannot block gastrin/ACh pathways)",
      "Antacids (aluminium/magnesium hydroxide): neutralise luminal acid directly; aluminium → constipation (reduces gut motility); magnesium → diarrhoea; both chelate tetracyclines/fluoroquinolones — drug interaction",
      "H. pylori eradication triple therapy: PPI (reduces acid → activates amoxicillin, clarithromycin works better at higher pH) + amoxicillin (cell wall) + clarithromycin (protein synthesis) for 7–14 days; clarithromycin resistance rising → bismuth quadruple therapy as alternative",
      "Misoprostol (PGE1 analogue): replaces prostaglandins in NSAID users → mucus/bicarb stimulation, mucosal blood flow maintenance; causes diarrhoea/uterine contractions — limited tolerability"
    ]
  }
]));

content.push(...block("3.2  Liver Disease and Cirrhosis", [
  {
    label: "Biochemistry of Liver Function",
    bullets: [
      "Hepatocyte functions: protein synthesis (albumin, clotting factors I, II, V, VII, IX, X, XI — all except vWF and VIII); gluconeogenesis (maintains fasting glucose), glycogen storage, lipid metabolism (VLDL synthesis, bile acid conjugation)",
      "Bilirubin metabolism: haem catabolism → unconjugated bilirubin (lipid-soluble, albumin-bound) → hepatocyte uptake → UGT1A1 conjugation (water-soluble bilirubin diglucuronide) → bile excretion → gut bacteria → urobilinogen → stercobilin (stool) + some absorbed → urinary urobilinogen",
      "Prehepatic jaundice: haemolysis → excess unconjugated bilirubin; dark urine absent (unconjugated not filtered by kidney); Hepatic jaundice: conjugation failure (hepatitis) → mixed; Posthepatic (obstructive): conjugated bilirubin backs up → dark urine, pale stools, pruritus (bile salts)",
      "LFTs interpretation: ALT/AST (hepatocellular damage — cytoplasmic enzymes); ALP/GGT (cholestatic — canalicular enzymes); albumin and PT (synthetic function — true markers of liver reserve)"
    ]
  },
  {
    label: "Pathophysiology of Portal Hypertension",
    bullets: [
      "Normal portal pressure 5–10 mmHg; portal hypertension defined as >12 mmHg; measured as hepatic venous pressure gradient (HVPG)",
      "In cirrhosis: hepatic fibrosis + regenerative nodules → increased intrahepatic resistance → portal hypertension; also splanchnic vasodilation (NO, glucagon) → reduced effective arterial blood volume → RAAS/SNS activation → sodium/water retention → ascites and oedema",
      "Portosystemic collateral vessels (varices): oesophageal (submucosal veins), rectal (haemorrhoids), caput medusae (umbilical vein recanalisation) — all consequences of diverted portal blood",
      "Hepatic encephalopathy: reduced hepatic clearance of nitrogenous compounds (ammonia from gut bacteria acting on protein) → astrocyte swelling (glutamine synthesis) → cerebral oedema; also GABA-ergic neurotransmission alteration; precipitated by GI bleed (protein load), constipation, infection, alkalosis (shifts NH4+ to NH3 — crosses BBB)",
      "Hepatorenal syndrome (HRS): splanchnic vasodilation → reduced renal perfusion → renal vasoconstriction (RAAS, ET-1, vasopressin) → functional renal failure without structural damage — kidneys are histologically normal"
    ]
  },
  {
    label: "Pharmacology",
    bullets: [
      "Terlipressin (vasopressin analogue): V1 receptor agonist → splanchnic vasoconstriction → reduces portal pressure → controls variceal bleeding; also used in HRS (increases renal perfusion)",
      "Propranolol/carvedilol (non-selective beta-blockers): reduce cardiac output (beta-1) + splanchnic vasodilation (beta-2 block) → reduce portal pressure; primary and secondary prophylaxis of variceal bleeding",
      "Lactulose: non-absorbable disaccharide → colonic acidification (lactate production) → NH4+ trapping (ionisation in acid environment → cannot cross colonic mucosa) + cathartic effect (reduces ammonia production time); also alters gut flora",
      "Rifaximin: non-absorbable antibiotic (rifamycin derivative) → suppresses urease-producing colonic bacteria → reduces ammonia production; superior to lactulose for secondary prevention of encephalopathy",
      "Spironolactone (aldosterone antagonist) + furosemide (loop diuretic): spironolactone targets secondary hyperaldosteronism driving ascites — given at 100:40 ratio with furosemide to maintain normonatraemia"
    ]
  }
]));

// ════════════════════════════════════════════════════════
content.push(h1("4. Neurological Diseases"));
// ════════════════════════════════════════════════════════

content.push(...block("4.1  Ischaemic Stroke", [
  {
    label: "Neuroanatomy Basis",
    bullets: [
      "Circle of Willis: formed by ICAs (anterior circulation) and basilar artery (posterior circulation); provides collateral flow — explains why proximal occlusion may not always cause infarction if collaterals patent",
      "MCA territory (largest territory): lateral frontal, parietal, temporal lobes → contralateral hemiplegia (motor cortex — precentral gyrus), hemisensory loss (postcentral gyrus), aphasia (dominant hemisphere Broca's/Wernicke's area), neglect/inattention (non-dominant parietal)",
      "ACA territory: medial frontal/parietal → contralateral leg weakness (leg cortex is medial) + urinary incontinence (paracentral lobule) + abulia (frontal lobe syndrome)",
      "Posterior circulation (PCA, basilar): occipital lobe (homonymous hemianopia), thalamus, brainstem (Weber's, Wallenberg's syndromes), cerebellum (ataxia)",
      "Penumbra concept: ischaemic core (irreversible infarction within minutes — no oxygen → ATP failure → Na/K-ATPase failure → depolarisation → cytotoxic oedema) surrounded by penumbra (reduced flow but not zero → potentially salvageable with reperfusion — basis for thrombolysis and thrombectomy time windows)"
    ]
  },
  {
    label: "Pathophysiology of Infarction",
    bullets: [
      "Ischaemic cascade: energy failure → glutamate excitotoxicity (NMDA receptor overactivation → Ca2+ influx) → mitochondrial dysfunction → ROS production → membrane phospholipase activation → cell death",
      "Cytotoxic oedema (early, minutes): cell swelling due to failure of Na/K-ATPase → no change in BBB permeability; followed by vasogenic oedema (hours–days): BBB disruption → protein-rich fluid leaks into extracellular space",
      "Cardioembolic stroke: AF → stagnant flow in left atrial appendage (LAA) → thrombus → Virchow's triad (stasis + hypercoagulability + endothelial dysfunction); typically large vessel, cortical territory involvement",
      "Lacunar infarcts: small perforating arteries (lenticulostriate, thalamoperforators) — hypertension and diabetes cause lipohyalinosis (fibrinoid degeneration of vessel wall) → small deep infarcts (<15 mm)"
    ]
  },
  {
    label: "Pharmacology",
    bullets: [
      "Alteplase (tPA — tissue plasminogen activator): serine protease → converts plasminogen → plasmin → digests fibrin clot; benefit limited to 4.5 h window (beyond this, haemorrhagic transformation risk outweighs benefit); contraindicated if BP >185/110, recent surgery, bleeding diathesis",
      "Aspirin 300 mg: COX-1 inhibition → antiplatelet effect; loading dose within 24 h of ischaemic stroke (after haemorrhage excluded); reduces early recurrence in TIA/minor stroke",
      "DOACs (apixaban, rivaroxaban, dabigatran): direct inhibitors of Xa (apixaban/rivaroxaban) or thrombin (dabigatran); superior to warfarin in AF stroke prevention with fewer intracranial haemorrhages; no need for INR monitoring",
      "Statins: pleiotropic effects — stabilise carotid plaques, improve endothelial function; atorvastatin 80 mg reduces stroke recurrence (SPARCL trial)"
    ]
  }
]));

content.push(...block("4.2  Parkinson's Disease", [
  {
    label: "Neuroanatomy and Neurochemistry Basis",
    bullets: [
      "Basal ganglia circuit: striatum (caudate + putamen) → globus pallidus interna (GPi) → thalamus (VL nucleus) → motor cortex; modulated by substantia nigra pars compacta (SNc) dopaminergic neurons",
      "Nigrostriatal pathway: SNc dopaminergic neurons project to striatum via D1/D2 receptors; dopamine activates direct pathway (D1 — facilitates movement) and inhibits indirect pathway (D2 — suppresses unwanted movement) → net effect: thalamic disinhibition → movement facilitation",
      "In PD: SNc neuron loss → reduced striatal dopamine → indirect pathway overactive → thalamic inhibition → reduced cortical motor activation → bradykinesia and rigidity",
      "Alpha-synuclein: protein that aggregates in Lewy bodies (acidophilic intraneuronal inclusions) → neurodegeneration; spreads prion-like through neural networks (Braak staging) explaining the rostrocaudal progression from brainstem to cortex",
      "Dopamine synthesis pathway: tyrosine → DOPA (tyrosine hydroxylase, rate-limiting step) → dopamine (DOPA decarboxylase/AADC) → stored in vesicles (VMAT2) → released; metabolism by MAO-B and COMT"
    ]
  },
  {
    label: "Pathophysiology",
    bullets: [
      "Loss of 60–70% of SNc neurons before motor symptoms appear (presymptomatic reserve) — explains why anosmia, constipation, REM sleep behaviour disorder (Braak stage 1–2, dorsal motor nucleus of vagus + olfactory bulb) precede motor features by years",
      "Tremor: abnormal oscillatory activity in the cortico-basal ganglia-thalamo-cortical loop; rest tremor (vs. essential tremor which is action tremor — different circuit)",
      "Rigidity: increased tonic muscle activity in both flexors and extensors (basal ganglia output excess); cogwheeling = rigidity + superimposed tremor",
      "Autonomic dysfunction: Lewy body involvement of sympathetic ganglia, dorsal vagal nucleus → orthostatic hypotension (reduced noradrenaline), constipation, bladder dysfunction, seborrhoea"
    ]
  },
  {
    label: "Pharmacology",
    bullets: [
      "Levodopa (co-careldopa): crosses blood-brain barrier (BBB) via large neutral amino acid transporter (LAT1) → decarboxylated to dopamine in striatum; carbidopa (peripheral DOPA decarboxylase inhibitor) prevents peripheral conversion → reduces nausea, allows lower levodopa dose, increases CNS availability",
      "Dopamine agonists (pramipexole — D3/D2; ropinirole — D2/D3): direct receptor agonists; bypass presynaptic neuron — useful when dopamine synthesis capacity is lost; impulse control disorders are a class side effect (D3 — reward circuitry)",
      "MAO-B inhibitors (rasagiline, selegiline): inhibit monoamine oxidase B → reduce dopamine degradation in synapse → increase synaptic dopamine; also neuroprotective effect (rasagiline — ADAGIO trial suggests disease modification)",
      "COMT inhibitors (entacapone, tolcapone): inhibit catechol-O-methyltransferase → prevent dopamine/levodopa breakdown → extend levodopa half-life and reduce 'wearing off' fluctuations",
      "Amantadine: NMDA receptor antagonist → reduces glutamate excitotoxicity; also dopamine-releasing effect; used for dyskinesias in advanced PD"
    ]
  }
]));

// ════════════════════════════════════════════════════════
content.push(h1("5. Endocrine Diseases"));
// ════════════════════════════════════════════════════════

content.push(...block("5.1  Diabetes Mellitus Type 2", [
  {
    label: "Physiology Basis",
    bullets: [
      "Insulin: 51 amino acid peptide hormone, synthesised as preproinsulin → proinsulin → cleaved to insulin + C-peptide (equimolar — C-peptide used to assess endogenous insulin secretion)",
      "Insulin actions: Liver — promotes glycogen synthesis (glycogen synthase activation), suppresses gluconeogenesis (PEPCK inhibition), promotes fatty acid synthesis; Muscle — GLUT4 translocation → glucose uptake, protein synthesis; Adipose — GLUT4 → glucose uptake, inhibits lipolysis (hormone-sensitive lipase)",
      "Counter-regulatory hormones: glucagon (alpha cells — promotes glycogenolysis, gluconeogenesis), adrenaline, cortisol, growth hormone — all increase blood glucose; relevant in stress hyperglycaemia and Somogyi effect",
      "Incretin effect: GLP-1 (glucagon-like peptide-1, from L-cells) and GIP enhance glucose-stimulated insulin secretion (account for 50–70% of postprandial insulin response) — absent in T2DM; basis for GLP-1 agonist therapy"
    ]
  },
  {
    label: "Pathophysiology",
    bullets: [
      "Insulin resistance: impaired GLUT4 translocation and post-receptor signalling (IRS-1/PI3K/Akt pathway); driven by ectopic lipid deposition (DAG → PKC activation → serine phosphorylation of IRS-1 → pathway inhibition) in liver and muscle; central (visceral) adiposity is the key driver",
      "Beta-cell compensation → progressive failure: initially beta cells compensate with hypersecretion; chronic hyperglycaemia → glucotoxicity (ROS, ER stress) and lipotoxicity (ceramide, long-chain fatty acids) → beta-cell apoptosis → insulin deficiency",
      "Advanced glycation end-products (AGEs): glucose reacts with lysine residues on proteins (Maillard reaction) → irreversible cross-links → protein dysfunction; measured as HbA1c (haemoglobin glycation — reflects 2–3 month average glucose)",
      "Diabetic nephropathy: hyperglycaemia → glomerular hyperfiltration (afferent arteriolar dilation > efferent) → increased intraglomerular pressure → mesangial expansion, GBM thickening → glomerulosclerosis (Kimmelstiel-Wilson nodules) → proteinuria",
      "Diabetic neuropathy: polyol pathway (aldose reductase converts glucose → sorbitol → fructose → osmotic damage); reduced nerve myoinositol → impaired Na/K-ATPase → axonal degeneration; oxidative stress from AGEs"
    ]
  },
  {
    label: "Pharmacology",
    bullets: [
      "Metformin (biguanide): activates AMPK → inhibits mitochondrial complex I → reduces hepatic glucose output (gluconeogenesis inhibition); does not cause hypoglycaemia (no insulin secretion); lactic acidosis risk with renal failure (metformin accumulates); also reduces intestinal glucose absorption",
      "SGLT2 inhibitors (empagliflozin, dapagliflozin): block sodium-glucose cotransporter 2 in proximal tubule → glucosuria (150–300 g glucose excreted per day) + osmotic diuresis + natriuresis → lower BP, reduce preload/afterload; cardiovascular benefit (EMPA-REG OUTCOME) and renal protection (CREDENCE trial) beyond glycaemic effect",
      "GLP-1 receptor agonists (semaglutide, liraglutide): activate GLP-1R → cAMP → PKA → insulin secretion (glucose-dependent → low hypoglycaemia risk) + glucagon suppression + delayed gastric emptying + central satiety (hypothalamic GLP-1R) → weight loss; CV benefit (LEADER trial)",
      "DPP-4 inhibitors (sitagliptin): inhibit dipeptidyl peptidase-4 → prevent GLP-1 degradation → prolong incretin effect; weight-neutral; well-tolerated in elderly; dose-reduce in renal impairment",
      "Insulin: exogenous insulin therapy; basal (glargine, detemir — long-acting, peakless: precipitate at injection site → slow dissolution); bolus (aspart, lispro — rapid onset 15 min, peak 1 h: mimic meal-time secretion); mixed insulins combine both"
    ]
  }
]));

content.push(...block("5.2  Hypothyroidism", [
  {
    label: "Physiology Basis",
    bullets: [
      "HPT axis: hypothalamus TRH → pituitary TSH → thyroid gland T4/T3; negative feedback: T3/T4 inhibit TRH and TSH at pituitary and hypothalamus",
      "Thyroid hormone synthesis: iodide uptake (NIS — sodium iodide symporter) → oxidation to I2 (thyroid peroxidase, TPO) → iodination of tyrosines on thyroglobulin (MIT, DIT) → coupling (T3 = MIT+DIT; T4 = DIT+DIT) → stored as colloid → proteolysis → secretion",
      "T3 vs T4: T4 is the major secretory product (80%); T3 is more active (3–4× potency); 80% of circulating T3 derives from peripheral deiodination of T4 (5'-deiodinase) in liver, kidney, muscle",
      "Thyroid hormone actions: bind nuclear receptors (TR-alpha, TR-beta) → regulate gene transcription; increase BMR (upregulate Na/K-ATPase), cardiac contractility (increase beta-adrenoceptor density), GI motility, bone turnover, CNS development (critical in neonates)"
    ]
  },
  {
    label: "Pathophysiology",
    bullets: [
      "Hashimoto's thyroiditis: HLA-DR3/DR5 associated; CD4+ T cells (Th1) infiltrate thyroid → activate CD8+ cytotoxic T cells + B cells → anti-TPO antibodies (do not block function directly but mediate ADCC); eventually lymphocytic infiltration + fibrosis → gland destruction → hypothyroidism",
      "Reduced T3/T4 → reduced gene transcription effects: reduced Na/K-ATPase activity → hyponatraemia risk; reduced cardiac beta-receptor expression → bradycardia; reduced gut motility → constipation; reduced thermogenesis → cold intolerance; reduced glycogenolysis → hypoglycaemia tendency; reduced protein degradation → myxoedema (GAG accumulation in connective tissue due to reduced hyaluronidase activity)",
      "TSH elevation: loss of T4 feedback → pituitary TSH rises (most sensitive indicator of primary hypothyroidism — detects subclinical disease before T4 falls below normal range)"
    ]
  },
  {
    label: "Pharmacology",
    bullets: [
      "Levothyroxine (synthetic T4): oral T4 undergoes peripheral deiodination to T3 in target tissues — mimics normal physiology; half-life 7 days (once-daily dosing appropriate); take fasting 30–60 min before food (food reduces absorption by 25–40%)",
      "Drug interactions reducing absorption: calcium carbonate, iron salts, PPIs (reduce gastric acid → may reduce dissolution), cholestyramine, aluminium antacids — all chelate or adsorb levothyroxine",
      "Monitoring: TSH is the target parameter; after dose change, wait 6 weeks before rechecking (pituitary TSH needs 6 weeks to equilibrate after T4 change); target TSH 0.4–2.0 mIU/L in most patients",
      "Amiodarone-induced thyroid disease: amiodarone contains 37% iodine by weight; iodine excess → Wolff-Chaikoff effect (acute hypothyroidism — iodine excess inhibits organification) OR Jod-Basedow effect (hyperthyroidism in autonomous nodules); also amiodarone itself blocks T4→T3 conversion (5'-deiodinase inhibition) → raised T4, raised reverse T3, normal/low T3 — complex interpretation"
    ]
  }
]));

// ════════════════════════════════════════════════════════
content.push(h1("6. Renal Disease"));
// ════════════════════════════════════════════════════════

content.push(...block("6.1  Acute Kidney Injury (AKI)", [
  {
    label: "Anatomy and Physiology Basis",
    bullets: [
      "Nephron: glomerulus (filtration) → PCT (bulk reabsorption: 65% Na/water, all glucose/AA, HCO3-) → loop of Henle (countercurrent multiplication — concentrating mechanism) → DCT (Na-Cl reabsorption, regulated by aldosterone) → collecting duct (water reabsorption via ADH/aquaporin-2, acid-base regulation)",
      "GFR regulation: afferent arteriolar dilation (prostaglandins, NO) increases GFR; efferent arteriolar constriction (angiotensin II) maintains GFR when perfusion pressure falls — explains why NSAIDs (reduce PG) and ACE inhibitors/ARBs (reduce Ang II) both reduce GFR in low-flow states",
      "Tubuloglomerular feedback (TGF): macula densa senses NaCl in distal tubule → signals JGA → adjust afferent arteriolar tone → maintains constant GFR (autoregulation); adenosine mediates afferent vasoconstriction in TGF",
      "Creatinine as GFR marker: freely filtered, not reabsorbed, small tubular secretion — creatinine clearance slightly overestimates GFR; important: serum creatinine inversely related to GFR (doubling of creatinine = halving of GFR)"
    ]
  },
  {
    label: "Pathophysiology",
    bullets: [
      "Pre-renal AKI: reduced renal perfusion → compensatory mechanisms (RAAS activation → Na/water retention, ADH → water retention, sympathetic → afferent vasoconstriction) → initially maintain GFR; if severe/prolonged → ischaemic ATN",
      "Acute tubular necrosis (ATN): most common intrinsic cause; ischaemic or nephrotoxic; tubular epithelial cell death → loss of polarity → integrins exposed on apical surface → cell detachment → tubular casts obstructing lumen → back-leak of filtrate → oliguria; epithelial regeneration begins within 24–48 h (intrinsic stem cell repair)",
      "Hyperkalaemia mechanism in AKI: reduced GFR → reduced tubular flow → reduced K+ secretion; metabolic acidosis → K+ shifts out of cells (H+ enters cells, K+ exits to maintain electroneutrality); oliguria prevents normal K+ excretion → rapidly life-threatening",
      "Contrast nephropathy: iodinated contrast → direct tubular toxicity + renal vasoconstriction (endothelin, adenosine) + ROS generation; risk factors — CKD, DM, heart failure, high contrast volume, dehydration; prevention — IV hydration (0.9% NaCl or NaHCO3) before and after, minimise contrast dose, stop nephrotoxins"
    ]
  },
  {
    label: "Pharmacology",
    bullets: [
      "Calcium gluconate (10 mL of 10% IV): raises extracellular Ca2+ → increases cardiac membrane threshold potential → stabilises against hyperkalaemia-induced arrhythmias; onset within 1–3 min; does not lower serum K+",
      "Insulin (10 units actrapid) + 50 mL 50% dextrose: insulin activates Na/K-ATPase and promotes K+ entry into cells; 50% dextrose prevents hypoglycaemia; lowers K+ by 0.5–1.0 mmol/L over 15–30 min",
      "Salbutamol (10–20 mg nebulised): beta-2 receptor activation → Na/K-ATPase stimulation → K+ into cells; additive with insulin; onset 15–30 min; tachycardia side effect",
      "Loop diuretics (furosemide): inhibit Na-K-2Cl cotransporter (NKCC2) in thick ascending limb → reduce medullary concentration gradient → reduce ADH effect → increase free water excretion; also increase K+ delivery to collecting duct → K+ excretion (useful in volume overload AKI)",
      "Sodium bicarbonate: raises blood pH → shifts K+ into cells (counters acidosis-driven hyperkalaemia); also corrects severe metabolic acidosis (pH <7.1)"
    ]
  }
]));

// ════════════════════════════════════════════════════════
content.push(h1("7. Infectious Diseases"));
// ════════════════════════════════════════════════════════

content.push(...block("7.1  Sepsis", [
  {
    label: "Microbiology Basis",
    bullets: [
      "Gram-positive cell wall: thick peptidoglycan + teichoic acid; no outer membrane; gram stain purple; LTA (lipoteichoic acid) is the PAMP; beta-lactams work well (access to PBPs without outer membrane barrier)",
      "Gram-negative cell wall: thin peptidoglycan + outer membrane containing LPS (lipopolysaccharide/endotoxin = most potent PAMP); outer membrane also functions as permeability barrier — reduces antibiotic penetration; LPS (specifically lipid A component) triggers TLR4",
      "Biofilm formation: Staphylococcus epidermidis, S. aureus, Pseudomonas — important in device infections (CVC, prosthetics, urinary catheters); biofilm provides physical protection from immune cells and antibiotics; most device infections require device removal",
      "Antibiotic resistance mechanisms: beta-lactamases (hydrolysis), ESBL (extended-spectrum beta-lactamases — Klebsiella, E. coli — resistant to 3rd gen cephalosporins), carbapenemases (KPC, NDM — resistant to carbapenems), efflux pumps (Pseudomonas — extrude multiple antibiotics), target modification (MRSA — mecA gene → altered PBP2a with low beta-lactam affinity)"
    ]
  },
  {
    label: "Immunopathophysiology",
    bullets: [
      "PRRs (pattern recognition receptors): TLR4 (LPS), TLR2 (LTA), NOD1/2 (intracellular peptidoglycan), NLRP3 inflammasome (activates IL-1beta) → NF-kB activation → cytokine gene transcription",
      "Systemic inflammatory response: TNF-alpha + IL-1 + IL-6 (pyrogenic cytokines) → fever, hepatic acute phase response (CRP, fibrinogen, complement), endothelial activation; IL-8 → neutrophil chemotaxis; IL-12 + IFN-gamma → macrophage activation",
      "Endothelial dysfunction in sepsis: cytokines + LPS → endothelial NO synthase (eNOS) overactivation → excess NO → profound vasodilation → distributive shock (warm peripheries, low SVR, high CO — early); also increased vascular permeability → capillary leak → interstitial oedema",
      "Coagulopathy/DIC: endothelial injury → tissue factor expression → extrinsic coagulation cascade; simultaneous fibrinolysis impairment (PAI-1 elevation); microthrombi → multi-organ dysfunction; thrombocytopaenia (platelet consumption in thrombi)",
      "Immunosuppressive phase (late sepsis): T-cell apoptosis, immunosuppressive cytokines (IL-10, TGF-beta) → anergy → risk of secondary opportunistic infections; explains why some sepsis patients deteriorate after initial improvement"
    ]
  },
  {
    label: "Pharmacology of Antibiotics and Vasopressors",
    bullets: [
      "Piperacillin-tazobactam: extended-spectrum penicillin (anti-Pseudomonal) + tazobactam (beta-lactamase inhibitor); covers gram-positive, gram-negative, and anaerobes — broad empirical sepsis coverage; time-dependent killing (keep concentration above MIC for >50% of dosing interval — extended infusion strategy)",
      "Meropenem (carbapenem): broadest-spectrum beta-lactam; stable to most beta-lactamases including ESBLs; reserved for documented MDR organisms; carbapenem stewardship essential to prevent KPC spread",
      "Vancomycin (glycopeptide): inhibits cell wall by binding D-Ala-D-Ala terminus of peptidoglycan precursors → prevents transpeptidase substrate binding; active against MRSA; VRE (vancomycin-resistant Enterococcus) — D-Ala-D-Lac substitution; TDM required (target AUC 400–600 mg.h/L)",
      "Noradrenaline (norepinephrine): alpha-1 (vasoconstriction — primary effect) + beta-1 (inotropy); first-line vasopressor in septic shock; increases SVR → raises MAP; preferred over dopamine (fewer arrhythmias — SOAP II trial)",
      "Vasopressin (ADH analogue): V1 receptor → vascular smooth muscle vasoconstriction (cAMP-independent); also V2 → renal water retention; added as vasopressor-sparing agent in refractory shock; does not increase HR (no adrenergic activity)"
    ]
  }
]));

// ════════════════════════════════════════════════════════
content.push(h1("8. Musculoskeletal Diseases"));
// ════════════════════════════════════════════════════════

content.push(...block("8.1  Rheumatoid Arthritis", [
  {
    label: "Immunology and Pathophysiology",
    bullets: [
      "Citrullination: peptidylarginine deiminase (PAD4) enzyme converts arginine → citrulline in proteins during inflammation or apoptosis; in genetically susceptible individuals (HLA-DRB1*04 — 'shared epitope') → auto-reactive T cells recognise citrullinated peptides (fibrinogen, vimentin, collagen II) → ACPA production",
      "ACPA and RF: anti-citrullinated protein antibodies (ACPA/anti-CCP) form immune complexes with citrullinated antigens → complement activation + FcgammaR activation on macrophages → synovial inflammation; rheumatoid factor = IgM against Fc portion of IgG",
      "Synovial pathology: T-cell (CD4+ Th1/Th17) infiltration → activate synovial fibroblasts (FLS) and macrophages → TNF-alpha, IL-1, IL-6, IL-17 production → synovial hyperplasia (pannus) + osteoclast activation (RANK-L from FLS → RANK on osteoclasts → bone erosion) + cartilage degradation (MMPs)",
      "TNF-alpha: master cytokine in RA; activates NF-kB in FLS → perpetuates inflammation; also increases VEGF → angiogenesis (explains synovial vascularity); TNF drives systemic features (cachexia, anaemia of chronic disease via hepcidin upregulation, cardiovascular risk)"
    ]
  },
  {
    label: "Pharmacology of DMARDs",
    bullets: [
      "Methotrexate (anchor DMARD): folate antagonist — inhibits DHFR (dihydrofolate reductase) → reduced tetrahydrofolate → impaired purine/thymidine synthesis → reduced T/B cell proliferation; also adenosine release → anti-inflammatory; weekly dosing (avoids folate toxicity by allowing recovery); folic acid 5 mg once weekly co-prescribed (reduces side effects without reducing efficacy)",
      "Hydroxychloroquine: inhibits lysosomal acidification → prevents antigen presentation (Toll-like receptor signalling) → reduces cytokine production; also blocks NLRP3 inflammasome; retinopathy risk with long-term use (accumulates in melanin-containing tissues)",
      "TNF inhibitors (adalimumab — fully human mAb; etanercept — soluble TNF receptor fusion protein; infliximab — chimeric mAb): bind and neutralise TNF-alpha; increase risk of reactivation of latent TB (TNF essential for granuloma maintenance) → mandatory TB screening (IGRA/Mantoux) before initiation",
      "Tocilizumab (IL-6 receptor antagonist): blocks IL-6 signalling (JAK-STAT3 pathway) → reduces acute phase response (CRP may normalise → masks infection signs — important clinical caveat); also used in COVID cytokine storm",
      "JAK inhibitors (tofacitinib — JAK1/3; baricitinib — JAK1/2; upadacitinib — JAK1): inhibit intracellular JAK-STAT signalling → block multiple cytokine receptors simultaneously (IL-6, IL-2, IFN-gamma, etc.); oral administration; DVT/PE risk — post-marketing safety concern (particularly in high CV-risk patients)"
    ]
  }
]));

content.push(...block("8.2  Osteoporosis", [
  {
    label: "Bone Biology Basis",
    bullets: [
      "Bone remodelling: continuous coupled process — osteoclasts (bone resorption) and osteoblasts (bone formation); RANK-L (on osteoblasts/stromal cells) binds RANK (on osteoclast precursors) → osteoclast differentiation and activation; osteoprotegerin (OPG, from osteoblasts) is the decoy receptor for RANK-L → inhibits osteoclastogenesis",
      "Peak bone mass achieved at 25–30 years; influenced by genetics (60–80%), physical activity, calcium/vitamin D intake, sex hormones; after peak, bone remodelling becomes negative → age-related bone loss",
      "Post-menopausal osteoporosis: oestrogen deficiency → loss of OPG production → RANK-L/RANK signalling unopposed → increased osteoclast activity → rapid bone loss (2–3% per year in first 5 years post-menopause)",
      "Vitamin D physiology: skin (7-dehydrocholesterol + UV-B → cholecalciferol/D3) → liver 25-hydroxylation (25-OH-D3, major circulating form, measured for status) → kidney 1-alpha-hydroxylation (1,25-(OH)2D3 = calcitriol, active form); calcitriol binds VDR → increases intestinal Ca2+/Pi absorption, bone mineralisation, renal Ca2+ reabsorption"
    ]
  },
  {
    label: "Pharmacology",
    bullets: [
      "Alendronate (bisphosphonate — nitrogen-containing): R-C(OH)(PO3) 2- analogue of pyrophosphate → binds hydroxyapatite with high affinity at sites of bone resorption → osteoclasts ingest during resorption → inhibit farnesyl pyrophosphate synthase (mevalonate pathway) → prevent prenylation of Ras/Rho GTPases → osteoclast cytoskeletal disruption → apoptosis",
      "Denosumab: fully human IgG2 monoclonal antibody against RANK-L → mimics OPG → inhibits osteoclastogenesis; equally effective at non-skeletal RANK-L sites → immune suppression (caution in infections); rebound fractures on cessation (rapid bone loss due to synchronised osteoclast activation)",
      "Teriparatide (PTH 1-34 fragment, anabolic): intermittent PTH administration (pulsatile) paradoxically stimulates osteoblast activity > resorption (continuous PTH does the opposite — stimulates resorption); activates Wnt signalling → bone formation; max 2 years (osteosarcoma signal in rat studies)",
      "Calcium + Vitamin D: calcium directly required for hydroxyapatite mineralisation; vitamin D required for intestinal calcium absorption; colecalciferol (D3) preferred over ergocalciferol (D2) for supplementation; doses 800–1000 IU D3 daily"
    ]
  }
]));

// ════════════════════════════════════════════════════════
content.push(h1("9. Haematological Diseases"));
// ════════════════════════════════════════════════════════

content.push(...block("9.1  Anaemia", [
  {
    label: "Physiology Basis",
    bullets: [
      "Haemoglobin structure: 4 subunits (2 alpha + 2 beta in HbA); each subunit contains a haem group (protoporphyrin IX + Fe2+); O2 binds cooperatively (sigmoidal dissociation curve) — haem-haem interaction (conformational change: T-state → R-state with each O2 binding)",
      "O2 dissociation curve shifts: Right shift (increased O2 delivery to tissues) — increased CO2 (Bohr effect), increased temperature, increased 2,3-BPG, acidosis; Left shift (increased O2 affinity, decreased delivery) — decreased CO2, alkalosis, decreased 2,3-BPG, HbF, methaemoglobin",
      "Erythropoiesis regulation: EPO (erythropoietin, produced by renal interstitial cells in response to hypoxia via HIF-1alpha/HIF-2alpha) → stimulates BFU-E/CFU-E differentiation; iron (Fe2+) required for haem synthesis; vitamin B12 and folate required for DNA synthesis (nuclear maturation)",
      "Iron metabolism: absorbed as haem iron (highly bioavailable) or non-haem Fe3+ (reduced to Fe2+ by duodenal cytochrome B — DcytB; enters enterocyte via DMT1); exported via ferroportin; bound to transferrin in blood (normal transferrin saturation 20–45%); stored as ferritin (intracellular) and haemosiderin; hepcidin (liver) inhibits ferroportin → reduces iron export → functional iron deficiency in inflammation (anaemia of chronic disease mechanism)"
    ]
  },
  {
    label: "Pathophysiology of Key Types",
    bullets: [
      "Iron deficiency anaemia (IDA): depleted stores → reduced haem synthesis → reduced Hb → microcytic hypochromic RBCs (small cells with low Hb content); also affects non-haematological iron-dependent enzymes (cytochrome c, myoglobin) → fatigue, impaired cognitive function, koilonychia (structural protein synthesis impaired)",
      "Megaloblastic anaemia (B12/Folate deficiency): impaired thymidylate synthesis → reduced DNA synthesis → nuclei fail to mature while cytoplasm continues to grow → megaloblasts in marrow; ineffective erythropoiesis + intramedullary haemolysis → raised LDH, raised unconjugated bilirubin, low haptoglobin; hypersegmented neutrophils (5+ lobes) is early peripheral blood marker",
      "B12 deficiency subacute combined degeneration: B12 required for methionine synthase (homocysteine → methionine → SAM — methyl donor for myelin proteins) + methylmalonyl-CoA mutase (methylmalonate → succinyl-CoA for fatty acid metabolism); deficiency → abnormal myelin lipid synthesis → demyelination of posterior (dorsal columns — vibration/proprioception loss) and lateral (corticospinal tracts — UMN signs) columns",
      "Anaemia of chronic disease (ACD): IL-6 → hepatic hepcidin production → ferroportin degradation → iron trapped in macrophages/hepatocytes → reduced iron availability for erythropoiesis despite adequate stores; EPO response is also blunted; serum iron low, TIBC low/normal, ferritin normal/high — distinguishes from IDA (low iron, high TIBC, low ferritin)"
    ]
  },
  {
    label: "Pharmacology",
    bullets: [
      "Ferrous sulphate (Fe2+): oral iron; absorbed in duodenum; taken with vitamin C (ascorbic acid reduces Fe3+ to Fe2+, prevents oxidation in alkaline environment); side effects — constipation (direct GI effect), dark stools; take 30 min before food for maximum absorption; reticulocytosis expected at 5–7 days if responding",
      "IV iron (ferric carboxymaltose, iron sucrose): avoids GI side effects; useful in malabsorption, non-compliance, pre-operatively, IBD; risk of anaphylaxis (especially iron dextran — less with newer formulations); small iron particle surrounded by carbohydrate shell — released slowly from RES macrophages",
      "Hydroxocobalamin (B12 IM): cyanocobalamin converted to active cobalamin forms (methylcobalamin, adenosylcobalamin) in vivo; IM route bypasses intrinsic factor requirement; given as loading regimen then 3-monthly maintenance in pernicious anaemia",
      "Folic acid: converted to active THF (tetrahydrofolate) by DHFR; supplement before conception/in pregnancy (neural tube defect prevention — requires folate for neural tube closure at day 26–28 post-conception)"
    ]
  }
]));

// ════════════════════════════════════════════════════════
content.push(h1("10. Geriatric Pharmacology — Basic Sciences of Prescribing in the Elderly"));
// ════════════════════════════════════════════════════════

content.push(...block("10.1  Pharmacokinetic Changes in Ageing", [
  {
    label: "Absorption",
    bullets: [
      "Reduced gastric acid secretion (achlorhydria) → delayed dissolution of enteric-coated tablets and pH-dependent drugs; gastric motility reduced → delayed absorption (may extend time to peak rather than reduce bioavailability)",
      "Reduced first-pass metabolism (hepatic blood flow and enzyme activity decline) → increased bioavailability of high extraction drugs (morphine, propranolol, nitrates, lidocaine) → lower starting doses required"
    ]
  },
  {
    label: "Distribution",
    bullets: [
      "Reduced total body water (-15%) + lean body mass → increased Vd for lipid-soluble drugs (benzodiazepines, barbiturates) → prolonged duration of action; increased fat:lean ratio → accumulation of fat-soluble drugs",
      "Reduced serum albumin (malnutrition, chronic illness) → increased free fraction of highly protein-bound drugs (warfarin, phenytoin, NSAIDs) → increased pharmacodynamic effect at standard doses"
    ]
  },
  {
    label: "Metabolism",
    bullets: [
      "Hepatic blood flow reduces 40% with age → reduced clearance of high-extraction drugs; hepatic mass and CYP enzyme content (CYP3A4, CYP2D6) decline → reduced phase I metabolism (oxidation, reduction, hydrolysis)",
      "Phase II metabolism (glucuronidation, sulphation) relatively preserved in normal ageing — lorazepam, oxazepam, temazepam preferred benzodiazepines as they undergo only glucuronidation (not dependent on CYP enzymes — 'LOT rule')"
    ]
  },
  {
    label: "Excretion",
    bullets: [
      "GFR declines ~1 mL/min per year after age 40 — by age 80, GFR typically 40–60% of young adult; muscle mass decreases → serum creatinine may remain 'normal' despite significant GFR reduction; use CKD-EPI or Cockcroft-Gault equation for dose adjustment",
      "Drugs requiring dose reduction in elderly (renally cleared): metformin, methotrexate, digoxin, LMWH, DOACS, aminoglycosides, acyclovir, allopurinol — regular renal function monitoring mandatory"
    ]
  }
]));

content.push(...block("10.2  Pharmacodynamic Changes and Polypharmacy", [
  {
    label: "Receptor and Target Sensitivity Changes",
    bullets: [
      "CNS: increased sensitivity to sedatives/opioids/benzodiazepines (reduced GABA receptor reserve, reduced cholinergic/dopaminergic tone); increased delirium risk with anticholinergic drugs (reduced ACh in already-reduced cholinergic neurotransmission)",
      "Cardiovascular: reduced baroreceptor reflex sensitivity → orthostatic hypotension with antihypertensives, diuretics, alpha-blockers; reduced cardiac beta-adrenoceptor density → attenuated HR response to beta-agonists/antagonists",
      "Anticholinergic burden: accumulative anticholinergic effects of multiple drugs (antihistamines, TCAs, bladder agents, antipsychotics, antispasmodics) → cognitive impairment, urinary retention, constipation, blurred vision; Anticholinergic Burden Scale used to quantify",
      "STOPP/START criteria: validated tool for identifying inappropriate prescribing in elderly (STOPP = medications to stop; START = medications to start); Beers criteria (USA) serve same purpose"
    ]
  },
  {
    label: "Clinically Relevant Drug Interactions in Elderly",
    bullets: [
      "Warfarin + antibiotics: many antibiotics (metronidazole, fluoroquinolones, clarithromycin) inhibit CYP2C9 → reduced warfarin clearance → elevated INR → bleeding risk; also antibiotics reduce gut flora → less vitamin K production",
      "ACE inhibitor + NSAID + diuretic (Triple Whammy): all three drugs together reduce renal perfusion → markedly increased AKI risk; NSAIDs reduce renal PG synthesis (afferent vasodilation) + ACE inhibitor removes efferent constriction + diuretic reduces volume → synergistic GFR reduction",
      "Digoxin toxicity: narrow therapeutic index; amiodarone, clarithromycin, verapamil, diltiazem all increase digoxin levels (inhibit P-glycoprotein — renal tubular secretion transporter); hypokalaemia (from diuretics) increases digoxin toxicity even at therapeutic levels (K+ and digoxin compete for Na/K-ATPase binding site)",
      "Serotonin syndrome risk: SSRIs + tramadol (weak serotonin reuptake inhibitor + opioid agonist) + triptans + MAOIs — excess serotonergic activity → triad of altered mental status + autonomic instability + neuromuscular abnormalities (clonus, hyperreflexia)"
    ]
  }
]));

// ── Build doc ─────────────────────────────────────────────────────────────────
const doc = new Document({
  numbering: {
    config: [{
      reference: "bullets",
      levels: [{
        level: 0,
        format: LevelFormat.BULLET,
        text: "\u2022",
        alignment: AlignmentType.LEFT,
        style: { paragraph: { indent: { left: 720, hanging: 360 } } }
      }]
    }]
  },
  styles: {
    default: { document: { run: { font: "Arial", size: 22 } } }
  },
  sections: [{ children: content }]
});

Packer.toBuffer(doc).then(buf => {
  fs.writeFileSync("/home/daytona/workspace/elog/B_Basic_Sciences_Applied.docx", buf);
  console.log("DONE");
});
Running Command

cd /home/daytona/workspace/elog && node generate_B_basic_sciences.js 2>&1

Running Command

cp /home/daytona/workspace/elog/B_Basic_Sciences_Applied.docx /tmp/B_basic.docx && soffice --headless --convert-to pdf --outdir /tmp/ /tmp/B_basic.docx 2>&1 && ls -lh /tmp/B_basic.pdf

Running Command

cp /tmp/B_basic.pdf /home/daytona/workspace/elog/B_Basic_Sciences_Applied.pdf && ls -lh /home/daytona/workspace/elog/

Both files are ready. Download here:
  • B Basic Sciences Applied

    Word Document · DOCX

    (Word, 33 KB)
  • B Basic Sciences Applied

    PDF Document · PDF

    (PDF, 241 KB)

What's inside — structured exactly like your reference PDFs

Plain title at top, short introduction, then numbered sections with bold labels and bullets. No page breaks, no colours.
SectionBasic Science Applied
1. CardiovascularCoronary anatomy → ECG localisation; Physiology of O2 demand; Plaque rupture & ischaemic cascade; Cardiac biomarker biochemistry; Pharmacology of antiplatelet/ACEi/statins/heparin
2. RespiratoryGram stain microbiology of CAP pathogens; Immune response & consolidation mechanism; Antibiotic mechanisms (penicillin/macrolide/fluoroquinolone); COPD surfactant physiology; Protease-antiprotease imbalance; Bronchodilator receptor pharmacology
3. GI/LiverGastric mucosal defence physiology; H. pylori virulence; PPI/H2-blocker mechanisms; Bilirubin metabolism & jaundice types; Portal hypertension pathophysiology; Terlipressin/lactulose/rifaximin pharmacology
4. NeurologyCircle of Willis anatomy; Penumbra concept; Glutamate excitotoxicity; Basal ganglia dopamine circuit; Alpha-synuclein pathology; Levodopa/MAO-B/COMT pharmacology
5. EndocrineInsulin signalling (IRS-1/PI3K/Akt); AGE formation & HbA1c; Diabetic nephropathy pathophysiology; HPT axis & T3/T4 conversion; Hashimoto's immunopathology; SGLT2i/GLP-1/Metformin mechanisms
6. RenalGFR regulation (PG/Ang II balance); ATN pathology & repair; Hyperkalaemia mechanism; Contrast nephropathy; Calcium gluconate/insulin/furosemide pharmacology
7. SepsisGram+/Gram- cell wall & PAMP recognition; TLR4-NF-kB-cytokine cascade; NO-mediated distributive shock; DIC mechanism; Vancomycin/piperacillin/noradrenaline pharmacology
8. MSKRANK-L/OPG osteoclast biology; ACPA/RF immunopathology; TNF-alpha in synovitis; Bisphosphonate/denosumab/teriparatide mechanisms; Methotrexate/JAK inhibitor pharmacology
9. HaematologyHb O2 dissociation curve; Iron metabolism (DMT1/ferroportin/hepcidin); Megaloblastic anaemia (DHFR/DNA synthesis); B12 subacute combined degeneration; Ferrous sulphate/IV iron/B12 pharmacology
10. Geriatric PharmacologyADME changes with ageing; Reduced albumin & free drug fraction; LOT rule for benzodiazepines; Triple whammy (ACEi+NSAID+diuretic); Digoxin toxicity mechanisms; Serotonin syndrome; STOPP/START criteria

C - Describe the investigations to be undertaken at various levels like OPD, Ward, ICU etc. and choose them appropriately depending on the clinical features and epidemiologic principles. Make docs do not mention elog book reference

Running Command

python3 -c " import pdfplumber path = '/home/daytona/workspace/attachments/b7ea4a55-97e9-43e4-a53c-c2a4eecb96d8/e-log%20book%20c-3%20.pdf.pdf' with pdfplumber.open(path) as pdf: for i, page in enumerate(pdf.pages): print(f'--- PAGE {i+1} ---') print(page.extract_text()) print() " 2>&1

Writing File

~/elog/gen_C_investigations.js

const {
  Document, Packer, Paragraph, TextRun,
  AlignmentType, LevelFormat, BorderStyle, WidthType,
  Table, TableRow, TableCell, VerticalAlign
} = require('docx');
const fs = require('fs');

// ── Helpers — plain style matching reference PDFs ────────────────────────────
function title(text) {
  return new Paragraph({
    children: [new TextRun({ text, bold: true, size: 30, font: "Arial" })],
    spacing: { before: 0, after: 200 }
  });
}
function introP(text) {
  return new Paragraph({
    children: [new TextRun({ text, font: "Arial", size: 22 })],
    spacing: { after: 180 }
  });
}
function h1(text) {
  return new Paragraph({
    children: [new TextRun({ text, bold: true, size: 26, font: "Arial" })],
    spacing: { before: 280, after: 100 }
  });
}
function h2(text) {
  return new Paragraph({
    children: [new TextRun({ text, bold: true, size: 24, font: "Arial" })],
    spacing: { before: 200, after: 80 }
  });
}
function h3(text) {
  return new Paragraph({
    children: [new TextRun({ text, bold: true, size: 22, font: "Arial" })],
    spacing: { before: 160, after: 60 }
  });
}
function label(text) {
  return new Paragraph({
    children: [new TextRun({ text: text + ":", bold: true, font: "Arial", size: 22 })],
    spacing: { before: 120, after: 40 }
  });
}
function bullet(text) {
  const parts = [];
  const segs = text.split(/(\*\*[^*]+\*\*)/);
  for (const s of segs) {
    if (s.startsWith("**") && s.endsWith("**"))
      parts.push(new TextRun({ text: s.slice(2,-2), bold: true, font: "Arial", size: 22 }));
    else
      parts.push(new TextRun({ text: s, font: "Arial", size: 22 }));
  }
  return new Paragraph({
    numbering: { reference: "bullets", level: 0 },
    children: parts,
    spacing: { after: 60 }
  });
}
function numberedItem(n, text) {
  return new Paragraph({
    children: [new TextRun({ text: n + ". " + text, font: "Arial", size: 22 })],
    indent: { left: 360 },
    spacing: { after: 60 }
  });
}
function sp() {
  return new Paragraph({ children: [new TextRun("")], spacing: { after: 80 } });
}
function docBox(text) {
  // Italic indented documentation snippet (matching reference style)
  return new Paragraph({
    children: [new TextRun({ text: '"' + text + '"', font: "Arial", size: 22, italics: true })],
    indent: { left: 720 },
    spacing: { before: 80, after: 120 },
    border: { left: { style: BorderStyle.SINGLE, size: 6, color: "888888", space: 12 } }
  });
}

// Simple inline table (for reference summary tables)
function simpleTable(rows) {
  const thinBorder = { style: BorderStyle.SINGLE, size: 4, color: "AAAAAA" };
  return new Table({
    width: { size: 100, type: WidthType.PERCENTAGE },
    borders: { top: thinBorder, bottom: thinBorder, left: thinBorder, right: thinBorder, insideH: thinBorder, insideV: thinBorder },
    rows: rows.map((cells, ri) => new TableRow({
      tableHeader: ri === 0,
      children: cells.map((cell, ci) => new TableCell({
        width: { size: Math.floor(100/cells.length), type: WidthType.PERCENTAGE },
        verticalAlign: VerticalAlign.TOP,
        children: [new Paragraph({
          children: [new TextRun({ text: cell, font: "Arial", size: ri===0 ? 20 : 18, bold: ri===0 })],
          spacing: { before: 60, after: 60 }
        })]
      }))
    }))
  });
}

// ════════════════════════════════════════════════════════════════════════════
// DOCUMENT CONTENT
// ════════════════════════════════════════════════════════════════════════════
const C = [];

// ── TITLE & INTRO ────────────────────────────────────────────────────────────
C.push(title("Investigations at Various Clinical Levels — OPD, Ward, and ICU"));
C.push(introP(
  "Choosing the right investigation at the right clinical level is as important as making the correct diagnosis. " +
  "Over-investigating wastes resources and exposes patients to harm; under-investigating delays diagnosis. " +
  "The selection of investigations must be guided by three principles working together: the clinical features " +
  "of the presenting illness, the setting and acuity of the patient, and the epidemiological context — " +
  "including local disease prevalence, seasonal patterns, outbreak status, and population-level risk factors. " +
  "This document outlines a structured, level-appropriate approach to investigation across common disease groups."
));

// ════════════════════════════════════════════════════════
C.push(h1("1. Core Principles That Drive Investigation Choice"));
// ════════════════════════════════════════════════════════

C.push(label("Pre-test Probability and Bayes' Theorem"));
C.push(...[
  "The likelihood of a disease before testing determines how useful any test result will be. A positive test in a low-prevalence population is more likely to be a false positive (low positive predictive value); a negative test in a high-prevalence population may be a false negative.",
  "Order high-yield tests first and avoid shotgun panels. In a 60-year-old smoker with haemoptysis, CXR and sputum cytology have high pre-test probability for lung cancer — order them before expensive CT.",
  "Clinical scoring tools (CURB-65, qSOFA, Wells score, GRACE, NIHSS) formalise pre-test probability and directly determine which investigations are needed and at what urgency.",
].map(t => bullet(t)));

C.push(label("Sensitivity vs. Specificity"));
C.push(...[
  "**High-sensitivity tests** (few false negatives) are used to rule OUT a disease. Example: D-dimer to exclude PE (high sensitivity ~95%); a negative D-dimer in low-probability Wells score reliably rules out PE without CT-PA.",
  "**High-specificity tests** (few false positives) are used to rule IN a disease. Example: Anti-CCP antibody for rheumatoid arthritis (specificity >95%); troponin is highly specific for myocardial injury.",
  "As clinical acuity increases, shift from screening (sensitive) to confirmatory (specific) tests.",
].map(t => bullet(t)));

C.push(label("Epidemiological Context"));
C.push(...[
  "**Prevalence-driven testing:** In tropical and subtropical regions, add dengue NS1 antigen, malaria RDT/thick film, and typhoid antigen (Widal/blood culture) to the fever workup — these have near-zero relevance in temperate climates.",
  "**Seasonality:** Influenza PCR in winter; leptospirosis serology during monsoon (post-flooding); meningococcal PCR during 'meningitis belt' season (Sub-Saharan Africa, dry season).",
  "**Outbreak status:** During a declared outbreak (COVID-19, cholera, mpox), specific rapid tests move to the top of the investigation list regardless of clinical severity.",
  "**Population risk factors:** HIV testing should be routine in all febrile admissions in high-prevalence settings; TB screening must be added to any chronic cough workup in high-burden countries.",
  "**Occupational and travel history:** Brucellosis serology in farmers/abattoir workers with fever; histoplasma/coccidioides serology in travellers returning from endemic regions; Q fever (Coxiella burnetti) in veterinarians.",
].map(t => bullet(t)));

C.push(label("Resource Stewardship and Cost-Effectiveness"));
C.push(...[
  "Do the cheapest test that answers the clinical question. A plain chest X-ray answers 'is there consolidation?' adequately in most CAP cases; HRCT chest is not a first-line investigation.",
  "Point-of-care tests (POC) — bedside glucometer, urine dipstick, malaria RDT — offer rapid results in OPD without laboratory infrastructure.",
  "Reserve costly/invasive tests (MRI, CTPA, coronary angiography, bronchoscopy) for situations where the result will change management.",
].map(t => bullet(t)));

C.push(label("Turn-Around Time (TAT) and Clinical Urgency"));
C.push(...[
  "**STAT:** For life-threatening decisions — ABG in respiratory failure, ECG in chest pain, bedside glucose in altered consciousness. Results needed in minutes.",
  "**Urgent (within 1–4 h):** Blood cultures before antibiotics, troponin at 0 and 3 h, D-dimer in suspected PE, lumbar puncture in suspected meningitis.",
  "**Routine (within 24 h):** Thyroid function, lipid profile, HbA1c, liver screen — outpatient monitoring and non-urgent diagnoses.",
  "The higher the acuity, the shorter the acceptable TAT.",
].map(t => bullet(t)));

C.push(label("Serial Monitoring vs. Single Snapshot"));
C.push(...[
  "Dynamic diseases require trending investigations, not isolated results. A single lactate of 2.5 mmol/L is less informative than a lactate falling from 4.0 → 2.5 → 1.5 mmol/L over 6 hours (confirms resuscitation response).",
  "Examples: serial troponin for ACS (0 h, 1 h, 3 h), serial ABGs in COPD exacerbation/ARDS, serial creatinine in AKI, serial INR in warfarin reversal.",
  "In ICU, parameters that guide immediate management (ABG, lactate, K+) must be repeated at defined intervals rather than only when the clinical team remembers.",
].map(t => bullet(t)));

C.push(label("Infection Control Considerations"));
C.push(...[
  "Aerosol-generating procedures (bronchoscopy, sputum induction, BAL) require negative-pressure rooms and full PPE — this changes when and where the test can be done.",
  "GeneXpert MTB/RIF (CBNAAT) for TB: can be performed in a standard lab setting without culture infrastructure; preferable to smear microscopy for sensitivity and rifampicin resistance detection.",
  "Suspected haemorrhagic fever (Ebola, Lassa, Marburg): strict isolation first; all investigations done at bedside — do not send patient to radiology.",
].map(t => bullet(t)));
C.push(sp());

// ════════════════════════════════════════════════════════
C.push(h1("2. General Workflow for Investigation Selection"));
// ════════════════════════════════════════════════════════

C.push(...[
  numberedItem(1, "Clinical Assessment: History → Physical examination → Differential diagnosis list (ranked by probability and danger)"),
  numberedItem(2, "Define Setting and Acuity: OPD (ambulatory, low acuity) → General Ward (moderate, requiring admission) → ICU (critical, organ support)"),
  numberedItem(3, "Prioritise the Goal: Diagnose? Rule out dangerous diagnosis? Risk-stratify? Monitor therapy? Identify complications?"),
  numberedItem(4, "Apply Epidemiological Filter: What is the patient's background — geography, season, occupation, immune status, travel, exposure?"),
  numberedItem(5, "Select Tests Logically: Basic → Focused → Advanced. Do not skip to advanced tests before basic ones have been interpreted."),
  numberedItem(6, "Document Rationale: For every test ordered, record: date/time, provisional diagnosis, test priority, reason ordered, result, interpretation, and next action."),
]);
C.push(sp());

// ════════════════════════════════════════════════════════
C.push(h1("3. Setting-Wise Investigation Framework"));
// ════════════════════════════════════════════════════════

C.push(h2("3.1  Out-Patient Department (OPD)"));
C.push(introP("Goal: Rapid triage, rule-in common diagnoses, avoid over-testing. The OPD is for ambulatory patients who are stable. Investigations should answer a specific clinical question, generate a result quickly, and guide whether to treat, watch, or admit."));

C.push(label("Standard Baseline Panel (OPD)"));
C.push(...[
  "CBC (complete blood count) with differential: anaemia, leukocytosis/leukopenia, thrombocytopaenia — first-line screen for infection, haematological disorders, inflammatory states",
  "ESR and CRP: inflammatory markers; CRP rises and falls faster than ESR — useful for acute-on-chronic conditions",
  "Urinalysis and microscopy (R/M): UTI (nitrites, leukocytes, casts), diabetes (glycosuria, ketonuria), renal disease (proteinuria, haematuria)",
  "Fasting plasma glucose + HbA1c: if metabolic symptoms (polyuria, polydipsia, weight loss) or incidental hyperglycaemia",
  "Basic metabolic panel (BMP): urea, creatinine, sodium, potassium, bicarbonate — if on diuretics, ACE inhibitors, or suspected renal/electrolyte disorder",
  "ECG: all patients with chest pain, palpitations, syncope, dyspnoea, or age >40 with cardiovascular risk factors",
  "Chest X-ray: cough >3 weeks, haemoptysis, dyspnoea, suspected pneumonia or TB, heart failure",
  "Ultrasound abdomen/pelvis: abdominal pain, hepatomegaly, splenomegaly, pelvic pain — better tolerated than CT, no radiation",
].map(t => bullet(t)));

C.push(label("Point-of-Care Tests at OPD Level"));
C.push(...[
  "Capillary blood glucose (glucometer): altered consciousness, known DM, first visit metabolic screening",
  "Urine pregnancy test (beta-hCG): any woman of reproductive age with abdominal pain, vomiting, or missed period before X-ray or drug prescription",
  "Rapid malaria test (RDT — HRP-2/pLDH): fever + headache + myalgia in endemic/tropical region; sensitivity ~95% for P. falciparum",
  "Dengue NS1 antigen (Day 1–5 of fever): fever + retroorbital pain + myalgia + rash in dengue-endemic zone; pair with dengue IgM/IgG after Day 5",
  "Pulse oximetry (SpO2): dyspnoea, wheeze, any respiratory complaint — SpO2 <94% triggers further workup and possible admission",
  "Urine dipstick: UTI, haematuria, proteinuria — immediate result, guides culture decision",
  "Rapid streptococcal antigen test (throat): pharyngitis with tonsillar exudate, fever, no cough — guides antibiotic prescription vs. watchful waiting",
].map(t => bullet(t)));

C.push(label("OPD Red Flag Triggers for Immediate Escalation"));
C.push(...[
  "**Haemoptysis + pallor + weight loss:** CBC + CXR + sputum AFB/cytology → urgent referral for bronchoscopy; do not discharge without result",
  "**Chest pain + diaphoresis:** ECG within 10 minutes + Troponin (0 h); if STEMI or NSTEMI pattern → direct catheterisation lab/ED referral",
  "**Sudden severe headache ('thunderclap'):** Do not perform LP in OPD; urgent CT head → neurosurgical referral if SAH suspected",
  "**SpO2 <90% at rest:** Do not manage as OPD; arterial blood gas + urgent admission",
  "**Altered consciousness/confusion:** Blood glucose immediately; CBC, metabolic panel; CT head if focal signs; admit",
].map(t => bullet(t)));

C.push(docBox("OPD 14/06/26 1100h — 58 y female, 3-week productive cough, low-grade fever, night sweats, 4 kg weight loss. Ordered: CBC (Hb 10.2, WBC 11k), CXR (right upper lobe infiltrate with cavity), sputum AFB x3 (smear-positive). Epidemiology: high TB burden area, returned from rural district. Rationale: weight loss + upper lobe cavity = TB until proven otherwise. Sent GeneXpert MTB/RIF — Rifampicin-sensitive TB confirmed. Notified to TB programme; started RHEZ."));
C.push(sp());

C.push(h2("3.2  General Ward"));
C.push(introP("Goal: Confirm diagnosis, initiate definitive therapy, monitor for deterioration, identify complications. Ward patients are admitted because they are too unwell for OPD management or require IV therapy, monitoring, or further investigations not available in OPD."));

C.push(label("Baseline Extensions on Ward Admission"));
C.push(...[
  "Comprehensive metabolic panel (CMP): LFTs (ALT, AST, ALP, GGT, bilirubin, albumin), bone profile (calcium, phosphate, ALP), urate, LDH — baseline before starting medications, identify organ involvement",
  "Coagulation profile (INR, aPTT, fibrinogen): any patient with bleeding, jaundice, severe sepsis, or before invasive procedures",
  "Blood cultures x2 (from separate peripheral sites, before first antibiotic dose): any suspected infection with systemic features; urine culture simultaneously if urinary source suspected",
  "Thyroid function (TSH, free T4): unexplained tachycardia, weight change, AF, altered mental status in elderly",
  "Cardiac biomarkers: Troponin I/T (serial at 0, 1, 3 h) for chest pain; NT-proBNP/BNP for dyspnoea/oedema to differentiate cardiac from respiratory cause",
  "D-dimer: suspected VTE (DVT/PE) — use only if Wells score indicates low-intermediate probability; high pre-test probability → go directly to imaging",
  "Iron studies + reticulocyte count: anaemia workup — iron deficiency vs. chronic disease vs. haemolysis",
  "Autoimmune screen (ANA, ANCA, anti-dsDNA, complement C3/C4): if systemic inflammatory disease suspected (multi-system involvement, young patient, rashes, arthritis)",
].map(t => bullet(t)));

C.push(label("Radiology and Procedural Investigations on Ward"));
C.push(...[
  "CT brain (non-contrast): stroke (haemorrhage exclusion before thrombolysis), new confusion/focal neurology, head trauma, raised ICP — not a routine fever workup test",
  "CT chest: inconclusive CXR, suspected pulmonary embolism (CTPA with contrast), lung malignancy staging, empyema characterisation",
  "CT abdomen/pelvis with contrast: acute abdomen, suspected intra-abdominal collection/abscess, bowel obstruction, pancreatitis staging (Balthazar score)",
  "Echocardiography: new murmur (infective endocarditis), decompensated heart failure (EF, valves, wall motion), pericardial effusion, shock of unknown cause",
  "Doppler ultrasound of leg veins: DVT workup when Wells score ≥2 or clinical suspicion",
  "Upper endoscopy (OGD): upper GI bleeding, dysphagia, refractory dyspepsia, suspected ulceration — within 24 hours for active bleed",
  "Lumbar puncture: suspected meningitis/encephalitis (after CT brain excludes raised ICP), CNS lymphoma, subarachnoid haemorrhage (after CT-negative), Guillain-Barre (elevated CSF protein without pleocytosis)",
  "Ascitic tap (diagnostic): new ascites or decompensated cirrhosis — cell count, albumin, culture; SAAG >11 g/L confirms portal hypertension",
].map(t => bullet(t)));

C.push(label("Monitoring Investigations on Ward"));
C.push(...[
  "Daily: CBC, CMP, creatinine for most acute medical admissions (sepsis, AKI, post-procedure, on IV antibiotics)",
  "48–72 hourly: repeat cultures if fever persists despite antibiotics; repeat imaging if no clinical improvement",
  "Strict input/output charting + daily weight: essential in heart failure, AKI, cirrhosis with ascites — guides diuretic therapy",
  "Drug-level monitoring: vancomycin (trough or AUC-guided), aminoglycosides (peak and trough), digoxin (8 h post-dose), phenytoin, cyclosporine — when on narrow therapeutic index drugs",
  "Repeat coagulation profile: every 12–24 h in DIC, liver failure, on anticoagulation infusion",
].map(t => bullet(t)));

C.push(docBox("Ward 15/06/26 0800h — 72 y male, 3-day history of confusion + productive cough + low-grade fever. CURB-65 = 3 (confusion + urea 9.2 + age). Ordered: CBC (WBC 18k, neutrophilia), CRP (214), CXR (right lower lobe consolidation), blood cultures x2 before antibiotics, sputum Gram stain/culture, Legionella urinary antigen, pneumococcal urinary antigen, ABG (pH 7.34, PaO2 68 mmHg on air). Rationale: CURB-65 ≥2 = high severity CAP, elderly confused patient needs full sepsis screen. Started IV co-amoxiclav + Clarithromycin. Legionella antigen returned positive on Day 2 → changed to IV Levofloxacin monotherapy."));
C.push(sp());

C.push(h2("3.3  Intensive Care Unit (ICU)"));
C.push(introP("Goal: Rapid organ-function diagnostics, real-time haemodynamic and metabolic monitoring, early complication detection, and organ-support guidance. Every investigation in ICU must have an immediate management implication. Blanket ordering without rationale is waste and noise."));

C.push(label("Immediate Investigations on ICU Admission (within 15–30 minutes)"));
C.push(...[
  "**Point-of-care ABG + lactate:** pH, PaO2, PaCO2, HCO3, base excess, Na, K, glucose, haemoglobin — most information-dense single test in critical care; lactate >2 mmol/L signals hypoperfusion; lactate >4 mmol/L = severe shock requiring immediate action",
  "**ECG (12-lead):** Arrhythmias, STEMI/NSTEMI, right heart strain (PE), electrolyte effects (hyperkalaemia peaked T waves; hypokalaemia U waves)",
  "**Bedside glucometer:** Hypoglycaemia in altered consciousness — treat before any other investigation",
  "**Portable chest X-ray:** Lung pathology (consolidation, pneumothorax, ARDS pattern), endotracheal tube position (should be 2–3 cm above carina), CVC tip position (SVC/RA junction), pleural effusion",
  "**Bedside ultrasound (POCUS — point-of-care):** Cardiac (global LV function, effusion, tamponade, RV dilation in PE), lung (B-lines = pulmonary oedema, consolidation, pneumothorax — sliding sign absent), abdomen (free fluid — FAST scan), IVC (collapsibility = volume responsiveness)",
  "**Ketone strip (bedside):** Any diabetic or alcoholic patient — hyperketonaemia confirms DKA/AKA before formal metabolic results available",
].map(t => bullet(t)));

C.push(label("Daily/Twice-Daily ICU Investigations"));
C.push(...[
  "CBC with differential: haemoglobin (guide transfusion decisions, target Hb 70–90 g/L in most ICU patients), WBC trajectory (rising suggests secondary infection, falling may reflect bone marrow suppression), platelet count (DIC, HIT — heparin-induced thrombocytopaenia if >50% fall)",
  "Comprehensive metabolic panel (CMP) with magnesium and phosphate: electrolyte correction is constant ICU work; hypomagnesaemia and hypophosphataemia are underrecognised causes of refractory arrhythmias and respiratory muscle weakness",
  "Coagulation: PT/INR, aPTT, fibrinogen, D-dimer — daily in sepsis/liver failure/post-thrombolytics; fibrinogen <1.5 g/L + rising D-dimer + thrombocytopaenia = DIC",
  "CRP and procalcitonin: guide antibiotic de-escalation (procalcitonin falling to <0.5 ng/mL or <80% of peak → antibiotics can be stopped); procalcitonin does not rise in viral infections — helps distinguish bacterial from viral sepsis",
  "Liver function tests: daily in fulminant liver failure, post-cardiac surgery, prolonged hypotension (ischaemic hepatitis — ALT can rise to 10,000+ U/L)",
  "Repeat blood cultures: with every new fever spike (temperature >38.3°C) not explained by existing diagnosis; minimum 2 sets from separate sites; through CVC only if CVC infection specifically suspected (paired cultures)",
  "Serial ABGs: frequency depends on instability — every 4 hours in the first 24 h of ventilation; with every ventilator change; target PaO2 55–80 mmHg (or SpO2 88–95%) in ARDS; PaO2/FiO2 ratio classifies ARDS severity (Berlin criteria)",
].map(t => bullet(t)));

C.push(label("Advanced and Condition-Specific ICU Investigations"));
C.push(...[
  "**CT pulmonary angiography (CTPA):** Suspected massive or submassive PE; Wells score >4 or high clinical probability + DVT signs; haemodynamic instability with RV dilation on echo in a patient too unstable for CTPA → give empirical thrombolysis",
  "**CT brain (non-contrast):** New focal neurology, seizures, GCS drop, before LP — exclude mass lesion, hydrocephalus, herniation, haemorrhage",
  "**Bronchoalveolar lavage (BAL):** Ventilator-associated pneumonia (VAP) that is not responding, immunocompromised patient with bilateral infiltrates (PCP, CMV, invasive Aspergillus), non-resolving pneumonia; send for culture, cytology, Pneumocystis PCR, viral panel",
  "**Continuous EEG monitoring:** Non-convulsive status epilepticus (NCSE) in ICU patients with unexplained consciousness impairment post-seizure, unexplained coma, hepatic encephalopathy, post-cardiac arrest neuroprognostication",
  "**Echocardiography (TTE/TOE):** Shock of unknown aetiology (distinguish cardiogenic from distributive), new murmur (infective endocarditis — TOE superior, especially for prosthetic valves), post-cardiac surgery LV function, suspected aortic dissection (TOE)",
  "**Intracranial pressure (ICP) monitoring:** Severe TBI with GCS ≤8, massive cerebral infarction with oedema, fulminant hepatic failure with cerebral oedema — Camino or Codman bolt; target CPP (MAP minus ICP) 60–70 mmHg",
  "**Coronary angiography/PCI (cardiac catheter lab):** STEMI, high-risk NSTEMI, cardiogenic shock post-MI — most time-critical investigation-intervention in medicine (door-to-balloon <90 minutes)",
  "**Serum beta-glucan + galactomannan:** Invasive fungal infection in prolonged ICU stay, prolonged broad-spectrum antibiotics, haematological malignancy, bone marrow transplant — Aspergillus galactomannan sensitivity ~70% (higher in haematology); Candida — blood cultures remain gold standard",
].map(t => bullet(t)));

C.push(label("Invasive Monitoring Parameters in ICU"));
C.push(...[
  "Arterial line (ABP): continuous beat-to-beat BP monitoring, convenient serial ABG sampling; radial artery most common; waveform analysis (pulse pressure variation >13% = fluid-responsive in mechanically ventilated patients)",
  "Central venous catheter (CVC): CVP measurement (value limited but trend and dynamic response to fluid bolus useful), ScvO2 measurement (>70% = adequate O2 delivery; <70% = increased extraction = mismatch), drug infusions (vasopressors, concentrated electrolytes, TPN)",
  "Pulmonary artery catheter (PAC — Swan-Ganz): cardiac output (thermodilution), PAWP (left heart filling), PVR — used in refractory shock, ARDS to guide fluid management; less frequently used since advent of POCUS",
  "Urinary catheter + hourly urine output: essential for fluid balance; UO <0.5 mL/kg/h for >6 h = AKI criterion; UO >0.5 mL/kg/h confirms adequate renal perfusion with fluid resuscitation",
  "Temperature monitoring (core temperature): critical in sepsis (high), post-cardiac arrest TTM (target 36°C), heat stroke, hypothermia",
].map(t => bullet(t)));

C.push(label("Monitoring Frequency in ICU"));
C.push(simpleTable([
  ["Parameter", "First 24 Hours", "After Stabilisation"],
  ["ABG / Na / K", "Every 4 h (or continuous via ABL)", "Every 8–12 h"],
  ["Lactate", "Baseline, 2 h, 6 h, 12 h", "Daily until normalised"],
  ["CBC", "Every 12 h", "Daily"],
  ["Coagulation", "Every 12 h if coagulopathic", "Daily"],
  ["Blood cultures", "Admission + new fever spikes", "As clinically indicated"],
  ["Troponin", "0 h, 1 h, 3 h (ACS protocol)", "Daily if ongoing rise"],
  ["Bedside POCUS", "Admission + haemodynamic change", "As clinically indicated"],
  ["Procalcitonin", "Admission", "Day 3, 5, 7 (antibiotic guidance)"],
  ["Drug levels", "24–48 h post-start", "Per pharmacokinetic protocol"],
]));
C.push(sp());

C.push(docBox("ICU 16/06/26 0300h — 68 y male, septic shock (MAP 55 despite 2L crystalloid), SpO2 85% on 15L O2, GCS 11. POC ABG: pH 7.21, PaO2 58, PaCO2 36, HCO3 14, Lactate 5.8 mmol/L, K+ 5.9, Glucose 14.2. Bedside echo: EF 25%, dilated RV, no tamponade. Portable CXR: bilateral infiltrates (ARDS pattern). Blood cultures x2 sent. Procalcitonin 48 ng/mL. Rationale: Sepsis-3 criteria met (SOFA ≥2); high lactate = tissue hypoperfusion despite fluid; echo clarifies cardiogenic component. Started noradrenaline 0.1 mcg/kg/min (low SVR confirmed), intubated (ARDS Berlin moderate — P/F ratio 102), started lung-protective ventilation (TV 6 mL/kg IBW). Repeat ABG at 2 h."));
C.push(sp());

// ════════════════════════════════════════════════════════
C.push(h1("4. Disease-Specific Investigation Pathways — OPD to ICU"));
// ════════════════════════════════════════════════════════

// ── 4.1 Fever and Infection ──────────────────────────────────────────────────
C.push(h2("4.1  Fever and Suspected Infection"));

C.push(label("Epidemiological Filter — Ask Before Ordering"));
C.push(...[
  "Where does the patient live/work? (TB-endemic area, malaria zone, dengue-endemic region)",
  "Travel history in past 3 weeks? (malaria, enteric fever, viral haemorrhagic fever, COVID-19, mpox)",
  "Season and local outbreak alert? (influenza — winter; dengue — post-monsoon; meningococcal — dry season in Sahel)",
  "Immune status? (HIV, on immunosuppressants, asplenic — atypical pathogens and severity differ markedly)",
  "Exposure? (animal contact → brucellosis, Q fever; stagnant water → leptospirosis; sexual exposure → HIV, gonorrhoea, STI screen)",
].map(t => bullet(t)));

C.push(label("OPD — Mild Fever, No Systemic Features"));
C.push(...[
  "CBC with differential (viral: lymphocytosis; bacterial: neutrophilia; dengue: leukopenia + thrombocytopaenia)",
  "CRP (if >100 mg/L → likely bacterial, consider antibiotic; <20 mg/L + viral pattern → symptomatic management)",
  "Malaria RDT + thick/thin film (if endemic area or travel history — RDT fast, smear confirms species and parasitaemia)",
  "Dengue NS1 antigen (Day 1–5) + dengue IgM/IgG (Day 6+)",
  "Urinalysis and microscopy (exclude UTI as fever source)",
  "CXR if respiratory symptoms or SpO2 <96%",
  "Typhoid: Widal test (sensitivity limited — use only where culture unavailable); blood culture x2 is gold standard for enteric fever",
].map(t => bullet(t)));

C.push(label("Ward — Fever with Systemic Features (SIRS/Sepsis Criteria)"));
C.push(...[
  "Blood cultures x2 from separate sites before first antibiotic — sensitivity 65–90% depending on technique and timing",
  "Urine culture (midstream clean catch), sputum Gram stain and culture, wound swab if applicable",
  "CBC, CMP, LFTs, coagulation profile (identify organ dysfunction — SOFA components)",
  "Lactate (venous or arterial): >2 mmol/L = sepsis-related hypoperfusion even if BP normal (cryptic shock)",
  "Procalcitonin: bacterial infection (rises) vs. viral (minimal rise) vs. fungal (variable) — guides antibiotic initiation and duration",
  "CXR (pneumonia), CT abdomen if intra-abdominal source suspected, USS liver/biliary for cholangitis",
  "HIV rapid test (if unknown status in high-prevalence setting — critical for identifying Pneumocystis, CMV, cryptococcal co-infection)",
  "Thick and thin blood film (quantitative parasitaemia): if malaria suspected — do not wait for RDT alone in severe malaria (also needed for species identification and monitoring treatment response)",
].map(t => bullet(t)));

C.push(label("ICU — Severe Sepsis / Septic Shock"));
C.push(...[
  "ABG + lactate STAT: confirms degree of metabolic acidosis and hypoperfusion; base deficit guides fluid and bicarbonate therapy",
  "Blood cultures x2 BEFORE antibiotics (target within 1 hour; do not delay antibiotics >1 hour for cultures — if impossible to get cultures first, cultures can be drawn within 3 hours of first antibiotic dose in refractory shock)",
  "Procalcitonin at admission (high sensitivity/specificity for bacterial sepsis, useful for de-escalation monitoring)",
  "Serum lactate trend (0, 2, 6 h): sustained elevated lactate = inadequate resuscitation or source not controlled",
  "Fibrinogen, D-dimer, PT, aPTT, platelet count: DIC screen — mandatory in meningococcal sepsis, severe falciparum malaria, obstetric sepsis",
  "Source-specific: LP + CSF analysis (suspected meningitis — cell count, glucose/protein, Gram stain, culture, bacterial PCR, cryptococcal antigen in HIV+); CTPA (septic emboli/PE); echocardiogram (endocarditis with bacteraemia)",
  "Species-specific PCR panels (multiplex blood/respiratory PCR): sepsis of unclear source in ICU — meningococcal PCR, HSV/VZV encephalitis PCR in CSF, Aspergillus/CMV in immunocompromised",
].map(t => bullet(t)));
C.push(sp());

// ── 4.2 Chest Pain / ACS ────────────────────────────────────────────────────
C.push(h2("4.2  Chest Pain and Suspected Acute Coronary Syndrome (ACS)"));

C.push(label("Epidemiological Context"));
C.push(...[
  "Risk factor burden: male >45 years, female >55 years, hypertension, DM, dyslipidaemia, smoking, family history of premature IHD — increases pre-test probability substantially",
  "In young patients (<40 years) without classical risk factors: consider cocaine use (vasospasm), spontaneous coronary artery dissection (SCAD — young women), myocarditis (viral, post-COVID vaccine), Kawasaki disease sequelae",
].map(t => bullet(t)));

C.push(label("OPD / Emergency Department — Initial Presentation"));
C.push(...[
  "**12-lead ECG within 10 minutes** of presentation: most important first test; STEMI = immediate catheter lab activation (no troponin needed to act); LBBB + chest pain = STEMI equivalent; normal ECG does NOT exclude ACS",
  "High-sensitivity Troponin I or T (0 h): if normal at 0 h and low-risk (HEART score 0–3 or GRACE <109) → repeat at 1 h or 3 h; rise >20% from baseline = acute MI",
  "Serial ECG every 15–30 minutes if ongoing pain with non-diagnostic initial ECG",
  "CBC, CMP, coagulation (INR if thrombolysis considered), lipid profile, thyroid function",
  "CXR: assess cardiac size, pulmonary oedema, mediastinal width (aortic dissection — if pain radiates to back)",
  "Echocardiogram (if available): new wall motion abnormality confirms ischaemia even with non-diagnostic ECG",
].map(t => bullet(t)));

C.push(label("Ward — Post-Stabilisation (NSTEMI / Unstable Angina)"));
C.push(...[
  "Serial troponin at 0, 1, 3 h (hs-troponin rapid rule-out protocol): delta troponin >20% of baseline on 1 h or 3 h sample = MI; stable troponin below 99th percentile URL = rule-out",
  "Echocardiography: LV function (EF), regional wall motion abnormalities, mechanical complications (VSD, papillary muscle rupture, free wall rupture in STEMI)",
  "Coronary angiography: definitive anatomy and revascularisation — within 24 h for high-risk NSTEMI (GRACE >140, rising troponin, dynamic ECG, haemodynamic instability); within 72 h for intermediate risk",
  "Daily troponin until trending down (confirms peak and infarct size trajectory)",
  "HbA1c, fasting lipids, renal function: secondary prevention targets and cardiovascular risk profile",
].map(t => bullet(t)));

C.push(label("ICU/CCU — STEMI / Cardiogenic Shock"));
C.push(...[
  "Primary PCI (coronary angiography + intervention): diagnosis and treatment in one — door-to-balloon ≤90 min is the quality standard; angiography defines culprit vessel, severity, multi-vessel disease",
  "Arterial line: continuous BP monitoring; especially in cardiogenic shock or on vasopressors/inotropes",
  "Serial ABGs: LV failure → pulmonary oedema → type I respiratory failure (hypoxia + hypocapnia initially)",
  "Right heart catheterisation (Swan-Ganz/Pulmonary artery catheter): cardiogenic vs. distributive shock — PCWP >18 mmHg + low CO = cardiogenic; PCWP <12 mmHg + high CO = distributive",
  "Repeat ECG every 8 h: watching for re-occlusion (new ST elevation), arrhythmias (VT/VF — highest risk in first 48 h), development of heart block (inferior MI + RCA occlusion)",
  "Daily echocardiogram: monitor EF, complications, decision for mechanical support (IABP, Impella) or surgical intervention",
].map(t => bullet(t)));
C.push(sp());

// ── 4.3 Dyspnoea ─────────────────────────────────────────────────────────────
C.push(h2("4.3  Dyspnoea — Differentiating Cause by Clinical Level"));

C.push(label("Epidemiological Filter"));
C.push(...[
  "Age and smoking history: COPD/emphysema in older smokers; asthma in younger atopic patients",
  "Occupational exposure: silica (silicosis), asbestos (asbestosis, mesothelioma), cotton dust (byssinosis) — occupational history is a mandatory part of respiratory assessment",
  "Geography/season: TB in high-burden country; pneumonia in post-monsoon period; histoplasmosis/coccidioidomycosis in travellers from endemic areas",
].map(t => bullet(t)));

C.push(label("OPD — Subacute / Stable Dyspnoea"));
C.push(...[
  "Spirometry (pre- and post-bronchodilator): FEV1/FVC <0.70 = obstructive (COPD/asthma); FVC reduced with preserved ratio = restrictive (ILD, obesity, pleural disease) — gold standard for airflow obstruction",
  "Peak expiratory flow rate (PEFR): bedside measurement of airway obstruction severity; diurnal variability >20% = asthma",
  "CXR: hyperinflation (COPD), infiltrates (pneumonia, TB, sarcoidosis), pleural effusion, cardiomegaly (cardiac cause)",
  "Pulse oximetry: resting SpO2; if ≥94% and stable → full investigation as outpatient; if <94% → urgent admission",
  "ECG + NT-proBNP: exclude heart failure as cause of dyspnoea (NT-proBNP >125 pg/mL = heart failure likely; <125 pg/mL = heart failure excluded in low-to-intermediate probability)",
  "CBC, CRP (infection/anaemia as contributing factor), thyroid function (thyrotoxicosis causes dyspnoea + tachycardia)",
].map(t => bullet(t)));

C.push(label("Ward — Acute Dyspnoea Requiring Admission"));
C.push(...[
  "ABG: type I (hypoxia only — pneumonia, PE, pulmonary oedema) vs. type II (hypoxia + hypercapnia — COPD exacerbation, neuromuscular disease, severe asthma) failure guides ventilatory decision",
  "Chest X-ray: infiltrates (pneumonia, ARDS), cardiomegaly + vascular congestion (CCF), pneumothorax (absent lung markings), pleural effusion",
  "CTPA: Wells score ≥4 or high clinical probability of PE; sensitivity 95%+ for PE diagnosis; also shows lung parenchyma (alternative diagnoses)",
  "NT-proBNP: very high (>5000 pg/mL) in decompensated heart failure; low (<300 pg/mL) effectively rules out cardiac cause",
  "Echocardiogram: EF, pericardial effusion, valvular disease, pulmonary hypertension (PAH causing dyspnoea)",
  "Sputum culture + sensitivity; blood cultures if infective exacerbation (AECOPD with purulent sputum, CAP with CURB-65 ≥2)",
  "D-dimer: only if Wells score <4 (low-intermediate probability for PE); positive D-dimer → CTPA; negative → PE excluded",
].map(t => bullet(t)));

C.push(label("ICU — Severe Respiratory Failure"));
C.push(...[
  "ABG immediately: P/F ratio (PaO2/FiO2) classifies ARDS — mild >200, moderate 100–200, severe <100; guides ventilator settings (prone position if P/F <150)",
  "Portable CXR on intubation: ETT position (2–3 cm above carina), bilateral infiltrates (ARDS), effusion, pneumothorax (post-intubation/barotrauma)",
  "Bedside lung ultrasound: consolidation (hepatisation pattern), pneumothorax (absent lung sliding, barcode sign on M-mode), B-lines (cardiogenic oedema vs. ARDS — bilateral diffuse B-lines in both; asymmetric suggests consolidation)",
  "BAL (bronchoalveolar lavage): non-resolving ventilator-associated pneumonia, immunocompromised with bilateral infiltrates (Pneumocystis PCR, CMV, Aspergillus, multiplex respiratory PCR FilmArray)",
  "Serial ABGs every 4 h or with every ventilator change: guide PEEP optimisation, FiO2 weaning, PaCO2 control in ARDS (target permissive hypercapnia pH >7.20)",
  "Troponin: ARDS can cause right heart strain — RV failure complicating ARDS is a management priority",
].map(t => bullet(t)));
C.push(sp());

// ── 4.4 Altered Consciousness ────────────────────────────────────────────────
C.push(h2("4.4  Altered Consciousness and Neurological Emergencies"));

C.push(label("Epidemiological Context"));
C.push(...[
  "Age: elderly (delirium, stroke, subdural haematoma, urinary/respiratory sepsis); young adult (drug overdose, meningitis, metabolic causes, epilepsy)",
  "HIV-positive patient with altered consciousness: cryptococcal meningitis (do India ink + CrAg), toxoplasmosis (CT brain — ring-enhancing lesions), CMV encephalitis, TB meningitis — all have different treatment urgency",
  "Travel history: cerebral malaria (P. falciparum) in traveller from Africa/Asia with fever + confusion — thick film is emergency",
].map(t => bullet(t)));

C.push(label("OPD / Emergency Triage — Rapid Assessment"));
C.push(...[
  "**Blood glucose immediately (within 2 minutes):** Hypoglycaemia (glucose <3.0 mmol/L) is the single most common treatable cause of altered consciousness — treat first, investigate second",
  "ECG: hyperkalaemia (in dialysis patient), arrhythmia, heart block, Torsades (drug toxicity), STEMI (inferior MI can present as collapse)",
  "Temperature, pulse oximetry, BP: vital signs localise the problem (fever = infection; low SpO2 = respiratory cause; shock = circulatory cause)",
  "Urine dipstick: glucose + ketones (DKA), leukocytes/nitrites (UTI → sepsis causing confusion)",
].map(t => bullet(t)));

C.push(label("Ward — Subacute/Acute Confusion"));
C.push(...[
  "CBC, CRP, CMP (Na — hyponatraemia; Ca — hypercalcaemia; creatinine/urea — uraemia; NH3 — hepatic encephalopathy), blood glucose, TFTs, cortisol (adrenal insufficiency)",
  "Urinalysis + culture, blood cultures (most common cause of delirium in elderly is occult infection — UTI, pneumonia, bacteraemia)",
  "CT brain (non-contrast): before LP; identifies haemorrhage, mass lesion, herniation, subdural haematoma (crescent-shaped hyperdense collection), hydrocephalus; normal CT does NOT exclude meningitis",
  "LP (lumbar puncture): after CT brain excludes contraindications; CSF sent for: opening pressure, appearance (clear/turbid/bloody), cell count (neutrophils = bacterial; lymphocytes = viral/TB/fungal), protein, glucose (CSF:serum ratio <0.5 = bacterial), Gram stain and culture, bacterial multiplex PCR (BioFire meningitis panel), cryptococcal antigen (if HIV+), AFB + TB PCR (if subacute + high-risk population)",
  "Drug/toxicology screen: paracetamol level, alcohol, benzodiazepines, opioids, salicylates — especially in young patients with unexplained altered consciousness",
  "Ammonia (venous): hepatic encephalopathy; correlate with clinical features (GCS, asterixis) — not all high ammonia = encephalopathy; LFTs, clotting",
  "EEG: non-convulsive status epilepticus (NCSE) — suspect in any unresponsive patient without clear structural cause after standard workup; requires specific expertise to interpret",
  "Thiamine 100 mg IV before any glucose infusion: prevent precipitation of Wernicke's encephalopathy in alcoholic/malnourished patients",
].map(t => bullet(t)));

C.push(label("ICU — Coma / Severe Neurological Failure"));
C.push(...[
  "CT brain with CT angiography: large vessel occlusion (LVO) for thrombectomy decision; subarachnoid haemorrhage (hyperdense cisterns); haemorrhagic transformation; midline shift",
  "MRI brain with DWI: most sensitive for early ischaemic stroke (hours); identifies posterior fossa lesions (CT misses); cerebral venous thrombosis (MRV); autoimmune encephalitis (FLAIR signal)",
  "Continuous EEG monitoring: any GCS ≤8 without structural explanation; post-cardiac arrest (neuroprognostication and seizure detection); SE refractory to medication",
  "ICP monitoring (Camino bolt): GCS ≤8 post-TBI, ADEM, hepatic encephalopathy with cerebral oedema — target ICP <20 mmHg, CPP 60–70 mmHg",
  "Evoked potentials (SSEP): neuroprognostication after cardiac arrest — absent cortical N20 responses bilaterally at 72 h predicts poor outcome",
  "Autoimmune encephalitis panel (CSF and serum): anti-NMDAR, anti-LGI1, anti-CASPR2, anti-GABA-B — particularly in young patients with psychiatric features + seizures + movement disorder; send before immunosuppression",
].map(t => bullet(t)));
C.push(sp());

// ── 4.5 Acute Abdomen ───────────────────────────────────────────────────────
C.push(h2("4.5  Acute Abdomen"));

C.push(label("OPD — Mild/Chronic Abdominal Symptoms"));
C.push(...[
  "CBC (leukocytosis in appendicitis/cholecystitis), CRP, LFTs (biliary disease — raised ALP, GGT, bilirubin)",
  "Urine pregnancy test: exclude ectopic pregnancy before any abdominal investigation in women of reproductive age",
  "Urinalysis: haematuria (ureteric stone), leukocytes (pyelonephritis mimicking acute abdomen)",
  "Ultrasound abdomen: hepatomegaly, gallstones (95% sensitive), biliary duct dilation (obstruction), free fluid, renal calculi, appendix (if visualised — up to 70% sensitivity); first-line for biliary and renal pathology",
  "H. pylori stool antigen or urea breath test: dyspepsia/epigastric pain, first-line non-invasive test before OGD",
].map(t => bullet(t)));

C.push(label("Ward — Acute Abdominal Pain Requiring Admission"));
C.push(...[
  "CBC, CMP, LFTs, lipase/amylase (acute pancreatitis — lipase 3× upper limit more specific than amylase), coagulation",
  "Serum lipase/amylase: pancreatitis diagnosis; lipase more sensitive and specific than amylase; does not predict severity",
  "CT abdomen/pelvis with IV contrast: gold standard for acute abdomen; appendicitis (sensitivity 94%), pancreatitis severity (Balthazar/CT Severity Index — contrast-enhanced CT at 48–72 h), bowel perforation (free air under diaphragm — CXR erect first), ischaemic bowel (mesenteric ischaemia — requires CTA with vascular phase)",
  "Erect CXR: free air under diaphragm = perforation (always do before CT if stable — cheap, fast, definitive if positive)",
  "OGD (oesophagogastroduodenoscopy): upper GI bleed (diagnostic + therapeutic) within 24 h; dysphagia; suspected peptic ulcer with alarm features",
  "Ascitic tap (diagnostic paracentesis): new ascites — cell count (>250 neutrophils/mm3 = SBP), albumin (SAAG), culture, cytology (malignant ascites)",
  "MRCP: bile duct stones (choledocholithiasis), PSC (primary sclerosing cholangitis), pancreatic duct pathology — before ERCP decision",
].map(t => bullet(t)));

C.push(label("ICU — Abdominal Emergency with Organ Dysfunction"));
C.push(...[
  "CT aortography: aortic dissection (Type A — surgical emergency; Type B — medical management), ruptured AAA — CT shows size, extravasation, extension",
  "Mesenteric CT angiography: acute mesenteric ischaemia (serum lactate rising + peritonism + AF or recent cardiac catheterisation = embolus to SMA) — CT angiography shows SMA occlusion; diagnosis is clinical + imaging + high index of suspicion",
  "Serial lactate: mesenteric ischaemia and peritonitis — rising lactate after initial resuscitation = ongoing ischaemia = surgical emergency",
  "Diagnostic laparoscopy/laparotomy: when CT does not provide diagnosis and patient is deteriorating (damage-control surgery may precede definitive imaging in extremis)",
  "Culture of peritoneal fluid/drain output: intra-abdominal sepsis — identify organisms, guide antibiotic escalation; fungi (Candida) common in post-operative abdominal sepsis",
].map(t => bullet(t)));
C.push(sp());

// ── 4.6 Diabetes-Related Emergencies ─────────────────────────────────────────
C.push(h2("4.6  Diabetes-Related Emergencies — DKA and HHS"));

C.push(label("OPD — New or Poorly Controlled Diabetes"));
C.push(...[
  "Fasting glucose + HbA1c: diagnosis and medium-term control; HbA1c ≥48 mmol/mol (6.5%) on two occasions = diabetes",
  "Urine ACR (albumin-creatinine ratio): nephropathy screening — microalbuminuria 3–30 mg/mmol; macroalbuminuria >30 mg/mmol",
  "Lipid profile, LFTs (NAFLD), thyroid function (hypothyroidism worsens glycaemic control)",
  "Annual dilated fundoscopy: diabetic retinopathy screening",
  "Foot examination + ankle-brachial pressure index (ABPI): peripheral arterial disease and neuropathy assessment",
].map(t => bullet(t)));

C.push(label("Ward — Diabetic Ketoacidosis (DKA)"));
C.push(...[
  "ABG or venous blood gas (VBG): pH <7.3 + bicarbonate <15 mmol/L + ketonaemia >3 mmol/L = DKA confirmed; VBG adequate for diagnosis and monitoring (reserve ABG for severe hypoxia or ventilatory decision)",
  "Serum ketones (betahydroxybutyrate): >3 mmol/L = significant ketonaemia; <0.3 mmol/L = resolved; guide treatment more accurately than urine ketones",
  "Blood glucose (hourly during insulin infusion): target fall of 3–5 mmol/L/h; switch to glucose-containing fluids when blood glucose <14 mmol/L",
  "Electrolytes (Na, K, bicarbonate) every 1–2 h: hypokalaemia during insulin infusion is the most common life-threatening complication — check K+ before starting insulin; if K+ <3.5 mmol/L → replace before insulin",
  "Renal function (hourly urine output + creatinine): dehydration + AKI is common in DKA; recovery of urine output signals adequate resuscitation",
  "ECG: hyperkalaemia (peaked T waves) on admission; hypokalaemia (U waves, prolonged QT) during treatment — monitor before and after electrolyte correction",
  "CBC, CRP, blood cultures: infection is the most common DKA precipitant — identify and treat simultaneously",
  "Serum osmolality: DKA vs. HHS — in HHS, osmolality >320 mOsm/kg with minimal ketosis; profound hypernatraemia and hyperglycaemia (>30 mmol/L)",
].map(t => bullet(t)));

C.push(label("ICU — Severe DKA / HHS with Organ Dysfunction"));
C.push(...[
  "Continuous cardiac monitoring: arrhythmias secondary to electrolyte instability (K, Mg, phosphate)",
  "Serial ABGs every 2–4 h: monitor acid-base response to treatment; persistent acidosis despite insulin + fluids → ensure ketonaemia resolving, consider precipitant not controlled (abdominal sepsis, MI)",
  "Phosphate: may drop significantly during DKA treatment (insulin drives phosphate into cells) → respiratory muscle weakness, haemolysis; replace if <0.3 mmol/L or if mechanically ventilated",
  "CT brain: cerebral oedema complication (rare, mostly paediatric, but in severe adult DKA with neurological deterioration) — headache + deteriorating consciousness during treatment",
  "Echocardiogram: HHS in elderly patients — concurrent AMI or heart failure may be precipitant; decompensated heart failure during large-volume fluid replacement",
].map(t => bullet(t)));
C.push(sp());

// ── 4.7 Renal Failure ────────────────────────────────────────────────────────
C.push(h2("4.7  Acute Kidney Injury (AKI)"));

C.push(label("OPD — Incidental Rise in Creatinine / CKD Monitoring"));
C.push(...[
  "Serum creatinine + eGFR (CKD-EPI equation): stage CKD; recall that in elderly and malnourished patients, creatinine may be 'normal' despite GFR of 30–40 mL/min due to reduced muscle mass",
  "Urine ACR: proteinuria quantification — key marker of CKD progression risk; ACR >30 mg/mmol = significant proteinuria",
  "Renal ultrasound: kidney size (small kidneys = chronic disease; asymmetric = renovascular), corticomedullary differentiation, obstruction (hydronephrosis)",
  "Urine dipstick: haematuria + proteinuria → glomerulonephritis workup (ANA, ANCA, anti-GBM, complement, anti-dsDNA)",
  "Medication review: stop or dose-reduce nephrotoxins (NSAIDs, metformin, contrast agents, aminoglycosides)",
].map(t => bullet(t)));

C.push(label("Ward — AKI (Acute Presentation)"));
C.push(...[
  "Serum creatinine, urea, electrolytes: KDIGO AKI staging (Stage 1: Cr 1.5–1.9× baseline; Stage 2: 2–2.9×; Stage 3: ≥3× or Cr ≥353 μmol/L or RRT initiation); urea:creatinine ratio >100:1 = pre-renal",
  "Urine microscopy and dipstick: granular/muddy brown casts = ATN; RBC casts = glomerulonephritis; white cell casts = pyelonephritis or interstitial nephritis; dysmorphic RBCs = glomerular bleeding",
  "Urine sodium and fractional excretion of sodium (FeNa): FeNa <1% = pre-renal (avid sodium reabsorption); FeNa >2% = intrinsic (tubular damage); FeNa unreliable if on diuretics or contrast",
  "Renal tract ultrasound (urgent): exclude post-renal obstruction (hydronephrosis) — if obstructed, urgent urology input (catheter for BPH; nephrostomy for upper tract obstruction)",
  "Serum and urine protein electrophoresis, BJP (Bence Jones protein): myeloma as cause of AKI (cast nephropathy) — particularly in older patient with AKI + hypercalcaemia + anaemia",
  "Complement (C3, C4), ANCA, anti-GBM, ANA, anti-dsDNA: rapidly progressive glomerulonephritis (RPGN) — urgent diagnosis required as treatment (cyclophosphamide, plasma exchange) is time-sensitive",
  "Renal biopsy: unexplained intrinsic AKI, suspected RPGN, nephrotic syndrome — result needed to direct specific immunosuppression; requires stable coagulation and BP",
].map(t => bullet(t)));

C.push(label("ICU — AKI with Organ Failure / Renal Replacement Therapy"));
C.push(...[
  "ABG: metabolic acidosis (anion gap elevated — uraemic acids accumulate); hyperphosphataemia; hypermagnesaemia",
  "Continuous ECG monitoring: hyperkalaemia in AKI is immediately life-threatening — peaked T waves, wide QRS, sine-wave pattern = near-arrest; calcium gluconate before all else",
  "Daily renal function, electrolytes x4 hourly if on IV insulin/bicarbonate therapy for hyperkalaemia",
  "Bladder scan/urinary catheter with hourly urine output: distinguish oliguria (output <0.5 mL/kg/h) from anuria (<100 mL/24 h); monitor response to fluid challenge (400 mL crystalloid over 15 min → UO should increase within 1 h if pre-renal)",
  "Indications for continuous renal replacement therapy (CRRT): ECG-confirmed hyperkalaemia refractory to medical therapy, severe metabolic acidosis pH <7.1, fluid overload unresponsive to diuretics, uraemic encephalopathy/pericarditis — do not wait for all four criteria to be present simultaneously",
].map(t => bullet(t)));
C.push(sp());

// ════════════════════════════════════════════════════════
C.push(h1("5. Avoiding Common Investigation Errors"));
// ════════════════════════════════════════════════════════

C.push(label("Tests to Avoid Ordering Inappropriately"));
C.push(...[
  "**MRI brain for every OPD headache:** MRI brain in unselected headache has a low positive yield and high false-positive rate (incidental findings causing patient anxiety). Use SNOOP mnemonic for red flags warranting imaging: Systemic symptoms, Neurological signs, Onset sudden/thunderclap, Older age (>50) new headache, Pattern change/Postural/Precipitated by Valsalva",
  "**D-dimer in high clinical probability PE:** D-dimer is a rule-out test only for low-to-intermediate probability. In high-probability Wells score (≥5), a positive D-dimer adds nothing and a negative D-dimer is unreliable — go directly to CTPA.",
  "**Widal test alone for typhoid:** Low specificity; cross-reacts with other Salmonella species and non-specific febrile illness. Blood culture (x3 over 24 h) is gold standard. Widal acceptable only where culture is unavailable.",
  "**Procalcitonin in non-infectious conditions:** Procalcitonin can rise in trauma, major surgery, medullary thyroid carcinoma, and certain autoimmune states — do not interpret in isolation; always correlate with clinical picture.",
  "**Repeat potassium without ECG in DKA:** Always check ECG and potassium BEFORE starting insulin infusion. Starting insulin with K+ <3.5 mmol/L risks fatal hypokalaemia.",
  "**HBsAg/HCV/HIV screen skipped before immunosuppression:** All patients starting DMARDs, biologics, steroids, or chemotherapy require viral hepatitis (HBV reactivation risk) and HIV screening — failure to do so risks catastrophic reactivation.",
  "**CXR for routine pre-operative assessment in young healthy patients:** Not indicated in asymptomatic patients <45 years for elective surgery without cardiorespiratory disease. Evidence-based pre-operative investigations are guided by clinical risk, not routine protocols.",
].map(t => bullet(t)));

C.push(label("Documenting Investigation Rationale — Standard Format"));
C.push(...[
  "**What was ordered:** Test name, priority (STAT/urgent/routine), time sent",
  "**Why it was ordered:** Clinical question being answered (one sentence)",
  "**Result and key numbers:** Include actual values, not just 'normal' or 'abnormal'",
  "**Interpretation:** What does the result mean in this specific patient context?",
  "**Next action:** Repeat test, escalate therapy, consult subspecialty, discharge, watch and wait",
].map(t => bullet(t)));

C.push(docBox("Ward 17/06/26 1430h — 45 y male, day 3 of IV cefazolin for cellulitis, now febrile again (38.7°C). Test ordered: Blood cultures x2 (STAT) + CRP repeat + WBC. Rationale: new fever spike during appropriate antibiotic therapy — must exclude bacteraemia, MRSA infection, or resistant organism. Result (6 h later): Staph aureus bacteraemia confirmed. WBC 22k, CRP 310 (worsening). Interpretation: cellulitis source bacteraemia, likely MSSA — pending MRSA screen. Action: changed to IV flucloxacillin (MSSA-specific); ordered echocardiogram (endocarditis exclusion in bacteraemia); repeat blood cultures at 48 h to confirm clearance."));
C.push(sp());

// ════════════════════════════════════════════════════════
C.push(h1("6. Summary Reference — Investigations by Level"));
// ════════════════════════════════════════════════════════

C.push(label("Quick Reference: First-Line Tests by Level and Condition"));
C.push(simpleTable([
  ["Condition", "OPD", "Ward", "ICU"],
  ["Fever / Infection", "CBC, CRP, malaria RDT, dengue NS1, urinalysis, CXR, blood culture if admitted", "Blood cultures x2, urine/sputum cultures, lactate, procalcitonin, CXR, CT abdomen if source unclear", "ABG + lactate STAT, blood cultures, POCUS, CXR portable, serial procalcitonin"],
  ["Chest pain / ACS", "ECG (10 min), hs-Troponin (0+3h), CXR, CBC, lipids", "Serial troponin (0,1,3h), echo, coronary angiography (≤24h high-risk)", "Coronary angio + PCI (STEMI), arterial line, serial ABG, serial ECG, Swan-Ganz if shocked"],
  ["Dyspnoea", "Spirometry, SpO2, CXR, ECG, NT-proBNP, CBC", "ABG, CTPA (if PE suspected), echo, blood and sputum cultures, D-dimer (if low probability)", "ABG q4h, P/F ratio, portable CXR, POCUS, BAL if VAP"],
  ["Altered Consciousness", "Blood glucose, ECG, BP/SpO2, urine dipstick", "CBC, CMP, TFTs, CT brain, LP (if meningitis), drug screen, EEG", "CT brain/angio, MRI/DWI, continuous EEG, ICP monitoring, autoimmune panel"],
  ["Acute Abdomen", "USS abdomen, CBC, CRP, LFTs, lipase, urine pregnancy test", "CT abdomen/pelvis, erect CXR, OGD (GI bleed), MRCP (biliary), ascitic tap", "CT aortography, mesenteric CTA, serial lactate, laparotomy if needed"],
  ["DKA / HHS", "HbA1c, fasting glucose, urine ketones, eGFR", "ABG/VBG, serum ketones, electrolytes q1-2h, blood glucose hourly, ECG", "Continuous ECG, serial ABGs q2-4h, phosphate, CT brain (cerebral oedema)"],
  ["AKI", "Creatinine, eGFR, urine ACR, renal USS, medication review", "Urine microscopy, FeNa, renal USS (urgent), autoimmune screen if RPGN, renal biopsy", "ECG (hyperkalaemia), ABG, hourly UO, electrolytes q4h, CRRT indications assessment"],
]));
C.push(sp());

// ════════════════════════════════════════════════════════
const doc = new Document({
  numbering: {
    config: [{
      reference: "bullets",
      levels: [{
        level: 0,
        format: LevelFormat.BULLET,
        text: "\u2022",
        alignment: AlignmentType.LEFT,
        style: { paragraph: { indent: { left: 720, hanging: 360 } } }
      }]
    }]
  },
  styles: {
    default: { document: { run: { font: "Arial", size: 22 } } }
  },
  sections: [{ children: C }]
});

Packer.toBuffer(doc).then(buf => {
  fs.writeFileSync("/home/daytona/workspace/elog/C_Investigations_by_Level.docx", buf);
  console.log("DONE");
});
Running Command

cd /home/daytona/workspace/elog && node gen_C_investigations.js 2>&1

Running Command

cp /home/daytona/workspace/elog/C_Investigations_by_Level.docx /tmp/C_inv.docx && soffice --headless --convert-to pdf --outdir /tmp/ /tmp/C_inv.docx 2>&1 && ls -lh /tmp/C_inv.pdf && cp /tmp/C_inv.pdf /home/daytona/workspace/elog/C_Investigations_by_Level.pdf

Both files ready. Download here:
  • C Investigations by Level

    Word Document · DOCX

    (Word, ~35 KB)
  • C Investigations by Level

    PDF Document · PDF

    (PDF, 297 KB)

Document structure — plain title, continuous flow, no page breaks

1. Core Principles That Drive Investigation Choice Pre-test probability, sensitivity vs. specificity, epidemiological context (tropics, seasons, outbreaks, occupational exposure), resource stewardship, turn-around time, serial monitoring vs. snapshot, infection control
2. General Workflow — 6-step numbered process: Assess → Define setting → Prioritise goal → Epidemiological filter → Select logically → Document rationale
3. Setting-Wise Framework
  • OPD: Standard baseline panel, point-of-care tests (RDT, dengue NS1, glucometer, SpO2), red-flag escalation triggers, documentation snippet
  • Ward: Baseline extensions, radiology/procedural investigations, daily monitoring parameters, documentation snippet
  • ICU: Immediate tests (ABG+lactate, ECG, bedside glucose, portable CXR, POCUS), daily/BID panel, advanced investigations (CTPA, BAL, continuous EEG, ICP bolt), invasive monitoring parameters, monitoring frequency table, documentation snippet
4. Disease-Specific Pathways (OPD → Ward → ICU) Fever/Infection · Chest pain/ACS · Dyspnoea · Altered consciousness · Acute abdomen · DKA/HHS · Acute kidney injury — each with epidemiological filter and tiered test selection
5. Common Errors to Avoid — with rationale (MRI for every headache, D-dimer in high-probability PE, Widal alone for typhoid, K+ before insulin in DKA, viral screens before immunosuppression)
6. Quick Reference Summary Table — all 7 conditions × 3 levels at a glance

C - Describe the pharmaco-therapeutics of various diseases and complications.

C - Describe the pharmaco-therapeutics of various diseases and complications.

This is a shared conversation. Sign in to Orris to start your own chat.