//----------------------------------------------------------------------------
//Borland C++Builder
//Copyright (c) 1987, 1998 Borland International Inc. All Rights Reserved.
// Updated by: Chr. Monstein, 08.03.2002 malloc/free instead array
// Updated by: Chr. Monstein, 17.03.2005 zero-buffer, SNR and layout
// Updated by: Chr. Monstein, 17.09.2008 mehr Stellen gespeichert
// Updated by: Chr. Monstein, 18.09.2008 get rid of old stuff ....
// Updated by: Chr. Monstein, 15.01.2014 adaption to Agilent M9703A (Magentasys)
// Updated by: Chr. Monstein, 16.01.2014 adaption to several input formats
// Updated by: Chr. Monstein, 01.02.2014 log() -> log10(), LO option
// Updated by: Chr. Monstein, 06.03.2014 prevent log(0)
// Updated by: Chr. Monstein, 28.10.2018 zoom in x and y
//----------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop
#include <sysutils.hpp>
#include <CLIPBRD.HPP> // clipboard only
#include <jpeg.hpp>
#include <stdio.h>
#include <fstream.h>
#include <Printers.hpp>
#include "imagewn.h"
#include "UnitYT.h"
#include <math.h>
//---------------------------------------------------------------------
#pragma resource "*.dfm"
TImageForm *ImageForm;

long N=32768; // 16 bit max
double *act, *Icold;

