refactored chapter writing logic