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

#include <vcl.h>
#pragma hdrstop

// BeginExample: TEncoding
// Class: SysUtils.TEncoding
// Method: Classes.THandleStream.Write
// Property: Classes.TStream.Size
// Property: Classes.TBytesStream.Bytes

// BeginCode
/*
This example reads any file and converts the encoding to UTF8.
This example uses the TBytesStream to read the files into a TBytes'
and also uses the auto_ptr construction to clean up created class
instances.

*/
#include <tchar.h>
#include <memory>       //for STL auto_ptr class
//---------------------------------------------------------------------------

#pragma argsused
int _tmain(int argc, _TCHAR* argv[])
{
  // Sample to convert a file of any encoding to UTF8.
  TEncoding *LEncoding = NULL;
  std::auto_ptr<TFileStream> LFileStream(new TFileStream("..\\Sample.txt", fmOpenRead));

  // Read file into buffer
  TBytes myBytes;
  std::auto_ptr<TBytesStream> myBytesStream(new TBytesStream(myBytes));
  myBytesStream->CopyFrom(LFileStream.get(), LFileStream->Size);

  // Identify encoding and convert buffer to UTF8
  int LOffset = TEncoding::GetBufferEncoding(myBytesStream->Bytes, LEncoding);
  if (LOffset == 0)
    return 1; // Unknown encoding, don't convert.
  myBytes = TEncoding::Convert(LEncoding, TEncoding::UTF8,
                               myBytesStream->Bytes,
							   LOffset, myBytesStream->Size-LOffset);
  // Create output file
  std::auto_ptr<TFileStream> DestFileStream(new TFileStream("..\\SampleUTF8.txt", fmCreate));

  // Write UTF8 byte order mark and buffer to output file
  TBytes LByteOrderMark;
  LByteOrderMark = TEncoding::UTF8->GetPreamble();

  // Grab preamble and write to destination
  DestFileStream->Write(&LByteOrderMark[0], LByteOrderMark.Length);

  // Write converted buffer
  DestFileStream->Write(&myBytes[0], myBytes.Length);
  return 0;
}
// EndCode
// EndExample: TEncoding
//---------------------------------------------------------------------------
