// This may look like C code, but it is really -*- C++ -*-
// RTSS --- Railway Total System Simulator
// (c) TAKAGI Ryo (at Kogakuin University)
// trnext.cc --- class train functions on nextmotion
// -----
// 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




// 前方制限速度の検知
bool
train :: vlimitbrake
()
{
  nextsta :: gc_size_type i = 0 ;
  for ( i = nxx -> dqgrad () ;
        ( i > pgrad && direc () == 1 ) || ( i < pgrad && direc () == - 1 ) ;
        i -= direc () )
  {
    if ( nxx -> vlimit ( i ) < INVLIM
         || nxx -> vlimit ( i ) >= nxx -> vlimit ( pgrad ) )
    {
      // 制限なしのとき
      continue ;
    }

    if ( bklen ( pos , pgrad , vel , nxx -> vlimit ( i ) ) * direc ()
         >= nxx -> spoint ( i ) * direc () )
    {
      // 前方制限速度減速の条件
      stat = Brake ;
      brakev = nxx -> vlimit ( i ) ;
      rnotchold = rnotch = - 1.0 ;
      return true ;
    }
  }
  return false ;
}




// 列車の次状態の計算
void
train :: nextmotion
( double tracff )
{
  switch ( stat )
  {
  case Power :		// 力行中
    nm_power ( tracff ) ;
    break ;
  case Coast :		// 惰行中
    nm_coast ( tracff ) ;
    break ;
  case Regenerate :	// 回生中 (非ブレーキ)
    nm_regen ( tracff ) ;
    break ;
  case Brake :		// ブレーキ中
    nm_brake ( tracff ) ;
    break ;
  case Stn_stop :	// 駅停車中
    nm_stnstop ( tracff ) ;
    break ;
  case Between_stop :	// 駅間停車中
    nm_stnbtws ( tracff ) ;
    break ;
  case Const_vel :	// 定速走行中
    nm_constv ( tracff ) ;
    break ;
  }
  if ( pos * direc() >= nxx -> nextswitch () * direc () )
  {
    setNextstaPointer ( nxx -> nextnxx () ) ;	// 次駅データの入れ換え
  }
}
