/*===========================================================================
  Copyright (C) 1995-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  VIEWIT_C
.LANGUAGE    C
.AUTHOR      K. Banse,			ESO - IPG, Garching
.KEYWORDS    ImageDisplay
.PURPOSE     does the actual work for VIEW.C
.ALGORITHM   uses IDI interfaces, and low and high PLOT interfaces
.INPUT/OUTPUT
  call as    VIEWIT_C( plotfl, cursfl, tid, colref, imno, frame, cuts );

  input:
         int   plotfl     :	display data on a graphics device, flag: 1/0
         char  *cursfl    :	flag for cursor readout (used by GetCursor)
         int   tid        :	table id ( < 0: no table opened & used )
         int   colref[10] :	column numbers (only used if tid >= 0 )
         int   imno       :	id number of frame
         char  *frame     :	name of frame
         float cuts[4]    :	cut values

.RETURNS     nothing
.ENVIRONment MIDAS and AGL
             #include <agl.h>           Prototypes for AGL application programs
             #include <idinumd.h>       Global variables for DISPLAY interfaces
             #include <plot_def.h>      Symbols used by the PLOT interfaces
             #include <midas_def.h>     Prototypes for MIDAS interfaces

.VERSIONS    1.00       940521  from VIEW.FOR    RvH

 100118		last modif
------------------------------------------------------------*/

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

#define  _POSIX_SOURCE 1

/* definition of the used functions in this module */

#include <midas_def.h>
#include <math.h>
#include <stdio.h> 
#include <stdlib.h> 
#include <plot_def.h>
#include <proto_II.h>
#include <idinumd.h>

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

/* Cursor routine constants */

#define C_NUM		0           /* force to single cursor in main window */
#define C_COLOR		2                                    /* cursor color */

/* Constants for sizes and dimensions */

#define NLEVL		5                  /* number of contours to be drawn */
#define PLOTCOL		9		/* synchronize with vcopy.for !!! */

/* Global variables */

static char   *metafl = "view_plot.plt ";      /* default name for meta file */
static char   cunit[50], ident[74];

static double step[3], start[3];

static int    maxsize, naxis, npix[3];         
static int    drrow = -1, drcol = -1;
static int    planoff = 0, ffelem = 1;


static int    zsta[2];		/* parent start frame pixels */
static int    zpix[3];		/* no. of parent frame pixels used */
static int    zwsta[4];		/* [0,1] = start pixels in zoom w. (0,0)
				   [2,3] = scaling factors for subimage */
static int    zinfo[5];		/* zoom window info */
static int    scrpix[4];	/* screen pixels of subimage in main display */
static int    scenter[2];	/* parent center screen pixels */

static float  image[4];		/* start, end pixels of subimage -> plotting */
static float  wcfram[12];	/* world coords of subimage -> plotting */
static float  pfrpix[2];	/* parent center frame pixels */
static float  zcuts[4]={-1,-1,-1,-1};


int  display_it();

/*

*/

/*++++++++++++++++++++++++++++++
.IDENTIFIER  LoadZwn
.PURPOSE     display data in zoom window given the cuts method
.INPUT/OUTPUT
  input:
             int   imno    :	id number of frame
             int   mnmxfl  :	cuts method
             int   methfl  :	statist/magnitude flag
             int   *loadfl :    flag for LOADWN, initflag and data type
             float *cuts   :	cuts in main window

.RETURNS     nothing
.COMMENTS    LOADWN uses global variables
------------------------------*/

#ifdef __STDC__
      static void LoadZwn( int imno, int mnmxfl, int methfl, 
                           int *loadfl, float *cuts)
#else
      static void LoadZwn( imno, mnmxfl, methfl, loadfl, cuts)
      int   imno, mnmxfl, methfl, *loadfl;
      float *cuts;
#endif

