/* @(#)plothtbl.c	19.1 (ESO-DMD) 02/25/03 14:08:04 */
/*===========================================================================
  Copyright (C) 1995 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
===========================================================================*/

/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
.COPYRIGHT   (c) 1993 European Southern Observatory
.IDENTIFIER  PLOTHTBL
.AUTHOR      R.M. van Hees IPG-ESO Garching
.KEYWORDS    Graphics, Table, Histogram, one-dimensional plotting
.LANGUAGE    C
.PURPOSE     Plots or overplot histogram of a column of a TABLE
      input: IN_A/C/1/60  = input table
             P2/C/1/40    = reference column
             INPUTC/C/1/2 = excess bin: Y -> plot excess bin
                                        N -> no excess bin plotted
             INPUTC/C/3/3 = scaling along the Y-axis: LIN, LOG, LN
             INPUTR/R/1/4 = Y-offset (only in OVERPLOT mode),
                            mode : histogram type selection:
                                   0) simple staircase
                                   1) staircase steps joined to X-axis
                                   2) data points joined to x-axis with
                                      boxes (current line width and style)
                                      with width starting from 0 (simple  
                                      line) and increasing with mode      
                                      value in steps of small character   
                                      width,
                            space: spacing between the filling lines,
                            ang  : angle of the filling lines with respect 
                                   to the X-axis.

.COMMENTS    none
.ENVIRONment MIDAS
             #include <midas_def.h>     Prototypes for MIDAS interfaces
             #include <plot_def.h>      General symbols for Plot routines

.VERSION     1.1     10-Sep-1993   FORTRAN --> C         RvH

 010423		last modif

------------------------------------------------------------*/
/*
 * Define _POSIX_SOURCE to indicate
 * that this is a POSIX program
 */
#define _POSIX_SOURCE 1

/*
 * definition of the used functions
 */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>

/*
 * define some macros and constants
 */
#include <midas_def.h>
#include <plot_def.h>

/*
 * here starts the code of the function
 */
