#include "fact.h"
#include <stdlib.h>
#include <stdio.h>

/* This function prints a prompt and reads a number from standard
   input.
   Note: You do not need to modify nor understand the workings of
   this function*/
int promptAndRead (int * p) {
  char buff[1000];
  char * tmp;
  /* print a prompt :*/
  printf("Please insert a number to take the factorial of (non-number to quit): ");
  /* read a line of input from the keyboard, up to 1000 in length*/
  fgets(buff, 1000, stdin);
  /* try to convert that input to a number (base 10)*/
  *p = (int) strtol(buff, &tmp, 10);
  /* check if the whole string converted to a valid number*/
  if(tmp == buff || 
     (*tmp != '\0' &&
      *tmp != '\n')) {
    return 0;
  }
  return 1;
}

/* The main program: read numbers from standard in,
   and compute their factorial until a non-number is entered*/
int main(void) {
  int num;
  
  while(promptAndRead(&num)) {
    int ans;

    ans = factorial (num);

    printf("factorial(%d) = %d\n", num, ans);

  }

  return EXIT_SUCCESS;
}