{
int   actvals, knul, sigma, unit, naxpix[4], xya[2], xyb[2];
int   nmpix[2];
register int nr;

float  rr, zbins[3], zstat[4];

double  da[3], db[3], dc[3];

char  labl[6], cbuff[81], formstr[20];
static char *cutstr = "Cuts used are: %12.6g%12.6g";


int  Zstats();



/* get size and effective zoom */

(void) Cauxwnd(6,zinfo,xya,xyb);		/* `zinfo' is static! */
ZDSPNO = *zinfo;
zwsta[2] = - zinfo[3];
zwsta[3] = - zinfo[4];



nmpix[0] = zinfo[1]/zinfo[3];	/* x-nopix to fit zoomed into aux_window */
nmpix[1] = zinfo[2]/zinfo[4];	/* y-nopix to fit zoomed into aux_window */


/* ensure, that start + end pixel remain inside */

zsta[0] = pfrpix[0] - nmpix[0]/2;
if (zsta[0] < 1) zsta[0] = 1;
zsta[1] = pfrpix[1] - nmpix[1]/2;
if (zsta[1] < 1) zsta[1] = 1;

zpix[0] = nmpix[0];		
naxpix[0] = zsta[0] + nmpix[0];
nr = naxpix[0]  - npix[0];
if (nr > 0) 				/* spill over last x-pixel */
   {
   zsta[0] -= nr;
   if (zsta[0] < 1)
      {					/* use as much as possible */
      zsta[0] = 1;
      zpix[0] = MYMIN(nmpix[0],npix[0]);
      }
   }
naxpix[0] = zsta[0] + zpix[0] - 1;

zpix[1] = nmpix[1];
naxpix[1] = zsta[1] + nmpix[1];
nr = naxpix[1]  - npix[1];
if (nr > 0)                             /* spill over last y-line */
   {
   zsta[1] -= nr;
   if (zsta[1] < 1)
      {                                 /* use as much as possible */
      zsta[1] = 1;
      zpix[1] = MYMIN(nmpix[1],npix[1]);
      }
   }
naxpix[1] = zsta[1] + zpix[1] - 1;

image[0] = (float) zsta[0];
image[1] = (float) naxpix[0];
image[2] = (float) zsta[1];
image[3] = (float) naxpix[1];

/*
printf("debug::: zsta = %d, %d, zpix = %d, %d\n",
zsta[0],zsta[1],zpix[0],zpix[1]);
printf("debug::: start pixels of subimage: %f, %f \n end pixels: %f, %f\n",
image[0],image[2],image[1],image[3]);
*/

da[0] = (double) zsta[0];
da[1] = (double) zsta[1];
nr = Pixconv("_RW",0,da,db,dc) ;
wcfram[0] = (float) dc[0];
wcfram[FOR_Y] = (float) dc[1];
nr = Pixconv("_RS",0,da,db,dc) ;
rr = (float) dc[0];
scrpix[0] = CGN_NINT(rr);
rr = (float) dc[1];
scrpix[1] = CGN_NINT(rr);

da[0] = (double) (zsta[0] + zpix[0] - 1);
da[1] = (double) (zsta[1] + zpix[1] - 1);
nr = Pixconv("_RW",0,da,db,dc) ;
wcfram[1] = (float) dc[0];
wcfram[FOR_Y+1] = (float) dc[1];
nr = Pixconv("_RS",0,da,db,dc) ;
rr = (float) dc[0];
scrpix[2] = CGN_NINT(rr);
rr = (float) dc[1];
scrpix[3] = CGN_NINT(rr);

if (planoff != 0)
   (void) sprintf(cbuff,"[%12.6g,%12.6g,@%d:%12.6g,%12.6g,@%d]",
          wcfram[0],wcfram[FOR_Y],ZPLANE,wcfram[1],wcfram[FOR_Y+1],ZPLANE);
else
   (void) sprintf(cbuff,"[%14.8g,%14.8g:%14.8g,%14.8g]",
                  wcfram[0],wcfram[FOR_Y],wcfram[1],wcfram[FOR_Y+1]);

if (methfl == 1)
   (void) strcpy(labl,"NYFNH");
else
   (void) strcpy(labl,"NYFXH");
naxpix[0] = naxis;
for (nr=0; nr<3; nr++)
   naxpix[nr+1] = npix[nr];
formstr[0] = '\0';
zbins[0] = 256.0; zbins[1] = zbins[2] = 0.0;
BLANKO_C(cbuff);				/* remove all blanks */


printf("\nstatistics of\n");
(void) Zstats(imno,cbuff,naxpix,zbins,formstr,labl);
     
if ( mnmxfl == 0 )
   {
   zcuts[0] = cuts[0];
   zcuts[1] = cuts[1];
   }
else
   {
   (void) SCKRDR("OUTPUTR",1,4,&actvals,zstat,&unit,&knul);
   if ( mnmxfl == 1 )
      {
      zcuts[0] = zstat[0];
      zcuts[1] = zstat[1];
      }
   else
      {
      if ( mnmxfl < 5 )
         {
         sigma = mnmxfl - 1;
         zcuts[0] = zstat[2] - sigma * zstat[3];
         zcuts[1] = zstat[2] + sigma * zstat[3];
         }
      else
         {
         zcuts[0] = zstat[2] - 0.1 * zstat[1];
         zcuts[1] = zstat[1];
         }

      if ( zcuts[0] < zstat[0] ) zcuts[0] = zstat[0];
      if ( zcuts[1] > zstat[1] ) zcuts[1] = zstat[1];
      }

   (void) sprintf( cbuff, cutstr, *zcuts, zcuts[1] );
   (void) display_it(cbuff,0);
   }

/* finally load the subimage into the zoom window */

LOADWN_C(loadfl,imno,npix,zsta,zpix,zwsta,zcuts);
}

/*

*/

/*++++++++++++++++++++++++++++++
.IDENTIFIER  HcpyZwn
.PURPOSE     make hard copy of zoom window
.INPUT/OUTPUT
 in/output:  int *hcopy :	number of hardcopies made from zoom window

.RETURNS     nothing
------------------------------*/

#ifdef __STDC__
      static void HcpyZwn( int *hcopy )
#else
      static void HcpyZwn( hcopy )
      int *hcopy;
#endif

{ 
int    mm, imnoH, packf, unit;

double Hstart[2], Hstep[2];

char   *pntrH, cbuff[16], output[84];

static int  Hsize = -1;
static float  rdum[4];
static char   imadev[24];



/* get size of zoom window */

if ( Hsize < 0 ) 
   {
   Hsize = zinfo[1] * zinfo[2];

   rdum[0] = rdum[2] = 0.0;
   rdum[1] = rdum[3] = QLUTSZ + PLOTCOL - 1;	/* LUTsize + Plot colours */

   (void) SCKGETC("ZHCOP",1,20,&mm,imadev);
   }


(void) sprintf(cbuff,"view_zcopy%02d",(*hcopy)++);
(void) sprintf(output,"contents of zoom window -> %s.bdf",cbuff);
(void) display_it(output,0);


/* Create 2-dim frame + read data */

Hstart[0] = Hstart[1] = 0.0;
Hstep[0]  = Hstep[1]  = 1.0;
if (QRGBFL == 1)
   {
   (void) SCIPUT(cbuff,D_I4_FORMAT,F_O_MODE,F_IMA_TYPE,2,&zinfo[1],Hstart,Hstep,
              ident,cunit,&pntrH,&imnoH);
   packf = 1;
   }
else
   {
   (void) SCIPUT(cbuff,D_I1_FORMAT,F_O_MODE,F_IMA_TYPE,2,&zinfo[1],Hstart,Hstep,
              ident,cunit,&pntrH,&imnoH);
   packf = 4;
   }

(void) IIDSNP_C(ZDSPNO,0,Hsize,0,0,QDDEP,packf,(unsigned char *) pntrH);

unit = 0;
(void) SCDWRR(imnoH,"ROOT_CUTS",zcuts,1,2,&unit);
(void) SCDWRR(imnoH,"LHCUTS",rdum,1,4,&unit);
mm = NINT(rdum[1]) + 1;
(void) SCDWRI(imnoH,"VCOPY-LUTSIZE",&mm,1,1,&unit);
(void) SCFCLO(imnoH);


#if vms
(void) sprintf(output,"hardcopy %s.ps will be printed out in the end",cbuff);
(void) display_it(output,0);

#else
(void) sprintf(output,"preparing hardcopy %s.ps",cbuff);
(void) display_it(output,0);

(void) sprintf(output,
       "inmidas z+ -p -j \"@ hardcopy %s %s ? ? P PC8NT;bye\" &",imadev,cbuff);
(void) oshcmd(output,NULL,NULL,NULL);
#endif
}

/*

*/

/*++++++++++++++++++++++++++++++
.IDENTIFIER  HcpyPlot
.PURPOSE     make hard copy of graphics window
.INPUT/OUTPUT
 in/output:  int *pcopy :	number of hardcopies made from graphics window

.RETURNS     nothing
------------------------------*/

#ifdef __STDC__
      static void HcpyPlot( int *pcopy )
#else
      static void HcpyPlot( pcopy )
      int *pcopy;
#endif

