
int string_to_number(int s) {
  int negative;
  int end_char_idx;
  int idx;
  int ch;
  int string_size;
  int int_val;
  int power;
  int ret;

  is_string(s);

  ret = Mtrue;
  string_size = MstrSizeRef(s);
  if (string_size == 0)
    ret = Mfalse;
  else
  if (MgetChar(string_ref(s, 0)) == '-') {
    if (string_size == 1)
      ret = Mfalse;
    else {
      negative = 1;
      end_char_idx = 1;
    }
  }
  else {
    negative = 0;
    end_char_idx = 0;
  }

  if (ret == Mfalse) // not a number
    return ret;
  else {
    power = 1;
    int_val = 0;
    for (idx = string_size - 1; idx >= end_char_idx; idx--) {
      ch = MgetChar(string_ref(s, idx));
      if (!isdigit(ch))
        return Mfalse;
      int_val = int_val + (ch - '0') * power;
      power = power * 10;
    }

    if (negative)
      int_val = - int_val;

    return make_integer(int_val);
  }
}

int number_to_string(int number) {
  int temp;
  int n;
  int n_temp;
  int negative;
  int s;
  int string_size;
  int string_idx;
  int first_idx;

  n = get_integer_val(number);

  negative = n < 0;
  if (negative) {
    n = -n;
    string_size = 1;
  }
  else
    string_size = 0;

  // first get number of digits in n

  n_temp = n;
  do {
    string_size = string_size + 1;
    n_temp = n_temp / 10;
  } while (n_temp != 0);

  s = make_string(string_size);

  if (negative) {
    string_set(
      s,
      0,
      MmakeChar('-'));
    first_idx = 1;
  }
  else
    first_idx = 0;

  for (string_idx = string_size - 1; string_idx >= first_idx; string_idx--) {
    string_set( // set string in reverse order
      s,
      string_idx,
      MmakeChar(n % 10 + '0'));
    n = n / 10;
  }

  return s;
}
