//---------------------------------------------------------------------------
#include <vcl.h>
#include <io.h>
#include <shellapi.h>
#pragma hdrstop

#include "Frm_MainSheet.h"
#include "Frm_Copyright.h"
#include "Frm_ErrLog.h"
#include "Frm_GetPwd.h"
#include "Frm_Help.h"
#include "Frm_Progress.h"
#include "Frm_Results.h"
#include "Frm_Splash.h"
#include "Frm_Wait4Jobs.h"
#include "param_fix.h"
#include "localiser/locale_set.h"

#include "../sources.cc/cp_lib/cptran.h"
#include "../sources.cc/images/image.h"
#include "RegShare.h"
#ifdef _REENTRANT
 #include "../sources.cc/jobs/jobs.h"
#endif
#include "UnitCommon.h"


RegisterInfo ShareVer;

#define STDOUT 1

//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TFrm_Main *Frm_Main;

//---------------------------------------------------------------------------
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

//Non standard include files
#include <common.h>
#include <stringa.h>
#include <lists.h>
#include "../sources.cc/wp2latex.h"
#include "raster.h"


extern FILE *wpd, *table;
extern FILE *strip, *logg, *err;
extern FILE *latex;

extern string wpd_filename, strip_filename, table_filename, latex_filename,
       log_filename;
extern string wpd_password;

extern string force, FORCE;
extern list ImgInputDirs;

static const char CONV_FILE_KEY[] = "ConvFile";
static const char IMG_DIR_KEY[] = "ImgDir";


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

/// Definition of methods of the Percentor class.
void Percentor::Actualise(long NewValue)
{
int NewPercent;
MSG msg;

 while(PeekMessage(&msg,NULL,NULL,NULL,PM_REMOVE))
      {
      TranslateMessage(&msg);
      DispatchMessage(&msg);
      }

 //if(!displayed) return;

 if(EndValue==StartValue) NewPercent=100;
	else NewPercent = (int)floor(
	     (float)(NewValue - StartValue) / (EndValue - StartValue) * 100 + 0.5);

 if(NewPercent!=CurrentPercent)
	{
	CurrentPercent = NewPercent;
        Progress->ProgressBar1->Position = NewPercent;
//	Show();
	}
}


void Percentor::Hide(void)
{
 if(displayed)
	{
	// printf("\b\b\b\b");
	}
 displayed = false;
}


void Percentor::Init(long Start, long End, const char *text)
{
 StartValue = Start;
 EndValue = End;
 if(text) Progress->SetLabel(text);
 Progress->Refresh();
}


Percentor::Percentor(void)
{
  displayed = false;
  CurrentPercent = -1;
  Progress->ProgressBar1->Position = 0;
  Progress->Show();
  Progress->ReferenceCount++;
}


Percentor::~Percentor(void)
{
  Progress->ReferenceCount--;
  Progress->Hide();
}


void Percentor::SetPercent(int NewPercent)
{
 if(NewPercent==CurrentPercent && displayed) return;
 CurrentPercent = NewPercent;
 Progress->ProgressBar1->Position = NewPercent;
// Show();
}


void Percentor::Show(void)
{
// printf(displayed?"\b\b\b\b%3d%%":"%3d%%",CurrentPercent);
 displayed = true;
}


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


/// Check validity of options.
static void CheckOptions(void)
{
 if(LaTeX_Version<0x300)		//disable colors for LaTeX 2.09
   {
   if(colors>true)
     if(err!=NULL)
	fprintf(err,_("Warning: Color style is available only for LaTeX 2e !\n"));
   colors=-1;
   }
}


void CheckCompiler(void)
{
if((sizeof(uint8_t)!=1)||(sizeof(uint16_t)!=2)||(sizeof(uint32_t)!=4)||
   (sizeof(int8_t)!=1)||(sizeof(int16_t)!=2)||(sizeof(int32_t)!=4))
	{
//	Heading();
	ShowMessage(_("\nFatal: Code was badly compiled. Check typedfs.h !!!!!"));
	}
}

/** This function prints text console WP2LaTeX heading. */
void Heading(void)
{
static boolean printed=false;
char *ShareStatus;

// if(Verbosing >= 1 && !printed)
 if(Frm_Splash==NULL) return;

 if(!printed)
     {
     Frm_Splash->Lbl_Version->Caption = VersionWP2L;
     Frm_Splash->ShowModal();
     printed = true;
     }
}


