/* $Id: create_table_1.c,v 1.4 2015/09/15 07:38:12 jim Exp $
 *
 * This file is part of the CASU Pipeline utilities
 * Copyright (C) 2015 European Southern Observatory
 *
 * 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

/*
 * $Author: jim $
 * $Date: 2015/09/15 07:38:12 $
 * $Revision: 1.4 $
 * $Name:  $
 */

#include <stdio.h>
#include <math.h>
#include "imcore.h"
#include "util.h"
#include "floatmath.h"

/* Column numbers for each item to be stored */

#define COL_NUMBER      1
#define COL_FLUXISO     2
#define COL_FLUXTOTAL   3
#define COL_APFLUX1     4
#define COL_X           5
#define COL_Y           6
#define COL_SIGMA       7
#define COL_ELLIPT      8
#define COL_PA          9
#define COL_PEAKHEIGHT 10
#define COL_AREAL1     11
#define COL_AREAL2     12
#define COL_AREAL3     13
#define COL_AREAL4     14
#define COL_AREAL5     15
#define COL_AREAL6     16
#define COL_AREAL7     17
#define COL_AREAL8     18
#define COL_APFLUX2    19
#define COL_APFLUX3    20
#define COL_APFLUX4    21
#define COL_APFLUX5    22
#define COL_RA         23
#define COL_DEC        24
#define COL_CLASS      25
#define COL_STAT       26
#define COL_APFLUX6    27
#define COL_SKYLEV     28
#define COL_SKYRMS     29

/* Number of columns in the table */

#define NCOLS 32

/* Core radius extras */

#define NRADS 6
static float rmults[] = {0.5,1.0,CPL_MATH_SQRT2,2.0,2.0*CPL_MATH_SQRT2,4.0};
static int nrcore = 1;
static float apertures[NRADS];

/* Column definitions */

static const char *ttype[NCOLS]={"No.","Isophotal_flux","Total_flux","Core_flux",
                                 "X_coordinate","Y_coordinate","Gaussian_sigma",
                                 "Ellipticity","Position_angle","Peak_height",
                                 "Areal_1_profile","Areal_2_profile","Areal_3_profile",
                                 "Areal_4_profile","Areal_5_profile","Areal_6_profile",
                                 "Areal_7_profile","Areal_8_profile","Core1_flux",
                                 "Core2_flux","Core3_flux","Core4_flux",
                                 "RA","DEC","Classification","Statistic",
                                 "Core5_flux","Skylev",
                                 "Skyrms","Blank_30","Blank_31","Blank_32"};
static const char *tunit[NCOLS]={" ","Counts","Counts","Counts","Pixels","Pixels",
                                 "Pixels"," ","Degrees","Counts","Pixels","Pixels",
                                 "Pixels","Pixels","Pixels","Pixels","Pixels","Pixels",
                                 "Counts","Counts","Counts","Counts",
                                 "Degrees","Degrees","Flag","N-sigma",
                                 "Counts","Counts","Counts","Blank_30",
                                 "Blank_31","Blank_32"};
static cpl_type tform[NCOLS]={CPL_TYPE_INT,CPL_TYPE_FLOAT,CPL_TYPE_FLOAT,
                              CPL_TYPE_FLOAT,CPL_TYPE_FLOAT,CPL_TYPE_FLOAT,
                              CPL_TYPE_FLOAT,CPL_TYPE_FLOAT,CPL_TYPE_FLOAT,
                              CPL_TYPE_FLOAT,CPL_TYPE_FLOAT,CPL_TYPE_FLOAT,
                              CPL_TYPE_FLOAT,CPL_TYPE_FLOAT,CPL_TYPE_FLOAT,
                              CPL_TYPE_FLOAT,CPL_TYPE_FLOAT,CPL_TYPE_FLOAT,
                              CPL_TYPE_FLOAT,CPL_TYPE_FLOAT,CPL_TYPE_FLOAT,
                              CPL_TYPE_FLOAT,CPL_TYPE_FLOAT,CPL_TYPE_FLOAT,
                              CPL_TYPE_FLOAT,CPL_TYPE_FLOAT,CPL_TYPE_FLOAT,
                              CPL_TYPE_FLOAT,CPL_TYPE_FLOAT,CPL_TYPE_FLOAT,
                              CPL_TYPE_FLOAT,CPL_TYPE_FLOAT};

