/*===========================================================================
  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
===========================================================================*/

/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
.IDENTifer   PLOTVEC
.AUTHOR      R.M. van Hees IPG-ESO Garching
.KEYWORDS    Graphics, bulk data frame
.LANGUAGE    C
.PURPOSE     Plots vectors (polarisation map) from 2 two-dimensional FRAME
  in/output: IN_A/C/1/60   = input frame with intensisty information
             IN_B/C/1/60   = input frame with position angle information
             INPUTC/C/1/72 = coord_string (default: whole frame)
             INPUTR/R/1/3  = scale of vector [units/mm]
                             position angle range (default: 0,360)
             INPUTI/I/1/2  = smooting parameter (default: 1)
                             head (default: 1, the vector get an arrow)

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

.VERSION     1.1     25-Nov-1993   Removed restrictions on frame size, RvH
             1.0     10-Sep-1993   FORTRAN --> C        RvH

 090710		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>

#define MAXLEV		50
#define MAXPIX          512    /* max frame dimension (X,Y) accessed at once */
#define MAXSIZ          (MAXPIX * MAXPIX)

/*
 * here starts the code of the function
 */
int main()
{
register int ii;
int     actvals, chunks, head, imfA, imfB, knul, last_row, naxis, 
        size, stat, unit, ndum[PLDIM2], npixA[PLDIM2], npixB[PLDIM2], 
        sublo[PLDIM2], subhi[PLDIM2];

float   amin, amax, *p_imgA, *p_imgB, scar, nrpix[2], ranp[4], area[4], 
        image[4], wcfram[12];

double  startA[PLDIM2], stepA[PLDIM2], startB[PLDIM2], stepB[PLDIM2];

char    cmnd[21], nameA[61], nameB[61], cunitA[49], identA[33], identB[33], 
        input[73], *label[4];
/*
 * initialised variables
 */
char  *err_start = "*** FATAL: START descriptor of the frames differ",
      *err_step  = "*** FATAL: STEP descriptor of the frames differ",
      *err_npix  = "*** FATAL: NPIX descriptor of the frames differ",
      *err_1dim  = "*** FATAL: the frames have only one dimension",
      *err_coord = "*** FATAL: invalid coordinate input ...",
      *err_xcuts = "*** FATAL: range in x has no overlap with current graph abscissa - NO PLOT",
      *err_ycuts = "*** FATAL: range in y has no overlap with current graph abscissa - NO PLOT";

static char *axis[PLDIM2] = { "MANU", "MANU" };

int     access =  0,                      /* parameter for PCOPEN: plot mode */
        plmode = -1,                   /* plot mode taken from keyword PMODE */
        ismoot =  1;                      /* Default no smooting of the data */
/*
 * allocate memory for different character pointers and initialise a few
 */
for ( ii = 0; ii < 4; ii++ ) label[ii] = osmmget(81);

(void) strcpy( label[0], "Position (" );
(void) strcpy( label[1], "Position (" );

/*
 * start of executable code
 */
(void) SCSPRO( "PLTVEC" );                   /*contact with the MIDAS monitor*/
(void) SCKGETC( "MID$CMND", 1, 20, &actvals, cmnd );
if ( *cmnd == 'O' ) access = 1; 

/*
 * find file name and size information of first frame
 */
(void) SCKGETC( "IN_A", 1, 60, &actvals, nameA );
(void) SCFOPN( nameA, D_R4_FORMAT, 0, F_IMA_TYPE, &imfA );
(void) SCDRDI( imfA, "NAXIS", 1, 1, &actvals, &naxis, &unit, &knul );
(void) SCDRDI( imfA, "NPIX" , 1, PLDIM2, &actvals, npixA , &unit, &knul );
if ( naxis < 2 || (npixA[0] == 1 || npixA[1] == 1) ) SCETER( 1, err_1dim );

/*
 * find file name and size information of second frame
 */
(void) SCKGETC( "IN_B", 1, 60, &actvals, nameB );
(void) SCFOPN( nameB, D_R4_FORMAT, 0, F_IMA_TYPE, &imfB );
(void) SCDRDI( imfB, "NPIX" , 1, PLDIM2, &actvals, npixB , &unit, &knul );
if ( npixA[0] != npixB[0] || npixA[1] != npixB[1] ) SCETER( 2, err_npix );

/*
 * read descriptor of first frame
 */
(void) SCDRDD( imfA, "START", 1, PLDIM2, &actvals, startA, &unit, &knul );
(void) SCDRDD( imfA, "STEP" , 1, PLDIM2, &actvals, stepA , &unit, &knul );
(void) SCDGETC( imfA, "IDENT", 1, 32, &actvals, identA );
(void) SCDGETC( imfA, "CUNIT", 1, 48, &actvals, cunitA );

/*
 * read descriptor of second frame
 */
(void) SCDRDD( imfB, "START", 1, PLDIM2, &actvals, startB, &unit, &knul );
(void) SCDRDD( imfB, "STEP" , 1, PLDIM2, &actvals, stepB , &unit, &knul );
(void) SCDGETC( imfB, "IDENT", 1, 32, &actvals, identB );

/*
 * do both frames overlap?
 */
if ( startA[0] != startB[0] || startA[1] != startB[1] ) SCETER( 3, err_start );
if ( stepA[0] != stepB[0] || stepA[1] != stepB[1] ) SCETER( 4, err_step );

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

/*
 * read window coordinates and take action
 */
(void) SCKGETC( "INPUTC", 1, 60, &actvals, input );

if ( *input == 'm' || *input == 'M' )                      /* manual scaling */
   { BOXWTP( wcfram,       npixA[0], startA[0], stepA[0], image );
     BOXWTP( wcfram+FOR_Y, npixA[1], startA[1], stepA[1], image+2 );
   }
else
   { if ( *input == 'c' || *input == 'C' )                  /* display input */
        { (void) SCKRDR( "OUTPUTR", 10, 1, &actvals, image, &unit, &knul);
          (void) SCKRDR( "OUTPUTR", 11, 1, &actvals, image+2, &unit, &knul); 
          (void) SCKRDR( "OUTPUTR", 15, 1, &actvals, image+1, &unit, &knul);
          (void) SCKRDR( "OUTPUTR", 16, 1, &actvals, image+3, &unit, &knul);
        }
     else                                               /* automatic scaling */
        { stat = Convcoo(1,imfA,input,PLDIM2,ndum,sublo,subhi);
          if ( stat != ERR_NORMAL ) SCETER( 5, err_coord );
          image[0] = sublo[0] + 1;
          image[1] = subhi[0] + 1;
          image[2] = sublo[1] + 1;
          image[3] = subhi[1] + 1;
        }
   }
BOXPTW( image,   npixA[0], startA[0], stepA[0], area );
BOXPTW( image+2, npixA[1], startA[1], stepA[1], area+2 );

PCKWRR( "PIXEL", 4, image );

if ( access == 0 )
   { 
/*
 * get size of frame along X-axis
 */
     if ( fabs( *wcfram ) < PLT_EPS && fabs( *(wcfram+1) ) < PLT_EPS )
        { wcfram[0] = area[2];
          wcfram[1] = area[3]; 
          wcfram[2] = wcfram[3] = 0.0;
        }
/*
 * get size of frame along Y-axis
 */
     if ( fabs( *(wcfram+FOR_Y) ) < PLT_EPS 
          && fabs( *(wcfram+FOR_Y+1) ) < PLT_EPS )
        { axis[1] = "AUTO";
          wcfram[FOR_Y]   = area[2];
          wcfram[FOR_Y+1] = area[3]; 
          wcfram[FOR_Y+2] = wcfram[FOR_Y+3] = 0.0;
        }
     GETFRM( axis[0], wcfram );
     GETFRM( axis[1], wcfram + FOR_Y );
     PCKWRR( "XWNDL", 4, wcfram );
     PCKWRR( "YWNDL", 4, wcfram+FOR_Y );
   }
else                                                         /* overplot mode*/
   { PCKRDR( "XWNDL", 4, &actvals, wcfram );
     PCKRDR( "YWNDL", 4, &actvals, wcfram+FOR_Y );                       
/*
 * does overplot data  fall within plotted frame? 
 */
     amin = MYMIN( *wcfram, *(wcfram + 1) );
     amax = MYMAX( *wcfram, *(wcfram + 1) );
     if ( ( MYMAX( area[0], area[1] ) < amin ) ||
          ( MYMIN( area[0], area[1] ) > amax ) )
        SCETER( 6, err_xcuts );

     amin = MYMIN( *(wcfram + FOR_Y), *(wcfram + FOR_Y + 1) );
     amax = MYMAX( *(wcfram + FOR_Y), *(wcfram + FOR_Y + 1) );
     if ( ( MYMAX( area[2], area[3] ) < amin ) ||
          ( MYMIN( area[2], area[3] ) > amax ) )
        SCETER( 7, err_ycuts );
   }
/*
 * get intensity
 */
(void) SCDRDR( imfA, "LHCUTS", 1, 4, &actvals, wcfram+FOR_Z, &unit, &knul);
(void) SCKRDR( "INPUTR", 2, 4, &actvals, ranp, &unit, &knul);
if ( fabs(ranp[0]) > PLT_EPS || fabs(ranp[1]) > PLT_EPS )
   { wcfram[FOR_Z]  = ranp[0];
     wcfram[FOR_Z+1]= ranp[1];
   }
else
   {
   if ( wcfram[FOR_Z] == wcfram[FOR_Z+1] )
      { wcfram[FOR_Z] = wcfram[FOR_Z+2];
        wcfram[FOR_Z+1] = wcfram[FOR_Z+3];
      }
    }
ranp[0] = wcfram[FOR_Z];
ranp[1] = wcfram[FOR_Z+1];
PCKWRR( "ZWNDL", 2, wcfram+FOR_Z);
(void) SCKRDR( "INPUTR", 1, 1, &actvals, &scar, &unit, &knul);
/*
 * the intensity scale
 */
if ( scar == 0.0 )
   { if ( wcfram[FOR_Z] == wcfram[FOR_Z+1] )
        scar = wcfram[FOR_Z] / 10.0;
     else
        scar = ( wcfram[FOR_Z+1] - wcfram[FOR_Z] ) / 10.0;
   }
/*
 * get the other input parameters
 */
(void) SCKRDI( "INPUTI", 1, 1, &actvals, &ismoot, &unit, &knul);
(void) SCKRDI( "INPUTI", 2, 1, &actvals, &head, &unit, &knul);

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

/*
 * determine number of pixels and number of chunks
 */
nrpix[0] = (int) fabs( image[1] - image[0] ) + 1;
nrpix[1] = (int) fabs( image[3] - image[2] ) + 1;
last_row = MYMAX( image[2], image[3]);
chunks   = (int) ceil( (double) nrpix[0] * nrpix[1] / MAXSIZ );
nrpix[1] = (int) ceil( (double) nrpix[1] / chunks );

/*
 * allocate virtual memory and scratch space
 */
size  = nrpix[0] * nrpix[1];
p_imgA = (float *) osmmget( size * sizeof( float ));
p_imgB = (float *) osmmget( size * sizeof( float ));

for ( ii = 0; ii < chunks; ii++ )
    { if ( image[3] > image[2] )                        /* size of chunk p.c.*/
         { if ( ii > 0 ) image[2] += nrpix[1] - 1.0;
           image[3] = MYMIN( last_row, image[2] + nrpix[1] - 1 );
         }
      else
         { if ( ii > 0 ) image[3] += nrpix[1] - 1.0;
           image[2] = MYMIN( last_row, image[3] + nrpix[1] - 1 );
         }
/*
 * get size of chunk in w.c.
 */
      BOXPTW( image+2, npixA[1], startA[1], stepA[1], area+2 );      
/*
 * extract chunck from original frame
 */
      GETDAT( imfA, MAXSIZ, npixA, image, ismoot, p_imgA );
      GETDAT( imfB, MAXSIZ, npixB, image, ismoot, p_imgB );
/*
 * do it!!
 */
      PLVEC( p_imgA, p_imgB, image, area, stepA, scar, ranp, head );
/*
 * updating for the next loop
 */
      nrpix[1] = MYMIN( last_row - ii * nrpix[1], nrpix[1] );
      size  = nrpix[0] * nrpix[1];
    }
(void) SCFCLO( imfA );
(void) SCFCLO( imfB );

/*
 * draw the axes and the label
 */
if ( plmode >= 0 && access == 0 )
   { if ( strlen( cunitA ) > (size_t) 32 ) 
        { (void) strncat( label[0], cunitA+32, 16 );
          *(cunitA+32) = '\0';
        }
     if ( strlen( cunitA ) > (size_t) 16 ) 
        (void) strcat( label[1], cunitA+16 );

     for ( ii = 0; ii < PLDIM2; ii++ )
         { (void) strcat( label[ii], ")" );
           LABSTR( label[ii] );
         }
/*
 * plot axes and labels
 */
     PCFRAM( wcfram, wcfram+FOR_Y, label[0], label[1] );

     if ( plmode == 1 )
        { (void) sprintf( label[2], "Frames: %s + %s", nameA, nameB );
          (void) sprintf( label[3], "Ident: %s + %s", identA, identB );
          PLIDEN( plmode, label[2], label[3] );
        }
     else if ( plmode == 2 )
        PLVECI( plmode, nameA, identA, nameB, identB, scar, ranp );
   }
/*
 * close plot file and terminate graphic operations
 */
PCCLOS();

return SCSEPI();
}

