/*===========================================================================
  Copyright (C) 1993-2009 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
===========================================================================*/

/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
.IDENTIFIER  PLOTHBDF
.AUTHOR      R.M. van Hees IPG-ESO Garching
.KEYWORDS    Graphics, BDF files, Histogram, one-dimensional plotting
.LANGUAGE    C
.PURPOSE     Plots or overplot a histogram of a FRAME
      input: IN_A/C/1/60  = input image
             INPUTC/C/1/2 = excess bin: Y -> plot the excess bin
                                        N -> no excess bin plotted
             INPUTC/C/3/3 = scaling along the Y-axis: LIN, LOG, LN
             INPUTR/R/2/3 = 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.
.ALGORITHM   Use routines from MIDAS and AGL plot libery
             Descriptors of the image frame are also needed:
             HIST_BINS/R/1/5 = no. of bins, binsize, lower and upper
                               excess limits
             HISTOGRAM/I/1/nbins = actual histogram (Y-values)
.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

 090707		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()

{
register int ii;
int mm, actvals, imf, knul, nbins, hist1, unit, *ifr, npix[PLDIM2]; 
int histo_source;
int access = 0,	/* parameter for PCOPEN: plot mode */
    plmode = -1,	/* plot mode taken from keyword PMODE */
    ilog = 0;

float binsiz, *cl, *rfr, fopt[3], histb[5], wcfram[8];
float yoff = 0.0;

double start[PLDIM2], step[PLDIM2];

char logpar[4], cmnd[21], cunit[17], ident[33], name[61], buff[81], 
     *label[4], ebin[3];
char *err_1dim = "*** FATAL: Image row contains only one point!";

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 < 4; ii++ ) label[ii] = osmmget(81);
(void) strcpy( label[0], "Pixel value (" );
(void) strcpy( label[2], "Image: " );
(void) strcpy( label[3], "Ident: %s" );

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

mm = 1;
(void) SCPSET(F_FITS_PARM,&mm);		/* don't read in ESO.xyz keywords */

/*
 * 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, name );
(void) SCFOPN( name, D_R4_FORMAT, 0, F_IMA_TYPE, &imf );
(void) SCDRDI( imf, "NPIX" , 1, PLDIM2, &actvals, npix , &unit, &knul );

/*
 * check frame parameters
 */
if ( npix[0] == 1 ) SCTPUT( err_1dim );

/*
 * read the descriptor
 */
(void) SCDRDD( imf, "START", 1, PLDIM2, &actvals, start, &unit, &knul );
(void) SCDRDD( imf, "STEP" , 1, PLDIM2, &actvals, step , &unit, &knul );
(void) SCDGETC( imf, "IDENT", 1, 32, &actvals, ident );
(void) SCDGETC( imf, "CUNIT", 1, 16, &actvals, cunit );


/* check, if histogram data from descr. or keyword */

histo_source = 0;
buff[0] = ' ';
(void) MID_FNDKEY("fits__histogram",buff,&mm,&mm,&unit);
if (buff[0] == 'I') histo_source = 1;



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

/*
 * read options
 */
(void) SCKGETC( "INPUTC", 1, 2, &actvals, ebin );
CGN_LOWSTR( ebin );
(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" ); 
(void) SCKRDR( "INPUTR", 2, 3, &actvals, fopt, &unit, &knul );

/*
 * get binning from descriptor or keyword (FITS files are usually read-only)
 */

if (histo_source == 0)
   (void) SCDRDR( imf, "HIST_BINS", 1, 5, &actvals, histb, &unit, &knul );
else
   (void) SCKRDR("fits__hist_bins",1,5, &actvals, histb, &unit, &knul );

nbins  = NINT( histb[0] );
binsiz = histb[1];

/*
 * get the X-values
 */
cl = (float *) osmmget( nbins * sizeof( float ));
*cl = histb[2] + binsiz/2.0;
hist1 = 1;
if ( histb[4] != 0.0 )                             /* number of excess bins */
   {
   if ( strncmp( ebin, "n", 1 ) == 0 ) 
      {
      nbins --;
      hist1 = 2;
      }
   else
      *cl  -= binsiz;

   if ( strncmp( ebin+1, "n", 1 ) == 0 )
      nbins --;
   }

for ( ii = 1; ii < nbins; ii++ ) 
    *(cl+ii) = *cl + ii * binsiz;
/*
 * get the Y-values
 */
if ( access != 0 ) 
   (void) SCKRDR( "INPUTR", 1, 1, &actvals, &yoff, &unit, &knul );

ifr = (int *) osmmget( nbins * sizeof( int ));
rfr = (float *) osmmget( nbins * sizeof( float ));

if (histo_source == 0)
   (void) SCDRDI( imf,"HISTOGRAM",hist1,nbins,&actvals,ifr,&unit,&knul);
else
   (void) SCKRDI("fits__histogram",hist1,nbins,&actvals,ifr,&unit,&knul);


for ( ii = 0; ii < nbins; ii++ )
    { rfr[ii] = yoff + ifr[ii];
      if ( rfr[ii] > 0.0 && ilog != 0 )
         { if ( ilog == 1 )
              rfr[ii] = (float) log10( rfr[ii] );
           else
              rfr[ii] = (float) log( rfr[ii] );
         }
    }
/*
 * calculate frame
 */
if ( access == 0 )
   { if ( fabs( *wcfram ) < PLT_EPS && fabs( *(wcfram+1) ) < PLT_EPS )
        { axis[0] = "AUTO";
          wcfram[0] = *cl;
          wcfram[1] = *(cl+nbins-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, nbins, wcfram+FOR_Y, wcfram+FOR_Y+1 );
          if ( wcfram[FOR_Y] == wcfram[FOR_Y+1] )
             { (void) sprintf( buff, err_flat[1], wcfram[FOR_Y] );
               SCTPUT( buff );
             }
          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 );
   }
/*
 * setup graphic device according to MIDAS settings
 */
PCOPEN( " ", " ", access, &plmode );

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

/*
 * draw the axes and the label
 */
if ( plmode >= 0 && access == 0 )
   { 
/*
 * setup label X-axis
 */
     (void) strcat( label[0], cunit );
     (void) strcat( label[0], " )" );
     LABSTR( label[0] );
/*
 * setup label Y-axis (log mode or not?)
 */
     if ( ilog == 0 )
        (void) strcpy( label[1], "Frequency" ); 
     else if ( ilog == 1 )
        (void) strcpy( label[1], "log10 Frequency" ); 
     else
        (void) strcpy( label[1], "ln Frequency" ); 
/*
 * plot axes and labels
 */
     PCFRAM( wcfram, wcfram+FOR_Y, label[0], label[1] );

     if ( plmode == 1 )
        { (void) strcat ( label[2], name );
	    (void) sprintf( label[3], "%s", ident );
          PLIDEN( plmode, label[2], label[3] );
        }
     else if ( plmode == 2 )
        PLHFRI( plmode, name, ident, nbins, binsiz );
   }
/*
 * good bye and finish
 */
PCCLOS();

return SCSEPI();
}