/** This function handles error situation. */
void RunError(int ExitCode, const char *s, const void *arg)
{
MSG msg;
string str;

 switch(ExitCode)
    {
    case -2:   ExitCode=0;break;           /* Silently exit program */
    case -1:   if(ErrLog==NULL) break;
               if(!(ErrLog->Visible))
                        {
                        ErrLog->Show();
                        ErrLog->Repaint();
                        }
               fflush(FileOut);
               try
                 {
                 while(ErrLog->Visible)
                  {
                  while(PeekMessage(&msg,NULL,NULL,NULL,PM_REMOVE))
                        {
                        TranslateMessage(&msg);
                        DispatchMessage(&msg);
                        }
                  }
                 }
               catch(...) {}
               break;
    case 0:    str=_("Conversion completed.\n\n");
	       break;
    case 0x2:  str.printf(_("Error: File %s not found.\n"),chk(s));
	       break;
    case 0x3:  str=_("Error: Path not found.\n");
	       break;
    case 0x4:  str.printf(_("\nError: File %s can not be created."),chk(s));
	       break;
    case 0x6:  str.printf(_("Error: Temporary file %s cannot be created!\n"),chk(s));
	       break;
    case 0x10: str=_("Info: Program was aborted.\n");
	       break;
    case 0x15: str=_("Info: Please report this situation to enable further developping WP2LaTeX.\n");
	       break;
    case 0x20: str=_("Error: Output device is full.\n");
	       break;
    case 0x8B: str=_("Fatal: Program Error. Write full bug report.\n");
	       break;
    case 0x200:str=_("Error: No filename entered!\n");
	       break;
    case 0x201:str.printf(_("Error: File \"%s\" is not a WordPerfect document!\n"),chk(s));
	       break;
    case 0x202:str=_("Error: Unsupported format ");
	       if(arg)
		 {
		 const FFormatDetect *FFD = (const FFormatDetect *)arg;
		 str.cat_printf("(%s",FFD->DocumentType);
		 if(FFD->DocVersion!=0)
		   str.cat_printf(" r%d.%d",FFD->DocVersion>>8,FFD->DocVersion & 0xFF);
		 str += ")";
		 }
	       break;
    case 0x203:str=_("Error: Sorry, I have no idea how to decrypt this file!\n");
	       break;
    case 0x204:str=_("Fatal: Memory exhausted!\n");
	       break;
    }

 if(!str.isEmpty())
    {
    str = replacesubstring(str,"%s",s);
    ShowMessage((AnsiString)str());
    }

                //close all opened files
 if(wpd != NULL)   fclose(wpd);     	  wpd = NULL;
 if(strip != NULL)
	{
	fclose(strip);			  strip = NULL;
#ifndef DEBUG
	if(EraseStrip) unlink(strip_filename);
#endif
	}
 if(table != NULL)
	{
	fclose(table);			 table = NULL;
#ifndef DEBUG
	if(EraseStrip) unlink(table_filename);
#endif
	}
 if(latex_filename != '-')
      if (latex != NULL) fclose(latex);   latex = NULL;
 if(logg != NULL)
	{
	if(!ExitCode)
	  fprintf(logg,_("\n!!!! Fatal Exit No %d!!!!\n"),ExitCode);
	fclose(logg);		          logg = NULL;
	}

 if(ExitCode==2 || ExitCode==0x202) return;

                //terminate application
 TErrLog::TerminateWorker(800);

 Application->Terminate();
 //abort();  //exit don't work????
}


/// Convert checkbox state to package allow trigger.
int Buttonify(TCheckBox *chk)
{
 if(chk==NULL) return -1;
 if(chk->Checked) return 0;
 return -1;
}



/** Ask user to get log file - not working, only stub. */
void GetLogFileName(string & LogFile)
{
AnsiString s =
 InputBox("WP2LaTeX", _("Enter filename for logs:"),
     (LogFile()==NULL) ? "logs.txt" : LogFile());
 if(s.Length() > 0) LogFile = s.c_str();
}


void ShowHelp(void)
{
 if(Frm_Help1 == NULL) Application->CreateForm(__classid(TFrm_Help1), &Frm_Help1);
 Frm_Help1->ShowModal();
}

void ShowCopyright(void)
{
 if(Frm_Copyright1)
     Frm_Copyright1->ShowModal();
}


/** This function asks waits for user response Yes, Ino or Ignore. */
char YesNoIgnore(const char *str)
{
  switch(MessageBoxFix((char *)str, "WP2LaTeX", MB_ABORTRETRYIGNORE, TFrm_Main::getMainFormHandle()))
  {
    case IDRETRY:
    case IDYES:    return('Y');
    case IDABORT:
    case IDNO:     return('N');
    case IDIGNORE: return('I');
  }
return('?');
}


/** This function asks user to enter password. */
void ObtainPassword(string & password)
{
  password = "";
  if(GetPassword!=NULL)
     {
     GetPassword->ShowModal();
     password = GetPassword->Edit1->Text.c_str();
     }
}


///**************************************************************


__fastcall TFrm_Main::TFrm_Main(TComponent* Owner): TForm(Owner)
{
 HELP = new TCMSDNHelp();
}


//---------------------------------------------------------------------------
__fastcall TFrm_Main::~TFrm_Main()
{
  if(HELP)
    {
    delete HELP;
    HELP = NULL;
    }
}


//---------------------------------------------------------------------------
void __fastcall TFrm_Main::TabControl1Change(TObject *Sender)
{
switch(TabControl1->TabIndex)
   {
   case 0:panel1->Visible=1;
          Panel2->Visible=0;
	  Panel3->Visible=0;
	  Panel4->Visible=0;
	  break;
   case 1:Panel2->Visible=1;
	  panel1->Visible=0;
          Panel3->Visible=0;
	  Panel4->Visible=0;
	  break;
   case 2:Panel3->Visible=1;
          panel1->Visible=0;
	  Panel2->Visible=0;
	  Panel4->Visible=0;
	  break;
   case 3:Panel4->Visible=1;
	  panel1->Visible=0;
	  Panel2->Visible=0;
	  Panel3->Visible=0;
	  break;
   }
}


