#include <stddef.h>
#include <stdint.h>
#include <ulib.h>

int32_t rr(int32_t min, int32_t max) {
  if (max <= min)
    return min;

  uint32_t range = (uint32_t)(max - min + 1);
  uint32_t val;
  int32_t rnd;

  for (size_t i = 0; i < 10; i++) {
    rnd = rand();
    if (rnd == -1)
      continue;

    val = (uint32_t)rnd;

    uint32_t limit = (uint32_t)(-range) % range;
    if (val >= limit) {
      return min + (val % range);
    }
  }

  return -1;
}

void rc_rr(void) {
  if (argslen() < 3) {
    uprintf("rc: Not enough arguments\n");
    return;
  }

  char *beginstr = *(args()+1);
  char *endstr = *(args()+2);

  char *endb;
  long begin = string_conv_strtol(beginstr, &endb, 10);
  char *ende;
  long end = string_conv_strtol(endstr, &ende, 10);

  int32_t r = rr(begin, end);
  if (r == -1) {
    uprintf("rc: failed to generate random number in range\n");
    return;
  }

  uprintf("%d\n", r);
}
