
#include <iostream.h>
#include <fstream.h>
#include <string>

#include "fecha.h"

typedef Fecha vector_fechas[500];

struct Vector
{
   vector_fechas info;
   int num_fechas;
};

void Presentacion (void);
bool LeerFicheroFechas (Vector &);
void OrdenarFechas (Vector &);
void Q_S_R(vector_fechas, int, int);
void MostrarFechas (Vector);

int main (void)
{
   Vector vect;

   Presentacion ();

   if (LeerFicheroFechas (vect) == false)
   {
      OrdenarFechas (vect);
      MostrarFechas (vect);
   }
   else
      cout << "Error leyendo el vector.\n";
}

void Presentacion (void)
{
}

bool LeerFicheroFechas (Vector & vect)
{
   ifstream f_in;
   bool error;
   int dia, mes, anyo;
   string s_aux;

   f_in.open ("fechas.dat");

   if (!f_in)
      error = true;
   else
   {
      error = false;
      vect.num_fechas = 0;
      while (f_in)
      {
	 f_in >> dia >> mes >> anyo;
	 if (vect.info[vect.num_fechas].IniciarFecha (dia, mes, anyo) )
	 {
	    cout << "Error. La fecha: " << dia << "/" << mes << "/" << anyo;
	    cout << " es incorrecta.\n";
        cout << "Pulsa enter para seguir";
        getline (cin, s_aux);
	 }
	 else
	    vect.num_fechas++;
      }
   }
   return error;
}

void OrdenarFechas (Vector & vect)
{
   Q_S_R (vect.info, 0, vect.num_fechas);
}

void MostrarFechas (Vector vect)
{
   int i;

   for (i = 0; i < vect.num_fechas; i++)
   {
      vect.info[i].EscribirFecha();
      if ( (i % 3) == 0 )
         cout << "\n";
      else
         cout << "\t";
   }
}

/*
 *  Funci¢n de ordenaci¢n por Quick-Sort
 */

void Q_S_R(vector_fechas vect, int izda, int dcha)
{
	int i, k;
	int dia_aux, mes_aux, anyo_aux;
    Fecha f_aux;
	Fecha pivote;

	i = izda;
	k = dcha;

    vect[(i + k) / 2].DeterminarFecha (dia_aux, mes_aux, anyo_aux);
	pivote.IniciarFecha (dia_aux, mes_aux, anyo_aux);

	do
	{
		while (vect[i].MenorFecha (pivote) )
			i++;

		while (vect[k].MayorFecha (pivote) )
			k--;

		if (i <= k)
		{
			vect[i].DeterminarFecha (dia_aux, mes_aux, anyo_aux);
            f_aux.IniciarFecha (dia_aux, mes_aux, anyo_aux);

            vect[k].DeterminarFecha (dia_aux, mes_aux, anyo_aux);
			vect[i].IniciarFecha (dia_aux, mes_aux, anyo_aux);

            f_aux.DeterminarFecha (dia_aux, mes_aux, anyo_aux);
			vect[k].IniciarFecha (dia_aux, mes_aux, anyo_aux);

			i++;
			k--;
		}
	}
    while(i <= k);

	if (izda < k)
		Q_S_R (vect, izda, k);

	if (i < dcha)
		Q_S_R (vect, i, dcha);

	return;
}

