#include "libscl.h"

using namespace std;
using namespace scl;

int main()
{
  
  intvec rank;

  INTEGER r = 10;
  INTEGER c = 5;
  
  realmat A(r,c);

  INT_32BIT seed = 100541;

  for (INTEGER j=1; j<=c; j++) {
    for (INTEGER i=1; i<=r; i++) {
      A(i,j) = ran(&seed);
    }
  }
  
  cout << starbox("/ A //") << A;
  
  intvec ivec = A.sort();
  cout << starbox("/ A sorted on default (column 1) //") << A;
  
  cout << starbox("/ Original row positions //") << endl;
  for (INTEGER i=1; i<= ivec.size(); i++) cout << "  " << ivec[i];
  cout << endl;
  
  cout << starbox("/ Ranks //") << endl;
  rank.resize(ivec.size());
  for (INTEGER i=1; i<= ivec.size(); i++) rank[ivec[i]] = i;
  for (INTEGER i=1; i<= ivec.size(); i++) cout << "  " << rank[i];
  cout << endl;

  ivec = A.sort(c);
  cout << starbox("/ A sorted on last column //") << A;
  
  cout << starbox("/ Original row positions //") << endl;
  for (INTEGER i=1; i<= ivec.size(); i++) cout << "  " << ivec[i];
  cout << endl;

  cout << starbox("/ Ranks //") << endl;
  rank.resize(ivec.size());
  for (INTEGER i=1; i<= ivec.size(); i++) rank[ivec[i]] = i;
  for (INTEGER i=1; i<= ivec.size(); i++) cout << "  " << rank[i];
  cout << endl;

  A.sort(c/2);
  cout << starbox("\n A sorted on column c/2 \n\n",'\n') << A;

/*
  realmat B;
  B.sort();
  cout << starbox("\n Attempt to sort null matrix \n\n",'\n') << B; 
*/

  realmat B = A("","1");
  cout << starbox("/ B //") << B; 
  B.sort(1); 
  cout << starbox("/ B sorted on column 1 //") << B;

  
  for (INTEGER j=1; j<=c; j++) {
    for (INTEGER i=1; i<=r; i++) {
      A(i,j) = iran(&seed,3);
    }
  }
  realmat A_save = A;

  cout << starbox("/ A //") << A;
  intvec svec = seq(c,1);
  A.sort(svec);
  cout << starbox("\n A sorted on last to first columns\n\n",'\n') << A;

  A = A_save;
  svec = -svec;
  A.sort(svec);
  cout << starbox("\n Same but reverse order \n\n",'\n') << A;

  A = A_save;
  svec = -svec;
  svec[c]=c+1;
  A.sort(svec);
  cout << starbox("\n Same but last svec bad col no \n\n",'\n') << A;

  return 0;
}

