//*****************************************************************************
////  Course:             COMS 2203 Foundations II Sect. 2
////  Semester:           Fall 2004
////  Assignment Number:  #4                             
////  Author Name:        DarC KonQuesT                        
////  Date Written:       September 23, 2004
////                                                         
////  Description of Program:                              
////  Take input file, sort in descending order, output to another file. 
////   Using a a truct datatype.                            
////*****************************************************************************
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>

using namespace std;

struct EmployeeType
{
  int employee_id;
  float sales_amount;
};


const int N = 100; // array size (max number of items that can be stored)

void sort(EmployeeType z[], int n)  //using z for array variable
{
 int smallestIndex, index, minIndex, temp2;
 float temp1;
 for(index = 0; index < n - 1; index++)
 {
   smallestIndex = index;
   for(minIndex = index + 1; minIndex < n; minIndex++)
     if(z[minIndex].sales_amount > z[smallestIndex].sales_amount)
       smallestIndex = minIndex;

   temp1 = z[smallestIndex].sales_amount;
   temp2 = z[smallestIndex].employee_id;
   
   z[smallestIndex].sales_amount = z[index].sales_amount;
   z[smallestIndex].employee_id = z[index].employee_id;
   
   z[index].sales_amount = temp1;
   z[index].employee_id = temp2;
 }

}

int main()
{
  ifstream infile;
  ofstream outfile;
  string fname;
  int id;     // ID# from file
  float sales;  // Sales amount from file
  int k;     // number of items stored in array, array subscript (index)
  EmployeeType a[N];  // EmployeType Array
  string ofilename;
 
  cout << "Enter input file name:  ";  
  cin >> fname;
  cout << "Enter output file name: ";
  cin >> ofilename;
  infile.open(fname.c_str());
  if(!infile) {
    cerr << "Error: Can't open file." << endl;
    return 1;
  } 
  
  k = 0;         // initialize array subscript value
  infile >> id;   // read 1st item
  infile >> sales;
  while(infile && k < N) { // if not eof and array has space for item
    a[k].sales_amount = sales;    // store item in array              
    a[k].employee_id = id;
    ++k;         // next location in array, number of items in array
    infile >> id; // read next item              
    infile >> sales;
  }

  sort(a, k);
  outfile << fixed << showpoint << setprecision(2); 
  outfile.open(ofilename.c_str());
  
  for(int i = 0; i < k; ++i)
    outfile << a[i].employee_id << "    " << a[i].sales_amount << endl; 
  return 0;
}

