#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>

#define ANTAL 50
#define RANGE 56

void genRan(int arr[])
{
  srand(time(NULL));
  
  for (int i = 0; i < ANTAL; i++)
    {
      arr[i]=rand() % RANGE;
    }
}

int bubbleSort(int arr[], int *count_)
{

  int tmp;
  for (int j = 0; j < ANTAL - 1; j++)
    {
      for (int i = 0; i < ANTAL -1 - j; i++)
	{
	  if (arr[i] > arr[i + 1])
	    {
	      tmp = arr[i+1];
	      arr[i + 1] = arr[i];
	      arr[i] = tmp;
	    }
	  (*count_)++;
	}
    }
  //  printf ("LOOPS: %i\n", *count_);
  return 0;
}

void printArr(int arr[])
{
  for (int i = 0; i < ANTAL; i++)
    {
      printf("%i\n", arr[i]);
    }
}

void printFile(char *filename, int *count_, int arr[])
{
  
  FILE *fp = fopen(filename, "w");
  if (fp == NULL)
    exit(1);
  else
    {
      for (int i = 0; i < ANTAL; i++)
	{
	  fprintf(fp, "%i\n", arr[i]);
	}
      fprintf(fp, "Number of iterations in this program: %i\n", *count_);
    }

  fclose(fp);
}

int main (int argc, char **argv)
{
  int arr[ANTAL]; //storage space for generated ints
  int count = 0;
  int *count_ = &count;
  char *filename;
  char *defaultfilename = "yourealoser.DAT";
  if (argv[1] != NULL)
    filename = argv[1];
  else
    filename = defaultfilename;

  genRan(arr);
  bubbleSort(arr, count_);

  //  printArr(arr);
  printf("Count: %i\n", *count_);
  printFile(filename, count_, arr);

  return 0;
}
