//_____________________________________________________________________________
///
/// \class FitStateDiverged
///
/// FitStateDiverged is the diverged state - Iterate calculates
/// number of planes to fit during next iteration.
///
/// \author Sergei avva@fnal.gov
///

#include <string>

#include "Algorithm/AlgConfig.h"
#include "MessageService/MsgService.h"

#include "CandFitTrackSA/ConstFT.h"
#include "CandFitTrackSA/DataFT.h"
#include "CandFitTrackSA/MatrixCalculator.h"

#include "CandFitTrackSA/FitStateFactory.h"
#include "CandFitTrackSA/FitStateDiverged.h"
#include "CandFitTrackSA/FitContext.h"

CVSID("$Id: FitStateDiverged.cxx,v 1.2 2006/02/04 21:47:35 avva Exp $");

// The ID of class Line
static const std::string DIVERGED_FIT_STATE = "Diverged";

// Create an anonymous namespace
// to make the function invisible from other modules
namespace {

FitState* CreateDivergedFS() { return new FitStateDiverged; }

// register block
bool registered = FitStateFactory::Instance().RegisterFitState(
                                                    DIVERGED_FIT_STATE,
                                                            CreateDivergedFS);
}  // namespace


///
/// Name() - return name of the state 
///
const std::string& FitStateDiverged::Name() const
{
    return DIVERGED_FIT_STATE;
}    


///
/// Iterate method
///
void FitStateDiverged::Iterate(FitContext& context) const
{
    // reset number of iterations
    context.fNIterationsStep = 0;
       
    // reset number of diverging iterations
    context.fNTriesDiverges = 0;   
    
    // next step in dearch of convergence
    if ( context.fConvergenceMaster.NextStep() ) {    
        if ( ! context.fConvergenceMaster.MaskIsValid() ) { 
            // apply the next mask
            context.fData.SetUHitUse( context.fConvergenceMaster.GetMaskUCur() );
            context.fData.SetVHitUse( context.fConvergenceMaster.GetMaskVCur() );
            context.fConvergenceMaster.SetMaskIsValid(kTRUE);
            MSG("FitTrackSA",Msg::kInfo) << "Updated U, V Masks.\n";
        }    
        context.fDChi2 = ConstFT::InitialDChi2;
        context.SetFromLastGoodFit();
        context.SetState(FitStateFactory::Instance().GetFitState("Iterating"));
        //context.Print();
        MSG("FitTrackSA",Msg::kInfo) << "Switched from Diverged to Iterating\n";
    } else {
        context.SetState(FitStateFactory::Instance().GetFitState("Final"));
        //context.Print();
        MSG("FitTrackSA",Msg::kInfo) << "Switched from Diverged to Final\n";
        return;
    }
    
}

