#include "TSFDefs.h"
#include "Sundance.h"
#include "LAPACKGeneralMatrix.h"
#include "DenseSerialVectorType.h"
#include "TSFTimer.h"
#include "FieldWriter.h"
#include "VTKWriter.h"

using namespace Sundance;

using namespace TSF;


int main(int argc, void** argv)
{
  try
    {
      MPIComm::init(&argc, &argv);
      Timer::start();

      double Re = 1000.0;

      int nx = 64;
      int ny = 64;
      Mesh mesh = rectMesh(0.0, 1.0, nx, 0.0, 1.0, ny);

      /* define coordinate functions for x and y coordinates */
      Expr x = new CoordExpr(0);
      Expr y = new CoordExpr(1);

      /* define cells sets for each of the four sides of the rectangle */
      CellSet boundary = new BoundaryCellSet();
      CellSet left = boundary.subset( x == 0.0 );
      CellSet right = boundary.subset( x == 1.0 );
      CellSet bottom = boundary.subset( y == 0.0 );
      CellSet top = boundary.subset( y == 1.0 );

      TSFVectorSpace discreteSpace 
        = new SundanceVectorSpace(mesh, new Lagrange(1),
                                  new PetraVectorType());

      // define variations and unknowns for U, V, and P.
      /* use Taylor-Hood discretization */
      Expr delU = new TestFunction(new Lagrange(2), "delU");
      Expr U = new UnknownFunction(new Lagrange(2), "U");
      Expr delV = new TestFunction(new Lagrange(2), "delV");
      Expr V = new UnknownFunction(new Lagrange(2), "V");
      Expr delP = new TestFunction(new Lagrange(1), "delP");
      Expr P = new UnknownFunction(new Lagrange(1), "P");

      Expr delPsi = new TestFunction(new Lagrange(1), "delPsi");
      Expr psi = new UnknownFunction(new Lagrange(1), "psi");

      /* initial velocity */
      Expr u0 = new DiscreteFunction(discreteSpace, 0.0, "u0");
      Expr v0 = new DiscreteFunction(discreteSpace, 0.0, "v0");
			
      Expr delVelocity = List(delU, delV);
      Expr velocity = List(U, V);

      // create differential operators for x and y directions, and
      // then form gradient operator.
      Expr dx = new Derivative(0);
      Expr dy = new Derivative(1);
      Expr grad = List(dx, dy);
			
      // momentum continuity 
			
      Expr momentumEqn  = delU*(u0*dx + v0*dy)*U + 1/Re*(grad*U)*(grad*delU) 
        + delV*(u0*dx + v0*dy)*V + 1.0/Re*(grad*V)*(grad*delV)
        + P*(dx*delU + dy*delV);

      // incompressibility

      Expr continuityEqn = delP*(dx*U + dy*V);

      /* extract streamfunction from velocity */
      Expr streamfunctionEqn = (grad*psi)*(grad*delPsi) 
        + delPsi*(dx*V - dy*U);

      Expr eqn = Integral(momentumEqn) + Integral(continuityEqn) 
        + Integral(streamfunctionEqn);

      /*
       * Boundary conditions: 
       * v=0 on all sides
       * u=1 on top 
       * u=0 elsewehere
       */

      EssentialBC bc = EssentialBC(top, delU*(U-1) + delV*V + delPsi*psi)
        && EssentialBC(left, delU*(U) + delV*V + delPsi*psi)
        && EssentialBC(right, delU*(U) + delV*V + delPsi*psi)
        && EssentialBC(bottom, delU*(U) + delV*V + delPsi*psi);


      /*
        Create a solver object: stablized biconjugate gradient solver
      */
      TSFPreconditionerFactory prec = new ILUKPreconditionerFactory(2);
      TSFLinearSolver solver = new BICGSTABSolver(prec, 1.0e-12, 400);

      StaticLinearProblem prob(mesh, eqn, bc, List(delU, delV, delP, delPsi),
                               List(U, V, P, psi), 
                               new PetraVectorType());

      int i=0; 
      int maxiters = 10;
      bool converged = false;
			
      while (i < maxiters)
        {
          Expr soln = prob.solve(solver);
          u0 = soln[0];
          v0 = soln[1];
          Expr p0 = soln[2];
          Expr psi0 = soln[3];
          ofstream uFile(string("u." + TSF::toString(i) + ".dat").c_str());
          ofstream vFile(string("v." + TSF::toString(i) + ".dat").c_str());
          ofstream pFile(string("p." + TSF::toString(i) + ".dat").c_str());
          ofstream psiFile(string("psi." + TSF::toString(i) + ".dat").c_str());
          //	u0.matlabDump(uFile);
          //v0.matlabDump(vFile);
          //p0.matlabDump(pFile);

          FieldWriter writer = new VTKWriter("psi." + TSF::toString(i) + ".vtk");
          writer.writeField(mesh, "temperature", psi0);
          psi0.matlabDump(psiFile);
          prob.flushMatrixValues();
          i++;
        }

      Expr omega = dx*v0 - dy*u0;
      double totalVorticity = omega.integral(mesh);

      cerr << "total vorticity = " << totalVorticity << endl;
			

    }
  catch(exception& e)
    {
      TSFOut::println(e.what());
      Testing::crash(__FILE__);
      Testing::timeStamp(__FILE__, __DATE__, __TIME__);
    }
  Timer::report();
  MPIComm::finalize();
}







