/* Jonathan Bogaty, Lab 8
   Extra Credit included */

#include "ballsort.h"
#include <iostream>

using namespace CS128;
using namespace std;

#define MAX_BALLS 10

/* Precondition[s]:
   An initialized array of balls, the size of the array, refresh delay for the display function, and if other than zero the current array index */
void sort_and_display(Ball ball_list[],int size,int delay,int index=0){
  static bool tripped=false;
  if(index==size){ // reached the end of the array. Index+1 would be a null element so don't try sorting this time.
    display(ball_list,index,size,delay);
    if(tripped){ // we've had to perform sorting
      sort_and_display(ball_list,size,delay); // Restart sorting from the beginning of the array
    }
  }else{ // We're still going through the array
    if(radius(ball_list[index]) > radius(ball_list[index+1])){ // The current element is bigger than the next one in the array
      tripped=true; // We're going to have to sort. Make a tmp variable and go from there.
      Ball tmp=ball_list[index];
      ball_list[index]=ball_list[index+1];
      ball_list[index+1]=tmp;
      display(ball_list,index,size,delay);
      sort_and_display(ball_list,size,delay,index+1); // Continue to sort the ball_list for the next element
    }else{ // Well, we didn't have to sort but we aren't at the end yet.
      display(ball_list,index,size,delay);
      sort_and_display(ball_list,size,delay,index+1);
    }
  }
}
/* Postcondition[s]:
   Sorts ball_list, loops through and displays the array of balls each time it is sorted, returns nothing. */

int main(int argc, char *argv[]){
  int balls_to_sort,refresh_delay;
  if(argc==3){
cout << "1\n"; 
    balls_to_sort=atoi(argv[1]);
cout << "2\n";
    refresh_delay=atoi(argv[2]);
    while(balls_to_sort<1 || balls_to_sort>MAX_BALLS){
      cout << "Balls to sort must be between 1 and " << MAX_BALLS << ", please enter another number: ";
      cin >> balls_to_sort;
    }
  }else{
    cout << "USAGE: lab8 <balls_to_sort> <refresh_delay>\n";
    cout << "Defaulting to 10 for balls to sort, 1000 for refresh delay\n";
    balls_to_sort=10;
    refresh_delay=1000;
  }
  Ball ball_list[balls_to_sort-1];
  for(int i=0;i<balls_to_sort;i++){
cout << "3\n";
    initialize(ball_list[i]);
cout << "4\n";
    if(i==0){
cout << "4a\n";
      cout << "Unsorted array: " << radius(ball_list[i]);}
    else if(i==balls_to_sort-1) {
cout << "4b\n"; 
      cout << " " << radius(ball_list[i]) << endl;}
    else
{
cout << "4c\n"; 
      cout << " " << radius(ball_list[i]);}
  }
cout << "5\n"; 
  sort_and_display(ball_list,balls_to_sort-1,refresh_delay);
  for(int j=0;j<balls_to_sort;j++){
    if(j==0)
      cout << "Sorted array: " << radius(ball_list[j]);
    else if(j==balls_to_sort-1)
      cout << " " << radius(ball_list[j]) << endl;
    else
      cout << " " << radius(ball_list[j]);
  }
  return(0);
}

