﻿#include <WinAPI\WinAPI.mqh>

#define PAGE_READWRITE			0x04
#define FILE_MAP_ALL_ACCESS 0x000f001f

#define MEMCPY_MACROS(A)                                                       \
	long memcpy( const long Destination, const A &Source[], const uint Length ); \
	long memcpy( A &Destination[], const long Source, const uint Length );

class FILEMAP
{
private:
  HANDLE Handle;
  PVOID Ptr;

  string Path;

  template <typename T>
  static int Save( const PVOID Address, const T &Array[], const int Amount = WHOLE_ARRAY )
  {
    bool Res = true;
    const int Size1 = ::ArraySize(Array);
    const uint Size2 = (uint)((Amount == WHOLE_ARRAY) ? Size1 : ::MathMin(Size1, ::MathAbs(Amount))) * sizeof(T);

    return(msvcrt::memcpy(Address, Array, Size2) ? (int)Size2 : 0);
  }

public:
  FILEMAP( void ) : Handle(0), Ptr(0), Path(NULL) {}
  ~FILEMAP( void ) { this.Close(); }

  bool Close( void )
  {
    if (this.Ptr)
    {
      kernel32::UnmapViewOfFile(this.Ptr);

      this.Ptr = 0;
    }

    if (this.Handle)
    {
      kernel32::CloseHandle(this.Handle);

      this.Handle = 0;
      this.Ptr = 0;
    }

    this.Path = NULL;

    return(true);
  }

  template <typename T>
  PVOID Save( const T &Array[], const string sPath = __FILE__ )
  {
    return((this.Close() &&
            (bool)(this.Handle =kernel32::CreateFileMappingW(INVALID_HANDLE, NULL, PAGE_READWRITE, 0,
                                                             (uint)::ArraySize(Array) * sizeof(T),
                                                             this.Path = sPath)) &&
            (bool)(this.Ptr = kernel32::MapViewOfFile(this.Handle, FILE_MAP_ALL_ACCESS, 0, 0, 0)) &&
            FILEMAP::Save(this.Ptr, Array))
             ? this.Ptr : !this.Close());
  }

  PVOID Save( const string FileName, const bool Common = false, const int BlockSize = 1e6, const string sPath = __FILE__ )
  {
    this.Close();

    const int HandleFile = ::FileOpen(FileName, FILE_READ | FILE_SHARE_READ | FILE_BIN | (Common ? FILE_COMMON : 0));

    if (HandleFile != INVALID_HANDLE)
    {
      const uint Size = (uint)::FileSize(HandleFile);

      if ((bool)(this.Handle =kernel32::CreateFileMappingW(INVALID_HANDLE, NULL, PAGE_READWRITE, 0,
                                                           Size, this.Path = sPath)) &&
          (bool)(this.Ptr = kernel32::MapViewOfFile(this.Handle, FILE_MAP_ALL_ACCESS, 0, 0, 0)))
      {
        uchar Array[];

        bool Res = true;

        for (uint Pos = 0; Res && (Pos < Size);)
        {
          const uint Amount = ::FileReadArray(HandleFile, Array, 0, BlockSize);

          Res = !::IsStopped() && (FILEMAP::Save(this.Ptr + Pos, Array, Amount) == Amount);

          Pos += Amount;
        }

        if (!Res)
          this.Close();
      }
      else
        this.Close();

      ::FileClose(HandleFile);
    }

    return(this.Ptr);
  }

  template <typename T>
  int Load( T &Array[], const int Count, const int Offset = 0, const string sPath = __FILE__ )
  {
    return((((this.Path != NULL) && (this.Path == sPath)) ||
            (this.Close() &&
             (bool)(this.Handle = kernel32::OpenFileMappingW(FILE_MAP_ALL_ACCESS, 0, this.Path = sPath)) &&
             (bool)(this.Ptr = kernel32::MapViewOfFile(this.Handle, FILE_MAP_ALL_ACCESS, 0, 0, 0))))
             ? FILEMAP::Load(this.Ptr, Array, Count, Offset) : !this.Close());
  }

  template <typename T>
  static int Load( const PVOID Address, T &Array[], const int Count, const int Offset = 0 )
  {
    const int Amount = Address ? ((::ArraySize(Array) < Count) ? ::ArrayResize(Array, Count) : Count) : 0;

    return(((Amount > 0) && msvcrt::memcpy(Array, Address + Offset * sizeof(T), Amount * sizeof(T))) ? Amount : 0);
  }

  template <typename T>
  static bool IsValidAddress( const PVOID Address )
  {
    return(!kernel32::IsBadReadPtr(Address, sizeof(T)));
  }

  PVOID GetAddress( void ) const
  {
    return(this.Ptr);
  }

  string GetPath( void ) const
  {
    return(this.Path);
  }

  bool ForceFree( void )
  {
    const string sPath = this.Path;

    return((sPath != NULL) && this.Close() &&
           kernel32::CreateFileMappingW(INVALID_HANDLE, NULL, PAGE_READWRITE, 0, 0, sPath) && this.Close());
  }
};

#import "msvcrt.dll"
  MEMCPY_MACROS(uchar)
//  MEMCPY_MACROS(MqlTick)
#import