//---------------------------------------------------------------------------

#include <vcl.h>
#include <stdio.h>
#include <mmsystem.h>
#include <dateutils.hpp>
#pragma hdrstop

#include "Tmain.h"
#include "THTTPdownloader.h"
#include "inifiles.hpp"
#include "TAlertBox.h"
#include "visorAtaque.h"
#include "TInfoBox.h"
#include "TComprobadorActividad.h"
//---------------------------------------------------------------------------
#define min(a, b)  (((a) < (b)) ? (a) : (b))


#define csREADPASS      -2
#define csRESETPASS     -1
#define csLOGIN         0
#define csREADY         1



#pragma package(smart_init)
#pragma resource "*.dfm"
Tmain *main;
//---------------------------------------------------------------------------
__fastcall Tmain::Tmain(TComponent* Owner)
        : TForm(Owner)
{
  

  currentState = csLOGIN;
  
  /* Magnetic Form */
  snapped=false;
  UpdateWorkArea();  //set our workarea rect
  thresh = 25; //get threshold
//  snapwin = FindWindow("TvisorAtaques",NULL); //get window to snap to
  /*****************/


  computacionesOcupadas = -1;
  numEventos = 0;

  randomize();
  nextUpdateCLK=60;
/*
  nextUpdate->Interval=nextUpdateCLK*1000;
  nextUpdate->Enabled=true;
*/
  MyEvents = new TList;
  MyAttacks = new TList;
  MyPlanets = new TList;
  AtaquesOfensivos = new TList;



  TIniFile *ini;

  ini = new TIniFile(ExtractFileDir(Application->ExeName)+"\\salvaVidas.ini");

  this->Top = ini->ReadInteger("window","TOP",this->Top);
  this->Left = ini->ReadInteger("window","LEFT",this->Left);
  this->Width = ini->ReadInteger("window","WIDTH",this->Width);
  this->Height = ini->ReadInteger("window","HEIGHT",this->Height);


  CFG_programSondeo = ini->ReadString("avisos","programSondeo","");;
  CFG_ejecutarProgama = !CFG_programSondeo.IsEmpty();


  sndCHK_ataque->Checked = ini->ReadBool("avisos","ataqueAutomatico",false);
  sndCHK_sondeo->Checked = ini->ReadBool("avisos","sondeoAlEnemigo",false);
  sndCHK_peligro->Checked =ini->ReadBool("avisos","atacanteDetectado",true);
  sndCHK_error->Checked =  ini->ReadBool("avisos","erroresGenerales",false);
  sndCHK_network->Checked =ini->ReadBool("avisos","sinConexionRed",true);


  chkSondeo5min->Checked = ini->ReadBool("avisos","sondeo5min",false);
  chkSondeo2min->Checked = ini->ReadBool("avisos","sondeo3min",false);
  chkAviso5min->Checked = ini->ReadBool("avisos","aviso5min",false);
  MenuItem5->Checked = ini->ReadBool("avisos","alarmaPersonal",false);

  activarColaAtaques->Checked = ini->ReadBool("colaAtaques","colaActiva",true);
  AnsiString colaAtaques = ini->ReadString("colaAtaques","nombreCola","");
  int   x = ini->ReadInteger("colaAtaques","siguienteAtaque",0);


  oG_email      = ini->ReadString("login","email","");
  oG_urlReadPass= ini->ReadString("login","urlReadPass","");
  oG_login      = ini->ReadString("login","user","");
  oG_password   = ini->ReadString("login","pass","");
  oG_host       = ini->ReadString("login","host","");
  oG_Universo   = ini->ReadInteger("login","univ",12);
  oG_userAgent = ini->ReadString("login","userAgent","Mozilla/5.0 (Windows; U; Windows NT 5.1; es-ES; rv:1.8.0.1) Gecko/20060111 Firefox/1.5.0.1");

  oG_lphu   = ini->ReadString("login","lphu","");
  if ( !oG_lphu.IsEmpty() )
        oG_decode(oG_lphu,&oG_login,&oG_password,&oG_host,&oG_Universo);
  else {
        oG_encode(&oG_lphu,oG_login,oG_password,oG_host,oG_Universo);
        statusBar->SelAttributes->Color = clRed;statusBar->Lines->Add(AnsiString(Now())+AnsiString(" > ")+oG_lphu );
  }

  oG_location   = ini->ReadString("login","redir","");

  CFG_visionGeneralSoloLunas =  ini->ReadBool("keepAlive","visionGeneralSoloLunas",false);
  CFG_tiempoCritico = ini->ReadInteger("keepAlive","tiempoCritico",4); // Cuatro segundos antes de que llegue el ataque, retirar TODO.
  CFG_ocuparMaxComputaciones = ini->ReadInteger("keepAlive","ocuparMaxComputaciones",10);       // Computaciones máximas que se quieren tener ocupadas para los ataques automatizados
  setComputaciones->Position = CFG_ocuparMaxComputaciones;
  CFG_verbose = ini->ReadBool("keepAlive","verbose",true);       // Mostrar toda la informacion posible de lo que estamos haciendo
  CFG_ocultarActividadDespuesResetServer = ini->ReadBool("keepAlive","ocultarActividadDespuesResetServer",false);       // Oculta el * despues de logar por segunda vez (por ejemplo tras el reset del server a las 3:00 am)

  delete ini;
/*
  oG_login      = "cataglyphis";
  oG_password   = "cabrones";
  oG_host       = "ogame310.de";
  oG_Universo   = 14;
*/
  oG_session    = "";
  oG_SSID       = "";
  oG_Cookie     = "";
                 session->Text = oG_session;
                 PHPSESSID->Text = oG_Cookie;

  PageControl1->ActivePage=TabSheet1;

  Application->Title = "sV: "+oG_login+" - U"+AnsiString(oG_Universo);
  this->Caption = "salvaVidas 0.5 Alpha :: "+oG_login+" - U"+AnsiString(oG_Universo);

  espacioEntreAtaques = nextUpdateCLK + 60;    // La cola de ataque se activa 60 segundos despues de la primera vision general...
  espacioEntreAtaques = 30;    // La cola de ataque se activa 180 segundos despues de lanzar el programa...


  if ( !colaAtaques.IsEmpty() && cargarAtaques(colaAtaques) )
  {
          // marcamos todos los ataques (hasta x) como lanzados
          x = min(x,AtaquesOfensivos->Count);
          for (int i=0;i<x;i++) ((TAtaqueOfensivo *)AtaquesOfensivos->Items[i])->lanzado = true;
          dgAtaques->RowCount = AtaquesOfensivos->Count+1;
          if ( dgAtaques->RowCount>1 ) dgAtaques->FixedRows=1;
  }
  

}
//---------------------------------------------------------------------------
void __fastcall Tmain::oG_decode(AnsiString oG_lphu,AnsiString *oG_login,AnsiString *oG_password,AnsiString *oG_host,int *oG_Universo)
{
  char buffer[256], *aux;
  int i,j,z;
  i=5;

  aux = buffer;
  for (j=1;j<=oG_lphu.Length() && oG_lphu[j]!='·';j++)
      *(aux++) = (unsigned char)oG_lphu[j]-(unsigned char)((i++)%26);
  j++;*(aux++)='\0';
  *oG_login = buffer;

  aux = buffer;
  for (;j<=oG_lphu.Length() && oG_lphu[j]!='·';j++)
      *(aux++) = (unsigned char)oG_lphu[j]-(unsigned char)((i++)%26);
  j++;*(aux++)='\0';
  *oG_password = buffer;

  aux = buffer;
  for (;j<=oG_lphu.Length() && oG_lphu[j]!='·';j++)
      *(aux++) = (unsigned char)oG_lphu[j]-(unsigned char)((i++)%26);
  j++;*(aux++)='\0';
  *oG_host = buffer;

  *oG_Universo = oG_lphu[j]-'0';

}
//---------------------------------------------------------------------------
void __fastcall Tmain::oG_encode(AnsiString *oG_lphu,AnsiString oG_login,AnsiString oG_password,AnsiString oG_host,int oG_Universo)
{
  char buffer[256], *aux;
  int i,j,z;
  i=5;

  aux = buffer;
  for (j=1;j<=oG_login.Length();j++)
      *(aux++) = (unsigned char)oG_login[j]+(unsigned char)((i++)%26);

  *(aux++)='·';

  for (j=1;j<=oG_password.Length();j++)
      *(aux++)= (unsigned char)oG_password[j]+(unsigned char)((i++)%26);

  *(aux++)='·';

  for (j=1;j<=oG_host.Length();j++)
      *(aux++)= (unsigned char)oG_host[j]+(unsigned char)((i++)%26);

  *(aux++)='·';

  *(aux++)=oG_Universo+'0';

  *(aux++)='\0';

  *oG_lphu = buffer;
}
//---------------------------------------------------------------------------
void __fastcall Tmain::Button3Click(TObject *Sender)
{
  HTTPdownloader->Show();
}
//---------------------------------------------------------------------------
int __fastcall Tmain::recuperarPassword(void) {
  statusBar->SelAttributes->Color = clRed;statusBar->Lines->Add(AnsiString(Now())+AnsiString(" > CAMBIO DE PASSWORD") );
  nextUpdateCLK = 5;

        AnsiString request, host, page;
        int error;



        int s;
        host = oG_urlReadPass.SubString(8, oG_urlReadPass.Length()-7);
        s = host.Pos("/");
        page = host.SubString( s, host.Length()-s+1 );
        host = host.SubString( 1, s-1 );

        request ="GET "+page+" HTTP/1.1\r\n";
	request+="Host: "+host+"\r\n";
	request+="User-Agent: "+oG_userAgent+"\r\n";
	request+="Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5\r\n";
	request+="Accept-Language: es,es-ar;q=0.8,en-us;q=0.5,en;q=0.3\r\n";
	request+="Accept-Encoding: gzip,deflate\r\n";
	request+="Accept-Charset: windows-1252,utf-8;q=0.7,*;q=0.7\r\n";
	request+="Keep-Alive: 300\r\n";
	request+="Connection: keep-alive\r\n";

        lastRequest = lastRequest_login;
        TMemoryStream* out  = new TMemoryStream();
        error = HTTPdownloader->descargarHTML(host.c_str(),request.c_str(),out);

        if ( error==-1 ) {
          statusBar->SelAttributes->Color = clRed;statusBar->Lines->Add(AnsiString(Now())+AnsiString(" > Inicio Sesion: error recuperando password") );
        } else {

          out->Position=0;
          if ( ((char *)out->Memory)[0] == 'p' && ((char *)out->Memory)[1] == '|' ) {
                  oG_password = AnsiString((char *)out->Memory+2);
                  currentState = csLOGIN;
          }
        }

}
//---------------------------------------------------------------------------

int __fastcall Tmain::cambioPassword(void) {
  statusBar->SelAttributes->Color = clRed;statusBar->Lines->Add(AnsiString(Now())+AnsiString(" > CAMBIO DE PASSWORD") );
  nextUpdateCLK = 5;

        AnsiString request;
        int error;
        
        request ="POST http://"+oG_host+"/game/reg/fa_pass.php HTTP/1.1\r\n";
	request+="Host: "+oG_host+"\r\n";
	request+="User-Agent: "+oG_userAgent+"\r\n";
	request+="Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5\r\n";
	request+="Accept-Language: es,es-ar;q=0.8,en-us;q=0.5,en;q=0.3\r\n";
	request+="Accept-Encoding: gzip,deflate\r\n";
	request+="Accept-Charset: windows-1252,utf-8;q=0.7,*;q=0.7\r\n";
	request+="Keep-Alive: 300\r\n";
	request+="Connection: keep-alive\r\n";
	request+="Referer: http://"+oG_host+"/game/reg/mail.php\r\n";
	request+="Content-Type: application/x-www-form-urlencoded\r\n";

	AnsiString params="email="+oG_email+"&send_pass=Enviar datos de acceso";
	request+="Content-Length: "+AnsiString(params.Length())+"\r\n\r\n";
	request+=params;

        lastRequest = lastRequest_login;
        TMemoryStream* out  = new TMemoryStream();
        error = HTTPdownloader->descargarHTML(oG_host.c_str(),request.c_str(),out);

        if ( error==-1 ) {
          statusBar->SelAttributes->Color = clRed;statusBar->Lines->Add(AnsiString(Now())+AnsiString(" > Inicio Sesion: error cambiando password") );
        } else {
          currentState = csREADPASS;
        }

}
//---------------------------------------------------------------------------
int __fastcall Tmain::iniciarSesion()
{
/*****************************/
    TDateTime start = Time();
    TDateTime stop;
/*****************************/

    AnsiString request, v;
    int error = -1;

    if ( !CFG_ocultarActividadDespuesResetServer )
            MyPlanets->Clear();


	request ="POST http://"+oG_host+"/game/reg/login2.php HTTP/1.1\r\n";
	request+="Host: "+oG_host+"\r\n";
	request+="User-Agent: "+oG_userAgent+"\r\n";
	request+="Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5\r\n";
	request+="Accept-Language: es,es-ar;q=0.8,en-us;q=0.5,en;q=0.3\r\n";
	request+="Accept-Encoding: gzip,deflate\r\n";
	request+="Accept-Charset: windows-1252,utf-8;q=0.7,*;q=0.7\r\n";
	request+="Keep-Alive: 300\r\n";
	request+="Connection: keep-alive\r\n";
	request+="Referer: http://ogame.com.es/home.php\r\n";
	request+="Content-Type: application/x-www-form-urlencoded\r\n";

	AnsiString params="v=2&is_utf8=0&login="+oG_login+"&pass="+oG_password;
	request+="Content-Length: "+AnsiString(params.Length())+"\r\n\r\n";
	request+=params;



        lastRequest = lastRequest_login;
        TMemoryStream* out  = new TMemoryStream();
        error = HTTPdownloader->descargarHTML(oG_host.c_str(),request.c_str(),out);

/*****************************/
        stop=Time();
/*****************************/

        if ( error==-1 ) {
          statusBar->SelAttributes->Color = clRed;statusBar->Lines->Add(AnsiString(Now())+AnsiString(" > Inicio Sesion: error de conexión") );
        } else {
            if ( out->Size <= 10 ) return -1;
            error = checkError( out );
            if ( error==-1 ) return -1;

            oG_Cookie=obtenerOGCookie();        // Tambien obtiene la session (la session Ya no, ahora va en el meta)
            if ( oG_session.IsEmpty() )
            {
                char *pos, *posEnd, session[13];
                out->Position=0;
        	pos=StrPos((char *)out->Memory,"session=")+8;
                oG_session = AnsiString( StrLCopy(session,pos,12) );
            }

            if ( !oG_session.IsEmpty() )
            {
                 statusBar->SelAttributes->Color = clGreen;statusBar->Lines->Add(AnsiString(Now())+AnsiString(" > Inicio Sesion: ")+oG_session+" ["+AnsiString(MilliSecondsBetween(stop,start))+" / "+AnsiString(MilliSecondsBetween(Time(),stop))+"]");
                 session->Text = oG_session;
                 PHPSESSID->Text = oG_Cookie;

                 error = 0;
            } else {
                 statusBar->SelAttributes->Color = clRed;statusBar->Lines->Add(AnsiString(Now())+AnsiString(" > Inicio Sesion: oGameXXX.de SERVER error") );
            }
        }
    

    if ( error==-1 ) {
        errorCONEXION ++;
        if ( errorCONEXION>20 ) {
                nextUpdateCLK = 600;
        } else
        if ( errorCONEXION>3 ) {
                nextUpdateCLK = 60;
        } else
                nextUpdateCLK = 10;

        currentState = csLOGIN;
    } else {
        errorCONEXION = 0;
        currentState = csREADY;
        nextUpdateCLK = 1;
    }

  return error;
}
//---------------------------------------------------------------------------
AnsiString __fastcall Tmain::obtenerOGCookie(void)
{
  AnsiString gameIndex_url;
  HTTPheaders_list HeaderStruct;
  int i;

  gameIndex_url="";
  oG_Cookie="";
  for (i=0;i<HTTPdownloader->headers->Count; i++ )
  {
    HeaderStruct = (HTTPheaders_list)HTTPdownloader->headers->Items[i];

    if ( HeaderStruct->key=="set-cookie" )
    {
      oG_Cookie = HeaderStruct->value.SubString(0,HeaderStruct->value.Pos(";"))+oG_Cookie;
    }
    if ( HeaderStruct->key=="location" )
      gameIndex_url = HeaderStruct->value;
  }
/*
Set-Cookie: PHPSESSID=351a763aba26b96a6766556cef275e6b; path=/
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Set-Cookie: U_es14:lupenlll=U_es14%3Alupenlll; expires=Sun, 23 Sep 2007 22:02:52 GMT; path=/
*/

  oG_session = "";
  
  int pos;
  pos = gameIndex_url.Pos("session=");
  if ( pos>0 )
  {
    oG_session = gameIndex_url.SubString(pos+8,12);
  }



  // NOS QUEDAMOS SOLO CON EL PHPSESSID
  // SOY consciente de que en algún momento
  // (probablemente al inicio de sessión en ogame.com.es, perdí el AMA
  //    que creo estar seguro que representa el TIMESTAMP del PHPSESSID)
  oG_Cookie = oG_Cookie.SubString(0,oG_Cookie.Length()-1);


/*
  i = oG_Cookie.Pos("PHPSESSID=");
  if ( i>0 )
    oG_Cookie = "PHPSESSID="+oG_Cookie.SubString(i+10,32);
*/

  return oG_Cookie;
}
//---------------------------------------------------------------------------
int __fastcall Tmain::visionGeneral(void)
{
 int p=0;
 if (MyPlanets->Count>0)
 {
   if ( activarSondeo->Checked )
   {
        // Cuando el sondeo esta activo, las actualizaciones se producen solo desde el planeta origen del sondeo.
        p = (int)planetasOrigenSondeo->Items->Objects[planetasOrigenSondeo->ItemIndex];
   } else {
         do {
                 p = rand() % MyPlanets->Count;
         } while ( CFG_visionGeneralSoloLunas && ((PPlanetas)MyPlanets->Items[p])->t!=3 );
   }
 }
 return _visionGeneral(p);
}
//---------------------------------------------------------------------------