//---------------------------------------------------------------------------
void __fastcall TFrm_Main::Button1Click(TObject *Sender)
{
 OpenDialog1->FileName = Edit_InputFile->Text;
 if(OpenDialog1->Execute())
   Edit_InputFile->Text = OpenDialog1->FileName;
}


//---------------------------------------------------------------------------
void __fastcall TFrm_Main::Button2Click(TObject *Sender)
{
 SaveDialog1->FileName=Edit2->Text;
 if(SaveDialog1->Execute())
   Edit2->Text=SaveDialog1->FileName;
}


//---------------------------------------------------------------------------
void __fastcall TFrm_Main::Button3Click(TObject *Sender)
{
 SaveDialog1->FileName=Edit3->Text;
 if(SaveDialog1->Execute())
   Edit3->Text=SaveDialog1->FileName;
}


//---------------------------------------------------------------------------
void __fastcall TFrm_Main::Btn_ExitClick(TObject *Sender)
{
 TErrLog::TerminateWorker();
 StoreSettings();
 Application->Terminate();
}


//------Main conversion procedure--------------------------------------------
void __fastcall TFrm_Main::Btn_ConvertClick(TObject *Sender)
{
TconvertedPass1 *cqPass1 = NULL;

  Btn_Convert->Enabled = false;
  UnknownCharacters = UnknownObjects = CorruptedObjects = 0;
  if(FileOut!=NULL)
     {
     if(!ErrLog->Visible)
	   {                  //Errlog must be painted here, otherwise it is not fully initialised
  	   ErrLog->Show();
 	   ErrLog->Hide();
 	   ErrLog->Repaint();
	   ErrLog->HELP=HELP;
 	   }
     err=FileOut;
     fputc(254,FileOut);
     // fprintf(err,"\nConversion started ...\n");
     }

  Widget2Setup();

  UpdateFigDir();
  CheckOptions();

  try {
      if ( (wpd = fopen(wpd_filename, "rb"))   == NULL )
		{RunError(2,wpd_filename);goto finish;}   //this is sometimes crashing - I don't know why
      }
  catch(...) {RunError(2,wpd_filename);goto finish;}

  CheckFileFormat(wpd,FilForD);
  cqPass1 = GetConverter(FilForD.Converter);

  if(cqPass1==NULL)
    {
    RunError(0x202);  /* unsupported WP version */
    goto finish;
    }

  if((strip = fopen(strip_filename, "w")) == NULL)
	{RunError(2,strip_filename);goto finish;}
  if((table = fopen(table_filename, "w+b")) == NULL)
	{RunError(2,table_filename);goto finish;}
  logg = NULL;
  if(!log_filename.isEmpty())
    {
    if(wpd_filename == log_filename)
      {
      if(err)
        fprintf(err,_("\nError: Log filename equals document filename. This could erase original document!"));
      log_filename.erase();
      }
    else
      {
      if((logg = fopen(log_filename, "w")) == NULL )
	{
	if(err)
	  fprintf(err,_("\nWarning: Cannot open log file %s ..."),log_filename());
	}
	else fprintf(logg,_("%% log file for converted file %s, WP ver %d.%d\n"
			    "%% conversion program WP2LaTex v. %s from %s.\n"),
			   wpd_filename(),FilForD.DocVersion >> 8,FilForD.DocVersion & 0xFF, VersionWP2L, VersionDate);
      }
    }

  cqPass1->InitMe(wpd, table, strip, logg, err);
  cqPass1->Convert_first_pass();
  fflush(err);

  if(wpd!=NULL)
      {
      fclose(wpd);
      wpd = NULL;
      }
  if(cqPass1!=NULL)	// First pass convertor is no longer needed.
      {
      delete(cqPass1);
      cqPass1 = NULL;
      }

  if(strip!=NULL)
      {
      if(fflush(strip)) {RunError(0x20,"");goto finish;} //The RunError procedure will erase strip in this case
      if(fclose(strip)) {strip = NULL;RunError(0x20,"");goto finish;}
      strip = NULL;
      }
  if(table!=NULL)
      {
      if(fflush(table)) RunError(0x20,""); //The RunError procedure will erase table in this case
      if(fclose(table)) {table = NULL;RunError(0x20,"");goto finish;}
      table = NULL;
      }

  if(logg!=NULL) fprintf(logg,_("\n%% pass1 finished going to pass2\n\n"));

  if((strip=fopen(strip_filename, "r")) == NULL)
	{RunError(2,strip_filename);goto finish;}
  if(latex_filename == '-') latex=stdout;
      else if((latex=fopen(latex_filename, "w"))   == NULL )
		 {RunError(2,latex_filename);goto finish;}
  if( (table = fopen(table_filename, "r+b")) == NULL )
	{RunError(2,table_filename);goto finish;}

  Convert_second_pass(strip, table, latex, logg, err);
  fflush(err);

  if(strip != NULL) fclose(strip);   strip = NULL;
  if(table != NULL) fclose(table);   table = NULL;
  if(latex_filename != '-')
      if(latex != NULL)
	{
	if(fclose(latex))
          {latex = NULL;RunError(0x20,"");goto finish;}
	}
  latex = NULL;

  if(logg != NULL)
	{
	fprintf(logg,_("\n%% pass2 finished\n"
		      "%%  There were %ld unconverted characters.\n"
		      "%%  There were %ld unrecognized/ignored objects.\n"),UnknownCharacters,UnknownObjects);
	if(CorruptedObjects>0)
	    fprintf(logg,_("%%  There were %ld corrupted objects.\n"),CorruptedObjects);
	if(fclose(logg))
	       fprintf(err,_("\nError: Log file is not completely written."));
        logg = NULL;
	}

#ifdef _REENTRANT
  if(JobBase::JobCount>0)
  {
    FinishJobs(50);
    if(JobBase::JobCount>0)
      Frm_WaitForJobs->ShowModal();
  }
#endif


/* Delete auxillary files */
  if(EraseStrip)
     {
#ifndef DEBUG
     unlink(strip_filename);
     unlink(table_filename);
#endif
     }

  if(FileOut)
    {
    fputc(254,FileOut);
    fflush(FileOut);
    }

 fflush(stdout);                //when stdout is not flushed here, program sometimes crashes at the end
 fflush(stderr);
 Btn_Convert->Enabled = true;
 FrmResults->Label2->Caption = wpd_filename();
 FrmResults->Label4->Caption=latex_filename();
 FrmResults->HELP = HELP;
 if(Verbosing>0) FrmResults->ShowModal();
 return;

finish:
 fflush(stdout);                //when stdout is not flushed here, program sometimes crashes at the end
 fflush(stderr);
 if(logg != NULL)
   {fclose(logg); logg=NULL;}
 Btn_Convert->Enabled=true;
 return;
}


