/*===========================================================================
  Copyright (C) 1991-2005 European Southern Observatory (ESO)
 
  This program is free software; you can redistribute it and/or 
  modify it under the terms of the GNU General Public License as 
  published by the Free Software Foundation; either version 2 of 
  the License, or (at your option) any later version.
 
  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.
 
  You should have received a copy of the GNU General Public 
  License along with this program; if not, write to the Free 
  Software Foundation, Inc., 675 Massachusetts Ave, Cambridge, 
  MA 02139, USA.
 
  Correspondence concerning ESO-MIDAS should be addressed as follows:
	Internet e-mail: midas@eso.org
	Postal address: European Southern Observatory
			Data Management Division 
			Karl-Schwarzschild-Strasse 2
			D 85748 Garching bei Muenchen 
			GERMANY
===========================================================================*/

/* Program : sortrow.c                      */
/* Author  : P. Ballester   ESO - Garching  */
/* Date    : 29.04.91                       */

/* 090710	last modif                  */

#include  <midas_def.h>

#include <stdio.h>
#include <mutil.h> 

#define   ipos(col, row,siz)    row * siz + col

int main()
{

      char   inpframe[TEXT_LEN+1], outframe[TEXT_LEN+1];
      char   ident[TEXT_LEN+1], cunit[16*2 + 1];
      char   text[TEXT_LEN+1], time[TEXT_LEN+1];

      float  *pntr_inp, *pntr_out;
      float  ratio, thres=20.;

      double start[2], step[2];

      int    naxis, npix[2], actvals, imno_inp, imno_out;
      int    nbrow, nbcol, row, pos, posmin, posmax;

      SCSPRO("sortrow");

      SCKGETC("IN_A", 1, 80, &actvals, inpframe);
      SCKGETC("IN_B", 1, 80, &actvals, outframe);

      SCIGET (inpframe, D_R4_FORMAT, F_I_MODE, F_IMA_TYPE, 2,
              &naxis, npix, start, step, ident, cunit, (char **)&pntr_inp,
              &imno_inp);


      SCIPUT (outframe, D_R4_FORMAT, F_IO_MODE, F_IMA_TYPE, naxis,
              npix, start, step, ident, cunit, (char **)&pntr_out, &imno_out);

      nbrow = npix[1];
      nbcol = npix[0];

      for (row=0; row<nbrow; row++) {

        ratio = 100. * (row+1) / nbrow;
        if (ratio >= thres) {
           OSY_ASCTIM(time);
           sprintf (text,"  %d%% done ...",(int) thres);
           strcat  (time,text);
           SCTPUT(time);
           thres += 20.;
	 }

        /* Copy column into output frame */
        posmin = ipos(0,row,nbcol);
        posmax = ipos(nbcol, row, nbcol);

        for (pos=posmin; pos<posmax; pos++)
                 pntr_out[pos] = pntr_inp[pos];

        // sort(nbcol,&pntr_out[posmin-1]);
        quick_sort(nbcol, &pntr_out[posmin]); 

      }
        SCSEPI();
return 0;
}