double maxi, mini;
double Fmin, Fmax;
char Header[120];
char unit[10];
long rows; // pixels per sweep
int Rmin, Rmax;
bool first = true;
//---------------------------------------------------------------------
__fastcall TImageForm::TImageForm(TComponent *Owner)
  : TForm(Owner)
{
    Button2->Enabled=false;
    act   = new double[N];
    Icold = new double[N];
}
//---------------------------------------------------------------------
void __fastcall TImageForm::FormCreate(TObject* /*Sender*/)
{
    FormCaption = Caption + " - ";
    ImageForm->Left=Screen->Width -ImageForm->Width;
    ImageForm->Top =Screen->Height-ImageForm->Height-33;
}
//----------------------------------------------------------------------------
#pragma argsused
//---------------------------------------------------------------------------
void __fastcall TImageForm::ReadFile(char *filename)
{
  char st[120];
  long row = 0;
  int channel;
  double tempi;

  maxi = -1.0E15, mini = 1.0E15;
  float LO = atof(Edit2->Text.c_str());
  Fmin = atof(Edit4->Text.c_str());
  Fmax = atof(Edit5->Text.c_str());
  ifstream infile(filename);
  infile.getline(st,80); // read and forget title   (skip header)
  while (infile)
  {
    infile.getline(st,80);
    if (infile)
    {
      if (strstr(st,","))
         sscanf(st,"%lf,%lf",&act[row],&tempi);
      if (strstr(st,";"))
         sscanf(st,"%lf;%lf",&act[row],&tempi);
      else
         sscanf(st,"%lf %lf",&act[row],&tempi);
      Icold[row] = tempi;

      if (RadioButton1->Checked) act[row] = act[row] + LO;
      if (RadioButton2->Checked) act[row] = LO - act[row];
      if (RadioButton3->Checked) act[row] = act[row] - LO;
      row++;
    }
  }
  infile.close();

  rows = row;
  sprintf(st,"Rows: %8u",rows);
  Label2->Caption = st;

  Fmin = act[0];
  Fmax = act[rows-1];
  sprintf(st,"%8.3e",Fmin);    // *1.1+0.5
  Edit4->Text = st; // plottrange min
  Edit4->Update();
  sprintf(st,"%8.3e",Fmax);    // *1.1+0.5
  Edit5->Text = st; // plottrange max
  Edit5->Update();

  Rmin = 0;
  Rmax = rows;

  if (strstr(filename,"OVS_"))
     sprintf(unit,"mV");
  else
     sprintf(unit,"ADU");

  if (CheckBox1->Checked)   // log scale
  {
    for (int i=0; i<row; i++)
    {
      if (strstr(filename,"OVS_"))
         Icold[i] = Icold[i]/25.4;  // Callisto spectral overview  mV->dB
      else
         Icold[i] = 10.0*log10(Icold[i]);
    }
    sprintf(unit,"dB");
  }


  maxi=-1.0e15, mini=1.0E15;
  for (int i=0; i<row; i++)
  {
    if (Icold[i]  > maxi) maxi = Icold[i];
    if (Icold[i]  < mini) mini = Icold[i];
  }

  if (CheckBox2->Checked)   // background subtraction
  {
    for (int i=0; i<row; i++)
    {
      Icold[i] = Icold[i] - mini;
    }
    maxi = maxi - mini;
    mini = 0.;
  }

  sprintf(st,"%8.3e",mini);    // *1.1+0.5
  Edit1->Text = st; // plottrange min
  Edit1->Update();
  sprintf(st,"%8.3e",maxi);    // *1.1+0.5
  Edit3->Text = st; // plottrange max
  Edit3->Update();

  Button2->Enabled=true;
}
//----------------------------------------------------------------------------
void __fastcall TImageForm::FileListBox1Click(TObject* /*Sender*/)
{
  FileExt = ExtractFileExt(FileListBox1->FileName);
  FileExt = UpperCase(FileExt);
  if ( !strcmp(FileExt.c_str(),".TXT") || !strcmp(FileExt.c_str(),".PRN") || !strcmp(FileExt.c_str(),".CSV") )
  {
    ReadFile(FileListBox1->FileName.c_str()); // read file into buffer
    //Form2->Show(); // show before plott
    Form2->PaintBox1Click(0);
  }
}
//----------------------------------------------------------------------------
void __fastcall TImageForm::Button2Click(TObject *Sender) // save as BMP
{
    Graphics::TBitmap* DestBitmap = new Graphics::TBitmap();
    int width=Form2->PaintBox1->Width;
    int height=Form2->PaintBox1->Height;
    DestBitmap->Width=width;
    DestBitmap->Height=height;
    TRect   SrcRect, DesRect;
    SrcRect = Rect(0,0,width, height);
    DesRect = Rect(0,0,width, height);
    DestBitmap->Canvas->CopyRect(SrcRect,Form2->Canvas,DesRect);
    try
    {
      SaveDialog1->Title = "Save Paintbox as bmp-file";
      if (SaveDialog1->Execute())
      {
        if (FileExists(SaveDialog1->FileName))
        DeleteFile(SaveDialog1->FileName);
        DestBitmap->SaveToFile(SaveDialog1->FileName); // Super läuft!
        Beep();
      }
    }
    catch(...)
    {
        ShowMessage("Error: Bitmap saving");
    }
    delete DestBitmap;
}
//---------------------------------------------------------------------------
void __fastcall TImageForm::BitBtn1Click(TObject *Sender) // exit
{
    free(act);
    free(Icold);
}
//---------------------------------------------------------------------------
void __fastcall TImageForm::Edit1Change(TObject *Sender)
{
    int Size = Edit1->GetTextLen(); // Länge des Strings in Edit1 ermitteln
    Size++;                      // Platz für NULL-Zeichen hinzufügen
    char *Buffer = new char[Size];  // Buffer als dynamische Variable definieren
    Edit1->GetTextBuf(Buffer,Size); // Edit1.Text in Buffer ablegen
    mini = atof(Buffer);
    delete Buffer;
    if (/*(range>0) && */(rows>0) && (Form2->Visible))
    {
        Form2->PaintBox1Click(0);
    }
}
//---------------------------------------------------------------------------
void __fastcall TImageForm::Edit3Change(TObject *Sender)
{
    int Size = Edit3->GetTextLen(); // Länge des Strings in Edit3 ermitteln
    Size++;                      // Platz für NULL-Zeichen hinzufügen
    char *Buffer = new char[Size];  // Buffer als dynamische Variable definieren
    Edit3->GetTextBuf(Buffer,Size); // Edit3.Text in Buffer ablegen
    maxi = atof(Buffer);
    delete Buffer;
    if (/*(range>0) && */(rows>0) && (Form2->Visible))
    {
        Form2->PaintBox1Click(0);
    }
}
//---------------------------------------------------------------------------
void __fastcall TImageForm::Button3Click(TObject *Sender) // Delete Selected file(s)
{
  AnsiString filenam;
  int lastsel;
  for (int i = 0; i < FileListBox1->Items->Count; i++)
  {
     if (FileListBox1->Selected[i])
     {
        filenam = FileListBox1->Items->Strings[i];//FileListBox1->FileName;
        std::remove(filenam.c_str());
        lastsel = i-1;
     }
  }
  FileListBox1->Update();
  if (lastsel == -1)
  {
     lastsel++;
     FileListBox1->Selected[lastsel] = true;
  }
  else
  {
     FileListBox1->Selected[lastsel] = true;
  }

  FileExt = ExtractFileExt(FileListBox1->FileName);
  FileExt = UpperCase(FileExt);

  if ( !strcmp(FileExt.c_str(),".TXT") || !strcmp(FileExt.c_str(),".PRN") || !strcmp(FileExt.c_str(),".CSV") )
  {
    ReadFile(FileListBox1->FileName.c_str()); // read file into buffer
   // Form2->Show(); // show before plott
   // Form2->PaintBox1Click(0);
  }
 }