/// This function prints text console WP2LaTeX heading.
void __fastcall TFrm_Main::FormCreate(TObject *Sender)
{
  latex = NULL;		/* The output Latex file */
  strip = NULL;		/* The temporary file rough conversion */
  table = NULL;		/* The temporary file with line informations */
  wpd   = NULL;		/* The input WP file */
  logg  = NULL;		/* The output log file */
  err   = FileOut;	/* The output for error messages */

	/* Default initialization */
  Verbosing = 1;
  TexChars = false;
  OutCodePage = 0;		/*unknown - no 8 bit code generated*/
  WPcharset = 1;	/*common char set 1*/
  ExtendedCheck = true;	/*true*/
  FixSpaces = false;
  OptimizeSection = true;

#if defined(__UNIX__) & !defined(DEBUG)
  HookSignals();
#endif
#ifdef DEBUG
  log_filename="default.log";
#endif

  CheckCompiler();

  CommandLine(argc,argv);

#ifdef __gettext__
  InitGettext("wp2latex");

  if(argc>1 && argv!=NULL)
    for(int i=1; i<argc; i++)
      if(!StrCmp(argv[i], "-dumpstrings")||!StrCmp(argv[i], "-DumpStrings"))
      {
        goto SKIP_TRANSLATION;
      }

  FixEnv();		//setup LANGUAGE according to LCID if it is not set yet
  CheckGettext(argv==NULL?NULL:*argv,"wp2latex");
  TranslateStrings(this);

SKIP_TRANSLATION:
#endif /* __gettext__ */

 //const char *pokus = _("Conversion from");

 TabControl1->TabIndex = 0;
 panel1->Visible = 1;
 Panel2->Visible = 0;
 Panel3->Visible = 0;
 Panel4->Visible = 0;
 panel1->BevelOuter = bvNone;
 Panel2->BevelOuter = bvNone;
 Panel3->BevelOuter = bvNone;
 Panel4->BevelOuter = bvNone;

 	// Build a list of available code page convertors.
 Cmb_UserWpCharset->Items->Clear();
 Cmb_UserWpCharset->Items->Add("None");
 CpTranslator *Ptrn = CpTranslator::getFirst();
 while(Ptrn!=NULL)
     {
     if(Ptrn->number()<=256)
     {
       const char *ToIntern = StrStr(Ptrn->Name,"TOinternal");
       if(ToIntern)
       {
         AnsiString str(Ptrn->Name,ToIntern-Ptrn->Name);
         if(str!="html")
           Cmb_UserWpCharset->Items->Add(str);
       }
     }
     Ptrn = Ptrn->getNext();
     }
}


//---------------------------------------------------------------------------
void __fastcall TFrm_Main::Btn_HelpClick(TObject *Sender)
{
  if(HELP)
    HELP->showChm(HelpFile);
}


//---------------------------------------------------------------------------
void __fastcall TFrm_Main::Rad_GraphicXDblClick(TObject *Sender)
{
  Rad_GraphicX->Checked = false;
}


//---------------------------------------------------------------------------
void __fastcall TFrm_Main::Rad_InputPSDblClick(TObject *Sender)
{
  Rad_InputPS->Checked = false;
}


