Progression of a chronic disease can lead to the development of secondary illnesses. An example is the development of active tuberculosis (TB) in HIV-infected individuals. HIV disease progression, as indicated by declining CD4 + T-cell count (CD4), increases both the risk of TB and the risk of AIDS-related mortality. This means that CD4 is a time-dependent confounder for the effect of TB on AIDS-related mortality. Part of the effect of TB on AIDS-related mortality may be indirect by causing a drop in CD4. Estimating the total causal effect of TB on AIDS-related mortality using standard statistical techniques, conditioning on CD4 to adjust for confounding, then gives an underestimate of the true effect. Marginal structural models (MSMs) can be used to obtain an unbiased estimate. We describe an easily implemented algorithm that uses G-computation to fit an MSM, as an alternative to inverse probability weighting (IPW). Our algorithm is simplified by utilizing individual baseline parameters that describe CD4 development. Simulation confirms that the algorithm can produce an unbiased estimate of the effect of a secondary illness, when a marker for primary disease progression is both a confounder and intermediary for the effect of the secondary illness. We used the algorithm to estimate the total causal effect of TB on AIDS-related mortality in HIV-infected individuals, and found a hazard ratio of 3.5 (95 per cent confidence interval 1.2–9.1). Copyright © 2009 John Wiley & Sons, Ltd.