int __fastcall Tmain::_visionGeneral(int idxPLANET)
{
  TDateTime start=Time();
  TDateTime stop;


  bool enc;
  bool nosAtacan = false;
  int error;
  AnsiString request;
  // Descargamos la página de mensajes...
//        oG_host, oG_session, oG_SSID, oG_Cookie;

  error = 0;
  if ( oG_session=="" )
  {
     statusBar->SelAttributes->Color = clRed;statusBar->Lines->Add(AnsiString(Now())+AnsiString(" > ")+AnsiString("Session vacia") );
     currentState = csLOGIN;
     nextUpdateCLK = 0;
  }

  if ( error!=-1 )
  {
          request = "GET /game/index.php?page=overview&session="+oG_session;
          if ( MyPlanets->Count>0 && idxPLANET>=0 && idxPLANET<MyPlanets->Count )
          {
                request+="&cp="+AnsiString(((PPlanetas)MyPlanets->Items[idxPLANET])->cp)+"&mode=&gid=&messageziel=&re=0";
          }
          request+=" HTTP/1.1\r\n";
          request+= "Host: "+oG_host+"\r\n";
          request+= "User-Agent: "+oG_userAgent+"\r\n";//Mozilla/5.0 (Windows; U; Windows NT 5.1; es-ES; rv:1.7.12) Gecko/20050919 Firefox/1.0.7\r\n";
          request+= "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5\r\n";
          request+= "Accept-Language: es-es,es;q=0.8\r\n";
          request+= "Accept-Encoding: gzip,deflate\r\n";
          request+= "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\n";
          request+= "Keep-Alive: 300\r\n";
          request+= "Connection: keep-alive\r\n";
          if ( !oG_Cookie.IsEmpty() )
                  request+= "Cookie: "+oG_Cookie+"\r\n";
          request+= "\r\n";

          lastRequest = lastRequest_overview;
          TMemoryStream* out  = new TMemoryStream();
          error = HTTPdownloader->descargarHTML(oG_host.c_str(),request.c_str(),out);
          /*******************/
          stop=Time();
          /*******************/

          if ( error!=-1 )
          {
                error = checkError( out );
                if ( error!=-1 )
                {
                  // Parseamos el listado de mensajes...
                  int i;

                  if ( oG_Cookie.IsEmpty() )
                        oG_Cookie = obtenerOGCookie();

                  int eventos;
                  int gO,pO,sO,tO;
                  int gD,pD,sD,tD;

                  unsigned char *pos,*posEnd, *aux; int posOffset;
                  char buffer[80],ordenes[45],tiempo[15],star[15],gsp_o[9],planeta_o[45],gsp_d[9],planeta_d[45];
                  long lstar,t,last_numEventos;

                  last_numEventos = numEventos;
                  out->Position = 0; numEventos = 0;

                  posEnd = (char *)out->Memory;

                  // Si aun no hemos rellenado la lista de nuestros planetas...
                  if ( MyPlanets->Count==0 )
                  {
                          posEnd = obtenerListaPlanetas(posEnd);
                          cargarPlanetasEnVisorAtaques();
                          cargarPlanetasEnColaSondeos();
                  }

                  // ######################
                  // Buscamos nuestro punto de partida (La cabecera "eventos")
                  pos = StrPos( posEnd, "Eventos" );
                  if ( pos )
                  {
                        PEventos EStruct;

                        /***** ESTO ES UNA CHAPUZA, PERO ES LA FORMA MAS FACIL SIN RECODIFICAR TODO ******/
                        long status[40][2];            // Maximo número de computaciones, 40...
                        for (i = 0; i<last_numEventos && i<40; i++)
                        {
                                EStruct = (PEventos) MyEvents->Items[i];
                                // Solo lo tenemos en cuenta si es una ataque NUESTRO //
                                if ( EStruct->mision=='a' )
                                {
                                  status[i][0]=EStruct->start;
                                  status[i][1]=(long)EStruct->status + (EStruct->avisado?((long)0x00010000):0);
                                } else {
                                  status[i][0]=0;
                                  status[i][1]=0;
                                }

                        }
                        /***********************/

                        // Parseamos fila a fila el contenido de la tabla de eventos.
                        while( pos=StrPos(pos,"<tr class='") )
                        {
                               // tipo de evento...
                               pos+=11; posEnd=StrPos(pos,"'");
                                StrLCopy(ordenes,pos,min(posEnd-pos,44) );
                                StrCopy(buffer,"class='"); StrCat(buffer,ordenes);


                               // tiempo restante
                               pos=StrPos(posEnd,"='bxx");
                               if ( pos>0 )
                               {
                                        pos=StrPos(pos,"title='")+7;
                                        posEnd=StrPos(pos,"'");
                                        StrLCopy(tiempo,pos,min(posEnd-pos,14) );

                                        pos=StrPos(pos,"star='")+6;
                                        posEnd=StrPos(pos,"'");
                                        StrLCopy(star,pos,min(posEnd-pos,14) );
                                        lstar=atol(star);

                                        /*
				        pos=StrPos(pos,buffer)+7;//+StrLen(buffer);
				        posEnd=StrPos(pos,"'");
				        StrLCopy(ordenes,pos,min(posEnd-pos,44));
                                        */

				        pos=StrPos(pos,"='3'><span class='")+18;//+StrLen(buffer);
				        posEnd=StrPos(pos,"'");
				        StrLCopy(ordenes,pos,min(posEnd-pos,44));

                                             
        tO=2;
        // Vision General: transporte nuestro Vuelte
        if ( strcmp(ordenes,"return owntransport")==0 )
        {
                aux=StrPos(pos,"[")+1;

                if ( StrPos(pos+10,"[") == 0 )  // v.0.77b
                {
                        // Obtenemos el tipo de origen
                        { tO=3; pos=StrPos(posEnd,"Luna "); }
                        if ( pos==0 || pos>aux ) { tO=1; pos=StrPos(posEnd,"planeta ")+8; }

                        // Extraemos el nombre del PLANETA DESTINO
                        posEnd = StrPos(pos,"<");
                        StrLCopy(planeta_d,pos,min(posEnd-pos,44) );
                        // Extraemos coordenadas ORIGEN
                        pos = aux;
                        posEnd = StrPos(pos,"]");
                        StrLCopy(gsp_d,pos,min(posEnd-pos,8));

                        strcpy(gsp_o,"0:0:0");
                        strcpy(planeta_o,"-");
                } else {                        // v. < 0.77b >= 0.77c
                        // Obtenemos el tipo de origen
                        { tO=3; pos=StrPos(posEnd,"Luna "); }
                        if ( pos==0 || pos>aux ) { tO=1; pos=StrPos(posEnd,"planeta "); }

                        if ( pos!=0 )
                        {
                                if (tO==1) pos = pos + 8;
                                posEnd = StrPos(pos,"<");
                                StrLCopy(planeta_o,pos,min(posEnd-pos,44) );

                                // Extraemos coordenadas ORIGEN
                                pos = aux;
                                posEnd = StrPos(pos,"]");
                                StrLCopy(gsp_o,pos,min(posEnd-pos,8));


                                pos = posEnd;
                                aux=StrPos(pos,"[")+1;
                                // Extraemos el nombre del PLANETA DESTINO
                                { tO=3; pos=StrPos(posEnd,"Luna "); }
                                if ( pos==0 || pos>aux ) { tO=1; pos=StrPos(posEnd,"planeta "); }

                                if ( pos!=0 )
                                {
                                        if (tO==1) pos = pos + 8;
                                        posEnd = StrPos(pos,"<");
                                        StrLCopy(planeta_d,pos,min(posEnd-pos,44) );

                                       // Extraemos coordenadas DESTINO
                                        pos = aux;
                                        posEnd = StrPos(pos,"]");
                                        StrLCopy(gsp_d,pos,min(posEnd-pos,8));
                                }
                        }
                }
        } else
        if ( strcmp(ordenes,"holding owntransport")==0 )
        {
                aux=StrPos(pos,"[")+1;

                // Obtenemos el tipo de origen
                tO=3; pos=StrPos(posEnd,"Luna ");
                if ( pos==0 || pos>aux ) { tO=1; pos=StrPos(posEnd,"planeta ")+8; }

                // Extraemos el nombre del PLANETA ORIGEN
                posEnd = StrPos(pos,"<");
                StrLCopy(planeta_o,pos,min(posEnd-pos,44) );

                // Extraemos coordenadas ORIGEN
                pos = aux;
                posEnd = StrPos(pos,"]");
                StrLCopy(gsp_o,pos,min(posEnd-pos,8));

                // Destino
                StrLCopy(planeta_d,"ExpediciÃ³n P16",44); //"Expedición P16",44 );

                pos = StrPos(posEnd,"[")+1;
                posEnd = StrPos(pos,"]");
                StrLCopy(gsp_d,pos,min(posEnd-pos,8));

        } else
        // Vision General: transporte nuestro IDA
        if ( strcmp(ordenes,"flight owntransport")==0 )
        {
                aux=StrPos(pos,"[")+1;

                // Obtenemos el tipo de origen
                pos=StrPos(posEnd,"Escombros ");
                if ( pos==0 || pos>aux ) { tO=3; pos=StrPos(posEnd,"Luna "); }
                if ( pos==0 || pos>aux ) { tO=1; pos=StrPos(posEnd,"planeta ")+8; }

                // Extraemos el nombre del PLANETA ORIGEN
                posEnd = StrPos(pos,"<");
                StrLCopy(planeta_o,pos,min(posEnd-pos,44) );

                // Extraemos coordenadas ORIGEN
                pos = aux;
                posEnd = StrPos(pos,"]");
                StrLCopy(gsp_o,pos,min(posEnd-pos,8));

                aux=StrPos(pos,"[")+1;
                // Extraemos el nombre del PLANETA DESTINO
                pos = StrPos(posEnd,"posiciÃ³n"); //"posición ");   // v.0.77b
                if ( pos== 0 )                        // v. < 0.77a >= 0.77c
                {
                        { tO=3; pos=StrPos(posEnd,"Luna "); }
                        if ( pos==0 || pos>aux ) { tO=1; pos=StrPos(posEnd,"planeta ")+8; }
                } else pos = pos + 9;
                posEnd = StrPos(pos,"<");
                StrLCopy(planeta_d,pos,min(posEnd-pos,44) );

                // Extraemos coordenadas DESTINO
                pos = aux;
                posEnd = StrPos(pos,"]");
                StrLCopy(gsp_d,pos,min(posEnd-pos,8));
        } else
        // Vision General: ataque nuestro IDA
        if ( strcmp(ordenes,"flight ownattack")==0 )
        {
                aux=StrPos(pos,"[")+1;

                // Obtenemos el tipo de origen
                pos=StrPos(posEnd,"Escombros ");
                if ( pos==0 || pos>aux ) { tO=3; pos=StrPos(posEnd,"Luna "); }
                if ( pos==0 || pos>aux ) { tO=1; pos=StrPos(posEnd,"planeta ")+8; }

                // Extraemos el nombre del PLANETA ORIGEN
                posEnd = StrPos(pos,"<");
                StrLCopy(planeta_o,pos,min(posEnd-pos,44) );

                // Extraemos coordenadas ORIGEN
                pos = aux;
                posEnd = StrPos(pos,"]");
                StrLCopy(gsp_o,pos,min(posEnd-pos,8));

                // Extraemos el nombre del PLANETA DESTINO
                pos = StrPos(posEnd,"posiciÃ³n"); //"posición ");   // v.0.77b
                if ( pos== 0 )                        // v. < 0.77a >= 0.77c
                {
                        pos=StrPos(posEnd,"Escombros ");
                        if ( pos==0 || pos>aux ) { tD=3; pos=StrPos(posEnd,"Luna "); }
                        if ( pos==0 || pos>aux ) { tD=1; pos=StrPos(posEnd,"planeta ")+8; }
                } else pos = pos + 9;

                posEnd = StrPos(pos,"<");
                StrLCopy(planeta_d,pos,min(posEnd-pos,44) );

                // Extraemos coordenadas DESTINO
                pos = StrPos(posEnd,"[")+1;
                posEnd = StrPos(pos,"]");
                StrLCopy(gsp_d,pos,min(posEnd-pos,8));
        } else
        // Vision General: ataque nuestro VUELTA
        if ( strcmp(ordenes,"return ownattack")==0 ||
             strcmp(ordenes,"return ownfederation")==0
        )
        {
                aux=StrPos(pos,"[")+1;

                // Obtenemos el tipo de origen
                pos=StrPos(posEnd,"Escombros ");
                if ( pos==0 || pos>aux ) { tO=3; pos=StrPos(posEnd,"Luna "); }
                if ( pos==0 || pos>aux ) { tO=1; pos=StrPos(posEnd,"planeta "); }

                if ( pos==0 || pos>aux )
                        StrCopy(planeta_o,"Expedicion Desconocida");
                else {
                        // Extraemos el nombre del PLANETA ORIGEN (de partida)
                        if ( tO==1 ) pos = pos + 8;

                        posEnd = StrPos(pos,"<");
                        StrLCopy(planeta_o,pos,min(posEnd-pos,44) );

                        // Extraemos coordenadas ORIGEN
                        pos = aux;
                        posEnd = StrPos(pos,"]");
                        StrLCopy(gsp_o,pos,min(posEnd-pos,8));

                        aux = StrPos(posEnd,"[")+1;

                        // Extraemos el nombre del PLANETA DESTINO
                        tD=3; pos=StrPos(posEnd,"Luna ");
                        if ( pos==0 || pos>aux ) { tD=1; pos=StrPos(posEnd,"planeta "); }
                        if ( pos==0 || pos>aux )
                        {
                                tD = 0;
                                // v. 0.77b
                                strcpy(gsp_d,"0:0:0");
                                strcpy(planeta_d,"-");
                        } else {
                                StrLCopy(planeta_d,planeta_o,44);
                                StrLCopy(gsp_d,gsp_o,8);

                                // v. < 0.77a >= 0.77c
                                posEnd = StrPos(pos,"<");
                                StrLCopy(planeta_o,pos,min(posEnd-pos,44) );

                                // Extraemos coordenadas DESTINO
                                pos = aux;
                                posEnd = StrPos(pos,"]");
                                StrLCopy(gsp_o,pos,min(posEnd-pos,8));
                        }
                }
        } else
        // Vision General: despliegue nuestro
        if ( strcmp(ordenes,"flight owndeploy")==0 )
        {
                aux=StrPos(pos,"[")+1;

                // Obtenemos el tipo de origen
                pos=StrPos(posEnd,"Escombros ");
                if ( pos==0 || pos>aux ) { tO=3; pos=StrPos(posEnd,"Luna "); }
                if ( pos==0 || pos>aux ) { tO=1; pos=StrPos(posEnd,"planeta ")+8; }

                // Extraemos el nombre del PLANETA ORIGEN (de partida)
                posEnd = StrPos(pos,"<");
                StrLCopy(planeta_o,pos,min(posEnd-pos,44) );

                // Extraemos coordenadas ORIGEN
                pos = aux;
                posEnd = StrPos(pos,"]");
                StrLCopy(gsp_o,pos,min(posEnd-pos,8));

                aux = StrPos(posEnd,"[")+1;

                // Extraemos el nombre del PLANETA DESTINO
                tD=3; pos=StrPos(posEnd,"Luna ");
                if ( pos==0 || pos>aux ) { tD=1; pos=StrPos(posEnd,"planeta "); }
                if ( pos==0 || pos>aux )
                {
                        tD = 0;
                        // v. 0.77b
                        strcpy(gsp_d,"0:0:0");
                        strcpy(planeta_d,"-");
                } else {
                        StrLCopy(planeta_d,planeta_o,44);
                        StrLCopy(gsp_d,gsp_o,8);

                        // v. < 0.77a >= 0.77c
                        posEnd = StrPos(pos,"<");
                        StrLCopy(planeta_o,pos,min(posEnd-pos,44) );
                        
                        // Extraemos coordenadas DESTINO
                        pos = aux;
                        posEnd = StrPos(pos,"]");
                        StrLCopy(gsp_o,pos,min(posEnd-pos,8));
                }

        } else
        // Vision General: Espionaje nuestro IDA
        if ( strcmp(ordenes,"flight ownespionage")==0 )
        {
                aux=StrPos(pos,"[")+1;

                // Obtenemos el tipo de origen
                pos=StrPos(posEnd,"Escombros ");
                if ( pos==0 || pos>aux ) { tO=3; pos=StrPos(posEnd,"Luna "); }
                if ( pos==0 || pos>aux ) { tO=1; pos=StrPos(posEnd,"planeta ")+8; }

                // Extraemos el nombre del PLANETA ORIGEN
                posEnd = StrPos(pos,"<");
                StrLCopy(planeta_o,pos,min(posEnd-pos,44) );

                // Extraemos coordenadas ORIGEN
                pos = aux;
                posEnd = StrPos(pos,"]");
                StrLCopy(gsp_o,pos,min(posEnd-pos,8));

                // Extraemos el nombre del PLANETA DESTINO
                pos = StrPos(posEnd,"posiciÃ³n"); //"posición ");   // v.0.77b
                if ( pos== 0 )                        // v. < 0.77a >= 0.77c
                {
                        pos=StrPos(posEnd,"Escombros ");
                        if ( pos==0 || pos>aux ) { tD=3; pos=StrPos(posEnd,"Luna "); }
                        if ( pos==0 || pos>aux ) { tD=1; pos=StrPos(posEnd,"planeta ")+8; }
                } else pos = pos + 9;
                posEnd = StrPos(pos,"<");
                StrLCopy(planeta_d,pos,min(posEnd-pos,44) );

                // Extraemos coordenadas DESTINO
                pos = StrPos(posEnd,"[")+1;
                posEnd = StrPos(pos,"]");
                StrLCopy(gsp_d,pos,min(posEnd-pos,8));
        } else
        // Vision General: Espionaje nuestro VUELTA
        if ( strcmp(ordenes,"return ownespionage")==0 )
        {
/*
<span class='return ownespionage'>Una de tus
<a href='#' onmouseover='return overlib("&lt;font color=white&gt;&lt;b&gt;Sonda de espionaje 4&lt;br&gt;&lt;/b&gt;&lt;/font&gt;");' onmouseout='return nd();' class='ownespionage'>flotas</a><a href='#' title='Sonda de espionaje 4'></a>
vuelve de el planeta DANAG <a href="index.php?page=galaxy&galaxy=2&system=334&position=9&session=c7148a3231f1" ownespionage>[2:334:9]</a> a el planeta 2500 arcturus <a href="index.php?page=galaxy&galaxy=2&system=334&position=6&session=c7148a3231f1" ownespionage>[2:334:6]</a>. Su misión era: <span class='class'>Espionaje</span></span>
*/
                aux = StrPos(posEnd,"[");
                pos = StrPos(posEnd,"vuelve ");   // v.0.77b
                if ( pos==0 || pos>aux )                        // v. < 0.77a >= 0.77c
                {
                        // Extraemos el nombre del PLANETA DE REGRESO
                        pos = StrPos(posEnd,"llega");
                        posEnd = StrPos(pos,"<");
                        StrLCopy(planeta_o,pos,min(posEnd-pos,44) );

                        // Extraemos coordenadas DESTINO
                        pos = StrPos(posEnd,"[")+1;
                        posEnd = StrPos(pos,"]");
                        StrLCopy(gsp_o,pos,min(posEnd-pos,8));

                        strcpy(gsp_d,"0:0:0");
                        strcpy(planeta_d,"-");
                } else {

                         aux=StrPos(pos,"[")+1;

                        // Obtenemos el tipo de origen
                        pos=StrPos(posEnd,"Escombros ");
                        if ( pos==0 || pos>aux ) { tO=3; pos=StrPos(posEnd,"Luna "); }
                        if ( pos==0 || pos>aux ) { tO=1; pos=StrPos(posEnd,"planeta ")+8; }

                        // Extraemos el nombre del PLANETA ORIGEN (de partida)
                        posEnd = StrPos(pos,"<");
                        StrLCopy(planeta_o,pos,min(posEnd-pos,44) );

                        // Extraemos coordenadas ORIGEN
                        pos = aux;
                        posEnd = StrPos(pos,"]");
                        StrLCopy(gsp_o,pos,min(posEnd-pos,8));

                        aux = StrPos(posEnd,"[")+1;

                        // Extraemos el nombre del PLANETA DESTINO
                        tD=3; pos=StrPos(posEnd,"Luna ");
                        if ( pos==0 || pos>aux ) { tD=1; pos=StrPos(posEnd,"planeta "); }
                        if ( pos==0 || pos>aux )
                        {
                                tD = 0;
                                // v. 0.77b
                                strcpy(gsp_d,"0:0:0");
                                strcpy(planeta_d,"-");
                        } else {
                                StrLCopy(planeta_d,planeta_o,44);
                                StrLCopy(gsp_d,gsp_o,8);

                                // v. < 0.77a >= 0.77c
                                posEnd = StrPos(pos,"<");
                                StrLCopy(planeta_o,pos,min(posEnd-pos,44) );

                                // Extraemos coordenadas DESTINO
                                pos = aux;
                                posEnd = StrPos(pos,"]");
                                StrLCopy(gsp_o,pos,min(posEnd-pos,8));
                        }
                }
        } else
        // Vision General: Ataque ¡¡¡ NOS ATACAN !!! en confederacion
        if ( strcmp(ordenes,"flight federation")==0 || strcmp(ordenes,"federation")==0 )
        {
                strcpy(ordenes, "flight attack");
                
                aux=StrPos(pos,"[")+1;

                // Obtenemos el tipo de origen
                tO=3; pos=StrPos(posEnd,"luna ");
                if ( pos==0 || pos>aux ) { tO=1; pos=StrPos(posEnd,"planeta "); if (pos!=0) pos+=8; }
                if ( pos==0 || pos>aux ) { tO=3; pos=StrPos(posEnd,"de la ")+6; }

                // Extraemos el nombre del PLANETA ORIGEN
                posEnd = StrPos(pos,"<");
                StrLCopy(planeta_o,pos,min(posEnd-pos,44) );

                // Extraemos coordenadas ORIGEN
                pos = aux;
                posEnd = StrPos(pos,"]");
                StrLCopy(gsp_o,pos,min(posEnd-pos,8));

                // Obtenemos el tipo de destino
                aux = StrPos(posEnd,"[")+1;
                tD=3; pos=StrPos(posEnd,"luna ");
                if ( pos==0 || pos>aux ) { tD=3; pos=StrPos(posEnd,"Luna "); }
                if ( pos==0 || pos>aux ) { tD=1; pos=StrPos(posEnd,"planeta ")+8; }

                // Extraemos el nombre del PLANETA DESTINO
                posEnd = StrPos(pos,"<");
                StrLCopy(planeta_d,pos,min(posEnd-pos,44) );

                // Extraemos coordenadas DESTINO
                pos = aux;
                posEnd = StrPos(pos,"]");
                StrLCopy(gsp_d,pos,min(posEnd-pos,8));

        } else
        // Vision General: Ataque ¡¡¡ NOS ATACAN !!!
        if ( strcmp(ordenes,"flight attack")==0 ||
             strcmp(ordenes,"flight ")==0 ||
             strcmp(ordenes,"attack")==0  ||
             ordenes==NULL               )
        {
                strcpy(ordenes, "flight attack");

                aux=StrPos(pos,"[")+1;

                // Obtenemos el tipo de origen
                pos=StrPos(posEnd,"Escombros ");
                if ( pos==0 || pos>aux ) { tO=3; pos=StrPos(posEnd,"luna "); }

                if ( pos==0 || pos>aux ) { tO=1; pos=StrPos(posEnd,"planeta "); if (pos!=0) pos+=8; }
                if ( pos==0 || pos>aux ) { tO=3; pos=StrPos(posEnd,"de la ")+6; }

                // Extraemos el nombre del PLANETA ORIGEN
                posEnd = StrPos(pos,"<");
                StrLCopy(planeta_o,pos,min(posEnd-pos,44) );

                // Extraemos coordenadas ORIGEN
                pos = aux;
                posEnd = StrPos(pos,"]");
                StrLCopy(gsp_o,pos,min(posEnd-pos,8));

                // Obtenemos el tipo de destino
                aux = StrPos(posEnd,"[")+1;
                tD=3; pos=StrPos(posEnd,"luna ");
                if ( pos==0 || pos>aux ) { tD=3; pos=StrPos(posEnd,"Luna "); }
                if ( pos==0 || pos>aux ) { tD=1; pos=StrPos(posEnd,"planeta ")+8; }

                // Extraemos el nombre del PLANETA DESTINO
                posEnd = StrPos(pos,"<");
                StrLCopy(planeta_d,pos,min(posEnd-pos,44) );

                // Extraemos coordenadas DESTINO
                pos = aux;
                posEnd = StrPos(pos,"]");
                StrLCopy(gsp_d,pos,min(posEnd-pos,8));
        } else
        if ( strcmp(ordenes,"flight espionage")==0 )
        // Espionaje enemigo ¡¡Atención pueden meter naves no deseadas!!
        {

/*
<tr class='flight'>
<th><div id='bxx1' title='1120'star='1214002911'></div></th>
<th colspan='3'><span class='flight espionage'>
Una <a href='#' onmouseover='return overlib("&lt;font color=white&gt;&lt;b&gt;Número de naves: 5 &lt;br&gt;Sonda de espionaje 5&lt;br&gt;&lt;/b&gt;&lt;/font&gt;");' onmouseout='return nd();' class='espionage'>flota</a><a href='#' title='Número de naves: 5 Sonda de espionaje 5'></a> enemiga de ulises21 <a href='#' onclick='showMessageMenu(189016)'><img src='http://uni14.ogame.com.es/evolution/img/m.gif' title='Escribir mensaje' alt='Escribir mensaje'></a>
de el planeta 81 <a href="javascript:showGalaxy(2,224,6)" espionage>
[2:224:6]</a> llega a la Luna <a href="javascript:showGalaxy(2,334,6)" espionage>[2:334:6]</a>. La misión es: Espionaje</span>

</th>
</tr>
------------
Una flota enemiga de ulises21 de el planeta 81 [2:224:6] llega a la Luna [2:334:6]. La misión es: Espionaje
-------------

*/
                aux=StrPos(pos,"[")+1;

                /************************************************/
                // Si es un ataque encubierto, en un espionaje...
                posEnd = StrPos(pos,"Nave de batalla");
                if ( posEnd!=0 && posEnd<aux ) strcpy(ordenes,"flight attack"); else
                {
                        posEnd = StrPos(pos,"Cazador ligero");
                        if ( posEnd!=0 && posEnd<aux ) strcpy(ordenes,"flight attack"); else
                        {
                                posEnd = StrPos(pos,"Nave peque");
                                if ( posEnd!=0 && posEnd<aux ) strcpy(ordenes,"flight attack"); else
                                {
                                        posEnd = StrPos(pos,"Crucero");
                                        if ( posEnd!=0 && posEnd<aux ) strcpy(ordenes,"flight attack"); else
                                        {
                                                posEnd = StrPos(pos,"Acorazado");
                                                if ( posEnd!=0 && posEnd<aux ) strcpy(ordenes,"flight attack"); else
                                                {
                                                        posEnd = aux;
                                                }
                                        }
                                }
                        }
                }
                /************************************************/
                posEnd = pos;

                // Obtenemos el tipo de origen

                tO=2; pos=StrPos(posEnd,"Escombros "); posOffset = 10; 
                if ( pos==0 || pos>aux ) { tO=3; pos=StrPos(posEnd,"luna"); posOffset=4; }
                if ( pos==0 || pos>aux ) { tO=3; pos=StrPos(posEnd,"Luna"); posOffset=4; }
                if ( pos==0 || pos>aux ) { tO=1; pos=StrPos(posEnd,"planeta "); posOffset=8; }
                pos = pos + posOffset;

                // Extraemos el nombre del PLANETA ORIGEN
                posEnd = StrPos(pos,"<");
                if ( posEnd==0 ) pos = posEnd;
                StrLCopy(planeta_o,pos,min(posEnd-pos,44) );


                // Extraemos coordenadas ORIGEN
                pos = aux;
                posEnd = StrPos(pos,"]");
                StrLCopy(gsp_o,pos,min(posEnd-pos,8));

                // Obtenemos el tipo de destino
                aux = StrPos(posEnd,"[")+1;

                tD=3; pos=StrPos(posEnd,"luna "); posOffset = 5;
                if ( pos==0 || pos>aux ) { tD=3; pos=StrPos(posEnd,"Luna "); posOffset = 5; }
                if ( pos==0 || pos>aux ) { tD=1; pos=StrPos(posEnd,"planeta "); posOffset = 8; }
                pos = pos + posOffset;

                // Extraemos el nombre del PLANETA DESTINO
                posEnd = StrPos(pos,"<");
                StrLCopy(planeta_d,pos,min(posEnd-pos,44) );

                // Extraemos coordenadas DESTINO
                pos = aux;
                posEnd = StrPos(pos,"]");
                StrLCopy(gsp_d,pos,min(posEnd-pos,8));
        } else
        if ( strcmp(ordenes,"flight owndestroy")==0 ) {
                // Detruir Luna
                aux=StrPos(pos,"[")+1;

                // Obtenemos el tipo de origen
                pos=StrPos(posEnd,"luna ");
                if ( pos==0 || pos>aux ) { tO=3; pos=StrPos(posEnd,"Luna "); }

                if ( pos==0 || pos>aux ) { tO=1; pos=StrPos(posEnd,"planeta "); if (pos!=0) pos+=8; }
                if ( pos==0 || pos>aux ) { tO=3; pos=StrPos(posEnd,"de la ")+6; }

                // Extraemos el nombre del PLANETA ORIGEN
                posEnd = StrPos(pos,"<");
                StrLCopy(planeta_o,pos,min(posEnd-pos,44) );

                // Extraemos coordenadas ORIGEN
                pos = aux;
                posEnd = StrPos(pos,"]");
                StrLCopy(gsp_o,pos,min(posEnd-pos,8));

                // Obtenemos el tipo de destino
                aux = StrPos(posEnd,"[")+1;
                tD=3; pos=StrPos(posEnd,"luna ");
                if ( pos==0 || pos>aux ) { tD=3; pos=StrPos(posEnd,"Luna "); }
                if ( pos==0 || pos>aux ) { tD=1; pos=StrPos(posEnd,"planeta ")+8; }

                // Extraemos el nombre del PLANETA DESTINO
                posEnd = StrPos(pos,"<");
                StrLCopy(planeta_d,pos,min(posEnd-pos,44) );

                // Extraemos coordenadas DESTINO
                pos = aux;
                posEnd = StrPos(pos,"]");
                StrLCopy(gsp_d,pos,min(posEnd-pos,8));
        } else
        if ( strcmp(ordenes,"return owndestroy")==0 ) {
                // Detruir Luna
                aux=StrPos(pos,"[")+1;

                // Obtenemos el tipo de origen
                tO=3; pos=StrPos(posEnd,"luna ");
                if ( pos==0 || pos>aux ) { tO=3; pos=StrPos(posEnd,"Luna "); }
                if ( pos==0 || pos>aux ) { tO=1; pos=StrPos(posEnd,"planeta "); if (pos!=0) pos+=8; }
                if ( pos==0 || pos>aux ) { tO=3; pos=StrPos(posEnd,"de la ")+6; }

                // Extraemos el nombre del PLANETA ORIGEN
                posEnd = StrPos(pos,"<") -1;
                StrLCopy(planeta_o,pos,min(posEnd-pos,44) );

                // Extraemos coordenadas ORIGEN
                pos = aux;
                posEnd = StrPos(pos,"]");
                StrLCopy(gsp_o,pos,min(posEnd-pos,8));

                // Obtenemos el tipo de destino
                aux = StrPos(posEnd,"[")+1;
                tD=3; pos=StrPos(posEnd,"luna ");
                if ( pos==0 || pos>aux ) { tD=3; pos=StrPos(posEnd,"Luna "); }
                if ( pos==0 || pos>aux ) { tD=1; pos=StrPos(posEnd,"planeta ")+8; }

                // Extraemos el nombre del PLANETA DESTINO
                posEnd = StrPos(pos,"<");
                StrLCopy(planeta_d,pos,min(posEnd-pos,44) );

                // Extraemos coordenadas DESTINO
                pos = aux;
                posEnd = StrPos(pos,"]");
                StrLCopy(gsp_d,pos,min(posEnd-pos,8));
        } else {


                ///////////////////////////////////////////////////////////////////////////
                ///////////////////////////////////////////////////////////////////////////
                ///////////////////////////////////////////////////////////////////////////

                // Extraemos las coordenadas para otro tipo de misiones...
                aux=StrPos(pos,"[")+1;

                // Obtenemos el tipo de origen
                tO=3; pos=StrPos(posEnd,"luna ");
                if ( pos==0 || pos>aux ) { tO=3; pos=StrPos(posEnd,"Luna "); }
                if ( pos==0 || pos>aux ) { tO=2; pos=StrPos(posEnd,"Escombros "); }
                if ( pos==0 || pos>aux ) { tO=1; pos=StrPos(posEnd,"planeta "); if (pos!=0) pos+=8; }
                if ( pos==0 || pos>aux ) { tO=3; pos=StrPos(posEnd,"de la ");  if (pos!=0) pos+=6; }
                if ( pos>0 ) {
                        // Extraemos el nombre del PLANETA ORIGEN
                        posEnd = StrPos(pos,"<") -1;
                        StrLCopy(planeta_o,pos,min(posEnd-pos,44) );
                }
                // Extraemos coordenadas ORIGEN
                if ( aux>0 ) {
                        pos = aux;
                        posEnd = StrPos(pos,"]");
                        if ( posEnd>0 ) StrLCopy(gsp_o,pos,min(posEnd-pos,8));
                }

                if ( posEnd>0 ) {
                        // Obtenemos el tipo de destino
                        aux = StrPos(posEnd,"[")+1;
                        tD=3; pos=StrPos(posEnd,"luna ");
                        if ( pos==0 || pos>aux ) { tD=3; pos=StrPos(posEnd,"Luna "); }
                        if ( pos==0 || pos>aux ) { tD=1; pos=StrPos(posEnd,"planeta "); if (pos!=0) pos+=8; }

                        if ( pos>0 ) {
                                // Extraemos el nombre del PLANETA DESTINO
                                posEnd = StrPos(pos,"<");
                                if ( posEnd>0 ) StrLCopy(planeta_d,pos,min(posEnd-pos,44) );
                        }
                }

                if ( aux>0 ) {
                        // Extraemos coordenadas DESTINO
                        pos = aux;
                        posEnd = StrPos(pos,"]");
                        if ( posEnd>0 ) StrLCopy(gsp_d,pos,min(posEnd-pos,8));
                }
                ///////////////////////////////////////////////////////////////////////////
                ///////////////////////////////////////////////////////////////////////////
                ///////////////////////////////////////////////////////////////////////////
                
        }



                                ///////////////////////////// ADD-FLIGHT-TO-LIST
                                /////////////////////////////////////////////////////////////////////////////////////////////////

                                        sscanf(gsp_o,"%d:%d:%d",&gO,&sO,&pO);
                                        sscanf(gsp_d,"%d:%d:%d",&gD,&sD,&pD);
                                        t=atol(tiempo);

        enc=false;
/*
        // Si es una flota que regresa al planeta origen...
        if ( strncmp(ordenes,"return",6)==0 )
        {
          // Vemos si aun no llego a su destino
          for (i = 0; i < computacionesOcupadas; i++)
          {
                EStruct = (PEventos) MyEvents->Items[i];
                if ( EStruct->stop == lstar ||
                        (EStruct->stop == 0 &&
                         EStruct->gD == gO && EStruct->sD == sO && EStruct->pD == pO && EStruct->tD == tO &&
                         EStruct->gO == gD && EStruct->sO == sD && EStruct->pO == pD && EStruct->tO == tD
                        )
                ) {
                   EStruct->vuelta = t;//atol(tiempo);
                   EStruct->stop = lstar;

                   enc=true;
                   break;
                }
          }
         }
*/


                                        if ( !enc )
                                        {
                                                if ( MyEvents->Count<=numEventos )
                                                {
                                                  EStruct = new TEventos;
                                                  MyEvents->Add(EStruct);
                                                }
                                                EStruct = (PEventos)MyEvents->Items[numEventos];
                                                EStruct->status = 0;
                                                EStruct->avisado = false;
                                                EStruct->mision='i';

                                                /* (e)spiar, (E)spiado, (a)tacar, (A)tacado, (r)ecolectar, (i)ndefinido      */
                                                if ( strncmp(ordenes,"return",6)==0 )
                                                {
                                                        if ( strcmp(ordenes+7,"ownattack")==0 )         EStruct->mision = 'a'; else
                                                        if ( strcmp(ordenes+7,"owndeploy")==0 )         EStruct->mision = 'd'; else
                                                        if ( strcmp(ordenes+7,"ownespionage")==0 )      EStruct->mision = 'e'; else
                                                        if ( strcmp(ordenes+7,"owntransport")==0 )      EStruct->mision = 't'; else
                                                        if ( strcmp(ordenes+7,"ownharvest")==0 )        EStruct->mision = 'r'; else
                                                        if ( strcmp(ordenes+7,"owndestroy")==0 )        EStruct->mision = 'D';

                                                        EStruct->ida = 0;
                                                        EStruct->vuelta = t;//atol(tiempo);

                                                        EStruct->gO = gD;
                                                        EStruct->sO = sD;
                                                        EStruct->pO = pD;
                                                        EStruct->tO = tD;
                                                        strcpy(EStruct->planeta_o,planeta_d);

                                                        EStruct->gD = gO;
                                                        EStruct->sD = sO;
                                                        EStruct->pD = pO;
                                                        EStruct->tD = tO;
                                                        strcpy(EStruct->planeta_d,planeta_o);

                                                        EStruct->start = 0;
                                                        EStruct->stop = lstar;
                                                } else
                                                if ( strncmp(ordenes,"flight ",7)==0 )
                                                {
                                                        if ( strcmp(ordenes+7,"owntransport")==0 )      EStruct->mision = 't'; else
                                                        if ( strcmp(ordenes+7,"owndeploy")==0 )         EStruct->mision = 'd'; else
                                                        if ( strcmp(ordenes+7,"transport")==0 )         EStruct->mision = 'T'; else
                                                        if ( strcmp(ordenes+7,"ownattack")==0 )         EStruct->mision = 'a'; else
                                                        if ( strcmp(ordenes+7,"ownespionage")==0 )      EStruct->mision = 'e'; else
                                                        if ( strcmp(ordenes+7,"espionage")==0 )         EStruct->mision = 'E'; else
                                                        if ( strcmp(ordenes+7,"ownharvest")==0 )        EStruct->mision = 'r'; else
                                                        if ( strcmp(ordenes+7,"owndestroy")==0 )        EStruct->mision = 'D'; else
/* COSIDERAR ATAQUE CUALQUIER ACCION DESCONOCIDA
                                                        if ( strcmp(ordenes+7,"attack")==0
                                                             || strcmp(ordenes,"flight ")==0
                                                             || strcmp(ordenes+7,"federation")==0
                                                           )
*/
                                                        {
                                                                                nosAtacan = true;
                                                                                EStruct->mision = 'A';
                                                                                if ( sndCHK_peligro->Checked )
                                                                                sndPlaySound("snd\\recibiendoAtaque.wav", SND_ASYNC | SND_FILENAME | SND_LOOP);
                                                                                //toFront=true; ShowMessage("Alerta: escuadron hostil detectado");
                                                                                AlertBox->Visible=true;
                                                        }

                                                        EStruct->ida = t;//atol(tiempo);
                                                        EStruct->vuelta = 0;

                                                        EStruct->gO = gO;
                                                        EStruct->sO = sO;
                                                        EStruct->pO = pO;
                                                        EStruct->tO = tO;
                                                        strcpy(EStruct->planeta_o,planeta_o);

                                                        EStruct->gD = gD;
                                                        EStruct->sD = sD;
                                                        EStruct->pD = pD;
                                                        EStruct->tD = tD;
                                                        strcpy(EStruct->planeta_d,planeta_d);

                                                        EStruct->start = lstar;
                                                        EStruct->stop = 0;

                                                        /*** CHAPU ****/
                                                        enc=false;
                                                        for (i=0;i<last_numEventos && i<40;i++)
                                                        {
                                                                if (status[i][0]==EStruct->start)
                                                                {
                                                                        EStruct->status=(int)(status[i][1]&0x0000FFFF);
                                                                        EStruct->avisado=(status[i][1]&0x00010000);
                                                                        enc=true;
                                                                        break;
                                                                }
                                                        }
                                                        /**************/
                                                } else
                                                if ( strncmp(ordenes, "holding",7)== 0 )
                                                {
                                                        if ( strcmp(ordenes+7,"owntransport")==0 )      EStruct->mision = 'x';

                                                        EStruct->ida = 0;
                                                        EStruct->vuelta = t;//atol(tiempo);

                                                        EStruct->gO = gD;
                                                        EStruct->sO = sD;
                                                        EStruct->pO = pD;
                                                        EStruct->tO = tD;
                                                        strcpy(EStruct->planeta_o,planeta_d);

                                                        EStruct->gD = gO;
                                                        EStruct->sD = sO;
                                                        EStruct->pD = pO;
                                                        EStruct->tD = tO;
                                                        strcpy(EStruct->planeta_d,planeta_o);

                                                        EStruct->start = 0;
                                                        EStruct->stop = lstar;
                                                }


                                                numEventos++;
                                        }
                                /////////////////////////////////////////////////////////////////////////////////////////////////
                                ///////////////////////////// END ADD-FLIGHT-TO-LIST


                               } // Fin flota en vuelo
                        } // END ** while( pos=StrPos(pos,"<tr class='") ) **



                        dgEventos->RowCount = numEventos+1;
                        if (numEventos>0) dgEventos->FixedRows=1;

                        // Marcamos para borrar todos los elementos en la lista de ataque...
                        PAtaques EAtaque;
                        int attack;

                        for(i=0;i<MyAttacks->Count;i++)
                                ((PAtaques)MyAttacks->Items[i])->borrar=true;

                        for (i = 0; i < numEventos; i++)
                        {
                                EStruct = (PEventos) MyEvents->Items[i];
                                if ( EStruct->mision=='A' )
                                {
                                        enc = false;
                                        for(attack=0;attack<MyAttacks->Count;attack++)
                                        {
                                                EAtaque =(PAtaques)MyAttacks->Items[attack];
                                                if ( EAtaque->start == EStruct->start )
                                                {
                                                   EAtaque->t = EStruct->ida;   // Actualizamos el tiempo que queda para el ataque.
                                                   EAtaque->borrar = false;
                                                   enc=true;
                                                   break;
                                                }
                                        }
                                        if ( !enc )
                                        {
                                          EAtaque = new TAtaques;
                                          EAtaque->t = EStruct->ida;
                                          EAtaque->start = EStruct->start;
                                          EAtaque->gO = EStruct->gO; EAtaque->sO = EStruct->sO; EAtaque->pO = EStruct->pO; EAtaque->tO = EStruct->tO;
                                          EAtaque->gD = EStruct->gD; EAtaque->sD = EStruct->sD; EAtaque->pD = EStruct->pD; EAtaque->tD = EStruct->tD;
                                          EAtaque->borrar = false;
                                          EAtaque->status = 0;                  // Aun no hemos manipulado este ataque
                                          EAtaque->tDelay = 0;
                                          MyAttacks->Add(EAtaque);
                                        }
                                }
                        }
                        // ********************************
                  }
                  // ######################
                  pos = StrPos( posEnd, "</html>" );

                  sprintf(buffer,"%s > Visión General [%d:%0.3d:%0.2d].%d [%ld/%ld]",AnsiString(Now()),((PPlanetas)MyPlanets->Items[idxPLANET])->g,((PPlanetas)MyPlanets->Items[idxPLANET])->s,((PPlanetas)MyPlanets->Items[idxPLANET])->p,((PPlanetas)MyPlanets->Items[idxPLANET])->t,MilliSecondsBetween(stop,start),MilliSecondsBetween(Time(),stop) );
                  if ( pos )
                  {
                          statusBar->SelAttributes->Color = clBlack;statusBar->Lines->Add(buffer);
                          if (sndCHK_network->Checked && !AlertBox->Visible) sndPlaySound(0,0);
                  } else {
                          statusBar->SelAttributes->Color = clRed;statusBar->Lines->Add(AnsiString(buffer)+" ¡¡INCOMPLETA!!" );
                          error = -1;
                  }

                  if ( CFG_verbose )
                  {
                        char buffer[255];
                        PAtaques EAtaque;
                        for (i = 0; i<MyAttacks->Count; i++)
                        {
                                EAtaque =(PAtaques)MyAttacks->Items[i];
                                sprintf(buffer,"> %0.4ld < [%d:%0.3d:%0.2d].%d -> [%d:%0.3d:%0.2d].%d (%d) %s",EAtaque->t,EAtaque->gO,EAtaque->sO,EAtaque->pO,EAtaque->tO,EAtaque->gD,EAtaque->sD,EAtaque->pD,EAtaque->tD,EAtaque->status,(EAtaque->borrar?"CANCELADO":""));
                                statusBar->SelAttributes->Color = clRed;statusBar->Lines->Add( buffer );
                        }
                  }

                  // Si no hay ataques en curso, y estaban todas las computaciones ocupadas
                  // revisar si se ha quedado alguna libre...
                  if ( computacionesOcupadas>=CFG_ocuparMaxComputaciones )
                                                          computacionesOcupadas = -1;
/*
                  if ( !nosAtacan && computacionesOcupadas>=CFG_ocuparMaxComputaciones )
                  {
                                Hangar NavesAparcadas[14];
                                flota_obtenerFlota(((PPlanetas)MyPlanets->Items[idxPLANET])->cp,&RecursosDisp,NavesAparcadas);
                  }
*/

                } else {
                  statusBar->SelAttributes->Color = clRed;statusBar->Lines->Add(AnsiString(Now())+AnsiString(" > ")+AnsiString("Error vision general (Sesion caducada)") );

/*
                  error = iniciarSesion();
                  // Deberiamos reintentar descargar los mensajes...
                  if ( error!=-1 )
                        _visionGeneral(-1);
*/
                }
          } else {
             statusBar->SelAttributes->Color = clRed;statusBar->Lines->Add(AnsiString(Now())+AnsiString(" > ")+AnsiString("Error vision general") );
          }


          delete out;
  }

  return error;
}
//---------------------------------------------------------------------------
char * __fastcall Tmain::obtenerListaPlanetas(char *html)
{
  char buffer[80];
  char *pos, *posEnd, *aux;

  PPlanetas EPlanetas;

  posEnd = pos = html;
  while( pos = StrPos( posEnd, "<option" ) )
  {

        EPlanetas = new TPlanetas;

        pos = StrPos( posEnd, "&cp=" )+4;
        posEnd = StrPos(pos,"&");
        StrLCopy(buffer,pos,min(posEnd-pos,12));
        EPlanetas->cp = atol(buffer);

        pos = StrPos(posEnd,">")+1;
        posEnd=StrPos(pos,"[");
        /* ver. 0.76 */
        aux=StrPos(pos,"<");
        posEnd = min(posEnd,aux);
        /***/
        StrLCopy(EPlanetas->planeta,pos,min(posEnd-pos,44)); // Deberia hacer TRIM sobre el planeta

        strRTrim(EPlanetas->planeta);
//        if ( strcmp(EPlanetas->planeta,"Luna")==0 )
        if ( StrPos(EPlanetas->planeta,"Luna")!=NULL )
                EPlanetas->t=3;
        else
                EPlanetas->t=1;

        pos=StrPos(pos,"[")+1;
        posEnd=StrPos(pos,"]");
        StrLCopy(buffer,pos,min(posEnd-pos,8) );
        sscanf(buffer,"%d:%d:%d",&EPlanetas->g,&EPlanetas->s,&EPlanetas->p);

        MyPlanets->Add(EPlanetas);
  }
  return posEnd;
}
//---------------------------------------------------------------------------
int __fastcall Tmain::descargarMensajes()
{
  int error;
  AnsiString request;
  // Descargamos la página de mensajes...
//        oG_host, oG_session, oG_SSID, oG_Cookie;

  error = 0;
  if ( oG_session=="" )
  {
     statusBar->SelAttributes->Color = clRed;statusBar->Lines->Add(AnsiString(Now())+AnsiString(" > ")+AnsiString("Session vacia") );
     currentState = csLOGIN;
     nextUpdateCLK = 0;
     error = -1;
  }

  if ( error!=-1 )
  {
//          request = "GET http://"+oG_host+"/game/index.php?page=messages&session="+oG_session+" HTTP/1.1\r\n";
          request = "GET /game/index.php?page=messages&session="+oG_session+" HTTP/1.1\r\n";
          request+= "Host: "+oG_host+"\r\n";
          request+= "User-Agent: "+oG_userAgent+"\r\n";
          request+= "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5\r\n";
          request+= "Accept-Language: es-es,es;q=0.8\r\n";
          request+= "Accept-Encoding: gzip,deflate\r\n";
          request+= "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\n";
          request+= "Keep-Alive: 300\r\n";
          request+= "Connection: keep-alive\r\n";
          if ( !oG_Cookie.IsEmpty() )
                  request+= "Cookie: "+oG_Cookie+"\r\n";
          request+= "\r\n";

          lastRequest = lastRequest_messages;
          TMemoryStream* out  = new TMemoryStream();
          error = HTTPdownloader->descargarHTML(oG_host.c_str(),request.c_str(),out);

          if ( error!=-1 )
          {
                error = checkError( out );
                if ( error!=-1 )
                {
                  // Parseamos el listado de mensajes...
                  out->Position = 0;

                  // ######################

                  // ######################

                  statusBar->SelAttributes->Color = clBlack;statusBar->Lines->Add(AnsiString(Now())+AnsiString(" > ")+AnsiString("Descarga de mensajes") );
                } else {
                  statusBar->SelAttributes->Color = clRed;statusBar->Lines->Add(AnsiString(Now())+AnsiString(" > ")+AnsiString("Error descargando mensaje (Sesion caducada)") );
                  currentState = csLOGIN;
                  nextUpdateCLK = 0;
                  error = -1;
                }
          } else {
             statusBar->SelAttributes->Color = clRed;statusBar->Lines->Add(AnsiString(Now())+AnsiString(" > ")+AnsiString("Error descargando mensaje") );
          }


          delete out;
  }

  return error;
}
//---------------------------------------------------------------------------
int __fastcall Tmain::checkError(TMemoryStream *html)
{
  int error=0;


  if ( StrPos((char *)(html->Memory)+1,"Esta cuenta esta suspendida") >= html->Memory ) { error=-1; currentState = csLOGIN; }
  if ( StrPos((char *)(html->Memory)+1,"Problema de base de datos") >= html->Memory )  { error=-1; currentState = csLOGIN; }
  if ( StrPos((char *)(html->Memory)+1,"action=\"/game/logout.php?")>0 )               { error=-1; currentState = csLOGIN; }
  if ( StrPos((char *)(html->Memory)+1,"Tu sesiÃ³n es inv") >0 )  { error=-1; currentState = csLOGIN; } // "Tu sesión es inv") >0 )  error=-1;


  if ( StrPos((char *)(html->Memory)+1,"Se presento un error") >0 )  { error=-1; currentState = csLOGIN; }

  if ( StrPos((char *)(html->Memory)+1,"Esta cuenta no existe o introdujiste una contra") >0 )  { error=-1; currentState = csRESETPASS; }

  return error;
}
//---------------------------------------------------------------------------


