1. Carbohydrates & Glucose Metabolism ● Classification: Classification of carbohydrates with examples (Homopolysaccharides, Mucopolysaccharides). ● Glycolysis & Pathways: Fate of Glucose in the body; Pathway of Glycolysis and its energetics; TCA Cycle (Krebs cycle) steps, energetics, and importance; Significance of HMP shunt. ● Synthesis & Storage: Define gluconeogenesis and glycogenesis (steps involved); Synthesis of glucose from non-carbohydrate sources. ● Blood Sugar Regulation: Regulation of blood glucose level; Factors, mechanisms, and hormones for regulation; Normal fasting and post-meal values; Renal threshold. ● Clinical Conditions & Tests: Glucose Tolerance Test (GTT) - when and how is it performed; Glycosuria.

Reading File
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Reading File
Reading File
Reading File
Reading File
Reading File
Reading File
Reading File
Finding Sources
Finding Sources
Here are your complete, structured notes on Carbohydrates & Glucose Metabolism, compiled from Basic Medical Biochemistry - A Clinical Approach (6e), Guyton and Hall Textbook of Medical Physiology, Tietz Textbook of Laboratory Medicine, and Goodman & Gilman's Pharmacological Basis of Therapeutics.

CARBOHYDRATES & GLUCOSE METABOLISM - Complete Notes


1. CLASSIFICATION OF CARBOHYDRATES

Carbohydrates are polyhydroxy aldehydes or ketones. They are classified by the number of sugar units:

Monosaccharides

  • Single sugar unit; cannot be hydrolyzed further
  • Examples: Glucose (aldohexose), Fructose (ketohexose), Galactose, Ribose (pentose), Deoxyribose

Disaccharides

  • Two monosaccharides joined by a glycosidic bond
  • Examples:
    • Sucrose = Glucose + Fructose (table sugar)
    • Lactose = Glucose + Galactose (milk sugar)
    • Maltose = Glucose + Glucose (malt sugar)

Oligosaccharides

  • 3-10 monosaccharide units
  • Found on cell surface glycoproteins and glycolipids (important for cell recognition)

Polysaccharides

Large chains of monosaccharides. Divided into:

A. Homopolysaccharides

All units are the same monosaccharide:
HomopolysaccharideMonomerKey Feature
Starch (amylose + amylopectin)GlucosePlant storage form; α-1,4 linkages (amylose), α-1,6 branches (amylopectin)
GlycogenGlucoseAnimal storage form; more branched than amylopectin (α-1,6 branch every 8-10 residues)
CelluloseGlucoseStructural (plants); β-1,4 linkages; not digestible by humans
DextranGlucoseBacterial; used as plasma expander
InulinFructoseUsed to measure GFR
ChitinN-AcetylglucosamineExoskeletons of insects, fungi cell walls

B. Mucopolysaccharides (Glycosaminoglycans - GAGs)

  • Long unbranched chains of repeating disaccharide units (one amino sugar + one uronic acid)
  • Highly negatively charged; attract water - form the gel-like ground substance of connective tissue
  • Usually attached to a protein core = Proteoglycans
GAGCompositionLocation
Hyaluronic acidGlucuronic acid + N-AcetylglucosamineVitreous humor, synovial fluid, loose CT
Chondroitin sulfateGlucuronic acid + N-AcetylgalactosamineCartilage, bone, cornea
Dermatan sulfateIduronic acid + N-AcetylgalactosamineSkin, blood vessels
Heparan sulfate / HeparinGlucuronic/Iduronic acid + GlucosamineMast cells; anticoagulant
Keratan sulfateGalactose + N-AcetylglucosamineCornea, cartilage
Clinical note: Deficiency of enzymes degrading GAGs causes Mucopolysaccharidoses (e.g., Hurler syndrome - deficiency of α-L-iduronidase; Hunter syndrome - iduronate sulfatase)

2. FATE OF GLUCOSE IN THE BODY

After absorption, glucose can be:
  1. Oxidized via Glycolysis → TCA Cycle → Oxidative Phosphorylation (primary ATP generation)
  2. Stored as Glycogen (glycogenesis) - in liver and muscle
  3. Converted to Fat (lipogenesis) - excess glucose → acetyl-CoA → fatty acids → triglycerides
  4. Enters Pentose Phosphate Pathway (HMP Shunt) - generates NADPH and ribose-5-phosphate
  5. Converted to other sugars (galactose, glucuronic acid, amino sugars)
  6. Excreted in urine if blood glucose exceeds renal threshold (~180 mg/dL)

3. GLYCOLYSIS - Pathway & Energetics

Definition: Glycolysis is the sequence of reactions that converts 1 mole of glucose (6C) into 2 moles of pyruvate (3C), generating ATP in both aerobic and anaerobic conditions. It occurs in the cytosol of all cells.
  • Source: Basic Medical Biochemistry, 6e

Phases

Phase 1 - Preparative / Investment Phase (uses ATP)

StepReactionEnzymeNotes
1Glucose → Glucose-6-phosphate (G6P)Hexokinase (all tissues) / Glucokinase (liver, β-cells)Irreversible; traps glucose in cell
2G6P → Fructose-6-phosphate (F6P)Phosphoglucose isomeraseReversible
3F6P → Fructose-1,6-bisphosphate (F1,6BP)Phosphofructokinase-1 (PFK-1)Rate-limiting step; irreversible; activated by AMP, ADP, F2,6BP; inhibited by ATP, citrate
4F1,6BP → DHAP + Glyceraldehyde-3-P (G3P)AldolaseReversible
5DHAP ⇌ G3PTriose phosphate isomeraseAllows both trioses to enter Phase 2
End of Phase 1: 2 ATP consumed per glucose

Phase 2 - ATP-Generating Phase (produces ATP) - all steps × 2

StepReactionEnzymeProduct
6G3P → 1,3-BisphosphoglycerateG3P Dehydrogenase2 NADH produced
71,3-BPG → 3-PhosphoglyceratePhosphoglycerate kinase2 ATP (substrate-level)
83-PG → 2-PhosphoglyceratePhosphoglycerate mutase
92-PG → Phosphoenolpyruvate (PEP)Enolase (inhibited by fluoride)
10PEP → PyruvatePyruvate kinase2 ATP (substrate-level); irreversible

Net Energetics of Glycolysis

ProductAmount
ATP (net)2 ATP per glucose
NADH2 NADH per glucose
Pyruvate2 pyruvate
If NADH enters mitochondria via malate-aspartate shuttle → 2.5 ATP each = +5 ATP If via glycerol-3-phosphate shuttle → 1.5 ATP each = +3 ATP

Fate of Pyruvate

  • Aerobic (O2 present): Pyruvate → Acetyl-CoA (by Pyruvate Dehydrogenase) → TCA Cycle → 30 ATP total
  • Anaerobic (no O2): Pyruvate → Lactate (by Lactate Dehydrogenase) - regenerates NAD+ to keep glycolysis running
    • Net ATP = only 2 per glucose
    • Important in: RBCs (no mitochondria), skeletal muscle during intense exercise, ischemic tissues

Regulation of Glycolysis

  • PFK-1 is the key regulatory enzyme
    • Activated by: AMP, ADP, fructose-2,6-bisphosphate (F2,6BP - made by PFK-2, stimulated by insulin)
    • Inhibited by: ATP (high energy charge), citrate
  • Pyruvate kinase - activated by F1,6BP (feedforward); inhibited by ATP, alanine; phosphorylated (inactivated) by glucagon/epinephrine

4. TCA CYCLE (Krebs Cycle / Citric Acid Cycle)

Location: Mitochondrial matrix Entry substrate: Acetyl-CoA (2C) + Oxaloacetate (4C) → Citrate (6C)

Steps of TCA Cycle

StepReactionEnzymeProduct
1Acetyl-CoA + OAA → CitrateCitrate synthaseCitrate (6C); regulated step
2Citrate → IsocitrateAconitase
3Isocitrate → α-KetoglutarateIsocitrate dehydrogenaseNADH + CO2; rate-limiting step
4α-Ketoglutarate → Succinyl-CoAα-Ketoglutarate dehydrogenaseNADH + CO2; irreversible
5Succinyl-CoA → SuccinateSuccinyl-CoA synthetaseGTP (substrate-level phosphorylation)
6Succinate → FumarateSuccinate dehydrogenaseFADH2 (only FAD-linked step; embedded in inner membrane)
7Fumarate → MalateFumaraseH2O added
8Malate → OxaloacetateMalate dehydrogenaseNADH (OAA regenerated for next turn)

Energetics of TCA Cycle (per Acetyl-CoA)

CofactorAmountATP equivalent
NADH33 × 2.5 = 7.5 ATP
FADH211 × 1.5 = 1.5 ATP
GTP11 ATP
Total per Acetyl-CoA~10 ATP
Per glucose (2 Acetyl-CoA): ~20 ATP from TCA cycle

Regulation

  • Citrate synthase: Inhibited by ATP, NADH, succinyl-CoA
  • Isocitrate dehydrogenase: Activated by ADP, Ca2+; inhibited by ATP, NADH
  • α-Ketoglutarate dehydrogenase: Activated by Ca2+; inhibited by NADH, succinyl-CoA

Importance of TCA Cycle

  1. Primary source of energy - generates most ATP via oxidative phosphorylation
  2. Amphibolic pathway - both catabolic and anabolic:
    • Provides precursors: OAA → aspartate/amino acids; α-KG → glutamate
    • Succinyl-CoA → heme synthesis (porphyrins)
    • Citrate → exported for fatty acid synthesis
  3. NADH/FADH2 generated feed electron transport chain (Complex I, II)
  4. Two CO2 released per turn (carbon dioxide exits as waste)
  5. Anaplerotic reactions replenish cycle intermediates (e.g., pyruvate carboxylase: pyruvate + CO2 → OAA)

5. HMP SHUNT (Hexose Monophosphate Pathway / Pentose Phosphate Pathway)

Location: Cytosol Occurs in: Liver, adipose tissue, adrenal cortex, RBCs, lactating mammary gland, gonads

Two Phases

Oxidative Phase (irreversible) - Generates NADPH

  1. Glucose-6-phosphate → 6-Phosphogluconolactone - by G6P Dehydrogenase (rate-limiting; generates NADPH)
  2. → 6-Phosphogluconate
  3. → Ribulose-5-phosphate + CO2 - generates another NADPH
Net: 2 NADPH + 1 CO2 per G6P

Non-Oxidative Phase (reversible) - Interconverts sugars

  • Produces Ribose-5-phosphate (for nucleotide/nucleic acid synthesis)
  • Transketolase and Transaldolase reactions interconvert C3, C4, C5, C6, C7 sugars
  • Products can feed back into glycolysis

Significance of HMP Shunt

  1. NADPH Production - most important function:
    • Maintains glutathione (GSH) in reduced form → protects RBCs from oxidative damage
    • Required for biosynthesis: fatty acids, cholesterol, steroid hormones
    • Required for phagocyte respiratory burst (NADPH oxidase)
  2. Ribose-5-phosphate synthesis - for DNA, RNA, ATP, NAD+, FAD, CoA
  3. RBC Protection - G6PD deficiency = failure to generate NADPH → oxidized Hb = Heinz bodies → hemolytic anemia triggered by oxidants (primaquine, fava beans, infections)
  4. Active in: tissues requiring NADPH for biosynthesis (liver, adipose, adrenal cortex), and all cells for antioxidant defense
G6PD Deficiency: Most common enzyme deficiency; X-linked; episodic hemolytic anemia precipitated by oxidative stress

6. GLUCONEOGENESIS

Definition: The synthesis of glucose from non-carbohydrate precursors. Occurs primarily in the liver (90%) and to a lesser extent in the kidney (10%, important during prolonged fasting).

Key Precursors (Non-Carbohydrate Sources)

  1. Lactate - from anaerobic glycolysis (muscle, RBCs) → Cori cycle: muscle lactate → liver → glucose
  2. Amino acids (especially Alanine) - Alanine cycle: muscle → transamination → alanine → liver → pyruvate → glucose
  3. Glycerol - from lipolysis of triglycerides → glycerol-3-phosphate → DHAP → enters gluconeogenesis
  4. Propionate - from odd-chain fatty acid oxidation → succinyl-CoA (TCA intermediate) → OAA → glucose
    • Note: Even-chain fatty acids CANNOT be used for gluconeogenesis (net carbon balance = 0)

The Three Unique Steps (Bypassing Irreversible Glycolytic Reactions)

Glycolytic Enzyme (irreversible)Gluconeogenic Bypass Enzyme(s)
Pyruvate kinase (PEP → Pyr)Pyruvate carboxylase (Pyr → OAA, in mitochondria, needs biotin) + PEPCK (OAA → PEP, in cytosol, needs GTP)
PFK-1 (F6P → F1,6BP)Fructose-1,6-bisphosphatase (F1,6BP → F6P); inhibited by AMP, F2,6BP
Hexokinase/Glucokinase (Glucose → G6P)Glucose-6-phosphatase (G6P → Glucose); only in liver and kidney (NOT muscle/brain)

Energy Cost of Gluconeogenesis

  • Synthesis of 1 glucose from 2 lactate requires 6 ATP equivalents
  • Synthesis from 2 pyruvate requires 4 ATP + 2 GTP + 2 NADH

Regulation

  • Insulin (fed state): Inhibits gluconeogenesis; decreases PEPCK gene expression; activates PFK-2 (raises F2,6BP, inhibiting FBPase)
  • Glucagon (fasted state): Activates gluconeogenesis via cAMP → PKA → phosphorylates PFK-2/FBPase-2 (raises FBPase-2 activity → lowers F2,6BP → activates FBPase-1)
  • Cortisol: Increases expression of gluconeogenic enzymes; provides amino acid substrates
  • Acetyl-CoA: Activates pyruvate carboxylase (signals fatty acid oxidation is occurring → gluconeogenesis needed)

7. GLYCOGENESIS (Glycogen Synthesis)

Definition: The synthesis of glycogen (a storage polymer of glucose). Occurs in liver and skeletal muscle.

Steps Involved

  1. Glucose → Glucose-6-phosphate (Hexokinase/Glucokinase; ATP consumed)
  2. G6P → Glucose-1-phosphate (Phosphoglucomutase)
  3. G1P + UTP → UDP-Glucose + PPi (UDP-Glucose Pyrophosphorylase)
    • UDP-Glucose is the activated (high-energy) form of glucose added to glycogen
  4. UDP-Glucose → Glycogen (chain elongation) - Glycogen Synthase adds glucose to the non-reducing end via α-1,4 glycosidic bonds (requires a primer - at least 4 glucose residues, initiated by glycogenin protein)
  5. Branching: When chain reaches ~11 residues, Branching Enzyme (Amylo-1,4 → 1,6-glucan transferase) moves a terminal 6-7 residue segment to create an α-1,6 branch point

Regulation of Glycogenesis

  • Insulin activates glycogen synthase (via protein phosphatase - dephosphorylates and activates synthase)
  • Glucagon/Epinephrine (via cAMP → PKA): Phosphorylates and inactivates glycogen synthase; simultaneously activates glycogen phosphorylase
  • Glucose-6-phosphate allosterically activates glycogen synthase (in muscle)

8. BLOOD GLUCOSE REGULATION

Normal Values

ConditionBlood Glucose
Normal fasting (8h fast)70-100 mg/dL (3.9-5.6 mmol/L)
Post-meal (2h postprandial)< 140 mg/dL (< 7.8 mmol/L)
Impaired fasting glucose100-125 mg/dL
Impaired glucose tolerance140-199 mg/dL at 2h OGTT
Diabetes diagnosisFasting ≥ 126 mg/dL; 2h OGTT ≥ 200 mg/dL
  • Source: Guyton & Hall: "Blood glucose concentration is normally between 80-90 mg/100 mL of blood in the fasting person each morning...increases to 120-140 mg/100 mL during the first hour after a meal."

Renal Threshold for Glucose

  • Normally, all filtered glucose is reabsorbed in the proximal convoluted tubule (by SGLT2/SGLT1 transporters)
  • Renal threshold = ~180 mg/dL (plasma glucose)
  • Above this, tubular maximum (Tm ~375 mg/min) is exceeded → glucose appears in urine (Glycosuria)

Mechanisms of Regulation

A. LIVER as Blood Glucose Buffer

  • After meal: liver removes up to 2/3 of absorbed glucose → stores as glycogen or converts to fat
  • During fasting: liver releases glucose via glycogenolysis (first 8-12h) and gluconeogenesis (beyond 12h)
  • After ~30 hours of complete fasting: glycogen depleted → gluconeogenesis is the sole source

B. Hormonal Regulation

HormoneEffect on Blood GlucoseMechanism
Insulin (β-cells, pancreas)Decreases↑ GLUT4 (muscle/adipose), ↑ glycolysis, ↑ glycogenesis, ↑ lipogenesis; ↓ gluconeogenesis, ↓ glycogenolysis
Glucagon (α-cells, pancreas)Increases↑ glycogenolysis, ↑ gluconeogenesis, ↑ lipolysis; ↓ glycolysis (via F2,6BP)
Epinephrine (adrenal medulla)Increases↑ glycogenolysis (liver + muscle via cAMP), ↑ gluconeogenesis, ↑ lipolysis
Cortisol (adrenal cortex)Increases↑ gluconeogenesis (↑ enzyme expression + provides amino acid substrates), ↓ peripheral glucose utilization
Growth HormoneIncreases↓ peripheral glucose uptake (anti-insulin), ↑ lipolysis; promotes gluconeogenesis
SomatostatinInhibitoryInhibits both insulin and glucagon secretion from pancreatic islets
GLP-1, GIP (incretins)Indirectly decreasePotentiate insulin secretion in response to glucose; inhibit glucagon
ThyroxineIncreases↑ glycogenolysis, ↑ glucose absorption from gut

C. Neural Regulation

  • Sympathetic nervous system stimulates glycogenolysis and gluconeogenesis
  • In severe hypoglycemia: hypothalamus → sympathetic activation → epinephrine release → glucose liberation from liver

D. Summary of Response to Hypoglycemia

  1. Glucagon (rapid)
  2. Epinephrine (rapid)
  3. Growth hormone (hours)
  4. Cortisol (hours to days)
  • Source: Guyton & Hall: "In severe hypoglycemia, a direct effect of low blood glucose on the hypothalamus also stimulates the sympathetic nervous system."

9. GLUCOSE TOLERANCE TEST (GTT)

What is GTT?

A diagnostic test assessing the body's ability to metabolize a standard glucose load. Used to diagnose diabetes mellitus, impaired glucose tolerance, and gestational diabetes.

When is GTT Performed?

  • Suspected Type 2 Diabetes Mellitus
  • Screening for Gestational Diabetes Mellitus (GDM) at 24-28 weeks gestation
  • Impaired fasting glucose (borderline values)
  • Suspected reactive hypoglycemia
  • When HbA1c is unreliable (hemolytic anemia, hemoglobinopathies)

How is GTT Performed? (Oral GTT - OGTT)

Preparation:
  • 3 days of unrestricted diet (≥150g carbohydrate/day)
  • 8-12 hours overnight fast
  • No medications, smoking, or vigorous exercise on test day
  • Patient must be ambulatory and not acutely ill
Procedure:
  1. Fasting blood glucose sample drawn (0 min)
  2. Patient drinks 75g anhydrous glucose dissolved in 250-300 mL water over 5 minutes (adults)
    • For GDM screening: 75g (WHO) or 100g (older Carpenter-Coustan criteria)
    • Children: 1.75 g/kg body weight (max 75g)
  3. Blood samples drawn at 1 hour and 2 hours (standard OGTT)
    • Urine may also be tested at each interval
Interpretation (75g OGTT, ADA criteria):
CategoryFasting2-hour
Normal< 100 mg/dL< 140 mg/dL
Impaired Glucose Tolerance100-125 mg/dL140-199 mg/dL
Diabetes Mellitus≥ 126 mg/dL≥ 200 mg/dL
Gestational Diabetes (75g OGTT, IADPSG criteria):
TimeThreshold
Fasting≥ 92 mg/dL
1 hour≥ 180 mg/dL
2 hours≥ 153 mg/dL
Any one value met = GDM diagnosis

Flat Glucose Tolerance Curve

  • Seen in: Malabsorption syndromes, Addison disease, hypothyroidism
  • Blood glucose fails to rise normally after glucose load

Lag Storage / Diabetic GTT Curve

  • In diabetes: exaggerated rise, delayed return to baseline

10. GLYCOSURIA

Definition: Presence of glucose in the urine (normally absent or trace amounts < 0.8 mmol/L).

Causes

A. Hyperglycemic Glycosuria (most common)

  • Blood glucose exceeds renal threshold (180 mg/dL) → tubular maximum exceeded
  • Causes: Diabetes mellitus, Cushing syndrome, acromegaly, pheochromocytoma, steroid use, pancreatitis

B. Renal Glycosuria (Normoglycemic)

  • Renal threshold is abnormally LOW despite normal blood glucose
  • Defect in renal tubular glucose reabsorption (SGLT2 mutation)
  • Benign renal glycosuria - no other abnormalities
  • Fanconi syndrome - generalized proximal tubule dysfunction (glycosuria + aminoaciduria + phosphaturia)

C. Other

  • Pregnancy: increased GFR lowers tubular threshold → physiological glycosuria
  • Alimentary glycosuria: rapid glucose absorption post-gastrectomy

Detection

  • Specific glucose dipstick (glucose oxidase) - only detects glucose
  • Reducing sugar test (Benedict's/Fehling's) - detects all reducing sugars (glucose, galactose, fructose, lactose)
    • Important in neonates: Galactosemia causes reducing sugar in urine but NOT on glucose-specific dipstick

QUICK SUMMARY TABLE: ATP Yield from Complete Glucose Oxidation

StageATP Yield
Glycolysis (net)2 ATP
Glycolysis NADH (×2, via malate-aspartate shuttle)5 ATP
Pyruvate → Acetyl-CoA (×2 NADH)5 ATP
TCA Cycle (×2 turns)20 ATP (from NADH/FADH2)
TCA GTP (×2)2 ATP
Total~30-32 ATP

KEY MNEMONICS

Glycolysis 10 steps: "Goodness Gracious, Father Franklin Did Go By Picking Peas" (Glucose → G6P → F6P → F1,6BP → DHAP/G3P → 1,3BPG → 3PG → 2PG → PEP → Pyruvate)
TCA cycle intermediates: "Citrate Is Krebs' Starting Substrate For Making Oxaloacetate" (Citrate → Isocitrate → α-Ketoglutarate → Succinyl-CoA → Succinate → Fumarate → Malate → Oxaloacetate)
Gluconeogenic precursors: "GOAL" = Glycerol, Odd-chain fatty acids, Amino acids, Lactate

Sources: Basic Medical Biochemistry - A Clinical Approach 6e; Guyton and Hall Textbook of Medical Physiology; Tietz Textbook of Laboratory Medicine 7e; Goodman & Gilman's Pharmacological Basis of Therapeutics

Can explain it In easy launguage

Carbohydrates & Glucose Metabolism - Simple Language Explanation 🍬


1. CLASSIFICATION OF CARBOHYDRATES

"Think of carbs like LEGO blocks"

Carbohydrates are basically sugar molecules. They come in different sizes:

🔹 Monosaccharides = Single LEGO block

  • The smallest unit - cannot be broken down further
  • Examples:
    • Glucose - the main fuel of your body (like petrol for a car)
    • Fructose - sugar in fruits
    • Galactose - sugar in milk
    • Ribose - building block of DNA/RNA

🔹 Disaccharides = 2 LEGO blocks joined together

NameMade ofFound in
SucroseGlucose + FructoseTable sugar
LactoseGlucose + GalactoseMilk
MaltoseGlucose + GlucoseSprouted grains

🔹 Polysaccharides = Many LEGO blocks joined in a long chain

A. Homopolysaccharides = All same blocks

