#ifndef __HP41HPIL_H__
#define __HP41HPIL_H__

#if _MSC_VER >= 1000
#pragma once
#endif

#include "HP41HpilIf.h"

class HP41;

class Hpil : public HpilIf
{
public:
  Hpil(HP41 *pHP41,flag fEnableAutoIDY = true,flag fEnableRFC = true);
  ~Hpil();

  // HP-IL 1LB6 registers
  byte HPIL_REG[9];                // 8 regs + R1W

  void EnableAutoIDY(flag fEnableAutoIDY) { m_fEnableAutoIDY = fEnableAutoIDY; }
  void EnableRFC(flag fEnableRFC) { m_fEnableRFC = fEnableRFC; }

  bool IsFrameInTransfer(DWORD dwIncr);
  bool CreateAutoIdyThread();
  void DestroyAutoIdyThread();
  void exec_perph_hpil();
  void hpil_wr(int reg, int n);

private:
  // source = calc -> controller, HPIL -> device
  enum MODE {eNone = 0, eController, eDevice};

  HP41 *m_pHP41;

  flag m_fEnableAutoIDY;
  flag m_fEnableRFC;

  CRITICAL_SECTION m_csLockIDY;
  HANDLE m_hEventIDY;
  HANDLE m_hThreadIDY;

  static const WORD RFC;                    // RFC frame constant
  enum MODE m_eMode;                        // controller/device mode
  DWORD m_dwCpuCycles;                      // count cpu cycles in HP-IL slow down mode
  WORD m_wLastFrame;                        // last send frame
  WORD m_wLastCmd;                          // last CMD frame

  bool m_bLoopClosed;                       // loop is closed

  static UINT __stdcall AutoIdyWorkerThread(LPVOID pParam);
  void update_flags();
  void SendFrame(WORD wFrame) override;
  void RecvFrame(WORD wFrame) override;
  int  hpil_rd(int reg);
};
#endif // __HP41HPIL_H__
