#include <stdio.h>
#include <math.h>
#include "timestep.h"
#include "solver.h"
#include "march-config.h"

Grid1D
march (Grid1D grid)
{
  int finFlag = 0;

  while (!finFlag) {
    int printFlag = 0;
    
    double tau = count_time_step(grid);
    double time = grid.time;
    double newTime = time + tau;
    
    // set output flag
    if (outputEveryStep)
      if (grid.iter % outputEveryStep == 0)
	printFlag = 1;
    if (outputEveryTime)
      if ( fmod(grid.time, outputEveryTime) == 0)
	printFlag = 1;
    
    // set fin flag
    if (finTime)
      if (grid.time >= finTime)
	finFlag = 1;
    if (finStep)
      if (grid.iter >= finStep)
	finFlag = 1;
    
    // modify time step
    if (outputEveryTime)
      {
	if (newTime>finTime)
	  {
	    tau = finTime-newTime;
	    newTime = finTime;
	  }
	if (tau>outputEveryTime)
	  {
	    tau = outputEveryTime;
	    newTime = grid.time + tau;
	  }
	// условие перехода через точку времени, когда мы обязаны сделать вывод
	if ( fmod(newTime,outputEveryTime) < fmod(time,outputEveryTime) )
	  {
	    tau -= fmod(time,outputEveryTime);
	    newTime = grid.time + tau;
	  }
      }
    
    // печать
    if (printFlag || finFlag)
      printGridToFile(grid);

    // шаг
    if (!finFlag)
      {
	printf("Making iteration %06d; Passed time: %f\n", grid.iter+1, grid.time);
	Grid1D newgrid = make_step(grid, tau);
	grid = newgrid;
      }
    else
      {
	printf("Final conditions are reached! Finishing.\n");
	return grid;
      };
  }
  return grid;
}