int main()
{
int     actvals, allcol, allrow, clen, dtype, ii, knul, lbin, 
        nrbin, sbin, nbins, nrcol, nrrow, nsort, tid, unit, *ifr, 
        ipoint, count;

float   binsiz, *pnbgn, *cl, *rfr, fopt[3], tstat[8], wcfram[8];

char    ebin[3], logpar[4], ws[4], cfmt[17], cunit[17], cmnd[21],
        column[41], table[61], sel[65], buff[81], *desnm[3], *label[4];
/*
 * initialised variables
 */
int   access =   0,                       /* parameter for PCOPEN: plot mode */
      plmode =  -1,                    /* plot mode taken from keyword PMODE */
      icol   =   0,
      ilog   =   0;
float yoff   = 0.0;

char  *err_row   = "*** FATAL: no points in this table ...",
      *err_count = "*** FATAL: count of selected entries is zero ...",
      *err_nmcol = "*** FATAL: can not find column with this name",
      *err_fcol  = "*** FATAL: column has character format";

static char *axis[PLDIM2] = { "MANU", "MANU" },
            *err_flat[PLDIM2] = 
            { "*** WARNING: zero dynamics range in x: %13.8g",
              "*** WARNING: zero dynamics range in y: %13.8g" };
/*
 * allocate memory for different character pointers and initialise a few
 */
for ( ii = 0; ii < 3; ii++ ) desnm[ii] = osmmget(9);
for ( ii = 0; ii < 4; ii++ ) label[ii] = osmmget(81);
(void) strcpy( label[2], "Table: " );
(void) strcpy( desnm[0], "TSTAT" );
(void) strcpy( desnm[1], "TCLAS" );
(void) strcpy( desnm[2], "TFREQ" );

/*
 * start of executable code
 */
(void) SCSPRO( "PLTHTBL" );                  /*contact with the MIDAS monitor*/

/*
 * Plot mode or Overplot mode??
 */
(void) SCKGETC( "MID$CMND", 1, 20, &actvals, cmnd );
if ( *cmnd == 'O' ) access = 1;

/*
 * find file name and read header information
 */
(void) SCKGETC( "IN_A", 1, 60, &actvals, table );

/*
 * Try to open table, this routine EXITS the program if the table can not 
 * be found !!
 */
(void) TCTOPN( table, F_I_MODE, &tid );

/*
 * read reference column identifier:
 */
(void) SCKGETC( "P2", 1, 40, &actvals, column );

/*
 * plot excess bin or not
 */
(void) SCKGETC( "INPUTC", 1, 2, &actvals, ebin );
CGN_LOWSTR( ebin );

/*
 * compute LOG or LN or not...
 */
(void) SCKGETC( "INPUTC", 3, 3, &actvals, logpar );
CGN_LOWSTR( logpar );
if ( strncmp( logpar, "log", 3 ) == 0 )
   { (void) strcpy( label[1], "log10 Frequency" ); 
     ilog = 1;
   }
else if ( strncmp( logpar, "ln", 2 ) == 0 )
   { (void) strcpy( label[1], "ln Frequency" );
     ilog = 2;
   }
else
   (void) strcpy( label[1], "Frequency" ); 
/*
 * read options
 */
(void) SCKRDR( "INPUTR", 2, 3, &actvals, fopt, &unit, &knul );

/*
 * read table size information
 */
(void) TCIGET( tid, &nrcol, &nrrow, &nsort, &allcol, &allrow );
if ( nrrow == 0 ) (void) SCETER( 1, err_row );

/*
 * get selection information
 */
(void) TCSINF( tid, sel );
(void) TCSCNT( tid, &count);
if  ( count <= 0 ) 
    (void) SCETER( 1, err_count );  
/*
 * get column adresses by its name
 */
(void) TCCSER( tid, column, &icol );
if ( icol == -1 ) (void) SCETER( 2, err_nmcol );

/*
 * read column label
 */
(void) TCLGET( tid, icol, label[0] );

/*
 * read column unit
 */
(void) TCUGET( tid, icol, cunit );

/*
 * read column format
 */
(void) TCFGET( tid, icol, cfmt, &clen, &dtype );
if ( dtype == D_C_FORMAT ) SCETER( 3, err_fcol );

/*
 * setup label X-axis
 */
if ( strncmp( label[0], "  ", 2 ) == 0 )
   (void) sprintf( buff, "Column: %d", icol );
else
   (void) strcpy( buff, label[0] );
(void) sprintf( label[0], "%s (%s)", buff, cunit );

/*
 * get binning from descriptor
 */
(void) sprintf( ws, "%03d", icol );
for ( ii = 0; ii < 3; ii++ )
    (void) strcat( desnm[ii], ws );

/*
 * determine the number of bins
 */
(void) SCDRDR( tid, desnm[0], 1, 8, &actvals, tstat, &unit, &knul );
nbins = NINT( tstat[6] );

sbin = 0;
lbin = nbins;
if ( strncmp( ebin, "n", 1 ) == 0 ) 
   sbin++ ;
if ( strncmp( ebin+1, "n", 1 ) == 0 )
   lbin-- ;
nrbin = lbin - sbin;
/*
 * get size and X-values of the bins 
 */
pnbgn = cl = (float *) osmmget( nbins * sizeof( float ));
(void) SCDRDR( tid, desnm[1], sbin+1, nbins, 
                              &actvals, cl, &unit, &knul );
binsiz = *(cl+1) - *cl; 

while ( (cl - pnbgn) < (nrbin - 1) )
      *cl++ -= binsiz/2;
*cl = *(cl-1) + binsiz;
cl = pnbgn;                            /* set pointer back to begin of array */

/*
 * get the Y-values
 */
ifr = (int *) osmmget( nbins * sizeof( int ));
pnbgn = rfr = (float *) osmmget( nbins * sizeof( float ));
(void) SCDRDI( tid, desnm[2], sbin+1, nbins, 
                              &actvals, ifr, &unit, &knul );
if ( access != 0 ) 
   (void) SCKRDR( "INPUTR", 1, 1, &actvals, &yoff, &unit, &knul );

ipoint = 0;
while ( (rfr - pnbgn) < nrbin )
    { *rfr = yoff + (float) ifr[ipoint];
      ipoint++;
      if ( ilog != 0 ){
         if ( *rfr <= 0.0 ) 
            *rfr = -9999;
         else { 
            if ( ilog == 1 )
              *rfr = log10( *rfr );
            else
              *rfr = log( *rfr );
	  }
      }
      rfr++;
    }
rfr = pnbgn;

/*
 * Get the manual setting for the axes
 */
PCKRDR( "XAXIS", 4, &actvals, wcfram );
PCKRDR( "YAXIS", 4, &actvals, wcfram+FOR_Y );

/*
 * calculate frame
 */
if ( access == 0 )
   { if ( fabs( *wcfram ) < PLT_EPS && fabs( *(wcfram+1) ) < PLT_EPS )
        { axis[0] = "AUTO";
          wcfram[0] = *cl;
          wcfram[1] = *(cl+nrbin-1);
          wcfram[2] = wcfram[3] = 0;
        }
     if ( fabs( *(wcfram+FOR_Y) ) < PLT_EPS 
          && fabs( *(wcfram+FOR_Y+1) ) < PLT_EPS )
        { axis[1] = "AUTO";
          MINMAX( rfr, nrbin, wcfram+FOR_Y, wcfram+FOR_Y+1 );
          if ( wcfram[FOR_Y] == wcfram[FOR_Y+1] )
             { (void) sprintf( buff, err_flat[ii], wcfram[FOR_Y] );
               SCTPUT( buff );
             }
          if (wcfram[FOR_Y] < 0.0) wcfram[FOR_Y] = 0;
          wcfram[FOR_Y+2] = wcfram[FOR_Y+3] = 0;
        }
     GETFRM( axis[0], wcfram );
     GETFRM( axis[1], wcfram + FOR_Y );
     PCKWRR( "XWNDL", 4, wcfram );
     PCKWRR( "YWNDL", 4, wcfram+FOR_Y );
   }

for (ii=0; ii<nrbin; ii++)
    rfr[ii] = MYMAX( *(wcfram+FOR_Y), rfr[ii]);

/*
 * setup graphic device according to MIDAS settings
 */
PCOPEN( " ", " ", access, &plmode );

/*
 * do the work
 */
PCHIST( nrbin, cl, rfr, fopt );

/*
 * draw the axes and the label
 */
if ( plmode >= 0 && access == 0 )
   { 
/*
 * plot axes and labels
 */
     PCFRAM( wcfram, wcfram+FOR_Y, label[0], label[1] );

     if ( plmode == 1 )
        { (void) strcat ( label[2], table );
          (void) sprintf( label[3], "Sel: %s", sel );
          PLIDEN( plmode, label[2], label[3] );
        }
     else if ( plmode == 2 )
        PLHTBI( plmode, table, column, sel, nrbin, binsiz );
   }
/*
 * good bye and finish
 */
PCCLOS();

return SCSEPI();
}
