// This may look like C code, but it is really -*- C++ -*-
// RTSS --- Railway Total System Simulator
// (c) TAKAGI Ryo (at Kogakuin University)
// trn_stop.cc --- class train functions on nextmotion: nm_stnstop
// -----
// ChangeLog:
// 2007. 11. 22
//  Redirected log messages to l_file.
// -----

#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <iostream>

#include "train.hh"
#include "StrPrintf.hh"

#define INVLIM 1e-5

//#define DEBUG
//#define TIMEPRINT

// 停車時間が終わったら力行開始
void train::nm_stnstop
( double tracff ) {
#ifdef DEBUG
  cerr << StrPrintf ( "nm_stnstop, tracff = %.1f" , tracff ) << endl ;
#endif
    if ( t_sim >= tdept + tdept_delay() ) {
#ifdef DEBUG
        cerr << "This train No. " << car_number() << " wants to depart\n";
#endif
        if ( g_sw_station_object_valid && g_sw_disttrain_ended ) {
            // 信号系が有効である時のみ *** 注意 ***
            if ( stnobj_now->do_not_depart( this ) ) {
#ifdef DEBUG
                cerr << "but signal will not permit it\n";
#endif
                return;
            }
#ifdef DEBUG
            cerr << "and signal will permit it, too\n";
#endif
        } else {
#ifdef DEBUG
            cerr << "and signal system not in use while in disttrain\n";
#endif
        }
	stat = Power;
	iamconst = true;	iamcoast = false;
	ontprec = nxx->get_ontprec();
	rnotchold = rnotch = 1.0;
	pfirst = 0;
        if ( g_sw_station_object_valid ) {
            // 信号系が有効である時のみ *** 注意 ***
            if ( g_sw_disttrain_ended ) {
                // disttrain が終了した後のみ行う
                // この列車は出発しますよ、という宣言
                stnobj_now->this_train_will_depart( this );
#ifdef DEBUG
                cerr << "declared to depart\n";
#endif
            }

            // stnobj_now の入れ換え
#ifdef DEBUG
            cerr << "get new station_obj, train No. " << car_number();
            cerr << ", station_obj No. " << stnobj_now->get_stnno() << "\n";
#endif
            stnobj_now = nxx->stnobj();

            if ( g_sw_disttrain_ended ) {
                // disttrain が終了した後のみ行う
                // to_station を新しい station_obj に通信,
#ifdef DEBUG
                cerr << "communicate with the new station_obj\n";
#endif
                stnobj_comm();	// 時隔計算を新たに行う
            }
        }
    }
}

double train::tdept_delay
() {
    if ( g_sw_station_object_valid && g_sw_disttrain_ended ) {
        // 信号系が有効である時のみ *** 注意 ***
#ifdef DEBUG
        cerr << "tdept_delay: before stnobj_now->do_not_depart()\n";
#endif
        if ( stnobj_now->do_not_depart( this ) ) {
            return 3600;	// とりあえず長〜い時間を返す
        } else {
            return stnobj_now->tdept_delay( this );
        }
    } else return 0.0;
}