{ 
char   cbuff[20], output[84];

static int  first = -1;
static char   plotdev[24];



/* get device name for output */

if (first < 0) 
   {
   int  mm;

   first = 0;
   (void) SCKGETC("GHCOP",1,20,&mm,plotdev);
   }


(void) sprintf(cbuff,"view_gcopy%02d.plt",(*pcopy)++);
(void) sprintf(output,"contents of graphics window -> %s",cbuff);
(void) display_it(output,0);
(void) SCFRNM(metafl,cbuff);

#if vms
(void) sprintf(output,"hardcopy on %s will be done in the end",plotdev);
#else
(void) sprintf(output,"preparing hardcopy on %s",plotdev);
(void) display_it(output,0);

(void) sprintf(output,
       "inmidas z+ -p -j \"copy/graph %s %s;bye\" &",plotdev,cbuff);
(void) oshcmd(output,NULL,NULL,NULL);
#endif
}

/*

*/

/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
.IDENTIFIER  GetData
.PURPOSE     extract a subimage from a FRAME and smoothes it (option)
        input: int   imf      file id of related MIDAS frame
               int   maxsize  maximum number of pixels stored
               int   *npix    standart descriptor of the frame
               float *image   contains in pixel units
               int   ffelem   1. plane pixel = (1 + (plane-1)*npix[0]*npix[1])
               int   ism      smoothing parameter
    in/output: float *p_img   pointer to the output frame

.COMMENTS    only two dimensional frames
             uses (little bit more than): 4 * 2 * maxsize Mbyte memory
             
.ENVIRONment MIDAS
             #include <plot_def.h>      Symbols used by the PLT interfaces
             #include <midas_def.h>     Prototypes for MIDAS interfaces

.VERSION     1.0     950627  copied from GETDAT of plot library (RvH)
------------------------------------------------------------*/

void GetData(imf,maxsize,npix,image,ffelem,ism,p_img)

int   imf, maxsize, *npix, ffelem, ism;
float *image, *p_img;

{
int    actvals, felem, ism1, ism2, navrg, nc, nr, nrcol, nrline,
       nrrow, size, ifram[4];
register int ix, iy;

float  avrg, *pntr;

char   *cpntr;


/* get sub-frame dimensions */

ifram[0] = NINT( MYMIN( image[0], image[1] ));
ifram[1] = NINT( MYMAX( image[0], image[1] ));
ifram[2] = NINT( MYMIN( image[2], image[3] ));
ifram[3] = NINT( MYMAX( image[2], image[3] ));

nrcol = ifram[1] - ifram[0] + 1;	/* determine  size of the sub image */
nrrow = ifram[3] - ifram[2] + 1;


/* we can extract nrlines of data from the original */

nrline = maxsize/(*npix);
if (ism != 0)
   {
   nrline = MYMIN((nrrow + 2*ism),nrline); 
   if ( (nrrow = nrline - 2*ism) < 1 ) 
      SCETER(1,"GetData: maxsize too small for given smooth factor");
   }
else
   {
   if (nrrow < nrline) nrline = nrrow;
   }


/* allocate scratch space */

size  = nrline * (*npix);
cpntr = malloc((size_t) (size *sizeof(float)));

if (ism == 0)
   {
   float  *pixptr;
   
   felem = (*npix)*(ifram[2]-1) + ffelem;	/* at beginning of line */
   (void) SCFGET(imf,felem,size,&actvals,cpntr); 
          
   pntr = (float *) cpntr;
   pntr += ifram[0] - 1;
   for (nr=0; nr<nrrow; nr++)
      {
      pixptr = pntr;
      for (nc=0; nc<nrcol; nc++) *p_img++ = *pixptr++;

      pntr += *npix;
      }
   }

else
   { 
      felem = *npix * MYMAX( ifram[2] - ism - 1, 0 ) + ffelem;
      (void) SCFGET(imf,felem,size,&actvals,cpntr); 

      ism1 = MYMIN( ism, ifram[2] - 1 );
      ism2 = MYMIN( ism, npix[1] - ifram[2] + 1 - nrrow );
      nrline = nrrow + ism1 + ism2;
      nrrow = MYMIN( ifram[3], nrrow );
          
      pntr = (float *) cpntr;
      pntr += ism1 * *npix + ifram[0] - 1;
      for (nr=0; nr<nrrow; nr++)
         {
         for (nc=0; nc<nrcol; nc++) 
            {
            navrg = 0;
            avrg  = 0.0;
            for (iy=(-ism); iy<=ism; iy++)
               {
               if ( nr+iy+ism1 >= 0 && nr+iy < nrline )
                  {
                  for (ix=(-ism); ix<=ism; ix++) 
                     {
                     if ( nc+ix >= 0 && nc+ix < *npix )
                        {
                        register int k = nc+ix+iy* *npix;

                        avrg += *(pntr + k);
                        navrg++;
                        }
                     }
                  }
               }

            if ( navrg > 0 )
               *p_img++ = avrg / navrg;
            else
               *p_img++ = 0.0;
            }

         pntr += *npix;
         }
   }
  
(void) free(cpntr);		/* release memory */
}

/*

*/

/*++++++++++++++++++++++++++++++
.IDENTIFIER  ExtrZwn
.PURPOSE     extract data displayed in zoom window
.ALGORITHM   low level and high level PLOT interfaces
.INPUT/OUTPUT
  input:     int  imno   :	id number of frame
             char *pntrF :	pointer to data of frame
             char *name  :	name of frame
             int  plotfl :	graphics flag: row/column/other data displayed 

.RETURNS     nothing
.COMMENTS    uses global variables: start, step, ident, cunit, image
------------------------------*/

#ifdef __STDC__
      static void ExtrZwn(int imno, char *pntrF,char *name,int plotfl)
#else
      static void ExtrZwn(imno,pntrF,name,plotfl)
      char  *pntrF, *name;
      int   imno, plotfl;
#endif