//---------------------------------------------------------------------------
void __fastcall TFrm_Main::Rad_graphicsDblClick(TObject *Sender)
{
  Rad_graphics->Checked = false;
}


//---------------------------------------------------------------------------
void __fastcall TFrm_Main::Rad_EpsFigDblClick(TObject *Sender)
{
  Rad_EpsFig->Checked = false;
}


//---------------------------------------------------------------------------
int OutputFile=2;
void __fastcall TFrm_Main::Edit_InputFileChange(TObject *Sender)
{
int p;

 if(Edit2->Text=="") OutputFile=0;
 if(OutputFile>=2) return;

 wpd_filename = Edit_InputFile->Text.c_str();
 p=length(wpd_filename);
 Btn_Convert->Enabled = p>0;
 while(p>0)
	 {
	 if(wpd_filename[p]=='.') break;
	 if((wpd_filename[p]=='/')||(wpd_filename[p]=='\\'))
		{
		p=length(wpd_filename);
		break;
		}
	 p--;
	 }
    if(p<=0) p=length(wpd_filename); //no extension

    latex_filename=copy(wpd_filename,0,p) + ".tex";
    Edit2->Text=latex_filename();
    OutputFile = 1;
}


//---------------------------------------------------------------------------
void __fastcall TFrm_Main::Edit2Change(TObject *Sender)
{
 OutputFile = 2; /* stop copy of filename */
}


//---------------------------------------------------------------------------
void __fastcall TFrm_Main::FormClose(TObject *Sender, TCloseAction &Action)
{
 TErrLog::TerminateWorker();
}


//---------------------------------------------------------------------------
void __fastcall TFrm_Main::FormActivate(TObject *Sender)
{
FFormatTranslator *FFTRan;
static bool Activated = false;

  if(Frm_Splash!=NULL) Frm_Splash->ActivateMe=this;

  if(Activated) return;
  Activated=true;

  if(FileOut!=NULL && ErrLog!=NULL)
        {
        if(!ErrLog->Visible)
 	   {                  //Errlog must be painted here, otherwise it is not fully initialised
  	   ErrLog->Show();
 	   ErrLog->Hide();
 	   ErrLog->Repaint();
           //Activated4=1;
 	   }
        //dup2(PipeHandles[1],STDOUT);
        }

 Sys_Variable();
 ParseRegistry();

#ifdef __gettext__
  if(argc>1 && argv!=NULL)
    for(int i=1; i<argc; i++)
      if(!StrCmp(argv[i], "-dumpstrings")||!StrCmp(argv[i], "-DumpStrings"))
      {
        if(Frm_Help1 == NULL) Application->CreateForm(__classid(TFrm_Help1), &Frm_Help1);
       
	DumpStrings(9, this,ErrLog,FrmResults,Frm_Splash,GetPassword,Progress,
		       Frm_Help1,Frm_Copyright1,Frm_WaitForJobs);
        Application->Terminate();
        return;
      }
#endif
 //CommandLine(argc,argv);
#ifdef __gettext__
  //FixEnv();		//setup LANGUAGE according to LCID if it is not set yet
  //CheckGettext(argv==NULL?NULL:*argv,"wp2latex");
  //TranslateStrings(this);
#endif

 Setup2Widget();

        //Show Translators in the list box
 FFTRan=FFormatTranslator::first();
 ListBox1->Items->Clear();
 Cmb_Force->Items->Clear();
 Cmb_Force->Items->Add(_("none"));
 while(FFTRan!=NULL)
   {
   ListBox1->Items->Add(FFTRan->shortkey());
   Cmb_Force->Items->Add(FFTRan->shortkey());
   FFTRan = FFTRan->next();
   }

        //show Supported Image formats:
 TImageFileHandler *LoadPicture_XXX;
 LST_Graphic->Items->Clear();
 for(LoadPicture_XXX=TImageFileHandler::first();LoadPicture_XXX!=NULL;LoadPicture_XXX=LoadPicture_XXX->next())
   {
   if(LoadPicture_XXX->LoadPicture!=NULL || LoadPicture_XXX->SavePicture!=NULL)
     {
     string ss(LoadPicture_XXX->extension());
     ss+=" [";
     if(LoadPicture_XXX->LoadPicture!=NULL) ss+="R";
     if(LoadPicture_XXX->SavePicture!=NULL) ss+="W";
     ss+="]";
     LST_Graphic->Items->Add(ss());
     }
   }

 Heading();  //Show splash
}