//---------------------------------------------------------------------------
void __fastcall TImageForm::Button4Click(TObject *Sender)
{
   FileListBox1->Update();
   DirectoryListBox1->Update();
}
//---------------------------------------------------------------------------
void __fastcall TImageForm::FormClose(TObject *Sender,

      TCloseAction &Action)
{
    delete [] act;
    delete [] Icold;
}
//---------------------------------------------------------------------------
void __fastcall TImageForm::Button1Click(TObject *Sender)
{
   Form2->FormClick(0);        
}
//---------------------------------------------------------------------------
void __fastcall TImageForm::CheckBox1Click(TObject *Sender)
{
   ReadFile(FileListBox1->FileName.c_str()); // read file into buffer
   Form2->PaintBox1Click(0);
}
//---------------------------------------------------------------------------
void __fastcall TImageForm::CheckBox2Click(TObject *Sender)
{
   ReadFile(FileListBox1->FileName.c_str()); // read file into buffer
   Form2->PaintBox1Click(0);
}
//---------------------------------------------------------------------------

void __fastcall TImageForm::Edit4Change(TObject *Sender)
{
    int Size = Edit4->GetTextLen(); // Länge des Strings in Edit1 ermitteln
    Size++;                      // Platz für NULL-Zeichen hinzufügen
    char *Buffer = new char[Size];  // Buffer als dynamische Variable definieren
    Edit4->GetTextBuf(Buffer,Size); // Edit1.Text in Buffer ablegen
    Fmin = atof(Buffer);
    delete Buffer;
    Rmin = 0;
    for (int i=0; i<rows; i++)
    {
      if (act[i]  <= Fmin) Rmin = i;
      if (act[i]  <= Fmax) Rmax = i;
    }

    if (/*(range>0) && */(rows>0) && (Form2->Visible))
    {
        Form2->PaintBox1Click(0);
    }
}
//---------------------------------------------------------------------------

void __fastcall TImageForm::Edit5Change(TObject *Sender)
{
    int Size = Edit5->GetTextLen(); // Länge des Strings in Edit1 ermitteln
    Size++;                      // Platz für NULL-Zeichen hinzufügen
    char *Buffer = new char[Size];  // Buffer als dynamische Variable definieren
    Edit5->GetTextBuf(Buffer,Size); // Edit1.Text in Buffer ablegen
    Fmax = atof(Buffer);
    delete Buffer;
    Rmax = rows;
    for (int i=0; i<rows; i++)
    {
      if (act[i]  <= Fmin) Rmin = i;
      if (act[i]  <= Fmax) Rmax = i;
    }

    if (/*(range>0) && */(rows>0) && (Form2->Visible))
    {
        Form2->PaintBox1Click(0);
    }
}
//---------------------------------------------------------------------------

