#ifndef COMMON_H
#define COMMON_H

#define CL_HPP_ENABLE_EXCEPTIONS
#define CL_HPP_MINIMUM_OPENCL_VERSION 120
#define CL_HPP_TARGET_OPENCL_VERSION 120

#include <CL/opencl.hpp>

#if defined(__APPLE__) || defined(__MACOSX) || defined(__FreeBSD__)
#include <sys/types.h>
#endif

#include <stdlib.h>
#include <chrono>
#include <string>
#include <cstdint>
#include <algorithm>

#define TAB             "  "
#define NEWLINE         "\n"

#ifdef UNUSED
#undef UNUSED
#endif
#define UNUSED(expr) do { (void)(expr); } while (0)

#if defined(__APPLE__) || defined(__MACOSX)
#define OS_NAME         "Macintosh"
#elif defined(__ANDROID__)
#define OS_NAME         "Android"
#elif defined(_WIN32)
  #if defined(_WIN64)
  #define OS_NAME     "Win64"
  #else
  #define OS_NAME     "Win32"
  #endif
#elif defined(__linux__)
  #if defined(__x86_64__)
  #define OS_NAME     "Linux x64"
  #elif defined(__i386__)
  #define OS_NAME     "Linux x86"
  #elif defined(__arm__)
  #define OS_NAME     "Linux ARM"
  #elif defined(__aarch64__)
  #define OS_NAME     "Linux ARM64"
  #else
  #define OS_NAME     "Linux unknown"
  #endif
#elif defined(__FreeBSD__)
#define OS_NAME     "FreeBSD"
#else
#define OS_NAME     "Unknown"
#endif


// Immutable device properties queried from OpenCL
struct device_info_t {
  std::string deviceName;
  std::string driverVersion;

  unsigned int numCUs;
  unsigned int maxWGSize;
  uint64_t maxAllocSize;
  uint64_t maxGlobalSize;
  unsigned int maxClockFreq;

  bool halfSupported;
  bool doubleSupported;
  bool int8DotProductSupported;
  cl_device_type  deviceType;

  uint64_t localMemSize;

  bool imageSupported;
  uint64_t image2dMaxWidth;
  uint64_t image2dMaxHeight;
};

// Per-device benchmark tuning knobs (CPU vs GPU defaults, overridable via --iters)
struct benchmark_config_t {
  unsigned int globalBWIters;
  uint64_t globalBWMaxSize;
  unsigned int computeWgsPerCU;
  unsigned int computeDPWgsPerCU;
  unsigned int computeIters;
  unsigned int atomicIters;
  unsigned int localBWIters;
  unsigned int imageBWIters;
  unsigned int transferBWIters;
  unsigned int kernelLatencyIters;
  uint64_t transferBWMaxSize;

  static benchmark_config_t forDevice(cl_device_type type);
};

class Timer
{
public:

  std::chrono::high_resolution_clock::time_point tick, tock;

  void start();

  // Stop and return time in micro-seconds
  float stopAndTime();
};

device_info_t getDeviceInfo(cl::Device &d);

// Return time in us for the given event
float timeInUS(cl::Event &timeEvent);

// Round down to next multiple of the given base with an optional maximum value
uint64_t roundToMultipleOf(uint64_t number, uint64_t base, uint64_t maxValue = UINT64_MAX);

void populate(float *ptr, uint64_t N);
void populate(double *ptr, uint64_t N);

void trimString(std::string &str);

#endif  // COMMON_H
