# include "psphotInternal.h"

// replace the flux for sources which failed
bool psphotReplaceUnfit (psArray *sources) { 

    pmSource *source;

    psTimerStart ("psphot");

    for (int i = 0; i < sources->n; i++) {
      source = sources->data[i];

      // replace other sources?
      if (source->mode & PM_SOURCE_MODE_FAIL) goto replace;
      continue;

    replace:
	pmSourceAdd (source, PM_MODEL_OP_FULL);
	source->mode &= ~PM_SOURCE_MODE_SUBTRACTED;
	source->mode &= ~PM_SOURCE_MODE_TEMPSUB;
    }
    psLogMsg ("psphot.replace", 3, "replace unfitted models: %f sec (%ld objects)\n", psTimerMark ("psphot"), sources->n);
    return true;
}

bool psphotReplaceAll (psArray *sources) { 

    pmSource *source;

    psTimerStart ("psphot");

    for (int i = 0; i < sources->n; i++) {
      source = sources->data[i];

      // replace other sources?
      if (!(source->mode & PM_SOURCE_MODE_SUBTRACTED)) continue;

      pmSourceAdd (source, PM_MODEL_OP_FULL);
      source->mode &= ~PM_SOURCE_MODE_SUBTRACTED;
    }
    psLogMsg ("psphot.replace", PS_LOG_INFO, "replace models for %ld objects: %f sec\n", sources->n, psTimerMark ("psphot"));
    return true;
}

// add source, if the source has been subtracted (or if we ignore the state)
bool psphotAddWithTest (pmSource *source, bool useState) { 

    // what is current state? (true : add; false : sub)
    bool state = !(source->mode & PM_SOURCE_MODE_SUBTRACTED);
    if (state && useState) return true;
    
    // replace the model if 1) state says it is missing or 2) useState is false (just do it)
    if (!state || !useState) {
	pmSourceAdd (source, PM_MODEL_OP_FULL);
    }
    return true;
}

// sub source, if the source has been added (or if we ignore the state)
bool psphotSubWithTest (pmSource *source, bool useState) { 

    // what is current state? (true : sub; false : add)
    bool state = (source->mode & PM_SOURCE_MODE_SUBTRACTED);
    if (state && useState) return true;

    // replace the model if 1) state says it is missing or 2) useState is false (just do it)
    if (!state || !useState) {
	pmSourceSub (source, PM_MODEL_OP_FULL);
    }
    return true;
}

// add or sub source replace or if the source has 
bool psphotSetState (pmSource *source, bool curState) { 

    // what is desired state? (true : add; false : sub)
    bool newState = !(source->mode & PM_SOURCE_MODE_SUBTRACTED);
    if (curState == newState) return true;
    
    if (curState && !newState) {
	pmSourceSub (source, PM_MODEL_OP_FULL);
    }
    if (newState && !curState) {
	pmSourceAdd (source, PM_MODEL_OP_FULL);
    }
    return true;
}