void __fastcall Tmain::ToolButton4Click(TObject *Sender)
{
  Close();
}
//---------------------------------------------------------------------------

void __fastcall Tmain::btTestClick(TObject *Sender)
{
 HINSTANCE HApp;

  // Cargar el SpeedSim
  HApp = ShellExecute(this,	                // handle to parent window
    NULL,		                        // pointer to string that specifies operation to perform
    "speedSIM\\speedSIM.exe",	       	// pointer to filename string
    NULL,		        // pointer to string that specifies executable-file parameters
    NULL,		                        // pointer to string that specifies default directory
    SW_SHOWNORMAL	 			                        // whether file is shown when opened
   );


/*
  TMemoryStream* out  = new TMemoryStream();
  HTTPdownloader->descargarHTML("www.infdj.com","GET / HTTP/1.1\r\nHost: infdj.com\r\nAccept-Encoding: gzip,deflate\r\n\r\n",out);

//  HTTPdownloader->descargarHTML("localhost","GET / HTTP/1.1\r\nHost: localhost\r\nAccept-Encoding: gzip,deflate\r\n\r\n",out);

  delete out;
*/

}
//---------------------------------------------------------------------------

void __fastcall Tmain::btDownloaderClick(TObject *Sender)
{
  HTTPdownloader->Show();
}
//---------------------------------------------------------------------------