{
char   *pntrE, cbuff[84], output[84]; 

int    imnoE, unit;

static int  ecopy=0;

double fpix[3], wc[3];



(void) sprintf(cbuff,"view_extr%02d.bdf",ecopy++);

if (plotfl == 1)                                              /* extract row */
   {
   float  *xdata;
   xdata = (float *) malloc((size_t) (npix[0]*sizeof(float)));

   (void) sprintf(output,"1-D row -> %s ",cbuff);
   (void) display_it(output,0);

   (void) SCIPUT( cbuff, D_R4_FORMAT, F_O_MODE, F_IMA_TYPE, 1, npix, 
                  start, step, ident, cunit, &pntrE, &imnoE );
   GETBDF( pntrF, image, npix, start, step, xdata, (float *) pntrE);
   fpix[0] = 1.0;			/* dummy x-pix */
   fpix[1] = (double) image[2];
   (void) fp2wc(1,2,fpix,wc);			/* fr_pix => world_co */
   (void) sprintf(cbuff,"[<,%g:>,%g]",wc[1],wc[1]);
   (void) free((char *) xdata);
   }

else if (plotfl == 2)                                      /* extract column */
   {
   float  *xdata;
   xdata = (float *) malloc((size_t) (npix[1]*sizeof(float)));

   (void) sprintf(output,"1-D column -> %s ",cbuff);
   (void) display_it(output,0);

   (void) SCIPUT(cbuff,D_R4_FORMAT,F_O_MODE,F_IMA_TYPE,1,&npix[1], 
                 &start[1],&step[1],ident,cunit,&pntrE,&imnoE);
   GETBDF(pntrF,image,npix,start,step,xdata,(float *)pntrE);
   fpix[0] = image[0];
   fpix[1] = 1.0;			/* dummy y-pix */
   (void) fp2wc(1,1,fpix,wc);			/* fr_pix => world_co */
   (void) sprintf(cbuff,"[%-g,<:%g,>]",wc[0],wc[0]);
   (void) free((char *) xdata);
   }

else
   {
   double Sstart[2];

   (void) sprintf(output,"2-D cursor window -> %s ",cbuff);
   (void) display_it(output,0);
   Sstart[0] = wcfram[0];
   Sstart[1] = wcfram[FOR_Y];
   (void) SCIPUT( cbuff, D_R4_FORMAT, F_O_MODE, F_IMA_TYPE, 2, zpix, 
                  Sstart, step, ident, cunit, &pntrE, &imnoE );
   GetData(imno,maxsize,npix,image,ffelem,0,(float *) pntrE);
   (void) sprintf(cbuff,
          "subimage extracted at (%12.6g,%12.6g) - %d x %d pixels",
          wcfram[0],wcfram[FOR_Y],zpix[0],zpix[1]);
   }


/* Write descriptor */

BLANKO_C(cbuff);			/* get rid of all blanks */

(void) sprintf(output,"Extracted from frame: %s",name);
if (((int)strlen(output) + (int)strlen(cbuff)) > 77)
   {
   (void) CGN_DSCUPD(imno,imnoE,output);
   (void) sprintf(output,"at %s",cbuff);
   unit = 0;
   (void) SCDWRC(imnoE,"HISTORY",1,cbuff,-1,80,&unit);
   }
else
   {
   (void) sprintf(output,"%s at %s",output,cbuff);
   (void) CGN_DSCUPD(imno,imnoE,output);
   }
(void) SCFCLO(imnoE);
}

/*

*/

/*++++++++++++++++++++++++++++++
.IDENTIFIER  MinMax
.PURPOSE     calculate minmax of array
.INPUT/OUTPUT
  input:     float  *array;
             int    ndim;
             float  *min;
             float  *max;

.RETURNS     nothing
.COMMENTS    
------------------------------*/

#ifdef __STDC__
  static void MinMax(float *array, int ndim, float *min, float *max)
#else
  static void MinMax(array, ndim, min, max)
  float *array, *min, *max;
  int   ndim;
#endif

{
register int nr;

register float fval, fmin, fmax;


fmin = *array++;
fmax = fmin;

for (nr=1; nr<ndim; nr++)
   {
   fval = *array++;
   if (fval < fmin)
      fmin = fval;
   else if (fval > fmax)
      fmax = fval;
   }

*min = fmin; *max = fmax;
}

/*

*/

/*++++++++++++++++++++++++++++++
.IDENTIFIER  ViewPlot
.PURPOSE     display data in graphics display
.ALGORITHM   low level and high level PLOT interfaces
.INPUT/OUTPUT
  input:     int  plotfl   :	flag for different display options:
                                 0) histogram, 1) plot row, 2) plot column
                                 3) plot perspective, 4) plot contour
             int  imno     :	id number of frame
             char *pntrF   :	pointer to data of frame
             char *name    :	name of frame

.RETURNS     nothing
.COMMENTS    uses global variables: start, step, ident, cunit, image
------------------------------*/

#ifdef __STDC__
      static void ViewPlot( int plotfl, int imno, 
                          char *pntrF,  char *name)
#else
      static void ViewPlot( plotfl, imno, pntrF, name)
      char  *pntrF, *name;
      int   plotfl, imno;
#endif

