/*------------------------------------------------------------------------------
© A J S Hamilton 2001
------------------------------------------------------------------------------*/
#include <errno.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "inputfile.h"
#include "manglefn.h"
#include "defaults.h"
#include "healpix/chealpix.h"

/* getopt options */
const char *optstr = "dqu:p:P:Wi:";

/* allocate polygons as a global array */
polygon *poly_global[NPOLYSMAX];

/* declared in rdmask */
extern inputfile file;

/* local functions */
void    usage(void);
#ifdef  GCC
int poly2hpx(long, char *, format *, int npoly, polygon *[npoly]);
#else
int poly2hpx(long, char *, format *, int npoly, polygon *[/*npoly*/]);
#endif

/*------------------------------------------------------------------------------
  Main program.
*/
int main(int argc, char *argv[])
{
    int ifile, nfiles, npoly, npolys,i;
    polygon **poly;
    poly=poly_global;

    /* parse arguments */
    parse_args(argc, argv);

    /* at least two input and one output filename required as arguments */
    if (argc - optind < 3) {
        if (optind > 1 || argc - optind >= 1) {
            fprintf(stderr, "%s requires at least 3 arguments: polygon_infile, nside, and outfile\n", argv[0]);
            usage();
            exit(1);
        } else {
            usage();
            exit(0);
        }
    }

    msg("---------------- polyid ----------------\n");

    /* advise data format */
    advise_fmt(&fmt);

    /* read polygons */
    npoly = 0;
    nfiles = argc - 2 - optind;
    for (ifile = optind; ifile < optind + nfiles; ifile++) {
        npolys = rdmask(argv[ifile], &fmt, NPOLYSMAX - npoly, &poly[npoly]);
        if (npolys == -1) 
            exit(1);
        npoly += npolys;
    }
    if (nfiles >= 2) {
        msg("total of %d polygons read\n", npoly);
    }
    if (npoly == 0) {
        msg("STOP\n");
        exit(0);
    }
    
    if (snapped==0) {
      msg("WARNING: 'snapped' keyword not found in all input files.\n");
      msg("Polygons should be snapped before performing other mangle operations.\n");
    }
    
    /* polygon id numbers */
    long nside = strtol(argv[argc - 2], 0, 10);
    if (nside == 0 && errno == EINVAL) {
        msg("Invalid NSIDE");
        exit(0);
    }
    npolys = poly2hpx(nside, argv[argc - 1], &fmt, npoly, poly);
    if (npolys == -1) exit(1);

    for(i=0;i<npoly;i++){
        free_poly(poly[i]);
    }
    return(0);
}

/*------------------------------------------------------------------------------
*/
void usage(void)
{
    printf("usage:\n");
    printf("poly2hpx [-d] [-q] [-i<f>] [-u<inunit>[,<outunit>]] [-p[+|-][<n>]] [-P[scheme][<p>][,<r>]] [-W] polygon_infile1 [polygon_infile2 ...] nside outfile\n");
#include "usage.h"
}

/*------------------------------------------------------------------------------
*/
#include "parse_args.c"