void __fastcall Tmain::ToolButton2Click(TObject *Sender)
{
  // Guardamos las preferencias...
  TIniFile *ini;

  ini = new TIniFile(ExtractFileDir(Application->ExeName)+"\\salvaVidas.ini");
  ini->WriteBool("avisos","ataqueAutomatico",sndCHK_ataque->Checked);
  ini->WriteBool("avisos","sondeoAlEnemigo",sndCHK_sondeo->Checked);
  ini->WriteBool("avisos","atacanteDetectado",sndCHK_peligro->Checked);
  ini->WriteBool("avisos","erroresGenerales",sndCHK_error->Checked);
  ini->WriteBool("avisos","sinConexionRed",sndCHK_network->Checked);

  ini->WriteBool("avisos","sondeo5min",chkSondeo5min->Checked);
  ini->WriteBool("avisos","sondeo3min",chkSondeo2min->Checked);
  ini->WriteBool("avisos","aviso5min",chkAviso5min->Checked);
  ini->WriteBool("avisos","alarmaPersonal",MenuItem5->Checked);

  ini->WriteBool("colaAtaques","colaActiva",activarColaAtaques->Checked);  

  delete ini;

  nextUpdateCLK = 0;
}
//---------------------------------------------------------------------------

void __fastcall Tmain::dgEventosDrawCell(TObject *Sender, int ACol,
      int ARow, TRect &Rect, TGridDrawState State)
{
/*
          dgEventos->Canvas->Brush->Color = clBackground;
          dgEventos->Canvas->FillRect(Rect);
*/

  if ( ARow==0 )
  {
        switch( ACol )
        {
                case 0:
                  dgEventos->Canvas->TextOut(Rect.Left,Rect.Top,"Tiempo");
                  dgEventos->Canvas->TextOut(Rect.Left,Rect.Top + dgEventos->Canvas->Font->Size+4,"Ida / Vuelta");
                  break;
                case 1:
                  dgEventos->Canvas->TextOut(Rect.Left,Rect.Top,"[GSP]"   );
                  dgEventos->Canvas->TextOut(Rect.Left,Rect.Top + dgEventos->Canvas->Font->Size+4,"Planeta Origen");
                  break;
                case 2:
                  dgEventos->Canvas->TextOut(Rect.Left,Rect.Top,"[GSP]"   );
                  dgEventos->Canvas->TextOut(Rect.Left,Rect.Top + dgEventos->Canvas->Font->Size+4,"Planeta Destino");
                  break;
                case 3:
                  dgEventos->Canvas->TextOut(Rect.Left,Rect.Top + dgEventos->Canvas->Font->Size,"Ordenes" );
                  break;
        }
  } else {
    if ( ARow<=MyEvents->Count ) //numEventos
    {

        int tH,tM,tS;
        PEventos EStruct;
        EStruct = (PEventos)MyEvents->Items[ARow-1];

        // Fondo del GRID
        switch( EStruct->mision )
        {
                case 'D': dgEventos->Canvas->Brush->Color = 0x00C1E0FF; break;
                case 'S': dgEventos->Canvas->Brush->Color = 0x007DDBFF; break;
                case 'T': dgEventos->Canvas->Brush->Color = clSkyBlue; break;
                case 'A': dgEventos->Canvas->Brush->Color = 0x006262FF; break;
                case 'r': dgEventos->Canvas->Brush->Color = 0x007282B8; break; /* BGR */
                default:
                          dgEventos->Canvas->Brush->Color = clWhite;
        }



        switch( ACol )
        {
                case 0:
                  if ( EStruct->ida > 0 )
                  {
                          tH = EStruct->ida/3600; tM = EStruct->ida%3600;

                          dgEventos->Canvas->TextRect(TRect(Rect.Left,Rect.Top,Rect.Right,Rect.Top+dgEventos->Canvas->Font->Size+4),Rect.Left,Rect.Top,Format("%02.2d:%02.2d:%02.2d",ARRAYOFCONST((tH,(tM/60),(tM%60))) ));
                  }
                  if ( EStruct->vuelta > 0 )
                  {
                          tH = EStruct->vuelta/3600; tM = EStruct->vuelta%3600;
                          dgEventos->Canvas->TextRect(TRect(Rect.Left,Rect.Top+dgEventos->Canvas->Font->Size+4,Rect.Right,Rect.Bottom),Rect.Left,Rect.Top + dgEventos->Canvas->Font->Size+4,Format("%02.2d:%02.2d:%02.2d",ARRAYOFCONST((tH,(tM/60),(tM%60))) ));
                  }
                  break;
                case 1:
                  dgEventos->Canvas->TextRect(TRect(Rect.Left,Rect.Top,Rect.Right,Rect.Top+dgEventos->Canvas->Font->Size+4),Rect.Left,Rect.Top,"["+AnsiString(EStruct->gO)+":"+AnsiString(EStruct->sO)+":"+AnsiString(EStruct->pO)+"]."+AnsiString(EStruct->tO)   );
                  dgEventos->Canvas->TextRect(TRect(Rect.Left,Rect.Top+dgEventos->Canvas->Font->Size+4,Rect.Right,Rect.Bottom),Rect.Left,Rect.Top + dgEventos->Canvas->Font->Size+4,EStruct->planeta_o);
                  break;
                case 2:
                  dgEventos->Canvas->TextRect(TRect(Rect.Left,Rect.Top,Rect.Right,Rect.Top+dgEventos->Canvas->Font->Size+4),Rect.Left,Rect.Top,"["+AnsiString(EStruct->gD)+":"+AnsiString(EStruct->sD)+":"+AnsiString(EStruct->pD)+"]."+AnsiString(EStruct->tD)   );
                  dgEventos->Canvas->TextRect(TRect(Rect.Left,Rect.Top+dgEventos->Canvas->Font->Size+4,Rect.Right,Rect.Bottom),Rect.Left,Rect.Top + dgEventos->Canvas->Font->Size+4,EStruct->planeta_d);
                  break;
                case 3:
                  dgEventos->Canvas->TextRect(Rect,Rect.Left,Rect.Top + dgEventos->Canvas->Font->Size+4, AnsiString(EStruct->mision) + (EStruct->mision=='a'?(AnsiString(" - ")+AnsiString(EStruct->status)):AnsiString("")) );
                  break;
        }
        if (State.Contains(gdFocused))
               dgEventos->Canvas->DrawFocusRect(Rect);
    }
  }

}
//---------------------------------------------------------------------------
void __fastcall Tmain::FormDestroy(TObject *Sender)
{
  PEventos EStruct;
  // Clean up – must free memory for the items as well as the list
  for (int i = 0; i < MyEvents->Count; i++)
  {
    EStruct = (PEventos) MyEvents->Items[i];
    delete EStruct;
  }
  delete MyEvents;

  PPlanetas EPlanetas;
  // Clean up – must free memory for the items as well as the list
  for (int i = 0; i < MyPlanets->Count; i++)
  {
    EPlanetas = (PPlanetas) MyPlanets->Items[i];
    delete EPlanetas;
  }
  delete MyPlanets;

  PAtaques EAtaques;
  // Clean up – must free memory for the items as well as the list
  for (int i = 0; i < MyAttacks->Count; i++)
  {
    EAtaques = (PAtaques) MyAttacks->Items[i];
    delete EAtaques;
  }
  delete MyAttacks;

  PAtaqueOfensivo AtaqueOfensivo;
  // Clean up – must free memory for the items as well as the list
  for (int i = 0; i < AtaquesOfensivos->Count; i++)
  {
    AtaqueOfensivo = (PAtaqueOfensivo) AtaquesOfensivos->Items[i];
    delete AtaqueOfensivo;
  }
  delete AtaquesOfensivos;

}
//---------------------------------------------------------------------------


void __fastcall Tmain::sessionKeyPress(TObject *Sender, char &Key)
{
  if ( Key==VK_RETURN && session->Text.Length()==12 ) {
        oG_session    = session->Text;
        currentState = csREADY;
  }
}
//---------------------------------------------------------------------------

void  __fastcall Tmain::maxResources(TRecursos *RecursosDisp,Hangar *Naves,TRecursos *maxRecursos)
{
  long capacidadDeCarga;

  // Debemos maximizar la cantidad de recursos cargados, para llevarnos todo lo que podamos.
  capacidadDeCarga=0;
  maxRecursos->Metal=0;
  maxRecursos->Cristal=0;
  maxRecursos->Deuterio=0;

  for ( int h=0;h<14;h++ )
  {
    // Seleccionamos todas las naves del planeta (menos los satelites solares)
    if  ( Naves[h].id>0 && Naves[h].id!=212 )
        capacidadDeCarga+= (Naves[h].capacity * Naves[h].ship);
  }

  // Prioridad al DEUTERIO / CRISTAL / METAL
  maxRecursos->Deuterio = min( RecursosDisp->Deuterio, capacidadDeCarga );
  capacidadDeCarga -= maxRecursos->Deuterio;

  maxRecursos->Cristal = min( RecursosDisp->Cristal, capacidadDeCarga );
  capacidadDeCarga -= maxRecursos->Cristal;

  maxRecursos->Metal = min( RecursosDisp->Metal, capacidadDeCarga );
  capacidadDeCarga -= maxRecursos->Metal;
}
//---------------------------------------------------------------------------
int  __fastcall Tmain::numNaves(Hangar *Naves)
{
  int h,num;
  num=0;
  for ( h=0;h<14;h++ )
  {
    // Seleccionamos todas las naves del planeta (menos los satelites solares)
    if  ( Naves[h].id>0 && Naves[h].id!=212 )
        num += Naves[h].maxship;
  }

  return num;
}
//---------------------------------------------------------------------------
int __fastcall Tmain::cmpNaves(Hangar *A, Hangar *B)
{
  int hA, hB;
  int dev=0;
  for ( hA=0;hA<13 && dev>=0;hA++ )
  {
        if ( A[hA].id>0 && A[hA].id!=212 && A[hA].ship>0 )
        {
          for ( hB=0;hB<14;hB++ )
          {
                if ( B[hB].id==A[hA].id )
                {
                        if ( B[hB].ship > A[hA].ship )
                        {
                                dev = -1;
                                break;
                        }
                }
          }
        }
  }

  return dev;
}
//---------------------------------------------------------------------------
// OBTIENE el total de flota disponible en el planeta
int  __fastcall Tmain::flota_obtenerFlota(int idPlaneta,TRecursos *RecursosDisp,Hangar *NavesAparcadas)
{

/*****************************/
    TDateTime start = Time();
    TDateTime stop;
/*****************************/

    AnsiString request,timeStamp, v;
    int error = -1;

//	request ="GET http://"+oG_host+"/game/index.php?page=flotten1&session="+oG_session+"&cp="+idPlaneta+"&mode=Flotte&gid=&messageziel=&re=0 HTTP/1.1\r\n";
	request ="GET /game/index.php?page=flotten1&session="+oG_session+"&cp="+idPlaneta+"&mode=Flotte&gid=&messageziel=&re=0 HTTP/1.1\r\n";
	request+="Host: "+oG_host+"\r\n";
	request+="User-Agent: "+oG_userAgent+"\r\n";
	request+="Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5\r\n";
	request+="Accept-Language: es-es,es;q=0.8\r\n";
	request+="Accept-Encoding: gzip,deflate\r\n";
	request+="Accept-Charset: windows-1252,utf-8;q=0.7,*;q=0.7\r\n";
	request+="Keep-Alive: 300\r\n";
	request+="Connection: keep-alive\r\n";
	request+="Referer: http://"+oG_host+"/game/index.php?page=flotten1&session="+oG_session+"&mode=Flotte\r\n";
        if ( !oG_Cookie.IsEmpty() )
                request+= "Cookie: "+oG_Cookie+"\r\n";
	request+="\r\n";

        lastRequest = lastRequest_flotten1;
        TMemoryStream* out  = new TMemoryStream();
        error = HTTPdownloader->descargarHTML(oG_host.c_str(),request.c_str(),out);
/*****************************/
        stop=Time();
/*****************************/
        if ( error!=-1 )
        {
            error = checkError( out );
            if ( error!=-1 )
            {
                    if ( oG_Cookie.IsEmpty() )
                            oG_Cookie = obtenerOGCookie();

                    out->Position=0;
                    char buffer[255];
                    char *pos,*posEnd,*aux, *aux1;
                    pos = StrPos((char *)out->Memory,"EnergÃ­a"); // "Energía");
        	    if ( pos>0 )
                    {
                         aux = pos;

                         // Extraemos las computaciones ocupadas
                         pos = StrPos(pos,"Flotas ");

                         aux1 = StrPos(pos,"MisiÃ³n");//"Misión");
                         posEnd = StrPos(pos,"</table>"); // v.0.77b
                         if ( aux1>posEnd ) // v.0.77c
                          posEnd = StrPos(aux1,"</table>");

                         do {
                          aux1 = pos;
                          pos = StrPos(pos,"<tr")+4;
                         } while( pos>0 && pos<posEnd );

                         pos = StrPos(aux1,"<th>")+4;
                         posEnd = StrPos(pos,"<");
                         StrLCopy(buffer, pos, min( (posEnd-pos), 3) );
                         computacionesOcupadas = atoi(buffer);
                         //////////////////////////////////////////////////////

                         pos = aux;
                         pos = extraerRecursos(pos,RecursosDisp);

                         /*
                         pos = extraerYcombinarFlota(pos,Flotas);
                         */

                         pos = extraerNavesAparcadas(pos,NavesAparcadas);


                        /*****************************/
                                 statusBar->SelAttributes->Color = clGreen;statusBar->Lines->Add(AnsiString(Now())+AnsiString(" > Flota en hangar (1/4)")+" ["+AnsiString(MilliSecondsBetween(stop,start))+"]");
                        /*****************************/
                         error = 0;
                    } else {
                         statusBar->SelAttributes->Color = clRed;statusBar->Lines->Add(AnsiString(Now())+AnsiString(" > Flota en hangar: ParseR ERROR") );
                         //nextUpdate->Interval = 10000; // Reintenamos logarnos 10segundos
                         error = -1;
                    }
            } else {
                  statusBar->SelAttributes->Color = clRed;statusBar->Lines->Add(AnsiString(Now())+AnsiString(" > ")+AnsiString("Error vision general (Sesion caducada)") );
            }
        } else {
                 statusBar->SelAttributes->Color = clRed;statusBar->Lines->Add(AnsiString(Now())+AnsiString(" > Flota en hangar: CONNECT ERROR") );
                 //nextUpdate->Interval = 2000; // Reintenamos logarnos 10segundos
                 nextUpdateCLK = 0;
//                 nextUpdateTimer(0);
                 error = -1;
        }

  return error;
}