{
register int ii;

int   actvals, stat, knul, nrpix, unit, xya[2], xyb[2];

float binsiz, rdum[6], *p_img, *xdata, *ydata;

char  bin[5], cbuff[81];

double  scpix[3], fpix[3], wc[3];




/* initialized and saved variables */

static char  *label[5];
static int   init = TRUE,                             /* initialisation flag */
             access =  0,                             /* parameter PCOPEN */
             plmode = -1,                             /* parameter PCOPEN */
             stype, ltype, binmod;
static float area[4];



binsiz = 0.0;
p_img = xdata = ydata = (float *) 0;

if ((plotfl == 3) && ((*zpix * zpix[1]) > maxsize))
   {
   (void) display_it("Subwindow too large: NO perspective plot",0);
   return;
   }

/* If first call: get symbol type, line type, binmode & write labels */

if ( init )
   {
   init = FALSE;
   PCKRDI( "STYPE", 1, &actvals, &stype );
   PCKRDI( "LTYPE", 1, &actvals, &ltype );
   PCKRDC( "BINMO", 4, &actvals, bin );
   binmod = (strncmp( bin, "ON", 2 ) == 0) ? 1 : 0;

   for ( ii = 0; ii < 5; ii++ ) label[ii] = malloc((size_t)81);

   (void) strcpy( label[0], "Position(");
   (void) strcpy( label[1], "Position(");
   (void) strcpy( label[2], "Pixel value(" );
   (void) strcpy( label[3], "Frame: " );
   (void) strcpy( label[4], "Ident: " );

   if ((int)strlen(cunit) > 32)
      (void) strncat(label[1],cunit+32,16);
   if ((int)strlen(cunit) > 16) 
      (void) strncat(label[0],cunit+16,16);
   if ((int)strlen(cunit) > 0) 
      (void) strncat(label[2],cunit,16);

   for (ii=0; ii<3; ii++)
      {
      (void) strcat(label[ii],")");
      LABSTR(label[ii]);
      }
   (void) strcat(label[3],name);
   (void) strcat(label[4],ident);
   }

PCKWRR("SCALE",0,rdum);			/* scaling to default */
PCKWRR("OFFSET",0,rdum);		/* offset to default */

scpix[0] = (double) scenter[0];		/* center of rectangle in main w. */
scpix[1] = (double) scenter[1];
scpix[2] = 1.0;


/* first collect data */

switch( plotfl )
   {
   case 0:                                                /* PLOT HISTOGRAM */
     {
     int   *ival;
     float histb[5];

     (void) SCDRDR(imno, "HIST_BINS", 1,5, &actvals, histb, &unit, &knul);
     nrpix  = NINT( *histb );
     binsiz = histb[1];

     ival  = (int *)   malloc((size_t)(nrpix*sizeof(int)));
     xdata = (float *) malloc((size_t)(nrpix*sizeof(float)));
     ydata = (float *) malloc((size_t)(nrpix*sizeof(float)));

     *xdata = histb[2];
     if ( histb[4] != 0.0 ) *xdata -= binsiz;
     for (ii=1; ii<nrpix; ii++) xdata[ii] = *xdata + ii * binsiz;
     wcfram[0] = *xdata;
     wcfram[1] = xdata[nrpix-1];
        
     (void) SCDRDI(imno,"HISTOGRAM",1,nrpix,&actvals,ival,&unit,&knul);
     for (ii=0; ii<nrpix; ii++) ydata[ii] = (float) ival[ii];

     MinMax(ydata,nrpix,wcfram+FOR_Y,wcfram+FOR_Y+1);
     (void) free( (char *) ival );
     }
     break;

   case 1:                                                      /* plot row */
     nrpix = npix[0];
     xdata = (float *) malloc((size_t)(nrpix*sizeof(float)));
     ydata = (float *) malloc((size_t)(nrpix*sizeof(float)));

     /* get central row no. (frame pixel) and central col. no. */

     (void) Pixconv("IRW",0,scpix,fpix,wc);
     image[2] = (float) fpix[1];		/* frame pixel (y) */
     image[3] = image[2];
     rdum[0] = (float) wc[0];
     rdum[1] = rdum[0];

     /* copy data of complete row */

     image[0] = 1.0;
     image[1] = npix[0];
     GETBDF(pntrF,image,npix,start,step,xdata,ydata);
     MinMax(ydata,nrpix,wcfram+FOR_Y,wcfram+FOR_Y+1);
     fpix[0] = 1.0;
     fpix[1] = 1.0;				/* dummy y-pix */
     stat = fp2wc(1,1,fpix,wc);
     wcfram[0] = (float) wc[0];
     fpix[0] = (double) npix[0];
     (void) fp2wc(1,1,fpix,wc);
     wcfram[1] = (float) wc[0];
     drrow = 2;
     Cauxwnd(7,&drrow,xya,xyb);			/* draw horizontal line */
     break;

   case 2:                                                   /* plot column */
     nrpix = npix[1];
     xdata = (float *) malloc((size_t)(nrpix*sizeof(float)));
     ydata = (float *) malloc((size_t)(nrpix*sizeof(float)));

     /* get central col. no. (frame pixel) and central row no. */

     (void) Pixconv("IRW",0,scpix,fpix,wc);
     *image = fpix[0];			/* frame pixel (x) */
     image[1] = *image;
     rdum[0] = (float) wc[1];
     rdum[1] = rdum[0];

     /* copy data of column */

     image[2] = 1.0;
     image[3] = npix[1];
     GETBDF(pntrF,image,npix,start,step,xdata,ydata);
     MinMax(ydata,nrpix,wcfram+FOR_Y,wcfram+FOR_Y+1);
     fpix[1] = 1.0;
     (void) fp2wc(1,2,fpix,wc);
     wcfram[0] = (float) wc[1];
     fpix[1] = (float) npix[1];
     (void) fp2wc(1,2,fpix,wc);
     wcfram[1] = (float) wc[1];
     drcol = 2;
     Cauxwnd(8,&drcol,xya,xyb);			/* draw vertical line */
     break;

   case 3:                                              /* PLOT PERSPECTIVE */
     nrpix = *zpix * zpix[1];
     p_img = (float *) malloc((size_t)(nrpix*sizeof(float)));
     GetData(imno,maxsize,npix,image,ffelem,1,p_img);
     if ( step[0] < 0.0 )
        {
        rdum[0] = wcfram[0];
        wcfram[0] = wcfram[1];
        wcfram[1] = rdum[0];
        }
     if ( step[1] < 0.0 )
        {
        rdum[0] = wcfram[FOR_Y];
        wcfram[FOR_Y]   = wcfram[FOR_Y+1];
        wcfram[FOR_Y+1] = wcfram[FOR_Y];
        }
     MinMax(p_img,nrpix,wcfram+FOR_Z,wcfram+FOR_Z+1);
     break;

   case 4:                                                  /* PLOT CONTOUR */
     PCKWRC( "FRAME", "SQUA" );
     nrpix = *zpix * zpix[1];
     p_img = (float *) malloc((size_t)(nrpix*sizeof(float)));
     GetData(imno,maxsize,npix,image,ffelem,1,p_img);
     MinMax(p_img,nrpix,wcfram+FOR_Z,wcfram+FOR_Z+1);
     break;

   default:                                                        /* ERROR */
     return;
   }


/* Calculate small and big tickmarks, set world and pixel coordinate box,
   and set up the graphics device according to MIDAS settings */

if ( fabs( wcfram[2] ) < PLT_EPS && fabs( wcfram[3] ) < PLT_EPS )
   {
   area[0] = wcfram[0];
   area[1] = wcfram[1];
   area[2] = wcfram[FOR_Y];
   area[3] = wcfram[FOR_Y+1];

   GETFRM( "AUTO", wcfram );
   PCKWRR( "XWNDL", 4, wcfram );
   GETFRM( "AUTO", wcfram + FOR_Y );
   PCKWRR( "YWNDL", 4, wcfram + FOR_Y );
   if ( plotfl > 2 )
      {
      GETFRM( "AUTO", wcfram + FOR_Z );    
      PCKWRR( "ZWNDL", 4, wcfram + FOR_Z );
      }
   }     

PCKWRR( "PIXEL", 4, image );
PCOPEN( " ", metafl, access, &plmode );


/* plot the data and draw a frame (if requested) */

switch( plotfl )
   {
   case 0:                                                /* PLOT HISTOGRAM */
     {
     static float fopt[3] = { 0., -999999., 0. };   /* layout histogram */

     PCHIST( nrpix, xdata, ydata, fopt );
     if ( plmode > 0 )
        {
        PCFRAM( wcfram, wcfram + FOR_Y, label[2], "Frequency" );
        PLIDEN( plmode, label[3], label[4] );
        PLHFRI( plmode, name, ident, nrpix, binsiz );
        }
     (void) free( (char *) xdata );
     (void) free( (char *) ydata );
     }
     break;

   case 1:                                                      /* PLOT ROW */
   case 2:                                                   /* PLOT COLUMN */
     {
     static float offset  = 0.0;                 /* no y-offs in PCDATA */

     PCDATA( stype, ltype, binmod, xdata, ydata, offset, nrpix );
     if ( plmode > 0 )
        {
        if ( plotfl == 1 )
           PCFRAM( wcfram, wcfram+FOR_Y, label[0], label[2] );
        else
           PCFRAM( wcfram, wcfram+FOR_Y, label[1], label[2] );
        PCKRDR("YWNDL",2,&actvals,&rdum[2]); /* get y-min, max */
        PCDATA(0,5,0,rdum,&rdum[2],0.,2);
        PLBDFI( plmode, name, ident, image );
        if ( plmode == 1 ) 
           {
           if ( plotfl == 1 )
              (void) sprintf( cbuff, "Row: # %-.0f", image[2] );
           else
              (void) sprintf( cbuff, "Column: # %-.0f", image[0] );
           PLIDEN( plmode, label[3], cbuff );
           }
        }
     (void) free( (char *) xdata );
     (void) free( (char *) ydata );
     }
   break;

   case 3:                                              /* PLOT PERSPECTIVE */
     {
     static int   xyflg[2] = { 1, 1 };             /* drw x & y lines   */
     static float angle[2] = { 45.0, 30.0 },       /* altitude  45 deg. */
                                                        /* azimuth   30 deg. */
     scale[2] = {  1.0,  0.0 };       /* screen filling    */
                                                        /* no offset         */

     PLPER( wcfram, p_img, image, start, step, angle, scale, xyflg );
     if ( plmode > 0 )
        { 
        PLFRM3(wcfram,wcfram+FOR_Y,wcfram+FOR_Z,
               label[0],label[1],label[2],angle,*scale);
        PLPERI( plmode, name, ident, image, angle, wcfram );
        PLIDEN( plmode, label[3], label[4] );
        }
     (void) free( (char *) p_img );
     }
   break;

   case 4:                                                  /* PLOT CONTOUR */
     {
     static int  ctype[NLEVL] = { -4, -2, -6, -3, -1 };
     float zfac, clevl[NLEVL];

     zfac = (zcuts[1] - *zcuts) / (NLEVL + 1);
     *clevl = *zcuts + zfac;
     for ( ii = 1; ii < NLEVL; ii++ )
        clevl[ii] = clevl[ii-1] + zfac;              /* contour levels */

     PLCON( p_img, image, area, step, NLEVL, clevl, ctype );
     if ( plmode > 0 )
        {
        PCFRAM( wcfram, wcfram+FOR_Y, label[0], label[1] );
        PLCONI( 2, name, ident, clevl, ctype, NLEVL );
        }
     PCKWRC( "FRAME", "AUTO" );
     (void) free( (char *) p_img );
     }
     break;
  }


/* close the meta file (opened in PCOPEN) */        

AG_MCLS();
}