static int areal_cols[NAREAL] = {COL_AREAL1,COL_AREAL2,COL_AREAL3,COL_AREAL4,
                                 COL_AREAL5,COL_AREAL6,COL_AREAL7,COL_AREAL8};
/**@{*/

/*---------------------------------------------------------------------------*/
/**
    \ingroup cataloguemodules
    \brief Initialise type 1 catalogue
  
    \par Name:
        imcore_tabinit_1
    \par Purpose:
        Initialise type 1 catalogue
    \par Description:
        Type 1 catalogue is initialised and the xy columns are identified.
    \par Language:
        C
    \returns
        Nothing
    \par QC headers:
        None
    \par DRS headers:
        None
    \author
        Jim Lewis, CASU
 */
/*---------------------------------------------------------------------------*/

extern void imcore_tabinit_1(int *imcore_xcol, int *imcore_ycol, 
                             cpl_table **tab) {

    /* Call the generic routine to open a new output table */

    imcore_tabinit_gen(NCOLS,ttype,tunit,tform,tab);

    /* Define RA and Dec columns */

    *imcore_xcol = COL_X;
    *imcore_ycol = COL_Y;
}

/*---------------------------------------------------------------------------*/
/**
    \ingroup cataloguemodules
    \brief Do seeing estimate for type 1 catalogue
  
    \par Name:
        imcore_do_seeing_1
    \par Purpose:
        Do seeing estimate for type 1 catalogue
    \par Description:
        Areal profiles in a type 1 catalogue are analysed and a seeing
        estimate is extracted
    \par Language:
        C
    \param ap
        The current ap structure
    \retval CASU_OK
        If all is well. Currently this is the only return value
    \par QC headers:
        None
    \par DRS headers:
        None
    \author
        Jim Lewis, CASU
 */
/*---------------------------------------------------------------------------*/

extern int imcore_do_seeing_1(ap_t *ap, int nobjects, cpl_table *tab) {
    int retval,i;
    char *areal_colnames[NAREAL];

    /* Sort out the areal profile column names */

    for (i = 0; i < NAREAL; i++) 
        areal_colnames[i] = (char *)ttype[areal_cols[i]-1];
 
    /* Just call the generic seeing routine */
 
    retval = imcore_do_seeing_gen(ap,ttype[COL_ELLIPT-1],ttype[COL_PEAKHEIGHT-1],
                                  areal_colnames,nobjects,tab);

    /* Get out of here */
 
    return(retval);
}
        
/*---------------------------------------------------------------------------*/
/**
    \ingroup cataloguemodules
    \brief Process results for type 1 catalogue
  
    \par Name:
        imcore_process_results_1
    \par Purpose:
        Create the results for objects in a type 1 catalogue
    \par Description:
        The pixel processing is done for all the parameters wanted for
        a type 1 catalogue
    \par Language:
        C
    \param ap
        The current ap structure
    \retval CASU_OK
        If all is well. 
    \retval CASU_FATAL
        If peak flux < 0
    \par QC headers:
        None
    \par DRS headers:
        None
    \author
        Jim Lewis, CASU
 */
/*---------------------------------------------------------------------------*/

