/*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
.TYPE        Module
.NAME        tblconv.c
.LANGUAGE    C
.AUTHOR      J.D.Ponz  ESA/VILSPA
.CATEGORY    IUEFA
.PURPOSE     Converts a 3D table file with MXLO/MXHI spectra into
             one or several 2D spectral tables.
.COMMENTS    Command syntax:
                   tblconv intab 
             where 'intab' is the input table. 
             In the case of low-dispersion, the program produces a table 
             per aperture. The name of the output table is generated by
             adding a letter to the input name to indicate the aperture.
             In case of high-dispersion, a single table with all the orders
             is generated. 
.VERSION     1.0 25-Mar-1993 JDP  First implementation     
.VERSION     1.1 05-Apr-1993 IY   Get out of MIDAS environment
.VERSION     2.0 24-Dec-1996 JDP  Include high dispersion option
.VERSION     2.1 21-May-1997 JDP  Modify column formats in HIGH disp. 
.VERSION     2.2 29-May-1997 JDP  Minor bug in LOW dispersion  
.VERSION     2.3  3-Jun-1997 JDP  Modify column format in LOW disp.  
.VERSION     2.4 23-Oct-1997 JDP  Modify offset.
.VERSION     2.5  3-Dec-1997 JDP  Number of orders for LW cameras
.VERSION 

 090903		last modif
------------------------------------------------------------*/

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <tbldef.h>
#include <midas_def.h>


#define PARLEN 80
#define NORDER 61
#define NARRAY 768L
/*=======================================================================*/

int main(argc,argv)
 int argc;     /* IN: No. of arguments in input command string */
 char *argv[]; /* IN: Pointer to contents of args. in inp. cmd. string */