/*

*/

/*++++++++++++++++++++++++++++++
.IDENTIFIER  Change_LoHi
.PURPOSE     change low and high cut values for auxiliary or main window
.INPUT/OUTPUT
  input:     int  cooco   :	number of cursor inputs
             int  imno    :	id number of frame
             char *pntrF  :	pointer to data of frame
             char *name   :     name of frame
             int  *loadfl :	flag for LOADWN, init flag and data type
             int  plotfl  :	flag for ViewPlot, histogram, row, contour, etc
.RETURNS     nothing
.COMMENTS    LOADWN & ViewPlot are using global variables
------------------------------*/

#ifdef __STDC__
      static void Change_LoHi( int cooco, int imno, char *pntrF, char *name,
                               int *loadfl, int plotfl)
#else
      static void Change_LoHi( cooco, imno, pntrF, name, loadfl, plotfl)
      char *pntrF, *name;
      int  imno, cooco, plotfl, *loadfl;
#endif

{
int    actvals, idum, knul, unit, vis, num;

float  cuts[2];

double ddum;

char   input[56];

static char q_minmax[72] = 
 "Enter lcut,hcut (zoom window) or lcut,hcut,main (main w.) and RETURN): ";


(void) display_it(q_minmax,0);
num = 55;
Cgetstr(input,&num);
num = CGN_CNVT(input,2,2,&idum,cuts,&ddum);

if (num < 2)
   display_it("Invalid input...", 0);
else
   {
   num = CGN_JNDEXC(input,',') + 1;		/* search for last ',' */

   if ((input[num] == 'm') || (input[num] == 'M'))	   /* main window */
      {
      unit = 0;
      (void) SCDWRR(imno,"LHCUTS",cuts,1,2,&unit);
      *loadfl = -100;
      LOADWN_C(loadfl,imno,npix,zsta,zpix,zwsta,cuts); 
      (void) SCKRDI("DAZHOLD",8,1,&actvals,&vis,&unit,&knul);
      WIMCLO_C(QDSPNO,QIMCH,vis,name,start,step,cuts);
      *loadfl = -1;		/* reset to aux_window #1 */
      }

   else                                                     /* zoom window */
      {
      if ( cooco == 0 )
         display_it( "Extract a subwindow first...", 0 );
      else
         {
         zcuts[0] = cuts[0];
         zcuts[1] = cuts[1];
         LOADWN_C(loadfl,imno,npix,zsta,zpix,zwsta,zcuts);

         /* update graphics display only for contour plots */

         if ( plotfl == 4 ) ViewPlot(plotfl,imno,pntrF,name);
         }
      }
   }
}

/*

*/

/*++++++++++++++++++++++++++++++
.IDENTIFIER  Calc_Magn
.PURPOSE     calculate magnitude around center of subwindow
.INPUT/OUTPUT
  input:     int  magpix :
             int  bakpix :
             int  nompix :
             char *pntrF :

.RETURNS     nothing
.COMMENTS    
------------------------------*/

#ifdef __STDC__
      static void Calc_Magn( int magpix, int bakpix, int nompix, char *pntrF )
#else
      static void Calc_Magn( magpix, bakpix, nompix, pntrF )
      int  magpix, bakpix, nompix;
      char *pntrF;
#endif