//---------------------------------------------------------------------------
// SELECCIONA la flota que va a utilisarse
int  __fastcall Tmain::flota_seleccionarFlota(Hangar *NavesAparcadas,TRecursos *RecursosDisp)
{
/*****************************/
    TDateTime start = Time();
    TDateTime stop;
/*****************************/

    AnsiString request,timeStamp, v;
    int error = -1;

//	request ="POST http://"+oG_host+"/game/index.php?page=flotten2&session="+oG_session+" HTTP/1.1\r\n";
	request ="POST /game/index.php?page=flotten2&session="+oG_session+" HTTP/1.1\r\n";
	request+="Host: "+oG_host+"\r\n";
	request+="User-Agent: "+oG_userAgent+"\r\n";
	request+="Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5\r\n";
	request+="Accept-Language: es-es,es;q=0.8\r\n";
	request+="Accept-Encoding: gzip,deflate\r\n";
	request+="Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\n";
	request+="Keep-Alive: 300\r\n";
	request+="Connection: keep-alive\r\n";
	request+="Referer: http://"+oG_host+"/game/index.php?page=flotten1&session="+oG_session+"&mode=Flotte\r\n";
        if ( !oG_Cookie.IsEmpty() )
                request+= "Cookie: "+oG_Cookie+"\r\n";
        request+="Content-Type: application/x-www-form-urlencoded\r\n";

	AnsiString params;
        for ( int h=0;h<14;h++ )
        {
          // Seleccionamos todas las naves del planeta (menos los satelites solares)
          if  ( NavesAparcadas[h].id>0 && NavesAparcadas[h].id!=212 )
          {
                if ( !params.IsEmpty() )
                  params+="&";
                  params+="maxship"+AnsiString(NavesAparcadas[h].id)+"="+AnsiString(NavesAparcadas[h].maxship);
                  params+="&consumption"+AnsiString(NavesAparcadas[h].id)+"="+AnsiString(NavesAparcadas[h].consumption);
                  params+="&speed"+AnsiString(NavesAparcadas[h].id)+"="+AnsiString(NavesAparcadas[h].speed);
                  params+="&capacity"+AnsiString(NavesAparcadas[h].id)+"="+AnsiString(NavesAparcadas[h].capacity);
                  params+="&ship"+AnsiString(NavesAparcadas[h].id)+"="+AnsiString(NavesAparcadas[h].ship);
          }
        }
	request+="Content-Length: "+AnsiString(params.Length())+"\r\n\r\n";
        request+=params;

        lastRequest = lastRequest_flotten2;
        TMemoryStream* out  = new TMemoryStream();
        error = HTTPdownloader->descargarHTML(oG_host.c_str(),request.c_str(),out);
/*****************************/
        stop=Time();
/*****************************/
        if ( error!=-1 )
        {
            char *pos;
            out->Position=0;
            pos = StrPos((char *)out->Memory,"EnergÃ­a");//"Energía");
	    if ( pos>0 )
            {
                 pos = extraerRecursos(pos,RecursosDisp);
                 statusBar->SelAttributes->Color = clGreen;statusBar->Lines->Add(AnsiString(Now())+AnsiString(" > Flota sel. naves (2/4)")+" ["+AnsiString(MilliSecondsBetween(stop,start))+"]");
                 error = 0;
            } else {
                 statusBar->SelAttributes->Color = clRed;statusBar->Lines->Add(AnsiString(Now())+AnsiString(" > Flota en hangar: ParseR ERROR") );
                 //nextUpdate->Interval = 2000; // Reintenamos logarnos 2segundos
                 error = -1;
            }
        } else {
                 statusBar->SelAttributes->Color = clRed;statusBar->Lines->Add(AnsiString(Now())+AnsiString(" > Flota en hangar: CONNECT ERROR") );
                 //nextUpdate->Interval = 2000; // Reintenamos logarnos 10segundos
//                 nextUpdateTimer(0);
                 nextUpdateCLK = 0;
                 error = -1;
        }

  return error;
}
//---------------------------------------------------------------------------
// FIJA EL OBJETIVO (tipo Planeta,luna,escombros) y la velocidad
int  __fastcall Tmain::flota_fijarObjetivo(int gO,int sO,int pO,int tipoO, TRecursos *RecursosDisp,Hangar *NavesAparcadas, int gD,int sD, int pD, int tipoD, int velocidad)
{
/*****************************/
    TDateTime start = Time();
    TDateTime stop;
/*****************************/

    AnsiString request,timeStamp, v;
    int error = -1;

//	request ="POST http://"+oG_host+"/game/index.php?page=flotten3&session="+oG_session+" HTTP/1.1\r\n";
	request ="POST /game/index.php?page=flotten3&session="+oG_session+" HTTP/1.1\r\n";
	request+="Host: "+oG_host+"\r\n";
	request+="User-Agent: "+oG_userAgent+"\r\n";
	request+="Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5\r\n";
	request+="Accept-Language: es-es,es;q=0.8\r\n";
	request+="Accept-Encoding: gzip,deflate\r\n";
	request+="Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\n";
	request+="Keep-Alive: 300\r\n";
	request+="Connection: keep-alive\r\n";
	request+="Referer: http://"+oG_host+"/game/index.php?page=flotten2&session="+oG_session+"&mode=Flotte\r\n";
        if ( !oG_Cookie.IsEmpty() )
                request+= "Cookie: "+oG_Cookie+"\r\n";
        request+="Content-Type: application/x-www-form-urlencoded\r\n";

	AnsiString params;
        params+="thisgalaxy"+AnsiString(gO)+"&thissystem="+AnsiString(sO)+"&thisplanet="+AnsiString(pO);
        params+="&thisplanettype="+AnsiString(tipoO)+"&speedfactor=1";
        params+="&thisresource1="+AnsiString(RecursosDisp->Metal)+"&thisresource2="+AnsiString(RecursosDisp->Cristal)+"&thisresource3="+AnsiString(RecursosDisp->Deuterio);
        for ( int h=0;h<14;h++ )
        {
          // Seleccionamos todas las naves del planeta (menos los satelites solares)
          if  ( NavesAparcadas[h].id>0 && NavesAparcadas[h].id!=212 )
          {
                  params+="&ship"+AnsiString(NavesAparcadas[h].id)+"="+AnsiString(NavesAparcadas[h].ship);
                  params+="&consumption"+AnsiString(NavesAparcadas[h].id)+"="+AnsiString(NavesAparcadas[h].consumption);
                  params+="&speed"+AnsiString(NavesAparcadas[h].id)+"="+AnsiString(NavesAparcadas[h].speed);
                  params+="&capacity"+AnsiString(NavesAparcadas[h].id)+"="+AnsiString(NavesAparcadas[h].capacity);
          }
        }
        params+="&galaxy"+AnsiString(gD)+"&system="+AnsiString(sD)+"&planet="+AnsiString(pD)+"&planettype="+AnsiString(tipoD)+"&speed="+AnsiString(velocidad);

	request+="Content-Length: "+AnsiString(params.Length())+"\r\n\r\n";
        request+=params;

        lastRequest = lastRequest_flotten3;
        TMemoryStream* out  = new TMemoryStream();
        error = HTTPdownloader->descargarHTML(oG_host.c_str(),request.c_str(),out);
/*****************************/
        stop=Time();
/*****************************/
        if ( error!=-1 )
        {
            out->Position=0;
            /***************************/
            /* La respuesta no nos interesa */
            /***************************/
                 statusBar->SelAttributes->Color = clGreen;statusBar->Lines->Add(AnsiString(Now())+AnsiString(" > Flota sel. destino (3/4)") );
        } else {
                 statusBar->SelAttributes->Color = clRed;statusBar->Lines->Add(AnsiString(Now())+AnsiString(" > Flota en hangar: CONNECT ERROR") );
                 //nextUpdate->Interval = 2000; // Reintenamos logarnos 10segundos
//                 nextUpdateTimer(0);
                 nextUpdateCLK = 0;
                 error = -1;
        }

  return error;
}
//---------------------------------------------------------------------------
// FIJA LA MISION y RECURSOS
int  __fastcall Tmain::flota_ejecutarMision(int gO,int sO,int pO,int tipoO, TRecursos *RecursosDisp,Hangar *NavesAparcadas, int gD,int sD, int pD, int tipoD, int velocidad, int mision, TRecursos *RecursosD,bool usarBUGS)
{
/*****************************/
    TDateTime start = Time();
    TDateTime stop;
/*****************************/

    AnsiString request,timeStamp, v;
    int error = -1;


//	request ="POST http://"+oG_host+"/game/index.php?page=flottenversand&session="+oG_session+" HTTP/1.1\r\n";
	request ="POST /game/index.php?page=flottenversand&session="+oG_session+" HTTP/1.1\r\n";
	request+="Host: "+oG_host+"\r\n";
	request+="User-Agent: "+oG_userAgent+"\r\n";
	request+="Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5\r\n";
	request+="Accept-Language: es-es,es;q=0.8\r\n";
	request+="Accept-Encoding: gzip,deflate\r\n";
	request+="Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\n";
	request+="Keep-Alive: 300\r\n";
	request+="Connection: keep-alive\r\n";
	request+="Referer: http://"+oG_host+"/game/index.php?page=flotten3&session="+oG_session+"\r\n";
        if ( !oG_Cookie.IsEmpty() )
                request+= "Cookie: "+oG_Cookie+"\r\n";
        request+="Content-Type: application/x-www-form-urlencoded\r\n";

	AnsiString params;
        params+="thisgalaxy"+AnsiString(gO)+"&thissystem="+AnsiString(sO)+"&thisplanet="+AnsiString(pO);
        params+="&thisplanettype="+AnsiString(tipoO)+"&speedfactor=1";
        params+="&thisresource1="+AnsiString(RecursosDisp->Metal)+"&thisresource2="+AnsiString(RecursosDisp->Cristal)+"&thisresource3="+AnsiString(RecursosDisp->Deuterio);
        params+="&galaxy="+AnsiString(gD)+"&system="+AnsiString(sD)+"&planet="+AnsiString(pD)+"&planettype="+AnsiString(tipoD);
        for ( int h=0;h<14;h++ )
        {
          // Seleccionamos todas las naves del planeta (menos los satelites solares)
          if  ( NavesAparcadas[h].id>0 && ( NavesAparcadas[h].id!=212 || usarBUGS) )
          {
                  params+="&ship"+AnsiString(NavesAparcadas[h].id)+"="+AnsiString(NavesAparcadas[h].ship);
                  params+="&consumption"+AnsiString(NavesAparcadas[h].id)+"="+AnsiString(NavesAparcadas[h].consumption);
                  params+="&speed"+AnsiString(NavesAparcadas[h].id)+"="+AnsiString(NavesAparcadas[h].speed);
                  params+="&capacity"+AnsiString(NavesAparcadas[h].id)+"="+AnsiString(NavesAparcadas[h].capacity);
          }
        }
        params+="&speed="+AnsiString(velocidad)+"&order="+AnsiString(mision);
        params+="&resource1="+AnsiString(RecursosD->Metal)+"&resource2="+AnsiString(RecursosD->Cristal)+"&resource3="+AnsiString(RecursosD->Deuterio);

	request+="Content-Length: "+AnsiString(params.Length())+"\r\n\r\n";
        request+=params;

        lastRequest = lastRequest_flottenversand;
        TMemoryStream* out  = new TMemoryStream();
        error = HTTPdownloader->descargarHTML(oG_host.c_str(),request.c_str(),out);
/*****************************/
        stop=Time();
/*****************************/
        if ( error!=-1 )
        {
//                La flota no ha podido ser enviada
//                La flota ha sido enviada
            char *pos;
            out->Position=0;
            pos = StrPos((char *)out->Memory,"La flota ha sido enviada");
            if ( pos>0 )
            {
                 error = 0;
                 statusBar->SelAttributes->Color = clGreen;statusBar->Lines->Add(AnsiString(Now())+AnsiString(" > Flota sel. mision (4/4)") );
            } else {
                 error = -1;
                 statusBar->SelAttributes->Color = clGreen;statusBar->Lines->Add(AnsiString(Now())+AnsiString(" > Flota sel. mision ERROR (4/4)") );
            }
        } else {
                 statusBar->SelAttributes->Color = clRed;statusBar->Lines->Add(AnsiString(Now())+AnsiString(" > Flota sel. mission: CONNECT ERROR") );
                 //nextUpdate->Interval = 2000; // Reintenamos logarnos 10segundos
//                 nextUpdateTimer(0);
                 nextUpdateCLK = 0;
                 error = -1;
        }

  return error;
}
//---------------------------------------------------------------------------
char * __fastcall Tmain::extraerNavesAparcadas(char *html,Hangar *NavesAparcadas)
{
  char buffer[255];
  char *pos,*posEnd;
  pos = html;

    int h;                 // Vaciamos "nuestro" hangar...
    for ( h=0;h<14;h++ )
           NavesAparcadas[h].id=-1;

    // Buscamos el punto de inicio
    pos = StrPos(pos,"elegir naves");
    if ( pos )
    {
        h=0;
        posEnd=pos;
        while( pos = StrPos(posEnd,"title=\"Velocidad:") )
        {
          if ( h>13 ) { statusBar->SelAttributes->Color = clPurple;statusBar->Lines->Add(AnsiString(Now())+AnsiString(" > ")+AnsiString("Extraer flota: El número de naves supera lo esperado." )); break; }

          // Extraemos los datos de la nave... [ Asumimos que siempre vienen como CONSUMO/VELOCIDAD/CAPACIDAD//NAVES ]
          pos = StrPos(pos,"name=\"") + 13; //  name="maxship
          posEnd = StrPos(pos,"\"");
          StrLCopy(buffer,pos,min(posEnd-pos,254));
          NavesAparcadas[h].id = atoi(buffer);
          /** VALUE **/
          pos = StrPos(pos,"value=\"") + 7; // value="
          posEnd = StrPos(pos,"\"");
          StrLCopy(buffer,pos,min(posEnd-pos,254));
          NavesAparcadas[h].maxship = atol(buffer);

/*
          pos = StrPos(pos,"name=\"") + 17; //  name="consumption
          posEnd = StrPos(pos,"\"");
          StrLCopy(buffer,pos,min(posEnd-pos,254));
          NavesAparcadas[h].id = atoi(buffer);
*/
          /** VALUE **/
          pos = StrPos(pos,"value=\"") + 7; // value="
          posEnd = StrPos(pos,"\"");
          StrLCopy(buffer,pos,min(posEnd-pos,254));
          NavesAparcadas[h].consumption = atol(buffer);

/*
          pos = StrPos(pos,"name=\"") + 11; //  name="speed
          posEnd = StrPos(pos,"\"");
          StrLCopy(buffer,pos,min(posEnd-pos,254));
          NavesAparcadas[h].id = atoi(buffer);
*/
          /** VALUE **/
          pos = StrPos(pos,"value=\"") + 7; // value="
          posEnd = StrPos(pos,"\"");
          StrLCopy(buffer,pos,min(posEnd-pos,254));
          NavesAparcadas[h].speed = atol(buffer);

/*
          pos = StrPos(pos,"name=\"") + 14; //  name="capacity
          posEnd = StrPos(pos,"\"");
          StrLCopy(buffer,pos,min(posEnd-pos,254));
          NavesAparcadas[h].id = atoi(buffer);
*/
          /** VALUE **/
          pos = StrPos(pos,"value=\"") + 7; // value="
          posEnd = StrPos(pos,"\"");
          StrLCopy(buffer,pos,min(posEnd-pos,254));
          NavesAparcadas[h].capacity = atol(buffer);

/*
          pos = StrPos(pos,"name=\"") + 11; //  name="ship
          posEnd = StrPos(pos,"\"");
          StrLCopy(buffer,pos,min(posEnd-pos,254));
          NavesAparcadas[h].id = atoi(buffer);
*/
          /** VALUE **/
/*
          pos = StrPos(pos,"value=\"") + 7; // value="
          posEnd = StrPos(pos,"\"");
          StrLCopy(buffer,pos,min(posEnd-pos,254));
          NavesAparcadas[h].ship = atol(buffer);
*/
          NavesAparcadas[h].ship = NavesAparcadas[h].maxship;


/*
   <tr height="20">
    <th><a title="Velocidad: 220000000">Sonda de espionaje</a></th>
           ^^^^^^^^^^^^^^^^^
    <th>56<input type="hidden" name="maxship210" value="56"/></th>

<!--    <th>220000000 -->
     <input type="hidden" name="consumption210" value="1"/>
     <input type="hidden" name="speed210" value="220000000" /></th>
     <input type="hidden" name="capacity210" value="5" /></th>
     <th><a href="javascript:maxShip('ship210');" >máx</a> </th>
     <th><input name="ship210" size="10" value="0" alt="Sonda de espionaje 56"/></th>
   </tr>
*/

          h++;
        }
  }

  return pos;
}
//---------------------------------------------------------------------------
char * __fastcall Tmain::extraerRecursos(char *html, TRecursos *RecursosDisp)
{
  char buffer[255];
  char *pos,*posEnd;
  pos = html;

                 // Metal / Cristal / Deuterio / EnergíaConsumida | EnergiaProducida
                 //****************************************************************************************
                 pos = StrPos( StrPos(pos,"<font")+5, ">")+1;
                 posEnd = StrPos(pos,"<");
                 StrLCopy(buffer,pos,min(posEnd-pos,15) );
                 RecursosDisp->Metal = toNumber(buffer);


                 pos = StrPos( StrPos(posEnd,"<font")+5, ">")+1;
                 posEnd = StrPos(pos,"<");
                 StrLCopy(buffer,pos,min(posEnd-pos,15) );
                 RecursosDisp->Cristal = toNumber(buffer);

                 pos = StrPos( StrPos(posEnd,"<font")+5, ">")+1;
                 posEnd = StrPos(pos,"<");
                 StrLCopy(buffer,pos,min(posEnd-pos,15) );
                 RecursosDisp->Deuterio = toNumber(buffer);

                 RecursosDisp->energiaConsumida = 0;
                 RecursosDisp->energiaProducida = 0;
                 //****************************************************************************************

  return posEnd;
}
//---------------------------------------------------------------------------

