#include "libcpp.h"

using namespace liberr;
using namespace libcpp;
using namespace std;

namespace {
  struct location {
    REAL lon;
    REAL lat;
  };
}

int main(int argc, char** argp, char** envp)
{
  string progname(argp[0]);

  if (argc != 2) error("Error, " + progname + ", no filename on command line");

  string filename = argp[1];

  ifstream dat_ifs(filename.c_str());
  if (!dat_ifs) error("Error, " + progname + ", cannot open " + filename);

  cout << "Processing file " << filename << '\n';

  ifstream zip_ifs("zipcodes.dat");
  if (!zip_ifs) error("Error, " + progname + ", cannot open zipcodes.dat");

  std::map<INTEGER,location> ziptab;

  INTEGER zip;
  location loc;

  string header;

  getline(zip_ifs,header);

  cout << header << '\n';

  while(zip_ifs >> zip >> loc.lon >> loc.lat) ziptab[zip]=loc; 

  cout << ziptab.size() << '\n';;

  ofstream lon_ofs("lon.dat");
  ofstream lat_ofs("lat.dat");

  lon_ofs << "LONGITUDE" << '\n';
  lat_ofs << "LATITUDE" << '\n';

  getline(dat_ifs,header);
  INTEGER count = 1;

  map<INTEGER,location>::const_iterator itr;

  while(dat_ifs >> zip) {
    ++count;
    itr = ziptab.find(zip);
    if (itr == ziptab.end()) {
      cout << "Missing value for zip " << zip << " at line " << count << '\n';
      lon_ofs << 0.0 << '\n';
      lat_ofs << 0.0 << '\n';
    }
    else {
      lon_ofs << itr->second.lon << '\n';
      lat_ofs << itr->second.lat << '\n';
    }
  } 
    
  return 0;
}