{
int   radius, stat, bgnA[2], wpix[2], ifram[4];
float *pntrW, mag, dmag, sky, dsky, nrpix, flux, xyval, 
      xypos[2], xyerr[2], xysig[2], xycen[2], fac;
char  output[81];

static int offsW[2] = { 1, 1 };

fac = 2.0;			/* default for sigma-kappa clipping */
radius = magpix + bakpix + nompix + 1;
bgnA[0] = NINT((image[1] + image[0])/ 2) - radius;
bgnA[1] = NINT((image[3] + image[2])/ 2) - radius;

if ( SCALX > 1 )
   wpix[0] = 2 * radius + SCALX;
else
   wpix[0] = 2 * radius + 1;

if ( SCALY > 1 )
   wpix[1] = 2 * radius + SCALY;
else
   wpix[1] = 2 * radius + 1;
pntrW = (float *) malloc((size_t)(wpix[0]*wpix[1]*sizeof(float)));

Ccopyf1( (float *) pntrF, npix, bgnA, wpix, pntrW, wpix, offsW );

ifram[0] = ifram[2] = 0;		/* C indexing */
ifram[1] = wpix[0] - 1;
ifram[3] = wpix[1] - 1;
(void) Cstacen( "GAU", pntrW, wpix, ifram, xypos, xyerr, xysig, &xyval );

xycen[0] = (float) (start[0] + step[0] * ( xypos[0] + bgnA[0] - 1 ));
xycen[1] = (float) (start[1] + step[1] * ( xypos[1] + bgnA[1] - 1 ));

stat = Cjmagn(3,pntrW,wpix,nompix,bakpix,&fac,xypos,&mag,&dmag,&sky,&dsky,
              &nrpix,&flux);
if (stat == 1)
   { 
   (void) display_it(ident,-9);
   (void) display_it("WARNING: source not in center... ",0);
   }
(void) sprintf(output,"xcenter, ycenter: %-.6g, %-.6g",xycen[0],xycen[1]);
(void) display_it(output,0);
(void) sprintf(output,"magnitude: %#10.6g  +/-%#10.5g   radius = %-d pixels",
                mag, dmag, magpix );
(void) display_it(output,0);
(void) sprintf(output,"sky      : %#10.6g  +/-%#10.5g   radius = %-d pixels",
                sky, dsky, bakpix );
(void) display_it(output,0);
(void) sprintf(output,
       "flux     : %#10.6g              NoMansLand = %-d pixels",flux,nompix);
(void) display_it(output,0);

(void) free( (char *) pntrW );
}

/*

*/

/*++++++++++++++++++++++++++++++++++++++++++++++++++
  
 main function VIEWIT_C 

++++++++++++++++++++++++++++++++++++++++++++++++++*/

#ifdef __STDC__
void VIEWIT_C(int plotfl, int tid, int *colref, int imno, 
              char *frame, float *cuts)

#else
void VIEWIT_C(plotfl,tid,colref,imno,frame,cuts)
char  *frame;
int   plotfl, tid, imno, *colref;
float *cuts;
#endif