void __fastcall Tmain::ToolButton5Click(TObject *Sender)
{
  char zBuffer[255];

  if ( oG_location.IsEmpty() )
  {
          StrCopy(zBuffer,"http://");   StrCat(zBuffer,oG_host.c_str());  StrCat(zBuffer,"/game/index.php?page=overview&session=");
  } else {
          StrCopy(zBuffer,oG_location.c_str());
  }


  StrCat(zBuffer,oG_session.c_str());
  StrCat(zBuffer,"&stat_universo=");                                            StrCat(zBuffer,AnsiString(oG_Universo).c_str());
  StrCat(zBuffer,"&url=http://localhost/oGame");

//68b27494f258
  ShellExecute(Application->MainForm->Handle, 0, zBuffer, "","", SW_SHOWNOACTIVATE > 32);
}
//---------------------------------------------------------------------------
void __fastcall Tmain::regresarNaves(PAtaques EAtaque)
{
  if ( sndCHK_peligro->Checked )
     sndPlaySound("snd\\regresarNavesRecursos.wav", SND_ASYNC | SND_FILENAME );
     statusBar->SelAttributes->Color = clBlack;statusBar->Lines->Add(AnsiString(Now())+AnsiString(" > ")+AnsiString("Regresando naves ")+"["+EAtaque->gD+":"+EAtaque->sD+":"+EAtaque->pD+"]" );

}
//---------------------------------------------------------------------------
bool __fastcall Tmain::cambiarPlaneta(int g, int s, int p,int t)
{
 bool enc;
 int i,idxP;
 PPlanetas EPlanetas;

     enc = false;
     // Buscamos el ID del planeta que esta siendo atacado
     for(i=0;i<MyPlanets->Count;i++ )
     {
        EPlanetas = (PPlanetas)MyPlanets->Items[i];
        if ( EPlanetas->g==g && EPlanetas->s==s && EPlanetas->p==p && EPlanetas->t==t )
        {
          idxP=i;
          enc=true;
          break;
        }
     }

     if ( enc )
     {
        enc = ( _visionGeneral(idxP)!=-1 );
        if ( !enc )
        {
          statusBar->SelAttributes->Color = clRed;statusBar->Lines->Add(AnsiString(Now())+AnsiString(" > ")+AnsiString("Error cambiando al origen ")+"["+g+":"+s+":"+p+"]."+t );
        }
     } else {
        statusBar->SelAttributes->Color = clRed;statusBar->Lines->Add(AnsiString(Now())+AnsiString(" > ")+AnsiString("Planeta origen no encontrado ")+"["+g+":"+s+":"+p+"]."+t );
     }

  return enc;
}
//---------------------------------------------------------------------------
int __fastcall Tmain::sondearAtacante(PAtaques EAtaque)
{
 int status;

 if ( sndCHK_sondeo->Checked )
     sndPlaySound("snd\\sondearAtacante.wav", SND_ASYNC | SND_FILENAME );

 status = sondearPlaneta(EAtaque->gD,EAtaque->sD,EAtaque->pD,EAtaque->tD,EAtaque->gO,EAtaque->sO,EAtaque->pO,EAtaque->tO);

 return status;
}
//---------------------------------------------------------------------------
int __fastcall Tmain::sondearPlaneta(int gO,int sO, int pO,int tO,int gD,int sD, int pD,int tD)
{
 int status = -1;

 TDateTime start=Time();
 if ( cambiarPlaneta(gO,sO,pO,tO) )
 {
        // Cargar la galaxia...
        cargarGalaxia(gD,sD,pD);
        status = enviarSondaModoGalaxia(gD,sD,pD,tD);
        statusBar->SelAttributes->Color = 0x0075BAFF;statusBar->Lines->Add(AnsiString(Now())+AnsiString(" > ")+AnsiString("Sondeando planeta ")+"["+gD+":"+sD+":"+pD+"]."+tD+" ["+AnsiString(MilliSecondsBetween(Time(),start))+"]" );

        // Añadimos el evento a la cola de eventos...
        addEvent( gO,sO,pO,tO,"Espionaje",0,0,gD,sD,pD,tD,"lanzado...",0,0,'e' );
 }
 return status;
}
//---------------------------------------------------------------------------
int __fastcall Tmain::cargarGalaxia(int g,int s, int p)
{
  int error;
  AnsiString request,post;

  if ( (g<1 || g>9) || (s<1 || s>499) || (p<1 || p>15) )
  {
    statusBar->SelAttributes->Color = clRed;statusBar->Lines->Add(AnsiString(Now())+AnsiString(" > ")+AnsiString("Error Galaxia (Fuera de rango)") );
    return 0;
  }

  error = 0;
  if ( error!=-1 )
  {
          request = "GET /game/index.php?page=galaxy&galaxy="+AnsiString(g)+"&system="+AnsiString(s)+"&position="+AnsiString(p)+"&session="+oG_session+" HTTP/1.1\r\n";
          request+= "Host: "+oG_host+"\r\n";
          request+= "User-Agent: "+oG_userAgent+"\r\n";
          request+= "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5\r\n";
          request+= "Accept-Language: es-es,es;q=0.8\r\n";
          request+= "Accept-Encoding: gzip,deflate\r\n";
          request+= "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\n";
          request+= "Keep-Alive: 300\r\n";
          request+= "Connection: keep-alive\r\n";
          request+= "Referer: http://"+oG_host+"/game/index.php?page=flotten1&session="+oG_session+"&mode=Flotte\r\n";
          if ( !oG_Cookie.IsEmpty() )
                  request+= "Cookie: "+oG_Cookie+"\r\n";
          request+= "\r\n";

          lastRequest = lastRequest_galaxy;
          TMemoryStream* out  = new TMemoryStream();
          error = HTTPdownloader->descargarHTML(oG_host.c_str(),request.c_str(),out);

          if ( error!=-1 )
          {
                error = checkError( out );
                if ( error!=-1 )
                {
                  // Parseamos el listado de mensajes...
                  /*
                  out->Position = 0;
                  (char *)out->Memory;
                  */
                  statusBar->SelAttributes->Color = clGreen;statusBar->Lines->Add(AnsiString(Now())+AnsiString(" > ")+AnsiString("Cargar Galaxia [")+AnsiString(g)+AnsiString(":")+AnsiString(s)+AnsiString("]") );
                } else {
                  statusBar->SelAttributes->Color = clRed;statusBar->Lines->Add(AnsiString(Now())+AnsiString(" > ")+AnsiString("Error descargando mensaje (Sesion caducada)") );
                }
          } else {
             statusBar->SelAttributes->Color = clRed;statusBar->Lines->Add(AnsiString(Now())+AnsiString(" > ")+AnsiString("Error Galaxia") );
          }
          delete out;
  }

  return error;
}
//---------------------------------------------------------------------------
/**** SONDEO DE PLANETA DESDE EL MODO GALAXIA ***********/
int __fastcall Tmain::enviarSondaModoGalaxia(int g,int s, int p,int pt)
{
  int error;
  AnsiString request,post;
  // Descargamos la página de mensajes...
//        oG_host, oG_session, oG_SSID, oG_Cookie;

  if ( (g<1 || g>9) || (s<1 || s>499) || (p<1 || p>15) || (pt<1 || pt>2) )
  {
    statusBar->SelAttributes->Color = clRed;statusBar->Lines->Add(AnsiString(Now())+AnsiString(" > ")+AnsiString("Error sondeando planeta (Fuera de rango)") );
    return 0;
  }


  error = 0;
  if ( oG_session=="" )
  {
     statusBar->SelAttributes->Color = clRed;statusBar->Lines->Add(AnsiString(Now())+AnsiString(" > ")+AnsiString("Session vacia") );
     currentState = csLOGIN;
     nextUpdateCLK = 0;
  }

  if ( error!=-1 )
  {
  /*?session="+oG_session+"*/


//          request = "POST http://"+oG_host+"/game/index.php?ajax=1&page=flottenversand&session="+oG_session+" HTTP/1.1\r\n";
          request = "POST /game/index.php?ajax=1&page=flottenversand&session="+oG_session+" HTTP/1.1\r\n";
          request+= "Host: "+oG_host+"\r\n";
          request+= "User-Agent: "+oG_userAgent+"\r\n";
          request+= "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5\r\n";
          request+= "Accept-Language: es-es,es;q=0.8\r\n";
          request+= "Accept-Encoding: gzip,deflate\r\n";
          request+= "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\n";
          request+= "Keep-Alive: 300\r\n";
          request+= "Connection: keep-alive\r\n";
          request+= "Content-Type: application/x-www-form-urlencoded\r\n";
          request+= "Referer: http://"+oG_host+"/game/index.php?page=galaxy&no_header=1&session="+oG_session+"\r\n";
//          request+= "Referer: http://"+oG_host+"/game/index.php?page=galaxy&session="+oG_session+"&no_header=1\r\n";
          post = "session="+oG_session+"&order=6&galaxy="+g+"&system="+s+"&planet="+p+"&planettype="+pt+"&shipcount=2&speed=10&reply=short&rndval="+AnsiString(MilliSecondsBetween(TDateTime::CurrentDateTime(),EncodeDateTime(1970,1,1,0,0,0,0)));
          request+= "Content-Length: "+AnsiString(post.Length())+"\r\n";
          if ( !oG_Cookie.IsEmpty() )
                  request+= "Cookie: "+oG_Cookie+"\r\n";
          request+= "Pragma: no-cache\r\n";
          request+= "Cache-Control: no-cache\r\n";
          request+= "\r\n";
          request+= post;

          lastRequest = lastRequest_galaxyProbe;
          TMemoryStream* out  = new TMemoryStream();
          error = HTTPdownloader->descargarHTML(oG_host.c_str(),request.c_str(),out);

          if ( error!=-1 )
          {
                error = checkError( out );
                if ( error!=-1 )
                {
                  // Parseamos el listado de mensajes...
                  out->Position = 0;

                  // ######################
                  char buffer[255];
                  strncpy(buffer,(char *)out->Memory,3);
 /*
 *
 *  600   OK
 *  601   no planet exists there
 *  602   no moon exists there
 *  603   player is in noob protection
 *  604   player is too strong
 *  605   player is in u-mode
 *  610   not enough espionage probes, sending x (parameter is the second return value)
 *  611   no espionage probes, nothing send
 *  612   no fleet slots free, nothing send
 *  613   not enough deuterium to send a probe
 *
 */

                  error = atoi(buffer);
                  // ######################
                  statusBar->SelAttributes->Color = clGreen;statusBar->Lines->Add(AnsiString(Now())+AnsiString(" > ")+AnsiString("Sondeo de planeta [")+AnsiString(g)+AnsiString(":")+AnsiString(s)+AnsiString(":")+AnsiString(p)+AnsiString("].")+AnsiString(pt)+AnsiString(" ¡")+AnsiString(error)+AnsiString("!") );
                } else {
                  statusBar->SelAttributes->Color = clRed;statusBar->Lines->Add(AnsiString(Now())+AnsiString(" > ")+AnsiString("Error descargando mensaje (Sesion caducada)") );
/*
                  error = iniciarSesion();
                  // Deberiamos reintentar descargar los mensajes...
                  if ( error!=-1 )
                        sondearPlaneta(g,s,p,1);
*/
                }
          } else {
             statusBar->SelAttributes->Color = clRed;statusBar->Lines->Add(AnsiString(Now())+AnsiString(" > ")+AnsiString("Error sondeando planeta") );
          }


          delete out;
  }

  return error;
}
//---------------------------------------------------------------------------
int __fastcall Tmain::retirarNavesRecursos(PAtaques EAtaque, bool irAEscombros, int velocidadRec )
{
  int error=0;

  TRecursos maxRecursos;
  Hangar NavesAparcadas[14];
  int velocidad=10; // 10%

  int mision=4; // 3 - transportar // 4 - desplegar   // 8 - recolectar
  int gO,sO,pO,tipoO;
  int gD,sD,pD,tipoD;
  tipoD=1;// 1 - planeta  // 2 - Escombros // 3 - Luna

  int idPlaneta;

  // ######################################
  gO=EAtaque->gD; sO=EAtaque->sD; pO=EAtaque->pD; tipoO=EAtaque->tD;
  gD=EAtaque->gD; sD=EAtaque->sD; pD=EAtaque->pD; tipoD=2;  mision=8;
  velocidad=1;
  // ######################################

  int i;bool enc=false;
  for ( i=0; i<MyPlanets->Count && !enc; i++ )
        if ( ((PPlanetas)MyPlanets->Items[i])->g==gO &&
             ((PPlanetas)MyPlanets->Items[i])->s==sO &&
             ((PPlanetas)MyPlanets->Items[i])->p==pO &&
                ((PPlanetas)MyPlanets->Items[i])->t==tipoO ) { enc=true; break; }
  if ( enc )
  {
          idPlaneta=((PPlanetas)MyPlanets->Items[i])->cp;

          if ( irAEscombros )
          {
                  gD=EAtaque->gD; sD=EAtaque->sD; pD=EAtaque->pD; tipoD=2; mision=8; velocidad=velocidadRec;
          }else {
                  buscarRefugio(idPlaneta,&gD,&sD,&pD,&tipoD);
                  if ( tipoD==2 )
                  {
                        mision = 8;
                        velocidad=9;
                  } else mision=4;
          }

        error = flota_obtenerFlota(idPlaneta,&RecursosDisp,NavesAparcadas);
        if ( error!=-1 )
        {
          if ( numNaves(NavesAparcadas)<=0 )
          {
            statusBar->SelAttributes->Color = 0x0075BAFF;statusBar->Lines->Add(AnsiString(Now())+AnsiString(" > ")+AnsiString("¡No hay naves! ")+"["+EAtaque->gD+":"+EAtaque->sD+":"+EAtaque->pD+"]" );
            EAtaque->status = ATAQUE_SACAR_NAVES_EN_ULTIMO_SEGUNDO;
            error = -1;
          } else {

            error = flota_seleccionarFlota(NavesAparcadas,&RecursosDisp);
            if ( error!=-1 )
            {
              error = flota_fijarObjetivo(gO,sO,pO,tipoO,&RecursosDisp,NavesAparcadas,gD,sD,pD,tipoD,velocidad);
              if ( error!=-1 )
              {
                maxResources(&RecursosDisp,NavesAparcadas,&maxRecursos);
                error = flota_ejecutarMision(gO,sO,pO,tipoO,&RecursosDisp,NavesAparcadas,gD,sD,pD,tipoD,velocidad,mision,&maxRecursos,false);

                if ( error!=-1 )
                {
                        if ( sndCHK_peligro->Checked )
                        sndPlaySound("snd\\retirarNavesRecursos.wav", SND_ASYNC | SND_FILENAME );
                        statusBar->SelAttributes->Color = 0x0075BAFF;statusBar->Lines->Add(AnsiString(Now())+AnsiString(" > ")+AnsiString("Retirando naves ")+"["+EAtaque->gD+":"+EAtaque->sD+":"+EAtaque->pD+"]" );
                } // ejecutarMision y seleccion de recursos
              } // fijarObjetivo
            } // seleccionarFlota

          } // sin naves en el hangar

        } // obtenerFlota

          if ( error==-1 )
          {
            statusBar->SelAttributes->Color = clRed;statusBar->Lines->Add(AnsiString(Now())+AnsiString(" > ")+AnsiString("Retirando naves ")+"["+EAtaque->gD+":"+EAtaque->sD+":"+EAtaque->pD+"]."+EAtaque->tD );
            if ( sndCHK_error->Checked )
            sndPlaySound("snd\\retirarNavesRecursos_error.wav", SND_ASYNC | SND_FILENAME );
          }

  } else {
        statusBar->SelAttributes->Color = clRed;statusBar->Lines->Add(AnsiString(Now())+AnsiString(" > ")+AnsiString("Flota: ERROR de ORIGEN ")+"["+EAtaque->gD+":"+EAtaque->sD+":"+EAtaque->pD+"]."+EAtaque->tD );
        error=-1;
  }

  return error;
}

//---------------------------------------------------------------------------
void __fastcall Tmain::cron(TObject *Sender)
{
  nextUpdateCLK--;

  if ( currentState==csREADY ) runREADY();

  if ( nextUpdateCLK<=0 ) {
        switch( currentState ) {
                case csREADPASS:
                        if ( recuperarPassword() ) {
                          currentState = csLOGIN;
                        } else
                          nextUpdateCLK = 5;
                        break;
                case csRESETPASS:
                        cambioPassword();
                        if( sndCHK_network->Checked ) sndPlaySound("snd\\errorConexion.wav", SND_ASYNC | SND_FILENAME | SND_LOOP);
                        break;
                case csLOGIN:
                        iniciarSesion();
                        break;
                case csREADY:
                        int error = visionGeneral();
                        if ( error==-1 ) {
                           errorCONEXION++;
                           if ( errorCONEXION>3 ) {
                                nextUpdateCLK = 5;
                                if( sndCHK_network->Checked ) sndPlaySound("snd\\errorConexion.wav", SND_ASYNC | SND_FILENAME | SND_LOOP);
                           } else {
                                nextUpdateCLK = 1;
                           }
                        } else {
                           errorCONEXION = 0;
                           currentState = csREADY;
                           nextUpdateCLK=20*60 + (rand()%100)*6;
                        }
                        break;
          }
  }
  nextUpdateCLOCK->Caption = AnsiString(nextUpdateCLK/60)+" minutos "+AnsiString(nextUpdateCLK%60)+" seg.";
  dgEventos->Refresh();
}