"Homo" = same
NameWhat it isWhere
StarchPlant's way of storing glucoseRice, wheat, potato
GlycogenHuman body's way of storing glucoseLiver & muscle
CelluloseStructural support in plantsVegetable fiber (we can't digest it)
InulinMade of fructose unitsUsed in lab to measure kidney filtration

B. Mucopolysaccharides (GAGs) = Mixed blocks with extra features

Think of these as the "jelly" or "glue" between your body's cells
  • They are long chains made of two alternating sugar units
  • They are negatively charged so they attract water - this makes them thick and gel-like
  • They form the ground substance of connective tissue (like the filling in a cushion)
NameWhere foundWhat it does
Hyaluronic acidKnee joint fluid, eyeActs as a lubricant/shock absorber
Chondroitin sulfateCartilage, boneGives cartilage its strength
HeparinMast cells, bloodPrevents blood clotting
Keratan sulfateCornea, cartilageMaintains cornea transparency
⚠️ Disease alert: If enzymes that break down these GAGs are missing → they accumulate → Mucopolysaccharidoses (e.g., Hurler syndrome - children with coarse facial features, short stature, mental retardation)

2. WHAT HAPPENS TO GLUCOSE IN YOUR BODY?

"Think of glucose as money - you can spend it, save it, or invest it"

When you eat rice/bread, glucose enters your blood. Your body then:
                    GLUCOSE (enters blood)
                         |
          ┌──────────────┼──────────────────┐
          |              |                  |
    BURN IT          STORE IT          CONVERT IT
    (for energy)    (for later)       (to other things)
          |              |                  |
     Glycolysis      Glycogenesis      → Fat (lipogenesis)
    → TCA Cycle    (liver + muscle)   → Amino sugars
    → ATP (energy)                    → Ribose (for DNA)
                                      → HMP Shunt (NADPH)

3. GLYCOLYSIS

"Breaking glucose for energy - like burning money for heat"

What: Breakdown of 1 glucose molecule into 2 pyruvate molecules Where: Cytoplasm (cytosol) of EVERY cell Needs oxygen? NO - works with OR without oxygen (that's why it's so important)

Think of it in 2 simple phases:

🔴 Phase 1: INVESTMENT Phase (spend 2 ATP to "prime the pump")

You spend 2 ATP to trap and split glucose
Glucose
  ↓ (Hexokinase/Glucokinase) [uses 1 ATP]
Glucose-6-Phosphate  ← Branch point: can go to glycogen, HMP shunt, or continue
  ↓
Fructose-6-Phosphate
  ↓ (PFK-1) ← THE MOST IMPORTANT CONTROL POINT (rate-limiting step)
Fructose-1,6-Bisphosphate
  ↓ (Aldolase) ← Splits into two 3-carbon pieces
DHAP + Glyceraldehyde-3-P (G3P)
🔑 PFK-1 is the traffic light of glycolysis:
  • Green light (activate): Low energy (AMP, ADP), insulin → "Keep burning glucose"
  • Red light (inhibit): High energy (ATP), citrate → "We have enough energy, stop"

🟢 Phase 2: PAYOFF Phase (earn 4 ATP + 2 NADH)

Both G3P molecules go through 5 more steps to produce energy
G3P (×2)
  ↓ (makes NADH)
1,3-Bisphosphoglycerate
  ↓ (makes ATP ×2) ← Substrate-level phosphorylation
3-Phosphoglycerate
  ↓
2-Phosphoglycerate
  ↓ (Enolase - inhibited by fluoride)
Phosphoenolpyruvate (PEP)
  ↓ (Pyruvate Kinase - makes ATP ×2)
PYRUVATE ✓

Final Score of Glycolysis:

What you getAmount
ATP (net)2 ATP
NADH2 NADH
Pyruvate2 molecules

What happens to Pyruvate next?

            PYRUVATE
               |
    ┌──────────┴────────────┐
    |                       |
  O2 available           No O2
  (aerobic)              (anaerobic)
    |                       |
Acetyl-CoA              LACTATE
(enters TCA cycle)      (by Lactate Dehydrogenase)
    |
More ATP!               Only 2 ATP total
(~30 ATP total          Used in: RBCs, hard-working muscles
 from 1 glucose)        → causes "muscle burn" feeling!

4. TCA CYCLE (Krebs Cycle)

"The body's main power plant - like a turbine that keeps spinning"

What: A circular series of reactions that completely burns Acetyl-CoA to CO2 and captures energy as NADH/FADH2 Where: Mitochondrial matrix (the "powerhouse of the cell") Entry point: Acetyl-CoA (2 carbons) combines with Oxaloacetate (4 carbons) = Citrate (6 carbons)

The 8 Steps - Easy Memory Version:

Oxaloacetate (4C) + Acetyl-CoA (2C)
         ↓ [Citrate Synthase]
    CITRATE (6C) 🍋
         ↓
   ISOCITRATE (6C)
         ↓ [Isocitrate Dehydrogenase] ← RATE-LIMITING STEP
    α-KETOGLUTARATE (5C) + CO2 + NADH
         ↓ [α-KG Dehydrogenase]
    SUCCINYL-CoA (4C) + CO2 + NADH
         ↓ [Succinyl-CoA Synthetase]
    SUCCINATE (4C) + GTP ← Energy!
         ↓ [Succinate Dehydrogenase] ← Only FAD-linked step
    FUMARATE (4C) + FADH2
         ↓ [Fumarase]
    MALATE (4C)
         ↓ [Malate Dehydrogenase]
    OXALOACETATE (4C) + NADH ← Ready for next round!
Mnemonic: "Citrate Is Krebs' Starting Substrate For Making OAA" (Citrate → Isocitrate → α-Ketoglutarate → Succinyl-CoA → Succinate → Fumarate → Malate → OAA)

Energy from 1 turn of TCA:

ProductAmountATP equivalent
NADH37.5 ATP
FADH211.5 ATP
GTP11 ATP
Total~10 ATP per Acetyl-CoA

Why is TCA Important? (Beyond just energy)

  1. CO2 is released - you breathe it out
  2. Provides building blocks for amino acids, heme (in hemoglobin), fat synthesis
  3. NADH/FADH2 feeds the electron transport chain → most of your body's ATP
  4. It is "amphibolic" - both breaks things down AND builds things up

Total ATP from 1 Glucose (Full Oxidation):

StageATP
Glycolysis2
Pyruvate → Acetyl-CoA (×2)5
TCA cycle (×2 turns)20
Subtotal from NADH/FADH2 via ETC5
Grand Total~30-32 ATP

5. HMP SHUNT (Pentose Phosphate Pathway)

"The 'side road' of glucose metabolism - not for energy, but for protection and building"

What: An alternate pathway glucose can take instead of glycolysis Where: Cytosol - especially active in liver, RBCs, adrenal gland, testes/ovaries

Think of HMP Shunt as having 2 jobs:

Job 1: Make NADPH (Protective role) 🛡️

  • NADPH keeps Glutathione (GSH) in its active reduced form
  • Glutathione neutralizes free radicals and peroxides that would otherwise destroy RBCs
  • Also needed for: fatty acid synthesis, steroid hormone synthesis, immune cell killing (NADPH oxidase)

Job 2: Make Ribose-5-Phosphate (Building role) 🏗️

  • Ribose is needed to make DNA, RNA, ATP, NAD+, FAD, CoA
  • Important in rapidly dividing cells

The Key Enzyme: Glucose-6-Phosphate Dehydrogenase (G6PD)

  • This is the rate-limiting enzyme of the oxidative phase
  • If G6PD is missing → no NADPH → RBCs get destroyed by oxidative stress
⚠️ G6PD Deficiency:
  • Most common enzyme deficiency in the world
  • X-linked (males affected more)
  • Triggers: Primaquine (malaria drug), Dapsone, Sulfonamides, Fava beans, Infections
  • Result: Hemolytic anemia (RBCs burst)
  • Heinz bodies seen on peripheral smear (denatured Hb)

6. GLUCONEOGENESIS

"Making glucose from scratch when food isn't available - like emergency power generation"

What: Synthesis of new glucose from non-carbohydrate sources Where: Mainly liver (90%), some in kidney (10%) When: During fasting, starvation, prolonged exercise, stress

Where does the raw material come from?

SourceHow it enters gluconeogenesisExample
Lactate→ Pyruvate (via LDH)Muscles working hard → send lactate to liver (Cori Cycle)
Amino acids (Alanine)→ Pyruvate (via transamination)Muscle proteins broken down during starvation (Alanine Cycle)
Glycerol→ DHAPFat stores broken down → glycerol released
Odd-chain fatty acids→ Succinyl-CoA → OAARare, but possible
Even-chain fatty acids CANNOT make glucose - they only make Acetyl-CoA which cannot be converted to glucose in humans

Gluconeogenesis is mostly the REVERSE of glycolysis - BUT 3 steps are different:

Think of it like a one-way street: glycolysis goes forward, but 3 steps are so energetically unfavorable to reverse that you need special enzymes to go backward:
Problem StepGlycolysis enzyme (irreversible)Gluconeogenesis solution
Pyruvate → PEPPyruvate kinase (can't reverse)Pyruvate Carboxylase (Pyr→OAA, needs biotin) + PEPCK (OAA→PEP)
F6P → F1,6BPPFK-1 (can't reverse)Fructose-1,6-Bisphosphatase
Glucose → G6PHexokinase (can't reverse)Glucose-6-Phosphatase (only in liver & kidney!)
💡 This is why muscle glycogen cannot directly release glucose into blood - muscle lacks G-6-Phosphatase!

7. GLYCOGENESIS (Making Glycogen)

"Saving glucose as glycogen - like putting money in a piggy bank"

What: Converting glucose into glycogen for storage Where: Liver (for blood glucose maintenance) and Muscle (for local use)

Steps (Simple):

Step 1: Glucose → Glucose-6-Phosphate  [Hexokinase, uses ATP]
            ↓
Step 2: G6P → Glucose-1-Phosphate  [Phosphoglucomutase]
            ↓
Step 3: G1P + UTP → UDP-Glucose  ← "Activated glucose" ready to be added
            ↓
Step 4: UDP-Glucose added to glycogen chain  [Glycogen Synthase] → α-1,4 bonds (straight chain)
            ↓
Step 5: Branching Enzyme creates α-1,6 branch points (every ~10 units)
🌿 Branching is important because it:
  • Makes glycogen more soluble (less compact)
  • Creates more free ends → faster breakdown when needed
Control:
  • Insulin → activates glycogen synthase → stores glucose (after a meal)
  • Glucagon/Adrenaline → inactivates glycogen synthase → breaks down glycogen (during fasting/stress)

8. BLOOD GLUCOSE REGULATION

"Your body keeps blood sugar in a very tight range - like a thermostat"

Normal Values - Must Know:

SituationNormal Range
Fasting blood glucose70-100 mg/dL
2 hours after meal< 140 mg/dL
Renal threshold (glucose appears in urine)~180 mg/dL

The Main Regulators:

🔽 Insulin - "The Storage Hormone" (LOWERS blood glucose)

  • Made by Beta (β) cells of pancreatic islets of Langerhans
  • Released when blood glucose rises after a meal
  • Actions:
    • Opens GLUT4 channels in muscle and fat → glucose enters cells
    • Promotes glycogen storage in liver and muscle
    • Promotes fat synthesis
    • Blocks gluconeogenesis and glycogenolysis

🔼 Glucagon - "The Fasting Hormone" (RAISES blood glucose)

  • Made by Alpha (α) cells of pancreatic islets
  • Released when blood glucose falls during fasting
  • Actions:
    • Breaks down liver glycogen (glycogenolysis)
    • Stimulates gluconeogenesis in liver
    • Stimulates fat breakdown

All Hormones at a Glance:

HormoneBlood Glucose EffectSimple Way to Remember
Insulin↓ Decreases"INsulin = INto cells = Decreases blood sugar"
Glucagon↑ Increases"GLUCAgon = GLUCose Agonist = Raises blood sugar"
Cortisol↑ IncreasesStress hormone → needs more glucose
Epinephrine (Adrenaline)↑ IncreasesFight-or-flight → needs quick energy
Growth Hormone↑ IncreasesAnti-insulin effect
SomatostatinBoth ↓Inhibits both insulin AND glucagon
Thyroxine (T4)↑ IncreasesSpeeds up glycogen breakdown

How the body responds to LOW blood sugar (Hypoglycemia):

Blood glucose falls below ~70 mg/dL
        ↓
Glucagon released (from α-cells) → Liver breaks glycogen → glucose out
        ↓ (if still low)
Epinephrine released → Emergency glycogen breakdown
        ↓ (if prolonged fasting)
Cortisol + Growth Hormone → Reduce glucose use by muscles → save for brain
        ↓
Gluconeogenesis in liver → Makes new glucose from lactate/amino acids/glycerol

9. GLUCOSE TOLERANCE TEST (GTT)

"Checking how well your body handles a sugar load - like a stress test for sugar metabolism"


When is it Done?

  • Suspected diabetes but fasting glucose is borderline (100-125 mg/dL)
  • Gestational diabetes screening (24-28 weeks pregnancy - mandatory!)
  • When HbA1c results are unreliable (e.g., in hemolytic anemia)
  • Suspected reactive hypoglycemia

How is it Done? (Standard 75g OGTT)

STEP 1: Fast for 8-12 hours overnight (no food, only water)
         ↓
STEP 2: Draw fasting blood sample (time = 0 min)
         ↓
STEP 3: Drink 75g glucose dissolved in water
         ↓
STEP 4: Draw blood at 1 hour and 2 hours
         ↓
STEP 5: Compare results with normal ranges
Preparation rules:
  • Eat normally (150g+ carbs/day) for 3 days before
  • No heavy exercise, smoking, or illness on test day
  • Stop medications that affect glucose (if possible)

Results Interpretation:

CategoryFasting2-Hour
✅ Normal< 100 mg/dL< 140 mg/dL
⚠️ Pre-diabetes100-125 mg/dL140-199 mg/dL
🔴 Diabetes≥ 126 mg/dL≥ 200 mg/dL

Gestational Diabetes (GDM) - 75g OGTT:

Any ONE value met or exceeded = GDM diagnosis
  • Fasting: ≥ 92 mg/dL
  • 1 hour: ≥ 180 mg/dL
  • 2 hours: ≥ 153 mg/dL

10. GLYCOSURIA

"Sugar in the urine - normally ZERO glucose should spill into urine"

Normal: Kidneys reabsorb ALL filtered glucose back into blood Renal threshold: When blood glucose exceeds ~180 mg/dL, kidneys can't reabsorb all of it → glucose spills into urine

Causes:

Type 1 - High Blood Sugar (Most common)

Blood sugar so high it overflows → Diabetes mellitus (classic symptom)
  • Also in: Cushing's syndrome, steroid use, pancreatitis

Type 2 - Kidney Problem (Blood sugar is NORMAL)

Kidney can't reabsorb glucose properly even at normal blood sugar
  • Benign Renal Glycosuria - just a genetic variant, harmless
  • Fanconi Syndrome - proximal tubule damaged → loses glucose + amino acids + phosphate
  • Pregnancy - increased kidney filtration rate → glucose spills even at normal levels

How Glycosuria is Detected:

TestWhat it detectsClinical use
Glucose oxidase dipstickOnly glucose (specific)Diabetes monitoring
Benedict's/Fehling's testAll reducing sugars (glucose, galactose, fructose)Screening newborns for metabolic disorders
⚠️ Important: In galactosemia (newborn), Benedict's test is positive but glucose dipstick is negative - because galactose (not glucose) is in the urine!

MASTER SUMMARY - One-Page Review

CARBS → DIGESTION → GLUCOSE (in blood)
                         |
              ┌──────────┼──────────────┐
              |          |              |
           GLYCOLYSIS  GLYCOGENESIS   HMP SHUNT
           (cytosol)   (liver/muscle) (liver/RBCs)
           Glucose→     Store as        Make NADPH
           Pyruvate     Glycogen        + Ribose
           +2 ATP       ↕ Glycogenolysis
              |
         PYRUVATE
              |
      ┌───────┴────────┐
    O2 present       No O2
      |                 |
  Acetyl-CoA         LACTATE
      |              (→ Cori cycle
    TCA Cycle          → back to liver
    +~28 ATP            → Gluconeogenesis)
              |
          CO2 + H2O
          (~30 ATP total)

FASTING STATE:
GLUCONEOGENESIS: Lactate + Amino acids + Glycerol → NEW GLUCOSE

Sources: Basic Medical Biochemistry 6e | Guyton & Hall Physiology | Tietz Laboratory Medicine 7e

Create a study guide PDF I can download and print

Reading File
Running Command

mkdir -p /home/daytona/workspace/carb-studyguide && ls /home/daytona/workspace/c…

Writing File

~/carb-studyguide/generate_pdf.py

from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import cm, mm
from reportlab.lib.colors import (HexColor, white, black, Color)
from reportlab.platypus import (
    SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle,
    HRFlowable, PageBreak, KeepTogether
)
from reportlab.lib.enums import TA_LEFT, TA_CENTER, TA_JUSTIFY
from reportlab.platypus.flowables import Flowable
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
import os

# ── Colors ──────────────────────────────────────────────────────────────────
C_DARK_BLUE   = HexColor('#1a3a5c')
C_MED_BLUE    = HexColor('#2563a8')
C_LIGHT_BLUE  = HexColor('#dbeafe')
C_ACCENT      = HexColor('#e63946')
C_GREEN       = HexColor('#16a34a')
C_GREEN_LIGHT = HexColor('#dcfce7')
C_ORANGE      = HexColor('#ea580c')
C_ORANGE_LIGHT= HexColor('#fff7ed')
C_YELLOW_LIGHT= HexColor('#fefce8')
C_YELLOW      = HexColor('#ca8a04')
C_PURPLE      = HexColor('#7c3aed')
C_PURPLE_LIGHT= HexColor('#f5f3ff')
C_GRAY_LIGHT  = HexColor('#f1f5f9')
C_GRAY_MED    = HexColor('#64748b')
C_GRAY_DARK   = HexColor('#334155')
C_TABLE_HDR   = HexColor('#1e40af')
C_TABLE_ALT   = HexColor('#eff6ff')

W = A4[0] - 2*cm  # usable width

# ── Styles ───────────────────────────────────────────────────────────────────
styles = getSampleStyleSheet()

def S(name, **kw):
    return ParagraphStyle(name, **kw)

TITLE_STYLE = S('Title',
    fontSize=26, textColor=white, fontName='Helvetica-Bold',
    alignment=TA_CENTER, spaceAfter=4)

SUBTITLE_STYLE = S('Subtitle',
    fontSize=12, textColor=HexColor('#bfdbfe'), fontName='Helvetica',
    alignment=TA_CENTER, spaceAfter=2)

H1 = S('H1',
    fontSize=14, textColor=white, fontName='Helvetica-Bold',
    alignment=TA_LEFT, spaceBefore=4, spaceAfter=4,
    leftIndent=0, borderPadding=(6,8,6,8))

H2 = S('H2',
    fontSize=12, textColor=C_DARK_BLUE, fontName='Helvetica-Bold',
    spaceBefore=10, spaceAfter=4, leftIndent=0)

H3 = S('H3',
    fontSize=10.5, textColor=C_MED_BLUE, fontName='Helvetica-Bold',
    spaceBefore=8, spaceAfter=3, leftIndent=0)

BODY = S('Body',
    fontSize=9.5, textColor=C_GRAY_DARK, fontName='Helvetica',
    leading=14, spaceBefore=2, spaceAfter=2, alignment=TA_JUSTIFY)

BODY_BOLD = S('BodyBold',
    fontSize=9.5, textColor=C_GRAY_DARK, fontName='Helvetica-Bold',
    leading=14, spaceBefore=2, spaceAfter=2)

BULLET = S('Bullet',
    fontSize=9.5, textColor=C_GRAY_DARK, fontName='Helvetica',
    leading=14, spaceBefore=1, spaceAfter=1,
    leftIndent=14, bulletIndent=4)

BULLET2 = S('Bullet2',
    fontSize=9, textColor=C_GRAY_DARK, fontName='Helvetica',
    leading=13, spaceBefore=1, spaceAfter=1,
    leftIndent=28, bulletIndent=18)

NOTE = S('Note',
    fontSize=9, textColor=C_ORANGE, fontName='Helvetica-BoldOblique',
    leading=13, spaceBefore=3, spaceAfter=3,
    leftIndent=10, borderPadding=4)

MNEMONIC = S('Mnemonic',
    fontSize=9.5, textColor=C_PURPLE, fontName='Helvetica-Bold',
    leading=14, spaceBefore=2, spaceAfter=2,
    leftIndent=10)

CODE = S('Code',
    fontSize=8.5, textColor=C_DARK_BLUE, fontName='Courier-Bold',
    leading=12, spaceBefore=1, spaceAfter=1,
    leftIndent=20)

CAPTION = S('Caption',
    fontSize=8, textColor=C_GRAY_MED, fontName='Helvetica-Oblique',
    alignment=TA_CENTER, spaceBefore=2, spaceAfter=4)

# ── Helper Flowables ─────────────────────────────────────────────────────────
class ColorBox(Flowable):
    """A colored rectangle used as section header background."""
    def __init__(self, text, bg_color, text_color=white, height=28, fontsize=13):
        Flowable.__init__(self)
        self.text = text
        self.bg_color = bg_color
        self.text_color = text_color
        self.height = height
        self.fontsize = fontsize
        self.width = W

    def draw(self):
        c = self.canv
        c.setFillColor(self.bg_color)
        c.roundRect(0, 0, self.width, self.height, 5, fill=1, stroke=0)
        c.setFillColor(self.text_color)
        c.setFont('Helvetica-Bold', self.fontsize)
        c.drawString(10, 8, self.text)

    def wrap(self, *args):
        return (self.width, self.height + 4)

class InfoBox(Flowable):
    """Colored info/alert box."""
    def __init__(self, lines, bg_color, border_color, label='', width=None):
        Flowable.__init__(self)
        self.lines = lines
        self.bg_color = bg_color
        self.border_color = border_color
        self.label = label
        self._width = width or W

    def wrap(self, avail_w, avail_h):
        self.width = self._width
        self.height = 14 * len(self.lines) + 16
        return (self.width, self.height)

    def draw(self):
        c = self.canv
        h = self.height
        c.setFillColor(self.bg_color)
        c.roundRect(0, 0, self.width, h, 5, fill=1, stroke=0)
        c.setStrokeColor(self.border_color)
        c.setLineWidth(1.5)
        c.roundRect(0, 0, self.width, h, 5, fill=0, stroke=1)
        c.setFillColor(self.border_color)
        if self.label:
            c.setFont('Helvetica-Bold', 9)
            c.drawString(10, h - 14, self.label)
        c.setFillColor(C_GRAY_DARK)
        c.setFont('Helvetica', 9)
        for i, line in enumerate(self.lines):
            y = h - 14 - (14 * i) - (14 if self.label else 0)
            if line.startswith('**') and line.endswith('**'):
                c.setFont('Helvetica-Bold', 9)
                c.drawString(12, y, line.strip('*'))
                c.setFont('Helvetica', 9)
            else:
                c.drawString(12, y, line)

def sp(h=4):
    return Spacer(1, h)

def hr(color=C_LIGHT_BLUE):
    return HRFlowable(width='100%', thickness=1, color=color, spaceAfter=4, spaceBefore=4)

def make_table(data, col_widths=None, header_bg=C_TABLE_HDR, alt_bg=C_TABLE_ALT):
    style = TableStyle([
        ('BACKGROUND',   (0,0), (-1,0), header_bg),
        ('TEXTCOLOR',    (0,0), (-1,0), white),
        ('FONTNAME',     (0,0), (-1,0), 'Helvetica-Bold'),
        ('FONTSIZE',     (0,0), (-1,0), 9),
        ('FONTNAME',     (0,1), (-1,-1), 'Helvetica'),
        ('FONTSIZE',     (0,1), (-1,-1), 8.5),
        ('TEXTCOLOR',    (0,1), (-1,-1), C_GRAY_DARK),
        ('ROWBACKGROUNDS',(0,1),(-1,-1), [white, alt_bg]),
        ('GRID',         (0,0), (-1,-1), 0.5, HexColor('#cbd5e1')),
        ('VALIGN',       (0,0), (-1,-1), 'MIDDLE'),
        ('LEFTPADDING',  (0,0), (-1,-1), 6),
        ('RIGHTPADDING', (0,0), (-1,-1), 6),
        ('TOPPADDING',   (0,0), (-1,-1), 4),
        ('BOTTOMPADDING',(0,0), (-1,-1), 4),
        ('ROWBACKGROUNDS',(0,0),(-1,0), [header_bg]),
    ])
    t = Table(data, colWidths=col_widths, repeatRows=1)
    t.setStyle(style)
    return t

def two_col_table(left_data, right_data, left_w=None, right_w=None):
    """Place two tables side by side."""
    lw = left_w or W*0.48
    rw = right_w or W*0.48
    gap = W - lw - rw
    combined = Table([[left_data, Spacer(gap, 1), right_data]],
                     colWidths=[lw, gap, rw])
    combined.setStyle(TableStyle([
        ('VALIGN', (0,0), (-1,-1), 'TOP'),
        ('LEFTPADDING', (0,0), (-1,-1), 0),
        ('RIGHTPADDING', (0,0), (-1,-1), 0),
    ]))
    return combined

# ── Cover page builder ───────────────────────────────────────────────────────
class CoverPage(Flowable):
    def __init__(self, width, height):
        Flowable.__init__(self)
        self.pg_width = width
        self.pg_height = height

    def wrap(self, *args):
        return (self.pg_width, self.pg_height)

    def draw(self):
        c = self.canv
        w, h = self.pg_width, self.pg_height
        # background gradient simulation
        c.setFillColor(C_DARK_BLUE)
        c.rect(0, 0, w, h, fill=1, stroke=0)
        # accent strip
        c.setFillColor(C_MED_BLUE)
        c.rect(0, h*0.35, w, h*0.3, fill=1, stroke=0)
        # decorative circles
        c.setFillColor(HexColor('#ffffff15'))
        c.circle(w*0.85, h*0.8, 120, fill=1, stroke=0)
        c.circle(w*0.1, h*0.15, 80, fill=1, stroke=0)
        # Title
        c.setFillColor(white)
        c.setFont('Helvetica-Bold', 32)
        c.drawCentredString(w/2, h*0.62, 'CARBOHYDRATES &')
        c.drawCentredString(w/2, h*0.55, 'GLUCOSE METABOLISM')
        # Subtitle
        c.setFont('Helvetica', 14)
        c.setFillColor(HexColor('#bfdbfe'))
        c.drawCentredString(w/2, h*0.48, 'Complete Study Guide')
        # divider
        c.setStrokeColor(C_ACCENT)
        c.setLineWidth(3)
        c.line(w*0.2, h*0.44, w*0.8, h*0.44)
        # Topics
        c.setFont('Helvetica-Bold', 10)
        c.setFillColor(white)
        topics = [
            '• Classification of Carbohydrates',
            '• Glycolysis & Energetics',
            '• TCA Cycle (Krebs Cycle)',
            '• HMP Shunt / Pentose Phosphate Pathway',
            '• Gluconeogenesis & Glycogenesis',
            '• Blood Glucose Regulation',
            '• Glucose Tolerance Test (GTT)',
            '• Glycosuria & Clinical Conditions',
        ]
        y = h*0.40
        for t in topics:
            c.drawCentredString(w/2, y, t)
            y -= 18
        # footer
        c.setFont('Helvetica', 9)
        c.setFillColor(HexColor('#94a3b8'))
        c.drawCentredString(w/2, 30, 'Sources: Basic Medical Biochemistry 6e  |  Guyton & Hall Physiology  |  Tietz Laboratory Medicine 7e')

# ── Build Story ───────────────────────────────────────────────────────────────
def build():
    path = '/home/daytona/workspace/carb-studyguide/Carbohydrates_Glucose_Metabolism_StudyGuide.pdf'
    doc = SimpleDocTemplate(
        path, pagesize=A4,
        leftMargin=1*cm, rightMargin=1*cm,
        topMargin=1.2*cm, bottomMargin=1.2*cm,
        title='Carbohydrates & Glucose Metabolism Study Guide',
        author='Orris Medical'
    )

    story = []

    # ── COVER ─────────────────────────────────────────────────────────────────
    story.append(CoverPage(A4[0], A4[1]))
    story.append(PageBreak())

    # ── SECTION 1: Classification ─────────────────────────────────────────────
    story.append(ColorBox('1.  CLASSIFICATION OF CARBOHYDRATES', C_DARK_BLUE))
    story.append(sp(6))

    story.append(Paragraph('Carbohydrates are polyhydroxy aldehydes or ketones - basically sugar molecules of different sizes.', BODY))
    story.append(sp(4))

    # Monosaccharides
    story.append(Paragraph('Monosaccharides  (Single sugar unit - cannot be broken down further)', H2))
    data = [['Sugar', 'Type', 'Key Role'],
            ['Glucose', 'Aldohexose', 'Primary fuel of the body'],
            ['Fructose', 'Ketohexose', 'Fruit sugar; enters glycolysis as F6P'],
            ['Galactose', 'Aldohexose', 'Milk sugar component'],
            ['Ribose', 'Aldopentose', 'Backbone of RNA, ATP, NAD+'],
            ['Deoxyribose', 'Deoxypentose', 'Backbone of DNA']]
    story.append(make_table(data, col_widths=[W*0.25, W*0.25, W*0.5]))
    story.append(sp(6))

    # Disaccharides
    story.append(Paragraph('Disaccharides  (Two monosaccharide units)', H2))
    data = [['Name', 'Components', 'Bond', 'Source'],
            ['Sucrose', 'Glucose + Fructose', 'α1,β2', 'Table sugar'],
            ['Lactose', 'Glucose + Galactose', 'β1,4', 'Milk (lactase deficiency = bloating)'],
            ['Maltose', 'Glucose + Glucose', 'α1,4', 'Malt, starch digestion product']]
    story.append(make_table(data, col_widths=[W*0.18, W*0.28, W*0.14, W*0.40]))
    story.append(sp(6))

    # Polysaccharides
    story.append(Paragraph('Polysaccharides  (Many sugar units)', H2))
    story.append(Paragraph('<b>A. Homopolysaccharides</b> — all units are the SAME monosaccharide', H3))
    data = [['Name', 'Monomer', 'Linkage', 'Location / Function'],
            ['Starch (Amylose)', 'Glucose', 'α-1,4', 'Plant storage; linear chain'],
            ['Starch (Amylopectin)', 'Glucose', 'α-1,4 + α-1,6 branches', 'Plant storage; branched (every 24-30 units)'],
            ['Glycogen', 'Glucose', 'α-1,4 + α-1,6 branches', 'Animal storage; liver & muscle (more branched)'],
            ['Cellulose', 'Glucose', 'β-1,4', 'Plant cell wall; not digestible by humans'],
            ['Dextran', 'Glucose', 'α-1,6', 'Bacterial; used as plasma volume expander'],
            ['Inulin', 'Fructose', 'β-2,1', 'Lab: used to measure GFR (freely filtered, not reabsorbed)'],
            ['Chitin', 'N-Acetylglucosamine', 'β-1,4', 'Insect exoskeletons, fungal cell walls']]
    story.append(make_table(data, col_widths=[W*0.22, W*0.18, W*0.22, W*0.38]))
    story.append(sp(8))

    story.append(Paragraph('<b>B. Mucopolysaccharides (Glycosaminoglycans / GAGs)</b> — alternating disaccharide units, highly negatively charged, attract water → form gel-like ground substance of connective tissue', H3))
    data = [['GAG', 'Composition', 'Key Location', 'Function'],
            ['Hyaluronic acid', 'GlcUA + GlcNAc', 'Synovial fluid, vitreous humor', 'Lubrication, shock absorption'],
            ['Chondroitin sulfate', 'GlcUA + GalNAc-SO4', 'Cartilage, bone, cornea', 'Structural support'],
            ['Dermatan sulfate', 'IdoUA + GalNAc-SO4', 'Skin, blood vessels', 'Structural, anticoagulant'],
            ['Heparin / Heparan sulfate', 'IdoUA/GlcUA + GlcNH2', 'Mast cells, blood vessel walls', 'Anticoagulant (activates antithrombin III)'],
            ['Keratan sulfate', 'Galactose + GlcNAc-SO4', 'Cornea, cartilage, bone', 'Corneal transparency']]
    story.append(make_table(data, col_widths=[W*0.22, W*0.25, W*0.28, W*0.25]))
    story.append(sp(4))
    story.append(InfoBox(
        ['⚠  CLINICAL: Mucopolysaccharidoses — deficiency of lysosomal enzymes that degrade GAGs',
         '   → GAGs accumulate in tissues → coarse facies, organomegaly, skeletal deformity, mental retardation',
         '   Hurler syndrome: deficiency of α-L-iduronidase (AR) | Hunter syndrome: iduronate sulfatase (XR)'],
        C_ORANGE_LIGHT, C_ORANGE, ''))
    story.append(PageBreak())

    # ── SECTION 2: Fate of Glucose ────────────────────────────────────────────
    story.append(ColorBox('2.  FATE OF GLUCOSE IN THE BODY', C_MED_BLUE))
    story.append(sp(6))
    story.append(Paragraph('After absorption from the gut, glucose in the blood can take 6 pathways:', BODY))
    story.append(sp(4))
    fate_data = [
        ['Pathway', 'Product', 'Where', 'When'],
        ['Glycolysis → TCA → OXPHOS', '~30-32 ATP', 'All cells', 'Always (primary energy source)'],
        ['Glycogenesis', 'Glycogen', 'Liver, Muscle', 'Fed state (high insulin)'],
        ['Pentose Phosphate (HMP Shunt)', 'NADPH + Ribose-5-P', 'Liver, RBCs, Adrenal', 'For biosynthesis + antioxidant'],
        ['Lipogenesis', 'Triglycerides', 'Liver, Adipose', 'Excess glucose; fed state'],
        ['Glucuronate pathway', 'Glucuronic acid', 'Liver', 'Detoxification, GAG synthesis'],
        ['Excretion in urine (Glycosuria)', 'None', 'Kidney', 'Only if blood glucose > 180 mg/dL'],
    ]
    story.append(make_table(fate_data, col_widths=[W*0.30, W*0.22, W*0.22, W*0.26]))
    story.append(PageBreak())

    # ── SECTION 3: Glycolysis ─────────────────────────────────────────────────
    story.append(ColorBox('3.  GLYCOLYSIS — Pathway & Energetics', C_DARK_BLUE))
    story.append(sp(6))
    story.append(Paragraph('<b>Definition:</b> Breakdown of 1 glucose (6C) → 2 pyruvate (3C) | Location: Cytosol | Works with OR without O₂', BODY))
    story.append(sp(8))

    story.append(Paragraph('PHASE 1 — Investment Phase (spends 2 ATP)', H2))
    p1_data = [
        ['Step', 'Reaction', 'Enzyme', 'Key Points'],
        ['1', 'Glucose → Glucose-6-P', 'Hexokinase (all tissues)\nGlucokinase (liver, β-cells)', 'Uses 1 ATP; traps glucose; irreversible; Glucokinase: high Km, not saturated at normal glucose'],
        ['2', 'G6P → Fructose-6-P', 'Phosphoglucose isomerase', 'Reversible; isomerization'],
        ['3', 'F6P → Fructose-1,6-BP', 'Phosphofructokinase-1 (PFK-1)', '★ RATE-LIMITING STEP; uses 1 ATP; irreversible\nActivated by: AMP, ADP, F-2,6-BP, insulin\nInhibited by: ATP, citrate, glucagon'],
        ['4', 'F-1,6-BP → DHAP + G3P', 'Aldolase', 'Splits 6C into two 3C fragments'],
        ['5', 'DHAP ⇌ G3P', 'Triose phosphate isomerase', 'DHAP converted to G3P → both enter Phase 2'],
    ]
    story.append(make_table(p1_data, col_widths=[W*0.06, W*0.28, W*0.26, W*0.40]))
    story.append(sp(8))

    story.append(Paragraph('PHASE 2 — Payoff Phase (all steps × 2, earns 4 ATP + 2 NADH)', H2))
    p2_data = [
        ['Step', 'Reaction', 'Enzyme', 'Key Points'],
        ['6', 'G3P → 1,3-Bisphosphoglycerate', 'G3P Dehydrogenase', 'Oxidation step; produces 2 NADH (×2); uses inorganic phosphate'],
        ['7', '1,3-BPG → 3-Phosphoglycerate', 'Phosphoglycerate kinase', '2 ATP produced (×2) — substrate-level phosphorylation'],
        ['8', '3-PG → 2-Phosphoglycerate', 'Phosphoglycerate mutase', 'Shifts phosphate group'],
        ['9', '2-PG → PEP', 'Enolase', 'Inhibited by fluoride (used in fluoride tubes!)'],
        ['10', 'PEP → Pyruvate', 'Pyruvate kinase', '2 ATP produced (×2); irreversible\nInhibited by: ATP, alanine\nActivated by: F-1,6-BP (feedforward)'],
    ]
    story.append(make_table(p2_data, col_widths=[W*0.06, W*0.28, W*0.24, W*0.42]))
    story.append(sp(8))

    story.append(Paragraph('Net Energetics of Glycolysis', H2))
    net_data = [
        ['Product', 'Amount', 'Notes'],
        ['ATP (net)', '2 ATP', 'Substrate-level phosphorylation'],
        ['NADH', '2 NADH', '5 ATP if via malate-aspartate shuttle; 3 ATP via G3P shuttle'],
        ['Pyruvate', '2 molecules', 'Further oxidized aerobically or reduced to lactate anaerobically'],
    ]
    story.append(make_table(net_data, col_widths=[W*0.25, W*0.20, W*0.55]))
    story.append(sp(6))

    story.append(Paragraph('Fate of Pyruvate', H3))
    fate_pyr = [
        ['Condition', 'Product', 'Enzyme', 'Significance'],
        ['Aerobic (O₂ present)', 'Acetyl-CoA + CO₂ + NADH', 'Pyruvate Dehydrogenase Complex\n(needs: TPP, lipoate, CoA, FAD, NAD+)', 'Enters TCA cycle → ~28 more ATP'],
        ['Anaerobic (no O₂)', 'Lactate + NAD+', 'Lactate Dehydrogenase (LDH)', 'Regenerates NAD+ → glycolysis continues; Cori cycle sends lactate to liver'],
        ['In liver/yeast', 'Acetaldehyde → Ethanol', 'Pyruvate decarboxylase → Alcohol DH', 'Alcoholic fermentation'],
    ]
    story.append(make_table(fate_pyr, col_widths=[W*0.22, W*0.30, W*0.26, W*0.22]))
    story.append(sp(4))
    story.append(InfoBox(
        ['★ Mnemonic for Glycolysis steps:',
         '   "Goodness Gracious, Father Franklin Did Go By Picking Peas"',
         '   Glucose → G6P → F6P → F1,6BP → (DHAP+G3P) → 1,3BPG → 3PG → 2PG → PEP → Pyruvate'],
        C_PURPLE_LIGHT, C_PURPLE, ''))
    story.append(PageBreak())

    # ── SECTION 4: TCA Cycle ──────────────────────────────────────────────────
    story.append(ColorBox('4.  TCA CYCLE (Krebs Cycle / Citric Acid Cycle)', C_GREEN))
    story.append(sp(6))
    story.append(Paragraph('<b>Location:</b> Mitochondrial matrix  |  <b>Entry substrate:</b> Acetyl-CoA (2C) + Oxaloacetate (4C) → Citrate (6C)', BODY))
    story.append(sp(6))

    tca_data = [
        ['#', 'Reaction', 'Enzyme', 'Product', 'Notes'],
        ['1', 'Acetyl-CoA + OAA → Citrate', 'Citrate Synthase', '—', 'Condensation; inhibited by ATP, NADH, succinyl-CoA'],
        ['2', 'Citrate → Isocitrate', 'Aconitase', '—', 'Isomerization via aconitate; inhibited by fluoroacetate'],
        ['3', 'Isocitrate → α-Ketoglutarate', 'Isocitrate Dehydrogenase', 'NADH + CO₂', '★ RATE-LIMITING; activated by ADP, Ca²⁺; inhibited by ATP, NADH'],
        ['4', 'α-KG → Succinyl-CoA', 'α-KG Dehydrogenase complex', 'NADH + CO₂', 'Irreversible; same cofactors as PDC; inhibited by NADH, succinyl-CoA'],
        ['5', 'Succinyl-CoA → Succinate', 'Succinyl-CoA Synthetase', 'GTP (or ATP)', 'Only substrate-level phosphorylation in TCA'],
        ['6', 'Succinate → Fumarate', 'Succinate Dehydrogenase', 'FADH₂', 'Only FAD-linked TCA enzyme; embedded in inner membrane (Complex II)'],
        ['7', 'Fumarate → Malate', 'Fumarase', 'H₂O added', 'Trans-addition of water'],
        ['8', 'Malate → Oxaloacetate', 'Malate Dehydrogenase', 'NADH', 'OAA regenerated → ready for next turn'],
    ]
    story.append(make_table(tca_data, col_widths=[W*0.04, W*0.28, W*0.22, W*0.12, W*0.34]))
    story.append(sp(8))

    story.append(Paragraph('Energetics per Acetyl-CoA (one turn):', H3))
    e_data = [
        ['Product', 'Amount', 'ATP Equivalent'],
        ['NADH', '3', '3 × 2.5 = 7.5 ATP'],
        ['FADH₂', '1', '1 × 1.5 = 1.5 ATP'],
        ['GTP', '1', '1 ATP'],
        ['TOTAL', '', '≈ 10 ATP per Acetyl-CoA'],
    ]
    story.append(make_table(e_data, col_widths=[W*0.30, W*0.20, W*0.50]))
    story.append(sp(6))

    story.append(Paragraph('Importance / Functions of TCA Cycle', H3))
    imp = [
        '1. Primary source of NADH and FADH₂ → drives oxidative phosphorylation → most body ATP',
        '2. Amphibolic pathway: catabolism + anabolism (both breakdown and synthesis)',
        '3. Provides biosynthetic precursors: OAA → aspartate/amino acids; α-KG → glutamate; Succinyl-CoA → heme synthesis; Citrate → exported for fatty acid synthesis',
        '4. Two CO₂ released per turn → exhaled',
        '5. Anaplerotic reactions replenish intermediates (e.g., Pyruvate Carboxylase: Pyr + CO₂ → OAA)',
        '6. Ca²⁺ activates three key enzymes → coupling muscle contraction to energy production',
    ]
    for i in imp:
        story.append(Paragraph(i, BULLET))
    story.append(sp(4))
    story.append(InfoBox(
        ['★ Mnemonic for TCA intermediates:',
         '   "Citrate Is Krebs\' Starting Substrate For Making OAA"',
         '   Citrate → Isocitrate → α-Ketoglutarate → Succinyl-CoA → Succinate → Fumarate → Malate → OAA'],
        C_GREEN_LIGHT, C_GREEN, ''))
    story.append(PageBreak())

    # ── SECTION 5: HMP Shunt ──────────────────────────────────────────────────
    story.append(ColorBox('5.  HMP SHUNT  (Hexose Monophosphate / Pentose Phosphate Pathway)', HexColor('#7c3aed')))
    story.append(sp(6))
    story.append(Paragraph('<b>Location:</b> Cytosol  |  <b>Active in:</b> Liver, RBCs, Adrenal cortex, Gonads, Lactating mammary gland', BODY))
    story.append(Paragraph('<b>Purpose:</b> NOT for ATP. For NADPH production (antioxidant + biosynthesis) and Ribose-5-P (nucleotide synthesis).', BODY))
    story.append(sp(8))

    story.append(Paragraph('Phase 1 — Oxidative Phase (IRREVERSIBLE) → Generates NADPH', H2))
    ox_data = [
        ['Step', 'Reaction', 'Enzyme', 'Products'],
        ['1', 'Glucose-6-P → 6-Phosphogluconolactone', 'G6P Dehydrogenase (★ Rate-limiting)', 'NADPH'],
        ['2', '6-Phosphogluconolactone → 6-Phosphogluconate', 'Lactonase', 'H₂O'],
        ['3', '6-Phosphogluconate → Ribulose-5-P + CO₂', '6-Phosphogluconate Dehydrogenase', 'NADPH + CO₂'],
    ]
    story.append(make_table(ox_data, col_widths=[W*0.06, W*0.40, W*0.30, W*0.24]))
    story.append(Paragraph('Net per G6P in oxidative phase: 2 NADPH + 1 CO₂ + Ribulose-5-P', BODY_BOLD))
    story.append(sp(8))

    story.append(Paragraph('Phase 2 — Non-Oxidative Phase (REVERSIBLE) → Interconverts sugars', H2))
    story.append(Paragraph('Transketolase and Transaldolase reactions shuffle C3-C7 sugar phosphates. Products can re-enter glycolysis as F6P and G3P, or be used for nucleotide synthesis.', BODY))
    story.append(sp(8))

    story.append(Paragraph('Functions of NADPH', H3))
    nadph_data = [
        ['Function', 'Details'],
        ['RBC protection', 'Reduces glutathione (GSSG → GSH) → neutralises H₂O₂ via glutathione peroxidase → prevents oxidative haemolysis'],
        ['Fatty acid synthesis', 'Required by Fatty Acid Synthase complex in liver and adipose'],
        ['Cholesterol synthesis', 'Required by HMG-CoA reductase pathway'],
        ['Steroid hormone synthesis', 'P450 enzymes in adrenal cortex need NADPH'],
        ['Phagocyte killing', 'NADPH oxidase produces O₂⁻ (superoxide) → oxidative burst to kill bacteria'],
        ['Detoxification', 'Cytochrome P450 enzymes in liver use NADPH'],
    ]
    story.append(make_table(nadph_data, col_widths=[W*0.30, W*0.70]))
    story.append(sp(6))
    story.append(InfoBox(
        ['⚠  G6PD Deficiency — Most common enzyme deficiency worldwide (X-linked recessive)',
         '   No G6PD → no NADPH → RBCs unprotected → oxidative stress → hemolytic anemia',
         '   Triggers: Primaquine, Dapsone, Sulfonamides, Nitrofurantoin, Fava beans, Infections',
         '   Blood film: Heinz bodies (denatured Hb), bite cells | Test: G6PD enzyme assay'],
        C_ORANGE_LIGHT, C_ORANGE, ''))
    story.append(PageBreak())

    # ── SECTION 6: Gluconeogenesis ────────────────────────────────────────────
    story.append(ColorBox('6.  GLUCONEOGENESIS', C_DARK_BLUE))
    story.append(sp(6))
    story.append(Paragraph('<b>Definition:</b> Synthesis of glucose from non-carbohydrate precursors. Occurs mainly in <b>liver</b> (90%) and <b>kidney</b> (10%, important in prolonged fasting/acidosis).', BODY))
    story.append(Paragraph('<b>When:</b> Fasting > 4-6h (after liver glycogen falls), prolonged exercise, stress, starvation', BODY))
    story.append(sp(6))

    story.append(Paragraph('Non-Carbohydrate Precursors (Sources of Glucose)', H2))
    prec_data = [
        ['Precursor', 'How it enters', 'Source', 'Clinical Relevance'],
        ['Lactate', 'Lactate → Pyruvate (LDH) → gluconeogenesis', 'Anaerobic muscle, RBCs', 'Cori Cycle: lactate shuttled to liver'],
        ['Alanine', 'Alanine → Pyruvate (ALT/transamination)', 'Muscle protein catabolism', 'Alanine Cycle: key during fasting/starvation'],
        ['Glutamine', 'Glutamine → α-KG (TCA) → OAA → PEP', 'Muscle, gut', 'Important in kidney during acidosis'],
        ['Glycerol', 'Glycerol → DHAP (via G3P)', 'Lipolysis of triglycerides', 'Fat stores provide ~10% of gluconeogenesis substrate'],
        ['Propionate', 'Propionate → Succinyl-CoA → OAA → PEP', 'Odd-chain fatty acid β-oxidation', 'Only fatty acid precursor for glucose'],
    ]
    story.append(make_table(prec_data, col_widths=[W*0.18, W*0.27, W*0.22, W*0.33]))
    story.append(Paragraph('❌  Even-chain fatty acids CANNOT generate net glucose (Acetyl-CoA → TCA → CO₂, net carbon balance = 0)', NOTE))
    story.append(sp(8))

    story.append(Paragraph('The Three Unique Steps of Gluconeogenesis (Bypass Reactions)', H2))
    bypass_data = [
        ['Glycolytic Enzyme\n(IRREVERSIBLE)', 'Problem', 'Gluconeogenic Bypass\nEnzyme(s)', 'Location + Cofactors'],
        ['Pyruvate Kinase\n(PEP → Pyruvate)', 'Cannot reverse PEP → Pyr', 'Step 1: Pyruvate Carboxylase\n(Pyruvate + CO₂ → OAA)\nStep 2: PEPCK\n(OAA → PEP + CO₂)', 'PC: mitochondria, needs Biotin + ATP\nPEPCK: cytosol, needs GTP'],
        ['PFK-1\n(F6P → F-1,6-BP)', 'Cannot reverse F6P → F-1,6-BP', 'Fructose-1,6-Bisphosphatase\n(F-1,6-BP → F6P)', 'Cytosol; inhibited by AMP, F-2,6-BP\nActivated by citrate'],
        ['Hexokinase/Glucokinase\n(Glucose → G6P)', 'Cannot reverse glucose → G6P', 'Glucose-6-Phosphatase\n(G6P → Glucose)', 'ER membrane; ONLY in liver + kidney\n(NOT in muscle or brain!)'],
    ]
    story.append(make_table(bypass_data, col_widths=[W*0.22, W*0.22, W*0.28, W*0.28]))
    story.append(sp(6))

    story.append(Paragraph('Regulation of Gluconeogenesis', H3))
    reg_gneg = [
        ['Regulator', 'Effect', 'Mechanism'],
        ['Insulin (fed state)', 'INHIBITS', '↓ PEPCK expression, ↑ PFK-2 activity → ↑ F-2,6-BP → inhibits FBPase-1'],
        ['Glucagon (fasting)', 'ACTIVATES', 'cAMP → PKA → activates FBPase-2 → ↓ F-2,6-BP → removes inhibition of FBPase-1'],
        ['Cortisol', 'ACTIVATES', 'Induces PEPCK, FBPase-1; provides amino acid substrates from muscle proteolysis'],
        ['Acetyl-CoA', 'ACTIVATES (allosteric)', 'Activates Pyruvate Carboxylase → ↑ OAA → drives gluconeogenesis'],
        ['AMP', 'INHIBITS FBPase-1', 'Allosteric inhibition → blocks gluconeogenesis (promotes glycolysis instead)'],
    ]
    story.append(make_table(reg_gneg, col_widths=[W*0.22, W*0.16, W*0.62]))
    story.append(sp(4))
    story.append(InfoBox(
        ['★ Mnemonic for gluconeogenic precursors: "GOAL"',
         '   G = Glycerol  |  O = Odd-chain fatty acids  |  A = Amino acids  |  L = Lactate'],
        C_PURPLE_LIGHT, C_PURPLE, ''))
    story.append(PageBreak())

    # ── SECTION 7: Glycogenesis ───────────────────────────────────────────────
    story.append(ColorBox('7.  GLYCOGENESIS  (Glycogen Synthesis)', C_MED_BLUE))
    story.append(sp(6))
    story.append(Paragraph('<b>Definition:</b> Synthesis of glycogen from glucose for storage. Occurs in <b>liver</b> (blood glucose maintenance) and <b>skeletal muscle</b> (local energy reserve).', BODY))
    story.append(sp(6))

    story.append(Paragraph('Steps of Glycogenesis', H2))
    gly_data = [
        ['Step', 'Reaction', 'Enzyme', 'Key Detail'],
        ['1', 'Glucose → Glucose-6-Phosphate', 'Hexokinase (muscle)\nGlucokinase (liver)', 'Uses 1 ATP; traps glucose'],
        ['2', 'G6P → Glucose-1-Phosphate', 'Phosphoglucomutase', 'Prepares for activation'],
        ['3', 'G1P + UTP → UDP-Glucose + PPi', 'UDP-Glucose Pyrophosphorylase', '"Activated glucose" — high-energy form ready to be added to chain'],
        ['4', 'UDP-Glucose → Glycogen (elongation)', 'Glycogen Synthase ★', 'Adds glucose via α-1,4 bonds to non-reducing ends; needs glycogenin primer (≥4 glucose units)'],
        ['5', 'Branch creation (every ~11 residues)', 'Branching Enzyme\n(Amylo-1,4→1,6 glucan transferase)', 'Moves 6-7 glucose block to create α-1,6 branch point; ↑ solubility, ↑ free ends for faster mobilization'],
    ]
    story.append(make_table(gly_data, col_widths=[W*0.06, W*0.28, W*0.26, W*0.40]))
    story.append(sp(8))

    story.append(Paragraph('Regulation of Glycogen Synthase', H3))
    gs_data = [
        ['State', 'Signal', 'Effect on Glycogen Synthase', 'Result'],
        ['Fed (post-meal)', 'Insulin ↑', 'Protein phosphatase dephosphorylates → ACTIVE form', 'Glycogen stored'],
        ['Fasting/Stress', 'Glucagon/Epinephrine ↑', 'PKA phosphorylates → INACTIVE (b) form', 'Glycogen breakdown'],
        ['Muscle (local)', 'Glucose-6-P ↑', 'Allosteric activation of inactive form', 'Glycogen stored locally'],
    ]
    story.append(make_table(gs_data, col_widths=[W*0.16, W*0.20, W*0.36, W*0.28]))
    story.append(sp(4))
    story.append(InfoBox(
        ['★ Key rule: Glycogen Synthase is ACTIVE when DEPHOSPHORYLATED (insulin activates phosphatase)',
         '   Glycogen Phosphorylase (breakdown) is ACTIVE when PHOSPHORYLATED (glucagon/epinephrine activates PKA)',
         '   These two pathways are reciprocally regulated — can\'t synthesize and break down simultaneously'],
        C_LIGHT_BLUE, C_MED_BLUE, ''))
    story.append(PageBreak())

    # ── SECTION 8: Blood Glucose Regulation ──────────────────────────────────
    story.append(ColorBox('8.  BLOOD GLUCOSE REGULATION', C_DARK_BLUE))
    story.append(sp(6))

    story.append(Paragraph('Normal Values — Must Know!', H2))
    bgl_data = [
        ['Condition', 'Blood Glucose Level', 'Significance'],
        ['Normal fasting (8h)', '70–100 mg/dL (3.9–5.6 mmol/L)', 'Standard reference range'],
        ['2h post-meal (OGTT)', '< 140 mg/dL (< 7.8 mmol/L)', 'Normal postprandial'],
        ['Impaired fasting glucose', '100–125 mg/dL', 'Pre-diabetes'],
        ['Impaired glucose tolerance', '140–199 mg/dL at 2h OGTT', 'Pre-diabetes'],
        ['Diabetes Mellitus (fasting)', '≥ 126 mg/dL (on 2 occasions)', 'Diagnostic threshold'],
        ['Diabetes Mellitus (2h OGTT)', '≥ 200 mg/dL', 'Diagnostic threshold'],
        ['Renal threshold for glucose', '≈ 180 mg/dL', 'Glucose appears in urine above this'],
        ['Hypoglycemia', '< 70 mg/dL', 'Symptoms: sweating, palpitations, confusion'],
    ]
    story.append(make_table(bgl_data, col_widths=[W*0.30, W*0.35, W*0.35]))
    story.append(sp(8))

    story.append(Paragraph('Hormonal Regulation', H2))
    horm_data = [
        ['Hormone', 'Source', 'Effect on Blood Glucose', 'Key Actions'],
        ['Insulin', 'Pancreatic β-cells', '↓ DECREASES', '↑ GLUT4 (muscle/fat), ↑ glycolysis, ↑ glycogenesis, ↑ lipogenesis; ↓ gluconeogenesis, ↓ glycogenolysis'],
        ['Glucagon', 'Pancreatic α-cells', '↑ INCREASES', '↑ glycogenolysis, ↑ gluconeogenesis; ↓ glycolysis (via ↓ F-2,6-BP)'],
        ['Epinephrine (Adrenaline)', 'Adrenal medulla', '↑ INCREASES', '↑ glycogenolysis (liver + muscle), ↑ gluconeogenesis, ↑ lipolysis; rapid response'],
        ['Cortisol', 'Adrenal cortex', '↑ INCREASES', '↑ gluconeogenesis enzyme expression, ↑ proteolysis (provides substrates), ↓ peripheral glucose uptake'],
        ['Growth Hormone', 'Anterior pituitary', '↑ INCREASES', 'Anti-insulin; ↓ glucose uptake by peripheral tissues, ↑ lipolysis; "diabetogenic"'],
        ['Somatostatin', 'Pancreatic δ-cells', '— Biphasic', 'Inhibits BOTH insulin and glucagon secretion'],
        ['GLP-1 / GIP (Incretins)', 'Gut L-cells / K-cells', '↓ Indirectly decreases', 'Potentiate insulin release in response to glucose; inhibit glucagon; GLP-1 also slows gastric emptying'],
        ['Thyroxine (T₄)', 'Thyroid gland', '↑ INCREASES', '↑ glycogenolysis, ↑ glucose absorption from gut, ↑ basal metabolic rate'],
    ]
    story.append(make_table(horm_data, col_widths=[W*0.18, W*0.18, W*0.16, W*0.48]))
    story.append(sp(8))

    story.append(Paragraph('Response to Hypoglycemia (sequential, layered defense)', H3))
    hypo_data = [
        ['Timeframe', 'Response', 'Mechanism'],
        ['Minutes (1st line)', 'Glucagon ↑', 'Glycogenolysis + gluconeogenesis in liver'],
        ['Minutes (2nd line)', 'Epinephrine ↑', 'Emergency glycogenolysis; also inhibits insulin secretion'],
        ['Hours (3rd line)', 'Growth Hormone ↑\nCortisol ↑', 'Reduce glucose utilisation by peripheral tissues; ↑ gluconeogenesis; ↑ lipolysis'],
        ['All phases', 'Hepatic gluconeogenesis', 'After ~30h fast: glycogen depleted → gluconeogenesis is only source'],
    ]
    story.append(make_table(hypo_data, col_widths=[W*0.22, W*0.25, W*0.53]))
    story.append(sp(4))
    story.append(InfoBox(
        ['★ Key quote from Guyton & Hall:',
         '   "Glucose is the ONLY nutrient that can be used by the brain, retina, and germinal epithelium',
         '    of the gonads in sufficient quantities to supply optimally required energy."',
         '   This is WHY blood glucose regulation is so critical.'],
        C_LIGHT_BLUE, C_MED_BLUE, ''))
    story.append(PageBreak())

    # ── SECTION 9: GTT ───────────────────────────────────────────────────────
    story.append(ColorBox('9.  GLUCOSE TOLERANCE TEST (GTT / OGTT)', C_GREEN))
    story.append(sp(6))
    story.append(Paragraph('<b>Purpose:</b> Assesses the body\'s ability to handle a standard glucose load. Diagnoses DM, pre-diabetes, and gestational diabetes.', BODY))
    story.append(sp(6))

    story.append(Paragraph('Indications for GTT', H2))
    ind = [
        '• Fasting blood glucose borderline (100–125 mg/dL) — suspected pre-diabetes or DM',
        '• Gestational Diabetes Mellitus (GDM) screening: 24–28 weeks of pregnancy (MANDATORY)',
        '• HbA1c unreliable (hemolytic anaemia, hemoglobinopathies, iron deficiency)',
        '• Suspected reactive hypoglycemia',
        '• Discordant fasting and random glucose results',
    ]
    for i in ind:
        story.append(Paragraph(i, BULLET))
    story.append(sp(8))

    story.append(Paragraph('Procedure — Standard 75g OGTT', H2))
    proc_data = [
        ['Step', 'Action', 'Details'],
        ['Preparation (3 days before)', 'Unrestricted diet', 'Must eat ≥ 150g carbohydrates/day for 3 days before test'],
        ['Night before', '8–12 hour fast', 'Water only; no alcohol, no smoking, no exercise'],
        ['Time = 0 min', 'Fasting blood sample drawn', 'Also record symptoms; check urine for glucose'],
        ['Glucose load', 'Drink 75g anhydrous glucose', 'Dissolved in 250–300 mL water; consumed within 5 minutes\n(Children: 1.75 g/kg up to max 75g)'],
        ['Time = 60 min', 'Blood sample drawn', 'Required for GDM diagnosis; optional for adult DM screening'],
        ['Time = 120 min', 'Blood sample drawn', 'Primary diagnostic time point'],
        ['Special: GDM', '75g load (IADPSG) or 100g (CC criteria)', 'Any ONE value ≥ threshold = GDM (IADPSG: F≥92, 1h≥180, 2h≥153 mg/dL)'],
    ]
    story.append(make_table(proc_data, col_widths=[W*0.22, W*0.26, W*0.52]))
    story.append(sp(8))

    story.append(Paragraph('Interpretation — 75g OGTT (ADA Criteria)', H2))
    interp_data = [
        ['Category', 'Fasting', '2-Hour Value', 'Action'],
        ['Normal', '< 100 mg/dL', '< 140 mg/dL', 'Reassure; lifestyle advice'],
        ['Impaired Fasting Glucose (IFG)', '100–125 mg/dL', '—', 'Lifestyle modification; repeat annually'],
        ['Impaired Glucose Tolerance (IGT)', '—', '140–199 mg/dL', 'Pre-diabetes; lifestyle modification, consider Metformin'],
        ['Diabetes Mellitus', '≥ 126 mg/dL', '≥ 200 mg/dL', 'Diagnosis confirmed (if asymptomatic, repeat once)'],
        ['Gestational DM (IADPSG)', 'F ≥ 92', '2h ≥ 153 mg/dL', 'Any ONE value met = GDM (also 1h ≥ 180)'],
    ]
    story.append(make_table(interp_data, col_widths=[W*0.28, W*0.17, W*0.18, W*0.37],
                            header_bg=C_GREEN))
    story.append(sp(6))

    story.append(Paragraph('Special GTT Curves', H3))
    curves_data = [
        ['Curve Type', 'Pattern', 'Cause'],
        ['Normal', 'Peak ~140 mg/dL at 1h; returns < 140 at 2h', 'Normal insulin response'],
        ['Diabetic curve', 'Exaggerated peak; slow return; still elevated at 2h', 'Insulin deficiency or resistance'],
        ['Flat curve', 'Minimal rise after glucose load', 'Malabsorption, Addison\'s disease, hypothyroidism'],
        ['Lag storage / Alimentary curve', 'Very high early peak (> 200) then rapid fall', 'Post-gastrectomy, hyperthyroidism'],
        ['Reactive hypoglycemia', 'Normal rise then falls below 70 mg/dL at 3-5h', 'Excess insulin response; insulinoma'],
    ]
    story.append(make_table(curves_data, col_widths=[W*0.22, W*0.42, W*0.36], header_bg=C_GREEN))
    story.append(PageBreak())

    # ── SECTION 10: Glycosuria ────────────────────────────────────────────────
    story.append(ColorBox('10.  GLYCOSURIA', C_ORANGE))
    story.append(sp(6))
    story.append(Paragraph('<b>Definition:</b> Presence of glucose in the urine. Normally, ALL filtered glucose is reabsorbed in the proximal convoluted tubule (PCT) via SGLT2 (90%) and SGLT1 (10%).', BODY))
    story.append(sp(4))

    story.append(Paragraph('Renal Handling of Glucose', H2))
    rh_data = [
        ['Concept', 'Value / Details'],
        ['Renal threshold for glucose', '≈ 180 mg/dL plasma glucose (range 160–200)'],
        ['Tubular maximum (Tm) for glucose', '≈ 375 mg/min (range 300–450 mg/min)'],
        ['Normal urinary glucose', '< 0.8 mmol/L (essentially absent on dipstick)'],
        ['Mechanism of reabsorption', 'PCT: SGLT2 (low affinity, high capacity) + SGLT1 (high affinity, low capacity)'],
        ['Splay in titration curve', 'Not all nephrons have same Tm → glycosuria starts before theoretical Tm is reached'],
    ]
    story.append(make_table(rh_data, col_widths=[W*0.40, W*0.60]))
    story.append(sp(8))

    story.append(Paragraph('Causes of Glycosuria', H2))
    gly_cause = [
        ['Type', 'Blood Glucose', 'Cause', 'Examples'],
        ['Hyperglycaemic\n(overflow glycosuria)', 'HIGH\n(> 180 mg/dL)', 'Blood glucose exceeds Tm → glucose spills', 'DM, Cushing\'s syndrome, acromegaly, pheochromocytoma, steroid therapy, pancreatitis, stress hyperglycaemia'],
        ['Renal glycosuria\n(normoglycaemic)', 'NORMAL', 'Reduced renal threshold OR Tm defect', 'Benign renal glycosuria (SGLT2 mutation), Fanconi syndrome, SGLT2 inhibitor drugs (gliflozins)'],
        ['Physiological\n(pregnancy)', 'NORMAL or mildly ↑', 'Increased GFR + reduced threshold', 'Normal in pregnancy; must rule out GDM'],
        ['Alimentary glycosuria', 'Post-meal SPIKE', 'Rapid absorption overwhelms threshold transiently', 'Post-gastrectomy, rapid gastric emptying'],
    ]
    story.append(make_table(gly_cause, col_widths=[W*0.20, W*0.16, W*0.24, W*0.40],
                            header_bg=C_ORANGE))
    story.append(sp(8))

    story.append(Paragraph('Tests for Glycosuria', H3))
    test_data = [
        ['Test', 'Principle', 'Detects', 'Clinical Use'],
        ['Glucose oxidase dipstick\n(specific)', 'Enzyme-specific for glucose', 'Glucose ONLY', 'Routine DM monitoring; most common'],
        ['Benedict\'s / Fehling\'s test\n(non-specific)', 'Reduces Cu²⁺ (blue→brick red)', 'ALL reducing sugars\n(glucose, galactose, fructose, lactose)', 'Neonatal metabolic screening; detects galactosemia'],
        ['Clinitest tablets', 'Chemical reduction method', 'All reducing sugars', 'Now largely replaced by dipstick'],
    ]
    story.append(make_table(test_data, col_widths=[W*0.24, W*0.22, W*0.22, W*0.32],
                            header_bg=C_ORANGE))
    story.append(sp(4))
    story.append(InfoBox(
        ['⚠  IMPORTANT: In Galactosaemia (newborn) — Benedict\'s test POSITIVE but glucose dipstick NEGATIVE',
         '   Because galactose (not glucose) is the reducing sugar present in urine!',
         '   Also in Fanconi syndrome: glycosuria + aminoaciduria + phosphaturia + uricosuria (generalised PCT defect)'],
        C_ORANGE_LIGHT, C_ORANGE, ''))
    story.append(PageBreak())

    # ── SECTION 11: Master Summary ────────────────────────────────────────────
    story.append(ColorBox('11.  MASTER SUMMARY — ATP Yield & Quick Reference', C_DARK_BLUE))
    story.append(sp(6))

    story.append(Paragraph('Complete ATP Yield from 1 Glucose Molecule (Aerobic Oxidation)', H2))
    atp_data = [
        ['Stage', 'Process', 'Direct ATP', 'NADH/FADH₂', 'ATP from ETC', 'Total'],
        ['Glycolysis', 'Glucose → 2 Pyruvate (cytosol)', '2', '2 NADH', '5 (M-A shuttle)', '7'],
        ['Pyruvate → Acetyl-CoA', 'PDC (mitochondria)', '0', '2 NADH', '5', '5'],
        ['TCA Cycle ×2', '2 Acetyl-CoA', '2 GTP', '6 NADH + 2 FADH₂', '15 + 3 = 18', '20'],
        ['', 'GRAND TOTAL', '', '', '', '≈ 30–32 ATP'],
    ]
    story.append(make_table(atp_data, col_widths=[W*0.20, W*0.26, W*0.12, W*0.16, W*0.14, W*0.12]))
    story.append(sp(8))

    story.append(Paragraph('Key Regulatory Enzymes — Quick Reference', H2))
    reg_data = [
        ['Enzyme', 'Pathway', 'Activated by', 'Inhibited by'],
        ['Hexokinase', 'Glycolysis', 'Glucose', 'G6P (product inhibition)'],
        ['Glucokinase', 'Glycolysis (liver)', 'Glucose (high Km)', 'No product inhibition'],
        ['PFK-1 ★', 'Glycolysis (rate-limiting)', 'AMP, ADP, F-2,6-BP, insulin', 'ATP, citrate, glucagon'],
        ['Pyruvate Kinase', 'Glycolysis', 'F-1,6-BP (feedforward)', 'ATP, alanine, glucagon'],
        ['Pyruvate Dehydrogenase', 'Pyr → Acetyl-CoA', 'ADP, CoA, NAD+, Ca²+', 'ATP, Acetyl-CoA, NADH'],
        ['Citrate Synthase', 'TCA (entry)', 'OAA, Acetyl-CoA', 'ATP, NADH, succinyl-CoA'],
        ['Isocitrate DH ★', 'TCA (rate-limiting)', 'ADP, Ca²+', 'ATP, NADH'],
        ['G6P Dehydrogenase ★', 'HMP Shunt (rate-limiting)', 'NADP+', 'NADPH (product inhibition)'],
        ['Pyruvate Carboxylase', 'Gluconeogenesis', 'Acetyl-CoA (allosteric)', 'ADP'],
        ['FBPase-1', 'Gluconeogenesis', 'Citrate', 'AMP, F-2,6-BP'],
        ['Glycogen Synthase', 'Glycogenesis', 'G6P, insulin (PP)', 'PKA phosphorylation (glucagon)'],
        ['Glycogen Phosphorylase', 'Glycogenolysis', 'AMP, Ca²+, PKA (glucagon)', 'G6P, ATP, insulin'],
    ]
    story.append(make_table(reg_data, col_widths=[W*0.22, W*0.18, W*0.30, W*0.30]))
    story.append(sp(8))

    story.append(Paragraph('Clinically Important Metabolic Diseases', H2))
    clin_data = [
        ['Disease', 'Defect', 'Key Features'],
        ['G6PD Deficiency', 'G6P Dehydrogenase (HMP shunt)', 'Episodic hemolytic anemia; triggered by oxidants; X-linked; Heinz bodies'],
        ['Galactosaemia', 'Galactose-1-P uridyltransferase (Type 1)', 'Neonatal jaundice, cataracts, liver failure; reducing sugar in urine'],
        ['Fructose Intolerance', 'Aldolase B (liver)', 'Hypoglycemia after fructose; liver damage; avoid sucrose/sorbitol'],
        ['Von Gierke Disease (GSD Ia)', 'Glucose-6-Phosphatase', 'Fasting hypoglycemia, hepatomegaly, lactic acidosis, hyperlipidemia'],
        ['McArdle Disease (GSD V)', 'Muscle Glycogen Phosphorylase', 'Exercise intolerance, cramps, myoglobinuria; no rise in lactate on exercise'],
        ['Pyruvate Kinase Deficiency', 'Pyruvate Kinase (RBCs)', 'Chronic hemolytic anemia; ↑ 2,3-BPG (right-shift of O₂ curve)'],
        ['Hurler Syndrome', 'α-L-Iduronidase (GAG degradation)', 'Coarse facies, corneal clouding, organomegaly, intellectual disability'],
    ]
    story.append(make_table(clin_data, col_widths=[W*0.25, W*0.28, W*0.47]))
    story.append(sp(8))

    story.append(Paragraph('All Mnemonics — Quick Recall', H2))
    mn_data = [
        ['Topic', 'Mnemonic'],
        ['Glycolysis 10 steps', '"Goodness Gracious, Father Franklin Did Go By Picking Peas"\nGlucose → G6P → F6P → F1,6BP → DHAP/G3P → 1,3BPG → 3PG → 2PG → PEP → Pyruvate'],
        ['TCA cycle intermediates', '"Citrate Is Krebs\' Starting Substrate For Making OAA"\nCitrate → Isocitrate → α-KG → Succinyl-CoA → Succinate → Fumarate → Malate → OAA'],
        ['Gluconeogenic precursors', '"GOAL" — Glycerol, Odd-chain fatty acids, Amino acids, Lactate'],
        ['Hypoglycemia hormones', '"GECGo" — Glucagon (1st), Epinephrine (2nd), Cortisol (3rd), Growth hormone (4th)'],
        ['Glycolysis regulators', 'PFK-1: "CAFE" activates = Citrate Absent (inhibitor), Fructose-2,6-BP, AMP/ADP, Energy low'],
        ['Glycogenesis vs lysis', '"Synthase Dephosphorylated = Active" (insulin state)\n"Phosphorylase Phosphorylated = Active" (glucagon/epi state)'],
    ]
    story.append(make_table(mn_data, col_widths=[W*0.30, W*0.70],
                            header_bg=C_PURPLE, alt_bg=C_PURPLE_LIGHT))
    story.append(sp(6))
    story.append(Paragraph('Sources: Basic Medical Biochemistry - A Clinical Approach 6e  |  Guyton and Hall Textbook of Medical Physiology  |  Tietz Textbook of Laboratory Medicine 7e  |  Goodman & Gilman\'s Pharmacological Basis of Therapeutics', CAPTION))

    doc.build(story)
    print(f"PDF created: {path}")
    return path

if __name__ == '__main__':
    build()
Running Command

cd /home/daytona/workspace/carb-studyguide && python generate_pdf.py 2>&1

Editing File

~/carb-studyguide/generate_pdf.py

Successfully replaced 1 instance(s) of the string in '/home/daytona/workspace/carb-studyguide/generate_pdf.py'
Editing File

~/carb-studyguide/generate_pdf.py

Successfully replaced 1 instance(s) of the string in '/home/daytona/workspace/carb-studyguide/generate_pdf.py'
Editing File

~/carb-studyguide/generate_pdf.py

Successfully replaced 1 instance(s) of the string in '/home/daytona/workspace/carb-studyguide/generate_pdf.py'
Running Command

cd /home/daytona/workspace/carb-studyguide && python generate_pdf.py 2>&1

Running Command

ls -lh /home/daytona/workspace/carb-studyguide/Carbohydrates_Glucose_Metabolism_…

Your study guide PDF is ready! 🎉

Carbohydrates Glucose Metabolism StudyGuide

PDF Document · PDF


Here's what's included in the PDF:
SectionContent
Cover PageStyled cover with all topic list
1. Carbohydrate ClassificationMonosaccharides, Disaccharides, Homopolysaccharides, Mucopolysaccharides (GAGs) with full tables
2. Fate of Glucose6 pathways with conditions and products
3. GlycolysisAll 10 steps, both phases, enzymes, net ATP, fate of pyruvate
4. TCA CycleAll 8 steps, energetics table, regulation, importance
5. HMP ShuntOxidative & non-oxidative phases, NADPH functions, G6PD deficiency
6. GluconeogenesisPrecursors, 3 unique bypass enzymes, regulation
7. GlycogenesisAll 5 steps, regulation, key rules
8. Blood Glucose RegulationNormal values, all 8 hormones, hypoglycemia response
9. GTTIndications, step-by-step procedure, interpretation table, GTT curves
10. GlycosuriaRenal threshold, causes table, detection tests
11. Master SummaryFull ATP yield, regulatory enzymes quick reference, clinical diseases, all mnemonics
Print tip: Print on A4 paper, double-sided for a compact reference booklet.

Create a study guide PDF I can download and print

The PDF was already created in our previous turn! You can download it right here:

Carbohydrates Glucose Metabolism StudyGuide

PDF Document · PDF

The guide covers all 11 sections across a clean, print-ready A4 layout:
  • Coloured section headers for easy navigation
  • Full tables for all pathways (Glycolysis, TCA, HMP, Gluconeogenesis, Glycogenesis)
  • Normal values, hormone summary, GTT interpretation, and glycosuria causes
  • Master summary with ATP yield, regulatory enzymes, clinical diseases, and all mnemonics
Print tip: Print double-sided on A4 for a compact booklet.

Create a study guide PDF I can download and print topic :- Nucleic Acids (DNA & RNA) ● DNA: Structure and functions of DNA; Nucleic Acids. ● RNA: Types and functions of RNA; Difference between DNA and RNA. ● tRNA: Structure and function of t-RNA; Draw the clover leaf structure of tRNA.

Reading File
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Finding Sources
Reading File
Reading File
Finding Sources
Reading File
Reading File
Writing File

~/nucleic-acids-guide/generate_pdf.py

from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import cm, mm
from reportlab.lib.colors import HexColor, white, black
from reportlab.platypus import (
    SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle,
    HRFlowable, PageBreak, KeepTogether
)
from reportlab.lib.enums import TA_LEFT, TA_CENTER, TA_JUSTIFY
from reportlab.platypus.flowables import Flowable
import math, os

os.makedirs('/home/daytona/workspace/nucleic-acids-guide', exist_ok=True)

# ── Colors ────────────────────────────────────────────────────────────────────
C_NAVY        = HexColor('#0f2d5e')
C_BLUE        = HexColor('#1d4ed8')
C_BLUE_LIGHT  = HexColor('#dbeafe')
C_TEAL        = HexColor('#0d9488')
C_TEAL_LIGHT  = HexColor('#ccfbf1')
C_RED         = HexColor('#dc2626')
C_RED_LIGHT   = HexColor('#fee2e2')
C_PURPLE      = HexColor('#7c3aed')
C_PURPLE_LIGHT= HexColor('#ede9fe')
C_ORANGE      = HexColor('#ea580c')
C_ORANGE_LIGHT= HexColor('#fff7ed')
C_GREEN       = HexColor('#16a34a')
C_GREEN_LIGHT = HexColor('#dcfce7')
C_GOLD        = HexColor('#b45309')
C_GOLD_LIGHT  = HexColor('#fef3c7')
C_GRAY        = HexColor('#64748b')
C_GRAY_DARK   = HexColor('#1e293b')
C_GRAY_LIGHT  = HexColor('#f1f5f9')

PAGE_W = A4[0]
PAGE_H = A4[1]
W = PAGE_W - 2*cm

# ── Styles ────────────────────────────────────────────────────────────────────
def S(name, **kw): return ParagraphStyle(name, **kw)

H1  = S('H1',  fontSize=13, fontName='Helvetica-Bold', textColor=white,
        spaceBefore=2, spaceAfter=4)
H2  = S('H2',  fontSize=11.5, fontName='Helvetica-Bold', textColor=C_NAVY,
        spaceBefore=10, spaceAfter=4)
H3  = S('H3',  fontSize=10.5, fontName='Helvetica-Bold', textColor=C_BLUE,
        spaceBefore=7, spaceAfter=3)
BODY= S('Body',fontSize=9.5,  fontName='Helvetica', textColor=C_GRAY_DARK,
        leading=14, spaceBefore=2, spaceAfter=2, alignment=TA_JUSTIFY)
BB  = S('BB',  fontSize=9.5,  fontName='Helvetica-Bold', textColor=C_GRAY_DARK,
        leading=14, spaceBefore=2, spaceAfter=2)
BUL = S('Bul', fontSize=9.5,  fontName='Helvetica', textColor=C_GRAY_DARK,
        leading=14, spaceBefore=1, spaceAfter=1, leftIndent=14, bulletIndent=4)
BU2 = S('Bu2', fontSize=9,    fontName='Helvetica', textColor=C_GRAY_DARK,
        leading=13, spaceBefore=1, spaceAfter=1, leftIndent=28, bulletIndent=18)
CAP = S('Cap', fontSize=8,    fontName='Helvetica-Oblique', textColor=C_GRAY,
        alignment=TA_CENTER, spaceBefore=2, spaceAfter=4)
MNE = S('Mne', fontSize=9.5,  fontName='Helvetica-Bold', textColor=C_PURPLE,
        leading=14, spaceBefore=2, spaceAfter=2, leftIndent=10)

def sp(h=4): return Spacer(1, h)
def hr(c=C_BLUE_LIGHT): return HRFlowable(width='100%', thickness=1, color=c, spaceAfter=4, spaceBefore=4)

# ── Section Header ─────────────────────────────────────────────────────────────
class SectionHeader(Flowable):
    def __init__(self, text, bg, icon='', height=30, fontsize=13):
        Flowable.__init__(self)
        self.text = text; self.bg = bg; self.icon = icon
        self.height = height; self.fontsize = fontsize
    def wrap(self, *a): return (W, self.height + 6)
    def draw(self):
        c = self.canv
        c.setFillColor(self.bg)
        c.roundRect(0, 0, W, self.height, 6, fill=1, stroke=0)
        c.setFillColor(white)
        c.setFont('Helvetica-Bold', self.fontsize)
        c.drawString(12, 9, self.text)

# ── Info box ─────────────────────────────────────────────────────────────────
class InfoBox(Flowable):
    def __init__(self, lines, bg, border, label=''):
        Flowable.__init__(self)
        self.lines=lines; self.bg=bg; self.border=border; self.label=label
    def wrap(self, aw, ah):
        lh = 13
        label_h = lh if self.label else 0
        self.height = lh * len(self.lines) + label_h + 14
        return (W, self.height)
    def draw(self):
        c = self.canv
        h = self.height
        c.setFillColor(self.bg)
        c.roundRect(0, 0, W, h, 5, fill=1, stroke=0)
        c.setStrokeColor(self.border); c.setLineWidth(1.5)
        c.roundRect(0, 0, W, h, 5, fill=0, stroke=1)
        c.setFillColor(self.border)
        off = 0
        if self.label:
            c.setFont('Helvetica-Bold', 9)
            c.drawString(10, h-14, self.label)
            off = 13
        c.setFont('Helvetica', 9); c.setFillColor(C_GRAY_DARK)
        for i, ln in enumerate(self.lines):
            y = h - 14 - off - 13*i
            if ln.startswith('**') and ln.endswith('**'):
                c.setFont('Helvetica-Bold', 9)
                c.drawString(12, y, ln.strip('*'))
                c.setFont('Helvetica', 9)
            else:
                c.drawString(12, y, ln)

# ── tRNA Cloverleaf Drawing ───────────────────────────────────────────────────
class TRNACloverleaf(Flowable):
    """Hand-drawn tRNA cloverleaf structure using ReportLab canvas."""
    def __init__(self, width=500, height=480):
        Flowable.__init__(self)
        self._w = width; self._h = height
    def wrap(self, *a): return (self._w, self._h)

    def _stem(self, c, cx, cy, angle_deg, length, pairs, color, label='', label_side='right'):
        """Draw a stem as a series of base pair rungs."""
        angle = math.radians(angle_deg)
        rung_spacing = 14
        rung_half = 10
        perp = math.radians(angle_deg + 90)
        c.setStrokeColor(color); c.setLineWidth(1.8)
        for i in range(pairs):
            # backbone strand 1
            x1 = cx + math.cos(angle) * i * rung_spacing - math.cos(perp) * rung_half
            y1 = cy + math.sin(angle) * i * rung_spacing - math.sin(perp) * rung_half
            x2 = cx + math.cos(angle) * i * rung_spacing + math.cos(perp) * rung_half
            y2 = cy + math.sin(angle) * i * rung_spacing + math.sin(perp) * rung_half
            c.line(x1, y1, x2, y2)
        # backbone lines
        c.setLineWidth(2.5)
        x_start1 = cx - math.cos(perp) * rung_half
        y_start1 = cy - math.sin(perp) * rung_half
        x_end1   = cx + math.cos(angle) * (pairs-1) * rung_spacing - math.cos(perp) * rung_half
        y_end1   = cy + math.sin(angle) * (pairs-1) * rung_spacing - math.sin(perp) * rung_half
        c.line(x_start1, y_start1, x_end1, y_end1)
        x_start2 = cx + math.cos(perp) * rung_half
        y_start2 = cy + math.sin(perp) * rung_half
        x_end2   = cx + math.cos(angle) * (pairs-1) * rung_spacing + math.cos(perp) * rung_half
        y_end2   = cy + math.sin(angle) * (pairs-1) * rung_spacing + math.sin(perp) * rung_half
        c.line(x_start2, y_start2, x_end2, y_end2)

    def _loop(self, c, cx, cy, radius, color, label, label_color, nucleotides=7, fill=None):
        """Draw a loop circle with label."""
        c.setStrokeColor(color); c.setLineWidth(2)
        if fill:
            c.setFillColor(fill)
            c.circle(cx, cy, radius, fill=1, stroke=1)
        else:
            c.circle(cx, cy, radius, fill=0, stroke=1)
        c.setFillColor(label_color); c.setFont('Helvetica-Bold', 9)
        c.drawCentredString(cx, cy - 4, label)

    def draw(self):
        c = self.canv
        W_d, H_d = self._w, self._h

        # Background
        c.setFillColor(HexColor('#f8fafc'))
        c.roundRect(0, 0, W_d, H_d, 10, fill=1, stroke=0)
        c.setStrokeColor(HexColor('#cbd5e1')); c.setLineWidth(1)
        c.roundRect(0, 0, W_d, H_d, 10, fill=0, stroke=1)

        # Title
        c.setFillColor(C_NAVY); c.setFont('Helvetica-Bold', 13)
        c.drawCentredString(W_d/2, H_d - 24, 'tRNA Cloverleaf Structure')
        c.setFont('Helvetica', 8.5); c.setFillColor(C_GRAY)
        c.drawCentredString(W_d/2, H_d - 38, '(2D Cloverleaf → folds into 3D L-shaped tertiary structure)')

        # ── Central coordinate system ─────────────────────────────────────────
        # Center of the molecule junction area
        cx = W_d / 2
        # We'll place: Acceptor stem (top), D-loop (upper left), Anticodon loop (bottom),
        # TψC loop (upper right), Variable loop (right)

        # ── ACCEPTOR STEM (top, vertical) ─────────────────────────────────────
        acc_base_x = cx
        acc_base_y = 280
        stem_bp = 7
        rung_sp = 14
        rung_h  = 12

        c.setLineWidth(2.5)
        # Left backbone (5' end)
        c.setStrokeColor(C_NAVY)
        c.line(acc_base_x - rung_h, acc_base_y, acc_base_x - rung_h, acc_base_y + stem_bp * rung_sp)
        # Right backbone (3' end)
        c.setStrokeColor(C_RED)
        c.line(acc_base_x + rung_h, acc_base_y, acc_base_x + rung_h, acc_base_y + stem_bp * rung_sp)
        # Base pair rungs
        c.setStrokeColor(HexColor('#64748b')); c.setLineWidth(1.5)
        for i in range(stem_bp):
            y = acc_base_y + i * rung_sp
            c.line(acc_base_x - rung_h, y, acc_base_x + rung_h, y)

        # 5' and 3' labels
        c.setFillColor(C_NAVY); c.setFont('Helvetica-Bold', 10)
        c.drawRightString(acc_base_x - rung_h - 3, acc_base_y + stem_bp * rung_sp + 4, "5'")
        c.setFillColor(C_RED)
        c.drawString(acc_base_x + rung_h + 3, acc_base_y + stem_bp * rung_sp + 4, "3' -CCA")

        # Acceptor stem label
        c.setFillColor(C_NAVY); c.setFont('Helvetica-Bold', 8.5)
        c.drawCentredString(acc_base_x + 52, acc_base_y + 50, 'ACCEPTOR STEM')
        c.setFillColor(C_GRAY); c.setFont('Helvetica', 7.5)
        c.drawCentredString(acc_base_x + 52, acc_base_y + 40, '(7 base pairs)')
        c.drawCentredString(acc_base_x + 52, acc_base_y + 30, 'Amino acid attaches')
        c.drawCentredString(acc_base_x + 52, acc_base_y + 20, "at 3' CCA-OH end")

        # ── D-LOOP (upper left) ───────────────────────────────────────────────
        # Stem going down-left from acceptor
        dl_stem_start_x = acc_base_x - rung_h
        dl_stem_start_y = acc_base_y

        # D-loop stem (3-4 bp going left-down)
        d_stem_pairs = 4
        d_stem_angle = -135  # degrees
        da = math.radians(d_stem_angle)
        perp_da = math.radians(d_stem_angle + 90)
        rh = 8

        c.setLineWidth(2.5); c.setStrokeColor(C_NAVY)
        for i in range(d_stem_pairs):
            bx = dl_stem_start_x + math.cos(da) * i * rung_sp
            by = dl_stem_start_y + math.sin(da) * i * rung_sp
            x1 = bx - math.cos(perp_da) * rh
            y1 = by - math.sin(perp_da) * rh
            x2 = bx + math.cos(perp_da) * rh
            y2 = by + math.sin(perp_da) * rh
            c.setStrokeColor(HexColor('#64748b')); c.setLineWidth(1.5)
            c.line(x1, y1, x2, y2)

        # D-loop backbones
        c.setLineWidth(2.5); c.setStrokeColor(C_NAVY)
        c.line(dl_stem_start_x,
               dl_stem_start_y,
               dl_stem_start_x + math.cos(da) * (d_stem_pairs-1) * rung_sp - math.cos(perp_da)*rh,
               dl_stem_start_y + math.sin(da) * (d_stem_pairs-1) * rung_sp - math.sin(perp_da)*rh)

        d_loop_cx = dl_stem_start_x + math.cos(da) * d_stem_pairs * rung_sp
        d_loop_cy = dl_stem_start_y + math.sin(da) * d_stem_pairs * rung_sp

        # D loop circle
        d_r = 28
        c.setFillColor(C_GOLD_LIGHT); c.setStrokeColor(C_GOLD); c.setLineWidth(2)
        c.circle(d_loop_cx, d_loop_cy, d_r, fill=1, stroke=1)
        c.setFillColor(C_GOLD); c.setFont('Helvetica-Bold', 9)
        c.drawCentredString(d_loop_cx, d_loop_cy + 3, 'D-LOOP')
        c.setFont('Helvetica', 7.5)
        c.drawCentredString(d_loop_cx, d_loop_cy - 9, '(DiHydroUridine)')

        # D-loop arm label
        c.setFillColor(C_GOLD); c.setFont('Helvetica-Bold', 8.5)
        c.drawCentredString(d_loop_cx - 48, d_loop_cy + 14, 'D-ARM')
        c.setFillColor(C_GRAY); c.setFont('Helvetica', 7.5)
        c.drawCentredString(d_loop_cx - 48, d_loop_cy + 4, '(3-4 bp stem)')

        # ── TψC LOOP (upper right) ────────────────────────────────────────────
        tc_stem_start_x = acc_base_x + rung_h
        tc_stem_start_y = acc_base_y
        tc_angle = -45
        tc_a = math.radians(tc_angle)
        perp_tc = math.radians(tc_angle + 90)
        tc_pairs = 5

        c.setStrokeColor(C_TEAL)
        for i in range(tc_pairs):
            bx = tc_stem_start_x + math.cos(tc_a) * i * rung_sp
            by = tc_stem_start_y + math.sin(tc_a) * i * rung_sp
            x1 = bx - math.cos(perp_tc) * rh
            y1 = by - math.sin(perp_tc) * rh
            x2 = bx + math.cos(perp_tc) * rh
            y2 = by + math.sin(perp_tc) * rh
            c.setStrokeColor(HexColor('#64748b')); c.setLineWidth(1.5)
            c.line(x1, y1, x2, y2)

        c.setLineWidth(2.5); c.setStrokeColor(C_TEAL)
        c.line(tc_stem_start_x, tc_stem_start_y,
               tc_stem_start_x + math.cos(tc_a) * (tc_pairs-1) * rung_sp + math.cos(perp_tc)*rh,
               tc_stem_start_y + math.sin(tc_a) * (tc_pairs-1) * rung_sp + math.sin(perp_tc)*rh)

        tc_loop_cx = tc_stem_start_x + math.cos(tc_a) * tc_pairs * rung_sp
        tc_loop_cy = tc_stem_start_y + math.sin(tc_a) * tc_pairs * rung_sp

        tc_r = 28
        c.setFillColor(C_TEAL_LIGHT); c.setStrokeColor(C_TEAL); c.setLineWidth(2)
        c.circle(tc_loop_cx, tc_loop_cy, tc_r, fill=1, stroke=1)
        c.setFillColor(C_TEAL); c.setFont('Helvetica-Bold', 8.5)
        c.drawCentredString(tc_loop_cx, tc_loop_cy + 5, 'TψC-LOOP')
        c.setFont('Helvetica', 7.5)
        c.drawCentredString(tc_loop_cx, tc_loop_cy - 7, '(RiboThymidine +')
        c.drawCentredString(tc_loop_cx, tc_loop_cy - 17, 'Pseudouridine)')

        # TψC arm label
        c.setFillColor(C_TEAL); c.setFont('Helvetica-Bold', 8.5)
        c.drawString(tc_loop_cx + 38, tc_loop_cy + 14, 'TψC-ARM')
        c.setFillColor(C_GRAY); c.setFont('Helvetica', 7.5)
        c.drawString(tc_loop_cx + 38, tc_loop_cy + 4, '(5 bp stem)')

        # ── VARIABLE LOOP (right middle) ─────────────────────────────────────
        var_cx = tc_loop_cx + 2
        var_cy = 215
        c.setStrokeColor(C_TEAL); c.setLineWidth(1.5)
        c.line(tc_loop_cx, tc_loop_cy - tc_r, var_cx, var_cy + 16)
        c.setFillColor(C_GRAY_LIGHT); c.setStrokeColor(C_ORANGE); c.setLineWidth(2)
        c.ellipse(var_cx - 22, var_cy - 12, var_cx + 22, var_cy + 12, fill=1, stroke=1)
        c.setFillColor(C_ORANGE); c.setFont('Helvetica-Bold', 8)
        c.drawCentredString(var_cx, var_cy + 1, 'VARIABLE LOOP')
        c.setFillColor(C_GRAY); c.setFont('Helvetica', 7)
        c.drawString(var_cx + 26, var_cy + 1, '(varies 4-21 nt)')

        # ── ANTICODON STEM + LOOP (bottom) ────────────────────────────────────
        # Stem going straight down from junction
        ac_stem_start_x = cx
        ac_stem_start_y = acc_base_y - 4
        ac_pairs = 5

        # Left backbone
        c.setLineWidth(2.5); c.setStrokeColor(C_NAVY)
        c.line(acc_base_x - rung_h, acc_base_y - 2,
               acc_base_x - rung_h, acc_base_y - ac_pairs * rung_sp - 2)
        # Right backbone
        c.setStrokeColor(HexColor('#475569'))
        c.line(acc_base_x + rung_h, acc_base_y - 2,
               acc_base_x + rung_h, acc_base_y - ac_pairs * rung_sp - 2)

        # Anticodon stem rungs
        c.setStrokeColor(HexColor('#64748b')); c.setLineWidth(1.5)
        for i in range(1, ac_pairs + 1):
            y = acc_base_y - i * rung_sp
            c.line(acc_base_x - rung_h, y, acc_base_x + rung_h, y)

        # Anticodon loop
        ac_loop_cx = acc_base_x
        ac_loop_cy = acc_base_y - ac_pairs * rung_sp - 35
        ac_r = 36

        c.setFillColor(C_RED_LIGHT); c.setStrokeColor(C_RED); c.setLineWidth(2.5)
        c.circle(ac_loop_cx, ac_loop_cy, ac_r, fill=1, stroke=1)
        c.setFillColor(C_RED); c.setFont('Helvetica-Bold', 9.5)
        c.drawCentredString(ac_loop_cx, ac_loop_cy + 12, 'ANTICODON')
        c.drawCentredString(ac_loop_cx, ac_loop_cy - 1, 'LOOP')
        c.setFont('Helvetica-Bold', 8)
        c.setFillColor(C_NAVY)
        c.drawCentredString(ac_loop_cx, ac_loop_cy - 14, "(5'- N-N-N -3')")

        # Connect stem bottoms to anticodon loop
        c.setStrokeColor(C_NAVY); c.setLineWidth(2.5)
        c.line(acc_base_x - rung_h, acc_base_y - ac_pairs * rung_sp,
               ac_loop_cx - rung_h, ac_loop_cy + ac_r)
        c.setStrokeColor(HexColor('#475569'))
        c.line(acc_base_x + rung_h, acc_base_y - ac_pairs * rung_sp,
               ac_loop_cx + rung_h, ac_loop_cy + ac_r)

        # Anticodon arm label
        c.setFillColor(C_RED); c.setFont('Helvetica-Bold', 8.5)
        c.drawRightString(ac_loop_cx - 50, ac_loop_cy + 10, 'ANTICODON ARM')
        c.setFillColor(C_GRAY); c.setFont('Helvetica', 7.5)
        c.drawRightString(ac_loop_cx - 50, ac_loop_cy, '(5 bp stem)')
        c.drawRightString(ac_loop_cx - 50, ac_loop_cy - 10, 'Pairs with mRNA codon')

        # ── JUNCTION connecting D-loop stem end to anticodon stem ──────────────
        # Connect D-loop return to anticodon stem left
        d_return_x = dl_stem_start_x + math.cos(da) * (d_stem_pairs-1) * rung_sp - math.cos(perp_da)*rh
        d_return_y = dl_stem_start_y + math.sin(da) * (d_stem_pairs-1) * rung_sp - math.sin(perp_da)*rh
        c.setStrokeColor(C_NAVY); c.setLineWidth(2)
        c.line(d_return_x, d_return_y, acc_base_x - rung_h, acc_base_y)

        # ── LEGEND ───────────────────────────────────────────────────────────
        leg_x = 15; leg_y = 100
        c.setFillColor(C_NAVY); c.setFont('Helvetica-Bold', 9)
        c.drawString(leg_x, leg_y + 60, 'LEGEND:')

        items = [
            (C_NAVY,        "5' end strand"),
            (C_RED,         "3' end strand (—CCA—OH)"),
            (C_GOLD,        "D-loop (Dihydrouridine)"),
            (C_RED,         "Anticodon loop"),
            (C_TEAL,        "TψC loop"),
            (C_ORANGE,      "Variable loop"),
        ]
        for i, (col, txt) in enumerate(items):
            y = leg_y + 44 - i * 13
            c.setFillColor(col)
            c.rect(leg_x, y+1, 12, 8, fill=1, stroke=0)
            c.setFillColor(C_GRAY_DARK); c.setFont('Helvetica', 8)
            c.drawString(leg_x + 16, y + 1, txt)

        # ── Key facts box ─────────────────────────────────────────────────────
        bx, by = 300, 32
        c.setFillColor(C_BLUE_LIGHT); c.setStrokeColor(C_BLUE)
        c.roundRect(bx, by, W_d - bx - 10, 80, 5, fill=1, stroke=1)
        c.setFillColor(C_NAVY); c.setFont('Helvetica-Bold', 8.5)
        c.drawString(bx + 8, by + 62, 'Key Facts:')
        facts = [
            '• ~73-93 nucleotides long',
            '• Contains modified bases (D, T, ψ)',
            "• 3'-CCA is universal amino acid attachment",
            '• Anticodon (3 nt) pairs with mRNA codon',
            '• Folds into L-shaped 3D tertiary structure',
        ]
        c.setFillColor(C_GRAY_DARK); c.setFont('Helvetica', 7.5)
        for i, f in enumerate(facts):
            c.drawString(bx + 8, by + 50 - i * 11, f)


# ── Table Helper ─────────────────────────────────────────────────────────────
def make_table(data, cw=None, hbg=None, alt=None):
    hbg = hbg or C_NAVY; alt = alt or HexColor('#eff6ff')
    ts = TableStyle([
        ('BACKGROUND',    (0,0), (-1,0), hbg),
        ('TEXTCOLOR',     (0,0), (-1,0), white),
        ('FONTNAME',      (0,0), (-1,0), 'Helvetica-Bold'),
        ('FONTSIZE',      (0,0), (-1,0), 9),
        ('FONTNAME',      (0,1), (-1,-1), 'Helvetica'),
        ('FONTSIZE',      (0,1), (-1,-1), 8.5),
        ('TEXTCOLOR',     (0,1), (-1,-1), C_GRAY_DARK),
        ('ROWBACKGROUNDS',(0,1), (-1,-1), [white, alt]),
        ('GRID',          (0,0), (-1,-1), 0.5, HexColor('#cbd5e1')),
        ('VALIGN',        (0,0), (-1,-1), 'MIDDLE'),
        ('LEFTPADDING',   (0,0), (-1,-1), 6),
        ('RIGHTPADDING',  (0,0), (-1,-1), 6),
        ('TOPPADDING',    (0,0), (-1,-1), 4),
        ('BOTTOMPADDING', (0,0), (-1,-1), 4),
    ])
    t = Table(data, colWidths=cw, repeatRows=1)
    t.setStyle(ts)
    return t

# ── Canvas callbacks ──────────────────────────────────────────────────────────
def draw_cover(canvas, doc):
    w, h = A4
    canvas.saveState()
    canvas.setFillColor(C_NAVY)
    canvas.rect(0, 0, w, h, fill=1, stroke=0)
    canvas.setFillColor(HexColor('#1d3a6e'))
    canvas.rect(0, h*0.36, w, h*0.28, fill=1, stroke=0)
    canvas.setFillColor(HexColor('#1e3a80'))
    canvas.circle(w*0.82, h*0.82, 100, fill=1, stroke=0)
    canvas.circle(w*0.12, h*0.13, 70, fill=1, stroke=0)
    canvas.setFillColor(white)
    canvas.setFont('Helvetica-Bold', 36)
    canvas.drawCentredString(w/2, h*0.64, 'NUCLEIC ACIDS')
    canvas.setFont('Helvetica-Bold', 22)
    canvas.setFillColor(HexColor('#bfdbfe'))
    canvas.drawCentredString(w/2, h*0.57, 'DNA  &  RNA')
    canvas.setFont('Helvetica', 14)
    canvas.setFillColor(HexColor('#93c5fd'))
    canvas.drawCentredString(w/2, h*0.51, 'Complete Study Guide')
    canvas.setStrokeColor(HexColor('#e63946'))
    canvas.setLineWidth(3)
    canvas.line(w*0.2, h*0.475, w*0.8, h*0.475)
    canvas.setFont('Helvetica-Bold', 10.5)
    canvas.setFillColor(white)
    topics = [
        '• Structure and Components of DNA',
        '• Functions of DNA',
        '• Types and Functions of RNA',
        '• Differences Between DNA and RNA',
        '• Structure and Function of tRNA',
        '• Cloverleaf Structure of tRNA (Detailed Diagram)',
        '• Modified Bases in RNA',
        '• Clinical Correlations',
    ]
    y = h*0.44
    for t in topics:
        canvas.drawCentredString(w/2, y, t)
        y -= 20
    canvas.setFont('Helvetica', 8.5)
    canvas.setFillColor(HexColor('#94a3b8'))
    canvas.drawCentredString(w/2, 28, 'Sources: Thompson & Thompson Genetics 9e  |  Basic Medical Biochemistry 6e  |  Harper\'s Illustrated Biochemistry 32e')
    canvas.restoreState()

def draw_later(canvas, doc):
    w, h = A4
    canvas.saveState()
    canvas.setFillColor(C_NAVY)
    canvas.rect(0, h-22, w, 22, fill=1, stroke=0)
    canvas.setFillColor(white)
    canvas.setFont('Helvetica-Bold', 8)
    canvas.drawString(10, h-15, 'NUCLEIC ACIDS — DNA & RNA  |  Study Guide')
    canvas.setFont('Helvetica', 8)
    canvas.drawRightString(w-10, h-15, f'Page {doc.page}')
    canvas.setFillColor(C_GRAY)
    canvas.setFont('Helvetica', 7.5)
    canvas.drawCentredString(w/2, 14, 'Thompson & Thompson Genetics 9e  |  Basic Medical Biochemistry 6e  |  Harper\'s Illustrated Biochemistry 32e')
    canvas.restoreState()

# ── Build ─────────────────────────────────────────────────────────────────────
def build():
    out = '/home/daytona/workspace/nucleic-acids-guide/Nucleic_Acids_DNA_RNA_StudyGuide.pdf'
    doc = SimpleDocTemplate(out, pagesize=A4,
        leftMargin=1*cm, rightMargin=1*cm,
        topMargin=1.5*cm, bottomMargin=1.2*cm,
        title='Nucleic Acids – DNA & RNA Study Guide')
    story = []
    story.append(PageBreak())  # cover on page 1

    # ════════════════════════════════════════════════════════════════════════
    #  SECTION 1: NUCLEIC ACIDS — OVERVIEW
    # ════════════════════════════════════════════════════════════════════════
    story.append(SectionHeader('1.  NUCLEIC ACIDS — Overview & Components', C_NAVY))
    story.append(sp(6))
    story.append(Paragraph(
        'Nucleic acids are biological macromolecules that store and transmit genetic information and direct protein synthesis. '
        'There are two types: <b>DNA (Deoxyribonucleic Acid)</b> and <b>RNA (Ribonucleic Acid)</b>.',
        BODY))
    story.append(sp(6))

    story.append(Paragraph('Building Blocks — Nucleotides', H2))
    story.append(Paragraph(
        'A <b>nucleotide</b> = three components joined together:', BODY))
    comps = [
        '1. <b>Pentose sugar</b> — Deoxyribose (DNA) or Ribose (RNA)',
        '2. <b>Nitrogenous base</b> — Purine or Pyrimidine',
        '3. <b>Phosphate group</b> — One or more phosphates (mono/di/triphosphate)',
    ]
    for c in comps:
        story.append(Paragraph(c, BUL))
    story.append(sp(6))

    story.append(Paragraph(
        'A <b>nucleoside</b> = sugar + base only (no phosphate). '
        'Nucleotides are linked by <b>3\'–5\' phosphodiester bonds</b> forming long polynucleotide chains.', BODY))
    story.append(sp(6))

    story.append(Paragraph('Nitrogenous Bases', H2))
    base_data = [
        ['Type', 'Base', 'Found in', 'Structure', 'Pairs with'],
        ['Purine\n(double ring)', 'Adenine (A)', 'DNA & RNA', '6-aminopurine', 'T (DNA) or U (RNA)'],
        ['Purine\n(double ring)', 'Guanine (G)', 'DNA & RNA', '2-amino-6-oxopurine', 'C (DNA & RNA)'],
        ['Pyrimidine\n(single ring)', 'Cytosine (C)', 'DNA & RNA', '2-oxo-4-aminopyrimidine', 'G (DNA & RNA)'],
        ['Pyrimidine\n(single ring)', 'Thymine (T)', 'DNA ONLY', '2,4-dioxo-5-methylpyrimidine', 'A (DNA)'],
        ['Pyrimidine\n(single ring)', 'Uracil (U)', 'RNA ONLY', '2,4-dioxopyrimidine (no methyl)', 'A (RNA)'],
    ]
    story.append(make_table(base_data, cw=[W*0.18, W*0.12, W*0.14, W*0.30, W*0.14]))
    story.append(sp(4))
    story.append(InfoBox(
        ['★  Mnemonic — Purines (double ring): "PURe As Gold" = PURines: Adenine, Guanine',
         '   Pyrimidines (single ring): "CUT the PY" = Cytosine, Uracil, Thymine are PYrimidines',
         '   "Funny (Phunny) = Pyrimidines" — C, U, T are "funny" (single ring)'],
        C_PURPLE_LIGHT, C_PURPLE, ''))
    story.append(sp(6))

    story.append(Paragraph('Watson-Crick Base Pairing Rules', H3))
    story.append(Paragraph('<b>A=T</b> (2 hydrogen bonds) | <b>G≡C</b> (3 hydrogen bonds, stronger!)', BB))
    story.append(Paragraph(
        'Because G≡C pairs have 3 H-bonds, DNA with high G+C content has a higher melting temperature (Tm). '
        'This is used in molecular biology to estimate DNA stability.', BODY))
    story.append(PageBreak())

    # ════════════════════════════════════════════════════════════════════════
    #  SECTION 2: DNA — STRUCTURE
    # ════════════════════════════════════════════════════════════════════════
    story.append(SectionHeader('2.  DNA — Structure', C_BLUE))
    story.append(sp(6))

    story.append(Paragraph('The Watson-Crick Double Helix Model (1953)', H2))
    story.append(Paragraph(
        'DNA exists as a <b>right-handed double helix</b>, as proposed by James Watson and Francis Crick in 1953 '
        '(based on X-ray crystallography data by Rosalind Franklin and Maurice Wilkins). '
        'It resembles a twisted ladder (spiral staircase).', BODY))
    story.append(sp(4))

    dna_feat = [
        ['Feature', 'Detail'],
        ['Two strands', 'Two antiparallel polynucleotide chains (one runs 5\'→3\', the other 3\'→5\')'],
        ['Antiparallel orientation', '5\' end of one strand faces the 3\' end of the other'],
        ['Backbone', 'Sugar-phosphate backbone on the outside of the helix'],
        ['Bases', 'Nitrogenous bases face the inside, stacked perpendicular to helix axis'],
        ['Helix direction', 'Right-handed (B-form is most common in cells)'],
        ['Helix diameter', '~2 nm (20 Å)'],
        ['Base pairs per turn', '10 bp per turn (B-DNA)'],
        ['Rise per base pair', '0.34 nm (3.4 Å)'],
        ['Pitch (full turn)', '3.4 nm per complete turn'],
        ['H-bonds', 'A=T (2 H-bonds); G≡C (3 H-bonds)'],
        ['Major groove', 'Wide groove — accessible to most regulatory proteins and restriction enzymes'],
        ['Minor groove', 'Narrow groove — some drugs and proteins bind here'],
    ]
    story.append(make_table(dna_feat, cw=[W*0.30, W*0.70]))
    story.append(sp(8))

    story.append(Paragraph('Forms of DNA Double Helix', H3))
    forms_data = [
        ['Form', 'Helix', 'bp/turn', 'Conditions', 'Significance'],
        ['B-DNA', 'Right-handed', '10', 'Physiological (aqueous)', 'Most common in living cells (Watson-Crick form)'],
        ['A-DNA', 'Right-handed', '11', 'Dehydrated conditions', 'Seen in RNA-DNA hybrids'],
        ['Z-DNA', 'Left-handed', '12', 'High salt; CG repeats', 'May play a role in gene regulation'],
    ]
    story.append(make_table(forms_data, cw=[W*0.12, W*0.16, W*0.12, W*0.25, W*0.35]))
    story.append(sp(8))

    story.append(Paragraph('DNA Packaging in the Nucleus', H2))
    pack = [
        '• DNA wraps around <b>histone</b> proteins (H2A, H2B, H3, H4 × 2 each) forming the <b>nucleosome</b> (core particle)',
        '• ~147 bp of DNA wraps 1.65 turns around each nucleosome',
        '• Nucleosomes joined by linker DNA (~20-60 bp) + H1 histone = <b>"beads on a string"</b> (10 nm fiber)',
        '• Further coiling → 30 nm fiber (solenoid) → loops → scaffold → chromosome',
        '• Total compaction from ~2 meters of DNA to ~6 μm nucleus!',
    ]
    for p in pack:
        story.append(Paragraph(p, BUL))
    story.append(PageBreak())

    # ════════════════════════════════════════════════════════════════════════
    #  SECTION 3: DNA — FUNCTIONS
    # ════════════════════════════════════════════════════════════════════════
    story.append(SectionHeader('3.  DNA — Functions', C_NAVY))
    story.append(sp(6))

    func_data = [
        ['Function', 'Description', 'How'],
        ['1. Genetic Information Storage', 'DNA carries the hereditary blueprint of every organism in the sequence of its bases (A, T, G, C)', 'Linear sequence of codons encodes amino acid sequences of all proteins'],
        ['2. Replication (Self-copying)', 'Exact duplication before cell division; each daughter cell gets an identical copy', 'Semi-conservative: each strand serves as template; DNA Polymerase synthesizes new strand'],
        ['3. Transcription (Gene Expression)', 'DNA serves as template for RNA synthesis', 'RNA Polymerase reads 3\'→5\' template strand; produces mRNA (5\'→3\')'],
        ['4. Mutation & Evolution', 'Base sequence changes (mutations) introduce genetic variation', 'Point mutations, insertions, deletions drive evolution and disease'],
        ['5. Recombination', 'Genetic diversity via chromosomal crossover during meiosis', 'Homologous recombination shuffles alleles between homologous chromosomes'],
        ['6. Regulation', 'Controls when and how much protein is made', 'Promoters, enhancers, silencers are regulatory DNA sequences'],
    ]
    story.append(make_table(func_data, cw=[W*0.28, W*0.38, W*0.34]))
    story.append(sp(8))

    story.append(Paragraph('DNA Replication — Key Points', H2))
    rep = [
        '• <b>Semi-conservative:</b> Each new DNA molecule has one old strand + one new strand',
        '• <b>Bidirectional:</b> Replication forks move outward from origin of replication (ori) in both directions',
        '• <b>DNA Polymerase III</b> (prokaryotes) / <b>DNA Polymerase δ/ε</b> (eukaryotes) adds nucleotides 5\'→3\'',
        '• Requires a <b>primer</b> (short RNA) — DNA Pol cannot initiate de novo',
        '• <b>Leading strand</b> — synthesized continuously toward replication fork',
        '• <b>Lagging strand</b> — synthesized discontinuously as Okazaki fragments (away from fork)',
        '• <b>Proofreading</b> — DNA Pol has 3\'→5\' exonuclease activity to correct errors (error rate ~10⁻⁹)',
    ]
    for r in rep:
        story.append(Paragraph(r, BUL))
    story.append(sp(4))
    story.append(InfoBox(
        ['⚠  Clinical: DNA Repair Defects',
         '   Xeroderma Pigmentosum: defective Nucleotide Excision Repair → UV damage not repaired → skin cancer',
         '   Lynch syndrome (HNPCC): defective Mismatch Repair → colorectal cancer',
         '   BRCA1/2 mutations: defective Homologous Recombination → breast and ovarian cancer'],
        C_RED_LIGHT, C_RED, ''))
    story.append(PageBreak())

    # ════════════════════════════════════════════════════════════════════════
    #  SECTION 4: RNA — Types & Functions
    # ════════════════════════════════════════════════════════════════════════
    story.append(SectionHeader('4.  RNA — Types and Functions', C_TEAL))
    story.append(sp(6))
    story.append(Paragraph(
        'RNA (Ribonucleic Acid) is a single-stranded nucleic acid transcribed from DNA. '
        'It serves as the intermediary between the genetic code (DNA) and protein synthesis. '
        'Three major functional types + multiple regulatory RNAs exist.',
        BODY))
    story.append(sp(6))

    story.append(Paragraph('A. Three Major Types of RNA', H2))
    major_data = [
        ['Type', 'Abbrev', '% of total RNA', 'Location', 'Function'],
        ['Messenger RNA', 'mRNA', '~3-5%', 'Nucleus → Cytoplasm', 'Carries genetic message (codons) from DNA to ribosome for translation into protein'],
        ['Ribosomal RNA', 'rRNA', '~80%', 'Cytoplasm (ribosomes)', 'Structural and catalytic component of ribosomes; 23S/16S (prokaryote); 28S/18S/5.8S/5S (eukaryote)'],
        ['Transfer RNA', 'tRNA', '~15%', 'Cytoplasm', 'Adaptor molecule: carries specific amino acid to ribosome; anticodon pairs with mRNA codon'],
    ]
    story.append(make_table(major_data, cw=[W*0.17, W*0.10, W*0.13, W*0.18, W*0.42], hbg=C_TEAL))
    story.append(sp(8))

    story.append(Paragraph('B. Other Regulatory RNA Types', H2))
    other_data = [
        ['Type', 'Abbrev', 'Function'],
        ['Small nuclear RNA', 'snRNA', 'Component of spliceosomes; removes introns from pre-mRNA (RNA splicing)'],
        ['Small nucleolar RNA', 'snoRNA', 'Directs chemical modifications (methylation, pseudouridylation) of rRNA and other RNAs in nucleolus'],
        ['MicroRNA', 'miRNA', 'Single-stranded ~22 nt; post-transcriptional gene silencing by binding 3\'UTR of target mRNA → degradation or translation inhibition'],
        ['Small interfering RNA', 'siRNA', 'Double-stranded ~21 nt; RNA interference (RNAi) — cleaves target mRNA; used as experimental tool and therapeutic'],
        ['Long non-coding RNA', 'lncRNA', 'Regulates gene expression at multiple levels; X-chromosome inactivation (XIST), chromatin remodeling'],
        ['Piwi-interacting RNA', 'piRNA', 'Germ-line specific; protects genome from transposable elements/parasitic DNA'],
        ['Ribozyme', '—', 'RNA with catalytic activity (self-splicing introns, ribonuclease P, ribosome peptidyl transferase activity of 23S rRNA)'],
    ]
    story.append(make_table(other_data, cw=[W*0.22, W*0.10, W*0.68], hbg=C_TEAL))
    story.append(sp(8))

    story.append(Paragraph('C. mRNA Structure (Eukaryotic)', H2))
    mrna_parts = [
        ['Component', 'Description', 'Function'],
        ["5' Cap (7-methylguanosine)", "Added co-transcriptionally at 5' end", 'Protects mRNA from degradation; required for ribosome binding (translation initiation)'],
        ['5\' Untranslated Region (UTR)', '5\' of start codon AUG', 'Regulatory; contains Kozak sequence (ribosome binding in eukaryotes)'],
        ['Open Reading Frame (ORF)', 'AUG (start) → UAA/UAG/UGA (stop)', 'Encodes the protein; read in triplet codons'],
        ['3\' UTR', "3' of stop codon", 'Regulatory; binding site for miRNAs; affects stability and translation'],
        ['3\' Poly-A tail', "Added post-transcriptionally; ~200 A's", 'Protects from degradation; aids nuclear export and translation'],
    ]
    story.append(make_table(mrna_parts, cw=[W*0.26, W*0.26, W*0.48], hbg=C_TEAL))
    story.append(sp(8))

    story.append(Paragraph('D. Ribosomal RNA (rRNA) — Key Facts', H2))
    rrna_data = [
        ['Organism', 'Small Subunit', 'Large Subunit', 'Assembled Ribosome', 'rRNA molecules'],
        ['Prokaryotes (E. coli)', '30S  (16S rRNA)', '50S  (23S + 5S rRNA)', '70S', '3 rRNA + ~55 proteins'],
        ['Eukaryotes (Human)', '40S  (18S rRNA)', '60S  (28S + 5.8S + 5S rRNA)', '80S', '4 rRNA + ~80 proteins'],
        ['Mitochondria (Human)', '28S (12S rRNA)', '39S (16S rRNA)', '55S', 'Resembles prokaryotic ribosomes'],
    ]
    story.append(make_table(rrna_data, cw=[W*0.22, W*0.20, W*0.22, W*0.18, W*0.18], hbg=C_TEAL))
    story.append(sp(4))
    story.append(InfoBox(
        ['★  "Goes (G) together (70S)" — 50S + 30S = 70S ribosome (prokaryote)',
         '   "Eukaryote Eighty (80S)" — 60S + 40S = 80S ribosome (eukaryote)',
         '★  Clinically important: Antibiotics target prokaryotic ribosomes:',
         '   30S inhibitors: Tetracycline, Aminoglycosides (Gentamicin), Streptomycin',
         '   50S inhibitors: Chloramphenicol, Erythromycin (macrolides), Clindamycin, Linezolid'],
        C_GOLD_LIGHT, C_GOLD, ''))
    story.append(PageBreak())

    # ════════════════════════════════════════════════════════════════════════
    #  SECTION 5: DNA vs RNA — Comparison
    # ════════════════════════════════════════════════════════════════════════
    story.append(SectionHeader('5.  DIFFERENCES BETWEEN DNA AND RNA', C_PURPLE))
    story.append(sp(6))

    diff_data = [
        ['Feature', 'DNA', 'RNA'],
        ['Full name', 'Deoxyribonucleic Acid', 'Ribonucleic Acid'],
        ['Sugar', 'Deoxyribose (lacks 2\'–OH)', 'Ribose (has 2\'–OH group)'],
        ['Bases', 'A, T, G, C', 'A, U, G, C  (Uracil replaces Thymine)'],
        ['Strands', 'Double-stranded (dsDNA)', 'Usually single-stranded (can fold on itself)'],
        ['Helix', 'Double helix (B-form)', 'No stable helix; forms hairpin loops, stems'],
        ['Location', 'Nucleus + Mitochondria', 'Nucleus + Cytoplasm + Ribosomes'],
        ['Stability', 'Very stable; long-lived', 'Less stable; shorter half-life; degraded by RNases'],
        ['2\'–OH group', 'Absent (deoxy)', 'Present — makes RNA more reactive and less stable'],
        ['Modified bases', '5-methylcytosine (epigenetics)', 'Many: pseudouridine (ψ), dihydrouridine (D), inosine, 7-methylguanosine'],
        ['Function', 'Permanent genetic information storage; template for replication and transcription', 'Functional intermediary: carries (mRNA), adapts (tRNA), and catalyzes (rRNA) protein synthesis'],
        ['Amount in cell', 'Constant (diploid = 6 pg/cell)', 'Variable; depends on gene expression'],
        ['Synthesis', 'DNA Replication (DNA-dependent DNA Pol)', 'Transcription (DNA-dependent RNA Pol); no primer needed'],
        ['Susceptibility', 'Stable to alkali', 'Hydrolyzed by dilute alkali (2\'–OH cleaves phosphodiester bond)'],
        ['Genetic material', 'In all cellular organisms and most viruses', 'Genetic material in RNA viruses (HIV, influenza, SARS-CoV-2)'],
    ]
    story.append(make_table(diff_data, cw=[W*0.22, W*0.39, W*0.39], hbg=C_PURPLE))
    story.append(PageBreak())

    # ════════════════════════════════════════════════════════════════════════
    #  SECTION 6: tRNA — Structure & Function
    # ════════════════════════════════════════════════════════════════════════
    story.append(SectionHeader('6.  tRNA — Structure and Function', C_RED))
    story.append(sp(6))

    story.append(Paragraph('Overview', H2))
    story.append(Paragraph(
        'Transfer RNA (tRNA) is the <b>adaptor molecule</b> of translation. '
        'It decodes the genetic code by carrying a specific amino acid to the ribosome, '
        'where it base-pairs its anticodon with the matching mRNA codon.',
        BODY))
    story.append(sp(4))

    overview = [
        '• Size: <b>73–93 nucleotides</b> (smallest functional RNA in the cell)',
        '• At least <b>20 types</b> of tRNA exist — one for each amino acid',
        '• Some amino acids are carried by multiple tRNAs (<b>isoacceptor tRNAs</b>)',
        '• Charged tRNA (aminoacyl-tRNA) = tRNA with amino acid attached',
        '• The enzyme that attaches amino acid to tRNA: <b>Aminoacyl-tRNA Synthetase</b> (20 types, one per amino acid)',
        '• The Aminoacyl-tRNA synthetase reaction requires <b>ATP → AMP + PPi</b> (consumes 2 high-energy bonds)',
    ]
    for o in overview:
        story.append(Paragraph(o, BUL))
    story.append(sp(8))

    story.append(Paragraph('The Cloverleaf Structure (2D Secondary Structure)', H2))
    story.append(Paragraph(
        'tRNA folds into a <b>cloverleaf</b> shape in 2D due to intramolecular base pairing. '
        'This structure has <b>4 stems</b> and <b>3-4 loops</b>:',
        BODY))
    story.append(sp(6))

    clover_data = [
        ['Structure', 'Base pairs in stem', 'Contents', 'Function'],
        ['Acceptor Stem', '7 bp', "5' end + 3'-CCA (universal)", "3'-CCA-OH is the amino acid attachment site (amino acid links to 3'-OH of ribose of terminal adenosine)"],
        ['D-Arm / D-Stem-Loop', '3-4 bp', 'D-loop contains Dihydrouridine (D) modified base', 'Interaction with aminoacyl-tRNA synthetase for recognition'],
        ['Anticodon Arm', '5 bp', 'Anticodon loop: 7 nt; middle 3 nt = anticodon (5\'–NNN–3\')', 'Anticodon reads mRNA codon by antiparallel complementary base pairing'],
        ['Variable Loop', '0-5 bp (small); up to 21 nt (large)', 'Variable number of nucleotides', 'Varies by tRNA class; used in synthetase recognition in some tRNAs'],
        ['TψC Arm', '5 bp', 'TψC loop contains Ribothymidine (T) and Pseudouridine (ψ)', 'Interacts with ribosome (EF-Tu/EF1A binding region); ensures correct positioning'],
    ]
    story.append(make_table(clover_data, cw=[W*0.20, W*0.16, W*0.28, W*0.36], hbg=C_RED))
    story.append(sp(8))

    story.append(Paragraph('The 3\' CCA End — Universal Feature', H3))
    story.append(Paragraph(
        'ALL tRNAs in ALL organisms end with the sequence <b>3\'-C–C–A–OH</b> at their 3\' terminus. '
        'The amino acid is attached to the <b>2\'–OH or 3\'–OH</b> of the terminal Adenosine by an ester bond. '
        'This CCA sequence is added post-transcriptionally by the enzyme <b>CCA-adding enzyme (tRNA nucleotidyltransferase)</b>.',
        BODY))
    story.append(sp(8))

    story.append(Paragraph('Modified Bases in tRNA', H3))
    mod_data = [
        ['Modified Base', 'Parent Base', 'Location in tRNA', 'Function'],
        ['Dihydrouridine (D)', 'Uridine', 'D-loop', 'Reduces base stacking → allows flexible conformation needed for synthetase recognition'],
        ['Pseudouridine (ψ)', 'Uridine', 'TψC loop', 'Isomeric form of uridine (C5-glycosidic bond instead of N1); stabilizes helix'],
        ['Ribothymidine (T)', 'Thymidine', 'TψC loop', 'Unusual in RNA (T normally only in DNA); ribosome binding'],
        ['Inosine (I)', 'Adenosine', 'Anticodon position 34 (wobble)', 'Wobble base pairing — can pair with U, C, or A on mRNA'],
        ['7-methylguanosine', 'Guanosine', 'Various', 'Part of 5\' cap of mRNA; also in tRNA'],
    ]
    story.append(make_table(mod_data, cw=[W*0.22, W*0.15, W*0.20, W*0.43], hbg=C_RED))
    story.append(sp(6))
    story.append(InfoBox(
        ['★  The Wobble Hypothesis (Crick, 1966):',
         '   The 3rd base of the codon (3rd position) can pair loosely ("wobble") with the 1st base of the anticodon',
         '   This allows ONE tRNA to recognize MULTIPLE codons differing at the 3rd position',
         '   Example: Inosine at anticodon position 34 can pair with U, C, or A in mRNA',
         '   This explains why fewer tRNAs (~45 in humans) are needed than the 61 sense codons'],
        C_ORANGE_LIGHT, C_ORANGE, ''))
    story.append(PageBreak())

    # ════════════════════════════════════════════════════════════════════════
    #  SECTION 7: tRNA CLOVERLEAF DIAGRAM
    # ════════════════════════════════════════════════════════════════════════
    story.append(SectionHeader('7.  tRNA CLOVERLEAF STRUCTURE — Diagram', C_RED))
    story.append(sp(10))
    story.append(TRNACloverleaf(width=W, height=490))
    story.append(sp(8))

    story.append(Paragraph('3D Tertiary Structure of tRNA', H2))
    story.append(Paragraph(
        'The cloverleaf folds further into an <b>L-shaped 3D structure</b> (determined by X-ray crystallography). '
        'The L-shape has two functional ends far apart:',
        BODY))
    l_shape = [
        '• <b>One end (acceptor stem)</b>: holds the amino acid at the 3\'–CCA–OH',
        '• <b>Other end (anticodon loop)</b>: reads the mRNA codon — these two ends are ~7 nm apart',
        '• The D-loop and TψC-loop form tertiary contacts with each other, stabilizing the L-shape',
        '• This L-shape is critical for: (1) fitting into the ribosomal A-site, (2) facilitating peptide bond formation',
    ]
    for l in l_shape:
        story.append(Paragraph(l, BUL))
    story.append(PageBreak())

    # ════════════════════════════════════════════════════════════════════════
    #  SECTION 8: tRNA FUNCTION — Translation
    # ════════════════════════════════════════════════════════════════════════
    story.append(SectionHeader('8.  tRNA FUNCTION in Translation', C_GREEN))
    story.append(sp(6))

    story.append(Paragraph('Steps of tRNA Action', H2))
    steps = [
        ['Step', 'Process', 'Details'],
        ['1', 'Aminoacylation (Charging)', 'Aminoacyl-tRNA Synthetase attaches correct amino acid to 3\'–OH of tRNA. Requires ATP → AMP + PPi. This step "interprets" the genetic code.'],
        ['2', 'Entry to Ribosome (A-site)', 'Aminoacyl-tRNA enters the A-site (acceptor site) of the ribosome as part of ternary complex with EF-Tu (prokaryote) / EF-1A (eukaryote) + GTP'],
        ['3', 'Codon-Anticodon Recognition', 'Anticodon of tRNA base-pairs with mRNA codon in A-site; GTP hydrolysis confirms correct pairing'],
        ['4', 'Peptide Bond Formation', 'Peptidyl transferase (23S rRNA ribozyme activity!) catalyzes transfer of growing peptide chain from P-site tRNA to amino acid on A-site tRNA'],
        ['5', 'Translocation', 'Ribosome moves 3 nucleotides along mRNA; A-site tRNA moves to P-site; P-site tRNA moves to E-site (exit); new A-site is exposed. Catalyzed by EF-G (prokaryote) / EF-2 (eukaryote) + GTP'],
        ['6', 'Release', 'When stop codon (UAA, UAG, UGA) is in A-site, Release Factors (RF) enter; polypeptide is released; ribosome dissociates'],
    ]
    story.append(make_table(steps, cw=[W*0.06, W*0.24, W*0.70], hbg=C_GREEN))
    story.append(sp(8))

    story.append(Paragraph('Ribosomal Sites for tRNA', H3))
    sites_data = [
        ['Site', 'Name', 'Contains', 'Function'],
        ['A-site', 'Aminoacyl site', 'Incoming aminoacyl-tRNA', 'Accepts new charged tRNA; codon-anticodon recognition'],
        ['P-site', 'Peptidyl site', 'tRNA carrying growing peptide', 'Peptide bond formation occurs here'],
        ['E-site', 'Exit site', 'Uncharged tRNA leaving ribosome', 'Discharged tRNA exits here'],
    ]
    story.append(make_table(sites_data, cw=[W*0.10, W*0.18, W*0.25, W*0.47], hbg=C_GREEN))
    story.append(sp(4))
    story.append(InfoBox(
        ['★  Mnemonic for ribosomal sites: "APE" — A (Aminoacyl) → P (Peptidyl) → E (Exit)',
         '   New tRNA enters A, chain is on P, empty tRNA exits from E',
         '★  Important: Peptidyl transferase activity is in 23S rRNA (large subunit) = a RIBOZYME',
         '   This proves the "RNA World" hypothesis — RNA came before protein'],
        C_GREEN_LIGHT, C_GREEN, ''))
    story.append(PageBreak())

    # ════════════════════════════════════════════════════════════════════════
    #  SECTION 9: MASTER SUMMARY & CLINICAL CORRELATIONS
    # ════════════════════════════════════════════════════════════════════════
    story.append(SectionHeader('9.  MASTER SUMMARY & CLINICAL CORRELATIONS', C_NAVY))
    story.append(sp(6))

    story.append(Paragraph('The Central Dogma of Molecular Biology', H2))
    story.append(Paragraph(
        'The Central Dogma (Francis Crick, 1958) describes the flow of genetic information:',
        BODY))
    story.append(sp(4))
    story.append(Paragraph(
        '  DNA  →(Replication)→  DNA  →(Transcription)→  RNA  →(Translation)→  Protein',
        ParagraphStyle('Central', fontSize=12, fontName='Helvetica-Bold', textColor=C_NAVY,
                       alignment=TA_CENTER, spaceBefore=4, spaceAfter=8)))
    additions = [
        '• <b>Reverse Transcription</b> (RNA → DNA): Retroviruses (HIV) use reverse transcriptase',
        '• <b>RNA Replication</b> (RNA → RNA): RNA viruses (influenza, SARS-CoV-2) use RNA-dependent RNA Pol',
        '• <b>No Protein → Nucleic Acid flow</b> exists in nature (Crick\'s "Weismann barrier")',
    ]
    for a in additions:
        story.append(Paragraph(a, BUL))
    story.append(sp(8))

    story.append(Paragraph('Clinical Correlations', H2))
    clin_data = [
        ['Disease / Application', 'Nucleic Acid Relevance', 'Key Detail'],
        ['HIV / AIDS', 'RNA virus; reverse transcription', 'HIV has RNA genome → Reverse Transcriptase → DNA → integrates as provirus. Drug target: RT inhibitors (AZT, Tenofovir)'],
        ['SARS-CoV-2 (COVID-19)', 'RNA virus; mRNA vaccine', 'mRNA vaccines deliver mRNA encoding spike protein → cell makes protein → immune response'],
        ['Cancer (oncogenes)', 'DNA mutations; altered gene expression', 'Proto-oncogene mutations → overexpression (RAS, MYC, HER2); tumor suppressor loss (p53, RB)'],
        ['Xeroderma Pigmentosum', 'DNA repair defect (NER)', 'Cannot repair UV-induced pyrimidine dimers → extreme sun sensitivity → skin cancer'],
        ['Sickle Cell Disease', 'Point mutation in DNA', 'A→T mutation in β-globin gene codon 6 → GAG (Glu) → GTG (Val) → HbS polymerization'],
        ['SLE (Lupus)', 'Autoantibodies to DNA/RNA', 'Anti-dsDNA antibodies, anti-snRNP (Smith) antibodies are diagnostic markers'],
        ['Ribosomes as antibiotic targets', 'rRNA targeted by antibiotics', '30S: tetracyclines, aminoglycosides | 50S: chloramphenicol, macrolides, linezolid'],
        ['PCR / Molecular Diagnostics', 'DNA amplification', 'Polymerase Chain Reaction amplifies specific DNA sequences for diagnosis (COVID-19 PCR test)'],
        ['Gene Therapy', 'Correcting DNA/RNA defects', 'Delivering correct DNA or using RNA interference (siRNA) to silence disease genes'],
        ['siRNA Therapeutics', 'RNA interference', 'Patisiran (Onpattro) — FDA-approved siRNA for hereditary transthyretin amyloidosis'],
    ]
    story.append(make_table(clin_data, cw=[W*0.26, W*0.22, W*0.52]))
    story.append(sp(8))

    story.append(Paragraph('All Key Mnemonics — Quick Reference', H2))
    mne_data = [
        ['Topic', 'Mnemonic'],
        ['Purines (2-ring bases)', '"PURe As Gold" → PURines = Adenine + Guanine'],
        ['Pyrimidines (1-ring bases)', '"CUT the PY" or "Funny" = Cytosine, Uracil, Thymine'],
        ['DNA only base', '"Thymine Tells DNA" — Thymine is DNA-specific (RNA has Uracil)'],
        ['tRNA loops', '"Departed Anticodons To Variable exits" = D-loop, Anticodon, TψC, Variable'],
        ['Ribosomal sites', '"APE" = A-site (Aminoacyl) → P-site (Peptidyl) → E-site (Exit)'],
        ['Prokaryotic ribosomes', '"50 + 30 = 70" — never actually adds like math but mnemonics are: 50S + 30S = 70S'],
        ['Eukaryotic ribosomes', '"60 + 40 = 80" — 60S + 40S = 80S'],
        ['H-bonds in base pairs', '"AT = 2, GC = 3" — AT has 2 H-bonds, GC has 3 (GC is stronger)'],
        ['Antibiotics on 30S', '"TANK" = Tetracyclines, Aminoglycosides, (strep)tomiaN, Kanamycin'],
        ['Antibiotics on 50S', '"CCLE" = Chloramphenicol, Clindamycin, Linezolid, Erythromycin (macrolides)'],
    ]
    story.append(make_table(mne_data, cw=[W*0.32, W*0.68], hbg=C_PURPLE,
                            alt=C_PURPLE_LIGHT))
    story.append(sp(6))
    story.append(Paragraph(
        'Sources: Thompson & Thompson Genetics and Genomics in Medicine, 9th ed  |  '
        'Basic Medical Biochemistry - A Clinical Approach, 6th ed  |  '
        "Harper's Illustrated Biochemistry, 32nd ed  |  Kaplan & Sadock's Comprehensive Textbook of Psychiatry",
        CAP))

    doc.build(story, onFirstPage=draw_cover, onLaterPages=draw_later)
    print(f'PDF created: {out}')

if __name__ == '__main__':
    build()
Running Command

cd /home/daytona/workspace/nucleic-acids-guide && python generate_pdf.py 2>&1

Running Command

ls -lh /home/daytona/workspace/nucleic-acids-guide/Nucleic_Acids_DNA_RNA_StudyGu…

Your study guide PDF is ready! 🎉

Nucleic Acids DNA RNA StudyGuide

PDF Document · PDF


Here's what's inside across 9 sections on a clean A4 print-ready layout:
SectionContent
Cover PageStyled dark-blue cover with full topic list
1. Nucleic Acids OverviewNucleotide components, nitrogenous bases table, Watson-Crick pairing, mnemonics
2. DNA StructureDouble helix features (all measurements), A/B/Z forms comparison, DNA packaging/histones
3. DNA Functions6 functions table, semi-conservative replication, proofreading, repair disorders
4. RNA Types & FunctionsAll 3 major types + 7 regulatory RNAs; mRNA structure (cap, UTR, poly-A); rRNA subunits (prokaryote vs eukaryote)
5. DNA vs RNA ComparisonFull 15-row side-by-side comparison table
6. tRNA Structure & FunctionAll 4 stems + 3 loops explained; 3'-CCA end; modified bases; wobble hypothesis
7. tRNA Cloverleaf DiagramHand-drawn cloverleaf with all arms/loops labeled, color-coded with legend and key facts box
8. tRNA in Translation6-step translation table; A-P-E ribosomal sites; peptidyl transferase (ribozyme)
9. Master SummaryCentral Dogma, clinical correlations (HIV, cancer, antibiotics, mRNA vaccines), all mnemonics
Print tip: Print double-sided on A4 for a neat 5-sheet booklet.

iam not able to download the file because it fails to dowwnload

Running Command

ls -lh /home/daytona/workspace/nucleic-acids-guide/ && ls -lh /home/daytona/work…

Running Command

python3 -c " from pypdf import PdfReader for f in ['/home/daytona/workspace/nucl…

Both PDFs are valid and complete. The download failure is likely a browser/network issue rather than a file problem. Here are a few things to try:

Both PDFs are valid ✅

  • Nucleic Acids guide: 10 pages
  • Carbohydrates guide: 14 pages

Try these download methods:

Method 1 — Right-click the link Right-click the link below → "Save link as..." or "Download linked file"

Nucleic Acids DNA RNA StudyGuide

PDF Document · PDF

Carbohydrates Glucose Metabolism StudyGuide

PDF Document · PDF


Method 2 — Try a different browser If you're on Chrome and it fails, try Firefox or Edge (or vice versa).
Method 3 — Disable browser extensions Ad blockers or security extensions sometimes block file downloads. Try opening in an incognito/private window.
Method 4 — Check your download folder Sometimes the file downloads silently to your Downloads folder without a popup — check there first.
Method 5 — Tell me your device/browser If none of the above work, let me know:
  • What device are you using? (Windows / Mac / Android / iPhone)
  • What browser? (Chrome / Firefox / Safari / Edge)
I can also convert the content to a Word (.docx) file or plain HTML file if the PDF download keeps failing — just let me know!

Create the study guide as a Word document (.docx) instead of PDF

Reading File
Running Command

ls /home/daytona/skills/docx/scripts/office/ && node --version && npm list -g do…

Writing File

~/nucleic-acids-guide/generate_docx.js

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

// ── Colour palette ──────────────────────────────────────────────────────────
const NAVY    = "0F2D5E";
const BLUE    = "1D4ED8";
const TEAL    = "0D9488";
const RED     = "DC2626";
const PURPLE  = "7C3AED";
const GREEN   = "16A34A";
const ORANGE  = "EA580C";
const GOLD    = "B45309";
const WHITE   = "FFFFFF";
const DARK    = "1E293B";
const GRAY    = "475569";
const LGRAY   = "F1F5F9";
const LBLUE   = "DBEAFE";
const LTEAL   = "CCFBF1";
const LRED    = "FEE2E2";
const LPURPLE = "EDE9FE";
const LGREEN  = "DCFCE7";
const LORANGE = "FFF7ED";
const LGOLD   = "FEF3C7";

// ── Helpers ─────────────────────────────────────────────────────────────────
const pt = (n) => n * 20; // half-points to twips

function h1(text, color = NAVY) {
  return new Paragraph({
    heading: HeadingLevel.HEADING_1,
    spacing: { before: pt(12), after: pt(6) },
    children: [new TextRun({ text, bold: true, color, size: pt(14), font: "Calibri" })],
    shading: { type: ShadingType.SOLID, fill: LBLUE },
  });
}

function h2(text, color = NAVY) {
  return new Paragraph({
    heading: HeadingLevel.HEADING_2,
    spacing: { before: pt(10), after: pt(4) },
    children: [new TextRun({ text, bold: true, color, size: pt(12), font: "Calibri" })],
  });
}

function h3(text, color = BLUE) {
  return new Paragraph({
    heading: HeadingLevel.HEADING_3,
    spacing: { before: pt(8), after: pt(3) },
    children: [new TextRun({ text, bold: true, color, size: pt(11), font: "Calibri" })],
  });
}

function sectionHeader(text, bgColor = NAVY) {
  return new Paragraph({
    spacing: { before: pt(14), after: pt(6) },
    shading: { type: ShadingType.SOLID, fill: bgColor },
    children: [new TextRun({ text: `  ${text}`, bold: true, color: WHITE, size: pt(13), font: "Calibri" })],
  });
}

function body(runs) {
  if (typeof runs === "string") {
    runs = [new TextRun({ text: runs, size: pt(10), font: "Calibri", color: DARK })];
  }
  return new Paragraph({
    spacing: { before: pt(2), after: pt(2), line: 276 },
    children: runs,
  });
}

function bullet(text, level = 0) {
  // Parse **bold** markers
  const children = [];
  const parts = text.split(/(\*\*[^*]+\*\*)/g);
  for (const p of parts) {
    if (p.startsWith("**") && p.endsWith("**")) {
      children.push(new TextRun({ text: p.slice(2,-2), bold: true, size: pt(10), font: "Calibri", color: DARK }));
    } else if (p) {
      children.push(new TextRun({ text: p, size: pt(10), font: "Calibri", color: DARK }));
    }
  }
  return new Paragraph({
    bullet: { level },
    spacing: { before: pt(1), after: pt(1), line: 260 },
    children,
  });
}

function boldBody(text) {
  return new Paragraph({
    spacing: { before: pt(2), after: pt(2) },
    children: [new TextRun({ text, bold: true, size: pt(10), font: "Calibri", color: DARK })],
  });
}

function mnemonic(text) {
  return new Paragraph({
    spacing: { before: pt(3), after: pt(3) },
    shading: { type: ShadingType.SOLID, fill: LPURPLE },
    indent: { left: pt(10) },
    children: [new TextRun({ text: `★  ${text}`, bold: true, size: pt(10), font: "Calibri", color: PURPLE })],
  });
}

function infoBox(lines, bgColor = LBLUE, textColor = NAVY) {
  return lines.map(line =>
    new Paragraph({
      spacing: { before: pt(1), after: pt(1) },
      shading: { type: ShadingType.SOLID, fill: bgColor },
      indent: { left: pt(10) },
      children: [new TextRun({
        text: line,
        size: pt(9.5),
        font: "Calibri",
        color: textColor,
        bold: line.startsWith("★") || line.startsWith("⚠"),
      })],
    })
  );
}

function spacer() {
  return new Paragraph({ spacing: { before: pt(4), after: pt(4) }, children: [new TextRun("")] });
}

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

// ── Table builder ─────────────────────────────────────────────────────────
function makeTable(rows, colWidths, headerBg = NAVY) {
  return new Table({
    width: { size: 9300, type: WidthType.DXA },
    margins: { top: 40, bottom: 40, left: 80, right: 80 },
    rows: rows.map((row, ri) =>
      new TableRow({
        children: row.map((cell, ci) => {
          const isHeader = ri === 0;
          const isAlt = !isHeader && ri % 2 === 0;
          const bg = isHeader ? headerBg : (isAlt ? LBLUE : WHITE);
          const textColor = isHeader ? WHITE : DARK;
          const parts = String(cell).split(/(\*\*[^*]+\*\*)/g);
          const runs = parts.map(p => {
            if (p.startsWith("**") && p.endsWith("**")) {
              return new TextRun({ text: p.slice(2,-2), bold: true, size: pt(9), font: "Calibri", color: textColor });
            }
            return new TextRun({ text: p, bold: isHeader, size: pt(9), font: "Calibri", color: textColor });
          });
          return new TableCell({
            width: colWidths ? { size: colWidths[ci], type: WidthType.DXA } : undefined,
            verticalAlign: VerticalAlign.CENTER,
            shading: { type: ShadingType.SOLID, fill: bg },
            borders: {
              top:    { style: BorderStyle.SINGLE, size: 4, color: "CBD5E1" },
              bottom: { style: BorderStyle.SINGLE, size: 4, color: "CBD5E1" },
              left:   { style: BorderStyle.SINGLE, size: 4, color: "CBD5E1" },
              right:  { style: BorderStyle.SINGLE, size: 4, color: "CBD5E1" },
            },
            children: [new Paragraph({
              spacing: { before: 40, after: 40 },
              children: runs,
            })],
          });
        }),
      })
    ),
  });
}

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

// ── TITLE PAGE ──────────────────────────────────────────────────────────────
children.push(
  new Paragraph({ spacing: { before: pt(60) }, children: [] }),
  new Paragraph({
    alignment: AlignmentType.CENTER,
    spacing: { before: pt(20), after: pt(8) },
    shading: { type: ShadingType.SOLID, fill: NAVY },
    children: [new TextRun({ text: "  NUCLEIC ACIDS — DNA & RNA  ", bold: true, color: WHITE, size: pt(28), font: "Calibri" })],
  }),
  new Paragraph({
    alignment: AlignmentType.CENTER,
    spacing: { before: pt(6), after: pt(6) },
    shading: { type: ShadingType.SOLID, fill: BLUE },
    children: [new TextRun({ text: "Complete Study Guide", bold: true, color: WHITE, size: pt(16), font: "Calibri" })],
  }),
  spacer(),
  new Paragraph({
    alignment: AlignmentType.CENTER,
    spacing: { before: pt(4), after: pt(4) },
    children: [new TextRun({ text: "Topics Covered:", bold: true, size: pt(11), color: NAVY, font: "Calibri" })],
  }),
);

const topics = [
  "• Structure and Components of DNA",
  "• Functions of DNA",
  "• Types and Functions of RNA",
  "• Differences Between DNA and RNA",
  "• Structure and Function of tRNA",
  "• Cloverleaf Structure of tRNA (Detailed Diagram)",
  "• Modified Bases in RNA",
  "• Clinical Correlations",
];
for (const t of topics) {
  children.push(new Paragraph({
    alignment: AlignmentType.CENTER,
    spacing: { before: pt(2), after: pt(2) },
    children: [new TextRun({ text: t, size: pt(11), color: DARK, font: "Calibri" })],
  }));
}

children.push(
  spacer(),
  new Paragraph({
    alignment: AlignmentType.CENTER,
    spacing: { before: pt(6) },
    children: [new TextRun({
      text: "Sources: Thompson & Thompson Genetics 9e  |  Basic Medical Biochemistry 6e  |  Harper's Illustrated Biochemistry 32e",
      size: pt(8), color: GRAY, italics: true, font: "Calibri"
    })],
  }),
  pageBreak(),
);

// ════════════════════════════════════════════════════════════════════════════
// SECTION 1 — NUCLEIC ACIDS OVERVIEW
// ════════════════════════════════════════════════════════════════════════════
children.push(
  sectionHeader("1.  NUCLEIC ACIDS — Overview & Components", NAVY),
  spacer(),
  body("Nucleic acids are biological macromolecules that store and transmit genetic information and direct protein synthesis. There are two types: DNA (Deoxyribonucleic Acid) and RNA (Ribonucleic Acid)."),
  spacer(),
  h2("Building Blocks — Nucleotides"),
  body("A nucleotide = three components joined together:"),
  bullet("**Pentose sugar** — Deoxyribose (DNA) or Ribose (RNA)"),
  bullet("**Nitrogenous base** — Purine or Pyrimidine"),
  bullet("**Phosphate group** — One or more phosphates (mono/di/triphosphate)"),
  body("A nucleoside = sugar + base only (no phosphate). Nucleotides are linked by 3'–5' phosphodiester bonds forming long polynucleotide chains."),
  spacer(),
  h2("Nitrogenous Bases"),
  makeTable([
    ["Type", "Base", "Found in", "Structure", "Pairs with"],
    ["Purine (2-ring)", "Adenine (A)", "DNA & RNA", "6-aminopurine", "T (DNA) / U (RNA)"],
    ["Purine (2-ring)", "Guanine (G)", "DNA & RNA", "2-amino-6-oxopurine", "C"],
    ["Pyrimidine (1-ring)", "Cytosine (C)", "DNA & RNA", "2-oxo-4-aminopyrimidine", "G"],
    ["Pyrimidine (1-ring)", "Thymine (T)", "DNA ONLY", "5-methyluracil", "A (DNA)"],
    ["Pyrimidine (1-ring)", "Uracil (U)", "RNA ONLY", "No methyl group at C5", "A (RNA)"],
  ], [1800, 1100, 1000, 2200, 1000]),
  spacer(),
  mnemonic("Purines = 'PURe As Gold' → Adenine + Guanine  |  Pyrimidines = 'CUT' → Cytosine, Uracil, Thymine"),
  spacer(),
  h2("Watson-Crick Base Pairing"),
  boldBody("A = T  (2 hydrogen bonds)   |   G ≡ C  (3 hydrogen bonds — stronger, higher melting temperature)"),
  body("Higher G+C content = higher melting temperature (Tm) of DNA. Used in molecular biology to estimate DNA stability."),
  pageBreak(),
);

// ════════════════════════════════════════════════════════════════════════════
// SECTION 2 — DNA STRUCTURE
// ════════════════════════════════════════════════════════════════════════════
children.push(
  sectionHeader("2.  DNA — Structure", BLUE),
  spacer(),
  h2("The Watson-Crick Double Helix Model (1953)"),
  body("DNA exists as a right-handed double helix proposed by James Watson and Francis Crick in 1953, based on X-ray crystallography data by Rosalind Franklin. It resembles a twisted ladder (spiral staircase)."),
  spacer(),
  makeTable([
    ["Feature", "Detail"],
    ["Two strands", "Two antiparallel polynucleotide chains (one runs 5'→3', the other 3'→5')"],
    ["Antiparallel", "5' end of one strand faces the 3' end of the other"],
    ["Backbone", "Sugar-phosphate backbone on the OUTSIDE of the helix"],
    ["Bases", "Nitrogenous bases face INSIDE, stacked perpendicular to helix axis"],
    ["Helix direction", "Right-handed (B-form — most common in cells)"],
    ["Helix diameter", "~2 nm (20 Å)"],
    ["Base pairs per turn", "10 bp per turn (B-DNA)"],
    ["Rise per base pair", "0.34 nm (3.4 Å) between adjacent base pairs"],
    ["Pitch (full turn)", "3.4 nm per complete turn of helix"],
    ["H-bonds", "A=T: 2 H-bonds  |  G≡C: 3 H-bonds (stronger)"],
    ["Major groove", "Wide — accessible to regulatory proteins, restriction enzymes"],
    ["Minor groove", "Narrow — some drugs (e.g. netropsin) and proteins bind here"],
  ], [2800, 6400]),
  spacer(),
  h2("Forms of DNA Double Helix"),
  makeTable([
    ["Form", "Helix", "bp/turn", "Conditions", "Significance"],
    ["B-DNA", "Right-handed", "10", "Physiological (aqueous)", "Most common in living cells — Watson-Crick form"],
    ["A-DNA", "Right-handed", "11", "Dehydrated conditions", "Found in RNA-DNA hybrid duplexes"],
    ["Z-DNA", "Left-handed", "12", "High salt; CG repeats", "May play a role in gene regulation"],
  ], [1200, 1400, 900, 2000, 3200]),
  spacer(),
  h2("DNA Packaging in the Nucleus"),
  bullet("DNA wraps around **histone** proteins (H2A, H2B, H3, H4 ×2 each) forming the **nucleosome** (core particle)"),
  bullet("~147 bp of DNA wraps 1.65 turns around each nucleosome"),
  bullet("Nucleosomes joined by linker DNA (~20-60 bp) + H1 histone = 'beads on a string' (10 nm fiber)"),
  bullet("Further coiling → 30 nm fiber (solenoid) → loops → scaffold → chromosome"),
  bullet("Total compaction: ~2 meters of DNA packed into a ~6 μm nucleus!"),
  pageBreak(),
);

// ════════════════════════════════════════════════════════════════════════════
// SECTION 3 — DNA FUNCTIONS
// ════════════════════════════════════════════════════════════════════════════
children.push(
  sectionHeader("3.  DNA — Functions", NAVY),
  spacer(),
  makeTable([
    ["Function", "Description", "Mechanism"],
    ["1. Genetic Information Storage", "Carries the hereditary blueprint in the sequence of A, T, G, C", "Linear sequence of codons encodes amino acid sequences of all proteins"],
    ["2. Replication (Self-copying)", "Exact duplication before every cell division", "Semi-conservative: each strand is a template; DNA Pol synthesizes new complementary strand"],
    ["3. Transcription (Gene Expression)", "DNA serves as template for RNA synthesis", "RNA Polymerase reads 3'→5' template strand; produces mRNA 5'→3'"],
    ["4. Mutation & Evolution", "Base sequence changes introduce genetic variation", "Point mutations, insertions, deletions drive evolution and disease"],
    ["5. Recombination", "Genetic diversity via chromosomal crossover in meiosis", "Homologous recombination shuffles alleles between homologous chromosomes"],
    ["6. Gene Regulation", "Controls when and how much protein is made", "Promoters, enhancers, silencers, insulators are regulatory DNA elements"],
  ], [2000, 3000, 4200]),
  spacer(),
  h2("DNA Replication — Key Points"),
  bullet("**Semi-conservative:** Each new DNA = one original strand + one new strand"),
  bullet("**Bidirectional:** Replication forks move from origin (ori) in both directions"),
  bullet("**DNA Pol III** (prokaryotes) / **DNA Pol δ/ε** (eukaryotes) adds nucleotides 5'→3'"),
  bullet("Requires a **RNA primer** — DNA Pol cannot initiate synthesis de novo"),
  bullet("**Leading strand** — synthesized continuously toward the replication fork"),
  bullet("**Lagging strand** — synthesized discontinuously as Okazaki fragments"),
  bullet("**Proofreading** — DNA Pol 3'→5' exonuclease corrects errors (rate ~1 in 10⁹)"),
  spacer(),
  ...infoBox([
    "⚠  DNA Repair Defects — Clinical Correlations:",
    "   Xeroderma Pigmentosum: defective Nucleotide Excision Repair → UV damage → skin cancers",
    "   Lynch syndrome (HNPCC): defective Mismatch Repair → colorectal cancer",
    "   BRCA1/2 mutations: defective Homologous Recombination → breast & ovarian cancer",
  ], LRED, RED),
  pageBreak(),
);

// ════════════════════════════════════════════════════════════════════════════
// SECTION 4 — RNA TYPES & FUNCTIONS
// ════════════════════════════════════════════════════════════════════════════
children.push(
  sectionHeader("4.  RNA — Types and Functions", TEAL),
  spacer(),
  body("RNA (Ribonucleic Acid) is a single-stranded nucleic acid transcribed from DNA. It serves as the intermediary between the genetic code (DNA) and protein synthesis."),
  spacer(),
  h2("A. Three Major Types of RNA"),
  makeTable([
    ["Type", "Abbrev", "% of RNA", "Location", "Function"],
    ["Messenger RNA", "mRNA", "~3-5%", "Nucleus → Cytoplasm", "Carries genetic message (codons) from DNA to ribosome for translation into protein"],
    ["Ribosomal RNA", "rRNA", "~80%", "Cytoplasm (ribosomes)", "Structural AND catalytic component of ribosomes; 28S/18S/5.8S/5S (eukaryotes)"],
    ["Transfer RNA", "tRNA", "~15%", "Cytoplasm", "Adaptor molecule: carries amino acid to ribosome; anticodon pairs with mRNA codon"],
  ], [1600, 800, 800, 1600, 4400], TEAL),
  spacer(),
  h2("B. Other Regulatory RNA Types"),
  makeTable([
    ["Type", "Abbrev", "Function"],
    ["Small nuclear RNA", "snRNA", "Component of spliceosomes; removes introns from pre-mRNA (RNA splicing)"],
    ["Small nucleolar RNA", "snoRNA", "Directs chemical modifications (methylation, pseudouridylation) of rRNA in nucleolus"],
    ["MicroRNA", "miRNA", "Single-stranded ~22 nt; post-transcriptional gene silencing by binding 3'UTR of target mRNA"],
    ["Small interfering RNA", "siRNA", "Double-stranded ~21 nt; RNA interference (RNAi) — cleaves target mRNA; therapeutic uses"],
    ["Long non-coding RNA", "lncRNA", "Regulates gene expression; X-chromosome inactivation (XIST); chromatin remodeling"],
    ["Ribozyme", "—", "RNA with catalytic activity (self-splicing introns; peptidyl transferase of 23S rRNA)"],
  ], [2000, 900, 6200], TEAL),
  spacer(),
  h2("C. mRNA Structure (Eukaryotic)"),
  makeTable([
    ["Component", "Description", "Function"],
    ["5' Cap (7-methylguanosine)", "Added co-transcriptionally at 5' end", "Protects from degradation; required for ribosome binding"],
    ["5' UTR", "5' of start codon AUG", "Contains Kozak sequence; ribosome binding in eukaryotes"],
    ["Open Reading Frame (ORF)", "AUG (start) → UAA/UAG/UGA (stop)", "Encodes the protein; read as triplet codons"],
    ["3' UTR", "3' of stop codon", "Regulatory; binding site for miRNAs; affects mRNA stability"],
    ["3' Poly-A tail", "~200 adenosine residues added post-transcriptionally", "Protects from degradation; aids nuclear export and translation"],
  ], [2200, 2400, 4600], TEAL),
  spacer(),
  h2("D. Ribosomal RNA (rRNA) — Prokaryote vs Eukaryote"),
  makeTable([
    ["Organism", "Small Subunit", "Large Subunit", "Ribosome", "Notes"],
    ["Prokaryotes (E. coli)", "30S (16S rRNA)", "50S (23S + 5S rRNA)", "70S", "Target of aminoglycosides, tetracyclines (30S); chloramphenicol, macrolides (50S)"],
    ["Eukaryotes (Human)", "40S (18S rRNA)", "60S (28S + 5.8S + 5S rRNA)", "80S", "Targeted by diphtheria toxin (EF-2), ricin (28S rRNA)"],
    ["Mitochondria (Human)", "28S (12S rRNA)", "39S (16S rRNA)", "55S", "Resembles prokaryotic — explains aminoglycoside ototoxicity/nephrotoxicity"],
  ], [1600, 1600, 2200, 900, 3200], TEAL),
  spacer(),
  ...infoBox([
    "★  Antibiotics targeting ribosomes:",
    "   30S inhibitors: Tetracyclines, Aminoglycosides (Gentamicin), Streptomycin",
    "   50S inhibitors: Chloramphenicol, Erythromycin (macrolides), Clindamycin, Linezolid",
    "   Mnemonic: 'TANK' hits 30S | 'CCLE' hits 50S",
  ], LGOLD, GOLD),
  pageBreak(),
);

// ════════════════════════════════════════════════════════════════════════════
// SECTION 5 — DNA vs RNA
// ════════════════════════════════════════════════════════════════════════════
children.push(
  sectionHeader("5.  DIFFERENCES BETWEEN DNA AND RNA", PURPLE),
  spacer(),
  makeTable([
    ["Feature", "DNA", "RNA"],
    ["Full name", "Deoxyribonucleic Acid", "Ribonucleic Acid"],
    ["Sugar", "Deoxyribose (lacks 2'–OH)", "Ribose (has 2'–OH group)"],
    ["Bases", "A, T, G, C", "A, U, G, C  (Uracil replaces Thymine)"],
    ["Strands", "Double-stranded (dsDNA)", "Usually single-stranded (can fold on itself)"],
    ["Helix", "Double helix (right-handed B-form)", "No stable helix; forms hairpin loops, stems"],
    ["Location", "Nucleus + Mitochondria", "Nucleus + Cytoplasm + Ribosomes"],
    ["Stability", "Very stable; long-lived", "Less stable; shorter half-life; degraded by RNases"],
    ["2'–OH group", "Absent (deoxy = more stable)", "Present — makes RNA more reactive and less stable"],
    ["Modified bases", "5-methylcytosine (epigenetics; CpG)", "Many: pseudouridine (ψ), dihydrouridine (D), inosine, 7-methylguanosine"],
    ["Function", "Permanent genetic information storage; template", "Functional intermediary: carries (mRNA), adapts (tRNA), catalyzes (rRNA)"],
    ["Amount in cell", "Constant (diploid = 6 pg/cell)", "Variable; depends on level of gene expression"],
    ["Synthesis", "DNA Replication (DNA-dependent DNA Pol)", "Transcription (DNA-dependent RNA Pol); no primer needed"],
    ["Alkali stability", "Stable to dilute alkali", "Hydrolyzed by dilute alkali (2'–OH cleaves phosphodiester bond)"],
    ["As genetic material", "All cellular organisms + most viruses", "RNA viruses: HIV, influenza, SARS-CoV-2"],
  ], [2200, 3300, 3700], PURPLE),
  pageBreak(),
);

// ════════════════════════════════════════════════════════════════════════════
// SECTION 6 — tRNA STRUCTURE & FUNCTION
// ════════════════════════════════════════════════════════════════════════════
children.push(
  sectionHeader("6.  tRNA — Structure and Function", RED),
  spacer(),
  h2("Overview"),
  body("Transfer RNA (tRNA) is the adaptor molecule of translation. It decodes the genetic code by carrying a specific amino acid to the ribosome, where its anticodon base-pairs with the matching mRNA codon."),
  bullet("**Size:** 73–93 nucleotides (smallest functional RNA in the cell)"),
  bullet("At least **20 types** of tRNA exist — one for each amino acid"),
  bullet("Some amino acids have multiple tRNAs (**isoacceptor tRNAs**)"),
  bullet("**Charged tRNA** (aminoacyl-tRNA) = tRNA with amino acid attached"),
  bullet("**Aminoacyl-tRNA Synthetase** attaches amino acid to tRNA (20 types, one per amino acid)"),
  bullet("The charging reaction requires **ATP → AMP + PPi** (consumes 2 high-energy phosphate bonds)"),
  spacer(),
  h2("The Cloverleaf Structure (2D Secondary Structure)"),
  body("tRNA folds into a cloverleaf shape due to intramolecular base pairing. It has 4 stems and 3-4 loops:"),
  spacer(),
  makeTable([
    ["Structure", "Base Pairs\nin Stem", "Contents", "Function"],
    ["Acceptor Stem", "7 bp", "5' end + universal 3'-CCA", "3'-CCA-OH is the amino acid attachment site; amino acid links to 3'-OH of terminal adenosine"],
    ["D-Arm (D-Stem-Loop)", "3-4 bp", "D-loop: contains Dihydrouridine (D) modified base", "Recognition by aminoacyl-tRNA synthetase"],
    ["Anticodon Arm", "5 bp", "Anticodon loop: 7 nt; middle 3 nt = anticodon (5'-NNN-3')", "Anticodon reads mRNA codon by antiparallel complementary base pairing"],
    ["Variable Loop", "0-5 bp (small)\nor up to 21 nt", "Variable number of nucleotides (4-21)", "Varies by tRNA class; used in synthetase recognition in Class II tRNAs"],
    ["TψC Arm", "5 bp", "TψC loop: contains Ribothymidine (T) and Pseudouridine (ψ)", "Interacts with ribosome (EF-Tu binding); ensures correct positioning in A-site"],
  ], [1800, 1200, 2800, 3400], RED),
  spacer(),
  h3("The 3'-CCA End — Universal Feature"),
  body("ALL tRNAs in ALL organisms end with 3'-C–C–A–OH. The amino acid is attached to the 2'–OH or 3'–OH of the terminal Adenosine by an ester bond. The CCA sequence is added post-transcriptionally by CCA-adding enzyme (tRNA nucleotidyltransferase)."),
  spacer(),
  h3("Modified Bases in tRNA"),
  makeTable([
    ["Modified Base", "Parent Base", "Location", "Function"],
    ["Dihydrouridine (D)", "Uridine", "D-loop", "Reduces base stacking → flexible conformation for synthetase recognition"],
    ["Pseudouridine (ψ)", "Uridine", "TψC loop", "C5-glycosidic bond (instead of N1); stabilizes helix structure"],
    ["Ribothymidine (T)", "Thymidine", "TψC loop", "Unusual in RNA (T normally only in DNA); involved in ribosome binding"],
    ["Inosine (I)", "Adenosine", "Anticodon position 34 (wobble)", "Wobble base: can pair with U, C, or A on mRNA → fewer tRNAs needed"],
    ["7-methylguanosine", "Guanosine", "5' cap of mRNA / tRNA", "Part of mRNA 5' cap; also modifies tRNA"],
  ], [2000, 1400, 1800, 4000], RED),
  spacer(),
  ...infoBox([
    "★  Wobble Hypothesis (Crick, 1966):",
    "   The 3rd codon base pairs loosely ('wobbles') with 1st anticodon base",
    "   ONE tRNA can recognize MULTIPLE codons differing at the 3rd position",
    "   Inosine at anticodon pos. 34 can pair with U, C, or A on mRNA",
    "   This explains why only ~45 tRNAs (humans) read 61 sense codons",
  ], LORANGE, ORANGE),
  pageBreak(),
);

// ════════════════════════════════════════════════════════════════════════════
// SECTION 7 — tRNA CLOVERLEAF DIAGRAM (ASCII / text-art)
// ════════════════════════════════════════════════════════════════════════════
children.push(
  sectionHeader("7.  tRNA CLOVERLEAF STRUCTURE — Annotated Diagram", RED),
  spacer(),
  new Paragraph({
    spacing: { before: pt(4), after: pt(4) },
    shading: { type: ShadingType.SOLID, fill: "F8FAFC" },
    alignment: AlignmentType.CENTER,
    children: [new TextRun({ text: "tRNA Cloverleaf — 2D Secondary Structure", bold: true, size: pt(13), color: NAVY, font: "Courier New" })],
  }),
  spacer(),
);

// Build the cloverleaf as a monospaced text diagram
const cloverLines = [
  "                     5'─────────────────────────────3'─CCA─OH",
  "                          │  A C C E P T O R  │         │",
  "                          │    S T E M        │    ← Amino acid",
  "                          │   (7 base pairs)  │       attaches",
  "                          │                   │       here",
  "                    ┌─────┘                   └─────┐",
  "                    │                               │",
  "              D-ARM │                               │ TψC-ARM",
  "             (3-4bp)│                               │(5bp)",
  "                    │                               │",
  "              ┌─────┘                               └─────┐",
  "              │   D - L O O P                TψC-LOOP    │",
  "              │  (Dihydrouridine)          (Ribothymidine │",
  "              │                             + Pseudouridine│",
  "              └─────┐                               ┌─────┘",
  "                    │                               │",
  "                    │        VARIABLE LOOP          │",
  "                    │         (4-21 nt)             │",
  "                    └───────────┬───────────────────┘",
  "                                │",
  "                         ANTICODON ARM",
  "                           (5 bp stem)",
  "                                │",
  "                         ┌─────────────┐",
  "                         │             │",
  "                         │  ANTICODON  │",
  "                         │    LOOP     │",
  "                         │  5'-N-N-N-3'│  ← base-pairs with",
  "                         │             │    mRNA CODON",
  "                         └─────────────┘",
];

for (const line of cloverLines) {
  children.push(new Paragraph({
    spacing: { before: 20, after: 20 },
    shading: { type: ShadingType.SOLID, fill: "F8FAFC" },
    children: [new TextRun({ text: line, font: "Courier New", size: pt(9.5), color: DARK })],
  }));
}

children.push(
  spacer(),
  new Paragraph({
    alignment: AlignmentType.CENTER,
    spacing: { before: pt(4), after: pt(4) },
    shading: { type: ShadingType.SOLID, fill: LRED },
    children: [new TextRun({
      text: "★  The cloverleaf (2D) folds into an L-shaped 3D structure — acceptor end and anticodon end are ~7 nm apart",
      bold: true, size: pt(10), color: RED, font: "Calibri"
    })],
  }),
  spacer(),
  h2("Summary of tRNA Loops and Arms"),
  makeTable([
    ["Region", "Stem (bp)", "Key Bases", "Function"],
    ["Acceptor stem", "7 bp", "5' end + 3'-CCA", "Amino acid attachment (ester bond to 3'-CCA-OH)"],
    ["D-loop / D-arm", "3-4 bp", "Dihydrouridine (D)", "Synthetase recognition; 'D' stands for dihydrouridine"],
    ["Anticodon loop / arm", "5 bp", "Anticodon (3 nt) + wobble base", "Reads mRNA codon by antiparallel complementary base pairing"],
    ["Variable loop", "0-5 bp", "Variable (4-21 nt)", "Classification of tRNA class; synthetase recognition in Class II"],
    ["TψC loop / arm", "5 bp", "Ribothymidine (T), Pseudouridine (ψ)", "Ribosome binding via EF-Tu; correct A-site positioning"],
  ], [1800, 1200, 2200, 4000], RED),
  pageBreak(),
);

// ════════════════════════════════════════════════════════════════════════════
// SECTION 8 — tRNA FUNCTION IN TRANSLATION
// ════════════════════════════════════════════════════════════════════════════
children.push(
  sectionHeader("8.  tRNA FUNCTION in Translation", GREEN),
  spacer(),
  h2("Steps of tRNA Action"),
  makeTable([
    ["Step", "Process", "Details"],
    ["1", "Aminoacylation (Charging)", "Aminoacyl-tRNA Synthetase attaches correct amino acid to 3'–OH of tRNA. Requires ATP → AMP + PPi. This step 'reads' the genetic code."],
    ["2", "Entry to Ribosome (A-site)", "Charged tRNA enters A-site as ternary complex with EF-Tu (prokaryote) / EF-1A (eukaryote) + GTP. GTP hydrolysis confirms correct codon-anticodon match."],
    ["3", "Codon-Anticodon Recognition", "Anticodon (3 nt) base-pairs with mRNA codon in A-site; wobble base pairing at 3rd codon position allowed"],
    ["4", "Peptide Bond Formation", "Peptidyl transferase (23S rRNA — a RIBOZYME!) transfers growing peptide from P-site tRNA to amino acid on A-site tRNA"],
    ["5", "Translocation", "Ribosome moves 3 nt along mRNA: A→P→E. EF-G (prokaryote) / EF-2 (eukaryote) + GTP hydrolysis drives this step"],
    ["6", "Release", "Stop codon (UAA, UAG, UGA) at A-site — Release Factors (RF1/2) enter; polypeptide released; ribosome dissociates"],
  ], [400, 2200, 6600], GREEN),
  spacer(),
  h2("Ribosomal Sites for tRNA"),
  makeTable([
    ["Site", "Name", "Contains", "Function"],
    ["A-site", "Aminoacyl site", "Incoming aminoacyl-tRNA", "Accepts new charged tRNA; codon-anticodon recognition occurs here"],
    ["P-site", "Peptidyl site", "tRNA carrying growing peptide chain", "Peptide bond formation occurs; peptide transferred from P to A-site tRNA"],
    ["E-site", "Exit site", "Uncharged (empty) tRNA leaving", "Discharged tRNA exits ribosome from here"],
  ], [900, 1700, 2500, 4100], GREEN),
  spacer(),
  mnemonic("Ribosomal sites: 'APE' = A (Aminoacyl) → P (Peptidyl) → E (Exit)"),
  mnemonic("Peptidyl transferase is a RIBOZYME (23S rRNA) — proves the RNA World hypothesis"),
  pageBreak(),
);

// ════════════════════════════════════════════════════════════════════════════
// SECTION 9 — MASTER SUMMARY & CLINICAL CORRELATIONS
// ════════════════════════════════════════════════════════════════════════════
children.push(
  sectionHeader("9.  MASTER SUMMARY & CLINICAL CORRELATIONS", NAVY),
  spacer(),
  h2("The Central Dogma of Molecular Biology"),
  new Paragraph({
    alignment: AlignmentType.CENTER,
    spacing: { before: pt(6), after: pt(8) },
    shading: { type: ShadingType.SOLID, fill: LBLUE },
    children: [
      new TextRun({ text: "  DNA  →(Replication)→  DNA  →(Transcription)→  RNA  →(Translation)→  Protein  ", bold: true, size: pt(12), font: "Calibri", color: NAVY }),
    ],
  }),
  bullet("**Reverse Transcription** (RNA → DNA): Retroviruses (HIV) use reverse transcriptase"),
  bullet("**RNA Replication** (RNA → RNA): RNA viruses (influenza, SARS-CoV-2) use RNA-dependent RNA Polymerase"),
  bullet("No Protein → Nucleic Acid flow exists in nature ('Weismann barrier')"),
  spacer(),
  h2("Clinical Correlations"),
  makeTable([
    ["Disease / Application", "Nucleic Acid Connection", "Key Detail"],
    ["HIV/AIDS", "RNA virus; reverse transcription", "HIV RNA → Reverse Transcriptase → DNA → integrates as provirus. Target: RT inhibitors (AZT, Tenofovir)"],
    ["SARS-CoV-2 (COVID-19)", "RNA virus; mRNA vaccine", "mRNA vaccines deliver mRNA encoding spike protein → immune response without live virus"],
    ["Cancer", "DNA mutations; altered expression", "Proto-oncogene mutations (RAS, MYC, HER2); tumor suppressor loss (p53, RB, BRCA)"],
    ["Xeroderma Pigmentosum", "DNA repair defect (NER)", "Cannot repair UV-induced thymine dimers → extreme photosensitivity → multiple skin cancers"],
    ["Sickle Cell Disease", "Single nucleotide mutation", "GAG→GTG in β-globin codon 6 → Glu→Val → HbS polymerization under hypoxia"],
    ["SLE (Lupus)", "Autoantibodies to DNA/RNA", "Anti-dsDNA and anti-snRNP (Smith) antibodies are diagnostic markers of SLE"],
    ["Antibiotic targets", "rRNA structural targets", "30S: aminoglycosides, tetracyclines  |  50S: chloramphenicol, macrolides, linezolid"],
    ["PCR Diagnostics", "DNA amplification", "PCR amplifies specific DNA/cDNA sequences — basis of COVID-19 molecular tests, pathogen ID"],
    ["siRNA Therapeutics", "RNA interference", "Patisiran (FDA-approved siRNA) — treats hereditary transthyretin amyloidosis"],
    ["mRNA Vaccines", "Synthetic mRNA delivery", "BNT162b2 (Pfizer), mRNA-1273 (Moderna) — modified mRNA with N1-methylpseudouridine for stability"],
  ], [2000, 2000, 5200]),
  spacer(),
  h2("All Key Mnemonics — Quick Reference"),
  makeTable([
    ["Topic", "Mnemonic"],
    ["Purines (2-ring)", "'PURe As Gold' → Purines = Adenine + Guanine"],
    ["Pyrimidines (1-ring)", "'CUT the PY' = Cytosine, Uracil, Thymine are Pyrimidines"],
    ["DNA-only base", "'Thymine Tells DNA' — Thymine is DNA-specific; RNA has Uracil"],
    ["tRNA loops", "'Departed Anticodons To Variable exits' = D-loop, Anticodon, TψC, Variable"],
    ["Ribosomal sites", "'APE' = A-site (Aminoacyl) → P-site (Peptidyl) → E-site (Exit)"],
    ["Prokaryotic ribosome", "50S + 30S = 70S  (antibiotic target)"],
    ["Eukaryotic ribosome", "60S + 40S = 80S  (diphtheria toxin, ricin target)"],
    ["H-bonds in base pairs", "'AT = 2, GC = 3' — AT has 2, GC has 3 H-bonds (GC is stronger)"],
    ["30S antibiotics", "'TANK' = Tetracyclines, Aminoglycosides, Neomycin, Kanamycin"],
    ["50S antibiotics", "'CCLE' = Chloramphenicol, Clindamycin, Linezolid, Erythromycin"],
    ["Anticodon wobble", "Inosine (I) at pos. 34 pairs with U, C, or A — 'I wobble with everyone'"],
    ["Central Dogma", "DNA → RNA → Protein  ('DRiP' = DNA Replicates in Pairs)"],
  ], [3200, 6000], PURPLE),
  spacer(),
  new Paragraph({
    alignment: AlignmentType.CENTER,
    spacing: { before: pt(10) },
    children: [new TextRun({
      text: "Sources: Thompson & Thompson Genetics 9e  |  Basic Medical Biochemistry 6e  |  Harper's Illustrated Biochemistry 32e  |  Kaplan & Sadock's Comprehensive Textbook of Psychiatry",
      size: pt(8), italics: true, color: GRAY, font: "Calibri"
    })],
  }),
);

// ════════════════════════════════════════════════════════════════════════════
// BUILD DOCUMENT
// ════════════════════════════════════════════════════════════════════════════
const doc = new Document({
  creator: "Orris Medical",
  title: "Nucleic Acids — DNA & RNA Study Guide",
  description: "Complete study guide for Nucleic Acids including DNA structure, RNA types, and tRNA cloverleaf",
  styles: {
    default: {
      document: {
        run: { font: "Calibri", size: pt(10), color: DARK },
      },
    },
  },
  sections: [{
    properties: {
      page: {
        margin: { top: 720, bottom: 720, left: 900, right: 900 },
      },
    },
    headers: {
      default: new Header({
        children: [
          new Paragraph({
            alignment: AlignmentType.RIGHT,
            shading: { type: ShadingType.SOLID, fill: NAVY },
            children: [
              new TextRun({ text: "  NUCLEIC ACIDS — DNA & RNA  |  Study Guide  |  Page ", bold: true, color: WHITE, size: pt(8.5), font: "Calibri" }),
              new TextRun({ children: [new PageNumber()], bold: true, color: WHITE, size: pt(8.5), font: "Calibri" }),
              new TextRun({ text: "  ", color: WHITE, size: pt(8.5) }),
            ],
          }),
        ],
      }),
    },
    footers: {
      default: new Footer({
        children: [
          new Paragraph({
            alignment: AlignmentType.CENTER,
            children: [new TextRun({
              text: "Thompson & Thompson Genetics 9e  |  Basic Medical Biochemistry 6e  |  Harper's Illustrated Biochemistry 32e",
              size: pt(7.5), italics: true, color: GRAY, font: "Calibri"
            })],
          }),
        ],
      }),
    },
    children,
  }],
});

const outPath = "/home/daytona/workspace/nucleic-acids-guide/Nucleic_Acids_DNA_RNA_StudyGuide.docx";
Packer.toBuffer(doc).then(buf => {
  fs.writeFileSync(outPath, buf);
  console.log("Created:", outPath, `(${(buf.length/1024).toFixed(1)} KB)`);
});
Writing File

~/carb-studyguide/generate_docx.js

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

const NAVY   = "0F2D5E"; const BLUE   = "1D4ED8"; const TEAL   = "0D9488";
const RED    = "DC2626"; const PURPLE = "7C3AED"; const GREEN  = "16A34A";
const ORANGE = "EA580C"; const GOLD   = "B45309"; const WHITE  = "FFFFFF";
const DARK   = "1E293B"; const GRAY   = "64748B";
const LBLUE  = "DBEAFE"; const LTEAL  = "CCFBF1"; const LRED   = "FEE2E2";
const LPURPLE= "EDE9FE"; const LGREEN = "DCFCE7"; const LORANGE= "FFF7ED";
const LGOLD  = "FEF3C7"; const LGRAY  = "F1F5F9";

const pt = n => n * 20;

function sectionHeader(text, bg = NAVY) {
  return new Paragraph({
    spacing: { before: pt(14), after: pt(6) },
    shading: { type: ShadingType.SOLID, fill: bg },
    children: [new TextRun({ text: `  ${text}`, bold: true, color: WHITE, size: pt(13), font: "Calibri" })],
  });
}
function h2(text, color = NAVY) {
  return new Paragraph({
    heading: HeadingLevel.HEADING_2,
    spacing: { before: pt(10), after: pt(4) },
    children: [new TextRun({ text, bold: true, color, size: pt(12), font: "Calibri" })],
  });
}
function h3(text, color = BLUE) {
  return new Paragraph({
    heading: HeadingLevel.HEADING_3,
    spacing: { before: pt(8), after: pt(3) },
    children: [new TextRun({ text, bold: true, color, size: pt(11), font: "Calibri" })],
  });
}
function body(text) {
  const parts = text.split(/(\*\*[^*]+\*\*)/g);
  const runs = parts.map(p => p.startsWith("**") && p.endsWith("**")
    ? new TextRun({ text: p.slice(2,-2), bold: true, size: pt(10), font: "Calibri", color: DARK })
    : new TextRun({ text: p, size: pt(10), font: "Calibri", color: DARK }));
  return new Paragraph({ spacing: { before: pt(2), after: pt(2), line: 276 }, children: runs });
}
function bullet(text, level = 0) {
  const parts = text.split(/(\*\*[^*]+\*\*)/g);
  const children = parts.map(p => p.startsWith("**") && p.endsWith("**")
    ? new TextRun({ text: p.slice(2,-2), bold: true, size: pt(10), font: "Calibri", color: DARK })
    : new TextRun({ text: p, size: pt(10), font: "Calibri", color: DARK }));
  return new Paragraph({ bullet: { level }, spacing: { before: pt(1), after: pt(1), line: 260 }, children });
}
function mnemonic(text) {
  return new Paragraph({
    spacing: { before: pt(3), after: pt(3) },
    shading: { type: ShadingType.SOLID, fill: LPURPLE },
    indent: { left: pt(10) },
    children: [new TextRun({ text: `★  ${text}`, bold: true, size: pt(10), font: "Calibri", color: PURPLE })],
  });
}
function infoBox(lines, bg = LBLUE, textColor = NAVY) {
  return lines.map(line => new Paragraph({
    spacing: { before: pt(1), after: pt(1) },
    shading: { type: ShadingType.SOLID, fill: bg },
    indent: { left: pt(10) },
    children: [new TextRun({ text: line, size: pt(9.5), font: "Calibri", color: textColor, bold: line.startsWith("★") || line.startsWith("⚠") })],
  }));
}
function boldCenter(text, color = NAVY, bg = LBLUE) {
  return new Paragraph({
    alignment: AlignmentType.CENTER,
    spacing: { before: pt(6), after: pt(8) },
    shading: { type: ShadingType.SOLID, fill: bg },
    children: [new TextRun({ text: `  ${text}  `, bold: true, size: pt(12), font: "Calibri", color })],
  });
}
function spacer() { return new Paragraph({ spacing: { before: pt(4), after: pt(4) }, children: [new TextRun("")] }); }
function pageBreak() { return new Paragraph({ children: [new PageBreak()] }); }

function makeTable(rows, colWidths, headerBg = NAVY) {
  return new Table({
    width: { size: 9300, type: WidthType.DXA },
    margins: { top: 40, bottom: 40, left: 80, right: 80 },
    rows: rows.map((row, ri) => new TableRow({
      children: row.map((cell, ci) => {
        const isH = ri === 0;
        const isA = !isH && ri % 2 === 0;
        const bg = isH ? headerBg : (isA ? LBLUE : WHITE);
        const tc = isH ? WHITE : DARK;
        const parts = String(cell).split(/(\*\*[^*]+\*\*)/g);
        const runs = parts.map(p => p.startsWith("**") && p.endsWith("**")
          ? new TextRun({ text: p.slice(2,-2), bold: true, size: pt(9), font: "Calibri", color: tc })
          : new TextRun({ text: p, bold: isH, size: pt(9), font: "Calibri", color: tc }));
        return new TableCell({
          width: colWidths ? { size: colWidths[ci], type: WidthType.DXA } : undefined,
          verticalAlign: VerticalAlign.CENTER,
          shading: { type: ShadingType.SOLID, fill: bg },
          borders: { top: { style: BorderStyle.SINGLE, size: 4, color: "CBD5E1" }, bottom: { style: BorderStyle.SINGLE, size: 4, color: "CBD5E1" }, left: { style: BorderStyle.SINGLE, size: 4, color: "CBD5E1" }, right: { style: BorderStyle.SINGLE, size: 4, color: "CBD5E1" } },
          children: [new Paragraph({ spacing: { before: 40, after: 40 }, children: runs })],
        });
      }),
    })),
  });
}

const children = [];

// COVER
children.push(
  new Paragraph({ spacing: { before: pt(60) }, children: [] }),
  new Paragraph({
    alignment: AlignmentType.CENTER,
    spacing: { before: pt(20), after: pt(8) },
    shading: { type: ShadingType.SOLID, fill: NAVY },
    children: [new TextRun({ text: "  CARBOHYDRATES & GLUCOSE METABOLISM  ", bold: true, color: WHITE, size: pt(26), font: "Calibri" })],
  }),
  new Paragraph({
    alignment: AlignmentType.CENTER,
    spacing: { before: pt(6), after: pt(8) },
    shading: { type: ShadingType.SOLID, fill: BLUE },
    children: [new TextRun({ text: "Complete Study Guide — Easy Language", bold: true, color: WHITE, size: pt(14), font: "Calibri" })],
  }),
  spacer(),
);
const coverTopics = [
  "• Classification of Carbohydrates (Homo- & Mucopolysaccharides)",
  "• Fate of Glucose in the Body",
  "• Glycolysis — All 10 Steps, Phases & Energetics",
  "• TCA Cycle (Krebs Cycle) — Steps, Energetics & Importance",
  "• HMP Shunt / Pentose Phosphate Pathway",
  "• Gluconeogenesis — Definition, Precursors & Bypass Steps",
  "• Glycogenesis — Definition & Steps",
  "• Blood Glucose Regulation — Normal Values, Hormones & Mechanisms",
  "• Glucose Tolerance Test (GTT) — Indications, Procedure & Interpretation",
  "• Glycosuria — Causes, Renal Threshold & Tests",
  "• Master Summary — ATP Yield, Regulatory Enzymes, Clinical Diseases, Mnemonics",
];
for (const t of coverTopics) {
  children.push(new Paragraph({ alignment: AlignmentType.CENTER, spacing: { before: pt(2), after: pt(2) }, children: [new TextRun({ text: t, size: pt(11), color: DARK, font: "Calibri" })] }));
}
children.push(
  spacer(),
  new Paragraph({ alignment: AlignmentType.CENTER, spacing: { before: pt(6) }, children: [new TextRun({ text: "Sources: Basic Medical Biochemistry 6e  |  Guyton & Hall Physiology  |  Tietz Laboratory Medicine 7e", size: pt(8), color: GRAY, italics: true, font: "Calibri" })] }),
  pageBreak(),
);

// ══ SECTION 1: Classification ══════════════════════════════════════════════
children.push(
  sectionHeader("1.  CLASSIFICATION OF CARBOHYDRATES", NAVY),
  spacer(),
  body("Carbohydrates are polyhydroxy aldehydes or ketones — basically sugar molecules of different sizes."),
  spacer(),
  h2("Monosaccharides (Single sugar unit — cannot be hydrolyzed further)"),
  makeTable([
    ["Sugar", "Type", "Key Role"],
    ["Glucose", "Aldohexose", "Primary fuel of the body — 'petrol for a car'"],
    ["Fructose", "Ketohexose", "Fruit sugar; enters glycolysis as Fructose-6-P"],
    ["Galactose", "Aldohexose", "Milk sugar component"],
    ["Ribose", "Aldopentose", "Backbone of RNA, ATP, NAD+, FAD, CoA"],
    ["Deoxyribose", "Deoxypentose", "Backbone of DNA"],
  ], [1800, 1800, 5700]),
  spacer(),
  h2("Disaccharides (Two monosaccharide units)"),
  makeTable([
    ["Name", "Components", "Bond", "Found in"],
    ["Sucrose", "Glucose + Fructose", "α1,β2", "Table sugar"],
    ["Lactose", "Glucose + Galactose", "β1,4", "Milk (lactase deficiency = bloating, diarrhea)"],
    ["Maltose", "Glucose + Glucose", "α1,4", "Malt; starch digestion product"],
  ], [1500, 2000, 1000, 4800]),
  spacer(),
  h2("Homopolysaccharides (All same monomer)"),
  makeTable([
    ["Name", "Monomer", "Linkage", "Location / Function"],
    ["Starch (Amylose)", "Glucose", "α-1,4", "Plant storage; linear chain; digestible"],
    ["Starch (Amylopectin)", "Glucose", "α-1,4 + α-1,6 branches", "Plant storage; branched every 24-30 units"],
    ["Glycogen", "Glucose", "α-1,4 + α-1,6 branches", "Animal storage — liver & muscle; more branched (every 8-10 units)"],
    ["Cellulose", "Glucose", "β-1,4", "Plant cell wall; NOT digestible by humans"],
    ["Dextran", "Glucose", "α-1,6", "Bacterial; used as plasma volume expander"],
    ["Inulin", "Fructose", "β-2,1", "Used to measure GFR (freely filtered, not reabsorbed)"],
    ["Chitin", "N-Acetylglucosamine", "β-1,4", "Insect exoskeletons, fungal cell walls"],
  ], [1600, 1300, 1800, 4600]),
  spacer(),
  h2("Mucopolysaccharides / Glycosaminoglycans (GAGs)"),
  body("Long unbranched chains of repeating disaccharide units (amino sugar + uronic acid). Highly negatively charged — attract water — form gel-like ground substance of connective tissue."),
  spacer(),
  makeTable([
    ["GAG", "Composition", "Location", "Function"],
    ["Hyaluronic acid", "GlcUA + GlcNAc", "Synovial fluid, vitreous humor", "Lubrication, shock absorption, wound healing"],
    ["Chondroitin sulfate", "GlcUA + GalNAc-SO4", "Cartilage, bone, cornea", "Structural support"],
    ["Dermatan sulfate", "IdoUA + GalNAc-SO4", "Skin, blood vessels", "Structural, anticoagulant role"],
    ["Heparin / Heparan sulfate", "IdoUA + GlcNH2", "Mast cells, blood vessel walls", "Anticoagulant (activates antithrombin III)"],
    ["Keratan sulfate", "Galactose + GlcNAc-SO4", "Cornea, cartilage, bone", "Corneal transparency; structural"],
  ], [1800, 2000, 2000, 3500]),
  spacer(),
  ...infoBox([
    "⚠  Mucopolysaccharidoses — deficiency of lysosomal enzymes that degrade GAGs",
    "   → GAGs accumulate in tissues → coarse facies, organomegaly, skeletal deformity",
    "   Hurler syndrome: α-L-iduronidase deficiency (AR)",
    "   Hunter syndrome: iduronate sulfatase deficiency (X-linked recessive)",
  ], LORANGE, ORANGE),
  pageBreak(),
);

// ══ SECTION 2: Fate of Glucose ════════════════════════════════════════════
children.push(
  sectionHeader("2.  FATE OF GLUCOSE IN THE BODY", BLUE),
  spacer(),
  body("After absorption, glucose can be 'spent, saved, or invested':"),
  spacer(),
  makeTable([
    ["Pathway", "Product", "Where", "When / Why"],
    ["Glycolysis → TCA → OXPHOS", "~30-32 ATP", "All cells", "Primary energy source — always active"],
    ["Glycogenesis", "Glycogen", "Liver, Muscle", "Fed state — insulin high"],
    ["HMP Shunt (Pentose Phosphate)", "NADPH + Ribose-5-P", "Liver, RBCs, Adrenal", "Biosynthesis + antioxidant defense"],
    ["Lipogenesis", "Triglycerides", "Liver, Adipose", "Excess glucose; fed state"],
    ["Glucuronate pathway", "Glucuronic acid", "Liver", "Detoxification, GAG synthesis"],
    ["Glycosuria (overflow)", "Lost in urine", "Kidney", "Only if blood glucose > ~180 mg/dL"],
  ], [2200, 1500, 1500, 4100]),
  pageBreak(),
);

// ══ SECTION 3: Glycolysis ════════════════════════════════════════════════
children.push(
  sectionHeader("3.  GLYCOLYSIS — Pathway & Energetics", NAVY),
  spacer(),
  body("**Definition:** Breakdown of 1 glucose (6C) → 2 pyruvate (3C).   **Location:** Cytosol of ALL cells.   **Works with OR without O₂.**"),
  spacer(),
  h2("PHASE 1 — Investment Phase (spends 2 ATP)"),
  makeTable([
    ["Step", "Reaction", "Enzyme", "Key Points"],
    ["1", "Glucose → Glucose-6-P", "Hexokinase (all tissues)\nGlucokinase (liver, β-cells)", "Uses 1 ATP; traps glucose in cell; IRREVERSIBLE\nGlucokinase: high Km, not saturated at normal glucose"],
    ["2", "G6P → Fructose-6-P", "Phosphoglucose isomerase", "Reversible; isomerization"],
    ["3", "F6P → Fructose-1,6-BP", "★ PFK-1 (RATE-LIMITING)", "Uses 1 ATP; IRREVERSIBLE\nActivated: AMP, ADP, F-2,6-BP, insulin\nInhibited: ATP, citrate, glucagon"],
    ["4", "F-1,6-BP → DHAP + G3P", "Aldolase", "Splits 6C into two 3C fragments"],
    ["5", "DHAP ⇌ G3P", "Triose phosphate isomerase", "DHAP converted to G3P — both enter Phase 2"],
  ], [400, 2400, 2200, 4300]),
  spacer(),
  h2("PHASE 2 — Payoff Phase (all steps ×2, earns 4 ATP + 2 NADH)"),
  makeTable([
    ["Step", "Reaction", "Enzyme", "Key Points"],
    ["6", "G3P → 1,3-Bisphosphoglycerate", "G3P Dehydrogenase", "Oxidation step; produces 2 NADH (×2); uses inorganic phosphate"],
    ["7", "1,3-BPG → 3-Phosphoglycerate", "Phosphoglycerate kinase", "2 ATP produced (×2) — substrate-level phosphorylation"],
    ["8", "3-PG → 2-Phosphoglycerate", "Phosphoglycerate mutase", "Shifts phosphate group"],
    ["9", "2-PG → PEP", "Enolase", "Inhibited by fluoride! (why blood glucose tubes have fluoride)"],
    ["10", "PEP → Pyruvate", "★ Pyruvate Kinase", "2 ATP produced (×2); IRREVERSIBLE\nActivated: F-1,6-BP (feedforward)\nInhibited: ATP, alanine, glucagon"],
  ], [400, 2400, 2200, 4300]),
  spacer(),
  h2("Net Energetics of Glycolysis"),
  makeTable([
    ["Product", "Amount", "Notes"],
    ["ATP (net)", "2 ATP", "Substrate-level phosphorylation"],
    ["NADH", "2 NADH", "→ 5 ATP via malate-aspartate shuttle; or 3 ATP via glycerol-3-P shuttle"],
    ["Pyruvate", "2 molecules", "Further oxidized (aerobic) or reduced to lactate (anaerobic)"],
  ], [2000, 1500, 5800]),
  spacer(),
  h2("Fate of Pyruvate"),
  makeTable([
    ["Condition", "Product", "Enzyme", "Significance"],
    ["Aerobic (O₂ present)", "Acetyl-CoA + CO₂ + NADH", "Pyruvate Dehydrogenase Complex\n(cofactors: TPP, lipoate, CoA, FAD, NAD+)", "Enters TCA cycle → ~28 more ATP"],
    ["Anaerobic (no O₂)", "Lactate + NAD+", "Lactate Dehydrogenase (LDH)", "Regenerates NAD+ → glycolysis continues; Cori cycle: lactate → liver → glucose"],
  ], [1800, 2000, 2600, 2900]),
  spacer(),
  mnemonic("Glycolysis steps: 'Goodness Gracious, Father Franklin Did Go By Picking Peas'"),
  mnemonic("Glucose→G6P→F6P→F1,6BP→DHAP/G3P→1,3BPG→3PG→2PG→PEP→Pyruvate"),
  pageBreak(),
);

// ══ SECTION 4: TCA Cycle ═══════════════════════════════════════════════
children.push(
  sectionHeader("4.  TCA CYCLE (Krebs Cycle / Citric Acid Cycle)", GREEN),
  spacer(),
  body("**Location:** Mitochondrial matrix   **Entry:** Acetyl-CoA (2C) + Oxaloacetate (4C) → Citrate (6C)"),
  spacer(),
  makeTable([
    ["#", "Reaction", "Enzyme", "Product", "Notes"],
    ["1", "Acetyl-CoA + OAA → Citrate", "Citrate Synthase", "—", "Condensation; inhibited by ATP, NADH, succinyl-CoA"],
    ["2", "Citrate → Isocitrate", "Aconitase", "—", "Via aconitate intermediate; inhibited by fluoroacetate"],
    ["3", "Isocitrate → α-Ketoglutarate", "★ Isocitrate DH (rate-limiting)", "NADH + CO₂", "Activated: ADP, Ca²⁺  |  Inhibited: ATP, NADH"],
    ["4", "α-KG → Succinyl-CoA", "α-KG Dehydrogenase", "NADH + CO₂", "IRREVERSIBLE; same cofactors as PDC; inhibited by NADH, succinyl-CoA"],
    ["5", "Succinyl-CoA → Succinate", "Succinyl-CoA Synthetase", "GTP", "Only substrate-level phosphorylation in TCA"],
    ["6", "Succinate → Fumarate", "Succinate Dehydrogenase", "FADH₂", "Only FAD-linked TCA enzyme; embedded in inner membrane (Complex II)"],
    ["7", "Fumarate → Malate", "Fumarase", "H₂O added", "Trans-addition of water"],
    ["8", "Malate → Oxaloacetate", "Malate Dehydrogenase", "NADH", "OAA regenerated for next turn"],
  ], [300, 2200, 2000, 1000, 3800]),
  spacer(),
  h2("Energetics per Acetyl-CoA (one turn)"),
  makeTable([
    ["Product", "Amount", "ATP Equivalent"],
    ["NADH", "3", "3 × 2.5 = 7.5 ATP"],
    ["FADH₂", "1", "1 × 1.5 = 1.5 ATP"],
    ["GTP", "1", "1 ATP"],
    ["TOTAL", "", "≈ 10 ATP per Acetyl-CoA"],
  ], [2500, 1500, 5300]),
  spacer(),
  h2("Importance of TCA Cycle"),
  bullet("**Primary source** of NADH and FADH₂ → drives oxidative phosphorylation → most body ATP"),
  bullet("**Amphibolic** — both catabolic AND anabolic (breakdown + synthesis)"),
  bullet("Provides **biosynthetic precursors:** OAA→amino acids; α-KG→glutamate; Succinyl-CoA→heme; Citrate→fatty acids"),
  bullet("Two **CO₂** released per turn → exhaled"),
  bullet("**Anaplerotic reactions** replenish cycle intermediates (e.g., Pyruvate Carboxylase: Pyr+CO₂→OAA)"),
  bullet("Ca²⁺ activates 3 key enzymes → couples muscle contraction to energy production"),
  spacer(),
  mnemonic("TCA intermediates: 'Citrate Is Krebs' Starting Substrate For Making OAA'"),
  mnemonic("Citrate → Isocitrate → α-KG → Succinyl-CoA → Succinate → Fumarate → Malate → OAA"),
  pageBreak(),
);

// ══ SECTION 5: HMP Shunt ══════════════════════════════════════════════
children.push(
  sectionHeader("5.  HMP SHUNT (Hexose Monophosphate / Pentose Phosphate Pathway)", PURPLE),
  spacer(),
  body("**Location:** Cytosol   **Active in:** Liver, RBCs, Adrenal cortex, Gonads, Lactating mammary gland"),
  body("**Purpose:** NOT for ATP — for NADPH production (antioxidant + biosynthesis) and Ribose-5-P (nucleotide synthesis)."),
  spacer(),
  h2("Phase 1 — Oxidative Phase (IRREVERSIBLE) → Generates NADPH"),
  makeTable([
    ["Step", "Reaction", "Enzyme", "Products"],
    ["1", "Glucose-6-P → 6-Phosphogluconolactone", "★ G6P Dehydrogenase (rate-limiting)", "NADPH"],
    ["2", "6-Phosphogluconolactone → 6-Phosphogluconate", "Lactonase", "H₂O"],
    ["3", "6-Phosphogluconate → Ribulose-5-P + CO₂", "6-Phosphogluconate Dehydrogenase", "NADPH + CO₂"],
  ], [400, 3200, 2800, 1900]),
  body("**Net per G6P in oxidative phase: 2 NADPH + 1 CO₂ + Ribulose-5-P**"),
  spacer(),
  h2("Phase 2 — Non-Oxidative Phase (REVERSIBLE)"),
  body("Transketolase and Transaldolase reactions shuffle C3-C7 sugar phosphates. Products can re-enter glycolysis as F6P and G3P, or go to nucleotide synthesis."),
  spacer(),
  h2("Functions of NADPH"),
  makeTable([
    ["Function", "Details"],
    ["**RBC protection**", "Reduces glutathione (GSSG → GSH) → neutralizes H₂O₂ → prevents oxidative hemolysis"],
    ["Fatty acid synthesis", "Required by Fatty Acid Synthase in liver and adipose tissue"],
    ["Cholesterol synthesis", "Required by HMG-CoA reductase pathway; all steroid hormone synthesis"],
    ["Phagocyte killing", "NADPH oxidase produces O₂⁻ (superoxide) → oxidative burst to kill bacteria"],
    ["Detoxification", "Cytochrome P450 enzymes in liver use NADPH"],
  ], [2500, 6800]),
  spacer(),
  ...infoBox([
    "⚠  G6PD Deficiency — Most common enzyme deficiency worldwide (X-linked recessive)",
    "   No G6PD → no NADPH → RBCs unprotected → oxidative stress → hemolytic anemia",
    "   Triggers: Primaquine, Dapsone, Sulfonamides, Nitrofurantoin, Fava beans, Infections",
    "   Blood film: Heinz bodies (denatured Hb), bite cells  |  Test: G6PD enzyme assay",
  ], LORANGE, ORANGE),
  pageBreak(),
);

// ══ SECTION 6: Gluconeogenesis ════════════════════════════════════════
children.push(
  sectionHeader("6.  GLUCONEOGENESIS", NAVY),
  spacer(),
  body("**Definition:** Synthesis of glucose from non-carbohydrate precursors. Occurs mainly in **liver** (90%) and **kidney** (10%). Active during fasting, starvation, prolonged exercise."),
  spacer(),
  h2("Non-Carbohydrate Precursors — 'GOAL'"),
  makeTable([
    ["Precursor", "How it enters", "Source", "Clinical Relevance"],
    ["**Lactate**", "Lactate → Pyruvate (LDH)", "Anaerobic muscle, RBCs", "Cori Cycle: muscle lactate → liver → glucose"],
    ["**Amino acids (Alanine)**", "Alanine → Pyruvate (ALT)", "Muscle protein breakdown", "Alanine Cycle: key during fasting / starvation"],
    ["**Glycerol**", "Glycerol → DHAP", "Lipolysis of triglycerides", "Fat stores provide substrate for gluconeogenesis"],
    ["**Odd-chain fatty acids**", "→ Succinyl-CoA → OAA → PEP", "β-oxidation of odd-chain FA", "Only FA that can generate net glucose"],
  ], [1800, 2200, 2000, 3300]),
  body("❌  Even-chain fatty acids CANNOT generate net glucose (Acetyl-CoA → TCA → CO₂, net carbon = 0)"),
  spacer(),
  h2("The Three Unique Bypass Steps"),
  makeTable([
    ["Glycolytic Enzyme (IRREVERSIBLE)", "Problem", "Gluconeogenic Bypass", "Location + Cofactors"],
    ["Pyruvate Kinase\n(PEP → Pyruvate)", "Cannot reverse", "Step 1: Pyruvate Carboxylase (Pyr→OAA)\nStep 2: PEPCK (OAA→PEP)", "PC: mitochondria; needs Biotin + ATP\nPEPCK: cytosol; needs GTP"],
    ["PFK-1\n(F6P → F-1,6-BP)", "Cannot reverse", "Fructose-1,6-Bisphosphatase\n(F-1,6-BP → F6P)", "Cytosol; inhibited by AMP, F-2,6-BP\nActivated by citrate"],
    ["Hexokinase/Glucokinase\n(Glucose → G6P)", "Cannot reverse", "Glucose-6-Phosphatase\n(G6P → Glucose)", "ER membrane; ONLY in liver + kidney\n★ NOT in muscle or brain!"],
  ], [2200, 1500, 2500, 3100]),
  spacer(),
  mnemonic("Gluconeogenic precursors: 'GOAL' = Glycerol, Odd-chain FA, Amino acids, Lactate"),
  pageBreak(),
);

// ══ SECTION 7: Glycogenesis ═══════════════════════════════════════════
children.push(
  sectionHeader("7.  GLYCOGENESIS (Glycogen Synthesis)", BLUE),
  spacer(),
  body("**Definition:** Converting glucose into glycogen for storage. **Where:** Liver (blood glucose buffer) and Skeletal Muscle (local reserve)."),
  spacer(),
  h2("Steps of Glycogenesis"),
  makeTable([
    ["Step", "Reaction", "Enzyme", "Key Detail"],
    ["1", "Glucose → Glucose-6-P", "Hexokinase / Glucokinase", "Uses 1 ATP; traps glucose"],
    ["2", "G6P → Glucose-1-P", "Phosphoglucomutase", "Prepares for activation"],
    ["3", "G1P + UTP → UDP-Glucose + PPi", "UDP-Glucose Pyrophosphorylase", "'Activated glucose' — high-energy form ready to be added to chain"],
    ["4", "UDP-Glucose added to chain", "★ Glycogen Synthase", "Adds via α-1,4 bonds to non-reducing ends; needs glycogenin primer"],
    ["5", "Branch creation (~every 11 residues)", "Branching Enzyme", "Moves 6-7 glucose block → creates α-1,6 branch point; ↑ solubility, ↑ free ends"],
  ], [400, 2200, 2200, 4500]),
  spacer(),
  h2("Regulation of Glycogenesis"),
  makeTable([
    ["State", "Signal", "Effect on Glycogen Synthase", "Result"],
    ["Fed (post-meal)", "Insulin ↑", "Protein phosphatase dephosphorylates → ACTIVE form (a)", "Glycogen stored"],
    ["Fasting / Stress", "Glucagon / Epinephrine ↑", "PKA phosphorylates → INACTIVE (b) form", "Glycogen breakdown"],
    ["Muscle (local)", "Glucose-6-P ↑", "Allosteric activation of inactive form", "Glycogen stored locally"],
  ], [1800, 2000, 3200, 2300]),
  spacer(),
  ...infoBox([
    "★  Key Rule: Glycogen Synthase = ACTIVE when DEPHOSPHORYLATED (insulin state)",
    "   Glycogen Phosphorylase = ACTIVE when PHOSPHORYLATED (glucagon/epinephrine state)",
    "   These pathways are RECIPROCALLY regulated — cannot synthesize and break down simultaneously",
  ], LBLUE, NAVY),
  pageBreak(),
);

// ══ SECTION 8: Blood Glucose Regulation ══════════════════════════════
children.push(
  sectionHeader("8.  BLOOD GLUCOSE REGULATION", NAVY),
  spacer(),
  h2("Normal Values — Must Know!"),
  makeTable([
    ["Condition", "Blood Glucose Level", "Significance"],
    ["**Normal fasting (8h)**", "**70–100 mg/dL**  (3.9–5.6 mmol/L)", "Standard reference range"],
    ["2h post-meal (OGTT)", "< 140 mg/dL (< 7.8 mmol/L)", "Normal postprandial"],
    ["Impaired fasting glucose", "100–125 mg/dL", "Pre-diabetes"],
    ["Impaired glucose tolerance", "140–199 mg/dL at 2h OGTT", "Pre-diabetes"],
    ["Diabetes Mellitus (fasting)", "≥ 126 mg/dL (×2 occasions)", "Diagnostic threshold"],
    ["Diabetes Mellitus (2h OGTT)", "≥ 200 mg/dL", "Diagnostic threshold"],
    ["**Renal threshold**", "**≈ 180 mg/dL**", "Glucose appears in urine above this value"],
    ["Hypoglycemia", "< 70 mg/dL", "Symptoms: sweating, palpitations, confusion, seizures"],
  ], [2500, 2800, 4000]),
  spacer(),
  h2("Hormonal Regulation"),
  makeTable([
    ["Hormone", "Source", "Effect", "Key Actions"],
    ["**Insulin**", "Pancreatic β-cells", "↓ DECREASES", "↑ GLUT4 (muscle/fat), ↑ glycolysis, ↑ glycogenesis, ↑ lipogenesis; ↓ gluconeogenesis, ↓ glycogenolysis"],
    ["**Glucagon**", "Pancreatic α-cells", "↑ INCREASES", "↑ glycogenolysis, ↑ gluconeogenesis; ↓ glycolysis (via ↓ F-2,6-BP)"],
    ["**Epinephrine**", "Adrenal medulla", "↑ INCREASES", "↑ glycogenolysis (liver + muscle), ↑ gluconeogenesis, ↑ lipolysis — rapid emergency response"],
    ["**Cortisol**", "Adrenal cortex", "↑ INCREASES", "↑ gluconeogenesis enzyme expression; ↑ proteolysis; ↓ peripheral glucose uptake"],
    ["**Growth Hormone**", "Anterior pituitary", "↑ INCREASES", "Anti-insulin; ↓ glucose uptake peripherally; ↑ lipolysis; 'diabetogenic'"],
    ["Somatostatin", "Pancreatic δ-cells", "Biphasic", "Inhibits BOTH insulin AND glucagon secretion"],
    ["GLP-1 / GIP (Incretins)", "Gut (L-cells / K-cells)", "↓ Indirectly", "Potentiate insulin release; inhibit glucagon; GLP-1 slows gastric emptying"],
    ["Thyroxine (T₄)", "Thyroid gland", "↑ INCREASES", "↑ glycogenolysis, ↑ gut glucose absorption, ↑ basal metabolic rate"],
  ], [1500, 1600, 1200, 5000]),
  spacer(),
  h2("Response to Hypoglycemia (Sequential Layered Defense)"),
  makeTable([
    ["Timeframe", "Response", "Mechanism"],
    ["Minutes (1st)", "Glucagon ↑", "Glycogenolysis + gluconeogenesis in liver"],
    ["Minutes (2nd)", "Epinephrine ↑", "Emergency glycogenolysis; inhibits insulin secretion"],
    ["Hours (3rd)", "Growth Hormone ↑ + Cortisol ↑", "Reduce peripheral glucose use; ↑ gluconeogenesis; ↑ lipolysis"],
    ["Prolonged fasting", "Hepatic gluconeogenesis only", "After ~30h fast: glycogen depleted → gluconeogenesis is the ONLY glucose source"],
  ], [1800, 2200, 5300]),
  spacer(),
  ...infoBox([
    "★  Quote from Guyton & Hall Physiology:",
    "   'Glucose is the ONLY nutrient that can be used by the brain, retina, and germinal",
    "    epithelium of the gonads in sufficient quantities to supply optimally required energy.'",
    "   This is WHY blood glucose regulation is so critical.",
  ], LBLUE, NAVY),
  pageBreak(),
);

// ══ SECTION 9: GTT ═══════════════════════════════════════════════════
children.push(
  sectionHeader("9.  GLUCOSE TOLERANCE TEST (GTT / OGTT)", GREEN),
  spacer(),
  body("**Purpose:** Assesses the body's ability to handle a standard glucose load. Diagnoses DM, pre-diabetes, and gestational diabetes (GDM)."),
  spacer(),
  h2("Indications for GTT"),
  bullet("Fasting blood glucose borderline (100–125 mg/dL) — suspected pre-diabetes or DM"),
  bullet("**Gestational Diabetes Mellitus (GDM) screening** — 24–28 weeks of pregnancy (MANDATORY)"),
  bullet("HbA1c unreliable (hemolytic anaemia, hemoglobinopathies, iron deficiency)"),
  bullet("Suspected reactive hypoglycemia or insulinoma"),
  bullet("Discordant fasting and random glucose results"),
  spacer(),
  h2("Procedure — Standard 75g OGTT"),
  makeTable([
    ["Step", "Action", "Details"],
    ["Preparation (3 days before)", "Unrestricted diet", "Must eat ≥ 150g carbohydrates/day for 3 days before test"],
    ["Night before", "8–12 hour fast", "Water only; no alcohol, no smoking, no heavy exercise"],
    ["Time = 0 min", "Fasting blood sample drawn", "Record symptoms; test urine for glucose"],
    ["Glucose load", "Drink 75g anhydrous glucose", "Dissolved in 250-300 mL water; consumed within 5 minutes\nChildren: 1.75 g/kg up to max 75g"],
    ["Time = 60 min", "Blood sample drawn", "Required for GDM diagnosis (IADPSG criteria)"],
    ["Time = 120 min", "Blood sample drawn", "Primary diagnostic time point for DM"],
    ["GDM (IADPSG)", "75g load; any ONE value ≥ threshold = GDM", "Fasting ≥ 92  |  1h ≥ 180  |  2h ≥ 153 mg/dL"],
  ], [2000, 2400, 5000]),
  spacer(),
  h2("Interpretation — 75g OGTT (ADA Criteria)"),
  makeTable([
    ["Category", "Fasting", "2-Hour Value", "Action"],
    ["**Normal**", "< 100 mg/dL", "< 140 mg/dL", "Reassure; lifestyle advice"],
    ["Pre-diabetes (IFG)", "100–125 mg/dL", "—", "Lifestyle modification; consider Metformin"],
    ["Pre-diabetes (IGT)", "—", "140–199 mg/dL", "Lifestyle modification; annual follow-up"],
    ["**Diabetes Mellitus**", "**≥ 126 mg/dL**", "**≥ 200 mg/dL**", "Diagnosis confirmed; initiate management"],
  ], [2200, 1500, 1800, 3800], GREEN),
  spacer(),
  h2("Special GTT Curves"),
  makeTable([
    ["Curve Type", "Pattern", "Cause"],
    ["Normal", "Peak ~140 at 1h; returns < 140 by 2h", "Normal insulin response"],
    ["Diabetic", "Exaggerated peak; slow return; still elevated at 2h", "Insulin deficiency or resistance"],
    ["Flat curve", "Minimal rise after glucose load", "Malabsorption, Addison's disease, hypothyroidism"],
    ["Lag storage", "Very high early peak then rapid fall", "Post-gastrectomy, hyperthyroidism"],
    ["Reactive hypoglycemia", "Normal rise then falls < 70 at 3-5h", "Excess insulin; suspect insulinoma"],
  ], [2000, 4000, 3300], GREEN),
  pageBreak(),
);

// ══ SECTION 10: Glycosuria ════════════════════════════════════════════
children.push(
  sectionHeader("10.  GLYCOSURIA", ORANGE),
  spacer(),
  body("**Definition:** Presence of glucose in the urine. Normally ALL filtered glucose is reabsorbed in the proximal convoluted tubule (PCT) via SGLT2 (90%) and SGLT1 (10%)."),
  spacer(),
  makeTable([
    ["Concept", "Value / Details"],
    ["**Renal threshold for glucose**", "**≈ 180 mg/dL** plasma glucose (range 160–200)"],
    ["Tubular maximum (Tm)", "≈ 375 mg/min (range 300–450 mg/min)"],
    ["Normal urinary glucose", "< 0.8 mmol/L (essentially absent on routine dipstick)"],
    ["Reabsorption mechanism", "PCT: SGLT2 (low affinity, high capacity) + SGLT1 (high affinity, low capacity)"],
  ], [3000, 6300]),
  spacer(),
  h2("Causes of Glycosuria"),
  makeTable([
    ["Type", "Blood Glucose", "Cause", "Examples"],
    ["**Hyperglycaemic** (most common)", "HIGH (> 180 mg/dL)", "Blood glucose exceeds Tm → glucose spills over", "DM, Cushing's syndrome, pheochromocytoma, steroid therapy, pancreatitis"],
    ["**Renal glycosuria** (normoglycaemic)", "NORMAL", "Reduced renal threshold / Tm defect", "Benign renal glycosuria (SGLT2 mutation), Fanconi syndrome, SGLT2 inhibitor drugs (gliflozins)"],
    ["Physiological (pregnancy)", "Normal or mildly ↑", "Increased GFR + reduced threshold", "Normal in pregnancy; must rule out GDM"],
    ["Alimentary glycosuria", "Post-meal spike", "Rapid absorption overwhelms threshold transiently", "Post-gastrectomy, rapid gastric emptying"],
  ], [1800, 1500, 2200, 3800]),
  spacer(),
  h2("Tests for Glycosuria"),
  makeTable([
    ["Test", "Principle", "Detects", "Use"],
    ["Glucose oxidase dipstick (specific)", "Enzyme-specific for glucose", "Glucose ONLY", "Routine DM monitoring; most common"],
    ["Benedict's / Fehling's test", "Reduces Cu²⁺ (blue→brick red)", "ALL reducing sugars\n(glucose, galactose, fructose, lactose)", "Neonatal metabolic screening; galactosemia"],
    ["Clinitest tablets", "Chemical reduction", "All reducing sugars", "Largely replaced by dipstick"],
  ], [2200, 1800, 2000, 3300], ORANGE),
  spacer(),
  ...infoBox([
    "⚠  IMPORTANT: In Galactosaemia — Benedict's test POSITIVE but glucose dipstick NEGATIVE",
    "   Because galactose (not glucose) is the reducing sugar present in urine!",
    "   Fanconi syndrome: glycosuria + aminoaciduria + phosphaturia + uricosuria (generalised PCT defect)",
  ], LORANGE, ORANGE),
  pageBreak(),
);

// ══ SECTION 11: Master Summary ════════════════════════════════════════
children.push(
  sectionHeader("11.  MASTER SUMMARY — ATP Yield, Regulatory Enzymes & Mnemonics", NAVY),
  spacer(),
  h2("Complete ATP Yield from 1 Glucose Molecule (Aerobic Oxidation)"),
  makeTable([
    ["Stage", "Process", "Direct ATP", "NADH/FADH₂", "ATP from ETC", "Total"],
    ["Glycolysis", "Glucose → 2 Pyruvate (cytosol)", "2", "2 NADH", "5 (M-A shuttle)", "7"],
    ["Pyruvate → Acetyl-CoA", "PDC × 2 (mitochondria)", "0", "2 NADH", "5", "5"],
    ["TCA Cycle ×2", "2 Acetyl-CoA oxidized", "2 GTP", "6 NADH + 2 FADH₂", "18", "20"],
    ["", "**GRAND TOTAL**", "", "", "", "**≈ 30-32 ATP**"],
  ], [1700, 2200, 1000, 1500, 1300, 1500]),
  spacer(),
  h2("Key Regulatory Enzymes — Quick Reference"),
  makeTable([
    ["Enzyme", "Pathway", "Activated by", "Inhibited by"],
    ["Hexokinase", "Glycolysis", "Glucose", "G6P (product inhibition)"],
    ["Glucokinase", "Glycolysis (liver)", "Glucose (high Km)", "No product inhibition; regulated by GKRP"],
    ["★ PFK-1", "Glycolysis (rate-limiting)", "AMP, ADP, F-2,6-BP, insulin", "ATP, citrate, glucagon"],
    ["Pyruvate Kinase", "Glycolysis", "F-1,6-BP (feedforward)", "ATP, alanine, glucagon (phosphorylation)"],
    ["Pyruvate Dehydrogenase", "Pyr → Acetyl-CoA", "ADP, CoA, NAD+, Ca²+", "ATP, Acetyl-CoA, NADH (product inhibition)"],
    ["★ Isocitrate DH", "TCA (rate-limiting)", "ADP, Ca²+", "ATP, NADH"],
    ["★ G6P Dehydrogenase", "HMP Shunt (rate-limiting)", "NADP+", "NADPH (product inhibition)"],
    ["Pyruvate Carboxylase", "Gluconeogenesis", "Acetyl-CoA (allosteric)", "ADP"],
    ["Fructose-1,6-Bisphosphatase", "Gluconeogenesis", "Citrate", "AMP, F-2,6-BP"],
    ["Glycogen Synthase", "Glycogenesis", "G6P, insulin (via PP)", "PKA phosphorylation (glucagon)"],
    ["Glycogen Phosphorylase", "Glycogenolysis", "AMP, Ca²+, PKA (glucagon)", "G6P, ATP, insulin"],
  ], [2000, 1600, 2500, 3200]),
  spacer(),
  h2("Clinically Important Metabolic Diseases"),
  makeTable([
    ["Disease", "Enzyme Defect", "Key Features"],
    ["G6PD Deficiency", "G6P Dehydrogenase (HMP shunt)", "Episodic hemolytic anemia; X-linked; Heinz bodies; triggered by oxidants"],
    ["Galactosaemia", "Galactose-1-P uridyltransferase", "Neonatal jaundice, cataracts, liver failure; reducing sugar in urine"],
    ["Fructose Intolerance", "Aldolase B (liver)", "Hypoglycemia after fructose; liver damage; avoid sucrose and sorbitol"],
    ["Von Gierke (GSD Ia)", "Glucose-6-Phosphatase", "Fasting hypoglycemia, hepatomegaly, lactic acidosis, hyperlipidemia"],
    ["McArdle (GSD V)", "Muscle Glycogen Phosphorylase", "Exercise intolerance, cramps, myoglobinuria; NO lactate rise on exercise"],
    ["Pyruvate Kinase Deficiency", "Pyruvate Kinase (RBCs)", "Chronic hemolytic anemia; ↑ 2,3-BPG (right shift O₂ curve)"],
    ["Hurler Syndrome", "α-L-Iduronidase", "Coarse facies, corneal clouding, organomegaly, intellectual disability"],
  ], [2000, 2200, 5100]),
  spacer(),
  h2("All Mnemonics — Quick Recall"),
  makeTable([
    ["Topic", "Mnemonic"],
    ["Glycolysis 10 steps", "'Goodness Gracious, Father Franklin Did Go By Picking Peas'\nGlucose → G6P → F6P → F1,6BP → DHAP/G3P → 1,3BPG → 3PG → 2PG → PEP → Pyruvate"],
    ["TCA intermediates", "'Citrate Is Krebs' Starting Substrate For Making OAA'\nCitrate → Isocitrate → α-KG → Succinyl-CoA → Succinate → Fumarate → Malate → OAA"],
    ["Gluconeogenic precursors", "'GOAL' = Glycerol, Odd-chain FA, Amino acids, Lactate"],
    ["Hypoglycemia hormones", "'GECGo' = Glucagon (1st), Epinephrine (2nd), Cortisol (3rd), Growth hormone (4th)"],
    ["Glycogen synthase activity", "'Synthase Dephosphorylated = Active' (insulin)\n'Phosphorylase Phosphorylated = Active' (glucagon/epinephrine)"],
    ["Insulin vs Glucagon", "'INsulin = INto cells = decreases blood glucose'\n'GLUCAgon = GLUCose Agonist = raises blood glucose'"],
    ["Purines", "'PURe As Gold' = Purines: Adenine + Guanine (HMP shunt nucleotide synthesis)"],
  ], [2500, 6800], PURPLE),
  spacer(),
  new Paragraph({
    alignment: AlignmentType.CENTER,
    spacing: { before: pt(10) },
    children: [new TextRun({ text: "Sources: Basic Medical Biochemistry 6e  |  Guyton & Hall Textbook of Medical Physiology  |  Tietz Textbook of Laboratory Medicine 7e  |  Goodman & Gilman's Pharmacological Basis of Therapeutics", size: pt(8), italics: true, color: GRAY, font: "Calibri" })],
  }),
);

// BUILD
const doc = new Document({
  creator: "Orris Medical",
  title: "Carbohydrates & Glucose Metabolism Study Guide",
  styles: {
    default: { document: { run: { font: "Calibri", size: pt(10), color: DARK } } },
  },
  sections: [{
    properties: { page: { margin: { top: 720, bottom: 720, left: 900, right: 900 } } },
    headers: {
      default: new Header({
        children: [new Paragraph({
          alignment: AlignmentType.RIGHT,
          shading: { type: ShadingType.SOLID, fill: NAVY },
          children: [
            new TextRun({ text: "  CARBOHYDRATES & GLUCOSE METABOLISM  |  Study Guide  |  Page ", bold: true, color: WHITE, size: pt(8.5), font: "Calibri" }),
            new TextRun({ children: [new PageNumber()], bold: true, color: WHITE, size: pt(8.5), font: "Calibri" }),
            new TextRun({ text: "  ", color: WHITE, size: pt(8.5) }),
          ],
        })],
      }),
    },
    footers: {
      default: new Footer({
        children: [new Paragraph({
          alignment: AlignmentType.CENTER,
          children: [new TextRun({ text: "Basic Medical Biochemistry 6e  |  Guyton & Hall Physiology  |  Tietz Laboratory Medicine 7e", size: pt(7.5), italics: true, color: GRAY, font: "Calibri" })],
        })],
      }),
    },
    children,
  }],
});

const outPath = "/home/daytona/workspace/carb-studyguide/Carbohydrates_Glucose_Metabolism_StudyGuide.docx";
Packer.toBuffer(doc).then(buf => {
  fs.writeFileSync(outPath, buf);
  console.log("Created:", outPath, `(${(buf.length/1024).toFixed(1)} KB)`);
});
Running Command

node /home/daytona/workspace/nucleic-acids-guide/generate_docx.js 2>&1 & node /h…

Running Command

ls -lh /home/daytona/workspace/nucleic-acids-guide/*.docx /home/daytona/workspac…

Running Command

node /home/daytona/workspace/nucleic-acids-guide/generate_docx.js 2>&1

Running Command

node -e "const d = require('docx'); console.log(Object.keys(d).filter(k=>k.toLow…

Running Command

node -e "const {PageNumberElement, PageNumberSeparator} = require('docx'); conso…

Running Command

# Fix both files: replace PageNumber with PageNumberElement in the header sed -i…

Running Command

python3 -c " for path in ['/home/daytona/workspace/nucleic-acids-guide/generate_…

Running Command

node /home/daytona/workspace/nucleic-acids-guide/generate_docx.js 2>&1

Running Command

node /home/daytona/workspace/carb-studyguide/generate_docx.js 2>&1

Running Command

python3 /home/daytona/skills/docx/scripts/office/validate.py /home/daytona/works…

give me in text

NUCLEIC ACIDS — DNA & RNA

Complete Study Guide


1. NUCLEIC ACIDS — Overview & Components

Nucleic acids are biological macromolecules that store and transmit genetic information and direct protein synthesis. Two types exist: DNA (Deoxyribonucleic Acid) and RNA (Ribonucleic Acid).

Building Block = Nucleotide (3 parts)

  1. Pentose sugar — Deoxyribose (DNA) or Ribose (RNA)
  2. Nitrogenous base — Purine or Pyrimidine
  3. Phosphate group — one or more phosphates
Nucleoside = sugar + base only (no phosphate) Nucleotides are linked by 3'–5' phosphodiester bonds forming long polynucleotide chains.

Nitrogenous Bases

TypeBaseFound inPairs with
Purine (2-ring)Adenine (A)DNA & RNAT (DNA) / U (RNA)
Purine (2-ring)Guanine (G)DNA & RNAC
Pyrimidine (1-ring)Cytosine (C)DNA & RNAG
Pyrimidine (1-ring)Thymine (T)DNA ONLYA
Pyrimidine (1-ring)Uracil (U)RNA ONLYA
Mnemonic: "PURe As Gold" = Purines: Adenine + Guanine "CUT the PY" = Cytosine, Uracil, Thymine are Pyrimidines

Watson-Crick Base Pairing

  • A = T → 2 hydrogen bonds
  • G ≡ C → 3 hydrogen bonds (stronger; higher melting temperature)

2. DNA — STRUCTURE

Watson-Crick Double Helix Model (1953)

Proposed by James Watson and Francis Crick, based on X-ray data by Rosalind Franklin. DNA is a right-handed double helix — like a twisted ladder.
FeatureDetail
Two strandsAntiparallel polynucleotide chains
OrientationOne runs 5'→3', the other 3'→5'
BackboneSugar-phosphate on the OUTSIDE
BasesFace INSIDE, stacked perpendicular to axis
Diameter~2 nm (20 Å)
Base pairs per turn10 bp (B-DNA)
Rise per base pair0.34 nm (3.4 Å)
Pitch (full turn)3.4 nm
H-bondsA=T: 2 bonds; G≡C: 3 bonds
Major grooveWide — proteins and enzymes bind here
Minor grooveNarrow — some drugs bind here

Forms of DNA

FormHelixConditionsSignificance
B-DNARight-handedPhysiologicalMost common in cells
A-DNARight-handedDehydratedRNA-DNA hybrids
Z-DNALeft-handedHigh saltGene regulation role

DNA Packaging

  • DNA wraps around histones (H2A, H2B, H3, H4 ×2) → nucleosome
  • ~147 bp per nucleosome core
  • "Beads on a string" (10 nm) → 30 nm fiber → loops → chromosome
  • Total: ~2 meters of DNA compacted into a ~6 μm nucleus!

3. DNA — FUNCTIONS

FunctionDescription
1. Genetic StorageBlueprint of every organism — sequence of A, T, G, C
2. ReplicationSemi-conservative self-copying before cell division
3. TranscriptionTemplate for RNA synthesis
4. Mutation & EvolutionBase changes drive genetic variation and disease
5. RecombinationCrossover in meiosis → genetic diversity
6. Gene RegulationPromoters, enhancers, silencers control gene expression

DNA Replication — Key Points

  • Semi-conservative — one old strand + one new strand in each daughter DNA
  • Bidirectional — forks move outward from origin (ori)
  • DNA Pol III (prokaryotes) / Pol δ/ε (eukaryotes) adds nucleotides 5'→3'
  • Requires RNA primer — DNA Pol cannot start de novo
  • Leading strand — synthesized continuously
  • Lagging strand — synthesized as Okazaki fragments
  • Proofreading — 3'→5' exonuclease corrects errors (error rate ~1 in 10⁹)
⚠️ Clinical — DNA Repair Defects:
  • Xeroderma Pigmentosum — defective NER → UV damage not repaired → skin cancer
  • Lynch Syndrome (HNPCC) — defective Mismatch Repair → colorectal cancer
  • BRCA1/2 mutations — defective Homologous Recombination → breast & ovarian cancer

4. RNA — TYPES AND FUNCTIONS

RNA is a single-stranded nucleic acid transcribed from DNA. It is the intermediary between the genetic code and protein synthesis.

A. Three Major Types of RNA

TypeAbbrev% of RNALocationFunction
Messenger RNAmRNA~3-5%Nucleus → CytoplasmCarries genetic message (codons) from DNA to ribosome for translation
Ribosomal RNArRNA~80%RibosomesStructural AND catalytic component of ribosomes
Transfer RNAtRNA~15%CytoplasmAdaptor molecule — carries amino acid to ribosome; anticodon reads mRNA codon

B. Other Regulatory RNA Types

TypeAbbrevFunction
Small nuclear RNAsnRNAPart of spliceosomes — removes introns from pre-mRNA
Small nucleolar RNAsnoRNADirects chemical modifications of rRNA in nucleolus
MicroRNAmiRNA~22 nt; post-transcriptional gene silencing
Small interfering RNAsiRNA~21 nt double-stranded; RNA interference (RNAi)
Long non-coding RNAlncRNAGene regulation; X-chromosome inactivation (XIST)
RibozymeRNA with catalytic activity (self-splicing; peptidyl transferase)

C. mRNA Structure (Eukaryotic)

ComponentFunction
5' Cap (7-methylguanosine)Protects mRNA; required for ribosome binding
5' UTRContains Kozak sequence; ribosome binding
Open Reading Frame (ORF)AUG (start) → UAA/UAG/UGA (stop); encodes protein
3' UTRmiRNA binding; mRNA stability
3' Poly-A tail (~200 A's)Protects from degradation; aids translation

D. Ribosomal RNA — Prokaryote vs Eukaryote

OrganismSmall SubunitLarge SubunitRibosome
Prokaryotes30S (16S rRNA)50S (23S + 5S rRNA)70S
Eukaryotes40S (18S rRNA)60S (28S + 5.8S + 5S rRNA)80S
Mitochondria28S (12S rRNA)39S (16S rRNA)55S
Antibiotics targeting ribosomes:
  • 30S inhibitors: Tetracyclines, Aminoglycosides (Gentamicin), Streptomycin
  • 50S inhibitors: Chloramphenicol, Erythromycin (macrolides), Clindamycin, Linezolid
  • Mnemonic: "TANK" hits 30S | "CCLE" hits 50S

5. DIFFERENCES BETWEEN DNA AND RNA

FeatureDNARNA
Full nameDeoxyribonucleic AcidRibonucleic Acid
SugarDeoxyribose (lacks 2'–OH)Ribose (has 2'–OH)
BasesA, T, G, CA, U, G, C (Uracil replaces Thymine)
StrandsDouble-strandedSingle-stranded (usually)
HelixRight-handed double helixNo stable helix; forms hairpin loops
LocationNucleus + MitochondriaNucleus + Cytoplasm + Ribosomes
StabilityVery stable; long-livedLess stable; degraded by RNases
2'–OH groupAbsent (more stable)Present (more reactive)
Modified bases5-methylcytosine (epigenetics)Pseudouridine (ψ), Dihydrouridine (D), Inosine
FunctionPermanent genetic storage; templateCarries, adapts, catalyzes protein synthesis
AmountConstant (6 pg/diploid cell)Variable (depends on gene expression)
SynthesisDNA ReplicationTranscription (no primer needed)
AlkaliStable to dilute alkaliHydrolyzed by dilute alkali (2'–OH cleaves)
As genetic materialAll cellular organisms + most virusesRNA viruses: HIV, influenza, SARS-CoV-2

6. tRNA — STRUCTURE AND FUNCTION

Overview

  • tRNA is the adaptor molecule of translation
  • Size: 73–93 nucleotides (smallest functional RNA)
  • At least 20 types — one for each amino acid
  • Some amino acids have multiple tRNAs (isoacceptor tRNAs)
  • Charged tRNA = tRNA + amino acid attached
  • Charging enzyme: Aminoacyl-tRNA Synthetase (20 types)
  • Charging reaction requires ATP → AMP + PPi (consumes 2 high-energy bonds)

Cloverleaf Structure (2D Secondary Structure)

tRNA folds into a cloverleaf shape through intramolecular base pairing. Has 4 stems and 3-4 loops:
StructureStem (bp)Key ContentsFunction
Acceptor Stem7 bp5' end + universal 3'-CCA-OHAmino acid attachment site — amino acid ester-bonded to 3'-OH of terminal adenosine
D-Arm (D-Stem-Loop)3-4 bpDihydrouridine (D)Recognition by aminoacyl-tRNA synthetase
Anticodon Arm5 bpMiddle 3 nt = anticodon (5'-NNN-3')Reads mRNA codon by antiparallel complementary pairing
Variable Loop0-5 bpVariable (4-21 nt)Classification; synthetase recognition in some tRNAs
TψC Arm5 bpRibothymidine (T) + Pseudouridine (ψ)Ribosome binding (EF-Tu); correct A-site positioning

7. tRNA CLOVERLEAF DIAGRAM

                    5'─────────────────3'─CCA─OH
                         │  ACCEPTOR │         │
                         │   STEM    │    ← Amino acid attaches here
                         │  (7 bp)   │      (ester bond to 3'–OH)
                   ┌─────┘           └─────┐
                   │                       │
             D-ARM │                       │ TψC-ARM
            (3-4bp)│                       │ (5 bp)
                   │                       │
             ┌─────┘                       └─────┐
             │       D-LOOP         TψC-LOOP     │
             │  (Dihydrouridine)  (RiboThymidine  │
             │                   + Pseudouridine) │
             └─────┐                       ┌─────┘
                   │                       │
                   │     VARIABLE LOOP     │
                   │      (4–21 nt)        │
                   └───────────┬───────────┘
                               │
                        ANTICODON ARM
                           (5 bp stem)
                               │
                        ┌─────────────┐
                        │             │
                        │  ANTICODON  │
                        │    LOOP     │
                        │ 5'─N─N─N─3'│  ← Base-pairs with
                        │             │    mRNA CODON
                        └─────────────┘
★ The cloverleaf (2D) folds into an L-shaped 3D structure where the acceptor end (amino acid) and anticodon end are ~7 nm apart.

Modified Bases in tRNA

Modified BaseParent BaseLocationFunction
Dihydrouridine (D)UridineD-loopFlexible conformation for synthetase recognition
Pseudouridine (ψ)UridineTψC loopStabilizes helix (C5-glycosidic bond instead of N1)
Ribothymidine (T)ThymidineTψC loopRibosome binding (unusual in RNA)
Inosine (I)AdenosineAnticodon pos. 34Wobble base — pairs with U, C, or A on mRNA
Wobble Hypothesis (Crick, 1966): The 3rd codon base pairs loosely ("wobbles") with the 1st anticodon base. ONE tRNA can read MULTIPLE codons differing at the 3rd position. Inosine (I) can pair with U, C, or A → fewer tRNAs needed than codons (~45 tRNAs read 61 codons).

8. tRNA FUNCTION IN TRANSLATION

Steps of tRNA Action

StepProcessDetails
1Aminoacylation (Charging)Aminoacyl-tRNA Synthetase attaches amino acid to 3'-OH. ATP → AMP + PPi
2Enter A-siteCharged tRNA enters A-site as ternary complex with EF-Tu + GTP
3Codon-Anticodon RecognitionAnticodon pairs with mRNA codon; GTP hydrolysis confirms correct match
4Peptide Bond FormationPeptidyl transferase (23S rRNA — a RIBOZYME!) transfers growing chain from P-site to A-site amino acid
5TranslocationRibosome moves 3 nt: A→P→E; catalyzed by EF-G + GTP
6ReleaseStop codon (UAA, UAG, UGA) → Release Factors → polypeptide released

Ribosomal Sites

SiteNameContainsFunction
A-siteAminoacylIncoming charged tRNACodon-anticodon recognition
P-sitePeptidyltRNA carrying growing chainPeptide bond formation
E-siteExitUncharged (empty) tRNAtRNA exits ribosome
Mnemonic: "APE" = A (Aminoacyl) → P (Peptidyl) → E (Exit) ★ Peptidyl transferase = 23S rRNA ribozyme — proves the RNA World hypothesis

9. MASTER SUMMARY

The Central Dogma

DNA → (Replication) → DNA → (Transcription) → RNA → (Translation) → Protein
  • Reverse Transcription (RNA → DNA): HIV uses Reverse Transcriptase
  • RNA Replication (RNA → RNA): RNA viruses use RNA-dependent RNA Pol

Clinical Correlations

DiseaseNucleic Acid ConnectionKey Point
HIV/AIDSRNA virus; reverse transcriptionHIV RNA → RT → DNA → provirus; drugs: AZT, Tenofovir
COVID-19RNA virus; mRNA vaccinemRNA vaccines encode spike protein
CancerDNA mutationsRAS, MYC, HER2 (oncogenes); p53, RB, BRCA (tumor suppressors)
Xeroderma PigmentosumDefective NERCannot repair UV thymine dimers → skin cancers
Sickle Cell DiseaseSingle nucleotide mutationGAG→GTG → Glu→Val in β-globin → HbS polymerization
SLE (Lupus)Anti-dsDNA antibodiesAnti-dsDNA and anti-Smith (snRNP) = diagnostic markers
GalactosaemiaGalactose metabolismBenedict's test +ve but glucose dipstick -ve (galactose in urine)

All Mnemonics

TopicMnemonic
Purines"PURe As Gold" = Adenine + Guanine
Pyrimidines"CUT the PY" = Cytosine, Uracil, Thymine
DNA-only base"Thymine Tells DNA"
tRNA loops"Departed Anticodons To Variable exits" = D-loop, Anticodon, TψC, Variable
Ribosomal sites"APE" = Aminoacyl → Peptidyl → Exit
Prokaryote ribosome50S + 30S = 70S
Eukaryote ribosome60S + 40S = 80S
H-bonds"AT = 2, GC = 3"
30S antibiotics"TANK" = Tetracyclines, Aminoglycosides, Neomycin, Kanamycin
50S antibiotics"CCLE" = Chloramphenicol, Clindamycin, Linezolid, Erythromycin
Central DogmaDNA → RNA → Protein = "DRiP"

Sources: Thompson & Thompson Genetics 9e | Basic Medical Biochemistry 6e | Harper's Illustrated Biochemistry 32e
This is a shared conversation. Sign in to Orris to start your own chat.