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

#include <vcl.h>
#pragma hdrstop

#include "fourier.h"
#include "fftw3.h"
#include "utilidades.h"
#include "math.h"
#include "Math.hpp"


//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "Spin"
#pragma resource "*.dfm"
TForm13 *Form13;

fftw_complex *datos_fft;   //datos de la imagen en bruto
double *datos_img;
fftw_plan plan;
double *amp,*amp2;
	int tamaY;
		float scale;

//---------------------------------------------------------------------------
__fastcall TForm13::TForm13(TComponent* Owner)
	: TForm(Owner)
{

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

void __fastcall TForm13::setImagen(TPicture* img){


}

void __fastcall TForm13::Button1Click(TObject *Sender)
{

  Form13->Hide();
}
//---------------------------------------------------------------------------
int __fastcall TForm13::maximo(int v1,int v2){
 int ret;
 if (v1>v2) {
	 ret=v1;
 } else {
	ret=v2;
 }
 return ret;
}

int __fastcall TForm13::minimo(int v1,int v2){
int ret;
 if (v1<v2) {
	 ret=v1;
 } else {
	ret=v2;
 }
 return ret;
}

void __fastcall TForm13::Button3Click(TObject *Sender)
{
	int i,j,k,l;
	float max,min;
	Byte *pixel;



	imgtmp=new TPicture;



	max=0;min=1000000;

	datos_img=new double[sizeof(double)*anchura*altura];

	for (i = 0; i < altura; i++) {
		for (j = 0; j < anchura; j++) {
		  datos_img[j*anchura+i]=(double)(doc->dameFinal()->Bitmap->Canvas->Pixels[i][j]);
		}
	}

	tamaY=(altura/2)+1;
	datos_fft=new fftw_complex[sizeof(fftw_complex)*anchura*tamaY];
	amp=new double[sizeof(fftw_complex)*anchura*tamaY];
	amp2=new double[sizeof(fftw_complex)*anchura*tamaY];

	plan=fftw_plan_dft_r2c_2d(anchura,altura,datos_img,datos_fft,FFTW_ESTIMATE);
	fftw_execute(plan);

	Image1->Picture->LoadFromFile("./res/paletafft2.bmp");    //cargar paleta
	imgtmp->LoadFromFile("./res/paletafft2.bmp");    //cargar paleta
	imagen->Bitmap->PixelFormat=pf8bit;
	imagen->LoadFromFile("./res/paletafft2.bmp");    //cargar paleta


	Image1->Picture->Bitmap->Width=anchura;
	Image1->Picture->Bitmap->Height=tamaY*2;
	imagen->Bitmap->Width=anchura;
	imagen->Bitmap->Height=tamaY;
	imgtmp->Bitmap->Width=anchura;
	imgtmp->Bitmap->Height=tamaY*4;

	for (i = 0; i < anchura-1; i++) {
		for (j=0; j<  tamaY; j++) {
			//sacamos el modulo  (magnitud)
			amp[tamaY*i+j]=(double)log10((sqrt(datos_fft[tamaY*i+j][0]*datos_fft[tamaY*i+j][0]+datos_fft[tamaY*i+j][1]*datos_fft[tamaY*i+j][1])));

			if (amp[tamaY*i+j]>max) {
				max=amp[tamaY*i+j];
			}
			if (amp[tamaY*i+j]<min) {
				min=amp[tamaY*i+j];
			}
		}
	}

  /*	 for (i = 0; i < anchura-1; i++) {
	 for (j=0; j<  tamaY; j++) {

			amp2[tamaY*i+j]=(double)(((amp[tamaY*i+j]-min-1)/max));

		}
	}         */

	scale=(float)(255.0/(max-min));


	for (k=0; k < anchura; k++) {
	 for (l=0; l < tamaY; l++) {
		i=(k+(anchura-1)/2)%(anchura-1);   //centramos la imagen
		j=(l+(tamaY)/2)%tamaY;
	  // i=k;
	  j=l;

		pixel=(byte *)imagen->Bitmap->ScanLine[l];

		{

				pixel[k]=doc->recortaSimple((byte)(((amp[i*tamaY+j]-min)*scale+0.5)+1));
		}

	 }

	}


	imgtmp->Bitmap->Canvas->CopyRect(Rect(0,tamaY-1,anchura,-1),imagen->Bitmap->Canvas,Rect(0,0,anchura,tamaY));
	imgtmp->Bitmap->Canvas->Draw(0,tamaY,imagen->Bitmap);

	Image1->Canvas->Draw(0,0,imgtmp->Bitmap);
	tY=imgtmp->Bitmap->Height;
	Button3->Enabled=false;
	  fftw_destroy_plan(plan);
  fftw_free(datos_img);
  fftw_free(datos_fft);
}
//---------------------------------------------------------------------------
void __fastcall TForm13::SpinEdit1Change(TObject *Sender)
{
  Image1->Canvas->Draw(0,0,imgtmp->Bitmap);
  if (SpinEdit1->Value!=1) {
	  Image1->Stretch=true;
	  Image1->Width=anchura*SpinEdit1->Value;
	  Image1->Height=altura*SpinEdit1->Value;
  } else {
	  Image1->Stretch=false;
	  Image1->Width=anchura;
	  Image1->Height=tY;

  }
}
//---------------------------------------------------------------------------
void __fastcall TForm13::setDoc(utilidades* documento){
	doc=documento;
	doc->reinicia();
	anchura=doc->dameAnchura();
	altura=doc->dameAltura();
	imagen=new TPicture;
	imagen->Assign(doc->dameFinal());
      Button3->Enabled=true;
}



void __fastcall TForm13::Button4Click(TObject *Sender)
{
  menu->Popup(Form13->Left+Button4->Left,Form13->Top+Button4->Top-30);
}
//---------------------------------------------------------------------------

void __fastcall TForm13::Button2Click(TObject *Sender)
{
 Panel1->Visible=false;
 Label1->Caption="Guardando archivo...";
 Button2->Visible=false;
}
//---------------------------------------------------------------------------

void __fastcall TForm13::FormatoHTML1Click(TObject *Sender)
{
int i,j;
 String tmp="";

	 guarda->Filter="Archivo HTML (*.html)|*.html";

	if (guarda->Execute()) {
	Panel1->Visible=true;
	Panel1->Repaint();
 tmp="<b>Datos FFT de: </b>"+String(doc->nombre())+"</br></br>";
		Memo1->Lines->Add(tmp);
tmp="<table border='1'><tr><td><b>Pixel</b></td><td><b>Valor</b></td><td><b>10log(modulo)</b></td></tr>";
tmp="<table border='1'><tr><td><b>Kx</b></td><td><b>Ky</b></td><td><b>Parte real</b></td><td><b>Parte imaginaria</b></td><td><b>Modulo</b></td><td><b>Fase</b></td></tr>";
		Memo1->Lines->Add(tmp);

	   for (i = 0; i < anchura-1; i++) {
		for (j = 0; j < tamaY; j++) {
		tmp="<tr><td>"+String(IntToStr(i))+"</td><td>"+String(IntToStr(j))+"</td><td>"+puntos(String(FloatToStr(datos_fft[tamaY*i+j][0])))+"</td><td>"+puntos(String(FloatToStr(datos_fft[tamaY*i+j][1])))+"</td><td>"+puntos(String(FloatToStr(amp[tamaY*i+j])))+"</td><td>"+puntos(String(FloatToStr(atan2(datos_fft[tamaY*i+j][0],datos_fft[tamaY*i+j][1]))))+"</td></tr>";

		Memo1->Lines->Add(tmp);
		}

	   }

Memo1->Lines->Add("</table>");
Memo1->Lines->SaveToFile(guarda->FileName);
Label1->Caption="Archivo Guardado";
Button2->Visible=true;
	}
}
//---------------------------------------------------------------------------

void __fastcall TForm13::FormatoTXT1Click(TObject *Sender)
{
int i,j;
 String tmp="";

		 guarda->Filter="Archivo CSV (*.csv)|*.csv";
	if (guarda->Execute()) {
	Panel1->Visible=true;
	Panel1->Repaint();
tmp="Kx,Ky,Parte real,Parte imaginaria,Modulo,Fase";
		Memo1->Lines->Add(tmp);

	   for (i = 0; i < anchura-1; i++) {
		for (j = 0; j < tamaY; j++) {
		 tmp=String(IntToStr(i))+","+String(IntToStr(j))+","+puntos(String(FloatToStr(datos_fft[tamaY*i+j][0])))+","+puntos(String(FloatToStr(datos_fft[tamaY*i+j][1])))+","+puntos(String(FloatToStr(amp[tamaY*i+j])))+","+puntos(String(FloatToStr(atan2(datos_fft[tamaY*i+j][0],datos_fft[tamaY*i+j][1]))));

		Memo1->Lines->Add(tmp);
		}

	   }


Memo1->Lines->SaveToFile(guarda->FileName);
Label1->Caption="Archivo Guardado";
Button2->Visible=true;
	}
}
//---------------------------------------------------------------------------
String __fastcall TForm13::puntos(String entrada){
	int i;
	String salida;

	salida=StringReplace(entrada,",",".",TReplaceFlags() << rfReplaceAll);



	return salida;
}
