#include <stdio.h>
#include <map>
#include <list>
#include <unistd.h>
#include <cstdlib>
#include "polygon.h"
#include "format.h"
#include "manglefn.h"

extern "C" int weight_dumb(format *fmt, int npoly, polygon **poly, char *survey)
{
    FILE *fw;
    int ipoly;
    double w;

    std::map<int, std::list<int> > id_to_ply;

    fw = fopen(survey, "rt");

    for (int i = 0; i < npoly; i++)
      {
        id_to_ply[poly[i]->id].push_back(i);
        poly[i]->weight = 0;
      }

    while (fscanf(fw, "%d %lf", &ipoly, &w) == 2)
      {
        std::list<int>& l = id_to_ply[ipoly];

        for (std::list<int>::iterator iter = l.begin(); iter != l.end(); ++iter)
          poly[*iter]->weight = w;
      }

    /* assign new polygon id numbers in place of inherited ids */
    if (fmt->newid == 'n') {
        for (ipoly = 0; ipoly < npoly; ipoly++) {
            poly[ipoly]->id = ipoly;
        }
    }

    if (fmt->newid == 'p') {
      for (ipoly = 0; ipoly < npoly; ipoly++) {
        poly[ipoly]->id = poly[ipoly]->pixel;
      }
    }

    fclose(fw);

    return(npoly);
}


extern "C" int weight_area(format *fmt, int npoly, polygon **polys, double mtol)
{
  static const int verb = 0;
  std::map<int, std::list<int> > id_to_ply;
  std::map<int, long double> ply_a;
  int p;

  for (int i = 0; i < npoly; i++)
  {
    id_to_ply[polys[i]->id].push_back(i);
    polys[i]->weight = 0;
  }

  for (p = 0; p < npoly; p++) {
    long double area, tol;
    int ier;

    area = 1.0;
    tol = mtol;
    ier = garea(polys[p], &tol, verb, &area);
    if (ier == -1) return(-1);
    if (ier) {
        fprintf(stderr, "weight_area: area of polygon %d is incorrect\n", polys[p]->id);
        std::abort();
    }
    
    if (ply_a.find(polys[p]->id) == ply_a.end()) {
      ply_a[polys[p]->id] = area;
    } else {
      ply_a[polys[p]->id] += area;
    }
  }

  for (p = 0; p < npoly; p++) {
    polys[p]->weight = ply_a[polys[p]->id];
  }
  return npoly;
}