void __fastcall Tmain::runREADY() {

   PEventos EStruct;
   PAtaques EAtaque;

   espacioEntreAtaques--;


   int dev,aux;
   unsigned long i, t;
   t=9999999;
/*
   // Borramos los ataques marcados para tal...
   for(i=0;i<MyAttacks->Count;i++)
   {
     try { EAtaque = (PAtaques)MyAttacks->Items[i]; } catch(...) { break; }
     if ( EAtaque->borrar==true ) {
        if ( EAtaque->status==ATAQUE_NAVES_VOLANDO ) {
                     regresarNaves(EAtaque);
        }
        MyAttacks->Delete(i);
        delete EAtaque;
     }
   }
   MyAttacks->Pack();
*/

   // Atendemos al resto de ataques...
   bool pack;
   pack=false;
   for(i=0;i<MyAttacks->Count;i++)
   {
     try { EAtaque = (PAtaques)MyAttacks->Items[i]; } catch(...) { break; } // Si no podemos llegar a este ataque, abortamos el bucle
     EAtaque->t--;
     EAtaque->tDelay++;

     if ( EAtaque->borrar==true )
     {
        pack=true;
        // Han cancelado el ataque, pero nuestras naves ya habían sido desplegadas...
        if ( EAtaque->status==ATAQUE_NAVES_VOLANDO )
                     regresarNaves(EAtaque);

         MyAttacks->Delete(i);
         delete EAtaque;
     } else {
        t = min( t, EAtaque->t );

        // Si estamos dentro del tiempo crítico, no intentar sondearlo, escapar directamente
        if ( EAtaque->t <= CFG_tiempoCritico && EAtaque->status==ATAQUE_SONDEAR_ATACANTE ) EAtaque->status=ATAQUE_BUSCAR_RUTA_ESCAPE;

        switch( EAtaque->status )
        {
          case ATAQUE_SONDEAR_ATACANTE: // Sondear al enemigo
                // Esperamos 5 Minutos antes de sondear a este atacante...
                if ( EAtaque->tDelay >= 300 )
                {
                        dev = 0;
                        // Evitar sondeos dobles
                        // Si ya hemos sondeado al planeta atacante (y hace menos de 5 minutos)
                        {
                          PAtaques a;
                          for (int s=0;s<MyAttacks->Count;s++)
                          {
                                try { a=(PAtaques)MyAttacks->Items[s]; } catch(...) { break; }
                                if ( a->status == ATAQUE_ESCAPAR_A_ESCOMBROS
                                       && a->gO==EAtaque->gO && a->sO==EAtaque->sO && a->pO==EAtaque->pO )
                                {
                                        dev = 600;
                                        break;
                                }

                          }
                        }

                        EAtaque->status=ATAQUE_ESCAPAR_A_ESCOMBROS;
                        EAtaque->tDelay = 0;

                        if ( dev == 0)
                        {
                                dev = sondearAtacante(EAtaque);

                                if ( CFG_ejecutarProgama )  ejecutarProgramaAntiSondeo(EAtaque);

                                switch(dev)
                                {
                                  case 600:
                                        break; // TODO OK
                                  default:
                                        break;
                                }
                        }
                }
                break;
          case ATAQUE_ESCAPAR_A_ESCOMBROS: // Retirar el ataque cuando llegue al tiempo crítico PARA ESCAPE A ESCOMBROS
                if ( EAtaque->t <= 618 )        // 10 minutos y 18 segundos
                {
                        if ( EAtaque->t<=375) aux = 10;     // 6 min y 15 seg
                        else {  if ( EAtaque->t<=415) aux = 9;     // 6 min y 55 seg
                          else {  if ( EAtaque->t<=466) aux = 8;     // 7 min y 46 seg
                            else {  if ( EAtaque->t<=531) aux = 7;     // 8 min y 51 seg
                              else {  if ( EAtaque->t<=618 ) aux = 6;    // 10 min y 18 seg
                              }
                            }
                          }
                        }

                        dev = retirarNavesRecursos(EAtaque,true,aux);  // Ir a escombros al 60%
                        if ( dev != -1 )
                        {
                                addEvent( EAtaque->gO,EAtaque->sO,EAtaque->pO,EAtaque->tO,"ATAQUE",0,0,EAtaque->gD,EAtaque->sD,EAtaque->pD,EAtaque->tD,"DETECTADO",0,0,'A' );

//                                computacionesOcupadas++;
                                EAtaque->status=ATAQUE_NAVES_VOLANDO;
                        } else
                                EAtaque->status=ATAQUE_BUSCAR_RUTA_ESCAPE;      // El siguiente intento sera escapar segun reglas definidas por el usuario

                        EAtaque->tDelay = 0;
                }
                break;
          case ATAQUE_BUSCAR_RUTA_ESCAPE: // Retirar el ataque cuando llegue al tiempo crítico
                if ( EAtaque->t <= CFG_tiempoCritico )
                {
                        dev = retirarNavesRecursos(EAtaque,false,0);
                        if ( dev != -1 )
                        {
                                addEvent( EAtaque->gO,EAtaque->sO,EAtaque->pO,EAtaque->tO,"ATAQUE",0,0,EAtaque->gD,EAtaque->sD,EAtaque->pD,EAtaque->tD,"DETECTADO",0,0,'A' );
//                                computacionesOcupadas++;
                                EAtaque->status=ATAQUE_NAVES_VOLANDO;
                        } else
                                EAtaque->status = ATAQUE_SACAR_NAVES_EN_ULTIMO_SEGUNDO;

                        EAtaque->tDelay = 0;
                }
                break;
          case ATAQUE_SACAR_NAVES_EN_ULTIMO_SEGUNDO:
                if ( EAtaque->t <= 6 )
                {
                        dev = retirarNavesRecursos(EAtaque,false,0);
                        if ( dev != -1 )
                        {
                                addEvent( EAtaque->gO,EAtaque->sO,EAtaque->pO,EAtaque->tO,"ATAQUE",0,0,EAtaque->gD,EAtaque->sD,EAtaque->pD,EAtaque->tD,"DETECTADO",0,0,'A' );
//                                computacionesOcupadas++;
                                EAtaque->status=ATAQUE_NAVES_VOLANDO;
                                EAtaque->tDelay = 0;
                        }
                }
                break;
        }
     }
   }
   if ( pack ) MyAttacks->Pack();

   // Control de la flota en vuelo (VISION GENERAL)
   for(i=0;i<numEventos;i++)
   {
     EStruct = (PEventos) MyEvents->Items[i];
     EStruct->ida--;
     EStruct->vuelta--;

     if ( /* t==9999999 && */ EStruct->ida<=-30 && EStruct->vuelta<=-30 ) nextUpdateCLK=0;
   }
   computaciones->Caption = (computacionesOcupadas<0?AnsiString("n/a"):AnsiString(computacionesOcupadas))+" / "+AnsiString(CFG_ocuparMaxComputaciones)+" Ev.("+AnsiString(numEventos)+")";


   // Hay un ataque en curso, asi que programamos la proxima actualizacion
   // para dentro de la mitad de tiempo que quede para llegar el ataque
   if ( t!=9999999 )
   {
       t = (t/2); if ( t<=0 ) t=10; // Grantizamos poder conectar incluso en el último segundo...

       if ( t>0 && nextUpdateCLK>t )
                        nextUpdateCLK = t;
   } else {
      // Si esta activada la opción de sondeo automático...
      if ( ( chkSondeo5min->Checked || chkSondeo2min->Checked || chkAviso5min->Checked )
//             computacionesOcupadas<=CFG_ocuparMaxComputaciones
       )
      {
        PEventos EStruct;
        for ( i=0;i<MyEvents->Count;i++ )
        {
          EStruct = (PEventos)MyEvents->Items[i];
          if (  EStruct->mision=='a' &&                         // Ataque nuestro
                EStruct->ida>0                                  // Que aun no ha llegado
             )
          {
            // Sondeo de los 5 minutos 25 segundos ...
            if ( EStruct->ida>46 && EStruct->ida<325 )
            {
                // Aviso 25 segundos despues de lanzar el sondeo...
                if ( chkAviso5min->Checked && EStruct->avisado == false && EStruct->ida<300 )   { EStruct->avisado = true;
                                                                              sndPlaySound("snd\\alarmaAtaquePropio.wav", SND_ASYNC | SND_FILENAME | SND_LOOP);
                                                                              InfoBox->Visible=true;
                                                                            }

                // Sondeo de los 2 minutos...
                if ( EStruct->ida>55 && computacionesOcupadas<=CFG_ocuparMaxComputaciones )
                {
                  if ( EStruct->status!=12 && chkSondeo2min->Checked && EStruct->ida<120 ) {  EStruct->status=12; sondearPlaneta(EStruct->gO,EStruct->sO,EStruct->pO,EStruct->tO,EStruct->gD,EStruct->sD,EStruct->pD,EStruct->tD); break; }

                  if ( EStruct->status==00 && chkSondeo5min->Checked )        {  EStruct->status=15; sondearPlaneta(EStruct->gO,EStruct->sO,EStruct->pO,EStruct->tO,EStruct->gD,EStruct->sD,EStruct->pD,EStruct->tD); break; }
                }
            }
          }
        }
      }

      // Si no estamos siendo atacados,
      // - hay una computación libre
      // - y tenemos una lista de ataques (con ataques pendientes)
      // - y hay un margen entre el útimo ataque y este prudencial...
      // ...lanzamos el siguiente ataque.

//      if (      activarColaAtaques->Checked &&
        if (
                computacionesOcupadas<CFG_ocuparMaxComputaciones &&
                espacioEntreAtaques <= 0
         )
      {
        // Las colas de sondeo tienen prioridad frente a las de ataque...
        if ( activarSondeo->Checked )
        {
                if ( sondeoMasivo->Lines->Count == 0 ) activarSondeo->Checked = false;
                else {
                        int gD,sD,pD,tD;
                        tD = 1;

                        // Computaciones ocupadas==-1 // Justo despues de una vision general, cuando todas las computaciones ocupadas
                        if ( computacionesOcupadas<0 )
                        {
                                Hangar NavesAparcadas[14];
                                flota_obtenerFlota(((PPlanetas)MyPlanets->Items[ (int)planetasOrigenSondeo->Items->Objects[planetasOrigenSondeo->ItemIndex] ])->cp,&RecursosDisp,NavesAparcadas);
                        }

                        if ( computacionesOcupadas<CFG_ocuparMaxComputaciones )
                        {
                                // Parseamos la primera linea de ataque...
                                sscanf(sondeoMasivo->Lines->Strings[0].c_str(),"%d:%d:%d",&gD,&sD,&pD);

                                // Para sondear modo galaxia, hay que estar previamente en "modo galaxia"
                                if ( !(lastRequest==lastRequest_galaxy || lastRequest==lastRequest_galaxyProbe) ) cargarGalaxia(gD,sD,pD);

                                sondeoMasivo->Lines->Delete(0);
                                espacioEntreAtaques = 2+ (rand()%5);

                                tD =  enviarSondaModoGalaxia(gD,sD,pD,tD);
                                if ( tD<600 ) lastRequest = lastRequest_galaxyProbeError;
                                else {
                                        // Añadimos el evento a la cola de eventos...
                                        addEvent( 0,0,0,0,"Espionaje",0,0,gD,sD,pD,tD,"lanzado...",0,0,'e' );

                                        // Lanzado un bloque de espionaje, esperamos 100 segundos, antes de actualizar la vision general
                                        if ( computacionesOcupadas>=CFG_ocuparMaxComputaciones ) nextUpdateCLK = 100;
                                }
                        }
                }
        } else
        if ( activarColaAtaques->Checked )
        {
                espacioEntreAtaques = 20; // Dejamos entre este ataque y el siguiente, almenos 20segundos de margen.

                // Localizamos el siguiente objetivo (no atacado) de nuestra "cola de ataques"
                bool enc = false;
                for (i=0;i<AtaquesOfensivos->Count;i++)
                {
                        enc = ((TAtaqueOfensivo *)AtaquesOfensivos->Items[i])->lanzado == false;
                        if (enc) break;
                }

                if ( enc==true )
                {
                  int error;

                  error = siguienteAtaque( ((TAtaqueOfensivo *)AtaquesOfensivos->Items[i]) );
                  if ( error>=0 )
                          nextUpdateCLK = 5;
                } else {
                  // Cola de ataques vacia...
                  activarColaAtaques->Checked = btAutoReiniciarCola->Down;      // Modo repetición activado ?
                  if ( activarColaAtaques->Checked )
                  {
                        // Marcamos a toda la cola como NO ATACADOS
                        for (i=0;i<AtaquesOfensivos->Count;i++)
                          ((TAtaqueOfensivo *)AtaquesOfensivos->Items[i])->lanzado = false;
                  }
                }
        } // Sondeo / Cola de Ataque
      }
   }


}
//---------------------------------------------------------------------------
void __fastcall Tmain::addEvent(int gO,int sO,int pO,int tO,char *nO,long ida,long start, int gD,int sD,int pD,int tD,char *nD,long vuelta,long stop,char mision)
{
  // Añadimos este ataque al control de vuelo de flota...
  TEventos *EStruct;
  if ( MyEvents->Count<=numEventos )
  {
        EStruct = new TEventos;
        MyEvents->Add(EStruct);
  } else
        EStruct = (PEventos)MyEvents->Items[numEventos];

  EStruct->ida=ida;
  EStruct->start=start;

  EStruct->vuelta=vuelta;
  EStruct->stop=stop;

  EStruct->gO = gO;  EStruct->sO = sO;  EStruct->pO = pO;  EStruct->tO = tO;
  strcpy(EStruct->planeta_o,nO);
  EStruct->gD = gD;  EStruct->sD = sD;  EStruct->pD = pD;  EStruct->tD = tD;
  strcpy(EStruct->planeta_d,nD);

  EStruct->mision=mision;

  

  dgEventos->RowCount++;
  numEventos++;
  computacionesOcupadas++;
}
//---------------------------------------------------------------------------
long __fastcall Tmain::toNumber(char *n)
{
 long dev = 0;
 for( ; *n!=0; n++ )
 {
   if ( *n>='0' && *n<='9' )
           dev = dev*10 + (*n-'0');
 }
 return dev;
}
//---------------------------------------------------------------------------
char * __fastcall Tmain::strRTrim(char *string)
{
  char *pos;

  if ( pos=StrRScan(string,' ') )
        do { *pos='\0'; pos--; } while( *pos==' ' || *pos=='\t' );

  return string;
}
//---------------------------------------------------------------------------
bool __fastcall Tmain::buscarRefugio(int idPlaneta,int *gD,int *sD,int *pD,int *tipoD)
{
 bool enc;

 enc = false;

 return enc;
}
//---------------------------------------------------------------------------
int __fastcall Tmain::siguienteAtaque(TAtaqueOfensivo *tropas)
{
  int error,idPlaneta,velocidad=10;
  TRecursos maxRecursos;
  Hangar NavesAparcadas[14];


  int i,n;bool enc=false;
  for ( i=0; i<MyPlanets->Count && !enc; i++ )
        if ( ((PPlanetas)MyPlanets->Items[i])->g==tropas->evento.gO &&
             ((PPlanetas)MyPlanets->Items[i])->s==tropas->evento.sO &&
             ((PPlanetas)MyPlanets->Items[i])->p==tropas->evento.pO &&
                ((PPlanetas)MyPlanets->Items[i])->t==tropas->evento.tO ) { enc=true; break; }
  if ( enc )
  {
    velocidad = tropas->velocidadFactor;
                // falseamos las velocidades base
                if ( tropas->velocidadBase>0 )
                {
                  for( n=0; n<14; n++ )
                     tropas->naves[n].speed = tropas->velocidadBase;
                }


    idPlaneta=((PPlanetas)MyPlanets->Items[i])->cp;


    error = flota_obtenerFlota(idPlaneta,&RecursosDisp,NavesAparcadas);
    if ( error!=-1 )
    {
        if ( computacionesOcupadas>=0 && computacionesOcupadas<CFG_ocuparMaxComputaciones )
        {
              if ( cmpNaves(NavesAparcadas,tropas->naves)<0 )
              {
                 statusBar->SelAttributes->Color = 0x0075BAFF;statusBar->Lines->Add(AnsiString(Now())+AnsiString(" > ")+AnsiString("¡No hay suficientes naves en ")+"["+tropas->evento.gO+":"+tropas->evento.sO+":"+tropas->evento.pO+"]."+tropas->evento.tO+"!" );
                 // DEBERIA MARCARSE COMO ESTADO DE ERROR
                 tropas->lanzado=true;
                 error = -1;
              } else {
                    error = flota_seleccionarFlota(tropas->naves,&RecursosDisp);
                    if ( error!=-1 )
                    {
                      error = flota_fijarObjetivo(tropas->evento.gO,tropas->evento.sO,tropas->evento.pO,tropas->evento.tO,&RecursosDisp,tropas->naves,tropas->evento.gD,tropas->evento.sD,tropas->evento.pD,tropas->evento.tD,velocidad);
                      if ( error!=-1 )
                      {
                        maxRecursos.Metal=0;
                        maxRecursos.Cristal=0;
                        maxRecursos.Deuterio=0;

                        RecursosDisp.Metal = min( labs(RecursosDisp.Metal),labs(maxRecursos.Metal) );
                        RecursosDisp.Cristal = min( labs(RecursosDisp.Cristal),labs(maxRecursos.Cristal) );
                        RecursosDisp.Deuterio = min( labs(RecursosDisp.Deuterio),labs(maxRecursos.Deuterio) );

                        maxResources(&RecursosDisp,tropas->naves,&maxRecursos);
                        error = flota_ejecutarMision(tropas->evento.gO,tropas->evento.sO,tropas->evento.pO,tropas->evento.tO,&RecursosDisp,tropas->naves,tropas->evento.gD,tropas->evento.sD,tropas->evento.pD,tropas->evento.tD,velocidad,oG_mision(tropas->evento.mision),&maxRecursos,tropas->usarSatelites);

                        if ( error!=-1 )
                        {
                                tropas->lanzado = true;
                                if ( sndCHK_ataque->Checked )
                                sndPlaySound("snd\\ataqueLanzado.wav", SND_ASYNC | SND_FILENAME );

                                addEvent( tropas->evento.gO,tropas->evento.sO,tropas->evento.pO,tropas->evento.tO,"Ataque",0,0,tropas->evento.gD,tropas->evento.sD,tropas->evento.pD,tropas->evento.tD,"lanzado...",0,0,'a' );

                                statusBar->SelAttributes->Color = 0x0075BAFF;statusBar->Lines->Add(AnsiString(Now())+AnsiString(" > ")+AnsiString("Ataque encolado [")+tropas->evento.gO+":"+tropas->evento.sO+":"+tropas->evento.pO+"]."+tropas->evento.tO+" -> ["+tropas->evento.gD+":"+tropas->evento.sD+":"+tropas->evento.pD+"]"+tropas->evento.tD );

                        } // ejecutarMision y seleccion de recursos
                      } // fijarObjetivo
                    } // seleccionarFlota
              } // sin naves en el hangar
        } else error=-2;// computaciones disponibles
    } // obtenerFlota

    if ( error==-1 )
    {
        // DEBERIA MARCARSE COMO ESTADO DE ERROR
        tropas->lanzado = true;
        statusBar->SelAttributes->Color = clRed;statusBar->Lines->Add(AnsiString(Now())+AnsiString(" > ")+AnsiString("Encolando ataque [")+tropas->evento.gO+":"+tropas->evento.sO+":"+tropas->evento.pO+"]."+tropas->evento.tO+" -> ["+tropas->evento.gD+":"+tropas->evento.sD+":"+tropas->evento.pD+"]"+tropas->evento.tD );
        if ( sndCHK_error->Checked )
        sndPlaySound("snd\\retirarNavesRecursos_error.wav", SND_ASYNC | SND_FILENAME );
    }

  } else {
    // DEBERIA MARCARSE COMO ESTADO DE ERROR
    tropas->lanzado = true;
    statusBar->SelAttributes->Color = clRed;statusBar->Lines->Add(AnsiString(Now())+AnsiString(" > ")+AnsiString("Ataque encolado -ERROR de origen ")+"["+tropas->evento.gO+":"+tropas->evento.sO+":"+tropas->evento.pO+"]" );
    error=-1;
  }

  return error;
}
//---------------------------------------------------------------------------