//This procedure transfers all setup related stuff from widgets to internal wp2latex structs
void TFrm_Main::Widget2Setup(void)
{               //filenames
  wpd_filename = Edit_InputFile->Text.c_str();
  strip_filename = Edit_InputFile->Text.c_str();
  strip_filename += ".STR";
  table_filename = Edit_InputFile->Text.c_str();
  table_filename += ".TBL";
  latex_filename = Edit2->Text.c_str();
  RelativeFigDir = Edit_ImgPath->Text.c_str();

  log_filename = Edit3->Text.c_str();
#ifdef DEBUG
  if(log_filename=="")
	log_filename = "default.log";
#endif
  RelativeFigDir = Edit_ImgPath->Text.c_str();

		//additional packages
  InputPS = -1;
  Accents = Buttonify(Chk_accents);
  Amssymb = Buttonify(Chk_AMSSymb);
  Bbm = Buttonify(Chk_BBM);
  colors = Buttonify(Chk_Color);
  CPStyles = Buttonify(Chk_CpStyles);
  Cyrillic = Buttonify(Chk_cyrillic);
  arabtex = Buttonify(Chk_ArabTeX);
  mxedruli = Buttonify(Chk_mxedruli);
  if(Rad_EpsFig->Checked) InputPS = 4;              //EpsFig
  FancyHdr = Buttonify(Chk_FancyHDR);
  fontenc = Buttonify(Chk_FontencT1);
  cjHebrew = Buttonify(Chk_Hebrew);
  if(Rad_GraphicX->Checked) InputPS = 2;        //GraphicX
  if(Rad_graphics->Checked) InputPS = 8;        //Graphics
  LaTeXsym = Buttonify(Chk_LatexSym);
  LongTable = Buttonify(Chk_LongTable);
  MakeIdx = Buttonify(Chk_MakeIDX);
  pifont = Buttonify(Chk_pifont);
  Rsfs = Buttonify(Chk_RSFS);
  TIPA = Buttonify(Chk_TIPA);
  Ulem = Buttonify(Chk_ulem);
  Wasy = Buttonify(Chk_Wasy);
  Scalerel = Buttonify(Chk_Scalerel);
  if(Rad_InputPS->Checked) InputPS = 0;        //Input PS

                //miscellaneous features
  SaveWPG = Chk_ExtractWPG->Checked;
  ExtendedCheck = Chk_SafeMode->Checked;
  Verbosing = 1;
  if(Chk_Silent->Checked) Verbosing = 0;
  CheckOversize = 0;
  if(Chk_ShrinkImages->Checked) CheckOversize = 1;

  TABs = Chk_IgnoreTabs->Checked;
  TexChars = Chk_TeX_chars->Checked;
  FixSpaces = Chk_FixSpaces->Checked;

  if(Cmb_OutputCodepage->Text=="" || Cmb_OutputCodepage->Text=="none" || Cmb_OutputCodepage->Text=="None")
	OutCodePage = 0;
  else
    {
    int i;
    for(i=0; i<sizeof(OutCodepages)/sizeof(OutCodePage); i++)
      {
      if(Cmb_OutputCodepage->Text == OutCodepages[i].Name)
        {
        //ShowMessage((AnsiString)"supported codepage"+OutCodepages[i].Name);
        OutCodePage = OutCodepages[i].Id;
        if(OutCodePage==UTF8)
          {
          CPStyles = true;
          Convert2Target = GetTranslator("internalTOunicode");
          }
        break;
        }
      }
    if(i>=sizeof(OutCodepages)/sizeof(OutCodePage))
      ShowMessage((AnsiString)_("Unsupported output codepage ") + Cmb_OutputCodepage->Text);
    }

  if(ComboBox2->Text=="Charset 1") WPcharset = 1;
  else if(ComboBox2->Text=="Charset CZ" || ComboBox2->Text=="Charset CS")
		  WPcharset = 2;
  else ShowMessage((AnsiString)_("Unsupported WP charset")+ComboBox2->Text);

  if(Cmb_LatexVer->Text=="LaTeX 2")
	 {
	 LaTeX_Version=0x209;
	 Amssymb=-1;
	 if(Columns==1) Columns=0;
	 }
  else if(Cmb_LatexVer->Text=="LaTeX 3 (2e)") LaTeX_Version=0x300;
  else ShowMessage((AnsiString)_("Unsupported output format")+Cmb_LatexVer->Text);

  if(Cmb_Force->Text!="None")
    {
    force = Cmb_Force->Text.c_str();
    //ShowMessage((AnsiString)"Cannot force format "+ComboBox4->Text);
    }

  if(Cmb_UserWpCharset->Text=="" || Cmb_UserWpCharset->Text=="None" || Cmb_UserWpCharset->Text=="none")
    {
    UserWPCharSet = NULL;
    }
  else
    {
    string CFSconvertor(Cmb_UserWpCharset->Text.c_str());
    CFSconvertor += "TOinternal";
    UserWPCharSet = GetTranslator(CFSconvertor());
    if(UserWPCharSet==NULL)
      ShowMessage((AnsiString)_("Warning, cannot get code page translator ")+Cmb_UserWpCharset->Text);
    }
}