{
  int    tid, tid1, ncol, nrow, nsort, allcol, allrow;
  int    npoints, i, j, jp4, k, ncols, ic, len, dtype, dnull, ival, k1;
  float  vals[1000];                       /* float values for spectra */
  int    ivals[1000];                      /* associated flags */
  float  wave, delta, rval;
  float   w;
  char   table_name[PARLEN];
  char   apert[10];
  char   label[17];
  char   unit[17];
  char   form[17];
  char   *new_name(), *table_out;

  int    joffset, i1, jrow, jref, iord;
  int    order[NORDER], norder[NORDER], iref[NORDER];
  double w0[NORDER], dw[NORDER];
  float  net[NARRAY], back[NARRAY], noise[NARRAY], ripple[NARRAY], flux[NARRAY];
  int    flag[NARRAY];


table_out = (char *) 0;

 
 /* Standalone Midas env. No Midas session needed */
  SCSPRO("-1");

 /* read input table name */
  if(argc != 2) {fprintf(stderr," Usage: tblconv tablename\n");
                 exit(0);
                 }
  strcpy(table_name,argv[1]); 

 /* read input spectrum */

  if (TCTOPN(table_name, F_IO_MODE, &tid))
      {SCTPUT ("**** Error: TCTOPN"); ospexit(0);}
                                      /* read table information */
  if (TCIGET(tid, &ncol, &nrow, &nsort, &allcol, &allrow))
      {SCTPUT ("**** Error: TCIGET"); ospexit(0);}
                                     /* check table size to check dispersion */
  if (ncol == 9) goto LOW;
  else if (ncol == 17) goto HIGH;
  else  
     {SCTPUT ("**** Error: wrong number of columns"); 
      ospexit(0);}

 /*******************************************************************/

 LOW: /* case of low-dispersion */

  if (nrow < 1 || nrow > 2)
      {SCTPUT ("**** Error: wrong number of rows"); ospexit(0);}
                                          /* loop to process each spectrum */
  for (i = 1; i <= nrow; i++)
   {TCERDC(tid, i, 1L, apert, &dnull);
    if (strncmp(apert, "LARGE", 5)==0) table_out = new_name(table_name, "L"); 
    else if (strncmp(apert,"SMALL",5)==0) 
                                       table_out = new_name(table_name, "S");
    else             {SCTPUT ("**** Error: wrong input table "); ospexit(0);}
                                              /* read sampling domain */
    TCERDI(tid, i, 2L, &npoints, &dnull);
    if (npoints != 640) {SCTPUT ("**** Error: bad number of bins"); 
                         ospexit(0);}
    TCERDR(tid, i, 3L, &wave, &dnull);
    TCERDR(tid, i, 4L, &delta, &dnull);
                                              /* create output table */
    ncols = 6;
    allcol = 9;
    if (TCTINI(table_out, F_TRANS, F_O_MODE, allcol, npoints, &tid1))
         {SCTPUT ("**** Error TCTINI"); ospexit(0);}
                                              /* generate wavelength column */
    /*   TCCINI(tid1, D_R8_FORMAT, 1L, "F10.3", "ANGSTROM", "WAVELENGTH", &ic);
    for (j = 1; j <= npoints; j++)
       {w = wave + (j-1)*delta; TCEWRD(tid1, j, ic, &w);} 
       */
    TCCINI(tid1, D_R4_FORMAT, 1L, "F10.3", "ANGSTROM", "WAVELENGTH", &ic);
    for (j = 1; j <= npoints; j++)
       {w = wave + (j-1)*delta; TCEWRR(tid1, j, ic, &w);}

    for (j = 1; j < ncols; j++)              /* generate rest of columns */
        {jp4 = j+4; 
         TCFGET(tid, jp4, form, &len, &dtype);
         TCLGET(tid, jp4, label);
         TCUGET(tid, jp4, unit);
         TCCINI(tid1, dtype, 1L, form, unit, label, &ic);
         switch (dtype) {
         case D_R4_FORMAT:                          /* float values */
             TCARDR(tid, i, jp4, 1L, npoints, vals);
             for (k=0; k < npoints; k++) 
                    {rval = vals[k]; k1 = k+1; TCEWRR(tid1, k1, ic, &rval);}
             break;
         case D_I2_FORMAT:                          /* integer values */
             TCARDI(tid, i, jp4, 1L, npoints, ivals);
             for (k=0; k < npoints; k++) 
                    {ival = ivals[k]; k1 = k+1; TCEWRI(tid1, k1, ic, &ival);}
             break;
         default:                                   /* never here */
             SCTPUT ("**** Error: wrong column type");
             ospexit(0);
         } 
       }
    if (TCTCLO(tid1)) {SCTPUT ("**** Error TCTCLO"); ospexit(0);}
  } 

  if (TCTCLO(tid))                           /* close input table */
  {SCTPUT ("**** Error TCTCLO"); ospexit(0);}

  ospexit(0);

 /*********************************************************************/

 HIGH: /* case of high-dispersion */

  if (nrow < NORDER-2 || nrow > NORDER)
      {SCTPUT ("**** Error: wrong number of rows"); ospexit(0);}

   /* loop to setup counters for each order */

  npoints = 0;

  for (i = 0, i1=1; i < nrow; i++, i1++)
   {TCERDI(tid, i1, 1L, &order[i],  &dnull);
    TCERDI(tid, i1, 2L, &norder[i], &dnull);
    npoints = npoints + norder[i];
    TCERDD(tid, i1, 3L, &w0[i],     &dnull);
    TCERDI(tid, i1, 4L, &iref[i],   &dnull);
    TCERDD(tid, i1, 5L, &dw[i],     &dnull);
   } 

    /* create output table */

  table_out = new_name(table_name, "H");     /* assign name as CCCnnnnnH */

  ncols  = 8;
  allcol = 10;
  if (TCTINI(table_out, F_TRANS, F_O_MODE, allcol, npoints, &tid1))
         {SCTPUT ("**** Error TCTINI"); ospexit(0);}

  TCCINI(tid1, D_I4_FORMAT, 1L, "I4",    "UNITLESS",    "ORDER",      &ic);
  TCCINI(tid1, D_R4_FORMAT, 1L, "F10.3", "ANGSTROM",    "WAVELENGTH", &ic);
  TCCINI(tid1, D_R4_FORMAT, 1L, "E15.5", "FN",          "NET",        &ic);
  TCCINI(tid1, D_R4_FORMAT, 1L, "E15.5", "FN",          "BACKGROUND", &ic);
  TCCINI(tid1, D_R4_FORMAT, 1L, "E15.5", "FN",          "NOISE",      &ic);
  TCCINI(tid1, D_I4_FORMAT, 1L, "I11",   "UNITLESS",    "QUALITY",    &ic);
  TCCINI(tid1, D_R4_FORMAT, 1L, "E15.5", "FN",          "RIPPLE",     &ic);
  TCCINI(tid1, D_R4_FORMAT, 1L, "E15.5", "ERG/CM2/S/A", "FLUX",       &ic);

    /* loop to transpose the 3D data vectors */

  joffset = 1;

  for (i = 0, i1=1; i < nrow; i++, i1++)       /* for each order */
    {TCARDR(tid, i1,  8L, 1L, NARRAY, net); 
     TCARDR(tid, i1,  9L, 1L, NARRAY, back); 
     TCARDR(tid, i1, 10L, 1L, NARRAY, noise); 
     TCARDI(tid, i1, 11L, 1L, NARRAY, flag); 
     TCARDR(tid, i1, 12L, 1L, NARRAY, ripple); 
     TCARDR(tid, i1, 13L, 1L, NARRAY, flux); 

     iord = order[i];

     for (j=0; j<norder[i]; j++)              /* for each sample */
       { jrow = j + joffset;   
         jref = j + iref[i] - 1 ;
                                 TCEWRI(tid1, jrow, 1L, &iord);
         rval = w0[i] + j*dw[i]; TCEWRR(tid1, jrow, 2L, &rval);  
         rval = net[jref];       TCEWRR(tid1, jrow, 3L, &rval); 
         rval = back[jref];      TCEWRR(tid1, jrow, 4L, &rval); 
         rval = noise[jref];     TCEWRR(tid1, jrow, 5L, &rval); 
         ival = flag[jref];      TCEWRI(tid1, jrow, 6L, &ival); 
         rval = ripple[jref];    TCEWRR(tid1, jrow, 7L, &rval); 
         rval = flux[jref];      TCEWRR(tid1, jrow, 8L, &rval); 
       }

     joffset = joffset + norder[i]; 
    }

  if (TCTCLO(tid1)) {SCTPUT ("**** Error TCTCLO"); ospexit(0);}
                      
  if (TCTCLO(tid))                           /* close input table */
  {SCTPUT ("**** Error TCTCLO"); ospexit(0);}

  ospexit(0);
return 0;
}

char *new_name(name, ap)        /* generate filename with aperture code */
char   *name;
char   ap[];
{
 char  *pc, *pcx;
 static char xname[PARLEN];

   pc = xname; pcx = (char *) 0;
   while ((*pc = *name++)) 
      if (*pc++ == '.') {pc--; *pc++ = ap[0]; *pc++ = '.'; pcx = pc;} 
   if (!pcx) *pc++ = ap[0];            /* if no '.' add aperture code at end */
   *pc = '\0';
   return xname;
}

