/*===========================================================================
  Copyright (C) 1994-2010 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  VIEW
.LANGUAGE    C
.AUTHOR      K. Banse, R.M. van Hees IPG-ESO Garching
.KEYWORDS    ImageDisplay
.PURPOSE     Preview an image
.ALGORITHM   Offer lots of display functionality, all controlled via cursor 
             input and some typing into the Midas command window
.INPUT/OUTPUT:
  the following keywords are used:

  IN_A/C/1/80		data frame to be loaded, BDF or FITS
  IN_B/C/1/80		
  DAZHOLD/I/1/14	cursor(s) enabled, cursor form(s),
			split screen mode + other info
  P1/C/1/15		optional descriptor name where world coordinates
			  + pixel values should be stored
                        or table name, if data should go to a table
                        = ?, if data only to be displayed on terminal
  P2/C/1/2 		= A or ?, for appending values to descriptor
                        or table or creating new descriptor/table
                        = ID for using identifiers in tables
                        start_no an optional starting number
  P3/C/1/2		mark flag,
                        (1:1) = Y for putting cross on screen, else no
                                  in case of P2 = ID or NO
                        (2:2) = Y for writing also the identifier into
                               the overlay channel
  SIZIN/I/1/2		mapping sizes for input data + output bytes
  MID$DISP/C/1/20	is either I_IMAGE_DISPLAY or M_name-of-display-file
  MID$SPEC/C/7/4	if = CUTS, we loop inside program with different cuts

.VERSION     1.00       940425  from VIEW.FOR    RvH

 100115		last modif
------------------------------------------------------------*/

/* Define _POSIX_SOURCE to indicate that this is a POSIX program */

#define  _POSIX_SOURCE 1

#include <stdio.h>
#include <midas_def.h>
#include <idinumd.h>

#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#ifndef TRUE
#define TRUE            1
#define FALSE           0
#endif

#define NRCOL		10                /* standard size of optional table */
#define NRROW		100

#define MYMIN(a,b)      ((a) > (b) ? (b) : (a))

int  logview_init(), display_it();

/*

*/

int main()