/** Transfer setup settings to widgets state. */
void TFrm_Main::Setup2Widget(void)
{
 Edit_InputFile->Text = wpd_filename();
 Edit2->Text = latex_filename();
 Edit3->Text = log_filename();
 Edit_ImgPath->Text = RelativeFigDir();

		//additional LaTeX packages
 Chk_accents->Checked = Accents>=0;
 Chk_AMSSymb->Checked = Amssymb>=0;
 Chk_BBM->Checked = Bbm>=0;
 Chk_Color->Checked = colors>=0;
 Chk_CpStyles->Checked = CPStyles>=0;
 Chk_cyrillic->Checked = Cyrillic>=0;
 Chk_ArabTeX->Checked = arabtex>=0;
 Chk_mxedruli->Checked = mxedruli>=0;
 Rad_EpsFig->Checked = InputPS==4;             //EpsFig
 Chk_FancyHDR->Checked = FancyHdr>=0;
 Chk_Hebrew->Checked = cjHebrew>=0;
 Rad_GraphicX->Checked = InputPS==2;       //GraphicX
 Chk_LatexSym->Checked = LaTeXsym>=0;
 Chk_LongTable->Checked = LongTable>=0;
 Chk_MakeIDX->Checked = MakeIdx>=0;
 Chk_pifont->Checked = pifont>=0;
 Chk_RSFS->Checked = Rsfs>=0;
 Chk_TIPA->Checked = TIPA>=0;
 Chk_ulem->Checked = Ulem>=0;
 Chk_Wasy->Checked = Wasy>=0;
 Rad_InputPS->Checked = InputPS==0;	   //Input PS
 Chk_FontencT1->Checked = fontenc>=0;
 Rad_graphics->Checked = InputPS==8;       //Graphics
 Chk_Scalerel->Checked = Scalerel>=0;

	       //miscellaneous features
 Chk_Silent->Checked = Verbosing<1;
 Chk_ExtractWPG->Checked = SaveWPG;
 Chk_SafeMode->Checked = ExtendedCheck;

 Chk_Silent->Checked = Verbosing<=0;

 Chk_IgnoreTabs->Checked = TABs;
 Chk_TeX_chars->Checked = TexChars;
 Chk_FixSpaces->Checked =  FixSpaces;
 Chk_ShrinkImages->Checked = CheckOversize > 0;

 for(int i=0; i<sizeof(OutCodepages)/sizeof(OutCodePage); i++)
   {
   if(OutCodePage == OutCodepages[i].Id)
     {
     Cmb_OutputCodepage->Text = OutCodepages[i].Name;
     break;
     }
   }
}


/** This procedure saves a current form settings into a registry. */
void TFrm_Main::StoreSettings(void)
{
long ret;
HKEY Key, ParentKey;
const char *KeyData="Software\\WP2LaTeX";

 ret = RegOpenKeyEx(HKEY_CURRENT_USER,KeyData,0,KEY_ALL_ACCESS,&Key);
 if(ret!=ERROR_SUCCESS)
   {
   if(RegOpenKeyEx(HKEY_CURRENT_USER,"Software",0,KEY_ALL_ACCESS,&ParentKey)!=ERROR_SUCCESS)
      return;
   ret= RegCreateKey(ParentKey,"WP2LaTeX",&Key);
   RegCloseKey(ParentKey);
   if(ret!=ERROR_SUCCESS) return;
   }

 ret = Edit_InputFile->Text.Length();
 RegSetValueEx(Key, CONV_FILE_KEY, NULL, REG_SZ, Edit_InputFile->Text.c_str(), ret);

 ret = Edit_ImgPath->Text.Length();
 if(ret>0 && AbsolutePath(Edit_ImgPath->Text.c_str())==0)
   RegSetValueEx(Key,IMG_DIR_KEY, NULL, REG_SZ, Edit_ImgPath->Text.c_str(), ret);
 else
   RegSetValueEx(Key,IMG_DIR_KEY, NULL, REG_SZ, ".", 1);

 RegCloseKey(Key);
}


void TFrm_Main::ParseRegistry(void)
{
long ret;
HKEY Key,ParentKey;
const char *KeyData="Software\\WP2LaTeX";
DWORD buflen,type;
char *Bufik;
TRegInfo RI;

 ret = RegOpenKeyEx(HKEY_CURRENT_USER,KeyData,0,KEY_ALL_ACCESS,&Key);
 if(ret!=ERROR_SUCCESS)
   {
   if(RegOpenKeyEx(HKEY_CURRENT_USER,"Software",0,KEY_ALL_ACCESS,&ParentKey)!=ERROR_SUCCESS)
      return;
   ret=RegCreateKey(ParentKey,"WP2LaTeX",&Key);
   RegCloseKey(ParentKey);
   if(ret!=ERROR_SUCCESS) return;
   }

 buflen = 2048;
 if(RegQueryValueEx(Key,CONV_FILE_KEY,NULL,&type,NULL,&buflen)==ERROR_SUCCESS)
   {
   Bufik = (char *)malloc(buflen+1);
   if(Bufik!=NULL)
     {
     Bufik[buflen] = 0;
     if(RegQueryValueEx(Key,CONV_FILE_KEY,NULL,&type,Bufik,&buflen)==ERROR_SUCCESS)
       {
       wpd_filename = Bufik;
       }
     free(Bufik);
     }
   }

 if(RegQueryValueEx(Key,IMG_DIR_KEY,NULL,&type,NULL,&buflen)==ERROR_SUCCESS)
   {
   Bufik = (char *)malloc(buflen+1);
   if(Bufik!=NULL)
     {
     Bufik[buflen] = 0;
     if(RegQueryValueEx(Key,IMG_DIR_KEY,NULL,&type,Bufik,&buflen)==ERROR_SUCCESS)
       {
       RelativeFigDir = Bufik;
       }
     free(Bufik);
     }
   }

 buflen = sizeof(TRegInfo);
 if(RegQueryValueEx(Key,"LicKey",NULL,&type,(unsigned char *)&RI,&buflen)==ERROR_SUCCESS)
   {
   if(RegInfo.UpdateRegInfo(&RI))
     RegSetValueEx(Key,"LicKey",NULL,REG_SZ,(unsigned char *)&RI,sizeof(TRegInfo));
   }
 else
   {
   RegSetValueEx(Key,"LicKey",NULL,REG_SZ,(unsigned char *)(TRegInfo*)&RegInfo,sizeof(TRegInfo));
   }

 RegCloseKey(Key);
}