extern int imcore_process_results_1(ap_t *ap, int *nobjects, cpl_table *tab) {
    float momresults[8],ttotal,parmall[IMNUM][NPAR],ratio,cflux[NRADS*IMNUM];
    float sxx,syy,srr,sxy,ecc,temp,xx,theta,radeg,ell,iso_flux,total_flux;
    float apflux1,apflux2,apflux3,apflux4,apflux5,yy,sigma,peak,areal1,apflux6;
    float areal2,areal3,areal4,areal5,areal6,areal7,areal8;
    float skylev,skyrms,badpix[IMNUM],avconf[IMNUM];
    int iareal[NAREAL],nbit,i,k,nr,mbit,j;
    long nrows;

    /* Do a basic moments analysis and work out the areal profiles*/

    imcore_moments(ap,momresults);
    if (momresults[0] < 0)
        return(CASU_FATAL);
    imcore_areals(ap,iareal);

    /* See if this object makes the cut in terms of its size.  If not, then
       just return with good status */

    if (iareal[0] < ap->ipnop || momresults[3] < ap->xintmin)
        return(CASU_OK);

    /* Work out the total flux */

    imcore_extend(ap,momresults[3],momresults[1],momresults[2],
                momresults[4],momresults[5],momresults[6],
                (float)iareal[0],momresults[7],&ttotal);
    ratio = MAX(ttotal,momresults[3])/momresults[3];

    /* Try and deblend the images if it is requested and justified */

    if (iareal[0] >= ap->mulpix && ap->icrowd)
        imcore_overlp(ap,parmall,&nbit,momresults[1],momresults[2],
                      momresults[3],iareal[0],momresults[7]);
    else
        nbit = 1;
    if (nbit == 1) {
        parmall[0][0] = momresults[3];
        parmall[0][1] = momresults[1];
        parmall[0][2] = momresults[2];
        parmall[0][3] = ap->thresh;
        for (i = 4; i < 8; i++) 
            parmall[0][i] = momresults[i];
        for (i = 0; i < NAREAL; i++)
            parmall[0][i+8] = (float)iareal[i];
    } else {
        mbit = 0;
        for (i = 0; i < nbit; i++) {
            if (parmall[i][1] > 1.0 && parmall[i][1] < ap->lsiz &&
                parmall[i][2] > 1.0 && parmall[i][2] < ap->csiz) {
                for (j = 0; j < NPAR; j++) 
                    parmall[mbit][j] = parmall[i][j];
                mbit++;
            }
        }
        nbit = mbit;
        if (nbit == 0)
            return(CASU_OK);
    } 

    /* Create a list of apertures */

    for (i = 0; i < NRADS; i++) 
        apertures[i] = rmults[i]*(ap->rcore);

    /* Initialise badpix accumulator */

    for (i = 0; i < nbit; i++) {
        badpix[i] = 0.0;
        avconf[i] = 0.0;
    }

    /* Get the core fluxes in all apertures */

    imcore_phopt(ap,parmall,nbit,NRADS,apertures,cflux,badpix,nrcore,avconf);

    /* Massage the results and write them to the fits table */

    radeg = 180.0/CPL_MATH_PI;
    for (k = 0; k < nbit; k++) {
        sxx = parmall[k][4];
        sxy = parmall[k][5];
        syy = parmall[k][6];    
        if(sxy > 0.0)
          sxy = MAX(1.0e-4,MIN(sxy,sqrtf(sxx*syy)));
        else
          sxy = MIN(-1.0e-4,MAX(sxy,-sqrtf(sxx*syy)));

        srr = MAX(0.5,sxx+syy);
        ecc = sqrtf((syy-sxx)*(syy-sxx)+4.0*sxy*sxy)/srr;
        temp = MAX((1.0-ecc)/(1.0+ecc),0.0);
        ell = 1.0 - sqrtf(temp);
        ell = MIN(0.99,MAX(0.0,ell));
        xx = 0.5*(1.0+ecc)*srr-sxx;
        if(xx == 0.0)
            theta = 0.0;
        else
            theta = 90.0-radeg*atanf(sxy/xx);

        /* Create a list of values */

        nrows = cpl_table_get_nrow(tab);
        (*nobjects)++;
        if (*nobjects > nrows) 
            (void)cpl_table_set_size(tab,nrows+INITROWS);
        nr = *nobjects - 1;
        iso_flux = parmall[k][0];
        total_flux = ratio*parmall[k][0];
        apflux1 = cflux[k*NRADS + 0];
        apflux2 = cflux[k*NRADS + 1];
        apflux3 = cflux[k*NRADS + 2];
        apflux4 = cflux[k*NRADS + 3];
        apflux5 = cflux[k*NRADS + 4];
        apflux6 = cflux[k*NRADS + 5];
        xx = parmall[k][1];
        yy = parmall[k][2];
        sigma = sqrt(srr);
        peak = parmall[k][7];
        areal1 = parmall[k][8];
        areal2 = parmall[k][9];
        areal3 = parmall[k][10];
        areal4 = parmall[k][11];
        areal5 = parmall[k][12];
        areal6 = parmall[k][13];
        areal7 = parmall[k][14];
        if (nbit > 1 && k == 0)
            areal8 = 0.0;
        else
            areal8 = parmall[k][15];
        imcore_backest(ap,xx,yy,&skylev,&skyrms);

        /* Store away the results for this object */
    
        cpl_table_set_int(tab,ttype[COL_NUMBER-1],nr,*nobjects);
        cpl_table_set_float(tab,ttype[COL_FLUXISO-1],nr,iso_flux);
        cpl_table_set_float(tab,ttype[COL_FLUXTOTAL-1],nr,total_flux);
        cpl_table_set_float(tab,ttype[COL_APFLUX1-1],nr,apflux2);
        cpl_table_set_float(tab,ttype[COL_X-1],nr,xx);
        cpl_table_set_float(tab,ttype[COL_Y-1],nr,yy);
        cpl_table_set_float(tab,ttype[COL_SIGMA-1],nr,sigma);
        cpl_table_set_float(tab,ttype[COL_ELLIPT-1],nr,ell);
        cpl_table_set_float(tab,ttype[COL_PA-1],nr,theta);
        cpl_table_set_float(tab,ttype[COL_PEAKHEIGHT-1],nr,peak);
        cpl_table_set_float(tab,ttype[COL_AREAL1-1],nr,areal1);
        cpl_table_set_float(tab,ttype[COL_AREAL2-1],nr,areal2);
        cpl_table_set_float(tab,ttype[COL_AREAL3-1],nr,areal3);
        cpl_table_set_float(tab,ttype[COL_AREAL4-1],nr,areal4);
        cpl_table_set_float(tab,ttype[COL_AREAL5-1],nr,areal5);
        cpl_table_set_float(tab,ttype[COL_AREAL6-1],nr,areal6);
        cpl_table_set_float(tab,ttype[COL_AREAL7-1],nr,areal7);
        cpl_table_set_float(tab,ttype[COL_AREAL8-1],nr,areal8);
        cpl_table_set_float(tab,ttype[COL_APFLUX2-1],nr,apflux1);
        cpl_table_set_float(tab,ttype[COL_APFLUX3-1],nr,apflux3);
        cpl_table_set_float(tab,ttype[COL_APFLUX4-1],nr,apflux4);
        cpl_table_set_float(tab,ttype[COL_APFLUX5-1],nr,apflux5);
        cpl_table_set_float(tab,ttype[COL_APFLUX6-1],nr,apflux6);
        cpl_table_set_float(tab,ttype[COL_SKYLEV-1],nr,skylev);
        cpl_table_set_float(tab,ttype[COL_SKYRMS-1],nr,skyrms);
    }

    /* Get outta here */

    return(CASU_OK);
}

/**@}*/

/*

$Log: create_table_1.c,v $
Revision 1.4  2015/09/15 07:38:12  jim
Trap for when nbit = 0 in phopt

Revision 1.3  2015/08/12 11:16:55  jim
Modified procedure names to protect namespace

Revision 1.2  2015/08/07 13:06:54  jim
Fixed copyright to ESO

Revision 1.1.1.1  2015/06/12 10:44:32  jim
Initial import

Revision 1.3  2015/01/09 11:42:36  jim
Fixed routines to remove globals

Revision 1.2  2014/04/09 09:09:51  jim
Detabbed

Revision 1.1.1.1  2013/08/27 12:07:48  jim
Imported


*/