/*------------------------------------------------------------------------------
  Id numbers of polygons containing az, el positions.
  The az, el positions are read from in_filename,
  and the results are written to out_filename.
  Implemented as interpretive read/write, to permit interactive behaviour.

   Input: in_filename = name of file to read from;
            "" or "-" means read from standard input.
      out_filename = name of file to write to;
            "" or "-" means write to standard output.
      fmt = pointer to format structure.
      poly = array of pointers to polygons.
      npoly = number of polygons in poly array.
  Return value: number of lines written,
        or -1 if error occurred.
*/
int poly2hpx(long nside, char *out_filename, format *fmt, int npoly, polygon *poly[/*npoly*/])
{
#define AZEL_STR_LEN    32
    char input[] = "input", output[] = "output";
    char *word, *next;
    char az_str[AZEL_STR_LEN], el_str[AZEL_STR_LEN];
    int i, idmax, idmin, idwidth, ird, len, nid, nids, nid0, nid2, np;
    int *id;
    long double *weight;
    long pix, npix;
    azel v;
    char *out_fn;
    FILE *outfile;
    int *start;
    int *total;
    int *parent_pixels;
    int p, res, max_pixel, ier;
    int old_pct = -1;
    float *hpx_map;
    
    max_pixel= poly[npoly-1]->pixel; 
    res_max=get_res(max_pixel, scheme);
    max_pixel=pixel_start(res_max+1,scheme);
    
    /* allocate memory for pixel info arrays start and total */ 
    printf("res_max=%d, max_pixel=%d\n",res_max,max_pixel);
    start = (int *) malloc(sizeof(int) * max_pixel);
    if (!start) {
      fprintf(stderr, "poly2hpx: failed to allocate memory for %d integers\n", max_pixel);
      return(-1);
    }
    total = (int *) malloc(sizeof(int) * max_pixel);
    if (!total) {
      fprintf(stderr, "poly2hpx: failed to allocate memory for %d integers\n", max_pixel);
      return(-1);
    }
    parent_pixels = (int *) malloc(sizeof(int) * (res_max+1));
    if (!parent_pixels) {
      fprintf(stderr, "poly2hpx: failed to allocate memory for %d integers\n", res_max+1);
      return(-1);
    }

    /* build lists of starting indices of each pixel and total number of polygons in each pixel*/
    
    ier=pixel_list(npoly, poly, max_pixel, start, total);
    if (ier == -1) {
      fprintf(stderr, "poly2hpx: error building pixel index lists\n");
      return(-1);
    }

    /* largest width of polygon id number */
    idmin = 0;
    idmax = 0;
    for (i = 0; i < npoly; i++) {
        if (!poly[i]) continue;
        if (poly[i]->id < idmin) idmin = poly[i]->id;
        if (poly[i]->id > idmax) idmax = poly[i]->id;
    }
    idmin = ((idmin < 0)? floorl(log10l((long double)-idmin)) + 2 : 1);
    idmax = ((idmax > 0)? floorl(log10l((long double)idmax)) + 1 : 1);
    idwidth = ((idmin > idmax)? idmin : idmax);

    /* write header */
    v.az = 0.;
    wrangle(v.az, fmt->outunit, fmt->outprecision, AZEL_STR_LEN, az_str);
    len = strlen(az_str);
    if (fmt->outunit == 'h') {
        sprintf(az_str, "az(hms)");
        sprintf(el_str, "el(dms)");
    } else {
        sprintf(az_str, "az(%c)", fmt->outunit);
        sprintf(el_str, "el(%c)", fmt->outunit);
    }

    /* interpretive read/write loop */
    np = 0;
    nid = 0;
    nids = 0;
    nid0 = 0;
    nid2 = 0;
    npix = nside2npix(nside);
    hpx_map = (float *) malloc(sizeof(float) * npix);
    if (hpx_map == 0) {
      fprintf(stderr, "poly2hpx: error allocating healpix map\n");
      return(-1);
    }
    
    for (pix = 0; pix < npix; pix++) {
        double phi, theta;
        int pct;

        pct = pix*100L/npix;
        if (pct != old_pct) {
            printf("Progress: %d %%\n", pct);
            old_pct = pct;
        }
        
        hpx_map[pix] = 0;
        pix2ang_ring(nside, pix, &theta, &phi);
        
        v.el = 0.5*M_PI - theta;
        v.az = phi;
        
        //find out what pixel the az el point is in at the maximum resolution
        p=which_pixel(v.az, v.el, res_max, scheme);
        //get the list of all the possible parent pixels
        get_parent_pixels(p, parent_pixels, scheme);

        nid=0;
        for(res=res_max;res>=0;res--){
            p=parent_pixels[res];
            //if this pixel isn't in the polygon list, go to next parent pixel
            if(total[p]==0) 
                continue;
            // id numbers of the polygons containing position az, el 
            nid = poly_id(total[p], &poly[start[p]], v.az, v.el, &id, &weight);
        }
        
        if(polyid_weight==1) {
            for (i = 0; i < nid; i++) {
                hpx_map[pix] += weight[i];
            }
        } else {
          hpx_map[pix] = nid;
        }

        /* increment counters of results */
        np++;
        nids += nid;
        if (nid == 0) {
            nid0++;
        } else if (nid >= 2) {
            nid2++;
        }
    }

    /* advise */
    if (nid0 > 0) msg("%d points were not inside any polygon\n", nid0);
    if (nid2 > 0) msg("%d points were inside >= 2 polygons\n", nid2);

    if (outfile != stdout) {
        if(polyid_weight==1){
            msg("polyid: %d weights at %d positions written to %s\n", nids, np, out_fn);
        } else {
            msg("polyid: %d id numbers at %d positions written to %s\n", nids, np, out_fn);
        }
    }
    
    printf("Writing to %s\n", out_filename);
    // Clobber the file
    unlink(out_filename);
    write_healpix_map (hpx_map, nside, out_filename, 0, "E");

    free(start);
    free(total);
    free(parent_pixels);
    free(hpx_map);

    return(np);
}