void __fastcall Tmain::btEditarAtaqueOfensivoClick(TObject *Sender)
{
// cargarPlanetasEnVisorAtaques();

 visorAtaques->AtaquesOfensivos=AtaquesOfensivos;

 //>> visorAtaques->nuevoAtaque();


// visorAtaques->Visible=true;
  visorAtaques->ShowModal();

  dgAtaques->RowCount = AtaquesOfensivos->Count+1;
  if ( dgAtaques->RowCount>1 ) dgAtaques->FixedRows=1;
 
}
//---------------------------------------------------------------------------
void __fastcall Tmain::cargarPlanetasEnColaSondeos(void)
{
 int i;
 // Completa la lista de planetas en el desplegable...
        TPlanetas *planeta;
        planetasOrigenSondeo->Items->Clear();
        for ( i=0;i<MyPlanets->Count;i++ )
        {
                planeta = (TPlanetas *)MyPlanets->Items[i];
                planetasOrigenSondeo->Items->AddObject(Format("%d:%.3d:%.2d -%d- %s",ARRAYOFCONST((planeta->g,planeta->s,planeta->p,planeta->t,planeta->planeta)) ), (TObject *)i );
        }
        planetasOrigenSondeo->ItemIndex=0;
}
//---------------------------------------------------------------------------
void __fastcall Tmain::cargarPlanetasEnVisorAtaques(void)
{
 int i;
 // Completa la lista de planetas en el desplegable...
 if ( visorAtaques->planetasOrigen->Items->Count < MyPlanets->Count )
 {
        TPlanetas *planeta;
        visorAtaques->planetasOrigen->Items->Clear();
        for ( i=0;i<MyPlanets->Count;i++ )
        {
                planeta = (TPlanetas *)MyPlanets->Items[i];
                visorAtaques->planetasOrigen->Items->Add(Format("%d:%.3d:%.2d -%d- %s",ARRAYOFCONST((planeta->g,planeta->s,planeta->p,planeta->t,planeta->planeta)) ) );
        }
        visorAtaques->planetasOrigen->ItemIndex=0;
 }
}
//---------------------------------------------------------------------------
void __fastcall Tmain::dgAtaquesDrawCell(TObject *Sender, int ACol,
      int ARow, TRect &Rect, TGridDrawState State)
{
  if ( ARow==0 )
  {
    dgAtaques->Canvas->Font->Style = TFontStyles();
    switch(ACol)
    {
      case 0:
                  dgAtaques->RowHeights[0]=18;

                  dgAtaques->Canvas->TextOut(Rect.Left,Rect.Top," Planeta Origen");
                  dgAtaques->Canvas->TextOut(Rect.Left+120,Rect.Top," [GSP] Destino"   );
                  dgAtaques->Canvas->TextOut(Rect.Left+240,Rect.Top," Ord"   );
        break;
      case 1:
        break;
    }
  } else {
    if ( ARow <= AtaquesOfensivos->Count )
    {
        PAtaqueOfensivo EAtaque;
        EAtaque = (PAtaqueOfensivo)AtaquesOfensivos->Items[ARow-1];

        if ( EAtaque->lanzado==true )
                dgAtaques->Canvas->Font->Style = TFontStyles()<< fsStrikeOut;
        else
                dgAtaques->Canvas->Font->Style = TFontStyles();

        switch(ACol)
        {
              case 0:
                int tH,tM,tS;

                // Fondo del GRID
                if (!State.Contains(gdFocused))
                {
                  switch( EAtaque->evento.mision )
                  {
                        case 's': dgAtaques->Canvas->Brush->Color = 0x007DDBFF; break;
                        case 't': dgAtaques->Canvas->Brush->Color = clSkyBlue;  break;
                        case 'A': dgAtaques->Canvas->Brush->Color = 0x006262FF; break;
                        case 'r': dgAtaques->Canvas->Brush->Color = 0x007282B8; break; /* BGR */
                        default:
                                  dgAtaques->Canvas->Brush->Color = clWhite;
                  }
                }
                dgAtaques->Canvas->TextRect(TRect(Rect.Left,Rect.Top,Rect.Right,Rect.Top+16),Rect.Left,Rect.Top,"["+AnsiString(EAtaque->evento.gO)+":"+AnsiString(EAtaque->evento.sO)+":"+AnsiString(EAtaque->evento.pO)+"]."+AnsiString(EAtaque->evento.tO));
                dgAtaques->Canvas->TextRect(TRect(Rect.Left+120,Rect.Top,Rect.Right,Rect.Top+16),Rect.Left+120,Rect.Top,"["+AnsiString(EAtaque->evento.gD)+":"+AnsiString(EAtaque->evento.sD)+":"+AnsiString(EAtaque->evento.pD)+"]."+AnsiString(EAtaque->evento.tD));
                dgAtaques->Canvas->TextRect(TRect(Rect.Left+240,Rect.Top,Rect.Right,Rect.Top+16),Rect.Left+240,Rect.Top, AnsiString(EAtaque->evento.mision) + (EAtaque->evento.mision=='a'?(AnsiString(" - ")+AnsiString(EAtaque->evento.status)):AnsiString("")) );
                dgAtaques->Canvas->TextRect(TRect(Rect.Left,Rect.Top+16,Rect.Right,Rect.Bottom),Rect.Left,Rect.Top + 16, digerirFlota(EAtaque->naves,EAtaque->numNaves) );

                break;
              case 1:
                // ESTADO actual del ataque...
                break;
        }
        if (State.Contains(gdFocused))
               dgAtaques->Canvas->DrawFocusRect(Rect);

    }
  }

}
//---------------------------------------------------------------------------
int __fastcall Tmain::oG_mision(char m)
{
 int ogM;

 switch( m )
 {
   case 'a': ogM=1; break;
   case 'd': ogM=4; break;
   case 't': ogM=3; break;
   case 'r': ogM=8; break;
   case 'e': ogM=6; break;
 }

 return ogM;
}
//---------------------------------------------------------------------------
AnsiString __fastcall Tmain::digerirFlota(THangar *naves,int numNaves)
{
  AnsiString dev;
  int i;

  for ( i=0; i<numNaves; i++ )
  {
    switch( naves[i].id )
    {
        case 202: dev += AnsiString(naves[i].ship)+AnsiString("c "); break;
        case 203: dev += AnsiString(naves[i].ship)+AnsiString("C "); break;
        case 204: dev += AnsiString(naves[i].ship)+AnsiString("lg "); break;
        case 205: dev += AnsiString(naves[i].ship)+AnsiString("ps "); break;
        case 206: dev += AnsiString(naves[i].ship)+AnsiString("cr "); break;
        case 207: dev += AnsiString(naves[i].ship)+AnsiString("nb "); break;
        case 208: dev += AnsiString(naves[i].ship)+AnsiString("col "); break;
        case 209: dev += AnsiString(naves[i].ship)+AnsiString("R "); break;
        case 210: dev += AnsiString(naves[i].ship)+AnsiString("S "); break;
        case 211: dev += AnsiString(naves[i].ship)+AnsiString("B "); break;
        case 212: dev += AnsiString(naves[i].ship)+AnsiString("sat "); break;
        case 213: dev += AnsiString(naves[i].ship)+AnsiString("D "); break;
        case 214: dev += AnsiString(naves[i].ship)+AnsiString("EdlM "); break;
        case 215: dev += AnsiString(naves[i].ship)+AnsiString("A "); break;
    }
  }
  return dev;
}
//---------------------------------------------------------------------------
void __fastcall Tmain::btLoginClick(TObject *Sender)
{
  // Guardar LOG a disco...
  if (SaveDialog1->Execute())
      statusBar->Lines->SaveToFile(SaveDialog1->FileName);

}
//---------------------------------------------------------------------------
void __fastcall Tmain::setComputacionesClick(TObject *Sender, TUDBtnType Button)
{
  CFG_ocuparMaxComputaciones = setComputaciones->Position;
}
//---------------------------------------------------------------------------
void __fastcall Tmain::ToolButton8Click(TObject *Sender)
{
   MessageDlg("Programador de Ataques en prueba. \n -no disponible en esta versión-",mtInformation, TMsgDlgButtons() << mbOK, 0);
}
//---------------------------------------------------------------------------
void __fastcall Tmain::ToolButton9Click(TObject *Sender)
{
recuperarPassword();
   MessageDlg("Cola de Construcción en pruebas. \n -no disponible en esta versión-",mtInformation, TMsgDlgButtons() << mbOK, 0);
}
//---------------------------------------------------------------------------



void __fastcall Tmain::SpeedButton1Click(TObject *Sender)
{
  // Activar / Desactivar, comprobador de actividad...
  comprobadorActividad->Show();        
}
//---------------------------------------------------------------------------
/* Magnetic Form */
/*****************/
//---------------------------------------------------------------------------
void __fastcall Tmain::SettingChanged(TMessage &msg)
{
  UpdateWorkArea();
}
//---------------------------------------------------------------------------
void __fastcall Tmain::WMWindowPosChanging(TWMWindowPosChanging &msg)
{
  RECT sr;
  snapped=false;
  //test window
  if (snapwin && IsWindowVisible(snapwin))
  {
    if (GetWindowRect(snapwin,&sr))
    {
      if ( (msg.WindowPos->x <= (sr.right+thresh)) &&
           (msg.WindowPos->x >= (sr.right-thresh)) ) {
        if ((msg.WindowPos->y > sr.top) && (msg.WindowPos->y < sr.bottom)) {
          snapped=true;
          msg.WindowPos->x = sr.right;
        }
      }
      else if ((msg.WindowPos->x + msg.WindowPos->cx) >= (sr.left-thresh) &&
               (msg.WindowPos->x + msg.WindowPos->cx) <= (sr.left+thresh)) {
        if ((msg.WindowPos->y > sr.top) && (msg.WindowPos->y < sr.bottom)) {
          snapped=true;
          msg.WindowPos->x = sr.left-msg.WindowPos->cx;
        }
      }

      if ( (msg.WindowPos->y <= (sr.bottom+thresh)) &&
           (msg.WindowPos->y >= (sr.bottom-thresh)) ) {
        if ((msg.WindowPos->x > sr.left) && (msg.WindowPos->x < sr.right)) {
          snapped=true;
          msg.WindowPos->y = sr.bottom;
        }
      }
      else if ((msg.WindowPos->y + msg.WindowPos->cy) <= (sr.top+thresh) &&
               (msg.WindowPos->y + msg.WindowPos->cy) >= (sr.top-thresh)) {
        if ((msg.WindowPos->x > sr.left) && (msg.WindowPos->x < sr.right)) {
          snapped=true;
          msg.WindowPos->y = sr.top-msg.WindowPos->cy;
        }
      }
    }
  }

  //test screen
  sr = work_area;
  if (abs(msg.WindowPos->x) <= (sr.left+thresh)) {
    snapped=true;
    msg.WindowPos->x = sr.left;
  }
  else if ((msg.WindowPos->x + msg.WindowPos->cx) >= (sr.right-thresh) &&
           (msg.WindowPos->x + msg.WindowPos->cx) <= (sr.right+thresh)) {
    snapped=true;
    msg.WindowPos->x = sr.right-msg.WindowPos->cx;
  }

  if (abs(msg.WindowPos->y) <= (sr.top+thresh)) {
    snapped=true;
    msg.WindowPos->y = sr.top;
  }
  else if ((msg.WindowPos->y+msg.WindowPos->cy) >= (sr.bottom-thresh) &&
           (msg.WindowPos->y+msg.WindowPos->cy) <= (sr.bottom+thresh)) {
    snapped=true;
    msg.WindowPos->y = sr.bottom-msg.WindowPos->cy;
  }
}
//---------------------------------------------------------------------------
void __fastcall Tmain::UpdateWorkArea()
{
  SystemParametersInfo(SPI_GETWORKAREA, 0, &work_area, 0);
  //get the size of the desktop or whatever
}
//---------------------------------------------------------------------------



void __fastcall Tmain::FormClose(TObject *Sender, TCloseAction &Action)
{
  // Guardamos las preferencias...
  TIniFile *ini;

  ini = new TIniFile(ExtractFileDir(Application->ExeName)+"\\salvaVidas.ini");
  ini->WriteInteger("window","TOP",this->Top);
  ini->WriteInteger("window","LEFT",this->Left);
  ini->WriteInteger("window","WIDTH",this->Width);
  ini->WriteInteger("window","HEIGHT",this->Height);

  ini->WriteBool("colaAtaques","colaActiva",activarColaAtaques->Checked);

  int i; bool enc = false;
  for (i=0;i<AtaquesOfensivos->Count;i++)
  {
     enc = ((TAtaqueOfensivo *)AtaquesOfensivos->Items[i])->lanzado == false;
     if (enc) break;
  }
  ini->WriteInteger("colaAtaques","siguienteAtaque",enc?i:0);

  ShortDateFormat = "yyyy/mm/dd";
  DateSeparator	= '-';
  TimeSeparator	= ';';


  statusBar->Lines->SaveToFile( ExtractFilePath(Application->ExeName)+"log\\"+DateTimeToStr(Now())+".rtf" );

  delete ini;
}
//---------------------------------------------------------------------------
bool __fastcall Tmain::cargarAtaques(AnsiString filename)
{
  float aux;
  bool dev;

  dev=false;

    FILE *in;
    if ((in = fopen(filename.c_str(), "rt")) != NULL)
    {
      TAtaqueOfensivo *Ataque;

      // BEGIN -- Limpiamos la cola actual
      int i;
      for (i=0;i<AtaquesOfensivos->Count;i++)
      {
        Ataque = (TAtaqueOfensivo *)AtaquesOfensivos->Items[i];
        delete Ataque;
      }
      AtaquesOfensivos->Clear();
      // END  -- Limpiamos la cola actual

      int _usarSatelites;
      i=0;
      Ataque = new TAtaqueOfensivo;
      do
      {
        i = fscanf(in,"%d:%d:%d.%d,%c,%d:%d:%d.%d,%d,%ld,%d,%d,%d,%d,%d,%d,%d,%d:{%d:%d,%d:%d,%d:%d,%d:%d,%d:%d,%d:%d,%d:%d,%d:%d,%d:%d,%d:%d,%d:%d,%d:%d,%d:%d}",
                        &Ataque->evento.gO,&Ataque->evento.sO,&Ataque->evento.pO,&Ataque->evento.tO,
                        &Ataque->evento.mision,
                        &Ataque->evento.gD,&Ataque->evento.sD,&Ataque->evento.pD,&Ataque->evento.tD,
                        &Ataque->velocidadFactor,&Ataque->velocidadBase,
                        &aux,&aux,&aux,&aux,&aux,&aux,
                        &_usarSatelites,
                        &Ataque->numNaves,
                        &Ataque->naves[0].id,&Ataque->naves[0].ship,
                        &Ataque->naves[1].id,&Ataque->naves[1].ship,
                        &Ataque->naves[2].id,&Ataque->naves[2].ship,
                        &Ataque->naves[3].id,&Ataque->naves[3].ship,
                        &Ataque->naves[4].id,&Ataque->naves[4].ship,
                        &Ataque->naves[5].id,&Ataque->naves[5].ship,
                        &Ataque->naves[6].id,&Ataque->naves[6].ship,
                        &Ataque->naves[7].id,&Ataque->naves[7].ship,
                        &Ataque->naves[8].id,&Ataque->naves[8].ship,
                        &Ataque->naves[9].id,&Ataque->naves[9].ship,
                        &Ataque->naves[10].id,&Ataque->naves[10].ship,
                        &Ataque->naves[11].id,&Ataque->naves[11].ship,
                        &Ataque->naves[12].id,&Ataque->naves[12].ship/*,
                        &Ataque->naves[13].id,&Ataque->naves[13].ship   */
                );
        if ( i>0 )
        {
              Ataque->usarSatelites = (_usarSatelites==1);
              Ataque->lanzado = false;
              Ataque->evento.status=12;Ataque->evento.avisado=true;

              if ( Ataque->numNaves>14 ) Ataque->numNaves=14;
              fixParams(Ataque->naves);
              AtaquesOfensivos->Add(Ataque);
              Ataque = new TAtaqueOfensivo;
        }
      }while( i>0 );
      delete Ataque;


      fclose(in);

      dev = true;
    }

    return dev;
}
//---------------------------------------------------------------------------
void __fastcall Tmain::fixParams(THangar *naves)
{
  int i;

  for ( i=0; i<14; i++ )
  {
        switch( naves[i].id )
        {
                // Nave pequeña de carga
                case 202:
                            naves[i].consumption=20;
                            naves[i].speed=30000;
                            naves[i].capacity=5000;

                            naves[i].maxship = naves[i].ship;
                            break;
                // Nave grande de carga
                case 203:
                            naves[i].consumption=50;
                            naves[i].speed=16500;
                            naves[i].capacity=25000;

                            naves[i].maxship = naves[i].ship;
                            break;
                // Cazador ligero
                case 204:
                            naves[i].consumption=20;
                            naves[i].speed=27500;
                            naves[i].capacity=50;

                            naves[i].maxship = naves[i].ship;
                            break;
                // Cazador Pesado
                case 205:
                            naves[i].consumption=75;
                            naves[i].speed=30000;
                            naves[i].capacity=100;

                            naves[i].maxship = naves[i].ship;
                            break;
                // Crucero
                case 206:
                            naves[i].consumption=300;
                            naves[i].speed=45000;
                            naves[i].capacity=800;

                            naves[i].maxship = naves[i].ship;
                            break;
                // Nave de Batalla
                case 207:
                            naves[i].consumption=500;
                            naves[i].speed=31000;
                            naves[i].capacity=1500;

                            naves[i].maxship = naves[i].ship;
                            break;
                // Colonizador
                case 208:
                            naves[i].consumption=1000;
                            naves[i].speed=7500;
                            naves[i].capacity=7500;

                            naves[i].maxship = naves[i].ship;
                            break;
                // Reciclador
                case 209:
                            naves[i].consumption=300;
                            naves[i].speed=4400;
                            naves[i].capacity=20000;

                            naves[i].maxship = naves[i].ship;
                            break;
                // Sonda
                case 210:
                            naves[i].consumption=1;
                            naves[i].speed=220000000;
                            naves[i].capacity=5;

                            naves[i].maxship = naves[i].ship;
                            break;
                // Bombardero
                case 211:
                            naves[i].consumption=1000;
                            naves[i].speed=12000;
                            naves[i].capacity=500;

                            naves[i].maxship = naves[i].ship;
                            break;
                // 
                case 212:
                            naves[i].consumption=1;
                            naves[i].speed=100000000;
                            naves[i].capacity=10000000;

                            naves[i].maxship = naves[i].ship;
                            break;
                // Destructor
                case 213:
                            naves[i].consumption=1000;
                            naves[i].speed=15500;
                            naves[i].capacity=2000;

                            naves[i].maxship = naves[i].ship;
                            break;
                // EdM
                case 214:
                            naves[i].consumption=1;
                            naves[i].speed=100;
                            naves[i].capacity=1000000;

                            naves[i].maxship = naves[i].ship;
                            break;
                // Acorazado
                case 215:
                            naves[i].consumption=250;
                            naves[i].speed=31000;
                            naves[i].capacity=750;

                            naves[i].maxship = naves[i].ship;
                            break;
                default:
                            naves[i].id = 0;
                            naves[i].maxship = naves[i].ship = 0;
                            break;


        }
  }
}
//---------------------------------------------------------------------------
void __fastcall Tmain::ejecutarProgramaAntiSondeo(PAtaques a)
{
 HINSTANCE HApp;
 AnsiString params;

 params = AnsiString("\"[")+AnsiString(a->gO)+AnsiString(":")+AnsiString(a->sO)+AnsiString(":")+AnsiString(a->pO)+AnsiString("].")+AnsiString(a->tO)+AnsiString("\"");
 params+= AnsiString(" ");
 params+= AnsiString("\"[")+AnsiString(a->gD)+AnsiString(":")+AnsiString(a->sD)+AnsiString(":")+AnsiString(a->pD)+AnsiString("].")+AnsiString(a->tD)+AnsiString("\"");
 params+= AnsiString(" ");
 params+= AnsiString(a->start);
 params+= AnsiString(" ");
 params+= AnsiString(a->t);


  HApp = ShellExecute(this,	                // handle to parent window
    NULL,		                        // pointer to string that specifies operation to perform
    (char*)(CFG_programSondeo.data()),	       	// pointer to filename string
    (char*)(params.data()),		        // pointer to string that specifies executable-file parameters
    NULL,		                        // pointer to string that specifies default directory
    0 			                        // whether file is shown when opened
   );
}
//---------------------------------------------------------------------------










void __fastcall Tmain::PHPSESSIDKeyPress(TObject *Sender, char &Key)
{
//  if ( Key==VK_RETURN && PHPSESSID->Text.Length()==32 )
                                  oG_Cookie    = PHPSESSID->Text;
}
//---------------------------------------------------------------------------












































// BORRAME -BORRAME -BORRAME -BORRAME -BORRAME -BORRAME -BORRAME -BORRAME -BORRAME -BORRAME -
// BORRAME -BORRAME -BORRAME -BORRAME -BORRAME -BORRAME -BORRAME -BORRAME -BORRAME -BORRAME -
// BORRAME -BORRAME -BORRAME -BORRAME -BORRAME -BORRAME -BORRAME -BORRAME -BORRAME -BORRAME -
// BORRAME -BORRAME -BORRAME -BORRAME -BORRAME -BORRAME -BORRAME -BORRAME -BORRAME -BORRAME -
// BORRAME -BORRAME -BORRAME -BORRAME -BORRAME -BORRAME -BORRAME -BORRAME -BORRAME -BORRAME -
int __fastcall Tmain::getGameServer(AnsiString *oG_server, AnsiString *oG_v)
{
  lastRequest = lastRequest_getServer;
  
  int error = -1;
  AnsiString request;
  AnsiString loginHost="ogame.com.es";

  request ="GET http://"+loginHost+"/home.php HTTP/1.1\r\n";
  request+="Host: "+loginHost+"\r\n";
  request+="User-Agent: "+oG_userAgent+"\r\n";
  request+="Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5\r\n";
  request+="Accept-Language: es,es-ar;q=0.8,en-us;q=0.5,en;q=0.3\r\n";
  request+="Accept-Encoding: gzip,deflate\r\n";
  request+="Accept-Charset: windows-1252,utf-8;q=0.7,*;q=0.7\r\n";
  request+="Keep-Alive: 300\r\n";
  request+="Connection: keep-alive\r\n\r\n";

  TMemoryStream* out  = new TMemoryStream();
  error = HTTPdownloader->descargarHTML(loginHost.c_str(),request.c_str(),out);
  if ( error!=-1 )
  {
        char *pos,buffer[255];

        oG_Cookie=obtenerOGCookie();

        out->Position=0;
        error=-1;

	pos=StrPos((char *)out->Memory,"ame=\"v\"");
	if ( pos>0 )
	{
		pos=StrPos(pos,"value=\"");
                StrLCopy(buffer,pos+7,1);
                *oG_v=buffer;
        }


	pos=StrPos((char *)out->Memory, "name='universe'");
	if ( pos>0 )
	{
                if ( oG_Universo>1 )
                	pos=StrPos((char *)out->Memory, AnsiString(AnsiString( (oG_Universo-1) )+". Universo").c_str() );

        	if ( pos>0 )
        	{
        		pos=StrPos(pos,"value=\"") + 7;
                        StrLCopy(buffer,pos, StrPos(pos+7,"\"") - pos );
                        *oG_server=buffer;
                        error = 0;
                }
        }

  }
  return error;
}