{
int   actvals, dattyp, ec, ed, el, imno, knul, naxis, overlay, plotfl, 
      tid, unit, user_lev, icent[4], idum[5], npix[2], colref[10];
register int ii;

float cuts[4];

char  cbuff[2], optio[2], frame[84], frame_str[84], table[84], text[84];



/* initialized variables */

char *tblunit = "World Coords";
static char *tbllabl[4] = { "XSTART", "YSTART", "XEND", "YEND" };
static char *infofile = "view_ima.info";

static int dis_no, log_no, con_alw = 1;              /* variables for SCECNT */
static int scale[3], disp[9] = { -1, -1, -1, -1, -1, -1, -1 -1, -1 }; 






(void) SCSPRO("VIEW");


/* start up parallel logviewer or `classical' terminal I/O */

(void) logview_init(infofile);


DCOPEN(1);						/* connect Display */
(void) SCKGETC("CFLAGS",1,1,&actvals,cbuff);		/* get plotflag */
if ((*cbuff == 'n') || (*cbuff == 'N'))
   plotfl = -1;
else
   plotfl = 0;


/* We give novice users a help + current zoomfactor */

(void) SCKRDI("ERROR",2,1,&actvals,&user_lev,&unit,&knul);
if (user_lev == 1) auxhelp(1);


/* Clear overlay-channel if necessary */

(void) SCKRDI("AUX_MODE",9,1,&actvals,&overlay,&unit,&knul);
if (overlay != 0) CONCHA_C(QDSPNO,QOVCH,1,0);


/* get name of frame to be displayed and it's data type */

(void) SCKGETC("IN_A",1,80,&actvals,frame_str);
ii = CGN_INDEXC(frame_str,']');         /* look for name[...] first */
if (ii > 0)
   {
   if (frame_str[ii+1] == ',')
      ec = ii + 1;
   else
      ec = 0;
   }
else
   ec = CGN_INDEXC(frame_str,',');         /* look for name,f_plane,l_plane */

if (ec > 0)
   {
   frame_str[ec] = '\0';
   (void) CGN_FRAME(frame_str,1,frame,0);
   frame_str[ec] = ',';                   /* back to original string */
   }
else
   (void) CGN_FRAME(frame_str,1,frame,0);

(void) SCFINF(frame,2,idum);
dattyp = idum[1];
     

/* if the frame isn't already loaded, then load it */

(void) SCKGETC("DEFAULT",11,1,&actvals,optio);
if ( *optio == 'l' || *optio == 'L' )     
   {
   if (dattyp == D_R8_FORMAT) dattyp = D_R4_FORMAT;
   (void) SCFOPN(frame,dattyp,0,F_IMA_TYPE,&imno);

   (void) SCDRDI(imno,"NAXIS",1,1,&actvals,&naxis,&unit,&knul);
   (void) SCDRDI(imno,"NPIX",1,naxis,&actvals,npix,&unit,&knul);


   /* get cut and display values (not necessarily there...) */

   SCECNT("GET",&ec,&el,&ed);
   SCECNT("PUT",&con_alw,&log_no,&dis_no);

   /* get the cut levels */

   cuts[0] = cuts[1] = cuts[2] = cuts[3] = 0.;     /* just to make sure */
   (void) SCDRDR(imno,"LHCUTS",1,4,&actvals,cuts,&unit, &knul);


   /* if cuts equal or specific CUTS strategy required, do it via MYCUTS_C */

   if (cuts[0] >= cuts[1])
      {
      if (cuts[2] < cuts[3])
         {
         cuts[0] = cuts[2];
         cuts[1] = cuts[3];
         }
      else
         {
         int  toto, num;

         (void) SCKRDI("MONITPAR",20,1,&actvals,&num,&unit,&knul);
         num = num * num;		/* default mapping size */
         toto = npix[0] * npix[1];	/* that's sloppy for 3-dim ... */
         if (dattyp != D_R4_FORMAT)
            {
            (void) SCFCLO(imno);
            (void) SCFOPN(frame,D_R4_FORMAT,0,F_IMA_TYPE,&imno);
            MYCUTS_C("3SIGMA",1,imno,toto,num,cuts);
            (void) SCFCLO(imno);
            (void) SCFOPN(frame,dattyp,0,F_IMA_TYPE,&imno);
            }
         else
            MYCUTS_C("3SIGMA",1,imno,toto,num,cuts);
         }

      if (cuts[0] >= cuts[1]) SCETER(1,"data range = 0.0 ...");
      }


   /* Look for new integer descr. DISPLAY_DATA, 
      if found, copy data + delete descr. DISPLAY
      we now use integer descriptor DISPLAY_DATA for that */

   if ( SCDRDI(imno,"DISPLAY_DATA",1,5,&actvals,disp,&unit,&knul) != 0)
      {
      disp[0] = 1;           /* if nothing there, init DISPLAY_DATA */
      disp[1] = 1;
      disp[2] = npix[0]/2 + 1;
      disp[3] = npix[1]/2 + 1;
      disp[4] = 0;
      }
   scale[0] = disp[0];
   scale[1] = disp[1];
   scale[2] = disp[4];                    /* average/omit option (scaling) */

   *icent = disp[2];
   if ( *icent < 1 || *icent > *npix ) *icent = *npix / 2 + 1;
   icent[1] = disp[3];
   if ( icent[1] < 1 || icent[1] > npix[1] ) icent[1] = npix[1] / 2 + 1;
   icent[2] = QMSZX / 2;                           /* screen center pixels */
   icent[3] = QMSZY / 2;


   /* update descriptor DISPLAY_DATA (if we can't too bad, but no abort!) */

   (void) SCDWRI(imno,"DISPLAY_DATA",disp,1,9,&unit);
   SCECNT("PUT",&ec,&el,&ed);                 /* reset error handling */


   /* load the image */

   LOADDR = 0;                                           /* load bottom up */
   SOURCE = 1;                                           /* load image */
   DCLOAD(imno,frame_str,dattyp,icent,cuts,scale,0);
   (void) Cdazvis(QDSPNO,QIMCH,2,1);

   if (dattyp != D_R4_FORMAT) (void) SCFCLO(imno);
   }

dattyp = D_R4_FORMAT;				/* now open as R*4 data */
(void) SCFOPN(frame,dattyp,0,F_IMA_TYPE,&imno);
(void) SCDRDR(imno,"LHCUTS",1,4,&actvals,cuts,&unit,&knul);


/* Get the optional output table name, create and initialize it */

(void) SCKGETC( "OUT_A", 1, 80, &actvals, table );
if ( *table == '+' )
   tid = -1;
else
   {
   (void) TCTINI( table, F_TRANS, F_O_MODE, NRCOL, NRROW, &tid );
   for (ii=0; ii<4; ii++)
      { 
      TCCINI(tid,D_R4_FORMAT,1,"G12.6",tblunit,tbllabl[ii],colref+ii);
      }
   }

/* start the actual job */

VIEWIT_C(plotfl,tid,colref,imno,frame,cuts);


/* Close the table */

if ( tid > 0 )
   {
   (void) sprintf(text,"Created by: VIEW/IMAGE %s",frame);
   (void) SCDWRC(tid,"HISTORY",1,text,-1,80,&unit);
   (void) TCTCLO(tid);
   }

(void) display_it("EOF",0);

/* close display + save global array dzdev */

(void) DCCLOS(QDSPNO);
(void) SCSEPI();

return 0;			/* to make "gcc -Wall" happy... */
}


