/* This C code is based on the ANSI C standard 
that was established in 1999 (almost 20 yrs 
after the original implementation of C). 
*/ 


#include <stdio.h>
#include <math.h> 

#define BUFSIZE 256


int globalCounter = 0;			/* global variable visible to any 
					   function. Avoid using as much as 
					   possible */ 

extern int extX;			/* external variable - resize in another                                           file */



/* function prototypes */ 
void print_converted(int);
void fib();
void prompt_convert();

void 
few_more()
{
  printf("Additional C concepts \n");

  /* some additional concepts */ 
  int i = 256;
  int root;
  root = sqrt((double) i);
  printf("%d\n", root);

  /* comparison operators */ 
  int a = 5;
  int b = 10;
  
  /* wrong version - common source of bugs */ 
  if (a = b) printf("We are equal - Oops how is this possible \n");
  else printf("We are not equal - that's right\n");

  /* correct version */ 
  a = 5;
  b = 10;
  if (a == b) printf("We are equal - Oops how is this possible \n");
  else printf("We are not equal - that's right\n");

  /* Logical operators */ 

  a = 1;				/* true  */
  b = 0;				/* false */
 
  if (!a) printf("Not acceptable\n");
  else printf("Acceptable\n");
  
}




/* print_converted:
   print pounds and corresponding kilos 
*/

void 
print_converted(int pounds) 
{
  static int counter = 0;
  float kilos_per_pound = 0.45359;
  float kilos = pounds * kilos_per_pound;
  printf("%d  %3d      %6.2f\n", counter, pounds, kilos);
  counter++;
  globalCounter++;
}


/* print 1st 24 Fibonacci numbers */ 
void 
fib() 
{
  int danger;
  int fib[24];
  int i;
  fib[0] = 0;
  fib[1] = 1;
  
  for (i=2; i < 24; i++)
    fib[i] = fib[i-1] + fib[i-2];
  
  for (i=0; i < 24; i++) 
    printf("%3d     %6d\n", i , fib[i]);

  /* the following code is wrong: fib[10000] is some unknown memory location 
   it might work or it might core dump. Welcome to the dirty 
   world of unsafe languages */ 
  
  /* fib[10000] = 100;
  danger = fib[10000];
  printf("%d\n", danger);
  */ 
}


void 
prompt_convert()
{
  int pounds;
  /* input with prompt */ 

  printf("Give an integer weight in pounds : ");
  scanf("%d", &pounds);
  print_converted(pounds);
}







int
main(int argc, char **argv)
{
  int pounds;
  if (argc != 2) 
    {
      fprintf(stderr, "Wrong number of arguments\n");
      exit(1);
    }
  else /* argc == 2 */ 
    {
      printf("%s: is weight conversion program and prints the first 24 Fibonacci numbers \n", argv[0]);
      if (strcmp(argv[1],"-p") == 0) 
	prompt_convert();
      else if (strcmp(argv[1], "-t") == 0) 
	{
	  printf("Full conversion table \n");
	  printf("Pounds     -    Kilos \n");
	  for (pounds=10; pounds < 250; pounds += 10)
	    print_converted(pounds);
	}
      else if (strcmp(argv[1], "-f") == 0)
	  fib();
      else if (strcmp(argv[1], "-a") == 0)
	few_more();
    }
  printf("Global counter = %d\n", globalCounter);

  
}


