#define XERR
#include "loop.ih"

    // true: the case has died or detected a tumor

    // by screening.cc

bool Loop::leaving(double screeningAge)
{
    bool before1stRound = screeningAge == d_firstRoundAge;

    // A1:
    if (not d_tumor.at(screeningAge))       // no tumor yet at this age
        return 
            d_naturalDeathAge <= screeningAge ?     // case dies naturally
                left(before1stRound ? NATURAL_PRE : NATURAL_DURING, d_deathAge)
            :
                false;                      // nothing happened: perform
                                            // the screening

    // A2: there is a tumor at 'screeningAge'

    if (    // A3
        d_naturalDeathAge < screeningAge and 
        not d_tumor.selfDetectBefore(d_naturalDeathAge)
    )
    {
        d_tumor.characteristicsAt(d_naturalDeathAge);
        d_deathAge = d_naturalDeathAge;
        bool died = d_naturalDeathAge < d_tumor.onset();
        return left(
                    before1stRound ? 
                            died ? NATURAL_PRE    : UNDETECTED_PRE 
                        : 
                            died ? NATURAL_DURING : UNDETECTED_DURING, 
                    d_naturalDeathAge);
    }

    // A4
    if (d_tumor.selfDetectBefore(screeningAge))     // self-detectable?
    {   
        d_tumor.characteristicsAt(d_tumor.selfDetectAge());

        d_tumor.setDeathAge();
        d_caseCost += treatmentCosts(d_tumor.selfDetectAge());

        return before1stRound ?
                    left(SELF_PRE, min(d_naturalDeathAge, d_tumor.deathAge()))
                :
                    intervalCancer();
    }

    return false;                       // perform the screening
}