{
int    actvals, forma, knul, statA, statB, unit;
int    mm, idum[4];

float  rdum[4], xyinfoA[7], xyinfoB[7];

double ddum, da[3], db[3], dc[3];

char   *pntrF, ccbuf[64], output[84];
char   cB, cursfl[8];

/* initialized variables */

int cooco     = 0,                                     /* coordinate counter */
    methfl    = 0,                              /* STATISTICS/magnitude flag */
    mnmxfl    = 0,                              /* cuts method, default MNMX */
    magpix    = 6,                              /* size of the source, JMAGN */
    bakpix    = 2,                             /* # background pixels, JMAGN */
    nompix    = 2,                          /* # no man's land pixels, JMAGN */
    once      = TRUE,                                 /* display header once */
    go_on     = TRUE,                                           /* loop flag */
    give_info = TRUE;                                           /* info flag */

static int  pcopy=0, hcopy=0;
static int  loadfl[2] = { -1, D_R4_FORMAT },    /* aux_window, R*4 data flag */
            coords[4] = { -1, -1, -1, -1 };    /* initial position of cursor */

static char *info_usr = "switch cursor(s) on - next time we exit...",
            *infomagn = 
 "Enter radius for Magnitude, Nomansland, Sky (in frame pixels) ",
            *infolabl = 
 "   frame pixels             world coords        intensity ";

static char *meth_str[2] = { "Calculate basis statistics for subwindow",
                             "Compute magnitude of center in subwindow" 
                           },
            *plot_str[5] = { "Histogram plotting mode",
                             "Line plotting mode",
                             "Column plotting mode",
                             "Perspective plotting mode",
                             "Contour plot mode"
                           },
            *mnmx_str[6] = { "Unchanged cuts for zoom window",
                             "Local minmax for zoom window",
                             "Local mean+-sigma as cuts for zoom window",
                             "Local mean+-2*sigma as cuts for zoom window",
                             "Local mean+-3*sigma as cuts for zoom window",
                             "Local mean-0.1*max,max as cuts for zoom window" 
                           };





/* get mapping size */

(void) SCKRDI("MONITPAR",20,1,&actvals,idum,&unit,&knul);
maxsize = idum[0] * idum[0];
zwsta[0] = zwsta[1] = 0;
strcpy(cursfl,"YNYZZV0");		/* continuous readout in main w. */


/* Init cursors in main window, get cursor shape from keyword DAZHOLD */

(void) SCKRDI("DAZHOLD",2,1,&actvals,&forma,&unit,&knul);
if (forma == -1) forma = 3;
SETCUR_C(QDSPNO,C_NUM,forma,C_COLOR,coords);

if (cuts[0] >= cuts[1])
   {
   cuts[0] = cuts[2];		/* if no cuts given, use min, max */
   cuts[1] = cuts[3];
   }


/* Read frame descriptor */

for (mm=0; mm<3; mm++)
   {
   npix[mm] = 1;
   start[mm] = 0.0;
   step[mm] = 1.0;
   }
(void) SCDRDI(imno,"NAXIS",1,1,&actvals,&naxis,&unit,&knul);
(void) SCDRDI(imno,"NPIX",1,naxis,&actvals,npix,&unit,&knul);
(void) SCDRDD(imno,"START",1,naxis,&actvals,start,&unit,&knul);
(void) SCDRDD(imno,"STEP" ,1,naxis,&actvals,step,&unit,&knul);
(void) SCDGETC(imno,"IDENT",1,72,&actvals,ident);
(void) SCDGETC(imno,"CUNIT",1,48,&actvals,cunit);
mm = npix[0] * npix[1];
if (ZPLANE != 0) planoff = (ZPLANE-1)*mm;
ffelem = planoff + 1;
(void) SCFMAP(imno,F_I_MODE,ffelem,mm,&actvals,&pntrF);
da[2] = db[2] = dc[2] = 1.0;
if (Pixconv("INIT",imno,da,db,dc) > 0)       /* init wc conversion */
   SCETER(69,"initialization of world coord. conversion failed ...");


/* read cursor position(s) */

(void) strcpy(ccbuf, " ");                            /* init GetCursor... */
while (go_on)
   {
   GetCursor(cursfl,ccbuf,xyinfoA,&statA,xyinfoB,&statB);

   if (once) 
      {
      display_it(infolabl,0);
      once = FALSE;
      }

   if (statA == 1)                              /* status of cursor = on */
      { 
      (void) sprintf(output,"%8.1f%8.1f %12.6g%12.6g %12.6g",
      xyinfoA[2],xyinfoA[3],xyinfoA[4],xyinfoA[5],xyinfoA[6]);
      (void) SCTDIS(output,80);
      }

   else if (statA == -9)                          /* input from keyboard */
      {
      cB = (char) statB;

      switch (cB)
         {
         case 'v':                      /* toggle between statistics */
                                                /* and magnitude calculation */
           methfl = (methfl == 0) ? 1 : 0; 
           (void) display_it(meth_str[methfl],80);
           break; 

         case 'm':                     /* enter different low, hicut */
           Change_LoHi(cooco,imno,pntrF,frame,loadfl,plotfl);
           break; 

         case 't':                    /* toggle different plot modes */
           if (plotfl != -1)
              {
              if (++plotfl > 4) plotfl = 0;
              (void) display_it(plot_str[plotfl],80);
              }
           break; 

         case 's':                    /* toggle local min,max or not */
           if (++mnmxfl > 5) mnmxfl = 0;
           (void) display_it(mnmx_str[mnmxfl],80);
           break; 

         case 'p':                   /* save metafile from last plot */
           if (cooco > 0) HcpyPlot(&pcopy);
           break; 

         case 'q':                   /* make hardcopy of zoom window */
           if (cooco > 0) HcpyZwn(&hcopy);
           break; 

         case 'e':                      /* extract current sub frame */
           if (cooco > 0) ExtrZwn(imno,pntrF,frame,plotfl);
           break; 

         case 'a':                     /* new magpix, bakpix, nompix */
           if (cooco > 0)
              {
              (void) display_it(infomagn,0);
              Cgetstr(output,&actvals);
              actvals = CGN_CNVT(output,1,3,idum,rdum,&ddum); 
              if (actvals < 3)
                 (void) display_it("Invalid input...",0);
              else
                 { 
                 if ( idum[0] < 1 || idum[1] < 0 || idum[2] < 0 )
                    (void) display_it("Invalid input...",80);
                 else
                    {
                    magpix = *idum;
                    nompix = idum[1];
                    bakpix = idum[2];
                    }
                 }
              }
              break; 

         case 'g':                     /* get cursor in zoom window */
           if (cooco > 0)
              {
              float  *pf;
              int  in[5];

              in[0] = QIMCH;                   /* copy area into zoom window */
              in[1] = QOVCH;
              in[2] = 0;
              in[3] = 0;
              in[4] = 1;

              statB = Cauxwnd(21,in,scrpix,idum);	/* ret. idum not used */
              (void) display_it(infolabl,0);

            curs_loop:
              statB = Cauxwnd(22,zsta,idum,in);		/* ret. in not used */
              if (statB == 0) break;

              da[0] = (double) idum[0];
              da[1] = (double) idum[1];
              statB = Pixconv("_RW",0,da,db,dc) ;
              rdum[2] = (float) idum[0];
              rdum[3] = (float) idum[1];
              pf = (float *)pntrF;
              rdum[0] = *(pf + (idum[1]-1)*npix[0] + (idum[0]-1));
              (void) sprintf(output,"%8.1f%8.1f %12.6g%12.6g %12.6g",
                     rdum[2],rdum[3],dc[0],dc[1],rdum[0]);
              display_it(output,0);
              goto curs_loop;
              }
 
         default:
           break; 
         }
      }

   else                              /* here we got a real cursor input... */
      {
      (void) display_it(output,0);
      (void) display_it(output,-9);			/* clear line */
      if (statA == 0)					/* check for EXIT */
         { 
         if (cooco == 0)
            { 
            if (give_info == FALSE)
               go_on = FALSE;                            /* we EXIT! */
            else
               {
               SCTPUT(info_usr);
               (void) strcpy(ccbuf," ");
               give_info = FALSE;
               }
            }
         else
            go_on = FALSE;                                 /* we EXIT! */
         }
      else
         {
         register int ii;

         if (drrow != -1)		/* erase last hor./vert. line */
            {
            drrow = 1;
            Cauxwnd(7,&drrow,idum,&idum[3]);
            drrow = -1;
            }
         if (drcol != -1)
            {
            drcol = 1;
            Cauxwnd(8,&drcol,idum,&idum[3]);
            drcol = -1;
            }

         cooco++;                         /* update coordinate counter */

         scenter[0] = CGN_NINT(xyinfoA[0]);	/* get parent center pixel */
         scenter[1] = CGN_NINT(xyinfoA[1]);
         da[0] = (double) xyinfoA[0];
         da[1] = (double) xyinfoA[1];
         mm = Pixconv("IRW",0,da,db,dc) ;
         pfrpix[0] = (float) db[0];
         pfrpix[1] = (float) db[1];

/*
printf("\ncursor: %d, %d, frpix: %f, %f\n",
scenter[0],scenter[1],pfrpix[0],pfrpix[1]);
*/

         for (ii=0; ii<12; ii++) wcfram[ii] = 0.0;

         LoadZwn(imno,mnmxfl,methfl,loadfl,cuts);

         /* fill table, if applicable */

         if (tid > 0)
            {
            rdum[0] = wcfram[0];
            rdum[1] = wcfram[FOR_Y];
            rdum[2] = wcfram[1];
            rdum[3] = wcfram[FOR_Y+1];
            (void) TCRWRR( tid, cooco, 4, colref, rdum );
            }

         if (methfl == 1)                    /* magnitude conversion */
            Calc_Magn( magpix, bakpix, nompix, pntrF );
         else                                       /* do the plotting */
            ViewPlot(plotfl,imno,pntrF,frame);
         }
      }
   }						/* end of the while loop */


#if vms

/* save number of frames created and return clear line */

idum[0] = pcopy;
idum[1] = hcopy;
(void) SCKWRI("OUTPUTI",idum,11,2,&unit);
#else
#endif

(void) display_it(output,-9);

}
