#include <iostream>
#include <iomanip>
#include <limits>

using namespace std;
//w starszych kompilatorach trzeba zakomentowa æ ten wiersz

void            Drukuj(double T[][4]);
void            SortujWgW(double T[][4], unsigned N);
void            SortujWgK(double T[][4], unsigned N);

int 
main()
{
  double          T[4][4];
  while (true)
  {
    for (int y = 0; y < 4;)
    {
      cout << "Podaj " << (y + 1) << " wiersz tablicy: ";
      for (int x = 0; x < 4; ++x)
	cin >> T[y][x];
      if (cin)
	++y;
      else
      {
	cin.clear();
	if (cin.get() == '!')
	  return 0;
	cout << "Blad wprowadzania" << endl;
      }
      cin.ignore(INT_MAX, '\n');
    }
    while (true)
    {
      cout << endl << "Wprowadzona macierz: " << endl;
      Drukuj(T);
      cout << "Sortowac wg [k1,k2,k3,k4,w1,w2,w3,w4,!] ? ";
      cin >> ws;
      //"zjada" wszystkie spacje tabuliatory i \ n
	int             Ch = cin.get();
      if (Ch == '!')
	break;
      else if ((Ch == 'k') || (Ch == 'K'))
	Ch = 0;
      else if ((Ch == 'w') || (Ch == 'W'))
	Ch = 1;
      else
    cin.clear(ios::badbit);
      unsigned        N;
      cin >> N;
      if (cin)
      {
	--N;
	//teraz numeracja od zera
	  if (N < 4)
	{
	  if (Ch)
	    SortujWgW(T, N);
	  else
	    SortujWgK(T, N);
	} else
	  cout << "Sa tylko 4 " << (Ch ? "wierszy" : "kolumny") << endl;
      } else
      {
	cin.clear();
	cout << "Blad wprowadzania" << endl;
      }
      cin.ignore(INT_MAX, '\n');
      cout << endl;
    }
    cout << endl;
  }
}

void 
Drukuj(double T[][4])
{
  cout.setf(ios::fixed);
  cout << setw(2) << ' ';
  for (int x = 0; x < 4; ++x)
    cout << setw(8) << 'k' << (x + 1);
  cout << endl;
  for (int y = 0; y < 4; ++y)
  {
    cout << 'w' << (y + 1);
    for (int x = 0; x < 4; ++x)
    {
      cout << setw(9) << setprecision(2) << T[y][x];
    }
    cout << endl;
  }
}

void 
SortujWgK(double T[][4], unsigned N)
{
  for (int I = 1; I < 4; ++I)
  {
    bool            f = true;
    for (int i = 1; i < 5 - I; ++i)
    {
      if (T[i][N] < T[i - 1][N])
      {
	f = false;
	for (int k = 0; k < 4; ++k)
	{
	  double          t = T[i][k];
	  T[i][k] = T[i - 1][k];
	  T[i - 1][k] = t;
	}
      }
    }
    if (f)
      break;
  }
}

void 
SortujWgW(double T[][4], unsigned N)
{
  for (int I = 1; I < 4; ++I)
  {
    bool            f = true;
    for (int i = 1; i < 5 - I; ++i)
    {
      if (T[N][i] < T[N][i - 1])
      {
	f = false;
	for (int k = 0; k < 4; ++k)
	{
	  double          t = T[k][i];
	  T[k][i] = T[k][i - 1];
	  T[k][i - 1] = t;
	}
      }
    }
    if (f)
      break;
  }
}