/** Timer1 checks a proper registration code and then it turns off. */
void __fastcall TFrm_Main::Tim_SplashTimer(TObject *Sender)
{
int ShareState;
string ShareStatus;

 if(Frm_Splash!=NULL) ShareStatus=Frm_Splash->StaticText4->Caption.c_str();
 ShareStatus+=' ';
 Tim_Splash->Enabled = false;
 ShareState = RegInfo.CheckShare();
 if(Frm_Splash!=NULL)
   {
   switch(ShareState)
	{
        case 0: ShareStatus+="Royalty free granted";break;//" Expired"; break;
        case 1: ShareStatus+="Evaluation";
		char Bufik[10];
                ShareStatus+=' ';
		ShareStatus+=ltoa(RegInfo.GetEvalDays(),Bufik,10);
		break;
        case 2: ShareStatus+="FirstRun";break;
        case 3: ShareStatus+="Registered";break;
        default: ShareStatus+="Problem";ShareState=255;break;
	}
   Frm_Splash->StaticText4->Caption = ShareStatus();
   }

 if(ShareState==255)	//the licence was expired
   {
   Btn_Convert->Visible=false;
   Btn_Convert->Enabled=false;
   ShowMessage("Evaluation period of this share program expired!\n"
	       "You have 4 possibilities:\n"
	       "    1, Register wp2latex\n"
               "    2, Use commandline version\n"
               "    3, Contribute to further WP2Latex development.\n"
	       "    4, Try to upgrade to a newer version.");
   Btn_ExitClick(NULL);
   }
 else
   {
   Btn_Convert->Visible = true;
   Btn_Convert->Enabled = (Edit_InputFile->Text.Length()>0);
   }

}


//---------------------------------------------------------------------------
void __fastcall TFrm_Main::FormKeyDown(TObject *Sender, WORD &Key,
      TShiftState Shift)
{
  if(Key==VK_F1) // && Shift==0)
    HELP->showChm(HelpFile);
}


//---------------------------------------------------------------------------
void __fastcall TFrm_Main::Lbl_Wp2latexPageClick(TObject *Sender)
{
  ShellExecute(Handle, "open", "https://ftsoft.com.cz/wp2latex/wp2latex.htm",NULL,NULL, SW_SHOWNORMAL) ;
}


//---------------------------------------------------------------------------
void __fastcall TFrm_Main::Panel4Resize(TObject *Sender)
{
  Lbl_Wp2latexPage->Top = Panel4->Height - Lbl_Wp2latexPage->Height - 4;
  Lbl_Copyright->Top = Lbl_Wp2latexPage->Top - Lbl_Copyright->Height - 4;
  Btn_Help->Top = Lbl_Copyright->Top - 8;
  Btn_Splash->Top = Btn_Help->Top;

  Btn_Splash->Left = Panel4->Width - Btn_Splash->Width - 4;
  Btn_Help->Left = Btn_Splash->Left - Btn_Help->Width - 6;

  ListBox1->Height = Btn_Help->Top - ListBox1->Top - 4;
  LST_Graphic->Height = ListBox1->Height;
}


//---------------------------------------------------------------------------
void __fastcall TFrm_Main::Panel2Resize(TObject *Sender)
{
  Button1->Left = panel1->Width - Button1->Width - 6;
  Button2->Left = panel1->Width - Button2->Width - 6;
  Button3->Left = panel1->Width - Button3->Width - 6;

  Edit_InputFile->Width = Button1->Left - Edit_InputFile->Left - 8;
  Edit2->Width = Button2->Left - Edit2->Left - 8;
  Edit3->Width = Button3->Left - Edit3->Left - 8;

  Btn_Exit->Left = panel1->Width - Btn_Exit->Width - Btn_Convert->Left;
}


//---------------------------------------------------------------------------
void __fastcall TFrm_Main::FormResize(TObject *Sender)
{
  Panel2->Width = ClientWidth;
}


//---------------------------------------------------------------------------
void __fastcall TFrm_Main::Btn_SplashClick(TObject *Sender)
{
  if(Frm_Splash==NULL) Frm_Splash = new TFrm_Splash(this);
  Frm_Splash->Lbl_Version->Caption = VersionWP2L;
  Frm_Splash->ShowModal();
}

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

