// SPDX-License-Identifier: Unlicense

#include "getopt.h"

#ifdef SHR3D_GETOPT

#include <string.h>

const char* optarg_;        // global argument pointer
int optind_ = 0;    // global argv index

int getopt(int argc, char* argv[], const char* optstring)
{
  static const char* next = nullptr;
  if (optind_ == 0)
    next = nullptr;

  optarg_ = nullptr;

  if (next == nullptr || *next == '\0')
  {
    if (optind_ == 0)
      optind_++;

    if (optind_ >= argc || argv[optind_][0] != '-' || argv[optind_][1] == '\0')
    {
      optarg_ = nullptr;
      if (optind_ < argc)
        optarg_ = argv[optind_];
      return -1;
    }

    if (strcmp(argv[optind_], "--") == 0)
    {
      optind_++;
      optarg_ = nullptr;
      if (optind_ < argc)
        optarg_ = argv[optind_];
      return -1;
    }

    next = argv[optind_];
    next++;        // skip past -
    optind_++;
  }

  char c = *next++;
  const char* cp = strchr(optstring, c);

  if (cp == nullptr || c == ':')
    return '?';

  cp++;
  if (*cp == ':')
  {
    if (*next != '\0')
    {
      optarg_ = next;
      next = nullptr;
    }
    else if (optind_ < argc)
    {
      optarg_ = argv[optind_];
      optind_++;
    }
    else
    {
      return '?';
    }
  }

  return c;
}

#endif // SHR3D_GETOPT
