OB.DAAC Logo
NASA Logo
Ocean Color Science Software

ocssw V2022
l1c.cpp
Go to the documentation of this file.
1 
2 // Created by Martin Montes on 10/26/20.
3 //latest update 3/7/2022
4 //****************************************************8
5 #include "l1c.h"
6 #include "l1c_filehandle.h"
7 #include "l1c_input.h"
8 #include "l1c_str.h"
9 #include "l2_str.h"
10 #include <string>
11 #include <stdlib.h>
12 #include <stdio.h>
13 #include <math.h>
14 #include <list>
15 #include <stack>
16 #include <vector>
17 #include <iostream>
18 #include <fstream>
19 #include <sstream>
20 #include <netcdf.h>
21 #include <nc4utils.h>
22 #include "hawkeye_methods.h"
23 #include "allocate4d.h"
24 #include <allocate3d.h>
25 #include <allocate2d.h>
26 #include <algorithm>
27 #include <bits/stdc++.h>
28 #include <cstdlib>
29 #include <ctime>
30 #include <chrono>
31 #include <GeographicLib/Geodesic.hpp>
32 #include <GeographicLib/Constants.hpp>
33 #include <timeutils.h>
34 #include <genutils.h>
35 #include <stdint.h>
36 #include "l2prod.h"
37 
38 
39 
40 static size_t INPIX,TOTPIX,OUTPIX;
41 static size_t num_scans, num_pixels,num_frames,nviews;
42 static size_t num_blue_bands, num_red_bands, num_SWIR_bands;
43 static int ncid_L1B,ncid_L2,ncid_L1A;
44 
45 // scan line attributes
46 //static double* scan_time; // seconds of day
47 //static int16_t scan_time_year, scan_time_month, scan_time_day, scan_time_hour, scan_time_min;
48 //static double scan_time_secs;
49 
50 //Navigation data
51 static int navGrp, scGrp, geoGrp, obsGrp;
52 static int ovId, opId, otId, latId, lonId, solzId, Lt_blueId, Lt_redId, Lt_SWIRId,I_Id,Ipol_Id,frameId;
53 static float** lat, ** lon;
54 static short** solz;
55 static float degrad = M_PI / 180, Re = 6378.137;//Re earth radius in km at equator
56 //static float *orbp;
57 //static float *attang;
58 //static double *timeArr;
59 
60 //L1C vars
61 static int16_t nswath, nswtfiles, ndswaths;
62 
63 
64 using namespace std;
65 using namespace boost::assign;
66 using namespace std::chrono;
67 using namespace GeographicLib;
68 
69 
70 namespace bg = boost::geometry;
71 typedef bg::model::point<double, 2, bg::cs::geographic<bg::degree>> Point_t;
72 typedef bg::model::polygon<Point_t> Polygon_t;
73 typedef bg::model::box<Point_t> Box_t;
74 
75 
76 namespace l1c {
77 
78 
79  L1C::L1C() {
80  }
81 
82 
83  L1C::~L1C() {
84  }
85 
86 
87 //function to calculate cross product of two vectors, 3 components each vector
88  void cross_product_double(double vector_a[], double vector_b[], double temp[]) {
89  temp[0] = vector_a[1] * vector_b[2] - vector_a[2] * vector_b[1];
90  temp[1] = -(vector_a[0] * vector_b[2] - vector_a[2] * vector_b[0]);
91  temp[2] = vector_a[0] * vector_b[1] - vector_a[1] * vector_b[0];
92  }
93 
94  double cross_product_norm_double(double vector_a[], double vector_b[]) {
95  double temp[3],nvec;
96  temp[0] = vector_a[1] * vector_b[2] - vector_a[2] * vector_b[1];
97  temp[1] = -(vector_a[0] * vector_b[2] - vector_a[2] * vector_b[0]);
98  temp[2] = vector_a[0] * vector_b[1] - vector_a[1] * vector_b[0];
99 
100  nvec=sqrt(temp[0]*temp[0]+temp[1]*temp[1]+temp[2]*temp[2]);
101  return nvec;
102  }
103 
104 
105 
106 int32_t L1C::azmean_swt2(int swt,L1C_input *l1cinput,l1c_filehandle *l1cfile,float *lati,float *loni){
107  float az,lat1_l,lat2,lon1_l,lon2,dlambda,az_r;
108  float sum=0,tot=0;
109  int32_t num_gridlines=-1;
110  size_t azc=0;
111 
112 
113  num_gridlines = l1cfile->num_gridlines;
114 
115 
116  for (int i = 0;i < num_gridlines-1;i++) {
117  if(lati[i]>=-10. && lati[i]<=10.){
118  //assign central positions---
119  lat1_l = lati[i] * M_PI / 180.;
120  lat2 = lati[i + 1] * M_PI / 180.;
121  lon1_l = loni[i] * M_PI / 180.;
122  lon2 = loni[i + 1] * M_PI / 180.;
123  dlambda = (lon2 - lon1_l);
124  //bearing---
125  //make sure there are not NAN values ----------
126  az = atan2(sin(dlambda) * cos(lat2), cos(lat1_l) * sin(lat2) - sin(lat1_l) * cos(lat2) * cos(dlambda));//this is the satellite track bearing in radians
127 
128  // cout<<"gd#..."<<i+1<<"az..track bearing with respdct to north"<<az<<"lati.."<<lat1_l<<endl;
129  // cout<<az*180/M_PI<<endl;
130 
131  if (az > M_PI | az < -M_PI) {
132  cout << "problem with BEARING in across-gridline method...az<-180 or >180...." << "az in degrees.." << az * 180 / M_PI << endl;
133  exit(1);
134  }
135  if (isnan(az) < 1) {
136  az_r = (az + M_PI / 2.);
137  sum = az_r * 180. / M_PI;
138  if (sum < 0.0001 && sum>0) sum = 0.0;
139  tot += sum;
140  azc++;
141  }
142  else {
143  sum = NAN;
144  }
145 
146  }
147 
148  }
149 
150  float mean_az_east = tot / (azc);
151 
152  cout << "mean_az_east.." << mean_az_east << "numgridlines.." <<num_gridlines<< endl;
153 
154  l1cfile->mean_az_east = mean_az_east;
155 
156  return 0;
157 }
158 
159 
160 
161 
162 int32_t L1C::azmean_swt(int swt,L1C_input *l1cinput,l1c_filehandle *l1cfile,float *lati,float *loni){
163  float az,lat1_l,lat2,lon1_l,lon2,dlambda,az_r;
164  float sum=0,tot=0;
165  int32_t num_gridlines=-1;
166  size_t azc=0;
167 
168 
169  num_gridlines = l1cfile->num_gridlines;
170 
171 
172  for (int i = 0;i < num_gridlines - 1;i++) {
173 
174  //assign central positions---
175  lat1_l = lati[i] * M_PI / 180.;
176  lat2 = lati[i + 1] * M_PI / 180.;
177  lon1_l = loni[i] * M_PI / 180.;
178  lon2 = loni[i + 1] * M_PI / 180.;
179  dlambda = (lon2 - lon1_l);
180  //bearing---
181  //make sure there are not NAN values ----------
182  az = atan2(sin(dlambda) * cos(lat2), cos(lat1_l) * sin(lat2) - sin(lat1_l) * cos(lat2) * cos(dlambda));//this is the satellite track bearing in radians
183 
184  // cout<<"gd#..."<<i+1<<"az..track bearing with respdct to north"<<az<<"lati.."<<lat1_l<<endl;
185  // cout<<az*180/M_PI<<endl;
186 
187  if (az > M_PI | az < -M_PI) {
188  cout << "problem with BEARING in across-gridline method...az<-180 or >180...." << "az in degrees.." << az * 180 / M_PI << endl;
189  exit(1);
190  }
191  if (isnan(az) < 1) {
192  az_r = (az + M_PI / 2.);
193  sum = az_r * 180. / M_PI;
194  if (sum < 0.0001 && sum>0) sum = 0.0;
195  tot += sum;
196  azc++;
197  }
198  else {
199  sum = NAN;
200  }
201  }
202  float mean_az_east = tot / (azc);
203 
204  cout << "mean_az_east.." << mean_az_east << "numgridlines-1.." <<num_gridlines-1<< endl;
205 
206  l1cfile->mean_az_east = mean_az_east;
207 
208 
209  return 0;
210 }
211 
212 
213 
214 int32_t L1C::swtime_swt2(int swt,L1C_input *l1cinput,l1c_filehandle *l1cfile,int32_t norbs,double *tswt,double tcross,double mgv,double *tmgv){
215  int16_t bina=0,binb=0,ix=-1,ngridlines,gd=0;
216  double tg=0.,mot=0.,tini=0.,tend=0.;
217 // double dtime;
218 // int asc_mode=-1;
219 
220 
221  mot = ((l1cinput->gres) * 1000) /mgv;//in seconds
222  // asc_mode=l1cfile->orb_dir;
223  ngridlines=l1cfile->num_gridlines;
224 // ngridlines=l1cfile->num_gridlines;
225  tini=tswt[0];
226  ix=norbs-1;
227  tend=tswt[ix];
228 
229 // dtime=tswt[0]-tcross;//relative time qith respect to equator
230 
231 
232  cout<<"mgv.."<<mgv<<"tini.."<<tini<<"tend.."<<tend<<"tcross..."<<tcross<<endl;
233  int flag_time=-1;
234 
235  if (tcross > 0.0) {
236  flag_time=0;
237  cout<<"computing time series assuming mean swath velocity..for swath#."<<swt<<endl;
238 
239  tg = tcross - mot / 2;
240  gd=ngridlines/2-1;
241  tmgv[gd]=tg;
242  binb=1;
243 
244  while(binb<ngridlines/2){
245  binb++;
246  tg -= mot;
247  gd--;
248  tmgv[gd]=tg;
249  }
250  tg = tcross + mot / 2;
251  gd=ngridlines/2;
252  tmgv[gd]=tg;
253  bina=1;
254 
255  while(bina<ngridlines/2+1){
256  bina++;
257  tg += mot;
258  gd++;
259  tmgv[gd]=tg;
260  }
261 
262  cout<<"bina.."<<bina<<"binb.."<<binb<<endl;
263 
264  l1cfile->num_gridlines = binb + bina;
265 
266  cout<<"number of L1C gridlines along-track..."<<l1cfile->num_gridlines<<"for swath #.."<<swt<<endl;
267  }//end equat crossing
268  else{
269  cout<<"time series not possible for swath #.."<<swt<<"tcross<0...."<<endl;
270  flag_time=1;
271  }
272 
273  //for(size_t g=0;g<l1cfile->num_gridlines;g++) cout<<"time series (constant mean swath velocity) for gd#.."<<g+1<<"...."<<tmgv[g]<<endl;
274 
275 
276  return flag_time;
277 }
278 
279 
280 
281 
282 
283 
284 
285 int32_t L1C::swtime_swt(int swt,L1C_input *l1cinput,l1c_filehandle *l1cfile,int32_t norbs,int16_t time_index[6],double *tswt,double tcross,double mgv,double *tmgv){
286  int16_t bina=0,binb=0,ix=-1;
287  double tg=0.,mot=0.,tini=0.,tend=0.;
288 
289  mot = ((l1cinput->gres) * 1000) /mgv;
290 
291 
292 // if(time_index[0]>=0 & time_index[4]<0){ //consecutive swaths
293  tini=tswt[0];
294  ix=norbs-1;
295  tend=tswt[ix];
296 
297  cout<<"mgv.."<<mgv<<"tini.."<<tini<<"tend.."<<tend<<"tcross..."<<tcross<<endl;
298  int flag_time=-1;
299 
300  if (tcross > 0.0) {
301  flag_time=0;
302  cout<<"computing time series assuming mean swath velocity..for swath#."<<swt<<endl;
303 
304 
305  tg = tcross - mot / 2;
306 
307  while (tg > (tini - mot / 2)) {
308  binb++; //bins below eq crossing bin which is eq cros time +-mot/2
309  tg -= mot;
310  }
311 
312  tg = tcross + mot / 2;
313 
314  while (tg < (tend + mot / 2)) {
315  bina++;//time bins aove eq crossing time
316  tg += mot;
317  }
318 
319  l1cfile->num_gridlines = binb + bina;
320 
321  cout<<"number of L1C gridlines along-track..."<<l1cfile->num_gridlines<<"for swath #.."<<swt<<endl;
322 
323  //before--
324  for (int bin = 0;bin < binb;bin++) //300 seconds are 5 minutes or 1 file from Fred
325  tmgv[bin] = tini + bin * mot;
326 
327  int binc = binb-1;
328 
329  //after
330  for (int bin = 1;bin < bina+1;bin++) //300 seconds are 5 minutes or 1 file from Fred
331  tmgv[binc + bin] = tmgv[binc] + bin * mot;
332 
333  }//end equat crossing
334  else{
335  cout<<"time series not possible for swath #.."<<swt<<"tcross<0...."<<endl;
336  flag_time=1;
337  }
338 
339 
340 
341 
342  return flag_time;
343  }
344 
345 
346 
347 
348 int32_t L1C::swtime_vec(int swt,L1C_input *l1cinput,l1c_filehandle *l1cfile,int16_t time_index[6],vector<double>&tvec,double tcross,double mgv,double *tmgv){
349  int16_t bina=0,binb=0,ix=-1;
350  double tg=0.,mot=0.,tini=0.,tend=0.;
351 
352  mot = ((l1cinput->gres) * 1000) /mgv;
353 
354 
355 
356  tini=tvec[0];
357  ix=tvec.size()-1;
358  tend=tvec[ix];
359 
360  cout<<"mgv.."<<mgv<<"tini.."<<tini<<"tend.."<<tend<<"tcross..."<<tcross<<endl;
361 
362 
363  int flag_time=-1;
364 
365  if (tcross > 0.0) {
366  flag_time=0;
367  cout<<"computing time series assuming mean swath velocity..for swath#."<<swt<<endl;
368 
369 
370  tg = tcross - mot / 2;
371 
372  while (tg > (tini - mot / 2)) {
373  binb++; //bins below eq crossing bin which is eq cros time +-mot/2
374  tg -= mot;
375  }
376 
377  tg = tcross + mot / 2;
378 
379  while (tg < (tend + mot / 2)) {
380  bina++;//time bins aove eq crossing time
381  tg += mot;
382  }
383 
384  l1cfile->num_gridlines = binb + bina;
385 
386  cout<<"number of L1C gridlines along-track..."<<l1cfile->num_gridlines<<"for swath #.."<<swt<<endl;
387 
388  //before--
389  for (int bin = 0;bin < binb;bin++) //300 seconds are 5 minutes or 1 file from Fred
390  tmgv[bin] = tini + bin * mot;
391 
392  int binc = binb-1;
393 
394  //after
395  for (int bin = 1;bin < bina+1;bin++) //300 seconds are 5 minutes or 1 file from Fred
396  tmgv[binc + bin] = tmgv[binc] + bin * mot;
397 
398  }//end equat crossing
399  else{
400  cout<<"time series not possible for swath #.."<<swt<<"tcross<0...."<<endl;
401  flag_time=1;
402  }
403 
404 
405 
406  return flag_time;
407  }
408 
409 
410 
411 
412 int32_t L1C::ect_swt(int swt,l1c_filehandle *l1cfile,int32_t norbs,double *tswt,double *latswt,double *lonswt,float*tcross,float*loncross){
413  //determine equatorial crossing time--------------
414  double t1=-1,t2=-1;
415  int asc_mode=-1;
416  size_t tindex=-1;
417  int scan_brack[2] = { -1,-1 };
418  float lat1, lat2, lon1, lon2;//lat,lon defined globally
419  int flag_ect=-1;
420 
421  //determine orbit direction--asc/desc
422  if (latswt[0] > latswt[1])
423  asc_mode = 0;//descending
424  else
425  asc_mode = 1;//ascending
426 
427  cout<<"computing equatorial crossing time and longitude at crossing for a specific swath...#..."<<swt<<"orbit direction 0: descending, 1: ascending..."<<asc_mode<<endl;
428  for (int i = 0;i < norbs - 1;i++) { //improve with binary search
429  if (asc_mode == 1 && latswt[i] < 0. && latswt[i + 1]>0.) {
430  scan_brack[0] = i + 1;
431  scan_brack[1] = i + 2;
432  lat1 = latswt[i];
433  lat2 = latswt[i + 1];
434  lon1 = lonswt[i];
435  lon2 = lonswt[i + 1];
436  tindex=i;
437  i=norbs;
438  break;
439  }
440 
441  else if (asc_mode == 0 && latswt[i] > 0. && latswt[i + 1] < 0) { //descending orbit
442  scan_brack[0] = i + 2;//negative lat first convention
443  scan_brack[1] = i + 1;
444  lat1 = latswt[i + 1];
445  lat2 = latswt[i];
446  lon1 = lonswt[i + 1];
447  lon2 = lonswt[i];
448  tindex=i;
449  i=norbs;
450  break;
451  }
452  } //end for
453 
454 
455  //interpolate time--linear
456 
457  if (scan_brack[0] > -1) {//if file with equat crossing
458  t1 = tswt[tindex];
459  t2 = tswt[tindex + 1];
460  cout<<"lat1.."<<lat1<<"lat2..."<<lat2<<"t1.."<<t1<<"t2..."<<t2<<endl;
461  *tcross = t1 - lat1 * (t2 - t1) / (lat2 - lat1);//equat crossing time
462 
463  float dtcross = (*tcross - t1) / (t2 - t1);
464  *loncross = lon1 + (lon2 - lon1) * dtcross;//latcross is zero
465 
466  l1cfile->eqt =*tcross;
467  l1cfile->orbit_node_lon = *loncross;
468  l1cfile->orb_dir = asc_mode;
469  flag_ect=0;
470  }
471  else {
472  l1cfile->eqt = -999.0;
473  l1cfile->orbit_node_lon = -999.0;
474  l1cfile->orb_dir = asc_mode;
475  flag_ect=1;
476  }
477 
478 
479  return flag_ect;
480  }
481 
482 
483 
484 
485 
486 
487 int32_t L1C::ect_vec(int swt,l1c_filehandle *l1cfile,vector<double>& tvec,vector<double>& latvec,vector<double>& lonvec,float*tcross,float*loncross){
488  //determine equatorial crossing time--------------
489  double t1=-1,t2=-1;
490  int asc_mode=-1;
491  size_t tindex=-1;
492  int scan_brack[2] = { -1,-1 };
493  float lat1, lat2, lon1, lon2;//lat,lon defined globally
494  int flag_ect=-1;
495 
496  //determine orbit direction--asc/desc
497  if (latvec[0] > latvec[1])
498  asc_mode = 0;//descending
499  else
500  asc_mode = 1;//ascending
501 
502  cout<<"computing equatorial crossing time and longitude at crossing for a specific swath...#..."<<swt<<"orbit direction 0: descending, 1: ascending..."<<asc_mode<<endl;
503  for (size_t i = 0;i < latvec.size() - 1;i++) { //improve with binary search
504  if (asc_mode == 1 && latvec[i] < 0. && latvec[i + 1]>0.) {
505  scan_brack[0] = i + 1;
506  scan_brack[1] = i + 2;
507  lat1 = latvec[i];
508  lat2 = latvec[i + 1];
509  lon1 = lonvec[i];
510  lon2 = lonvec[i + 1];
511  tindex=i;
512  i=latvec.size();
513  break;
514  }
515 
516  else if (asc_mode == 0 && latvec[i] > 0. && latvec[i + 1] < 0) { //descending orbit
517  scan_brack[0] = i + 2;//negative lat first convention
518  scan_brack[1] = i + 1;
519  lat1 = latvec[i + 1];
520  lat2 = latvec[i];
521  lon1 = lonvec[i + 1];
522  lon2 = lonvec[i];
523  tindex=i;
524  i=latvec.size();
525  break;
526  }
527  } //end for
528 
529 
530  //interpolate time--linear
531 
532  if (scan_brack[0] > -1) {//if file with equat crossing
533  t1 = tvec[tindex];
534  t2 = tvec[tindex + 1];
535  cout<<"lat1.."<<lat1<<"lat2..."<<lat2<<"t1.."<<t1<<"t2..."<<t2<<endl;
536  *tcross = t1 - lat1 * (t2 - t1) / (lat2 - lat1);//equat crossing time
537 
538  float dtcross = (*tcross - t1) / (t2 - t1);
539  *loncross = lon1 + (lon2 - lon1) * dtcross;//latcross is zero
540 
541  l1cfile->eqt =*tcross;
542  l1cfile->orbit_node_lon = *loncross;
543  l1cfile->orb_dir = asc_mode;
544  flag_ect=0;
545  }
546  else {
547  l1cfile->eqt = -999.0;
548  l1cfile->orbit_node_lon = -999.0;
549  l1cfile->orb_dir = asc_mode;
550  flag_ect=1;
551  }
552 
553 
554  return flag_ect;
555  }
556 
557 
558 //open telemetry file parameters for creating L1C grid----
559 
560  int32_t L1C::open_l1atol1c(L1C_input *l1cinput,l1c_filehandle *l1cfile){
561  int32_t n_files;
562  const char* ptstr;
563  char *ifile_char;
564  string str,ifile_str;
565  int status=-1,status1=-1,status2=-1;
566  int telGrp,navGrp,scpId,otimeId,olatId,olonId;
567  int dimhp,dimtp,dimor;
568  unsigned char **hkpackets=nullptr;
569  uint8_t *apids=nullptr;
570  size_t number_hkpack,number_scpack,number_orecords;
571  uint8_t ubnum1,ubnum2;
572  double *sec=nullptr,*tai58_sec=nullptr;
573  int16_t *year=nullptr,*mon=nullptr,*day=nullptr,*hour=nullptr,*min=nullptr;
574  int16_t oneyear,onemon,oneday,onehour,onemin;
575  double onesec;
576  double *orb_time=nullptr,*orb_lat=nullptr,*orb_lon=nullptr;
577  float *lati=nullptr,*loni=nullptr,*lati2=nullptr,*loni2=nullptr;
578  float **lat_gd=nullptr,**lon_gd=nullptr,*az_gd=nullptr;
579  double omeg = 7.29211585494e-5;
580  short n_ephem;
581  string temp_str,tai_str;
582  double vxyz=0,sum1=0,sum2=0,mov1=0.,mgv1=0.,mov2=0,mgv2,*orb_vel=nullptr,*grn_vel=nullptr;
583  double sum3=0;
584  int *orb_dir=nullptr;
585  size_t nswath;
586  int32_t ix1=-1,ix2=-1,ix3=-1,ix4=-1,ix5=-1,ix6=-1;
587  double *tmgv1=nullptr,*tmgv2=nullptr,*tmgvf=nullptr,*tmgvf2=nullptr;
588  int32_t num_gridlines=-1,norbs=-1;
589  double *tswt=nullptr,*latswt=nullptr,*lonswt=nullptr;
590  double *tswt2=nullptr,*latswt2=nullptr,*lonswt2=nullptr;
591  const char* outfile;
592  string ofile_str,senstr;
593  size_t fi=0;
594  float latmin,latmax;
595  string y_swt,mo_swt,d_swt,h_swt,mi_swt,s_swt,tswt_ini,tswt_end;
596  int32_t gd_per_gran=-1,numgran=-1;
597  double deltasec=-1;
598  string s_swt2;
599  int length;
600  string tswt_ini_file;
601  double v1[3],v2[3],vecout[3],orbnorm[3],nvec,vi,toff;
602  double rl2,pos_norm,clatg2,fe=1/298.257;
603 
604  double oangle,G[3],glat,glon,gnorm,rem=6371,omf2,omf2p,pxy,temp;
605 // double alt=0.,rl,clatg;
606  vector<size_t> ix;
607  double tfile_ini;
608  size_t att_len;
609  int16_t syear, smon, sday,shour,smin;
610  double secs,second;
611  int logoff=-1;
612 
613 
614  ifile_str = l1cinput->files[0];
615  ifile_char = &ifile_str[0];
616  ofile_str=ifile_str.substr(0,24);
617  outfile=ofile_str.c_str();
618  strcpy(l1cinput->ofile,outfile);
619 
620  cout<<"output file token...."<<l1cinput->ofile<<endl;
621  l1cfile->nbinx=l1cinput->nbinx;
622  l1cfile->gransize=l1cinput->gransize;
623 
624  file_format format = getFormat(ifile_char);
625  cout<<"format.type.."<<format.type<<endl;
626  cout<<"# of L1C across gridlines..."<<l1cfile->nbinx<<endl;
627 
628  l1cfile->sensor=l1cinput->sensor;//SPEX 1, OCI 2 and HARP 3
629 
630  if(l1cinput->sensor==1){
631  senstr="SPEXone";
632  l1cfile->nbinx=20;
633  }
634  else if (l1cinput->sensor==2){
635  senstr="OCI";
636  l1cfile->nbinx=514;
637  }
638  else if (l1cinput->sensor==3){
639  senstr="HARP2";
640  l1cfile->nbinx=452;
641  }
642  else{cout<<"sensor by default is OCI option 2....."<<endl;
643  senstr="OCI";
644  l1cfile->nbinx=514;
645  }
646 
647  cout<<"PACE sensor to be griddded....."<<senstr<<endl;
648 
649  n_files = l1cfile->ifiles.size();
650  cout<<"number of files in the list...."<<n_files<<endl;
651 
652 //big loop-------
653  //opening datafile for binning-----
654  fi=0;
655  str = l1cfile->ifiles[fi];
656  ptstr = str.c_str();
657  cout<<"*********************************************************************************************************"<<endl;
658  cout<<"Opening L1A file ..."<<ptstr<<"for telemetry......."<<ptstr<<"file index list #...."<<l1cinput->fileix<<endl;
659  cout<<"*********************************************************************************************************"<<endl;
660 
661  // Open the netcdf4 input file
662  // NC_UBYTE
663  status = nc_open(ptstr, NC_NOWRITE, &ncid_L1A);
664  if (status != NC_NOERR) {
665  fprintf(stderr, "-E- Error failed nc_open.\n");
666  exit(EXIT_FAILURE);
667  }
668 
669  // reading file start coverage time---------
670  //make sure the date (year/month.day) is the same for the bunch of files--
671  status = nc_inq_attlen(ncid_L1A, NC_GLOBAL, "time_coverage_start", &att_len);
672  check_err(status, __LINE__, __FILE__);
673  // allocate required space before retrieving values
674  char* time_str = (char*)malloc(att_len + 1); // + 1 for trailing null
675  // get global attribute values
676  status = nc_get_att_text(ncid_L1A, NC_GLOBAL, "time_coverage_start", time_str);
677  check_err(status, __LINE__, __FILE__);
678  time_str[att_len] = '\0';
679  tfile_ini = isodate2unix(time_str);//iso time string to unix since 1970
680  unix2ymds(tfile_ini, &syear, &smon, &sday,&secs);
681  cout<<"secs elapsed.."<<secs<<"initial granule #..."<<round(secs/(l1cfile->gransize*60))<<endl;
682  unix2ymdhms(tfile_ini, &syear,&smon,&sday,&shour,&smin,&second);
683  cout<<"HKT file start time................."<<"year.."<<syear<<"month..."<<smon<<"day..."<<sday<<"hour.."<<shour<<"min.."<<smin<<"sec..."<<second<<endl;
684 
685  secs=0.;
686 
687  double tfile_ini_sec=ymds2unix(syear,smon,sday,secs);
688 
689  int16_t y_ini,mo_ini,d_ini,h_ini,mi_ini;
690  double sec_ini;
691  unix2ymdhms(tfile_ini_sec,&y_ini,&mo_ini,&d_ini, &h_ini, &mi_ini, &sec_ini);
692  cout<<"tfile_ini_sec.."<<"YEAR.."<<y_ini<<"MONTH.."<<mo_ini<<"DAY.."<<d_ini<<"HOUR.."<<h_ini<<"MIN.."<<mi_ini<<"SEC.."<<sec_ini<<endl;
693 
694 
695  //open dimensions
697  status = nc_inq_dimid(ncid_L1A, "SC_hkt_pkts", &dimhp);//number of spacecraft packets
698  check_err(status, __LINE__, __FILE__);
699  status = nc_inq_dimid(ncid_L1A, "max_SC_packet", &dimtp);//size of packets
700  check_err(status, __LINE__, __FILE__);
701  status = nc_inq_dimid(ncid_L1A, "orb_records", &dimor);//number of orbital records for SC track lat/lon
702  check_err(status, __LINE__, __FILE__);
703 
704  nc_inq_dimlen(ncid_L1A, dimhp, &number_hkpack);
705  nc_inq_dimlen(ncid_L1A, dimtp, &number_scpack);
706  nc_inq_dimlen(ncid_L1A, dimor, &number_orecords);
707 
708  cout<<"number_hkpack.."<<number_hkpack<<"number_scpack.."<<number_scpack<<"number of orbit records.."<<number_orecords<<endl;
709 
710  //allocat mem
711  hkpackets=allocate2d_uchar(number_hkpack, number_scpack);//NUMBER of ephem elements x max SIZE of package
712  apids=(uint8_t*)calloc(number_hkpack,sizeof(uint8_t));
713 
714  orb_time=(double*)calloc(number_orecords,sizeof(double));
715  orb_lat=(double*)calloc(number_orecords,sizeof(double));
716  orb_lon=(double*)calloc(number_orecords,sizeof(double));
717  orb_dir = (int*)calloc(number_orecords,sizeof(int));
718 
719  //open groups
720  status = nc_inq_grp_ncid(ncid_L1A, "housekeeping_data", &telGrp);
721  check_err(status, __LINE__, __FILE__);
722  status = nc_inq_grp_ncid(ncid_L1A, "navigation_data", &navGrp);
723  check_err(status, __LINE__, __FILE__);
724 
725  //open vars ids
726  status = nc_inq_varid(telGrp, "SC_HKT_packets", &scpId);
727  check_err(status, __LINE__, __FILE__);
728  status = nc_inq_varid(navGrp, "orb_time", &otimeId);//second of the day
729  check_err(status, __LINE__, __FILE__);
730  status = nc_inq_varid(navGrp, "orb_lat", &olatId);
731  check_err(status, __LINE__, __FILE__);
732  status = nc_inq_varid(navGrp, "orb_lon", &olonId);
733  check_err(status, __LINE__, __FILE__);
734 
735  //get data
736  status = nc_get_var_ubyte(telGrp, scpId, &hkpackets[0][0]);
737  check_err(status, __LINE__, __FILE__);
738 
739 
740  status = nc_get_var_double(navGrp, otimeId, &orb_time[0]);
741  check_err(status, __LINE__, __FILE__);
742  status = nc_get_var_double(navGrp, olatId, &orb_lat[0]);
743  check_err(status, __LINE__, __FILE__);
744  status = nc_get_var_double(navGrp, olonId, &orb_lon[0]);
745  check_err(status, __LINE__, __FILE__);
746 
747 
748  for(size_t hk=0;hk<number_hkpack;hk++){
749  ubnum1=(uint8_t)hkpackets[hk][0]; //-48;//48 is 0 ascii code
750  ubnum2=(uint8_t)hkpackets[hk][1];
751 
752  apids[hk] = (ubnum1%8)*256 + ubnum2;
753  if(apids[hk]==128){
754  ix.push_back(hk);//packet index where ephemr
755  }
756  }
757 
758  cout<<"#number of ephem elements...."<<ix.size()<<endl;
759  n_ephem=ix.size();
760 
761  // Reverse the byte order from small endian to large endian, small endian last byte is stored first
762  // convert to double and later swap endian
763 
764  //allocate mem
765  orb_vel = (double*)calloc(n_ephem,sizeof(double));
766  grn_vel = (double*)calloc(n_ephem,sizeof(double));
767 
768  sec=(double*)calloc(n_ephem,sizeof(double));
769  year=(int16_t*)calloc(n_ephem,sizeof(int16_t));
770  mon=(int16_t*)calloc(n_ephem,sizeof(int16_t));
771  day=(int16_t*)calloc(n_ephem,sizeof(int16_t));
772  hour=(int16_t*)calloc(n_ephem,sizeof(int16_t));
773  min=(int16_t*)calloc(n_ephem,sizeof(int16_t));
774 
775  tai58_sec=(double*)calloc(n_ephem,sizeof(double));
776 
777 
778  //process all packets----
779  double tai58;
780  size_t c=0;
781  //TIME
782  while (c<ix.size()){
783  double *tai_ptr = (double*) (hkpackets[ix[c]] + 16);//moving pointer to position 16
784  swapc_bytes((char*) tai_ptr, 8, 1);//swap 8 bytes once or 1 16-23 pos, lets say we have 16-32 indexes and we want to swap 8 bytes at the time, some we need ntime=2
785  tai58 = *tai_ptr;
786  double tai58unix=tai58_to_unix(tai58);
787 
788  unix2ymdhms(tai58unix,&oneyear,&onemon,&oneday, &onehour, &onemin, &onesec);
789 
790  year[c]=oneyear;
791  mon[c]=onemon;
792  day[c]=oneday;
793  hour[c]=onehour;
794  min[c]=onemin;
795  sec[c]=onesec;
796 
797  tai58_sec[c]=tai58unix;
798 
799  c++;
800  }
801 
802 
803  //POS/VEL alloc mem-----
804  orb_array2* posr = new orb_array2[n_ephem]();
805  orb_array2* velr = new orb_array2[n_ephem]();
806 
807  double dp1,dp2,dp3;
808 
809  //computed orbital velocity from ephemeris
810  c=0;
811  while (c<ix.size()){
812  double *posi = (double*) (hkpackets[ix[c]] + 120);
813  double *veli = (double*) (hkpackets[ix[c]] + 144);
814  double *ecmat = (double*) (hkpackets[ix[c]] + 176);
815 
816  swapc_bytes((char*) posi, 8, 3);
817  swapc_bytes((char*) veli, 8, 3);
818  swapc_bytes((char*) ecmat, 8, 9);
819 
820  //assuming ecmat index 1-3 first row, 4-6 second row and 7-9 third row
821  //dot product
822  //position
823  dp1=posi[0]*ecmat[0]+posi[1]*ecmat[1]+posi[2]*ecmat[2];
824  dp2=posi[0]*ecmat[3]+posi[1]*ecmat[4]+posi[2]*ecmat[5];
825  dp3=posi[0]*ecmat[6]+posi[1]*ecmat[7]+posi[2]*ecmat[8];
826 
827  posr[c][0]=dp1;
828  posr[c][1]=dp2;
829  posr[c][2]=dp3;
830 
831  //velocity
832  dp1=veli[0]*ecmat[0]+veli[1]*ecmat[1]+veli[2]*ecmat[2];
833  dp2=veli[0]*ecmat[3]+veli[1]*ecmat[4]+veli[2]*ecmat[5];
834  dp3=veli[0]*ecmat[6]+veli[1]*ecmat[7]+veli[2]*ecmat[8];
835 
836  velr[c][0]=dp1;
837  velr[c][1]=dp2;
838  velr[c][2]=dp3;
839 
840  velr[c][0]=velr[c][0] + posr[c][1]*omeg;
841  velr[c][1]=velr[c][1] - posr[c][0]*omeg;
842 
843  //computing orbital velocity
844  vxyz = sqrt(velr[c][0] * velr[c][0] + velr[c][1] * velr[c][1] + velr[c][2] * velr[c][2]);//units m/s
845  orb_vel[c]=vxyz;
846 
847  pos_norm=sqrt(posr[c][0]*posr[c][0]+posr[c][1]*posr[c][1]+posr[c][2]*posr[c][2]);
848  clatg2=sqrt(posr[c][0]*posr[c][0]+posr[c][1]*posr[c][1])/pos_norm;
849  rl2=Re*(1-fe)/(sqrt(1-(2-fe)*fe*clatg2*clatg2));
850  grn_vel[c]=vxyz*rl2/pos_norm;
851 
852  c++;
853  }
854 
855  if (hkpackets != nullptr)
856  delete[](hkpackets);
857  hkpackets= nullptr;
858 
859  if (apids != nullptr)
860  delete[](apids);
861  apids= nullptr;
862 
863 
864 //determine ini/end time indexes for asc/desc passes
865  for(size_t k=0;k<number_orecords-1;k++){
866  if(orb_lat[k+1]>orb_lat[k])
867  orb_dir[k]=1;//ascending
868  else orb_dir[k]=0;//descending
869  }
870 
871 //find time limits for half-orbits
872  int swt=1;
873  int16_t tlimits_swt[2][2]={{-1,-1},{-1,-1}};//2 swath x time limits ini/end
874  tlimits_swt[swt-1][0]=0;//only the indexes
875 
876 
877  for(size_t k=0;k<number_orecords-1;k++){
878  if(orb_dir[k]!=orb_dir[k+1]){
879  if(swt==1){
880  tlimits_swt[swt-1][1]=k;//this time is a 'local' end cause may continue circling the earth after ascending or descending
881  swt++;
882  tlimits_swt[swt-1][0]=k+1;
883  }
884  else if(swt==2){//another partial swath
885  tlimits_swt[swt-1][1]=k;
886  tlimits_swt[swt-2][1]=number_orecords-1;
887  swt++;
888  }
889  }
890 
891  if(k==number_orecords-2 && swt==2) tlimits_swt[swt-1][1]=number_orecords-1;
892  }
893 
894  nswath=swt;
895 
896 
897 //split half-orbits---- group lat/lon time and velocity vector
898 
899  for (size_t sw=0;sw<2;sw++){
900  if(nswath==2){
901  if(sw==0){
902  ix1=tlimits_swt[sw][0];
903  ix2=tlimits_swt[sw][1];
904  cout<<"swat#1...ix1"<<ix1<<"ix2.."<<ix2<<endl;
905  }
906  else if(sw==1){
907  ix3=tlimits_swt[sw][0];
908  ix4=tlimits_swt[sw][1];
909  cout<<"swat#2...ix3"<<ix3<<"ix4.."<<ix4<<endl;
910  }
911  }
912  else if(nswath==3){ //>2 we have 4 limits for swath 1
913  if(sw==0){
914  ix1=tlimits_swt[sw][0];
915  ix2=tlimits_swt[sw+1][0]-1;
916  ix3=tlimits_swt[sw+1][1]+1;
917  ix4=tlimits_swt[sw][1];
918  cout<<"swat#1...ix1"<<ix1<<"ix2.."<<ix2<<"ix3.."<<ix3<<"ix4..."<<ix4<<endl;
919  }
920  else if(sw==1){
921  ix5=tlimits_swt[sw][0];
922  ix6=tlimits_swt[sw][1];
923  cout<<"swat#2...ix5"<<ix5<<"ix6.."<<ix6<<endl;
924  }
925  }
926  else{
927  cout<<"number of swaths is less than 2..!! exit..."<<endl;
928  exit(1);
929  }
930  }
931 
932  int kk;
933  float tcross1=-999.,loncross1=-999.,tcross2=-999.,loncross2=-999.;
934 
935 //--------------------------------------------------------------------------------------
936 //----half orbits are consecutive
937 //swath1
938 //--------------------------------------------------------------------------------------
939  if(nswath==2){
940  if(ix1>=0 && ix5<0){
941  norbs=ix2-ix1+1;
942  kk=ix1;
943  c=0;
944  latmin=orb_lat[ix1];
945  latmax=orb_lat[ix2];
946 
947 //orbit direction
948  l1cfile->orb_dir=orb_dir[ix1];
949 
950 //ini and end UTC--this is swath orbital time, not interpolated time
951  y_swt=std::to_string(year[ix1]);
952  mo_swt=std::to_string(mon[ix1]);
953  d_swt=std::to_string(day[ix1]);
954  h_swt=std::to_string(hour[ix1]);
955  mi_swt=std::to_string(min[ix1]);
956  s_swt2=std::to_string(round(sec[ix1]));
957 
958  length = (int) floor( log10 (mon[ix1]) ) + 1;
959  if(length==1) mo_swt="0"+mo_swt;
960  length = (int) floor( log10 (day[ix1]) ) + 1;
961  if(length==1) d_swt="0"+d_swt;
962 
963  if(hour[ix1]==0) logoff=1; else logoff=0;
964  length = (int) floor( log10 (hour[ix1]+logoff)) + 1;
965  if(length==1) h_swt="0"+h_swt;
966 
967  if(min[ix1]==0) logoff=1; else logoff=0;
968  length = (int) floor( log10 (min[ix1]+logoff)) + 1;
969  if(length==1) mi_swt="0"+mi_swt;
970 
971  if(sec[ix1]==0) logoff=1; else logoff=0;
972  length = (int) floor( log10 (round(sec[ix1])+logoff)) + 1;
973  if(length==1) s_swt2="0"+s_swt2;
974 
975  tswt_ini=y_swt+"-"+mo_swt+"-"+d_swt+"T"+h_swt+":"+mi_swt+":"+s_swt2.substr(0,2)+"Z";
976  tswt_ini_file=y_swt+mo_swt+d_swt+"T"+h_swt+mi_swt+s_swt2.substr(0,2)+"Z";
977 
978  y_swt=std::to_string(year[ix2]);
979  mo_swt=std::to_string(mon[ix2]);
980  d_swt=std::to_string(day[ix2]);
981  h_swt=std::to_string(hour[ix2]);
982  mi_swt=std::to_string(min[ix2]);
983 
984  length = (int) floor( log10 (mon[ix2]) ) + 1;
985  if(length==1) mo_swt="0"+mo_swt;
986  length = (int) floor( log10 (day[ix2]) ) + 1;
987  if(length==1) d_swt="0"+d_swt;
988 
989  if(hour[ix2]==0) logoff=1; else logoff=0;
990  length = (int) floor( log10 (hour[ix2]+logoff)) + 1;
991  if(length==1) h_swt="0"+h_swt;
992 
993  if(min[ix2]==0) logoff=1; else logoff=0;
994  length = (int) floor( log10 (min[ix2]+logoff)) + 1;
995  if(length==1) mi_swt="0"+mi_swt;
996 
997  if(sec[ix2]==0) logoff=1; else logoff=0;
998  length = (int) floor( log10 (round(sec[ix2])+logoff)) + 1;
999  if(length==1) s_swt2="0"+s_swt2;
1000 
1001  tswt_end=y_swt+"-"+mo_swt+"-"+d_swt+"T"+h_swt+":"+mi_swt+":"+s_swt2.substr(0,2)+"Z";
1002 
1003  tswt=(double*)calloc(norbs,sizeof(double));
1004  latswt=(double*)calloc(norbs,sizeof(double));
1005  lonswt=(double*)calloc(norbs,sizeof(double));
1006 
1007  sum1=0,sum3=0,c=0;
1008  while(kk<=ix2){
1009  latswt[c]=orb_lat[kk];
1010  lonswt[c]=orb_lon[kk];
1011  tswt[c]=orb_time[kk];
1012 
1013  if(orb_lat[kk]<=latmin){
1014  latmin=orb_lat[kk];
1015  }
1016  if(orb_lat[kk]>=latmax){
1017  latmax=orb_lat[kk];
1018  }
1019 
1020  sum1+=orb_vel[kk];
1021  sum3+=grn_vel[kk];
1022  kk++;
1023  c++;
1024  }
1025  //computing mean swath velocity (m/s) --------------------------
1026  mov1 = (sum1 /norbs);//mean velocity in m/s
1027  mgv1 = (sum3 /norbs)*1000;//in meters/s
1028 
1029  cout<<"mov1..."<<mov1<<"mvg1..."<<mgv1<<endl;
1030 
1031  status=ect_swt(1,l1cfile,norbs,tswt,latswt,lonswt,&tcross1,&loncross1);
1032  cout<<"nswath==2 --tcross equat crossing in (s)..swath#1..."<<tcross1<<"loncross1..."<<loncross1<<endl;
1033  cout<<"latmin.."<<latmin<<"latmax..."<<latmax<<endl;
1034 
1035 
1036  if (latswt != nullptr)
1037  delete[](latswt);
1038  latswt= nullptr;
1039  if (lonswt != nullptr)
1040  delete[](lonswt);
1041  lonswt= nullptr;
1042 
1043  l1cfile->num_gridlines=4001;
1044  if(status==0){
1045  tmgv1=(double*)calloc(l1cfile->num_gridlines,sizeof(double));
1046  tmgvf=(double*)calloc(l1cfile->num_gridlines,sizeof(double));
1047 
1048  swtime_swt2(1,l1cinput,l1cfile,norbs,tswt,tcross1,mgv1,tmgv1);
1049 
1050  //ini/end times for swath
1051  num_gridlines = l1cfile->num_gridlines;
1052 
1053  //tini/tend swath
1054  l1cfile->tswt_ini=tswt_ini;
1055  l1cfile->tswt_end=tswt_end;
1056  l1cfile->tswt_ini_file=tswt_ini_file;
1057 
1058  //first interpolation
1059  lati=(float*)calloc(num_gridlines,sizeof(float));
1060  loni=(float*)calloc(num_gridlines,sizeof(float));
1061  lati2=(float*)calloc(num_gridlines,sizeof(float));
1062  loni2=(float*)calloc(num_gridlines,sizeof(float));
1063  az_gd = (float*)calloc(num_gridlines,sizeof(float));
1064 
1065  cout<<"number of across bins L1C grid...#.."<<l1cfile->nbinx<<endl;
1066 
1067 //FRED SOCEA---
1068  // search_SOCEA(l1cinput,l1cfile, lat_gd,lon_gd,tmgv1,tcross1,loncross1);
1069 
1070  lat_gd = allocate2d_float(4001, l1cfile->nbinx);
1071  lon_gd = allocate2d_float(4001, l1cfile->nbinx);
1072 
1073  orb_array2* posgrid = new orb_array2[num_gridlines]();//these are doubles
1074  orb_array2* velgrid = new orb_array2[num_gridlines]();
1075 
1076  orb_array2* posgrid2 = new orb_array2[num_gridlines]();//these are doubles
1077  orb_array2* velgrid2 = new orb_array2[num_gridlines]();
1078 
1079 //interp 1-- always based on orbitals---
1080  //interpola pos/veloc as a function of time
1081  orb_interp2(number_orecords, num_gridlines,orb_time,posr,velr,tmgv1, posgrid,velgrid);
1082 
1083  for(int i=0;i<num_gridlines-1;i++){
1084  pos_norm=sqrt(posgrid[i][0]*posgrid[i][0]+posgrid[i][1]*posgrid[i][1]+posgrid[i][2]*posgrid[i][2]);
1085  clatg2=sqrt(posgrid[i][0]*posgrid[i][0]+posgrid[i][1]*posgrid[i][1])/pos_norm;
1086  rl2=Re*(1-fe)/(sqrt(1-(2-fe)*fe*clatg2*clatg2));
1087 
1088  v2[0]=velgrid[i][0]*rl2/pos_norm;
1089  v2[1]=velgrid[i][1]*rl2/pos_norm;
1090  v2[2]=velgrid[i][2]*rl2/pos_norm;
1091 
1092  vi=sqrt(v2[0]*v2[0]+v2[1]*v2[1]+v2[2]*v2[2])*1000;
1093  toff=vi/mgv1;
1094  tmgvf[i]=tmgv1[i]+toff;
1095 
1096  }
1097 
1098  orb_interp2(number_orecords, num_gridlines,orb_time,posr,velr,tmgvf, posgrid2,velgrid2);
1099 
1100 
1101  //angle subsat track----
1102  omf2=(1-fe)*(1-fe);
1103 
1104  for(int i=0;i<num_gridlines-1;i++){
1105  pos_norm=sqrt(posgrid2[i][0]*posgrid2[i][0]+posgrid2[i][1]*posgrid2[i][1]+posgrid2[i][2]*posgrid2[i][2]);
1106  clatg2=sqrt(posgrid2[i][0]*posgrid2[i][0]+posgrid2[i][1]*posgrid2[i][1])/pos_norm;
1107  rl2=Re*(1-fe)/(sqrt(1-(2-fe)*fe*clatg2*clatg2));
1108 
1109  v1[0]=(posgrid2[i][0])*rl2/pos_norm;
1110  v1[1]=(posgrid2[i][1])*rl2/pos_norm;
1111  v1[2]=(posgrid2[i][2])*rl2/pos_norm;
1112 
1113  v2[0]=(velgrid2[i][0])*rl2/pos_norm;
1114  v2[1]=(velgrid2[i][1])*rl2/pos_norm;
1115  v2[2]=(velgrid2[i][2])*rl2/pos_norm;
1116 
1117  cross_product_double(v1,v2,vecout);
1118  nvec=cross_product_norm_double(v1,v2);//length of orb norm vect
1119 
1120  orbnorm[0]=vecout[0]/nvec;
1121  orbnorm[1]=vecout[1]/nvec;
1122  orbnorm[2]=vecout[2]/nvec;
1123 
1124  for(int j=0;j<l1cfile->nbinx;j++){
1125 
1126  pos_norm=sqrt(v1[0]*v1[0]+v1[1]*v1[1]+v1[2]*v1[2]);//first gridline
1127 
1128  oangle=asin((j-(l1cfile->nbinx-1)/2)*5.2/pos_norm);
1129 
1130  //Geocentric vector
1131  G[0]=v1[0]*cos(oangle)-orbnorm[0]*pos_norm*sin(oangle);
1132  G[1]=v1[1]*cos(oangle)-orbnorm[1]*pos_norm*sin(oangle);
1133  G[2]=v1[2]*cos(oangle)-orbnorm[2]*pos_norm*sin(oangle);
1134 
1135  glon=atan2(G[1],G[0])*180/M_PI;
1136 
1137  gnorm = sqrt(G[0]*G[0]+G[1]*G[1]+G[2]*G[2]);
1138  omf2p = (omf2*rem + gnorm - rem)/gnorm;
1139  pxy = G[0]*G[0]+G[1]*G[1];
1140  temp = sqrt(G[2]*G[2] + omf2p*omf2p*pxy);
1141  glat=asin(G[2]/temp)*180/M_PI;
1142 
1143  lat_gd[i][j]=glat;
1144  lon_gd[i][j]=glon;
1145 
1146  //altitude
1147  // clatg = cos(atan(omf2*tan(glat*M_PI/180.)));
1148 // rl = re*(1.-fe)/sqrt(1.-(2.-fe)*fe*clatg*clatg);
1149  // alt = gnorm - rl;
1150  }
1151  }
1152 
1153  if (posgrid != nullptr)
1154  delete[](posgrid);
1155 
1156  if (velgrid != nullptr)
1157  delete[](velgrid);
1158 
1159  if (posgrid2 != nullptr)
1160  delete[](posgrid2);
1161 
1162  if (velgrid2 != nullptr)
1163  delete[](velgrid2);
1164 
1165  l1cfile->num_gridlines = l1cfile->num_gridlines-1;
1166  // create_SOCEA(1,l1cinput,l1cfile,lat_gd,lon_gd);//THIS IS SWATH PROCESSING
1167 
1168 //--------------------------------------------------------------
1169 //granule processing---------------------------------------------
1170 //---------------------------------------------------------------
1171 
1172  l1cfile->tfile_ini_sec=tfile_ini_sec;
1173  deltasec=tmgvf[num_gridlines-2]-tmgvf[0]+1;
1174  cout<<"deltasec..swath."<<deltasec<<endl;
1175 
1176  if(tswt != nullptr)
1177  delete[](tswt);
1178  tswt= nullptr;
1179 
1180  numgran=144*2;
1181  l1cfile->numgran=numgran;
1182  gd_per_gran=round(num_gridlines/10);//10 granules per half orbit
1183  l1cfile->gd_per_gran=gd_per_gran;
1184 
1185  cout<<"estimated # of granules to be processed..."<<numgran<<"gd_per_gran..."<<gd_per_gran<<"#gridlines.."<<num_gridlines<<endl;
1186 
1187  write_L1C_granule(1,l1cfile,l1cinput,tmgvf,lat_gd, lon_gd);
1188 
1189 //-----------------------------------------------------------------
1190 //-----------------------------------------------------------------
1191 
1192  if (lat_gd != nullptr)
1193  delete [](lat_gd);
1194  lat_gd = nullptr;
1195  if (lon_gd != nullptr)
1196  delete [](lon_gd);
1197  lon_gd = nullptr;
1198  if (az_gd != nullptr)
1199  delete [](az_gd);
1200  az_gd = nullptr;
1201 
1202  if (lati != nullptr)
1203  delete[](lati);
1204  lati= nullptr;
1205  if (loni != nullptr)
1206  delete[](loni);
1207  loni= nullptr;
1208 
1209  if (lati2 != nullptr)
1210  delete[](lati2);
1211  lati2= nullptr;
1212  if (loni2 != nullptr)
1213  delete[](loni2);
1214  loni2= nullptr;
1215  if (tmgv1 != nullptr)
1216  delete[](tmgv1);
1217  tmgv1= nullptr;
1218  if (tmgvf != nullptr)
1219  delete[](tmgvf);
1220  tmgvf= nullptr;
1221  }
1222  else{
1223  cout<<"ERROR swath #1 does not cross the equator..."<<endl;
1224  cout<<"checking swath #2..."<<endl;
1225  }
1226 
1227 //nswath=2
1228 //-------------------------------------------------------------------------------------------------------
1229 //swath#2
1230 //-------------------------------------------------------------------------------------------------------
1231  kk=ix3;
1232  c=0;
1233  norbs=ix4-ix3+1;
1234  latmin=orb_lat[ix3];
1235  latmax=orb_lat[ix3];
1236 
1237  //orbit direction
1238  l1cfile->orb_dir=orb_dir[ix3];
1239 
1240  //ini and end UTC--this is swath orbital time, not interpolated time
1241  y_swt=std::to_string(year[ix3]);
1242  mo_swt=std::to_string(mon[ix3]);
1243  d_swt=std::to_string(day[ix3]);
1244  h_swt=std::to_string(hour[ix3]);
1245  mi_swt=std::to_string(min[ix3]);
1246  s_swt2=std::to_string(round(sec[ix3]));
1247 
1248  length = (int) floor( log10 (mon[ix3]) ) + 1;
1249  if(length==1) mo_swt="0"+mo_swt;
1250  length = (int) floor( log10 (day[ix3]) ) + 1;
1251  if(length==1) d_swt="0"+d_swt;
1252 
1253  if(hour[ix3]==0) logoff=1; else logoff=0;
1254  length = (int) floor( log10 (hour[ix3]+logoff)) + 1;
1255  if(length==1) h_swt="0"+h_swt;
1256 
1257  if(min[ix3]==0) logoff=1; else logoff=0;
1258  length = (int) floor( log10 (min[ix3]+logoff)) + 1;
1259  if(length==1) mi_swt="0"+mi_swt;
1260 
1261  if(sec[ix3]==0) logoff=1; else logoff=0;
1262  length = (int) floor( log10 (round(sec[ix3])+logoff)) + 1;
1263  if(length==1) s_swt2="0"+s_swt2;
1264 
1265  tswt_ini=y_swt+"-"+mo_swt+"-"+d_swt+"T"+h_swt+":"+mi_swt+":"+s_swt2.substr(0,2)+"Z";
1266  tswt_ini_file=y_swt+mo_swt+d_swt+"T"+h_swt+mi_swt+s_swt2.substr(0,2)+"Z";
1267 
1268  y_swt=std::to_string(year[ix4]);
1269  mo_swt=std::to_string(mon[ix4]);
1270  d_swt=std::to_string(day[ix4]);
1271  h_swt=std::to_string(hour[ix4]);
1272  mi_swt=std::to_string(min[ix4]);
1273  s_swt2=std::to_string(round(sec[ix4]));
1274 
1275 
1276  length = (int) floor( log10 (mon[ix4]) ) + 1;
1277  if(length==1) mo_swt="0"+mo_swt;
1278  length = (int) floor( log10 (day[ix4]) ) + 1;
1279  if(length==1) d_swt="0"+d_swt;
1280 
1281  if(hour[ix4]==0) logoff=1; else logoff=0;
1282  length = (int) floor( log10 (hour[ix4]+logoff)) + 1;
1283  if(length==1) h_swt="0"+h_swt;
1284 
1285  if(min[ix4]==0) logoff=1; else logoff=0;
1286  length = (int) floor( log10 (min[ix4]+logoff)) + 1;
1287  if(length==1) mi_swt="0"+mi_swt;
1288 
1289  if(sec[ix4]==0) logoff=1; else logoff=0;
1290  length = (int) floor( log10 (round(sec[ix4])+logoff)) + 1;
1291  if(length==1) s_swt2="0"+s_swt2;
1292 
1293  tswt_end=y_swt+"-"+mo_swt+"-"+d_swt+"T"+h_swt+":"+mi_swt+":"+s_swt2.substr(0,2)+"Z";
1294 
1295  tswt2=(double*)calloc(norbs,sizeof(double));
1296  latswt2=(double*)calloc(norbs,sizeof(double));
1297  lonswt2=(double*)calloc(norbs,sizeof(double));
1298 
1299  sum2=0,sum3=0,c=0;
1300  while(kk<=ix4){
1301  latswt2[c]=orb_lat[kk];
1302  lonswt2[c]=orb_lon[kk];
1303  tswt2[c]=orb_time[kk];
1304 
1305  if(orb_lat[kk]<=latmin){
1306  latmin=orb_lat[kk];
1307  }
1308  if(orb_lat[kk]>=latmax){
1309  latmax=orb_lat[kk];
1310  }
1311 
1312  sum2+=orb_vel[kk];
1313  sum3+=grn_vel[kk];
1314  kk++;
1315  c++;
1316  }
1317  mov2 = (sum2 /norbs);//mean velocity in m/s x 10^3
1318  mgv2 = (sum3 /norbs)*1000;//in meters/s
1319 
1320  cout<<"mov2..."<<mov2<<"mvg2..."<<mgv2<<endl;
1321 
1322  status=ect_swt(2,l1cfile,norbs,tswt2,latswt2,lonswt2,&tcross2,&loncross2);
1323  cout<<"nswath==2 ---tcross equat crossing in (s)..swath#2..."<<tcross2<<"loncross2..."<<loncross2<<endl;
1324  cout<<"latmin.."<<latmin<<"latmax..."<<latmax<<endl;
1325 
1326  if (latswt2 != nullptr)
1327  delete[](latswt2);
1328  latswt2= nullptr;
1329  if (lonswt2 != nullptr)
1330  delete[](lonswt2);
1331  lonswt2= nullptr;
1332 
1333  l1cfile->num_gridlines=4001;
1334 
1335  if(status==0){
1336  tmgv2=(double*)calloc(l1cfile->num_gridlines,sizeof(double));
1337  tmgvf2=(double*)calloc(l1cfile->num_gridlines,sizeof(double));
1338 
1339  swtime_swt2(2,l1cinput,l1cfile,norbs,tswt2,tcross2,mgv2,tmgv2);
1340  num_gridlines = l1cfile->num_gridlines;
1341 
1342 //granule processing ------------------------
1343 
1344  numgran=144;
1345  l1cfile->numgran=numgran;
1346  gd_per_gran=round(num_gridlines/10);
1347  l1cfile->gd_per_gran=gd_per_gran;
1348 
1349  cout<<"# of granules to be processed..."<<numgran<<"gd_per_gran..."<<gd_per_gran<<endl;
1350 
1351  //tini/tend swath
1352  l1cfile->tswt_ini=tswt_ini;
1353  l1cfile->tswt_end=tswt_end;
1354  l1cfile->tswt_ini_file=tswt_ini_file;
1355 
1356  if(tswt2 != nullptr)
1357  delete[](tswt2);
1358  tswt2= nullptr;
1359 
1360  //first interpolation
1361  lati=(float*)calloc(num_gridlines,sizeof(float));
1362  loni=(float*)calloc(num_gridlines,sizeof(float));
1363  lati2=(float*)calloc(num_gridlines,sizeof(float));
1364  loni2=(float*)calloc(num_gridlines,sizeof(float));
1365  az_gd = (float*)calloc(num_gridlines,sizeof(float));
1366 
1367  cout<<"number of across bins L1C grid...#.."<<l1cfile->nbinx<<endl;
1368  lat_gd = allocate2d_float(4001, l1cfile->nbinx);
1369  lon_gd = allocate2d_float(4001, l1cfile->nbinx);
1370 
1371  orb_array2* posgrid = new orb_array2[num_gridlines]();//these are doubles
1372  orb_array2* velgrid = new orb_array2[num_gridlines]();
1373  orb_array2* posgrid2 = new orb_array2[num_gridlines]();//these are doubles
1374  orb_array2* velgrid2 = new orb_array2[num_gridlines]();
1375 
1376  orb_interp2(number_orecords, num_gridlines,orb_time,posr,velr,tmgv2, posgrid,velgrid);
1377 
1378  for(int i=0;i<num_gridlines-1;i++){
1379  pos_norm=sqrt(posgrid[i][0]*posgrid[i][0]+posgrid[i][1]*posgrid[i][1]+posgrid[i][2]*posgrid[i][2]);
1380  clatg2=sqrt(posgrid[i][0]*posgrid[i][0]+posgrid[i][1]*posgrid[i][1])/pos_norm;
1381  rl2=Re*(1-fe)/(sqrt(1-(2-fe)*fe*clatg2*clatg2));
1382 
1383  v2[0]=velgrid[i][0]*rl2/pos_norm;
1384  v2[1]=velgrid[i][1]*rl2/pos_norm;
1385  v2[2]=velgrid[i][2]*rl2/pos_norm;
1386 
1387  vi=sqrt(v2[0]*v2[0]+v2[1]*v2[1]+v2[2]*v2[2])*1000;
1388  toff=vi/mgv2;
1389  tmgvf2[i]=tmgv2[i]+toff;
1390  }
1391 
1392 
1393  orb_interp2(number_orecords, num_gridlines,orb_time,posr,velr,tmgvf2, posgrid2,velgrid2);
1394 
1395  //angle subsat track----
1396  omf2=(1-fe)*(1-fe);
1397 
1398  for(int i=0;i<num_gridlines-1;i++){
1399  pos_norm=sqrt(posgrid2[i][0]*posgrid2[i][0]+posgrid2[i][1]*posgrid2[i][1]+posgrid2[i][2]*posgrid2[i][2]);
1400  clatg2=sqrt(posgrid2[i][0]*posgrid2[i][0]+posgrid2[i][1]*posgrid2[i][1])/pos_norm;
1401  rl2=Re*(1-fe)/(sqrt(1-(2-fe)*fe*clatg2*clatg2));
1402 
1403  v1[0]=(posgrid2[i][0])*rl2/pos_norm;
1404  v1[1]=(posgrid2[i][1])*rl2/pos_norm;
1405  v1[2]=(posgrid2[i][2])*rl2/pos_norm;
1406 
1407  v2[0]=(velgrid2[i][0])*rl2/pos_norm;
1408  v2[1]=(velgrid2[i][1])*rl2/pos_norm;
1409  v2[2]=(velgrid2[i][2])*rl2/pos_norm;
1410 
1411  cross_product_double(v1,v2,vecout);
1412  nvec=cross_product_norm_double(v1,v2);//length of orb norm vect
1413 
1414  orbnorm[0]=vecout[0]/nvec;
1415  orbnorm[1]=vecout[1]/nvec;
1416  orbnorm[2]=vecout[2]/nvec;
1417 
1418  for(int j=0;j<l1cfile->nbinx;j++){
1419 
1420  pos_norm=sqrt(v1[0]*v1[0]+v1[1]*v1[1]+v1[2]*v1[2]);//first gridline
1421 
1422  oangle=asin((j-(l1cfile->nbinx-1)/2)*5.2/pos_norm);
1423 
1424  //Geocentric vector
1425  G[0]=v1[0]*cos(oangle)-orbnorm[0]*pos_norm*sin(oangle);
1426  G[1]=v1[1]*cos(oangle)-orbnorm[1]*pos_norm*sin(oangle);
1427  G[2]=v1[2]*cos(oangle)-orbnorm[2]*pos_norm*sin(oangle);
1428 
1429  glon=atan2(G[1],G[0])*180/M_PI;
1430 
1431  gnorm = sqrt(G[0]*G[0]+G[1]*G[1]+G[2]*G[2]);
1432  omf2p = (omf2*rem + gnorm - rem)/gnorm;
1433  pxy = G[0]*G[0]+G[1]*G[1];
1434  temp = sqrt(G[2]*G[2] + omf2p*omf2p*pxy);
1435  glat=asin(G[2]/temp)*180/M_PI;
1436 
1437  lat_gd[i][j]=glat;
1438  lon_gd[i][j]=glon;
1439 
1440  //altitude
1441  // clatg = cos(atan(omf2*tan(glat*M_PI/180.)));
1442  // rl = re*(1.-fe)/sqrt(1.-(2.-fe)*fe*clatg*clatg);
1443  // alt = gnorm - rl;
1444  }
1445 
1446  }
1447 
1448  if (posgrid != nullptr)
1449  delete[](posgrid);
1450 
1451  if (velgrid != nullptr)
1452  delete[](velgrid);
1453 
1454  if (posgrid2 != nullptr)
1455  delete[](posgrid2);
1456 
1457  if (velgrid2 != nullptr)
1458  delete[](velgrid2);
1459 
1460  l1cfile->num_gridlines = l1cfile->num_gridlines-1;
1461  // create_SOCEA(1,l1cinput,l1cfile,lat_gd,lon_gd);//this is swath processing---------------
1462 
1463 //--------------------------------------------------------------
1464 //granule processing---------------------------------------------
1465 //---------------------------------------------------------------
1466  l1cfile->tfile_ini_sec=tfile_ini_sec;
1467 
1468  deltasec=tmgvf[num_gridlines-2]-tmgvf2[0]+1;
1469  cout<<"deltasec..swath."<<deltasec<<endl;
1470 
1471  numgran=144*2;
1472  l1cfile->numgran=numgran;
1473  gd_per_gran=round(num_gridlines/10);//10 granules per half orbit
1474  l1cfile->gd_per_gran=gd_per_gran;
1475 
1476  cout<<"estimated # of granules to be processed..."<<numgran<<"gd_per_gran..."<<gd_per_gran<<"#gridlines.."<<num_gridlines<<endl;
1477 
1478  write_L1C_granule(2,l1cfile,l1cinput,tmgvf2,lat_gd, lon_gd);
1479 //--------------------------------------------------------------------
1480 //--------------------------------------------------------------------
1481  if (lat_gd != nullptr)
1482  delete [](lat_gd);
1483  lat_gd = nullptr;
1484  if (lon_gd != nullptr)
1485  delete [](lon_gd);
1486  lon_gd = nullptr;
1487  if (az_gd != nullptr)
1488  delete [](az_gd);
1489  az_gd = nullptr;
1490 
1491  if (lati != nullptr)
1492  delete[](lati);
1493  lati= nullptr;
1494  if (loni != nullptr)
1495  delete[](loni);
1496  loni= nullptr;
1497 
1498  if (lati2 != nullptr)
1499  delete[](lati2);
1500  lati2= nullptr;
1501  if (loni2 != nullptr)
1502  delete[](loni2);
1503  loni2= nullptr;
1504  if (tmgv2 != nullptr)
1505  delete[](tmgv2);
1506  tmgv2= nullptr;
1507  if (tmgvf2 != nullptr)
1508  delete[](tmgvf2);
1509  tmgvf2= nullptr;
1510 
1511  }
1512  else{
1513  cout<<"ERROR swath #2 does not cross the equator..NO L1C grid for swath #2"<<endl;
1514  }
1515 
1516  }
1517 
1518 
1519  }//end nswath=2
1520 
1521 
1522 //-------------HALF-ORBITS IN TWO NON-CONSECUTIVE PORTIONS ------
1523 //nswath =3
1524 //swath1
1525 //-------------------------------------------------------------
1526  c=0;
1527  if(nswath==3){
1528  if(ix1>=0 && ix5>0){
1529  norbs=ix2-ix1+1;
1530  kk=ix1;
1531  latmin=orb_lat[ix1];
1532  latmax=orb_lat[ix2];
1533 
1534  //orbit direction
1535  l1cfile->orb_dir=orb_dir[ix1];
1536 
1537  //ini and end UTC--this is swath orbital time, not interpolated time
1538  y_swt=std::to_string(year[ix1]);
1539  mo_swt=std::to_string(mon[ix1]);
1540  d_swt=std::to_string(day[ix1]);
1541  h_swt=std::to_string(hour[ix1]);
1542  mi_swt=std::to_string(min[ix1]);
1543  s_swt2=std::to_string(round(sec[ix1]));
1544 
1545  length = (int) floor( log10 (mon[ix1]) ) + 1;
1546  if(length==1) mo_swt="0"+mo_swt;
1547  length = (int) floor( log10 (day[ix1]) ) + 1;
1548  if(length==1) d_swt="0"+d_swt;
1549 
1550  if(hour[ix1]==0) logoff=1; else logoff=0;
1551  length = (int) floor( log10 (hour[ix1]+logoff)) + 1;
1552  if(length==1) h_swt="0"+h_swt;
1553 
1554  if(min[ix1]==0) logoff=1; else logoff=0;
1555  length = (int) floor( log10 (min[ix1]+logoff)) + 1;
1556  if(length==1) mi_swt="0"+mi_swt;
1557 
1558  if(sec[ix1]==0) logoff=1; else logoff=0;
1559  length = (int) floor( log10 (round(sec[ix1])+logoff)) + 1;
1560  if(length==1) s_swt2="0"+s_swt2;
1561 
1562  tswt_ini=y_swt+"-"+mo_swt+"-"+d_swt+"T"+h_swt+":"+mi_swt+":"+s_swt2.substr(0,2)+"Z";
1563  tswt_ini_file=y_swt+mo_swt+d_swt+"T"+h_swt+mi_swt+s_swt2.substr(0,2)+"Z";
1564 
1565  y_swt=std::to_string(year[ix2]);
1566  mo_swt=std::to_string(mon[ix2]);
1567  d_swt=std::to_string(day[ix2]);
1568  h_swt=std::to_string(hour[ix2]);
1569  mi_swt=std::to_string(min[ix2]);
1570  s_swt2=std::to_string(round(sec[ix2]));
1571 
1572  length = (int) floor( log10 (mon[ix2]) ) + 1;
1573  if(length==1) mo_swt="0"+mo_swt;
1574  length = (int) floor( log10 (day[ix2]) ) + 1;
1575  if(length==1) d_swt="0"+d_swt;
1576 
1577  if(hour[ix2]==0) logoff=1; else logoff=0;
1578  length = (int) floor( log10 (hour[ix2]+logoff)) + 1;
1579  if(length==1) h_swt="0"+h_swt;
1580 
1581  if(min[ix2]==0) logoff=1; else logoff=0;
1582  length = (int) floor( log10 (min[ix2]+logoff)) + 1;
1583  if(length==1) mi_swt="0"+mi_swt;
1584 
1585  if(sec[ix2]==0) logoff=1; else logoff=0;
1586  length = (int) floor( log10 (round(sec[ix2])+logoff)) + 1;
1587  if(length==1) s_swt2="0"+s_swt2;
1588 
1589  tswt_end=y_swt+"-"+mo_swt+"-"+d_swt+"T"+h_swt+":"+mi_swt+":"+s_swt2.substr(0,2)+"Z";
1590 
1591  tswt=(double*)calloc(norbs,sizeof(double));
1592  latswt=(double*)calloc(norbs,sizeof(double));
1593  lonswt=(double*)calloc(norbs,sizeof(double));
1594 
1595  sum1=0,sum3=0,c=0;
1596  while(kk<=ix2){
1597  latswt[c]=orb_lat[kk];
1598  lonswt[c]=orb_lon[kk];
1599  tswt[c]=orb_time[kk];
1600  sum1+=orb_vel[kk];
1601  sum3+=grn_vel[kk];
1602  kk++;
1603  c++;
1604  }
1605  //computing mean swath velocity (m/s) --------------------------
1606  mov1 = (sum1 /norbs);//mean velocity in m/s x 10^3
1607  mgv1 = (sum3 /norbs)*1000;
1608  cout<<"mov1..."<<mov1<<"mvg1..."<<mgv1<<endl;
1609 
1610  status1=ect_swt(1,l1cfile,norbs,tswt,latswt,lonswt,&tcross1,&loncross1);
1611  cout<<"nswath==3 --tcross equat crossing in (s)..swath#1.(segment #1).."<<tcross1<<"loncross1..."<<loncross1<<endl;
1612 
1613  c=0;
1614  if(tcross1<0.){
1615 
1616  if(tswt != nullptr)
1617  delete[](tswt);
1618  tswt= nullptr;
1619  if (latswt != nullptr)
1620  delete[](latswt);
1621  latswt= nullptr;
1622  if (lonswt != nullptr)
1623  delete[](lonswt);
1624  lonswt= nullptr;
1625 
1626  norbs=ix4-ix3+1;
1627 
1628  tswt=(double*)calloc(norbs,sizeof(double));
1629  latswt=(double*)calloc(norbs,sizeof(double));
1630  lonswt=(double*)calloc(norbs,sizeof(double));
1631 
1632  kk=ix3;
1633  sum1=0.;
1634  tcross1=-999,loncross1=-999.;
1635 
1636  l1cfile->orb_dir=orb_dir[ix3];
1637 
1638  //ini and end UTC--this is swath orbital time, not interpolated time
1639  y_swt=std::to_string(year[ix3]);
1640  mo_swt=std::to_string(mon[ix3]);
1641  d_swt=std::to_string(day[ix3]);
1642  h_swt=std::to_string(hour[ix3]);
1643  mi_swt=std::to_string(min[ix3]);
1644  s_swt2=std::to_string(round(sec[ix3]));
1645 
1646  length = (int) floor( log10 (mon[ix3]) ) + 1;
1647  if(length==1) mo_swt="0"+mo_swt;
1648  length = (int) floor( log10 (day[ix3]) ) + 1;
1649  if(length==1) d_swt="0"+d_swt;
1650 
1651  if(hour[ix3]==0) logoff=1; else logoff=0;
1652  length = (int) floor( log10 (hour[ix3]+logoff)) + 1;
1653  if(length==1) h_swt="0"+h_swt;
1654 
1655  if(min[ix3]==0) logoff=1; else logoff=0;
1656  length = (int) floor( log10 (min[ix3]+logoff)) + 1;
1657  if(length==1) mi_swt="0"+mi_swt;
1658 
1659  if(sec[ix3]==0) logoff=1; else logoff=0;
1660  length = (int) floor( log10 (round(sec[ix3])+logoff)) + 1;
1661  if(length==1) s_swt2="0"+s_swt2;
1662 
1663  tswt_ini=y_swt+"-"+mo_swt+"-"+d_swt+"T"+h_swt+":"+mi_swt+":"+s_swt2+"Z";
1664  tswt_ini_file=y_swt+mo_swt+d_swt+"T"+h_swt+mi_swt+s_swt2.substr(0,2)+"Z";
1665 
1666  y_swt=std::to_string(year[ix4]);
1667  mo_swt=std::to_string(mon[ix4]);
1668  d_swt=std::to_string(day[ix4]);
1669  h_swt=std::to_string(hour[ix4]);
1670  mi_swt=std::to_string(min[ix4]);
1671  s_swt2=std::to_string(round(sec[ix4]));
1672 
1673 
1674  length = (int) floor( log10 (mon[ix4]) ) + 1;
1675  if(length==1) mo_swt="0"+mo_swt;
1676  length = (int) floor( log10 (day[ix4]) ) + 1;
1677  if(length==1) d_swt="0"+d_swt;
1678 
1679  if(hour[ix4]==0) logoff=1; else logoff=0;
1680  length = (int) floor( log10 (hour[ix4]+logoff)) + 1;
1681  if(length==1) h_swt="0"+h_swt;
1682 
1683  if(min[ix4]==0) logoff=1; else logoff=0;
1684  length = (int) floor( log10 (min[ix4]+logoff)) + 1;
1685  if(length==1) mi_swt="0"+mi_swt;
1686 
1687  if(sec[ix4]==0) logoff=1; else logoff=0;
1688  length = (int) floor( log10 (round(sec[ix4])+logoff)) + 1;
1689  if(length==1) s_swt2="0"+s_swt2;
1690 
1691  tswt_end=y_swt+"-"+mo_swt+"-"+d_swt+"T"+h_swt+":"+mi_swt+":"+s_swt2+"Z";
1692 
1693 
1694  sum1=0,sum3=0,c=0;
1695  while(kk<=ix4){
1696  latswt[c]=orb_lat[kk];
1697  lonswt[c]=orb_lon[kk];
1698  tswt[c]=orb_time[kk];
1699  sum1+=orb_vel[kk];
1700  sum3+=grn_vel[kk];
1701  kk++;
1702  c++;
1703  }
1704  //computing mean swath velocity (m/s) --------------------------
1705  mov1 = (sum1 /norbs);//mean velocity in m/s x 10^3
1706  mgv1 = (sum3 /norbs)*1000;
1707  cout<<"mov1..."<<mov1<<"mvg1..."<<mgv1<<endl;
1708 
1709  status2=ect_swt(1,l1cfile,norbs,tswt,latswt,lonswt,&tcross1,&loncross1);
1710  cout<<"nswath==3 --tcross equat crossing in (s)..swath#1.(segment #2).."<<tcross1<<"loncross1..."<<loncross1<<endl;
1711  }
1712 
1713  l1cfile->num_gridlines=4001;
1714 
1715  if(status1==0 || status2==0){
1716  tmgv1=(double*)calloc(l1cfile->num_gridlines,sizeof(double));
1717  tmgvf=(double*)calloc(l1cfile->num_gridlines,sizeof(double));
1718 
1719  cout<<"#gridlines..."<<l1cfile->num_gridlines<<"norbs.."<<norbs<<endl;
1720 
1721  swtime_swt2(1,l1cinput,l1cfile,norbs,tswt,tcross1,mgv1,tmgv1);
1722 
1723  num_gridlines = l1cfile->num_gridlines;
1724 
1725  //tini/tend for each swath
1726  l1cfile->tswt_ini=tswt_ini;
1727  l1cfile->tswt_end=tswt_end;
1728  l1cfile->tswt_ini_file=tswt_ini_file;
1729 
1730  if(tswt != nullptr)
1731  delete[](tswt);
1732  tswt= nullptr;
1733  if (latswt != nullptr)
1734  delete[](latswt);
1735  latswt= nullptr;
1736  if (lonswt != nullptr)
1737  delete[](lonswt);
1738  lonswt= nullptr;
1739 
1740  //first interpolation
1741  lati=(float*)calloc(num_gridlines,sizeof(float));
1742  loni=(float*)calloc(num_gridlines,sizeof(float));
1743  lati2=(float*)calloc(num_gridlines,sizeof(float));
1744  loni2=(float*)calloc(num_gridlines,sizeof(float));
1745  az_gd = (float*)calloc(num_gridlines,sizeof(float));
1746 
1747  cout<<"number of across bins L1C grid...#.."<<l1cfile->nbinx<<endl;
1748  lat_gd = allocate2d_float(4001, l1cfile->nbinx);
1749  lon_gd = allocate2d_float(4001, l1cfile->nbinx);
1750 
1751  orb_array2* posgrid = new orb_array2[num_gridlines]();//these are doubles
1752  orb_array2* velgrid = new orb_array2[num_gridlines]();
1753 
1754  orb_array2* posgrid2 = new orb_array2[num_gridlines]();//these are doubles
1755  orb_array2* velgrid2 = new orb_array2[num_gridlines]();
1756 
1757 
1758 //interp 1-- always based on orbitals---
1759  //interpola pos/veloc as a function of time
1760  orb_interp2(number_orecords, num_gridlines,orb_time,posr,velr,tmgv1, posgrid,velgrid);
1761 
1762  for(int i=0;i<num_gridlines-1;i++){
1763  pos_norm=sqrt(posgrid[i][0]*posgrid[i][0]+posgrid[i][1]*posgrid[i][1]+posgrid[i][2]*posgrid[i][2]);
1764  clatg2=sqrt(posgrid[i][0]*posgrid[i][0]+posgrid[i][1]*posgrid[i][1])/pos_norm;
1765  rl2=Re*(1-fe)/(sqrt(1-(2-fe)*fe*clatg2*clatg2));
1766 
1767  v2[0]=velgrid[i][0]*rl2/pos_norm;
1768  v2[1]=velgrid[i][1]*rl2/pos_norm;
1769  v2[2]=velgrid[i][2]*rl2/pos_norm;
1770 
1771  vi=sqrt(v2[0]*v2[0]+v2[1]*v2[1]+v2[2]*v2[2])*1000;
1772  toff=vi/mgv1;
1773  tmgvf[i]=tmgv1[i]+toff;
1774  }
1775 
1776  l1cfile->tfile_ini_sec=tfile_ini_sec;
1777 
1778  deltasec=tmgvf[num_gridlines-2]-tmgvf[0]+1;
1779  cout<<"deltasec..swath."<<deltasec<<endl;
1780 
1781  orb_interp2(number_orecords, num_gridlines,orb_time,posr,velr,tmgvf, posgrid2,velgrid2);
1782 
1783  //angle subsat track----
1784  omf2=(1-fe)*(1-fe);
1785 
1786  for(int i=0;i<num_gridlines-1;i++){
1787  pos_norm=sqrt(posgrid2[i][0]*posgrid2[i][0]+posgrid2[i][1]*posgrid2[i][1]+posgrid2[i][2]*posgrid2[i][2]);
1788  clatg2=sqrt(posgrid2[i][0]*posgrid2[i][0]+posgrid2[i][1]*posgrid2[i][1])/pos_norm;
1789  rl2=Re*(1-fe)/(sqrt(1-(2-fe)*fe*clatg2*clatg2));
1790 
1791  v1[0]=(posgrid2[i][0])*rl2/pos_norm;
1792  v1[1]=(posgrid2[i][1])*rl2/pos_norm;
1793  v1[2]=(posgrid2[i][2])*rl2/pos_norm;
1794 
1795  v2[0]=(velgrid2[i][0])*rl2/pos_norm;
1796  v2[1]=(velgrid2[i][1])*rl2/pos_norm;
1797  v2[2]=(velgrid2[i][2])*rl2/pos_norm;
1798 
1799  cross_product_double(v1,v2,vecout);
1800  nvec=cross_product_norm_double(v1,v2);//length of orb norm vect
1801 
1802  orbnorm[0]=vecout[0]/nvec;
1803  orbnorm[1]=vecout[1]/nvec;
1804  orbnorm[2]=vecout[2]/nvec;
1805 
1806  for(int j=0;j<l1cfile->nbinx;j++){
1807 
1808  pos_norm=sqrt(v1[0]*v1[0]+v1[1]*v1[1]+v1[2]*v1[2]);//first gridline
1809 
1810  oangle=asin((j-(l1cfile->nbinx-1)/2)*5.2/pos_norm);
1811 
1812  //Geocentric vector
1813  G[0]=v1[0]*cos(oangle)-orbnorm[0]*pos_norm*sin(oangle);
1814  G[1]=v1[1]*cos(oangle)-orbnorm[1]*pos_norm*sin(oangle);
1815  G[2]=v1[2]*cos(oangle)-orbnorm[2]*pos_norm*sin(oangle);
1816 
1817  glon=atan2(G[1],G[0])*180/M_PI;
1818 
1819  gnorm = sqrt(G[0]*G[0]+G[1]*G[1]+G[2]*G[2]);
1820  omf2p = (omf2*rem + gnorm - rem)/gnorm;
1821  pxy = G[0]*G[0]+G[1]*G[1];
1822  temp = sqrt(G[2]*G[2] + omf2p*omf2p*pxy);
1823  glat=asin(G[2]/temp)*180/M_PI;
1824 
1825  lat_gd[i][j]=glat;
1826  lon_gd[i][j]=glon;
1827 
1828  //altitude
1829  // clatg = cos(atan(omf2*tan(glat*M_PI/180.)));
1830  // rl = re*(1.-fe)/sqrt(1.-(2.-fe)*fe*clatg*clatg);
1831  // alt = gnorm - rl;
1832  }
1833  }
1834 
1835  if (posgrid != nullptr)
1836  delete[](posgrid);
1837 
1838  if (velgrid != nullptr)
1839  delete[](velgrid);
1840 
1841  if (posgrid2 != nullptr)
1842  delete[](posgrid2);
1843 
1844  if (velgrid2 != nullptr)
1845  delete[](velgrid2);
1846 
1847  l1cfile->num_gridlines = l1cfile->num_gridlines-1;
1848  // create_SOCEA(1,l1cinput,l1cfile,lat_gd,lon_gd);//SWATH PROCESSING
1849 
1850 //--------------------------------------------------------------
1851 //granule processing---------------------------------------------
1852 //---------------------------------------------------------------
1853  numgran=144*2;
1854  l1cfile->numgran=numgran;
1855  gd_per_gran=round(num_gridlines/10);
1856  l1cfile->gd_per_gran=gd_per_gran;
1857 
1858  cout<<"estimated # of granules to be processed..."<<numgran<<"gd_per_gran..."<<gd_per_gran<<"#gridlines.."<<num_gridlines<<endl;
1859 
1860 // write_L1C_granule(1,l1cfile,l1cinput,tmgvf,lat_gd, lon_gd);
1861 
1862 
1863 
1864 //-----------------------------------------------------------------
1865 //-----------------------------------------------------------------
1866 
1867  if (lat_gd != nullptr)
1868  delete [](lat_gd);
1869  lat_gd = nullptr;
1870  if (lon_gd != nullptr)
1871  delete [](lon_gd);
1872  lon_gd = nullptr;
1873  if (az_gd != nullptr)
1874  delete [](az_gd);
1875  az_gd = nullptr;
1876 
1877  if (lati != nullptr)
1878  delete[](lati);
1879  lati= nullptr;
1880  if (loni != nullptr)
1881  delete[](loni);
1882  loni= nullptr;
1883 
1884  if (lati2 != nullptr)
1885  delete[](lati2);
1886  lati2= nullptr;
1887  if (loni2 != nullptr)
1888  delete[](loni2);
1889  loni2= nullptr;
1890 
1891  if (tmgv1 != nullptr)
1892  delete[](tmgv1);
1893  tmgv1= nullptr;
1894  if (tmgvf != nullptr)
1895  delete[](tmgvf);
1896  tmgvf= nullptr;
1897 
1898  }//end tcross
1899  } //end 2 segments swath 1
1900 
1901  else{
1902  cout<<"ERROR swath #1 does not cross the equator..."<<endl;
1903  cout<<"checking swath #2..."<<endl;
1904  }
1905 
1906 
1907  //exit(1);
1908 
1909 
1910 //-----------------------------------------------------------------------------------
1911 //nswath =3
1912 //swath 2
1913 //----------------------------------------------------------------------------------
1914  kk=ix5;
1915  c=0;
1916  norbs=ix6-ix5+1;
1917  latmin=orb_lat[ix5];
1918  latmax=orb_lat[ix5];
1919 
1920  //orbit direction
1921  l1cfile->orb_dir=orb_dir[ix5];
1922 
1923  //ini and end UTC--this is swath orbital time, not interpolated time
1924  y_swt=std::to_string(year[ix5]);
1925  mo_swt=std::to_string(mon[ix5]);
1926  d_swt=std::to_string(day[ix5]);
1927  h_swt=std::to_string(hour[ix5]);
1928  mi_swt=std::to_string(min[ix5]);
1929  s_swt2=std::to_string(round(sec[ix5]));
1930 
1931  length = (int) floor( log10 (mon[ix5]) ) + 1;
1932  if(length==1) mo_swt="0"+mo_swt;
1933  length = (int) floor( log10 (day[ix5]) ) + 1;
1934  if(length==1) d_swt="0"+d_swt;
1935 
1936 
1937  if(hour[ix5]==0) logoff=1; else logoff=0;
1938  length = (int) floor( log10 (hour[ix5]+logoff)) + 1;
1939  if(length==1) h_swt="0"+h_swt;
1940 
1941  if(min[ix5]==0) logoff=1; else logoff=0;
1942  length = (int) floor( log10 (min[ix5]+logoff)) + 1;
1943  if(length==1) mi_swt="0"+mi_swt;
1944 
1945  if(sec[ix5]==0) logoff=1; else logoff=0;
1946  length = (int) floor( log10 (round(sec[ix5])+logoff)) + 1;
1947  if(length==1) s_swt2="0"+s_swt2;
1948 
1949  tswt_ini=y_swt+"-"+mo_swt+"-"+d_swt+"T"+h_swt+":"+mi_swt+":"+s_swt2.substr(0,2)+"Z";
1950  tswt_ini_file=y_swt+mo_swt+d_swt+"T"+h_swt+mi_swt+s_swt2.substr(0,2)+"Z";
1951 
1952  y_swt=std::to_string(year[ix6]);
1953  mo_swt=std::to_string(mon[ix6]);
1954  d_swt=std::to_string(day[ix6]);
1955  h_swt=std::to_string(hour[ix6]);
1956  mi_swt=std::to_string(min[ix6]);
1957  s_swt2=std::to_string(round(sec[ix6]));
1958 
1959  length = (int) floor( log10 (mon[ix6]) ) + 1;
1960  if(length==1) mo_swt="0"+mo_swt;
1961  length = (int) floor( log10 (day[ix6]) ) + 1;
1962  if(length==1) d_swt="0"+d_swt;
1963 
1964  if(hour[ix6]==0) logoff=1; else logoff=0;
1965  length = (int) floor( log10 (hour[ix6]+logoff)) + 1;
1966  if(length==1) h_swt="0"+h_swt;
1967 
1968  if(min[ix6]==0) logoff=1; else logoff=0;
1969  length = (int) floor( log10 (min[ix6]+logoff)) + 1;
1970  if(length==1) mi_swt="0"+mi_swt;
1971 
1972  if(sec[ix6]==0) logoff=1; else logoff=0;
1973  length = (int) floor( log10 (round(sec[ix6])+logoff)) + 1;
1974  if(length==1) s_swt2="0"+s_swt2;
1975 
1976  tswt_end=y_swt+"-"+mo_swt+"-"+d_swt+"T"+h_swt+":"+mi_swt+":"+s_swt2.substr(0,2)+"Z";
1977 
1978  tswt2=(double*)calloc(norbs,sizeof(double));
1979  latswt2=(double*)calloc(norbs,sizeof(double));
1980  lonswt2=(double*)calloc(norbs,sizeof(double));
1981 
1982  sum2=0,sum3=0,c=0;
1983  while(kk<=ix6){
1984  latswt2[c]=orb_lat[kk];
1985  lonswt2[c]=orb_lon[kk];
1986  tswt2[c]=orb_time[kk];
1987 
1988  if(orb_lat[kk]<=latmin){
1989  latmin=orb_lat[kk];
1990  }
1991  if(orb_lat[kk]>=latmax){
1992  latmax=orb_lat[kk];
1993  }
1994 
1995  sum2+=orb_vel[kk];
1996  sum3+=grn_vel[kk];
1997  kk++;
1998  c++;
1999  }
2000  mov2 = (sum2 /norbs);//mean velocity in m/s x 10^3
2001  mgv2 = (sum3 /norbs)*1000;//in meters/s
2002 
2003  cout<<"mov2..."<<mov2<<"mvg2..."<<mgv2<<endl;
2004 
2005  status=ect_swt(2,l1cfile,norbs,tswt2,latswt2,lonswt2,&tcross2,&loncross2);
2006  cout<<"nswath==2 ---tcross equat crossing in (s)..swath#2..."<<tcross2<<"loncross2..."<<loncross2<<endl;
2007  cout<<"latmin.."<<latmin<<"latmax..."<<latmax<<endl;
2008 
2009  if (latswt2 != nullptr)
2010  delete[](latswt2);
2011  latswt2= nullptr;
2012  if (lonswt2 != nullptr)
2013  delete[](lonswt2);
2014  lonswt2= nullptr;
2015 
2016  l1cfile->num_gridlines=4001;
2017 
2018  if(status==0){
2019  tmgv2=(double*)calloc(l1cfile->num_gridlines,sizeof(double));
2020  tmgvf2=(double*)calloc(l1cfile->num_gridlines,sizeof(double));
2021 
2022  swtime_swt2(2,l1cinput,l1cfile,norbs,tswt2,tcross2,mgv2,tmgv2);
2023 
2024  num_gridlines = l1cfile->num_gridlines;
2025 
2026  //tini/tend swath
2027  l1cfile->tswt_ini=tswt_ini;
2028  l1cfile->tswt_end=tswt_end;
2029  l1cfile->tswt_ini_file=tswt_ini_file;
2030 
2031  if(tswt2 != nullptr)
2032  delete[](tswt2);
2033  tswt2= nullptr;
2034 
2035  //first interpolation
2036  lati=(float*)calloc(num_gridlines,sizeof(float));
2037  loni=(float*)calloc(num_gridlines,sizeof(float));
2038  lati2=(float*)calloc(num_gridlines,sizeof(float));
2039  loni2=(float*)calloc(num_gridlines,sizeof(float));
2040  az_gd = (float*)calloc(num_gridlines,sizeof(float));
2041 
2042  cout<<"number of across bins L1C grid...#.."<<l1cfile->nbinx<<endl;
2043  lat_gd = allocate2d_float(4001, l1cfile->nbinx);
2044  lon_gd = allocate2d_float(4001, l1cfile->nbinx);
2045 
2046  orb_array2* posgrid = new orb_array2[num_gridlines]();//these are doubles
2047  orb_array2* velgrid = new orb_array2[num_gridlines]();
2048  orb_array2* posgrid2 = new orb_array2[num_gridlines]();//these are doubles
2049  orb_array2* velgrid2 = new orb_array2[num_gridlines]();
2050 
2051  orb_interp2(number_orecords, num_gridlines,orb_time,posr,velr,tmgv2, posgrid,velgrid);
2052 
2053  for(int i=0;i<num_gridlines-1;i++){
2054  pos_norm=sqrt(posgrid[i][0]*posgrid[i][0]+posgrid[i][1]*posgrid[i][1]+posgrid[i][2]*posgrid[i][2]);
2055  clatg2=sqrt(posgrid[i][0]*posgrid[i][0]+posgrid[i][1]*posgrid[i][1])/pos_norm;
2056  rl2=Re*(1-fe)/(sqrt(1-(2-fe)*fe*clatg2*clatg2));
2057 
2058  v2[0]=velgrid[i][0]*rl2/pos_norm;
2059  v2[1]=velgrid[i][1]*rl2/pos_norm;
2060  v2[2]=velgrid[i][2]*rl2/pos_norm;
2061 
2062  vi=sqrt(v2[0]*v2[0]+v2[1]*v2[1]+v2[2]*v2[2])*1000;
2063  toff=vi/mgv2;
2064  tmgvf2[i]=tmgv2[i]+toff;
2065  }
2066 
2067  orb_interp2(number_orecords, num_gridlines,orb_time,posr,velr,tmgvf2, posgrid2,velgrid2);
2068 
2069  //angle subsat track----
2070  omf2=(1-fe)*(1-fe);
2071 
2072  for(int i=0;i<num_gridlines-1;i++){
2073  pos_norm=sqrt(posgrid2[i][0]*posgrid2[i][0]+posgrid2[i][1]*posgrid2[i][1]+posgrid2[i][2]*posgrid2[i][2]);
2074  clatg2=sqrt(posgrid2[i][0]*posgrid2[i][0]+posgrid2[i][1]*posgrid2[i][1])/pos_norm;
2075  rl2=Re*(1-fe)/(sqrt(1-(2-fe)*fe*clatg2*clatg2));
2076 
2077  v1[0]=(posgrid2[i][0])*rl2/pos_norm;
2078  v1[1]=(posgrid2[i][1])*rl2/pos_norm;
2079  v1[2]=(posgrid2[i][2])*rl2/pos_norm;
2080 
2081  v2[0]=(velgrid2[i][0])*rl2/pos_norm;
2082  v2[1]=(velgrid2[i][1])*rl2/pos_norm;
2083  v2[2]=(velgrid2[i][2])*rl2/pos_norm;
2084 
2085  cross_product_double(v1,v2,vecout);
2086  nvec=cross_product_norm_double(v1,v2);//length of orb norm vect
2087 
2088  orbnorm[0]=vecout[0]/nvec;
2089  orbnorm[1]=vecout[1]/nvec;
2090  orbnorm[2]=vecout[2]/nvec;
2091 
2092  for(int j=0;j<l1cfile->nbinx;j++){
2093 
2094  pos_norm=sqrt(v1[0]*v1[0]+v1[1]*v1[1]+v1[2]*v1[2]);//first gridline
2095 
2096  oangle=asin((j-(l1cfile->nbinx-1)/2)*5.2/pos_norm);
2097 
2098  //Geocentric vector
2099  G[0]=v1[0]*cos(oangle)-orbnorm[0]*pos_norm*sin(oangle);
2100  G[1]=v1[1]*cos(oangle)-orbnorm[1]*pos_norm*sin(oangle);
2101  G[2]=v1[2]*cos(oangle)-orbnorm[2]*pos_norm*sin(oangle);
2102 
2103  glon=atan2(G[1],G[0])*180/M_PI;
2104 
2105  gnorm = sqrt(G[0]*G[0]+G[1]*G[1]+G[2]*G[2]);
2106  omf2p = (omf2*rem + gnorm - rem)/gnorm;
2107  pxy = G[0]*G[0]+G[1]*G[1];
2108  temp = sqrt(G[2]*G[2] + omf2p*omf2p*pxy);
2109  glat=asin(G[2]/temp)*180/M_PI;
2110 
2111  lat_gd[i][j]=glat;
2112  lon_gd[i][j]=glon;
2113 
2114  //altitude
2115  // clatg = cos(atan(omf2*tan(glat*M_PI/180.)));
2116  // rl = re*(1.-fe)/sqrt(1.-(2.-fe)*fe*clatg*clatg);
2117  // alt = gnorm - rl;
2118  }
2119  }
2120 
2121  if (posgrid != nullptr)
2122  delete[](posgrid);
2123 
2124  if (velgrid != nullptr)
2125  delete[](velgrid);
2126 
2127  if (posgrid2 != nullptr)
2128  delete[](posgrid2);
2129 
2130  if (velgrid2 != nullptr)
2131  delete[](velgrid2);
2132 
2133  l1cfile->num_gridlines = l1cfile->num_gridlines-1;
2134  // create_SOCEA(1,l1cinput,l1cfile,lat_gd,lon_gd);//SWATH PROCESSING
2135 
2136  //--------------------------------------------------------------
2137 //granule processing---------------------------------------------
2138 //---------------------------------------------------------------
2139  l1cfile->tfile_ini_sec=tfile_ini_sec;
2140 
2141  deltasec=tmgvf2[num_gridlines-2]-tmgvf2[0]+1;
2142  cout<<"deltasec..swath."<<deltasec<<endl;
2143 
2144  numgran=144*2;
2145 
2146  l1cfile->numgran=numgran;
2147  gd_per_gran=round(num_gridlines/10);//10 granules per half orbit
2148  l1cfile->gd_per_gran=gd_per_gran;
2149 
2150  cout<<"estimated # of granules to be processed..."<<numgran<<"gd_per_gran..."<<gd_per_gran<<"#gridlines.."<<num_gridlines<<endl;
2151 
2152  write_L1C_granule(2,l1cfile,l1cinput,tmgvf2,lat_gd, lon_gd);
2153 
2154 //---------------------------------------------------------------
2155 //---------------------------------------------------------------
2156  if (lat_gd != nullptr)
2157  delete [](lat_gd);
2158  lat_gd = nullptr;
2159  if (lon_gd != nullptr)
2160  delete [](lon_gd);
2161  lon_gd = nullptr;
2162  if (az_gd != nullptr)
2163  delete [](az_gd);
2164  az_gd = nullptr;
2165 
2166  if (lati != nullptr)
2167  delete[](lati);
2168  lati= nullptr;
2169  if (loni != nullptr)
2170  delete[](loni);
2171  loni= nullptr;
2172 
2173  if (lati2 != nullptr)
2174  delete[](lati2);
2175  lati2= nullptr;
2176  if (loni2 != nullptr)
2177  delete[](loni2);
2178  loni2= nullptr;
2179  if (tmgv2 != nullptr)
2180  delete[](tmgv2);
2181  tmgv2= nullptr;
2182  if (tmgvf2 != nullptr)
2183  delete[](tmgvf2);
2184  tmgvf2= nullptr;
2185 
2186  }
2187  else {
2188  cout<<"ERROR swath #2 does not cross the equator..NO L1C grid for swath #2"<<endl;
2189  }
2190 
2191  }//end nswath =3
2192 
2193  ix.clear();
2194 
2195  if (tai58_sec != nullptr)
2196  delete[](tai58_sec);
2197  tai58_sec= nullptr;
2198 
2199  if (sec != nullptr)
2200  delete[](sec);
2201  sec= nullptr;
2202 
2203  if (year != nullptr)
2204  delete[](year);
2205  year= nullptr;
2206 
2207  if (mon != nullptr)
2208  delete[](mon);
2209  mon= nullptr;
2210 
2211  if (day != nullptr)
2212  delete[](day);
2213  day= nullptr;
2214 
2215  if (hour != nullptr)
2216  delete[](hour);
2217  hour= nullptr;
2218 
2219  if (min != nullptr)
2220  delete[](min);
2221  min= nullptr;
2222 
2223  if (orb_lat != nullptr)
2224  delete[](orb_lat);
2225  orb_lat= nullptr;
2226 
2227  if (orb_lon != nullptr)
2228  delete[](orb_lon);
2229  orb_lon= nullptr;
2230 
2231  if (orb_time != nullptr)
2232  delete[](orb_time);
2233  orb_time= nullptr;
2234 
2235  if (orb_vel != nullptr)
2236  delete[](orb_vel);
2237  orb_vel= nullptr;
2238 
2239  if (grn_vel != nullptr)
2240  delete[](grn_vel);
2241  grn_vel= nullptr;
2242 
2243  if (orb_dir != nullptr)
2244  delete[](orb_dir);
2245  orb_dir= nullptr;
2246 
2247  if (posr != nullptr)
2248  delete[](posr);
2249  posr= nullptr;
2250 
2251  if (velr != nullptr)
2252  delete[](velr);
2253  velr= nullptr;
2254 
2255  if ((status = nc_close(ncid_L1A)))
2256  check_err(status, __LINE__, __FILE__);
2257 
2258  return 0;
2259  }
2260 
2261 
2262 
2263 
2264 
2265 
2266 
2267  int32_t L1C::open_l2tol1c(l1c_filehandle *l1cfile, L1C_input *l1cinput){
2268  int32_t n_files;
2269  const char* ptstr;
2270  int status,nl2prod,dimid;
2271  string str;
2272  float **latpix=nullptr, **lonpix=nullptr,**l2pix=nullptr;
2273  float slope=0,offset=0;
2274 
2275  // cout<<"checking l2 product..index must be between 0 and 345."<<CAT_chl_xx"<<endl;
2276 
2277  // If l3bprod="ALL", replace with product list from first file
2278  /* if (boost::iequals(input.l3bprod, "ALL")) {
2279  vector<string> l2prods(l2_str[0].prodname, l2_str[0].prodname+l2_str[0].nprod);
2280  string joined = boost::algorithm::join(l2prods, ":");
2281  strcpy(input.l3bprod, joined.c_str());
2282 
2283  // fix l3bprod entry in Input Parameters attribute
2284  string parms = input.parms;
2285  boost::ireplace_all(parms, "l3bprod = ALL", "l3bprod = " + joined);
2286  strcpy(input.parms, parms.c_str());
2287  }
2288 */
2289  // Parse L3 Product list
2290  n_files = l1cfile->ifiles.size();
2291 
2292  string delim1 = ":, "; // product delimiters
2293  string l2prod = l1cinput->l2prod;
2294  boost::trim_if(l2prod, boost::is_any_of(delim1));
2295  vector<string> prodparam;
2296  boost::algorithm::split(prodparam, l2prod,
2297  boost::is_any_of(delim1));
2298  cout<<"number of L2 products to be processed...................#:..."<<prodparam.size()<<endl;
2299  for(size_t iprod=0;iprod<prodparam.size();iprod++){
2300  cout<<"selected L2 ----------- prodparam...."<<prodparam[iprod]<<endl;
2301  }
2302 
2303  nl2prod=prodparam.size();//number of selected l2 products
2304  int prodims[nl2prod];
2305 
2306 
2307  //opening datafile for binning-----
2308  for (int i = 0;i < n_files;i++) {
2309  str = l1cfile->ifiles[i];
2310  ptstr = str.c_str();
2311  cout<<"Opening L2 file ..."<<ptstr<<"for SDS binning......."<<endl;
2312 
2313  // Open the netcdf4 input file
2314  status = nc_open(ptstr, NC_NOWRITE, &ncid_L2);
2315  if (status != NC_NOERR) {
2316  fprintf(stderr, "-E- Error failed nc_open.\n");
2317  exit(EXIT_FAILURE);
2318  }
2319 
2320  //dimensions
2321  //num_scans num_pixels
2322  status = nc_inq_dimid(ncid_L2, "number_of_lines", &dimid);
2323  check_err(status, __LINE__, __FILE__);
2324  nc_inq_dimlen(ncid_L2, dimid, &num_scans);
2325  status = nc_inq_dimid(ncid_L2, "pixels_per_line", &dimid);
2326  check_err(status, __LINE__, __FILE__);
2327  nc_inq_dimlen(ncid_L2, dimid, &num_pixels);
2328 
2329  cout<<"num_scans..."<<num_scans<<"num_pixels...."<<num_pixels<<endl;
2330  l1cfile->nscan=num_scans;
2331  l1cfile->npix=num_pixels;
2332 
2333 
2334  //open groups and variables
2335  status = nc_inq_grp_ncid(ncid_L2, "navigation_data", &geoGrp);
2336  check_err(status, __LINE__, __FILE__);
2337  status = nc_inq_varid(geoGrp, "latitude", &latId);
2338  check_err(status, __LINE__, __FILE__);
2339  status = nc_inq_varid(geoGrp, "longitude", &lonId);
2340  check_err(status, __LINE__, __FILE__);
2341  status = nc_inq_grp_ncid(ncid_L2, "geophysical_data", &obsGrp);
2342  check_err(status, __LINE__, __FILE__);
2343 
2344  for (int iprod = 0;iprod <nl2prod;iprod++) {
2345  cout<<"getting sds id for product.."<<prodparam[iprod].c_str()<<endl;
2346  status = nc_inq_varid(obsGrp, prodparam[iprod].c_str(), &prodims[iprod]);
2347  check_err(status, __LINE__, __FILE__);
2348  }
2349 
2350  //allocating mem
2351  latpix = allocate2d_float(num_scans, num_pixels);
2352  lonpix = allocate2d_float(num_scans, num_pixels);
2353  l2pix = allocate2d_float(num_scans, num_pixels);
2354  //opening variables
2355  status = nc_get_var_float(geoGrp, latId, &latpix[0][0]);
2356  check_err(status, __LINE__, __FILE__);
2357  status = nc_get_var_float(geoGrp, lonId, &lonpix[0][0]);
2358  check_err(status, __LINE__, __FILE__);
2359  status = nc_get_var_float(obsGrp, prodims[0], &l2pix[0][0]);
2360  check_err(status, __LINE__, __FILE__);
2361 
2362  string ATT_NAME1="scale_factor",ATT_NAME2="add_offset";
2363 
2364  if (nc_get_att_float(obsGrp, prodims[0], ATT_NAME1.c_str(), &slope))
2365  check_err(status, __LINE__, __FILE__);
2366  if (nc_get_att_float(obsGrp, prodims[0], ATT_NAME2.c_str() , &offset))
2367  check_err(status, __LINE__, __FILE__);
2368 
2369  if ((status = nc_close(ncid_L2)))
2370  check_err(status, __LINE__, __FILE__);
2371 
2372  delete [](latpix);
2373  delete [](lonpix);
2374  delete [](l2pix);
2375  }
2376 
2377  // expand 3D products
2378  // string delim2 = ";="; // minval delimiters
2379  // string wave_string=std::string{","} + std::string{input.output_wavelengths} + ",";
2380 
2381  return 0;
2382 
2383  }
2384 
2385 
2386 
2387  //write mean Lt as nc file---
2388  int32_t L1C::savebinL1C_v2(int swtd, L1C_input* l1cinput, l1c_filehandle* l1cfile, float** lat_gd, float** lon_gd, float** Ltfracsum, float** areafracsum, float** nobs_perbin) {
2389 
2390  int32_t NY = -1, NX = -1, NY1 = -1, NY2 = -1, num_gridlines, nbinx;//create Lt file
2391  int16_t selyear = -1, selmon = -1, selday = -1;
2392  float** lat_out, ** lon_out;
2393  int status, ncid, x_dimid, y_dimid, varid, varid2, varid3, varid4, NDIMS;
2394  float** data_out, ** data_out2;
2395 
2396  int dimids[2];
2397  const char* filename_lt;
2398 
2399  nbinx = l1cfile->nbinx;
2400  num_gridlines = l1cfile->num_gridlines;
2401 
2402  selday = l1cinput->selday;
2403  selmon = l1cinput->selmon;
2404  selyear = l1cinput->selyear;
2405 
2406  std::string fname_out, pathstr, senstr, monstr, daystr, yearstr, prodstr, gdstr, swtstr, swtnum, extstr, granstr,ofilestr;
2407 
2408  pathstr = "out/";
2409  senstr = "OCIS_";
2410  monstr = std::to_string(selmon);
2411  daystr = std::to_string(selday);
2412  yearstr = std::to_string(selyear);
2413  prodstr = "binLt_blue1_AW";//area-weighted binned
2414  swtstr = "_swt";
2415  granstr = "";
2416  swtnum = std::to_string(swtd);
2417  extstr = ".nc";
2418  NDIMS = 2;
2419 // fname_out = pathstr + senstr + monstr + daystr + yearstr + prodstr + swtstr + swtnum + granstr + extstr;
2420  ofilestr=std::string(l1cinput->ofile);
2421  fname_out = pathstr + ofilestr+"_"+ prodstr + swtstr + swtnum + granstr + extstr;
2422 
2423  filename_lt = fname_out.c_str();
2424  if ((status = nc_create(filename_lt, NC_CLOBBER, &ncid)))
2425  check_err(status, __LINE__, __FILE__);
2426 
2427  // Define the dimensions. NetCDF will hand back an ID for each.
2428 
2429  NY = num_gridlines;
2430  NX = nbinx;
2431 
2432  NY1 = l1cfile->NY1;//these are indexes not line #!!!!!!!!!!!!!!!!!
2433  NY2 = l1cfile->NY2;
2434  cout << "rowgrid ini.." << NY1 << "rowgrid end.." << NY2 << endl;
2435 
2436 
2437  cout << "NY.." << NY << "NX.." << NX << endl;
2438 
2439  //alloc mem for data_out and assign values from lat_gdI
2440  //NX AND NY are inverted for visualization in SeaDAS
2441  data_out = allocate2d_float(NY, NX);
2442  data_out2 = allocate2d_float(NY, NX);
2443  lat_out = allocate2d_float(NY, NX);
2444  lon_out = allocate2d_float(NY, NX);
2445 
2446  int c = 0;
2447  for (int i = NY1; i < NY2 + 1; i++) {
2448  for (int j = 0; j < NX; j++) {
2449  lat_out[NY - 1 - c][NX - 1 - j] = lat_gd[i][j];
2450  lon_out[NY - 1 - c][j] = lon_gd[i][j];
2451  //blue
2452  if (Ltfracsum[i][j] > 0 && areafracsum[i][j] > 0 && nobs_perbin[i][j] > 0) {
2453  data_out[NY - 1 - c][NX - 1 - j] = Ltfracsum[i][j] / sqrt(areafracsum[i][j]);
2454  data_out2[NY - 1 - c][NX - 1 - j] = nobs_perbin[i][j];
2455  }
2456  else {
2457  data_out[NY - 1 - c][NX - 1 - j] = NAN;
2458  data_out2[NY - 1 - c][NX - 1 - j] = 0;
2459  }
2460  }
2461  c++;
2462  }
2463 
2464 
2465 
2466  if ((status = nc_def_dim(ncid, "x", NX, &x_dimid)))
2467  check_err(status, __LINE__, __FILE__);
2468  if ((status = nc_def_dim(ncid, "y", NY, &y_dimid)))
2469  check_err(status, __LINE__, __FILE__);
2470  //dims for output var
2471  dimids[0] = y_dimid;
2472  dimids[1] = x_dimid;
2473  //def var
2474  if ((status = nc_def_var(ncid, "binLt_blue_AW", NC_FLOAT, NDIMS,
2475  dimids, &varid)))
2476  check_err(status, __LINE__, __FILE__);
2477 
2478  if ((status = nc_def_var(ncid, "lat_gd", NC_FLOAT, NDIMS,
2479  dimids, &varid2)))
2480  check_err(status, __LINE__, __FILE__);
2481  if ((status = nc_def_var(ncid, "lon_gd", NC_FLOAT, NDIMS,
2482  dimids, &varid3)))
2483  check_err(status, __LINE__, __FILE__);
2484  if ((status = nc_def_var(ncid, "nobs_perbin_AW", NC_FLOAT, NDIMS,
2485  dimids, &varid4)))
2486  check_err(status, __LINE__, __FILE__);
2487 
2488 
2489  if ((status = nc_enddef(ncid))) //done def vars etc
2490  check_err(status, __LINE__, __FILE__);
2491 
2492  //writing the whole thing
2493  if ((status = nc_put_var_float(ncid, varid2, &lat_out[0][0])))
2494  check_err(status, __LINE__, __FILE__);
2495 
2496  if ((status = nc_put_var_float(ncid, varid3, &lon_out[0][0])))
2497  check_err(status, __LINE__, __FILE__);
2498  //blue
2499  if ((status = nc_put_var_float(ncid, varid, &data_out[0][0])))
2500  check_err(status, __LINE__, __FILE__);
2501  if ((status = nc_put_var_float(ncid, varid4, &data_out2[0][0])))
2502  check_err(status, __LINE__, __FILE__);
2503 
2504  if ((status = nc_close(ncid)))
2505  check_err(status, __LINE__, __FILE__);
2506 
2507  delete[](lat_out);
2508  delete[](lon_out);
2509  delete[](data_out);
2510  delete[](data_out2);
2511 
2512  cout << "*********************** sucess writing area-wighted Lt nc file ****************************************************" << endl;
2513 
2514  return 0;
2515  }
2516 
2517 
2518 
2519 
2520  bool L1C::binIntersectsPix4corn4_l1c(l1c_filehandle* l1cfile, L1C_input* l1cinput, short row, short col, float** lat_gd, float** lon_gd, Polygon_t& pixelPoly, double areaFracBox[3][3], double areabinBox[3][3]) {
2521  bool result = false;
2522  double ws_lat, wn_lat, es_lat, en_lat, ws_lon, wn_lon, es_lon, en_lon;
2523  double ws_lat2, wn_lat2, es_lat2, en_lat2, ws_lon2, wn_lon2, es_lon2, en_lon2;
2524  double ws_lat3, wn_lat3, es_lat3, en_lat3, ws_lon3, wn_lon3, es_lon3, en_lon3;
2525  double ws_lat4, wn_lat4, es_lat4, en_lat4, ws_lon4, wn_lon4, es_lon4, en_lon4;
2526  double ws_lat5, wn_lat5, es_lat5, en_lat5, ws_lon5, wn_lon5, es_lon5, en_lon5;
2527  double ws_lat6, wn_lat6, es_lat6, en_lat6, ws_lon6, wn_lon6, es_lon6, en_lon6;
2528  double ws_lat7, wn_lat7, es_lat7, en_lat7, ws_lon7, wn_lon7, es_lon7, en_lon7;
2529  double ws_lat8, wn_lat8, es_lat8, en_lat8, ws_lon8, wn_lon8, es_lon8, en_lon8;
2530  double ws_lat9, wn_lat9, es_lat9, en_lat9, ws_lon9, wn_lon9, es_lon9, en_lon9;
2531  bool ingeom = false;
2532  int pc = 1;
2533  double intersectArea = 0, binAreapix = 0, binAreagrid = 0.;
2534  std::string ws_lon_str, ws_lat_str, wn_lon_str, wn_lat_str, en_lon_str, en_lat_str, es_lon_str, es_lat_str, gridstr;
2535  std::string ws2_lon_str, ws2_lat_str, wn2_lon_str, wn2_lat_str, en2_lon_str, en2_lat_str, es2_lon_str, es2_lat_str;
2536  std::string ws3_lon_str, ws3_lat_str, wn3_lon_str, wn3_lat_str, en3_lon_str, en3_lat_str, es3_lon_str, es3_lat_str;
2537  std::string ws4_lon_str, ws4_lat_str, wn4_lon_str, wn4_lat_str, en4_lon_str, en4_lat_str, es4_lon_str, es4_lat_str;
2538  std::string ws5_lon_str, ws5_lat_str, wn5_lon_str, wn5_lat_str, en5_lon_str, en5_lat_str, es5_lon_str, es5_lat_str;
2539  std::string ws6_lon_str, ws6_lat_str, wn6_lon_str, wn6_lat_str, en6_lon_str, en6_lat_str, es6_lon_str, es6_lat_str;
2540  std::string ws7_lon_str, ws7_lat_str, wn7_lon_str, wn7_lat_str, en7_lon_str, en7_lat_str, es7_lon_str, es7_lat_str;
2541  std::string ws8_lon_str, ws8_lat_str, wn8_lon_str, wn8_lat_str, en8_lon_str, en8_lat_str, es8_lon_str, es8_lat_str;
2542  std::string ws9_lon_str, ws9_lat_str, wn9_lon_str, wn9_lat_str, en9_lon_str, en9_lat_str, es9_lon_str, es9_lat_str;
2543  float binres = 0, azgc,deltaphi, deltalam, azpixc;
2544  float aterm, bterm, dist_u, dist_v, theta, thetares,thetagrad,dist_corn2, mean_az_east;
2545  double res1, res2, res3, res4, lat1, lon1, lat2, lon2;
2546  float az1, az2, az3, az4;
2547  bool infull = false;
2548  Geodesic geod(Constants::WGS84_a(), Constants::WGS84_f());
2549 
2550 
2551  mean_az_east = l1cfile->mean_az_east; //in degrees
2552 
2553  // cout<<"mean az east.for L1C grid................. in degrees..."<<mean_az_east<<endl;
2554  binres = (l1cinput->gres);//in km
2555 
2556 // cout << "binIntersectsPix4corn4_l1c...........................row......" << row << "col...." << col << endl;
2557 
2558  //*******************************************************************************************
2559  //center center bin
2560  //********************************************************************************************************
2561  ingeom = 0, binAreagrid = 0., binAreapix = 0, intersectArea = 0., pc = 1;
2562  deltaphi = (lat_gd[row][col] - lat_gd[row][col + 1]) * degrad;
2563  deltalam = (lon_gd[row][col] - lon_gd[row][col + 1]) * degrad;
2564  //across-track grid size
2565  aterm = sin(deltaphi / 2) * sin(deltaphi / 2) + cos(lat_gd[row][col] * degrad) * cos(lat_gd[row][col + 1] * degrad) * sin(deltalam / 2) * sin(deltalam / 2);
2566  bterm = 2 * atan2(sqrt(aterm), sqrt(1 - aterm));
2567  dist_u = Re * bterm; //horizontal distance Harversine in km
2568 
2569  deltaphi = (lat_gd[row][col] - lat_gd[row + 1][col]) * degrad;
2570  deltalam = (lon_gd[row][col] - lon_gd[row + 1][col]) * degrad;
2571  //along-track distance
2572  aterm = sin(deltaphi / 2) * sin(deltaphi / 2) + cos(lat_gd[row][col] * degrad) * cos(lat_gd[row + 1][col] * degrad) * sin(deltalam / 2) * sin(deltalam / 2);
2573  bterm = 2 * atan2(sqrt(aterm), sqrt(1 - aterm));
2574  dist_v = Re * bterm;
2575 
2576  lat1 = lat_gd[row][col];
2577  lon1 = lon_gd[row][col];
2578  lat2 = lat_gd[row][col + 1];
2579  lon2 = lon_gd[row][col + 1];
2580  geod.Inverse(lat1, lon1, lat2, lon2, res1);
2581 
2582  // ad=0.5*(sqrt(dist_u*dist_u+dist_v*dist_v)/Re);
2583 // dist_corn = 0.5 * sqrt(dist_u * dist_u + dist_v * dist_v) * 1000;
2584  dist_corn2 = 0.5 * sqrt(binres * binres + binres * binres) * 1000;
2585 
2586  //azimuth grid cell calculation
2587  // azgc=atan2(sin(deltalam)*cos(lat_gd[row+1][col]*degrad),cos(lat_gd[row][col]*degrad)*sin(lat_gd[row+1][col]*degrad)-sin(lat_gd[row][col]*degrad)*cos(lat_gd[row+1][col]*degrad)*cos(deltaphi));
2588  azgc = (mean_az_east - 90) * degrad;//this is the bearing
2589 
2590  if (azgc > M_PI || azgc < -M_PI)cout << "problem with BEARING in across-gridline method...az<-180 or >180...." << "azpixc in degrees.." << azgc * 180 / M_PI << endl;
2591 
2592  theta = atan2(dist_v, dist_u);
2593  thetagrad = 2 * theta * 180 / M_PI;
2594  thetares = (M_PI / 2 - theta) * 180 / M_PI;
2595  azgc = azgc * 180 / M_PI;
2596 
2597  //nw corner
2598  azpixc = (azgc - thetares) * degrad;//pixel bearing
2599  if (azpixc > M_PI || azpixc < -M_PI) {
2600  cout << "problem with BEARING in across-gridline method...az<-180 or >180...." << "NW azpixc in degrees.." << azpixc * 180 / M_PI << endl;
2601  exit(1);
2602  }
2603 
2604  azpixc = azpixc * 180 / M_PI;
2605  az1 = azpixc;
2606  geod.Direct(lat_gd[row][col], lon_gd[row][col], azpixc, dist_corn2, wn_lat, wn_lon);
2607  geod.Inverse(lat_gd[row][col], lon_gd[row][col], wn_lat, wn_lon, res1);
2608  // cout<<"azgc.Center-Center."<<azgc<<"azpixc.."<<azpixc<<"dist_corn.."<<dist_corn<<"dist_corn2.."<<dist_corn2<<endl;
2609  // cout<<"res1..nw."<<res1<<endl;
2610 
2611  //ne corner
2612  azpixc = (azgc + thetares) * degrad;//pixel bearing
2613  if (azpixc > M_PI || azpixc < -M_PI) {
2614  cout << "problem with BEARING in across-gridline method...az<-180 or >180...." << "NE azpixc in degrees.." << azpixc * 180 / M_PI << endl;
2615  exit(1);
2616  }
2617 
2618  azpixc = azpixc * 180 / M_PI;
2619  az2 = azpixc;
2620  geod.Direct(lat_gd[row][col], lon_gd[row][col], azpixc, dist_corn2, en_lat, en_lon);
2621  geod.Inverse(lat_gd[row][col], lon_gd[row][col], en_lat, en_lon, res2);
2622  // cout<<"azpixc.."<<azpixc<<"res2 ne.."<<res2<<endl;
2623  //sw corner
2624  azpixc = (azgc - thetares - thetagrad) * degrad;//pixel bearing
2625  if (azpixc > M_PI || azpixc < -M_PI) {
2626  cout << "problem with BEARING in across-gridline method...az<-180 or >180...." << "SW azpixc in degrees.." << azpixc * 180 / M_PI << endl;
2627  exit(1);
2628  }
2629 
2630  azpixc = azpixc * 180 / M_PI;
2631  az3 = azpixc;
2632  geod.Direct(lat_gd[row][col], lon_gd[row][col], azpixc, dist_corn2, ws_lat, ws_lon);
2633  geod.Inverse(lat_gd[row][col], lon_gd[row][col], ws_lat, ws_lon, res3);
2634  // cout<<"azpixc.."<<azpixc<<"res3..sw.."<<res3<<endl;
2635 
2636  //se corner
2637  azpixc = (azgc + thetares + thetagrad) * degrad;//pixel bearing
2638  if (azpixc > M_PI || azpixc < -M_PI) {
2639  cout << "problem with BEARING in across-gridline method...az<-180 or >180...." << "SE azpixc in degrees.." << azpixc * 180 / M_PI << endl;
2640  exit(1);
2641  }
2642 
2643  azpixc = azpixc * 180 / M_PI;
2644  az4 = azpixc;
2645  geod.Direct(lat_gd[row][col], lon_gd[row][col], azpixc, dist_corn2, es_lat, es_lon);
2646  geod.Inverse(lat_gd[row][col], lon_gd[row][col], es_lat, es_lon, res4);
2647  // cout<<"azpixc.."<<azpixc<<"res4...se.."<<res4<<endl;
2648 
2649  Polygon_t gridPoly;
2650  ws_lon_str = std::to_string(ws_lon);
2651  ws_lat_str = std::to_string(ws_lat);
2652  wn_lon_str = std::to_string(wn_lon);
2653  wn_lat_str = std::to_string(wn_lat);
2654  en_lon_str = std::to_string(en_lon);
2655  en_lat_str = std::to_string(en_lat);
2656  es_lon_str = std::to_string(es_lon);
2657  es_lat_str = std::to_string(es_lat);
2658  gridstr = "POLYGON((" + ws_lon_str + " " + ws_lat_str + "," + wn_lon_str + " " + wn_lat_str + "," + en_lon_str + " " + en_lat_str + "," + es_lon_str + " " + es_lat_str + "," + ws_lon_str + " " + ws_lat_str + "))";
2659  bg::read_wkt(gridstr, gridPoly);
2660 
2661  ingeom = within(pixelPoly, gridPoly);
2662  binAreagrid = bg::area(gridPoly);
2663  binAreapix = bg::area(pixelPoly);//area in m2 --Andoyer method --- DIVIDE BY 10^6 FOR KM2
2664  /*
2665  cout<<"center center-----------------"<<endl;
2666  cout<<"gd_row.."<<row<<"gd_col.."<<col<<endl;
2667  cout<<"dist_u.."<<dist_u<<"dist_v.."<<dist_v<<endl;
2668  cout<<"ingeom.."<<ingeom<<"binAreagrid..."<<binAreagrid<<"binAreapix.."<<binAreapix<<endl;
2669  cout<<"lat_gd.."<<lat_gd[row][col]<<"lon_gd.."<<lon_gd[row][col]<<"wn_lat.."<<wn_lat<<"wn_lon.."<<wn_lon<<endl;
2670  cout<<"lat_gd.."<<lat_gd[row][col]<<"lon_gd.."<<lon_gd[row][col]<<"ws_lat.."<<ws_lat<<"ws_lon.."<<ws_lon<<endl;
2671  cout<<"lat_gd.."<<lat_gd[row][col]<<"lon_gd.."<<lon_gd[row][col]<<"en_lat.."<<en_lat<<"en_lon.."<<en_lon<<endl;
2672  cout<<"lat_gd.."<<lat_gd[row][col]<<"lon_gd.."<<lon_gd[row][col]<<"es_lat.."<<es_lat<<"es_lon.."<<es_lon<<endl;
2673  */
2674  areabinBox[1][1] = binAreagrid;
2675 
2676  if (ingeom > 0) { //pixel fully inside the grid cell
2677  infull = true;
2678  intersectArea = binAreapix;
2679  result = true;
2680  areaFracBox[1][1] = intersectArea / binAreagrid;
2681 
2682  }
2683  else {
2684  if (!bg::disjoint(pixelPoly, gridPoly) && binAreagrid > 0) {
2685  std::deque<Polygon_t> output;//this is a list
2686  if (bg::intersection(pixelPoly, gridPoly, output)) {
2687  BOOST_FOREACH(Polygon_t const& p, output)
2688  {
2689  intersectArea = bg::area(p);
2690  if (intersectArea > 0.0 && pc == 1) {
2691  result = true;
2692  areaFracBox[1][1] = intersectArea / binAreagrid;
2693  if (intersectArea / binAreagrid < 0.000001) areaFracBox[1][1] = 0.0;
2694  pc++;
2695  }
2696  }
2697  }
2698  }
2699  }//end else
2700 
2701  // cout<<"center center.."<<"areaFracBox[1][1].........................................."<<areaFracBox[1][1]<<endl;
2702 
2703  //***********************************************************************************************************
2704  //left center bin
2705  //********************************************************************************************************
2706  ingeom = 0, binAreagrid = 0., binAreapix = 0, intersectArea = 0., pc = 1;
2707  if (col >= 1) {
2708 
2709  deltaphi = (lat_gd[row][col - 1] - lat_gd[row][col]) * degrad;
2710  deltalam = (lon_gd[row][col - 1] - lon_gd[row][col]) * degrad;
2711  //across-track grid size
2712  aterm = sin(deltaphi / 2) * sin(deltaphi / 2) + cos(lat_gd[row][col - 1] * degrad) * cos(lat_gd[row][col] * degrad) * sin(deltalam / 2) * sin(deltalam / 2);
2713  bterm = 2 * atan2(sqrt(aterm), sqrt(1 - aterm));
2714  dist_u = Re * bterm; //horizontal distance Harversine in km
2715 
2716  deltaphi = (lat_gd[row][col - 1] - lat_gd[row + 1][col - 1]) * degrad;
2717  deltalam = (lon_gd[row][col - 1] - lon_gd[row + 1][col - 1]) * degrad;
2718  //along-track distance
2719  aterm = sin(deltaphi / 2) * sin(deltaphi / 2) + cos(lat_gd[row][col - 1] * degrad) * cos(lat_gd[row + 1][col - 1] * degrad) * sin(deltalam / 2) * sin(deltalam / 2);
2720  bterm = 2 * atan2(sqrt(aterm), sqrt(1 - aterm));
2721  dist_v = Re * bterm;
2722 
2723  theta = atan2(dist_v, dist_u);
2724  thetagrad = 2 * theta * 180 / M_PI;
2725  thetares = (M_PI / 2 - theta) * 180 / M_PI;
2726 
2727 
2728  //nw corner
2729  azpixc = az1;
2730  geod.Direct(lat_gd[row][col - 1], lon_gd[row][col - 1], azpixc, dist_corn2, wn_lat2, wn_lon2);
2731  geod.Inverse(lat_gd[row][col - 1], lon_gd[row][col - 1], wn_lat2, wn_lon2, res1);
2732  // cout<<"azgc..CENTER-LEFT"<<azgc<<"azpixc.."<<azpixc<<"dist_corn.."<<dist_corn<<"dist_corn2.."<<dist_corn2<<endl;
2733  // cout<<"res1..nw."<<res1<<endl;
2734  //ne corner
2735  azpixc = az2;
2736  geod.Direct(lat_gd[row][col - 1], lon_gd[row][col - 1], azpixc, dist_corn2, en_lat2, en_lon2);
2737  geod.Inverse(lat_gd[row][col - 1], lon_gd[row][col - 1], en_lat2, en_lon2, res2);
2738  // cout<<"azpixc.."<<azpixc<<"res2 ne.."<<res2<<endl;
2739  //sw corner
2740  azpixc = az3;
2741  geod.Direct(lat_gd[row][col - 1], lon_gd[row][col - 1], azpixc, dist_corn2, ws_lat2, ws_lon2);
2742  geod.Inverse(lat_gd[row][col - 1], lon_gd[row][col - 1], ws_lat2, ws_lon2, res3);
2743  // cout<<"azpixc.."<<azpixc<<"res3..sw.."<<res3<<endl;
2744  //se corner
2745  azpixc = az4;
2746  geod.Direct(lat_gd[row][col - 1], lon_gd[row][col - 1], azpixc, dist_corn2, es_lat2, es_lon2);
2747  geod.Inverse(lat_gd[row][col - 1], lon_gd[row][col - 1], es_lat2, es_lon2, res4);
2748  // cout<<"azpixc.."<<azpixc<<"res4...se.."<<res4<<endl;
2749 
2750  Polygon_t gridPoly;
2751  ws2_lon_str = std::to_string(ws_lon2);
2752  ws2_lat_str = std::to_string(ws_lat2);
2753  wn2_lon_str = std::to_string(wn_lon2);
2754  wn2_lat_str = std::to_string(wn_lat2);
2755  en2_lon_str = std::to_string(en_lon2);
2756  en2_lat_str = std::to_string(en_lat2);
2757  es2_lon_str = std::to_string(es_lon2);
2758  es2_lat_str = std::to_string(es_lat2);
2759  gridstr = "POLYGON((" + ws2_lon_str + " " + ws2_lat_str + "," + wn2_lon_str + " " + wn2_lat_str + "," + wn_lon_str + " " + wn_lat_str + "," + ws_lon_str + " " + ws_lat_str + "," + ws2_lon_str + " " + ws2_lat_str + "))";
2760  bg::read_wkt(gridstr, gridPoly);
2761 
2762  ingeom = within(pixelPoly, gridPoly);
2763  binAreagrid = bg::area(gridPoly);
2764  binAreapix = bg::area(pixelPoly);//area in m2 --Andoyer method --- DIVIDE BY 10^6 FOR KM2
2765  /*
2766  cout<<"center LEFT-----------------"<<endl;
2767  cout<<"gd_row.."<<row<<"gd_col.."<<col<<endl;
2768  cout<<"dist_u.."<<dist_u<<"dist_v.."<<dist_v<<endl;
2769  cout<<"ingeom.."<<ingeom<<"binAreagrid..."<<binAreagrid<<"binAreapix.."<<binAreapix<<endl;
2770  cout<<"lat_gd.."<<lat_gd[row][col-1]<<"lon_gd.."<<lon_gd[row][col-1]<<"wn_lat.."<<wn_lat2<<"wn_lon.."<<wn_lon2<<endl;
2771  cout<<"lat_gd.."<<lat_gd[row][col-1]<<"lon_gd.."<<lon_gd[row][col-1]<<"ws_lat.."<<ws_lat2<<"ws_lon.."<<ws_lon2<<endl;
2772  cout<<"lat_gd.."<<lat_gd[row][col-1]<<"lon_gd.."<<lon_gd[row][col-1]<<"en_lat.."<<wn_lat<<"en_lon.."<<wn_lon<<endl;
2773  cout<<"lat_gd.."<<lat_gd[row][col-1]<<"lon_gd.."<<lon_gd[row][col-1]<<"es_lat.."<<ws_lat<<"es_lon.."<<ws_lon<<endl;
2774  */
2775 
2776  areabinBox[1][0] = binAreagrid;
2777 
2778  if (ingeom > 0) { //pixel fully inside the grid cell
2779  infull = true;
2780  intersectArea = binAreapix;
2781  result = true;
2782  areaFracBox[1][0] = intersectArea / binAreagrid;
2783  }
2784  else {
2785  if (!bg::disjoint(pixelPoly, gridPoly) && binAreagrid > 0) {
2786  std::deque<Polygon_t> output;
2787  if (bg::intersection(pixelPoly, gridPoly, output)) {
2788  BOOST_FOREACH(Polygon_t const& p, output)
2789  {
2790  intersectArea = bg::area(p);
2791  if (intersectArea > 0.0 && pc == 1) {
2792  result = true;
2793  areaFracBox[1][0] = intersectArea / binAreagrid;
2794  if (intersectArea / binAreagrid < 0.000001) areaFracBox[1][0] = 0.0;
2795  binAreapix = bg::area(pixelPoly);
2796  pc++;
2797  }
2798  }
2799  }
2800  }
2801  }//end else
2802 
2803  }//end col>=1 left center bin
2804 
2805  // cout<<"center LEFT.."<<"areaFracBox[1][0]........................................."<<areaFracBox[1][0]<<endl;
2806 
2807 
2808  //***************************************************************************
2809  //right center bin
2810  //**************************************************************************8
2811  ingeom = 0, binAreagrid = 0., binAreapix = 0, intersectArea = 0.;
2812 
2813  deltaphi = (lat_gd[row][col + 1] - lat_gd[row][col + 2]) * degrad;
2814  deltalam = (lon_gd[row][col + 1] - lon_gd[row][col + 2]) * degrad;
2815  //across-track grid size
2816  aterm = sin(deltaphi / 2) * sin(deltaphi / 2) + cos(lat_gd[row][col + 1] * degrad) * cos(lat_gd[row][col + 2] * degrad) * sin(deltalam / 2) * sin(deltalam / 2);
2817  bterm = 2 * atan2(sqrt(aterm), sqrt(1 - aterm));
2818  dist_u = Re * bterm; //horizontal distance Harversine in km
2819 
2820  deltaphi = (lat_gd[row][col + 1] - lat_gd[row + 1][col + 1]) * degrad;
2821  deltalam = (lon_gd[row][col + 1] - lon_gd[row + 1][col + 1]) * degrad;
2822  //along-track distance
2823  aterm = sin(deltaphi / 2) * sin(deltaphi / 2) + cos(lat_gd[row][col + 1] * degrad) * cos(lat_gd[row + 1][col + 1] * degrad) * sin(deltalam / 2) * sin(deltalam / 2);
2824  bterm = 2 * atan2(sqrt(aterm), sqrt(1 - aterm));
2825  dist_v = Re * bterm;
2826 
2827  theta = atan2(dist_v, dist_u);
2828  thetagrad = 2 * theta * 180 / M_PI;
2829  thetares = (M_PI / 2 - theta) * 180 / M_PI;
2830 
2831  //nw corner
2832  azpixc = az1;
2833  geod.Direct(lat_gd[row][col + 1], lon_gd[row][col + 1], azpixc, dist_corn2, wn_lat3, wn_lon3);
2834  geod.Inverse(lat_gd[row][col + 1], lon_gd[row][col + 1], wn_lat3, wn_lon3, res1);
2835  // cout<<"azgc..CENTER-RIGHT..."<<azgc<<"azpixc.."<<azpixc<<"dist_corn.."<<dist_corn<<"dist_corn2.."<<dist_corn2<<endl;
2836  // cout<<"res1..nw."<<res1<<endl;
2837 
2838  //ne corner
2839  azpixc = az2;
2840  geod.Direct(lat_gd[row][col + 1], lon_gd[row][col + 1], azpixc, dist_corn2, en_lat3, en_lon3);
2841  geod.Inverse(lat_gd[row][col + 1], lon_gd[row][col + 1], en_lat3, en_lon3, res2);
2842  // cout<<"azpixc.."<<azpixc<<"res2 ne.."<<res2<<endl;
2843  //sw corner
2844  azpixc = az3;
2845  geod.Direct(lat_gd[row][col + 1], lon_gd[row][col + 1], azpixc, dist_corn2, ws_lat3, ws_lon3);
2846  geod.Inverse(lat_gd[row][col + 1], lon_gd[row][col + 1], ws_lat3, ws_lon3, res3);
2847  // cout<<"azpixc.."<<azpixc<<"res3..sw.."<<res3<<endl;
2848  //se corner
2849  azpixc = az4;
2850  geod.Direct(lat_gd[row][col + 1], lon_gd[row][col + 1], azpixc, dist_corn2, es_lat3, es_lon3);
2851  geod.Inverse(lat_gd[row][col + 1], lon_gd[row][col + 1], es_lat3, es_lon3, res4);
2852  // cout<<"azpixc.."<<azpixc<<"res4...se.."<<res4<<endl;
2853  ws3_lon_str = std::to_string(ws_lon3);
2854  ws3_lat_str = std::to_string(ws_lat3);
2855  wn3_lon_str = std::to_string(wn_lon3);
2856  wn3_lat_str = std::to_string(wn_lat3);
2857  en3_lon_str = std::to_string(en_lon3);
2858  en3_lat_str = std::to_string(en_lat3);
2859  es3_lon_str = std::to_string(es_lon3);
2860  es3_lat_str = std::to_string(es_lat3);
2861  gridstr = "POLYGON((" + es_lon_str + " " + es_lat_str + "," + en_lon_str + " " + en_lat_str + "," + en3_lon_str + " " + en3_lat_str + "," + es3_lon_str + " " + es3_lat_str + "," + es_lon_str + " " + es_lat_str + "))";
2862  bg::read_wkt(gridstr, gridPoly);
2863 
2864  ingeom = within(pixelPoly, gridPoly);
2865  binAreagrid = bg::area(gridPoly);
2866  binAreapix = bg::area(pixelPoly);//area in m2 --Andoyer method --- DIVIDE BY 10^6 FOR KM2
2867 
2868  /*
2869  cout<<"center RIGHT-----------------"<<endl;
2870  cout<<"gd_row.."<<row<<"gd_col.."<<col<<endl;
2871  cout<<"dist_u.."<<dist_u<<"dist_v.."<<dist_v<<endl;
2872  cout<<"ingeom.."<<ingeom<<"binAreagrid..."<<binAreagrid<<"binAreapix.."<<binAreapix<<endl;
2873  cout<<"lat_gd.."<<lat_gd[row][col+1]<<"lon_gd.."<<lon_gd[row][col+1]<<"wn_lat.."<<en_lat<<"wn_lon.."<<en_lon<<endl;
2874  cout<<"lat_gd.."<<lat_gd[row][col+1]<<"lon_gd.."<<lon_gd[row][col+1]<<"ws_lat.."<<es_lat<<"ws_lon.."<<es_lon<<endl;
2875  cout<<"lat_gd.."<<lat_gd[row][col+1]<<"lon_gd.."<<lon_gd[row][col+1]<<"en_lat.."<<en_lat3<<"en_lon.."<<en_lon3<<endl;
2876  cout<<"lat_gd.."<<lat_gd[row][col+1]<<"lon_gd.."<<lon_gd[row][col+1]<<"es_lat.."<<es_lat3<<"es_lon.."<<es_lon3<<endl;
2877  */
2878 
2879  areabinBox[1][2] = binAreagrid;
2880  if (ingeom > 0) { //pixel fully inside the grid cell
2881  infull = true;
2882  intersectArea = binAreapix;
2883  result = true;
2884  areaFracBox[1][2] = intersectArea / binAreagrid;
2885  }
2886  else {
2887  if (!bg::disjoint(pixelPoly, gridPoly) && binAreagrid > 0.) {
2888  std::deque<Polygon_t> output;
2889  if (bg::intersection(pixelPoly, gridPoly, output)) {
2890  BOOST_FOREACH(Polygon_t const& p, output)
2891  {
2892  intersectArea = bg::area(p);
2893  if (intersectArea > 0.0 && pc == 1) {
2894  result = true;
2895  areaFracBox[1][2] = intersectArea / binAreagrid;
2896  if (intersectArea / binAreagrid < 0.000001) areaFracBox[1][2] = 0.0;
2897  pc++;
2898  }
2899  }
2900  }
2901  }
2902  }//end else
2903 
2904  // cout<<"center RIGHT.."<<"areaFracBox[1][2]........................................."<<areaFracBox[1][2]<<endl;
2905 
2906  //******************************************************************************************************
2907  //upper center bin
2908  //*****************************************************************************************************
2909  ingeom = 0, binAreagrid = 0., binAreapix = 0, intersectArea = 0., pc = 1;
2910 
2911  deltaphi = (lat_gd[row + 1][col] - lat_gd[row + 1][col + 1]) * degrad;
2912  deltalam = (lon_gd[row + 1][col] - lon_gd[row + 1][col + 1]) * degrad;
2913  //across-track grid size
2914  aterm = sin(deltaphi / 2) * sin(deltaphi / 2) + cos(lat_gd[row + 1][col] * degrad) * cos(lat_gd[row + 1][col + 1] * degrad) * sin(deltalam / 2) * sin(deltalam / 2);
2915  bterm = 2 * atan2(sqrt(aterm), sqrt(1 - aterm));
2916  dist_u = Re * bterm; //horizontal distance Harversine in km
2917 
2918  deltaphi = (lat_gd[row + 2][col] - lat_gd[row + 1][col]) * degrad;
2919  deltalam = (lon_gd[row + 2][col] - lon_gd[row + 1][col]) * degrad;
2920  //along-track distance
2921  aterm = sin(deltaphi / 2) * sin(deltaphi / 2) + cos(lat_gd[row + 1][col] * degrad) * cos(lat_gd[row + 2][col] * degrad) * sin(deltalam / 2) * sin(deltalam / 2);
2922  bterm = 2 * atan2(sqrt(aterm), sqrt(1 - aterm));
2923  dist_v = Re * bterm;
2924 
2925  theta = atan2(dist_v, dist_u);
2926  thetagrad = 2 * theta * 180 / M_PI;
2927  thetares = (M_PI / 2 - theta) * 180 / M_PI;
2928 
2929  //nw corner
2930  azpixc = az1;
2931  geod.Direct(lat_gd[row + 1][col], lon_gd[row + 1][col], azpixc, dist_corn2, wn_lat4, wn_lon4);
2932  geod.Inverse(lat_gd[row + 1][col], lon_gd[row + 1][col], wn_lat4, wn_lon4, res1);
2933  // cout<<"azgc..CENTER-UPPER..."<<azgc<<"azpixc.."<<azpixc<<"dist_corn.."<<dist_corn<<"dist_corn2.."<<dist_corn2<<endl;
2934  // cout<<"res1..nw."<<res1<<endl;
2935  //ne corner
2936  azpixc = az2;
2937  geod.Direct(lat_gd[row + 1][col], lon_gd[row + 1][col], azpixc, dist_corn2, en_lat4, en_lon4);
2938  geod.Inverse(lat_gd[row + 1][col], lon_gd[row + 1][col], en_lat4, en_lon4, res2);
2939  // cout<<"azpixc.."<<azpixc<<"res2 ne.."<<res2<<endl;
2940  //sw corner
2941  azpixc = az3;
2942  geod.Direct(lat_gd[row + 1][col], lon_gd[row + 1][col], azpixc, dist_corn2, ws_lat4, ws_lon4);
2943  geod.Inverse(lat_gd[row + 1][col], lon_gd[row + 1][col], ws_lat4, ws_lon4, res3);
2944  // cout<<"azpixc.."<<azpixc<<"res3..sw.."<<res3<<endl;
2945 
2946  //se corner
2947  azpixc = az4;
2948  geod.Direct(lat_gd[row + 1][col], lon_gd[row + 1][col], azpixc, dist_corn2, es_lat4, es_lon4);
2949  geod.Inverse(lat_gd[row + 1][col], lon_gd[row + 1][col], es_lat4, es_lon4, res4);
2950  // cout<<"azpixc.."<<azpixc<<"res4...se.."<<res4<<endl;
2951 
2952  ws4_lon_str = std::to_string(ws_lon4);
2953  ws4_lat_str = std::to_string(ws_lat4);
2954  wn4_lon_str = std::to_string(wn_lon4);
2955  wn4_lat_str = std::to_string(wn_lat4);
2956  en4_lon_str = std::to_string(en_lon4);
2957  en4_lat_str = std::to_string(en_lat4);
2958  es4_lon_str = std::to_string(es_lon4);
2959  es4_lat_str = std::to_string(es_lat4);
2960  gridstr = "POLYGON((" + wn_lon_str + " " + wn_lat_str + "," + wn4_lon_str + " " + wn4_lat_str + "," + en4_lon_str + " " + en4_lat_str + "," + en_lon_str + " " + en_lat_str + "," + wn_lon_str + " " + wn_lat_str + "))";
2961  bg::read_wkt(gridstr, gridPoly);
2962 
2963  ingeom = within(pixelPoly, gridPoly);
2964  binAreagrid = bg::area(gridPoly);
2965  binAreapix = bg::area(pixelPoly);//area in m2 --Andoyer method --- DIVIDE BY 10^6 FOR KM2
2966 
2967  /*
2968  cout<<"center UPPER-----------------"<<endl;
2969  cout<<"gd_row.."<<row<<"gd_col.."<<col<<endl;
2970  cout<<"dist_u.."<<dist_u<<"dist_v.."<<dist_v<<endl;
2971  cout<<"ingeom.."<<ingeom<<"binAreagrid..."<<binAreagrid<<"binAreapix.."<<binAreapix<<endl;
2972  cout<<"lat_gd.."<<lat_gd[row+1][col]<<"lon_gd.."<<lon_gd[row+1][col]<<"wn_lat.."<<wn_lat4<<"wn_lon.."<<wn_lon4<<endl;
2973  cout<<"lat_gd.."<<lat_gd[row+1][col]<<"lon_gd.."<<lon_gd[row+1][col]<<"ws_lat.."<<wn_lat<<"ws_lon.."<<wn_lon<<endl;
2974  cout<<"lat_gd.."<<lat_gd[row+1][col]<<"lon_gd.."<<lon_gd[row+1][col]<<"en_lat.."<<en_lat4<<"en_lon.."<<en_lon4<<endl;
2975  cout<<"lat_gd.."<<lat_gd[row+1][col]<<"lon_gd.."<<lon_gd[row+1][col]<<"es_lat.."<<en_lat<<"es_lon.."<<en_lon<<endl;
2976  */
2977 
2978  areabinBox[2][1] = binAreagrid;
2979  if (ingeom > 0) { //pixel fully inside the grid cell
2980  infull = true;
2981  intersectArea = binAreapix;
2982  result = true;
2983  areaFracBox[2][1] = intersectArea / binAreagrid;
2984  // cout<<"pixel fully inside gricell [2][1].."<<endl;
2985  }
2986  else {
2987  if (!bg::disjoint(pixelPoly, gridPoly) && binAreagrid > 0) {
2988  std::deque<Polygon_t> output;
2989  if (bg::intersection(pixelPoly, gridPoly, output)) {
2990  BOOST_FOREACH(Polygon_t const& p, output)
2991  {
2992  intersectArea = bg::area(p);
2993  if (intersectArea > 0.0 && pc == 1) {
2994  result = true;
2995  areaFracBox[2][1] = intersectArea / binAreagrid;
2996  if (intersectArea / binAreagrid < 0.000001) areaFracBox[2][1] = 0.0;
2997  pc++;
2998  }
2999  }
3000  }
3001  }
3002  }//end else
3003 
3004 
3005  // cout<<"CENTER UPPER.."<<"areaFracBox[2][1]........................................."<<areaFracBox[2][1]<<endl;
3006 
3007 
3008  //********************************************************
3009  //upper left bin
3010  //*******************************************************
3011  ingeom = 0, binAreagrid = 0., binAreapix = 0, intersectArea = 0., pc = 1;
3012 
3013  deltaphi = (lat_gd[row + 1][col - 1] - lat_gd[row + 1][col]) * degrad;
3014  deltalam = (lon_gd[row + 1][col - 1] - lon_gd[row + 1][col]) * degrad;
3015  //across-track grid size
3016  aterm = sin(deltaphi / 2) * sin(deltaphi / 2) + cos(lat_gd[row + 1][col - 1] * degrad) * cos(lat_gd[row + 1][col] * degrad) * sin(deltalam / 2) * sin(deltalam / 2);
3017  bterm = 2 * atan2(sqrt(aterm), sqrt(1 - aterm));
3018  dist_u = Re * bterm; //horizontal distance Harversine in km
3019 
3020  deltaphi = (lat_gd[row + 2][col - 1] - lat_gd[row + 1][col - 1]) * degrad;
3021  deltalam = (lon_gd[row + 2][col - 1] - lon_gd[row + 1][col - 1]) * degrad;
3022  //along-track distance
3023  aterm = sin(deltaphi / 2) * sin(deltaphi / 2) + cos(lat_gd[row + 1][col - 1] * degrad) * cos(lat_gd[row + 2][col - 1] * degrad) * sin(deltalam / 2) * sin(deltalam / 2);
3024  bterm = 2 * atan2(sqrt(aterm), sqrt(1 - aterm));
3025  dist_v = Re * bterm;
3026 
3027  theta = atan2(dist_v, dist_u);
3028  thetagrad = 2 * theta * 180 / M_PI;
3029  thetares = (M_PI / 2 - theta) * 180 / M_PI;
3030 
3031  //nw corner
3032  azpixc = az1;
3033  geod.Direct(lat_gd[row + 1][col - 1], lon_gd[row + 1][col - 1], azpixc, dist_corn2, wn_lat5, wn_lon5);
3034  geod.Inverse(lat_gd[row + 1][col - 1], lon_gd[row + 1][col - 1], wn_lat5, wn_lon5, res1);
3035  // cout<<"azgc..LEFT-UPPER..."<<azgc<<"azpixc.."<<azpixc<<"dist_corn.."<<dist_corn<<"dist_corn2.."<<dist_corn2<<endl;
3036  // cout<<"res1..nw."<<res1<<endl;
3037  //ne corner
3038  azpixc = az2;
3039  geod.Direct(lat_gd[row + 1][col - 1], lon_gd[row + 1][col - 1], azpixc, dist_corn2, en_lat5, en_lon5);
3040  geod.Inverse(lat_gd[row + 1][col - 1], lon_gd[row + 1][col - 1], en_lat5, en_lon5, res2);
3041  // cout<<"azpixc.."<<azpixc<<"res2 ne.."<<res2<<endl;
3042  //sw corner
3043  azpixc = az3;
3044  geod.Direct(lat_gd[row + 1][col - 1], lon_gd[row + 1][col - 1], azpixc, dist_corn2, ws_lat5, ws_lon5);
3045  geod.Inverse(lat_gd[row + 1][col - 1], lon_gd[row + 1][col - 1], ws_lat5, ws_lon5, res3);
3046  // cout<<"azpixc.."<<azpixc<<"res3..sw.."<<res3<<endl;
3047  //se corner
3048  azpixc = az4;
3049  geod.Direct(lat_gd[row + 1][col - 1], lon_gd[row + 1][col - 1], azpixc, dist_corn2, es_lat5, es_lon5);
3050  geod.Inverse(lat_gd[row + 1][col - 1], lon_gd[row + 1][col - 1], es_lat5, es_lon5, res4);
3051  // cout<<"azpixc.."<<azpixc<<"res4...se.."<<res4<<endl;
3052  ws5_lon_str = std::to_string(ws_lon5);
3053  ws5_lat_str = std::to_string(ws_lat5);
3054  wn5_lon_str = std::to_string(wn_lon5);
3055  wn5_lat_str = std::to_string(wn_lat5);
3056  en5_lon_str = std::to_string(en_lon5);
3057  en5_lat_str = std::to_string(en_lat5);
3058  es5_lon_str = std::to_string(es_lon5);
3059  es5_lat_str = std::to_string(es_lat5);
3060  gridstr = "POLYGON((" + wn2_lon_str + " " + wn2_lat_str + "," + wn5_lon_str + " " + wn5_lat_str + "," + wn4_lon_str + " " + wn4_lat_str + "," + wn_lon_str + " " + wn_lat_str + "," + wn2_lon_str + " " + wn2_lat_str + "))";
3061  bg::read_wkt(gridstr, gridPoly);
3062 
3063  ingeom = within(pixelPoly, gridPoly);
3064  binAreagrid = bg::area(gridPoly);
3065  binAreapix = bg::area(pixelPoly);//area in m2 --Andoyer method --- DIVIDE BY 10^6 FOR KM2
3066  /*
3067  cout<<"LEFT UPPER-----------------"<<endl;
3068  cout<<"gd_row.."<<row<<"gd_col.."<<col<<endl;
3069  cout<<"dist_u.."<<dist_u<<"dist_v.."<<dist_v<<endl;
3070  cout<<"ingeom.."<<ingeom<<"binAreagrid..."<<binAreagrid<<"binAreapix.."<<binAreapix<<endl;
3071  cout<<"lat_gd.."<<lat_gd[row+1][col-1]<<"lon_gd.."<<lon_gd[row+1][col-1]<<"wn_lat.."<<wn_lat5<<"wn_lon.."<<wn_lon5<<endl;
3072  cout<<"lat_gd.."<<lat_gd[row+1][col-1]<<"lon_gd.."<<lon_gd[row+1][col-1]<<"ws_lat.."<<wn_lat2<<"ws_lon.."<<wn_lon2<<endl;
3073  cout<<"lat_gd.."<<lat_gd[row+1][col-1]<<"lon_gd.."<<lon_gd[row+1][col-1]<<"en_lat.."<<wn_lat4<<"en_lon.."<<wn_lon4<<endl;
3074  cout<<"lat_gd.."<<lat_gd[row+1][col-1]<<"lon_gd.."<<lon_gd[row+1][col-1]<<"es_lat.."<<wn_lat<<"es_lon.."<<wn_lon<<endl;
3075  */
3076 
3077  areabinBox[2][0] = binAreagrid;
3078  if (ingeom > 0) { //pixel fully inside the grid cell
3079  infull = true;
3080  intersectArea = binAreapix;
3081  result = true;
3082  areaFracBox[2][0] = intersectArea / binAreagrid;
3083  // cout<<"pixel fully inside gricell [2][0].."<<endl;
3084  }
3085  else {
3086  if (!bg::disjoint(pixelPoly, gridPoly) && binAreagrid > 0) {
3087  std::deque<Polygon_t> output;
3088  if (bg::intersection(pixelPoly, gridPoly, output)) {
3089  BOOST_FOREACH(Polygon_t const& p, output)
3090  {
3091  intersectArea = bg::area(p);
3092  if (intersectArea > 0.0 && pc == 1) {
3093  result = true;
3094  areaFracBox[2][0] = intersectArea / binAreagrid;
3095  if (intersectArea / binAreagrid < 0.000001) areaFracBox[2][0] = 0.0;
3096  pc++;
3097  }
3098  }
3099  }
3100  }
3101  }//end else
3102 
3103  // cout<<"LEFT UPPER.."<<"areaFracBox[2][0]........................................."<<areaFracBox[2][0]<<endl;
3104 
3105  //**************************************************************************************
3106  //upper right bin
3107  //**************************************************************************************
3108  ingeom = 0, binAreagrid = 0., binAreapix = 0, intersectArea = 0., pc = 1;
3109 
3110  deltaphi = (lat_gd[row + 1][col + 1] - lat_gd[row + 1][col + 2]) * degrad;
3111  deltalam = (lon_gd[row + 1][col + 1] - lon_gd[row + 1][col + 2]) * degrad;
3112  //across-track grid size
3113  aterm = sin(deltaphi / 2) * sin(deltaphi / 2) + cos(lat_gd[row + 1][col + 1] * degrad) * cos(lat_gd[row + 1][col + 2] * degrad) * sin(deltalam / 2) * sin(deltalam / 2);
3114  bterm = 2 * atan2(sqrt(aterm), sqrt(1 - aterm));
3115  dist_u = Re * bterm; //horizontal distance Harversine in km
3116 
3117  deltaphi = (lat_gd[row + 2][col + 1] - lat_gd[row + 1][col + 1]) * degrad;
3118  deltalam = (lon_gd[row + 2][col + 1] - lon_gd[row + 1][col + 1]) * degrad;
3119  //along-track distance
3120  aterm = sin(deltaphi / 2) * sin(deltaphi / 2) + cos(lat_gd[row + 1][col + 1] * degrad) * cos(lat_gd[row + 2][col + 1] * degrad) * sin(deltalam / 2) * sin(deltalam / 2);
3121  bterm = 2 * atan2(sqrt(aterm), sqrt(1 - aterm));
3122  dist_v = Re * bterm;
3123 
3124  theta = atan2(dist_v, dist_u);
3125  thetagrad = 2 * theta * 180 / M_PI;
3126  thetares = (M_PI / 2 - theta) * 180 / M_PI;
3127 
3128  //nw corner
3129  azpixc = az1;
3130  geod.Direct(lat_gd[row + 1][col + 1], lon_gd[row + 1][col + 1], azpixc, dist_corn2, wn_lat6, wn_lon6);
3131  geod.Inverse(lat_gd[row + 1][col + 1], lon_gd[row + 1][col + 1], wn_lat6, wn_lon6, res1);
3132  // cout<<"azgc..RIGHT-UPPER..."<<azgc<<"azpixc.."<<azpixc<<"dist_corn.."<<dist_corn<<"dist_corn2.."<<dist_corn2<<endl;
3133  // cout<<"res1..nw."<<res1<<endl;
3134  //ne corner
3135  azpixc = az2;
3136  geod.Direct(lat_gd[row + 1][col + 1], lon_gd[row + 1][col + 1], azpixc, dist_corn2, en_lat6, en_lon6);
3137  geod.Inverse(lat_gd[row + 1][col + 1], lon_gd[row + 1][col + 1], en_lat6, en_lon6, res2);
3138  // cout<<"azpixc.."<<azpixc<<"res2 ne.."<<res2<<endl;
3139  //sw corner
3140  azpixc = az3;
3141  geod.Direct(lat_gd[row + 1][col + 1], lon_gd[row + 1][col + 1], azpixc, dist_corn2, ws_lat6, ws_lon6);
3142  geod.Inverse(lat_gd[row + 1][col + 1], lon_gd[row + 1][col + 1], ws_lat6, ws_lon6, res3);
3143  // cout<<"azpixc.."<<azpixc<<"res3..sw.."<<res3<<endl;
3144  //se corner
3145  azpixc = az4;
3146  geod.Direct(lat_gd[row + 1][col + 1], lon_gd[row + 1][col + 1], azpixc, dist_corn2, es_lat6, es_lon6);
3147  geod.Inverse(lat_gd[row + 1][col + 1], lon_gd[row + 1][col + 1], es_lat6, es_lon6, res4);
3148  // cout<<"azpixc.."<<azpixc<<"res4...se.."<<res4<<endl;
3149 
3150  ws6_lon_str = std::to_string(ws_lon6);
3151  ws6_lat_str = std::to_string(ws_lat6);
3152  wn6_lon_str = std::to_string(wn_lon6);
3153  wn6_lat_str = std::to_string(wn_lat6);
3154  en6_lon_str = std::to_string(en_lon6);
3155  en6_lat_str = std::to_string(en_lat6);
3156  es6_lon_str = std::to_string(es_lon6);
3157  es6_lat_str = std::to_string(es_lat6);
3158  gridstr = "POLYGON((" + en_lon_str + " " + en_lat_str + "," + en4_lon_str + " " + en4_lat_str + "," + en6_lon_str + " " + en6_lat_str + "," + en3_lon_str + " " + en3_lat_str + "," + en_lon_str + " " + en_lat_str + "))";
3159  bg::read_wkt(gridstr, gridPoly);
3160 
3161  ingeom = within(pixelPoly, gridPoly);
3162  binAreagrid = bg::area(gridPoly);
3163  binAreapix = bg::area(pixelPoly);//area in m2 --Andoyer method --- DIVIDE BY 10^6 FOR KM2
3164  /*
3165  cout<<"RIGHT UPPER-----------------"<<endl;
3166  cout<<"gd_row.."<<row<<"gd_col.."<<col<<endl;
3167  cout<<"dist_u.."<<dist_u<<"dist_v.."<<dist_v<<endl;
3168  cout<<"ingeom.."<<ingeom<<"binAreagrid..."<<binAreagrid<<"binAreapix.."<<binAreapix<<endl;
3169  cout<<"lat_gd.."<<lat_gd[row+1][col+1]<<"lon_gd.."<<lon_gd[row+1][col+1]<<"wn_lat.."<<en_lat4<<"wn_lon.."<<en_lon4<<endl;
3170  cout<<"lat_gd.."<<lat_gd[row+1][col+1]<<"lon_gd.."<<lon_gd[row+1][col+1]<<"ws_lat.."<<en_lat<<"ws_lon.."<<en_lon<<endl;
3171  cout<<"lat_gd.."<<lat_gd[row+1][col+1]<<"lon_gd.."<<lon_gd[row+1][col+1]<<"en_lat.."<<en_lat6<<"en_lon.."<<en_lon6<<endl;
3172  cout<<"lat_gd.."<<lat_gd[row+1][col+1]<<"lon_gd.."<<lon_gd[row+1][col+1]<<"es_lat.."<<en_lat3<<"es_lon.."<<en_lon3<<endl;
3173  */
3174 
3175  areabinBox[2][2] = binAreagrid;
3176  if (ingeom > 0) { //pixel fully inside the grid cell
3177  infull = true;
3178  intersectArea = binAreapix;
3179  result = true;
3180  areaFracBox[2][2] = intersectArea / binAreagrid;
3181  // cout<<"pixel fully inside gricell [2][2].."<<endl;
3182  }
3183  else {
3184  if (!bg::disjoint(pixelPoly, gridPoly) && binAreagrid > 0) {
3185  std::deque<Polygon_t> output;
3186  if (bg::intersection(pixelPoly, gridPoly, output)) {
3187  BOOST_FOREACH(Polygon_t const& p, output)
3188  {
3189  intersectArea = bg::area(p);
3190  if (intersectArea > 0.0 && pc == 1) {
3191  result = true;
3192  areaFracBox[2][2] = intersectArea / binAreagrid;
3193  if (intersectArea / binAreagrid < 0.000001) areaFracBox[2][2] = 0.0;
3194  pc++;
3195  }
3196  }
3197  }
3198  }
3199  }//end else
3200 
3201  // cout<<"RIGHT UPPER.."<<"areaFracBox[2][0]........................................."<<areaFracBox[2][2]<<endl;
3202 
3203  //************************************************************
3204  //lower center bin
3205  //*************************************************************
3206 
3207  ingeom = 0, binAreagrid = 0., binAreapix = 0, intersectArea = 0., pc = 1;
3208 
3209  deltaphi = (lat_gd[row - 1][col] - lat_gd[row - 1][col + 1]) * degrad;
3210  deltalam = (lon_gd[row - 1][col] - lon_gd[row - 1][col + 1]) * degrad;
3211  //across-track grid size
3212  aterm = sin(deltaphi / 2) * sin(deltaphi / 2) + cos(lat_gd[row - 1][col] * degrad) * cos(lat_gd[row - 1][col + 1] * degrad) * sin(deltalam / 2) * sin(deltalam / 2);
3213  bterm = 2 * atan2(sqrt(aterm), sqrt(1 - aterm));
3214  dist_u = Re * bterm; //horizontal distance Harversine in km
3215 
3216  deltaphi = (lat_gd[row - 1][col] - lat_gd[row][col]) * degrad;
3217  deltalam = (lon_gd[row - 1][col] - lon_gd[row][col]) * degrad;
3218  //along-track distance
3219  aterm = sin(deltaphi / 2) * sin(deltaphi / 2) + cos(lat_gd[row - 1][col] * degrad) * cos(lat_gd[row][col] * degrad) * sin(deltalam / 2) * sin(deltalam / 2);
3220  bterm = 2 * atan2(sqrt(aterm), sqrt(1 - aterm));
3221  dist_v = Re * bterm;
3222 
3223  theta = atan2(dist_v, dist_u);
3224  thetagrad = 2 * theta * 180 / M_PI;
3225  thetares = (M_PI / 2 - theta) * 180 / M_PI;
3226 
3227  //nw corner
3228  /* azpixc=(azgc-thetares)*degrad;//pixel bearing
3229  if(azpixc>M_PI | azpixc<-M_PI){
3230  cout<<"problem with BEARING in across-gridline method...az<-180 or >180...."<<"NW azpixc in degrees.."<<azpixc*180/M_PI<<endl;
3231  }
3232  azpixc=azpixc*180/M_PI;
3233  */
3234  azpixc = az1;
3235  geod.Direct(lat_gd[row - 1][col], lon_gd[row - 1][col], azpixc, dist_corn2, wn_lat7, wn_lon7);
3236  geod.Inverse(lat_gd[row - 1][col], lon_gd[row - 1][col], wn_lat7, wn_lon7, res1);
3237  // cout<<"azgc..LOWER CENTER..."<<azgc<<"azpixc.."<<azpixc<<"dist_corn.."<<dist_corn<<"dist_corn2.."<<dist_corn2<<endl;
3238  // cout<<"res1..nw."<<res1<<endl;
3239 
3240  //ne corner
3241  azpixc = az2;
3242  geod.Direct(lat_gd[row - 1][col], lon_gd[row - 1][col], azpixc, dist_corn2, en_lat7, en_lon7);
3243  geod.Inverse(lat_gd[row - 1][col], lon_gd[row - 1][col], en_lat7, en_lon7, res2);
3244  // cout<<"azpixc.."<<azpixc<<"res2 ne.."<<res2<<endl;
3245  //sw corner
3246  azpixc = az3;
3247  geod.Direct(lat_gd[row - 1][col], lon_gd[row - 1][col], azpixc, dist_corn2, ws_lat7, ws_lon7);
3248  geod.Inverse(lat_gd[row - 1][col], lon_gd[row - 1][col], ws_lat7, ws_lon7, res3);
3249  // cout<<"azpixc.."<<azpixc<<"res3..sw.."<<res3<<endl;
3250 
3251  //se corner
3252  azpixc = az4;
3253  geod.Direct(lat_gd[row - 1][col], lon_gd[row - 1][col], azpixc, dist_corn2, es_lat7, es_lon7);
3254  geod.Inverse(lat_gd[row - 1][col], lon_gd[row - 1][col], es_lat7, es_lon7, res4);
3255  // cout<<"azpixc.."<<azpixc<<"res4...se.."<<res4<<endl;
3256 
3257  ws7_lon_str = std::to_string(ws_lon7);
3258  ws7_lat_str = std::to_string(ws_lat7);
3259  wn7_lon_str = std::to_string(wn_lon7);
3260  wn7_lat_str = std::to_string(wn_lat7);
3261  en7_lon_str = std::to_string(en_lon7);
3262  en7_lat_str = std::to_string(en_lat7);
3263  es7_lon_str = std::to_string(es_lon7);
3264  es7_lat_str = std::to_string(es_lat7);
3265  gridstr = "POLYGON((" + ws7_lon_str + " " + ws7_lat_str + "," + ws_lon_str + " " + ws_lat_str + "," + es_lon_str + " " + es_lat_str + "," + es7_lon_str + " " + es7_lat_str + "," + ws7_lon_str + " " + ws7_lat_str + "))";
3266  bg::read_wkt(gridstr, gridPoly);
3267 
3268  ingeom = within(pixelPoly, gridPoly);
3269  binAreagrid = bg::area(gridPoly);
3270  binAreapix = bg::area(pixelPoly);//area in m2 --Andoyer method --- DIVIDE BY 10^6 FOR KM2
3271  /*
3272  cout<<"LOWER CENTER-----------------"<<endl;
3273  cout<<"gd_row.."<<row<<"gd_col.."<<col<<endl;
3274  cout<<"dist_u.."<<dist_u<<"dist_v.."<<dist_v<<endl;
3275  cout<<"ingeom.."<<ingeom<<"binAreagrid..."<<binAreagrid<<"binAreapix.."<<binAreapix<<endl;
3276  cout<<"lat_gd.."<<lat_gd[row-1][col]<<"lon_gd.."<<lon_gd[row-1][col]<<"wn_lat.."<<ws_lat<<"wn_lon.."<<ws_lon<<endl;
3277  cout<<"lat_gd.."<<lat_gd[row-1][col]<<"lon_gd.."<<lon_gd[row-1][col]<<"ws_lat.."<<ws_lat7<<"ws_lon.."<<ws_lon7<<endl;
3278  cout<<"lat_gd.."<<lat_gd[row-1][col]<<"lon_gd.."<<lon_gd[row-1][col]<<"en_lat.."<<es_lat<<"en_lon.."<<es_lon<<endl;
3279  cout<<"lat_gd.."<<lat_gd[row-1][col]<<"lon_gd.."<<lon_gd[row-1][col]<<"es_lat.."<<es_lat7<<"es_lon.."<<es_lon7<<endl;
3280  */
3281  areabinBox[0][1] = binAreagrid;
3282  if (ingeom > 0) { //pixel fully inside the grid cell
3283  infull = true;
3284  intersectArea = binAreapix;
3285  result = true;
3286  areaFracBox[0][1] = intersectArea / binAreagrid;
3287  // cout<<"pixel fully inside gricell [0][1].."<<endl;
3288  }
3289  else {
3290  if (!bg::disjoint(pixelPoly, gridPoly) && binAreagrid > 0) {
3291  std::deque<Polygon_t> output;
3292  if (bg::intersection(pixelPoly, gridPoly, output)) {
3293  BOOST_FOREACH(Polygon_t const& p, output)
3294  {
3295  intersectArea = bg::area(p);
3296  if (intersectArea > 0.0 && pc == 1) {
3297  result = true;
3298  areaFracBox[0][1] = intersectArea / binAreagrid;
3299  if (intersectArea / binAreagrid < 0.000001) areaFracBox[0][1] = 0.0;
3300  pc++;
3301  }
3302  }
3303  }
3304  }
3305  }//end else
3306 
3307 
3308  // cout<<"CENTER LOWER.."<<"areaFracBox[0][1]........................................."<<areaFracBox[0][1]<<endl;
3309 
3310 
3311  //******************************************************************
3312  //lower left bin
3313  //****************************************************************
3314  ingeom = 0, binAreagrid = 0, binAreapix = 0, intersectArea = 0., pc = 1;
3315 
3316  deltaphi = (lat_gd[row - 1][col - 1] - lat_gd[row - 1][col]) * degrad;
3317  deltalam = (lon_gd[row - 1][col - 1] - lon_gd[row - 1][col]) * degrad;
3318  //across-track grid size
3319  aterm = sin(deltaphi / 2) * sin(deltaphi / 2) + cos(lat_gd[row - 1][col - 1] * degrad) * cos(lat_gd[row - 1][col] * degrad) * sin(deltalam / 2) * sin(deltalam / 2);
3320  bterm = 2 * atan2(sqrt(aterm), sqrt(1 - aterm));
3321  dist_u = Re * bterm; //horizontal distance Harversine in km
3322 
3323  deltaphi = (lat_gd[row - 1][col - 1] - lat_gd[row][col - 1]) * degrad;
3324  deltalam = (lon_gd[row - 1][col - 1] - lon_gd[row][col - 1]) * degrad;
3325  //along-track distance
3326  aterm = sin(deltaphi / 2) * sin(deltaphi / 2) + cos(lat_gd[row - 1][col - 1] * degrad) * cos(lat_gd[row][col - 1] * degrad) * sin(deltalam / 2) * sin(deltalam / 2);
3327  bterm = 2 * atan2(sqrt(aterm), sqrt(1 - aterm));
3328  dist_v = Re * bterm;
3329 
3330  theta = atan2(dist_v, dist_u);
3331  thetagrad = 2 * theta * 180 / M_PI;
3332  thetares = (M_PI / 2 - theta) * 180 / M_PI;
3333 
3334  //nw corner
3335  azpixc = az1;
3336  geod.Direct(lat_gd[row - 1][col - 1], lon_gd[row - 1][col - 1], azpixc, dist_corn2, wn_lat8, wn_lon8);
3337  geod.Inverse(lat_gd[row - 1][col - 1], lon_gd[row - 1][col - 1], wn_lat8, wn_lon8, res1);
3338  // cout<<"azgc..LOWER LEFT..."<<azgc<<"azpixc.."<<azpixc<<"dist_corn.."<<dist_corn<<"dist_corn2.."<<dist_corn2<<endl;
3339  // cout<<"res1..nw."<<res1<<endl;
3340 
3341  //ne corner
3342  azpixc = az2;
3343  geod.Direct(lat_gd[row - 1][col - 1], lon_gd[row - 1][col - 1], azpixc, dist_corn2, en_lat8, en_lon8);
3344  geod.Inverse(lat_gd[row - 1][col - 1], lon_gd[row - 1][col - 1], en_lat8, en_lon8, res2);
3345  // cout<<"azpixc.."<<azpixc<<"res2 ne.."<<res2<<endl;
3346  //sw corner
3347  azpixc = az3;
3348  geod.Direct(lat_gd[row - 1][col - 1], lon_gd[row - 1][col - 1], azpixc, dist_corn2, ws_lat8, ws_lon8);
3349  geod.Inverse(lat_gd[row - 1][col - 1], lon_gd[row - 1][col - 1], ws_lat8, ws_lon8, res3);
3350  // cout<<"azpixc.."<<azpixc<<"res3..sw.."<<res3<<endl;
3351 
3352  //se corner
3353  azpixc = az4;
3354  geod.Direct(lat_gd[row - 1][col - 1], lon_gd[row - 1][col - 1], azpixc, dist_corn2, es_lat8, es_lon8);
3355  geod.Inverse(lat_gd[row - 1][col - 1], lon_gd[row - 1][col - 1], es_lat8, es_lon8, res4);
3356  // cout<<"azpixc.."<<azpixc<<"res4...se.."<<res4<<endl;
3357  ws8_lon_str = std::to_string(ws_lon8);
3358  ws8_lat_str = std::to_string(ws_lat8);
3359  wn8_lon_str = std::to_string(wn_lon8);
3360  wn8_lat_str = std::to_string(wn_lat8);
3361  en8_lon_str = std::to_string(en_lon8);
3362  en8_lat_str = std::to_string(en_lat8);
3363  es8_lon_str = std::to_string(es_lon8);
3364  es8_lat_str = std::to_string(es_lat8);
3365  gridstr = "POLYGON((" + ws8_lon_str + " " + ws8_lat_str + "," + ws2_lon_str + " " + ws2_lat_str + "," + ws_lon_str + " " + ws_lat_str + "," + ws7_lon_str + " " + ws7_lat_str + "," + ws8_lon_str + " " + ws8_lat_str + "))";
3366  bg::read_wkt(gridstr, gridPoly);
3367 
3368  ingeom = within(pixelPoly, gridPoly);
3369  binAreagrid = bg::area(gridPoly);
3370  binAreapix = bg::area(pixelPoly);//area in m2 --Andoyer method --- DIVIDE BY 10^6 FOR KM2
3371  /*
3372  cout<<"LOWER LEFT-----------------"<<endl;
3373  cout<<"gd_row.."<<row<<"gd_col.."<<col<<endl;
3374  cout<<"dist_u.."<<dist_u<<"dist_v.."<<dist_v<<endl;
3375  cout<<"ingeom.."<<ingeom<<"binAreagrid..."<<binAreagrid<<"binAreapix.."<<binAreapix<<endl;
3376  cout<<"lat_gd.."<<lat_gd[row-1][col-1]<<"lon_gd.."<<lon_gd[row-1][col-1]<<"wn_lat.."<<ws_lat2<<"wn_lon.."<<ws_lon2<<endl;
3377  cout<<"lat_gd.."<<lat_gd[row-1][col-1]<<"lon_gd.."<<lon_gd[row-1][col-1]<<"ws_lat.."<<ws_lat8<<"ws_lon.."<<ws_lon8<<endl;
3378  cout<<"lat_gd.."<<lat_gd[row-1][col-1]<<"lon_gd.."<<lon_gd[row-1][col-1]<<"en_lat.."<<ws_lat<<"en_lon.."<<ws_lon<<endl;
3379  cout<<"lat_gd.."<<lat_gd[row-1][col-1]<<"lon_gd.."<<lon_gd[row-1][col-1]<<"es_lat.."<<ws_lat7<<"es_lon.."<<ws_lon7<<endl;
3380  */
3381 
3382  areabinBox[0][0] = binAreagrid;
3383  if (ingeom > 0) { //pixel fully inside the grid cell
3384  infull = true;
3385  intersectArea = binAreapix;
3386  result = true;
3387  areaFracBox[0][0] = intersectArea / binAreagrid;
3388  }
3389  else {
3390  if (!bg::disjoint(pixelPoly, gridPoly) && binAreagrid > 0) {
3391  std::deque<Polygon_t> output;
3392  if (bg::intersection(pixelPoly, gridPoly, output)) {
3393  BOOST_FOREACH(Polygon_t const& p, output)
3394  {
3395  intersectArea = bg::area(p);
3396  if (intersectArea > 0.0 && pc == 1) {
3397  result = true;
3398  areaFracBox[0][0] = intersectArea / binAreagrid;
3399  if (intersectArea / binAreagrid < 0.000001) areaFracBox[0][0] = 0.0;
3400  pc++;
3401  }
3402  }
3403  }
3404  }
3405  }//end else
3406 
3407 
3408  // cout<<"LEFT LOWER.."<<"areaFracBox[0][0]........................................."<<areaFracBox[0][0]<<endl;
3409 
3410  //******************************************************************
3411  //lower right bin
3412  //****************************************************************
3413  ingeom = 0, binAreagrid = 0, binAreapix = 0, intersectArea = 0., pc = 1;
3414 
3415  deltaphi = (lat_gd[row - 1][col + 1] - lat_gd[row - 1][col + 2]) * degrad;
3416  deltalam = (lon_gd[row - 1][col + 1] - lon_gd[row - 1][col + 2]) * degrad;
3417  //across-track grid size
3418  aterm = sin(deltaphi / 2) * sin(deltaphi / 2) + cos(lat_gd[row - 1][col + 1] * degrad) * cos(lat_gd[row - 1][col + 2] * degrad) * sin(deltalam / 2) * sin(deltalam / 2);
3419  bterm = 2 * atan2(sqrt(aterm), sqrt(1 - aterm));
3420  dist_u = Re * bterm; //horizontal distance Harversine in km
3421 
3422  deltaphi = (lat_gd[row - 1][col + 1] - lat_gd[row][col + 1]) * degrad;
3423  deltalam = (lon_gd[row - 1][col + 1] - lon_gd[row][col + 1]) * degrad;
3424  //along-track distance
3425  aterm = sin(deltaphi / 2) * sin(deltaphi / 2) + cos(lat_gd[row - 1][col + 1] * degrad) * cos(lat_gd[row][col + 1] * degrad) * sin(deltalam / 2) * sin(deltalam / 2);
3426  bterm = 2 * atan2(sqrt(aterm), sqrt(1 - aterm));
3427  dist_v = Re * bterm;
3428 
3429  theta = atan2(dist_v, dist_u);
3430  thetagrad = 2 * theta * 180 / M_PI;
3431  thetares = (M_PI / 2 - theta) * 180 / M_PI;
3432 
3433  //nw corner
3434  azpixc = az1;
3435  geod.Direct(lat_gd[row - 1][col + 1], lon_gd[row - 1][col + 1], azpixc, dist_corn2, wn_lat9, wn_lon9);
3436  geod.Inverse(lat_gd[row - 1][col + 1], lon_gd[row - 1][col + 1], wn_lat9, wn_lon9, res1);
3437  // cout<<"azgc..LOWER RIGHT..."<<azgc<<"azpixc.."<<azpixc<<"dist_corn.."<<dist_corn<<"dist_corn2.."<<dist_corn2<<endl;
3438  // cout<<"res1..nw."<<res1<<endl;
3439 
3440  //ne corner
3441  azpixc = az2;
3442  geod.Direct(lat_gd[row - 1][col + 1], lon_gd[row - 1][col + 1], azpixc, dist_corn2, en_lat9, en_lon9);
3443  geod.Inverse(lat_gd[row - 1][col + 1], lon_gd[row - 1][col + 1], en_lat9, en_lon9, res2);
3444  // cout<<"azpixc.."<<azpixc<<"res2 ne.."<<res2<<endl;
3445  //sw corner
3446  azpixc = az3;
3447  geod.Direct(lat_gd[row - 1][col + 1], lon_gd[row - 1][col + 1], azpixc, dist_corn2, ws_lat9, ws_lon9);
3448  geod.Inverse(lat_gd[row - 1][col + 1], lon_gd[row - 1][col + 1], ws_lat9, ws_lon9, res3);
3449  // cout<<"azpixc.."<<azpixc<<"res3..sw.."<<res3<<endl;
3450 
3451  //se corner
3452  azpixc = az4;
3453  geod.Direct(lat_gd[row - 1][col + 1], lon_gd[row - 1][col + 1], azpixc, dist_corn2, es_lat9, es_lon9);
3454  geod.Inverse(lat_gd[row - 1][col + 1], lon_gd[row - 1][col + 1], es_lat9, es_lon9, res4);
3455  // cout<<"azpixc.."<<azpixc<<"res4...se.."<<res4<<endl;
3456 
3457  ws9_lon_str = std::to_string(ws_lon9);
3458  ws9_lat_str = std::to_string(ws_lat9);
3459  wn9_lon_str = std::to_string(wn_lon9);
3460  wn9_lat_str = std::to_string(wn_lat9);
3461  en9_lon_str = std::to_string(en_lon9);
3462  en9_lat_str = std::to_string(en_lat9);
3463  es9_lon_str = std::to_string(es_lon9);
3464  es9_lat_str = std::to_string(es_lat9);
3465  gridstr = "POLYGON((" + es7_lon_str + " " + es7_lat_str + "," + es_lon_str + " " + es_lat_str + "," + es3_lon_str + " " + es3_lat_str + "," + es9_lon_str + " " + es9_lat_str + "," + es7_lon_str + " " + es7_lat_str + "))";
3466  bg::read_wkt(gridstr, gridPoly);
3467 
3468  ingeom = within(pixelPoly, gridPoly);
3469  binAreagrid = bg::area(gridPoly);
3470  binAreapix = bg::area(pixelPoly);//area in m2 --Andoyer method --- DIVIDE BY 10^6 FOR KM2
3471 
3472  /*
3473  cout<<"LOWER RIGHT-----------------"<<endl;
3474  cout<<"gd_row.."<<row<<"gd_col.."<<col<<endl;
3475  cout<<"dist_u.."<<dist_u<<"dist_v.."<<dist_v<<endl;
3476  cout<<"ingeom.."<<ingeom<<"binAreagrid..."<<binAreagrid<<"binAreapix.."<<binAreapix<<endl;
3477  cout<<"lat_gd.."<<lat_gd[row-1][col+1]<<"lon_gd.."<<lon_gd[row-1][col+1]<<"wn_lat.."<<es_lat<<"wn_lon.."<<es_lon<<endl;
3478  cout<<"lat_gd.."<<lat_gd[row-1][col+1]<<"lon_gd.."<<lon_gd[row-1][col+1]<<"ws_lat.."<<es_lat7<<"ws_lon.."<<es_lon7<<endl;
3479  cout<<"lat_gd.."<<lat_gd[row-1][col+1]<<"lon_gd.."<<lon_gd[row-1][col+1]<<"en_lat.."<<es_lat3<<"en_lon.."<<es_lon3<<endl;
3480  cout<<"lat_gd.."<<lat_gd[row-1][col+1]<<"lon_gd.."<<lon_gd[row-1][col+1]<<"es_lat.."<<es_lat9<<"es_lon.."<<es_lon9<<endl;
3481  */
3482 
3483  areabinBox[0][2] = binAreagrid;
3484  if (ingeom > 0) { //pixel fully inside the grid cell
3485  infull = true;
3486  intersectArea = binAreapix;
3487  result = true;
3488  areaFracBox[0][2] = intersectArea / binAreagrid;
3489  }
3490  else {
3491  if (!bg::disjoint(pixelPoly, gridPoly) && binAreagrid > 0) {
3492  std::deque<Polygon_t> output;
3493  if (bg::intersection(pixelPoly, gridPoly, output)) {
3494  BOOST_FOREACH(Polygon_t const& p, output)
3495  {
3496  intersectArea = bg::area(p);
3497  if (intersectArea > 0.0 && pc == 1) {
3498  result = true;
3499  areaFracBox[0][2] = intersectArea / binAreagrid;
3500  if (intersectArea / binAreagrid < 0.000001) areaFracBox[0][2] = 0.0;
3501  pc++;
3502  }
3503  }
3504  }
3505  }
3506  }//end else
3507 
3508  // cout<<"RIGHT LOWER.."<<"areaFracBox[0][2]........................................."<<areaFracBox[0][2]<<endl;
3509 
3510 
3511 
3512  if (infull == true) {
3513  // cout << "pixelbox fully inside gridbox..........................................." << endl;
3514  // exit(1);
3515  }
3516 
3517  return result;
3518 
3519  }
3520 
3521 
3522 
3523  bool L1C::binIntersectsPix4corn3(short row, short col, double** lat_cgd, double** lon_cgd, Polygon_t& pixelPoly, double areaFracBox[3][3], double areabinBox[3][3]) {
3524  bool result = false;
3525  double ws_lat, wn_lat, es_lat, en_lat, ws_lon, wn_lon, es_lon, en_lon;
3526  bool ingeom = false;
3527  // shape->rowcol2bounds(row, col, n, s, e, w);
3528  int32_t rowc = 0, colc = 0;
3529  int pc = 1;
3530  double intersectArea = 0, binAreapix = 0, binAreagrid = 0.;
3531  std::string ws_lon_str, ws_lat_str, wn_lon_str, wn_lat_str, en_lon_str, en_lat_str, es_lon_str, es_lat_str, gridstr;
3532  rowc = row + 1;
3533  colc = col + 1;
3534 
3535  if (rowc < 0 || colc < 0) {
3536  cout << "ERROR ON binIntersectsPix4corn3...rowc or colc are negative for cornerlines.." << endl;
3537  exit(1);
3538 }
3539 
3540  ingeom = 0, binAreagrid = 0., binAreapix = 0, intersectArea = 0., pc = 1;
3541 
3542  //center center bin---------------------------------------------
3543 
3544  ws_lat = lat_cgd[rowc - 1][colc - 1];
3545  ws_lon = lon_cgd[rowc - 1][colc - 1];
3546  wn_lat = lat_cgd[rowc][colc - 1];
3547  wn_lon = lon_cgd[rowc][colc - 1];
3548  en_lat = lat_cgd[rowc][colc];
3549  en_lon = lon_cgd[rowc][colc];
3550  es_lat = lat_cgd[rowc - 1][colc];
3551  es_lon = lon_cgd[rowc - 1][colc];
3552 
3553 
3554  if (ws_lon > es_lon || wn_lon > en_lon || ws_lat > wn_lat || es_lat > en_lat) {
3555  cout << "ws_lon>es_lon | wn_lon>en_lon | ws_lat>wn_lat | es_lat>en_lat..." << ws_lon << es_lon << wn_lon << en_lon << ws_lat << wn_lat << es_lat << en_lat << endl;
3556  cout << "-------------------------------gd_row.." << row << "gd_col.." << col << "----------------------" << endl;
3557  }
3558 
3559 
3560  Polygon_t gridPoly;
3561  ws_lon_str = std::to_string(ws_lon);
3562  ws_lat_str = std::to_string(ws_lat);
3563  wn_lon_str = std::to_string(wn_lon);
3564  wn_lat_str = std::to_string(wn_lat);
3565  en_lon_str = std::to_string(en_lon);
3566  en_lat_str = std::to_string(en_lat);
3567  es_lon_str = std::to_string(es_lon);
3568  es_lat_str = std::to_string(es_lat);
3569  gridstr = "POLYGON((" + ws_lon_str + " " + ws_lat_str + "," + wn_lon_str + " " + wn_lat_str + "," + en_lon_str + " " + en_lat_str + "," + es_lon_str + " " + es_lat_str + "," + ws_lon_str + " " + ws_lat_str + "))";
3570  bg::read_wkt(gridstr, gridPoly);
3571 
3572  ingeom = within(pixelPoly, gridPoly);
3573  binAreagrid = bg::area(gridPoly);
3574  binAreapix = bg::area(pixelPoly);//area in m2 --Andoyer method --- DIVIDE BY 10^6 FOR KM2
3575  if (binAreagrid < 0.000001)areabinBox[1][1] = 0.0;else areabinBox[1][1] = binAreagrid;
3576  /* cout<<"inside binIntersectsPix4corn.."<<"ws_lon.."<<ws_lon<<"ws_lat.."<<ws_lat<<endl;
3577  cout<<"inside binIntersectsPix4corn.."<<"wn_lon.."<<wn_lon<<"wn_lat.."<<wn_lat<<endl;
3578  cout<<"inside binIntersectsPix4corn.."<<"en_lon.."<<en_lon<<"en_lat.."<<en_lat<<endl;
3579  cout<<"inside binIntersectsPix4corn.."<<"es_lon.."<<es_lon<<"es_lat.."<<es_lat<<endl;
3580  */
3581  // if(binAreagrid<0.000001)cout<<"binAreagrid<0.000001.[1][1]."<<endl;
3582 
3583  if (ingeom > 0) { //pixel fully inside the grid cell
3584  intersectArea = binAreapix;
3585  result = true;
3586  areaFracBox[1][1] = intersectArea / binAreagrid;
3587  // cout<<"pixel fully inside gricell [1][1].."<<endl;
3588  }
3589  else {
3590  if (!bg::disjoint(pixelPoly, gridPoly) && binAreagrid > 0) {
3591  std::deque<Polygon_t> output;//this is a list
3592  if (bg::intersection(pixelPoly, gridPoly, output)) {
3593  BOOST_FOREACH(Polygon_t const& p, output)
3594  {
3595  intersectArea = bg::area(p);
3596  if (intersectArea > 0.0 && pc == 1) {
3597  result = true;
3598  areaFracBox[1][1] = intersectArea / binAreagrid;
3599  if (intersectArea / binAreagrid < 0.000001) areaFracBox[1][1] = 0.0;
3600  pc++;
3601  }
3602  }
3603  }
3604  }
3605  }//end else
3606 
3607  ingeom = 0, binAreagrid = 0., binAreapix = 0, intersectArea = 0., pc = 1;
3608 
3609  //left center bin
3610  ws_lat = lat_cgd[rowc - 1][colc - 2];
3611  ws_lon = lon_cgd[rowc - 1][colc - 2];
3612  wn_lat = lat_cgd[rowc][colc - 2];
3613  wn_lon = lon_cgd[rowc][colc - 2];
3614  en_lat = lat_cgd[rowc][colc - 1];
3615  en_lon = lon_cgd[rowc][colc - 1];
3616  es_lat = lat_cgd[rowc - 1][colc - 1];
3617  es_lon = lon_cgd[rowc - 1][colc - 1];
3618 
3619 
3620  ws_lon_str = std::to_string(ws_lon);
3621  ws_lat_str = std::to_string(ws_lat);
3622  wn_lon_str = std::to_string(wn_lon);
3623  wn_lat_str = std::to_string(wn_lat);
3624  en_lon_str = std::to_string(en_lon);
3625  en_lat_str = std::to_string(en_lat);
3626  es_lon_str = std::to_string(es_lon);
3627  es_lat_str = std::to_string(es_lat);
3628  gridstr = "POLYGON((" + ws_lon_str + " " + ws_lat_str + "," + wn_lon_str + " " + wn_lat_str + "," + en_lon_str + " " + en_lat_str + "," + es_lon_str + " " + es_lat_str + "," + ws_lon_str + " " + ws_lat_str + "))";
3629  bg::read_wkt(gridstr, gridPoly);
3630 
3631  ingeom = within(pixelPoly, gridPoly);
3632  binAreagrid = bg::area(gridPoly);
3633  binAreapix = bg::area(pixelPoly);//area in m2 --Andoyer method --- DIVIDE BY 10^6 FOR KM2
3634  if (binAreagrid < 0.000001)areabinBox[1][0] = 0.0;else areabinBox[1][0] = binAreagrid;
3635  /* cout<<"inside binIntersectsPix4corn.."<<"ws_lon.."<<ws_lon<<"ws_lat.."<<ws_lat<<endl;
3636  cout<<"inside binIntersectsPix4corn.."<<"wn_lon.."<<wn_lon<<"wn_lat.."<<wn_lat<<endl;
3637  cout<<"inside binIntersectsPix4corn.."<<"en_lon.."<<en_lon<<"en_lat.."<<en_lat<<endl;
3638  cout<<"inside binIntersectsPix4corn.."<<"es_lon.."<<es_lon<<"es_lat.."<<es_lat<<endl;*/
3639  // if(binAreagrid<0.000001)cout<<"binAreagrid<0.000001..[1][0]"<<endl;
3640 
3641 
3642  if (ingeom > 0) { //pixel fully inside the grid cell
3643  intersectArea = binAreapix;
3644  result = true;
3645  areaFracBox[1][0] = intersectArea / binAreagrid;
3646  // cout<<"pixel fully inside gricell [1][0].."<<endl;
3647  }
3648  else {
3649  if (!bg::disjoint(pixelPoly, gridPoly) && binAreagrid > 0) {
3650  std::deque<Polygon_t> output;
3651  if (bg::intersection(pixelPoly, gridPoly, output)) {
3652  BOOST_FOREACH(Polygon_t const& p, output)
3653  {
3654  intersectArea = bg::area(p);
3655  if (intersectArea > 0.0 && pc == 1) {
3656  result = true;
3657  areaFracBox[1][0] = intersectArea / binAreagrid;
3658  if (intersectArea / binAreagrid < 0.000001) areaFracBox[1][0] = 0.0;
3659  binAreapix = bg::area(pixelPoly);
3660  pc++;
3661  }
3662  }
3663  }
3664  }
3665  }//end else
3666 
3667  ingeom = 0, binAreagrid = 0., binAreapix = 0, intersectArea = 0.;
3668  //right center bin
3669  ws_lat = lat_cgd[rowc - 1][colc];
3670  ws_lon = lon_cgd[rowc - 1][colc];
3671  wn_lat = lat_cgd[rowc][colc];
3672  wn_lon = lon_cgd[rowc][colc];
3673  en_lat = lat_cgd[rowc][colc + 1];
3674  en_lon = lon_cgd[rowc][colc + 1];
3675  es_lat = lat_cgd[rowc - 1][colc + 1];
3676  es_lon = lon_cgd[rowc - 1][colc + 1];
3677  //**********************************************************************
3678  ws_lon_str = std::to_string(ws_lon);
3679  ws_lat_str = std::to_string(ws_lat);
3680  wn_lon_str = std::to_string(wn_lon);
3681  wn_lat_str = std::to_string(wn_lat);
3682  en_lon_str = std::to_string(en_lon);
3683  en_lat_str = std::to_string(en_lat);
3684  es_lon_str = std::to_string(es_lon);
3685  es_lat_str = std::to_string(es_lat);
3686  gridstr = "POLYGON((" + ws_lon_str + " " + ws_lat_str + "," + wn_lon_str + " " + wn_lat_str + "," + en_lon_str + " " + en_lat_str + "," + es_lon_str + " " + es_lat_str + "," + ws_lon_str + " " + ws_lat_str + "))";
3687  bg::read_wkt(gridstr, gridPoly);
3688 
3689  ingeom = within(pixelPoly, gridPoly);
3690  binAreagrid = bg::area(gridPoly);
3691  binAreapix = bg::area(pixelPoly);//area in m2 --Andoyer method --- DIVIDE BY 10^6 FOR KM2
3692  if (binAreagrid < 0.000001)areabinBox[1][2] = 0.0;else areabinBox[1][2] = binAreagrid;
3693  /* cout<<"inside binIntersectsPix4corn.."<<"ws_lon.."<<ws_lon<<"ws_lat.."<<ws_lat<<endl;
3694  cout<<"inside binIntersectsPix4corn.."<<"wn_lon.."<<wn_lon<<"wn_lat.."<<wn_lat<<endl;
3695  cout<<"inside binIntersectsPix4corn.."<<"en_lon.."<<en_lon<<"en_lat.."<<en_lat<<endl;
3696  cout<<"inside binIntersectsPix4corn.."<<"es_lon.."<<es_lon<<"es_lat.."<<es_lat<<endl;*/
3697  // if(binAreagrid<0.000001) cout<<"binAreagrid<0.000001.[1][2]."<<endl;
3698 
3699  if (ingeom > 0) { //pixel fully inside the grid cell
3700  intersectArea = binAreapix;
3701  result = true;
3702  areaFracBox[1][2] = intersectArea / binAreagrid;
3703  // cout<<"pixel fully inside gricell [1][2].."<<endl;
3704  }
3705  else {
3706  if (!bg::disjoint(pixelPoly, gridPoly) && binAreagrid > 0.) {
3707  std::deque<Polygon_t> output;
3708  if (bg::intersection(pixelPoly, gridPoly, output)) {
3709  BOOST_FOREACH(Polygon_t const& p, output)
3710  {
3711  intersectArea = bg::area(p);
3712  if (intersectArea > 0.0 && pc == 1) {
3713  result = true;
3714  areaFracBox[1][2] = intersectArea / binAreagrid;
3715  if (intersectArea / binAreagrid < 0.000001) areaFracBox[1][2] = 0.0;
3716  pc++;
3717  }
3718  }
3719  }
3720  }
3721  }//end else
3722  ingeom = 0, binAreagrid = 0., binAreapix = 0, intersectArea = 0., pc = 1;
3723  //upper center bin
3724  ws_lat = lat_cgd[rowc][colc - 1];
3725  ws_lon = lon_cgd[rowc][colc - 1];
3726  wn_lat = lat_cgd[rowc + 1][colc - 1];
3727  wn_lon = lon_cgd[rowc + 1][colc - 1];
3728  en_lat = lat_cgd[rowc + 1][colc];
3729  en_lon = lon_cgd[rowc + 1][colc];
3730  es_lat = lat_cgd[rowc][colc];
3731  es_lon = lon_cgd[rowc][colc];
3732 
3733 
3734  ws_lon_str = std::to_string(ws_lon);
3735  ws_lat_str = std::to_string(ws_lat);
3736  wn_lon_str = std::to_string(wn_lon);
3737  wn_lat_str = std::to_string(wn_lat);
3738  en_lon_str = std::to_string(en_lon);
3739  en_lat_str = std::to_string(en_lat);
3740  es_lon_str = std::to_string(es_lon);
3741  es_lat_str = std::to_string(es_lat);
3742  gridstr = "POLYGON((" + ws_lon_str + " " + ws_lat_str + "," + wn_lon_str + " " + wn_lat_str + "," + en_lon_str + " " + en_lat_str + "," + es_lon_str + " " + es_lat_str + "," + ws_lon_str + " " + ws_lat_str + "))";
3743  bg::read_wkt(gridstr, gridPoly);
3744 
3745  ingeom = within(pixelPoly, gridPoly);
3746  binAreagrid = bg::area(gridPoly);
3747  binAreapix = bg::area(pixelPoly);//area in m2 --Andoyer method --- DIVIDE BY 10^6 FOR KM2
3748  if (binAreagrid < 0.000001)areabinBox[2][1] = 0.0;else areabinBox[2][1] = binAreagrid;
3749  /* cout<<"inside binIntersectsPix4corn.."<<"ws_lon.."<<ws_lon<<"ws_lat.."<<ws_lat<<endl;
3750  cout<<"inside binIntersectsPix4corn.."<<"wn_lon.."<<wn_lon<<"wn_lat.."<<wn_lat<<endl;
3751  cout<<"inside binIntersectsPix4corn.."<<"en_lon.."<<en_lon<<"en_lat.."<<en_lat<<endl;
3752  cout<<"inside binIntersectsPix4corn.."<<"es_lon.."<<es_lon<<"es_lat.."<<es_lat<<endl;*/
3753  // if(binAreagrid<0.000001) cout<<"binAreagrid<0.000001..[2][1]"<<endl;
3754 
3755  if (ingeom > 0) { //pixel fully inside the grid cell
3756  intersectArea = binAreapix;
3757  result = true;
3758  areaFracBox[2][1] = intersectArea / binAreagrid;
3759  // cout<<"pixel fully inside gricell [2][1].."<<endl;
3760  }
3761  else {
3762  if (!bg::disjoint(pixelPoly, gridPoly) && binAreagrid > 0) {
3763  std::deque<Polygon_t> output;
3764  if (bg::intersection(pixelPoly, gridPoly, output)) {
3765  BOOST_FOREACH(Polygon_t const& p, output)
3766  {
3767  intersectArea = bg::area(p);
3768  if (intersectArea > 0.0 && pc == 1) {
3769  result = true;
3770  areaFracBox[2][1] = intersectArea / binAreagrid;
3771  if (intersectArea / binAreagrid < 0.000001) areaFracBox[2][1] = 0.0;
3772  pc++;
3773  }
3774  }
3775  }
3776  }
3777  }//end else
3778 
3779  ingeom = 0, binAreagrid = 0., binAreapix = 0, intersectArea = 0., pc = 1;
3780  //upper left bin
3781  ws_lat = lat_cgd[rowc][colc - 2];
3782  ws_lon = lon_cgd[rowc][colc - 2];
3783  wn_lat = lat_cgd[rowc + 1][colc - 2];
3784  wn_lon = lon_cgd[rowc + 1][colc - 2];
3785  en_lat = lat_cgd[rowc + 1][colc - 1];
3786  en_lon = lon_cgd[rowc + 1][colc - 1];
3787  es_lat = lat_cgd[rowc][colc - 1];
3788  es_lon = lon_cgd[rowc][colc - 1];
3789 
3790 
3791  ws_lon_str = std::to_string(ws_lon);
3792  ws_lat_str = std::to_string(ws_lat);
3793  wn_lon_str = std::to_string(wn_lon);
3794  wn_lat_str = std::to_string(wn_lat);
3795  en_lon_str = std::to_string(en_lon);
3796  en_lat_str = std::to_string(en_lat);
3797  es_lon_str = std::to_string(es_lon);
3798  es_lat_str = std::to_string(es_lat);
3799  gridstr = "POLYGON((" + ws_lon_str + " " + ws_lat_str + "," + wn_lon_str + " " + wn_lat_str + "," + en_lon_str + " " + en_lat_str + "," + es_lon_str + " " + es_lat_str + "," + ws_lon_str + " " + ws_lat_str + "))";
3800  bg::read_wkt(gridstr, gridPoly);
3801 
3802  ingeom = within(pixelPoly, gridPoly);
3803  binAreagrid = bg::area(gridPoly);
3804  binAreapix = bg::area(pixelPoly);//area in m2 --Andoyer method --- DIVIDE BY 10^6 FOR KM2
3805  // if(binAreagrid<0.000001)areabinBox[2][0]=0.0;else areabinBox[2][0]= binAreagrid;
3806  /* cout<<"inside binIntersectsPix4corn.."<<"ws_lon.."<<ws_lon<<"ws_lat.."<<ws_lat<<endl;
3807  cout<<"inside binIntersectsPix4corn.."<<"wn_lon.."<<wn_lon<<"wn_lat.."<<wn_lat<<endl;
3808  cout<<"inside binIntersectsPix4corn.."<<"en_lon.."<<en_lon<<"en_lat.."<<en_lat<<endl;
3809  cout<<"inside binIntersectsPix4corn.."<<"es_lon.."<<es_lon<<"es_lat.."<<es_lat<<endl;*/
3810  if (binAreagrid < 0.000001) cout << "binAreagrid<0.000001..[2][0]" << endl;
3811 
3812  if (ingeom > 0) { //pixel fully inside the grid cell
3813  intersectArea = binAreapix;
3814  result = true;
3815  areaFracBox[2][0] = intersectArea / binAreagrid;
3816  // cout<<"pixel fully inside gricell [2][0].."<<endl;
3817  }
3818  else {
3819  if (!bg::disjoint(pixelPoly, gridPoly) && binAreagrid > 0) {
3820  std::deque<Polygon_t> output;
3821  if (bg::intersection(pixelPoly, gridPoly, output)) {
3822  BOOST_FOREACH(Polygon_t const& p, output)
3823  {
3824  intersectArea = bg::area(p);
3825  if (intersectArea > 0.0 && pc == 1) {
3826  result = true;
3827  areaFracBox[2][0] = intersectArea / binAreagrid;
3828  if (intersectArea / binAreagrid < 0.000001) areaFracBox[2][0] = 0.0;
3829  pc++;
3830  }
3831  }
3832  }
3833  }
3834  }//end else
3835  ingeom = 0, binAreagrid = 0., binAreapix = 0, intersectArea = 0., pc = 1;
3836  //upper right bin
3837  ws_lat = lat_cgd[rowc][colc];
3838  ws_lon = lon_cgd[rowc][colc];
3839  wn_lat = lat_cgd[rowc + 1][colc];
3840  wn_lon = lon_cgd[rowc + 1][colc];
3841  en_lat = lat_cgd[rowc + 1][colc + 1];
3842  en_lon = lon_cgd[rowc + 1][colc + 1];
3843  es_lat = lat_cgd[rowc][colc + 1];
3844  es_lon = lon_cgd[rowc][colc + 1];
3845 
3846  ws_lon_str = std::to_string(ws_lon);
3847  ws_lat_str = std::to_string(ws_lat);
3848  wn_lon_str = std::to_string(wn_lon);
3849  wn_lat_str = std::to_string(wn_lat);
3850  en_lon_str = std::to_string(en_lon);
3851  en_lat_str = std::to_string(en_lat);
3852  es_lon_str = std::to_string(es_lon);
3853  es_lat_str = std::to_string(es_lat);
3854  gridstr = "POLYGON((" + ws_lon_str + " " + ws_lat_str + "," + wn_lon_str + " " + wn_lat_str + "," + en_lon_str + " " + en_lat_str + "," + es_lon_str + " " + es_lat_str + "," + ws_lon_str + " " + ws_lat_str + "))";
3855  bg::read_wkt(gridstr, gridPoly);
3856 
3857  ingeom = within(pixelPoly, gridPoly);
3858  binAreagrid = bg::area(gridPoly);
3859  binAreapix = bg::area(pixelPoly);//area in m2 --Andoyer method --- DIVIDE BY 10^6 FOR KM2
3860  if (binAreagrid < 0.000001)areabinBox[2][2] = 0.0;else areabinBox[2][2] = binAreagrid;
3861  /* cout<<"inside binIntersectsPix4corn.."<<"ws_lon.."<<ws_lon<<"ws_lat.."<<ws_lat<<endl;
3862  cout<<"inside binIntersectsPix4corn.."<<"wn_lon.."<<wn_lon<<"wn_lat.."<<wn_lat<<endl;
3863  cout<<"inside binIntersectsPix4corn.."<<"en_lon.."<<en_lon<<"en_lat.."<<en_lat<<endl;
3864  cout<<"inside binIntersectsPix4corn.."<<"es_lon.."<<es_lon<<"es_lat.."<<es_lat<<endl;*/
3865  // if(binAreagrid<0.000001) cout<<"binAreagrid<0.000001..[2][2]"<<endl;
3866 
3867  if (ingeom > 0) { //pixel fully inside the grid cell
3868  intersectArea = binAreapix;
3869  result = true;
3870  areaFracBox[2][2] = intersectArea / binAreagrid;
3871  // cout<<"pixel fully inside gricell [2][2].."<<endl;
3872  }
3873  else {
3874  if (!bg::disjoint(pixelPoly, gridPoly) && binAreagrid > 0) {
3875  std::deque<Polygon_t> output;
3876  if (bg::intersection(pixelPoly, gridPoly, output)) {
3877  BOOST_FOREACH(Polygon_t const& p, output)
3878  {
3879  intersectArea = bg::area(p);
3880  if (intersectArea > 0.0 && pc == 1) {
3881  result = true;
3882  areaFracBox[2][2] = intersectArea / binAreagrid;
3883  if (intersectArea / binAreagrid < 0.000001) areaFracBox[2][2] = 0.0;
3884  pc++;
3885  }
3886  }
3887  }
3888  }
3889  }//end else
3890 
3891  ingeom = 0, binAreagrid = 0., binAreapix = 0, intersectArea = 0., pc = 1;
3892  //lower center bin
3893  ws_lat = lat_cgd[rowc - 2][colc - 1];
3894  ws_lon = lon_cgd[rowc - 2][colc - 1];
3895  wn_lat = lat_cgd[rowc - 1][colc - 1];
3896  wn_lon = lon_cgd[rowc - 1][colc - 1];
3897  en_lat = lat_cgd[rowc - 1][colc];
3898  en_lon = lon_cgd[rowc - 1][colc];
3899  es_lat = lat_cgd[rowc - 2][colc];
3900  es_lon = lon_cgd[rowc - 2][colc];
3901 
3902  ws_lon_str = std::to_string(ws_lon);
3903  ws_lat_str = std::to_string(ws_lat);
3904  wn_lon_str = std::to_string(wn_lon);
3905  wn_lat_str = std::to_string(wn_lat);
3906  en_lon_str = std::to_string(en_lon);
3907  en_lat_str = std::to_string(en_lat);
3908  es_lon_str = std::to_string(es_lon);
3909  es_lat_str = std::to_string(es_lat);
3910  gridstr = "POLYGON((" + ws_lon_str + " " + ws_lat_str + "," + wn_lon_str + " " + wn_lat_str + "," + en_lon_str + " " + en_lat_str + "," + es_lon_str + " " + es_lat_str + "," + ws_lon_str + " " + ws_lat_str + "))";
3911  bg::read_wkt(gridstr, gridPoly);
3912 
3913  ingeom = within(pixelPoly, gridPoly);
3914  binAreagrid = bg::area(gridPoly);
3915  binAreapix = bg::area(pixelPoly);//area in m2 --Andoyer method --- DIVIDE BY 10^6 FOR KM2
3916  if (binAreagrid < 0.000001)areabinBox[0][1] = 0.0;else areabinBox[0][1] = binAreagrid;
3917  /* cout<<"inside binIntersectsPix4corn.."<<"ws_lon.."<<ws_lon<<"ws_lat.."<<ws_lat<<endl;
3918  cout<<"inside binIntersectsPix4corn.."<<"wn_lon.."<<wn_lon<<"wn_lat.."<<wn_lat<<endl;
3919  cout<<"inside binIntersectsPix4corn.."<<"en_lon.."<<en_lon<<"en_lat.."<<en_lat<<endl;
3920  cout<<"inside binIntersectsPix4corn.."<<"es_lon.."<<es_lon<<"es_lat.."<<es_lat<<endl;*/
3921  // if(binAreagrid<0.000001) cout<<"binAreagrid<0.000001..[0][1]"<<endl;
3922 
3923  if (ingeom > 0) { //pixel fully inside the grid cell
3924  intersectArea = binAreapix;
3925  result = true;
3926  areaFracBox[0][1] = intersectArea / binAreagrid;
3927  // cout<<"pixel fully inside gricell [0][1].."<<endl;
3928  }
3929  else {
3930  if (!bg::disjoint(pixelPoly, gridPoly) && binAreagrid > 0) {
3931  std::deque<Polygon_t> output;
3932  if (bg::intersection(pixelPoly, gridPoly, output)) {
3933  BOOST_FOREACH(Polygon_t const& p, output)
3934  {
3935  intersectArea = bg::area(p);
3936  if (intersectArea > 0.0 && pc == 1) {
3937  result = true;
3938  areaFracBox[0][1] = intersectArea / binAreagrid;
3939  if (intersectArea / binAreagrid < 0.000001) areaFracBox[0][1] = 0.0;
3940  pc++;
3941  }
3942  }
3943  }
3944  }
3945  }//end else
3946  ingeom = 0, binAreagrid = 0., binAreapix = 0, intersectArea = 0., pc = 1;
3947  //lower left bin
3948  ws_lat = lat_cgd[rowc - 2][colc - 2];
3949  ws_lon = lon_cgd[rowc - 2][colc - 2];
3950  wn_lat = lat_cgd[rowc - 1][colc - 2];
3951  wn_lon = lon_cgd[rowc - 1][colc - 2];
3952  en_lat = lat_cgd[rowc - 1][colc - 1];
3953  en_lon = lon_cgd[rowc - 1][colc - 1];
3954  es_lat = lat_cgd[rowc - 2][colc - 1];
3955  es_lon = lon_cgd[rowc - 2][colc - 1];
3956 
3957 
3958  ws_lon_str = std::to_string(ws_lon);
3959  ws_lat_str = std::to_string(ws_lat);
3960  wn_lon_str = std::to_string(wn_lon);
3961  wn_lat_str = std::to_string(wn_lat);
3962  en_lon_str = std::to_string(en_lon);
3963  en_lat_str = std::to_string(en_lat);
3964  es_lon_str = std::to_string(es_lon);
3965  es_lat_str = std::to_string(es_lat);
3966  gridstr = "POLYGON((" + ws_lon_str + " " + ws_lat_str + "," + wn_lon_str + " " + wn_lat_str + "," + en_lon_str + " " + en_lat_str + "," + es_lon_str + " " + es_lat_str + "," + ws_lon_str + " " + ws_lat_str + "))";
3967  bg::read_wkt(gridstr, gridPoly);
3968 
3969  ingeom = within(pixelPoly, gridPoly);
3970  binAreagrid = bg::area(gridPoly);
3971  binAreapix = bg::area(pixelPoly);//area in m2 --Andoyer method --- DIVIDE BY 10^6 FOR KM2
3972  if (binAreagrid < 0.000001)areabinBox[0][0] = 0.0;else areabinBox[0][0] = binAreagrid;
3973  /* cout<<"inside binIntersectsPix4corn.."<<"ws_lon.."<<ws_lon<<"ws_lat.."<<ws_lat<<endl;
3974  cout<<"inside binIntersectsPix4corn.."<<"wn_lon.."<<wn_lon<<"wn_lat.."<<wn_lat<<endl;
3975  cout<<"inside binIntersectsPix4corn.."<<"en_lon.."<<en_lon<<"en_lat.."<<en_lat<<endl;
3976  cout<<"inside binIntersectsPix4corn.."<<"es_lon.."<<es_lon<<"es_lat.."<<es_lat<<endl;*/
3977  // if(binAreagrid<0.000001) cout<<"binAreagrid<0.000001..[0][0]"<<endl;
3978 
3979  if (ingeom > 0) { //pixel fully inside the grid cell
3980  intersectArea = binAreapix;
3981  result = true;
3982  areaFracBox[0][0] = intersectArea / binAreagrid;
3983  // cout<<"pixel fully inside gricell [0][0].."<<endl;
3984  }
3985  else {
3986  if (!bg::disjoint(pixelPoly, gridPoly) && binAreagrid > 0) {
3987  std::deque<Polygon_t> output;
3988  if (bg::intersection(pixelPoly, gridPoly, output)) {
3989  BOOST_FOREACH(Polygon_t const& p, output)
3990  {
3991  intersectArea = bg::area(p);
3992  if (intersectArea > 0.0 && pc == 1) {
3993  result = true;
3994  areaFracBox[0][0] = intersectArea / binAreagrid;
3995  if (intersectArea / binAreagrid < 0.000001) areaFracBox[0][0] = 0.0;
3996  pc++;
3997  }
3998  }
3999  }
4000  }
4001  }//end else
4002  ingeom = 0, binAreagrid = 0, binAreapix = 0, intersectArea = 0., pc = 1;
4003  //lower right bin
4004  ws_lat = lat_cgd[rowc - 2][colc];
4005  ws_lon = lon_cgd[rowc - 2][colc];
4006  wn_lat = lat_cgd[rowc - 1][colc];
4007  wn_lon = lon_cgd[rowc - 1][colc];
4008  en_lat = lat_cgd[rowc - 1][colc + 1];
4009  en_lon = lon_cgd[rowc - 1][colc + 1];
4010  es_lat = lat_cgd[rowc - 2][colc + 1];
4011  es_lon = lon_cgd[rowc - 2][colc + 1];
4012 
4013  ws_lon_str = std::to_string(ws_lon);
4014  ws_lat_str = std::to_string(ws_lat);
4015  wn_lon_str = std::to_string(wn_lon);
4016  wn_lat_str = std::to_string(wn_lat);
4017  en_lon_str = std::to_string(en_lon);
4018  en_lat_str = std::to_string(en_lat);
4019  es_lon_str = std::to_string(es_lon);
4020  es_lat_str = std::to_string(es_lat);
4021  gridstr = "POLYGON((" + ws_lon_str + " " + ws_lat_str + "," + wn_lon_str + " " + wn_lat_str + "," + en_lon_str + " " + en_lat_str + "," + es_lon_str + " " + es_lat_str + "," + ws_lon_str + " " + ws_lat_str + "))";
4022  bg::read_wkt(gridstr, gridPoly);
4023 
4024  ingeom = within(pixelPoly, gridPoly);
4025  binAreagrid = bg::area(gridPoly);
4026  binAreapix = bg::area(pixelPoly);//area in m2 --Andoyer method --- DIVIDE BY 10^6 FOR KM2
4027  if (binAreagrid < 0.000001)areabinBox[0][2] = 0.0;else areabinBox[0][2] = binAreagrid;
4028  /* cout<<"inside binIntersectsPix4corn.."<<"ws_lon.."<<ws_lon<<"ws_lat.."<<ws_lat<<endl;
4029  cout<<"inside binIntersectsPix4corn.."<<"wn_lon.."<<wn_lon<<"wn_lat.."<<wn_lat<<endl;
4030  cout<<"inside binIntersectsPix4corn.."<<"en_lon.."<<en_lon<<"en_lat.."<<en_lat<<endl;
4031  cout<<"inside binIntersectsPix4corn.."<<"es_lon.."<<es_lon<<"es_lat.."<<es_lat<<endl;*/
4032  // if(binAreagrid<0.000001) cout<<"binAreagrid<0.000001..[0][2]"<<endl;
4033 
4034  if (ingeom > 0) { //pixel fully inside the grid cell
4035  intersectArea = binAreapix;
4036  result = true;
4037  areaFracBox[0][2] = intersectArea / binAreagrid;
4038  // cout<<"pixel fully inside gricell [0][2].."<<endl;
4039  }
4040  else {
4041  if (!bg::disjoint(pixelPoly, gridPoly) && binAreagrid > 0) {
4042  std::deque<Polygon_t> output;
4043  if (bg::intersection(pixelPoly, gridPoly, output)) {
4044  BOOST_FOREACH(Polygon_t const& p, output)
4045  {
4046  intersectArea = bg::area(p);
4047  if (intersectArea > 0.0 && pc == 1) {
4048  result = true;
4049  areaFracBox[0][2] = intersectArea / binAreagrid;
4050  if (intersectArea / binAreagrid < 0.000001) areaFracBox[0][2] = 0.0;
4051  pc++;
4052  }
4053  }
4054  }
4055  }
4056  }//end else
4057 
4058 
4059  return result;
4060 
4061  }
4062 
4063 
4064  //modified method from l2bin-----
4065  //4 bounds in pixel--- polygon intersection
4066  bool L1C::binIntersectsPix4corn2(int32_t row, int32_t col, double** lat_cgd, double** lon_cgd, Polygon_t& pixelPoly, double areaFracBox[3][3]) {
4067  bool result = false;
4068  double ws_lat, wn_lat, es_lat, en_lat, ws_lon, wn_lon, es_lon, en_lon;
4069  bool ingeom = false;
4070  // shape->rowcol2bounds(row, col, n, s, e, w);
4071  int32_t rowc = 0, colc = 0;
4072  int pc = 1;
4073  double intersectArea = 0, binAreapix = 0, binAreagrid = 0.;
4074  std::string ws_lon_str, ws_lat_str, wn_lon_str, wn_lat_str, en_lon_str, en_lat_str, es_lon_str, es_lat_str, gridstr;
4075 
4076  rowc = row + 1;
4077  colc = col + 1;
4078 
4079  if (rowc < 0 || colc < 0) {
4080  cout << "ERROR ON binIntersectsPix4corn2...rowc or colc are negative for cornerlines.." << endl;
4081  exit(1);
4082 }
4083 
4084  ingeom = 0, binAreagrid = 0., binAreapix = 0, intersectArea = 0., pc = 1;
4085  //center center bin
4086  ws_lat = lat_cgd[rowc][colc];
4087  ws_lon = lon_cgd[rowc][colc];
4088  wn_lat = lat_cgd[rowc + 1][colc];
4089  wn_lon = lon_cgd[rowc + 1][colc];
4090  en_lat = lat_cgd[rowc + 1][colc + 1];
4091  en_lon = lon_cgd[rowc + 1][colc + 1];
4092  es_lat = lat_cgd[rowc][colc + 1];
4093  es_lon = lon_cgd[rowc][colc + 1];
4094 
4095 
4096  Polygon_t gridPoly;
4097 
4098  ws_lon_str = std::to_string(ws_lon);
4099  ws_lat_str = std::to_string(ws_lat);
4100  wn_lon_str = std::to_string(wn_lon);
4101  wn_lat_str = std::to_string(wn_lat);
4102  en_lon_str = std::to_string(en_lon);
4103  en_lat_str = std::to_string(en_lat);
4104  es_lon_str = std::to_string(es_lon);
4105  es_lat_str = std::to_string(es_lat);
4106  gridstr = "POLYGON((" + ws_lon_str + " " + ws_lat_str + "," + wn_lon_str + " " + wn_lat_str + "," + en_lon_str + " " + en_lat_str + "," + es_lon_str + " " + es_lat_str + "," + ws_lon_str + " " + ws_lat_str + "))";
4107  bg::read_wkt(gridstr, gridPoly);
4108 
4109  ingeom = within(pixelPoly, gridPoly);
4110  // cout<<"ingeom..center center."<<ingeom<<endl;
4111  binAreagrid = bg::area(gridPoly);
4112  binAreapix = bg::area(pixelPoly);//area in m2 --Andoyer method --- DIVIDE BY 10^6 FOR KM2
4113  // cout<<"binAreagrid.."<<binAreagrid<<"binAreagrid.."<<binAreagrid<<endl;
4114 
4115  if (ingeom > 0) { //pixel fully inside the grid cell
4116  // cout<<"pixel full inside gridcell-- binarea.."<<binArea<<endl;
4117  intersectArea = binAreapix;
4118  result = true;
4119  areaFracBox[1][1] = intersectArea / binAreagrid;
4120  }
4121  else {
4122  if (!bg::disjoint(pixelPoly, gridPoly) && binAreagrid > 0) {
4123  std::deque<Polygon_t> output;//this is a list
4124  if (bg::intersection(pixelPoly, gridPoly, output)) {
4125  // cout<<"partial pixel inside gridcell--binarea.."<<binAreagrid<<endl;
4126  BOOST_FOREACH(Polygon_t const& p, output)
4127  {
4128  intersectArea = bg::area(p);
4129  if (intersectArea > 0.0 && pc == 1) {
4130  result = true;
4131  areaFracBox[1][1] = intersectArea / binAreagrid;
4132  if (intersectArea / binAreagrid < 0.000001) areaFracBox[1][1] = 0.0;
4133  /* cout<<"binAreapix..."<<binAreapix<<"binAreagrid..."<<binAreagrid<<endl;
4134  cout<<"partial pixel inside gridcell--areaFracBox[1][1].."<<areaFracBox[1][1]<<endl;
4135  cout<<"inside binIntersectsPix4corn.."<<"ws_lon.."<<ws_lon<<"ws_lat.."<<ws_lat<<endl;
4136  cout<<"inside binIntersectsPix4corn.."<<"wn_lon.."<<wn_lon<<"wn_lat.."<<wn_lat<<endl;
4137  cout<<"inside binIntersectsPix4corn.."<<"en_lon.."<<en_lon<<"en_lat.."<<en_lat<<endl;
4138  cout<<"inside binIntersectsPix4corn.."<<"es_lon.."<<es_lon<<"es_lat.."<<es_lat<<endl;*/
4139  pc++;
4140  }
4141  }
4142  }
4143  }
4144  }//end else
4145 
4146  ingeom = 0, binAreagrid = 0., binAreapix = 0, intersectArea = 0., pc = 1;
4147 
4148  //left center bin
4149  ws_lat = lat_cgd[rowc][colc - 1];
4150  ws_lon = lon_cgd[rowc][colc - 1];
4151  wn_lat = lat_cgd[rowc + 1][colc - 1];
4152  wn_lon = lon_cgd[rowc + 1][colc - 1];
4153  en_lat = lat_cgd[rowc + 1][colc];
4154  en_lon = lon_cgd[rowc + 1][colc];
4155  es_lat = lat_cgd[rowc][colc];
4156  es_lon = lon_cgd[rowc][colc];
4157 
4158  ws_lon_str = std::to_string(ws_lon);
4159  ws_lat_str = std::to_string(ws_lat);
4160  wn_lon_str = std::to_string(wn_lon);
4161  wn_lat_str = std::to_string(wn_lat);
4162  en_lon_str = std::to_string(en_lon);
4163  en_lat_str = std::to_string(en_lat);
4164  es_lon_str = std::to_string(es_lon);
4165  es_lat_str = std::to_string(es_lat);
4166  gridstr = "POLYGON((" + ws_lon_str + " " + ws_lat_str + "," + wn_lon_str + " " + wn_lat_str + "," + en_lon_str + " " + en_lat_str + "," + es_lon_str + " " + es_lat_str + "," + ws_lon_str + " " + ws_lat_str + "))";
4167  bg::read_wkt(gridstr, gridPoly);
4168 
4169  ingeom = within(pixelPoly, gridPoly);
4170  // cout<<"ingeom..center.left "<<ingeom<<endl;
4171  binAreagrid = bg::area(gridPoly);
4172  binAreapix = bg::area(pixelPoly);//area in m2 --Andoyer method --- DIVIDE BY 10^6 FOR KM2
4173  // cout<<"binAreagrid.."<<binAreagrid<<"binAreagrid.."<<binAreagrid<<endl;
4174 
4175  if (ingeom > 0) { //pixel fully inside the grid cell
4176  // cout<<"pixel full inside gridcell-- binarea.."<<binArea<<endl;
4177  intersectArea = binAreapix;
4178  result = true;
4179  areaFracBox[1][0] = intersectArea / binAreagrid;
4180  }
4181  else {
4182  if (!bg::disjoint(pixelPoly, gridPoly) && binAreagrid > 0) {
4183  std::deque<Polygon_t> output;
4184  if (bg::intersection(pixelPoly, gridPoly, output)) {
4185  // cout<<"partial pixel inside gridcell--binarea.."<<binArea<<endl;
4186  BOOST_FOREACH(Polygon_t const& p, output)
4187  {
4188  intersectArea = bg::area(p);
4189  if (intersectArea > 0.0 && pc == 1) {
4190  result = true;
4191  areaFracBox[1][0] = intersectArea / binAreagrid;
4192  if (intersectArea / binAreagrid < 0.000001) areaFracBox[1][0] = 0.0;
4193  /* cout<<"binAreapix..."<<binAreapix<<"binAreagrid..."<<binAreagrid<<endl;
4194  cout<<"partial pixel inside gridcell--areaFracBox[1][0].."<<areaFracBox[1][0]<<endl;
4195  cout<<"inside binIntersectsPix4corn.."<<"ws_lon.."<<ws_lon<<"ws_lat.."<<ws_lat<<endl;
4196  cout<<"inside binIntersectsPix4corn.."<<"wn_lon.."<<wn_lon<<"wn_lat.."<<wn_lat<<endl;
4197  cout<<"inside binIntersectsPix4corn.."<<"en_lon.."<<en_lon<<"en_lat.."<<en_lat<<endl;
4198  cout<<"inside binIntersectsPix4corn.."<<"es_lon.."<<es_lon<<"es_lat.."<<es_lat<<endl;*/
4199  pc++;
4200  }
4201  }
4202  }
4203  }
4204  }//end else
4205 
4206  ingeom = 0, binAreagrid = 0., binAreapix = 0, intersectArea = 0.;
4207  //right center bin
4208  ws_lat = lat_cgd[rowc][colc + 1];
4209  ws_lon = lon_cgd[rowc][colc + 1];
4210  wn_lat = lat_cgd[rowc + 1][colc + 1];
4211  wn_lon = lon_cgd[rowc + 1][colc + 1];
4212  en_lat = lat_cgd[rowc + 1][colc + 2];
4213  en_lon = lon_cgd[rowc + 1][colc + 2];
4214  es_lat = lat_cgd[rowc][colc + 2];
4215  es_lon = lon_cgd[rowc][colc + 2];
4216 
4217  ws_lon_str = std::to_string(ws_lon);
4218  ws_lat_str = std::to_string(ws_lat);
4219  wn_lon_str = std::to_string(wn_lon);
4220  wn_lat_str = std::to_string(wn_lat);
4221  en_lon_str = std::to_string(en_lon);
4222  en_lat_str = std::to_string(en_lat);
4223  es_lon_str = std::to_string(es_lon);
4224  es_lat_str = std::to_string(es_lat);
4225  gridstr = "POLYGON((" + ws_lon_str + " " + ws_lat_str + "," + wn_lon_str + " " + wn_lat_str + "," + en_lon_str + " " + en_lat_str + "," + es_lon_str + " " + es_lat_str + "," + ws_lon_str + " " + ws_lat_str + "))";
4226  bg::read_wkt(gridstr, gridPoly);
4227 
4228  ingeom = within(pixelPoly, gridPoly);
4229  // cout<<"ingeom..center.right "<<ingeom<<endl;
4230  binAreagrid = bg::area(gridPoly);
4231  binAreapix = bg::area(pixelPoly);//area in m2 --Andoyer method --- DIVIDE BY 10^6 FOR KM2
4232  // cout<<"binAreagrid.."<<binAreagrid<<"binAreagrid.."<<binAreagrid<<endl;
4233 
4234  if (ingeom > 0) { //pixel fully inside the grid cell
4235  // cout<<"pixel full inside gridcell-- binarea.."<<binArea<<endl;
4236  intersectArea = binAreapix;
4237  result = true;
4238  areaFracBox[1][2] = intersectArea / binAreagrid;
4239  }
4240  else {
4241  if (!bg::disjoint(pixelPoly, gridPoly) && binAreagrid > 0.) {
4242  std::deque<Polygon_t> output;
4243  if (bg::intersection(pixelPoly, gridPoly, output)) {
4244  // cout<<"partial pixel inside gridcell--binarea.."<<binArea<<endl;
4245  BOOST_FOREACH(Polygon_t const& p, output)
4246  {
4247  intersectArea = bg::area(p);
4248  if (intersectArea > 0.0 && pc == 1) {
4249  result = true;
4250  areaFracBox[1][2] = intersectArea / binAreagrid;
4251  if (intersectArea / binAreagrid < 0.000001) areaFracBox[1][2] = 0.0;
4252  /* cout<<"binAreapix..."<<binAreapix<<"binAreagrid..."<<binAreagrid<<endl;
4253  cout<<"partial pixel inside gridcell--areaFracBox[1][2].."<<areaFracBox[1][2]<<endl;
4254  cout<<"inside binIntersectsPix4corn.."<<"ws_lon.."<<ws_lon<<"ws_lat.."<<ws_lat<<endl;
4255  cout<<"inside binIntersectsPix4corn.."<<"wn_lon.."<<wn_lon<<"wn_lat.."<<wn_lat<<endl;
4256  cout<<"inside binIntersectsPix4corn.."<<"en_lon.."<<en_lon<<"en_lat.."<<en_lat<<endl;
4257  cout<<"inside binIntersectsPix4corn.."<<"es_lon.."<<es_lon<<"es_lat.."<<es_lat<<endl;*/
4258  pc++;
4259  }
4260  }
4261  }
4262  }
4263  }//end else
4264  ingeom = 0, binAreagrid = 0., binAreapix = 0, intersectArea = 0., pc = 1;
4265  //upper center bin
4266  ws_lat = lat_cgd[rowc + 1][colc];
4267  ws_lon = lon_cgd[rowc + 1][colc];
4268  wn_lat = lat_cgd[rowc + 2][colc];
4269  wn_lon = lon_cgd[rowc + 2][colc];
4270  en_lat = lat_cgd[rowc + 2][colc + 1];
4271  en_lon = lon_cgd[rowc + 2][colc + 1];
4272  es_lat = lat_cgd[rowc + 1][colc + 1];
4273  es_lon = lon_cgd[rowc + 1][colc + 1];
4274 
4275  ws_lon_str = std::to_string(ws_lon);
4276  ws_lat_str = std::to_string(ws_lat);
4277  wn_lon_str = std::to_string(wn_lon);
4278  wn_lat_str = std::to_string(wn_lat);
4279  en_lon_str = std::to_string(en_lon);
4280  en_lat_str = std::to_string(en_lat);
4281  es_lon_str = std::to_string(es_lon);
4282  es_lat_str = std::to_string(es_lat);
4283  gridstr = "POLYGON((" + ws_lon_str + " " + ws_lat_str + "," + wn_lon_str + " " + wn_lat_str + "," + en_lon_str + " " + en_lat_str + "," + es_lon_str + " " + es_lat_str + "," + ws_lon_str + " " + ws_lat_str + "))";
4284  bg::read_wkt(gridstr, gridPoly);
4285 
4286  ingeom = within(pixelPoly, gridPoly);
4287  // cout<<"ingeom..upper .center"<<ingeom<<endl;
4288  binAreagrid = bg::area(gridPoly);
4289  binAreapix = bg::area(pixelPoly);//area in m2 --Andoyer method --- DIVIDE BY 10^6 FOR KM2
4290  // cout<<"binAreagrid.."<<binAreagrid<<"binAreagrid.."<<binAreagrid<<endl;
4291 
4292  if (ingeom > 0) { //pixel fully inside the grid cell
4293  // cout<<"pixel full inside gridcell-- binarea.."<<binArea<<endl;
4294  intersectArea = binAreapix;
4295  result = true;
4296  areaFracBox[2][1] = intersectArea / binAreagrid;
4297  }
4298  else {
4299  if (!bg::disjoint(pixelPoly, gridPoly) && binAreagrid > 0) {
4300  std::deque<Polygon_t> output;
4301  if (bg::intersection(pixelPoly, gridPoly, output)) {
4302  // cout<<"partial pixel inside gridcell--binarea.."<<binArea<<endl;
4303  BOOST_FOREACH(Polygon_t const& p, output)
4304  {
4305  intersectArea = bg::area(p);
4306  if (intersectArea > 0.0 && pc == 1) {
4307  result = true;
4308  areaFracBox[2][1] = intersectArea / binAreagrid;
4309  if (intersectArea / binAreagrid < 0.000001) areaFracBox[2][1] = 0.0;
4310  /* cout<<"binAreapix..."<<binAreapix<<"binAreagrid..."<<binAreagrid<<endl;
4311  cout<<"partial pixel inside gridcell--areaFracBox[2][1].."<<areaFracBox[2][1]<<endl;
4312  cout<<"inside binIntersectsPix4corn.."<<"ws_lon.."<<ws_lon<<"ws_lat.."<<ws_lat<<endl;
4313  cout<<"inside binIntersectsPix4corn.."<<"wn_lon.."<<wn_lon<<"wn_lat.."<<wn_lat<<endl;
4314  cout<<"inside binIntersectsPix4corn.."<<"en_lon.."<<en_lon<<"en_lat.."<<en_lat<<endl;
4315  cout<<"inside binIntersectsPix4corn.."<<"es_lon.."<<es_lon<<"es_lat.."<<es_lat<<endl;*/
4316  pc++;
4317  }
4318  }
4319  }
4320  }
4321  }//end else
4322 
4323  ingeom = 0, binAreagrid = 0., binAreapix = 0, intersectArea = 0., pc = 1;
4324  //upper left bin
4325  ws_lat = lat_cgd[rowc + 1][colc - 1];
4326  ws_lon = lon_cgd[rowc + 1][colc - 1];
4327  wn_lat = lat_cgd[rowc + 2][colc - 1];
4328  wn_lon = lon_cgd[rowc + 2][colc - 1];
4329  en_lat = lat_cgd[rowc + 2][colc];
4330  en_lon = lon_cgd[rowc + 2][colc];
4331  es_lat = lat_cgd[rowc + 1][colc];
4332  es_lon = lon_cgd[rowc + 1][colc];
4333 
4334  ws_lon_str = std::to_string(ws_lon);
4335  ws_lat_str = std::to_string(ws_lat);
4336  wn_lon_str = std::to_string(wn_lon);
4337  wn_lat_str = std::to_string(wn_lat);
4338  en_lon_str = std::to_string(en_lon);
4339  en_lat_str = std::to_string(en_lat);
4340  es_lon_str = std::to_string(es_lon);
4341  es_lat_str = std::to_string(es_lat);
4342  gridstr = "POLYGON((" + ws_lon_str + " " + ws_lat_str + "," + wn_lon_str + " " + wn_lat_str + "," + en_lon_str + " " + en_lat_str + "," + es_lon_str + " " + es_lat_str + "," + ws_lon_str + " " + ws_lat_str + "))";
4343  bg::read_wkt(gridstr, gridPoly);
4344 
4345  ingeom = within(pixelPoly, gridPoly);
4346  // cout<<"ingeom..upper left "<<ingeom<<endl;
4347  binAreagrid = bg::area(gridPoly);
4348  binAreapix = bg::area(pixelPoly);//area in m2 --Andoyer method --- DIVIDE BY 10^6 FOR KM2
4349  // cout<<"binAreagrid.."<<binAreagrid<<"binAreagrid.."<<binAreagrid<<endl;
4350 
4351  if (ingeom > 0) { //pixel fully inside the grid cell
4352  // cout<<"pixel full inside gridcell-- binarea.."<<binArea<<endl;
4353  intersectArea = binAreapix;
4354  result = true;
4355  areaFracBox[2][0] = intersectArea / binAreagrid;
4356  }
4357  else {
4358  if (!bg::disjoint(pixelPoly, gridPoly) && binAreagrid > 0) {
4359  std::deque<Polygon_t> output;
4360  if (bg::intersection(pixelPoly, gridPoly, output)) {
4361  // cout<<"partial pixel inside gridcell--binarea.."<<binArea<<endl;
4362  BOOST_FOREACH(Polygon_t const& p, output)
4363  {
4364  intersectArea = bg::area(p);
4365  if (intersectArea > 0.0 && pc == 1) {
4366  result = true;
4367  areaFracBox[2][0] = intersectArea / binAreagrid;
4368  if (intersectArea / binAreagrid < 0.000001) areaFracBox[2][0] = 0.0;
4369 
4370  /* cout<<"binAreapix..."<<binAreapix<<"binAreagrid..."<<binAreagrid<<endl;
4371  cout<<"partial pixel inside gridcell--areaFracBox[2][0].."<<areaFracBox[2][0]<<endl;
4372  cout<<"inside binIntersectsPix4corn.."<<"ws_lon.."<<ws_lon<<"ws_lat.."<<ws_lat<<endl;
4373  cout<<"inside binIntersectsPix4corn.."<<"wn_lon.."<<wn_lon<<"wn_lat.."<<wn_lat<<endl;
4374  cout<<"inside binIntersectsPix4corn.."<<"en_lon.."<<en_lon<<"en_lat.."<<en_lat<<endl;
4375  cout<<"inside binIntersectsPix4corn.."<<"es_lon.."<<es_lon<<"es_lat.."<<es_lat<<endl;*/
4376  pc++;
4377  }
4378  }
4379  }
4380  }
4381  }//end else
4382  ingeom = 0, binAreagrid = 0., binAreapix = 0, intersectArea = 0., pc = 1;
4383  //upper right bin
4384  ws_lat = lat_cgd[rowc + 1][colc + 1];
4385  ws_lon = lon_cgd[rowc + 1][colc + 1];
4386  wn_lat = lat_cgd[rowc + 2][colc + 1];
4387  wn_lon = lon_cgd[rowc + 2][colc + 1];
4388  en_lat = lat_cgd[rowc + 2][colc + 2];
4389  en_lon = lon_cgd[rowc + 2][colc + 2];
4390  es_lat = lat_cgd[rowc + 1][colc + 2];
4391  es_lon = lon_cgd[rowc + 1][colc + 2];
4392 
4393  ws_lon_str = std::to_string(ws_lon);
4394  ws_lat_str = std::to_string(ws_lat);
4395  wn_lon_str = std::to_string(wn_lon);
4396  wn_lat_str = std::to_string(wn_lat);
4397  en_lon_str = std::to_string(en_lon);
4398  en_lat_str = std::to_string(en_lat);
4399  es_lon_str = std::to_string(es_lon);
4400  es_lat_str = std::to_string(es_lat);
4401  gridstr = "POLYGON((" + ws_lon_str + " " + ws_lat_str + "," + wn_lon_str + " " + wn_lat_str + "," + en_lon_str + " " + en_lat_str + "," + es_lon_str + " " + es_lat_str + "," + ws_lon_str + " " + ws_lat_str + "))";
4402  bg::read_wkt(gridstr, gridPoly);
4403 
4404  ingeom = within(pixelPoly, gridPoly);
4405  // cout<<"ingeom..upper.right"<<ingeom<<endl;
4406  binAreagrid = bg::area(gridPoly);
4407  binAreapix = bg::area(pixelPoly);//area in m2 --Andoyer method --- DIVIDE BY 10^6 FOR KM2
4408  // cout<<"binAreagrid.."<<binAreagrid<<"binAreagrid.."<<binAreagrid<<endl;
4409 
4410  if (ingeom > 0) { //pixel fully inside the grid cell
4411  // cout<<"pixel full inside gridcell-- binarea.."<<binArea<<endl;
4412  intersectArea = binAreapix;
4413  result = true;
4414  areaFracBox[2][2] = intersectArea / binAreagrid;
4415  }
4416  else {
4417  if (!bg::disjoint(pixelPoly, gridPoly) && binAreagrid > 0) {
4418  std::deque<Polygon_t> output;
4419  if (bg::intersection(pixelPoly, gridPoly, output)) {
4420  // cout<<"partial pixel inside gridcell--binarea.."<<binArea<<endl;
4421  BOOST_FOREACH(Polygon_t const& p, output)
4422  {
4423  intersectArea = bg::area(p);
4424  if (intersectArea > 0.0 && pc == 1) {
4425  result = true;
4426  areaFracBox[2][2] = intersectArea / binAreagrid;
4427  if (intersectArea / binAreagrid < 0.000001) areaFracBox[2][2] = 0.0;
4428 
4429  /* cout<<"binAreapix..."<<binAreapix<<"binAreagrid..."<<binAreagrid<<endl;
4430  cout<<"partial pixel inside gridcell--areaFracBox[2][2].."<<areaFracBox[2][2]<<endl;
4431  cout<<"inside binIntersectsPix4corn.."<<"ws_lon.."<<ws_lon<<"ws_lat.."<<ws_lat<<endl;
4432  cout<<"inside binIntersectsPix4corn.."<<"wn_lon.."<<wn_lon<<"wn_lat.."<<wn_lat<<endl;
4433  cout<<"inside binIntersectsPix4corn.."<<"en_lon.."<<en_lon<<"en_lat.."<<en_lat<<endl;
4434  cout<<"inside binIntersectsPix4corn.."<<"es_lon.."<<es_lon<<"es_lat.."<<es_lat<<endl;*/
4435  pc++;
4436  }
4437  }
4438  }
4439  }
4440  }//end else
4441 
4442  ingeom = 0, binAreagrid = 0., binAreapix = 0, intersectArea = 0., pc = 1;
4443  //lower center bin
4444  ws_lat = lat_cgd[rowc - 1][colc];
4445  ws_lon = lon_cgd[rowc - 1][colc];
4446  wn_lat = lat_cgd[rowc][colc];
4447  wn_lon = lon_cgd[rowc][colc];
4448  en_lat = lat_cgd[rowc][colc + 1];
4449  en_lon = lon_cgd[rowc][colc + 1];
4450  es_lat = lat_cgd[rowc - 1][colc + 1];
4451  es_lon = lon_cgd[rowc - 1][colc + 1];
4452 
4453  ws_lon_str = std::to_string(ws_lon);
4454  ws_lat_str = std::to_string(ws_lat);
4455  wn_lon_str = std::to_string(wn_lon);
4456  wn_lat_str = std::to_string(wn_lat);
4457  en_lon_str = std::to_string(en_lon);
4458  en_lat_str = std::to_string(en_lat);
4459  es_lon_str = std::to_string(es_lon);
4460  es_lat_str = std::to_string(es_lat);
4461  gridstr = "POLYGON((" + ws_lon_str + " " + ws_lat_str + "," + wn_lon_str + " " + wn_lat_str + "," + en_lon_str + " " + en_lat_str + "," + es_lon_str + " " + es_lat_str + "," + ws_lon_str + " " + ws_lat_str + "))";
4462  bg::read_wkt(gridstr, gridPoly);
4463 
4464  ingeom = within(pixelPoly, gridPoly);
4465  // cout<<"ingeom..lower. center"<<ingeom<<endl;
4466  binAreagrid = bg::area(gridPoly);
4467  binAreapix = bg::area(pixelPoly);//area in m2 --Andoyer method --- DIVIDE BY 10^6 FOR KM2
4468  // cout<<"binAreagrid.."<<binAreagrid<<"binAreapix.."<<binAreapix<<endl;
4469 
4470  /* cout<<"inside binIntersectsPix4corn.."<<"ws_lon.."<<ws_lon<<"ws_lat.."<<ws_lat<<endl;
4471  cout<<"inside binIntersectsPix4corn.."<<"wn_lon.."<<wn_lon<<"wn_lat.."<<wn_lat<<endl;
4472  cout<<"inside binIntersectsPix4corn.."<<"en_lon.."<<en_lon<<"en_lat.."<<en_lat<<endl;
4473  cout<<"inside binIntersectsPix4corn.."<<"es_lon.."<<es_lon<<"es_lat.."<<es_lat<<endl;
4474  */
4475 
4476  if (ingeom > 0) { //pixel fully inside the grid cell
4477  // cout<<"pixel full inside gridcell-- binarea.."<<binArea<<endl;
4478  intersectArea = binAreapix;
4479  result = true;
4480  areaFracBox[0][1] = intersectArea / binAreagrid;
4481  }
4482  else {
4483  if (!bg::disjoint(pixelPoly, gridPoly) && binAreagrid > 0) {
4484  std::deque<Polygon_t> output;
4485  if (bg::intersection(pixelPoly, gridPoly, output)) {
4486  // cout<<"partial pixel inside gridcell--binarea.."<<binArea<<endl;
4487  BOOST_FOREACH(Polygon_t const& p, output)
4488  {
4489  intersectArea = bg::area(p);
4490  if (intersectArea > 0.0 && pc == 1) {
4491  result = true;
4492  areaFracBox[0][1] = intersectArea / binAreagrid;
4493  if (intersectArea / binAreagrid < 0.000001) areaFracBox[0][1] = 0.0;
4494 
4495  /* cout<<"binAreapix..."<<binAreapix<<"binAreagrid..."<<binAreagrid<<endl;
4496  cout<<"partial pixel inside gridcell--areaFracBox[0][1].."<<areaFracBox[0][1]<<endl;
4497  cout<<"inside binIntersectsPix4corn.."<<"ws_lon.."<<ws_lon<<"ws_lat.."<<ws_lat<<endl;
4498  cout<<"inside binIntersectsPix4corn.."<<"wn_lon.."<<wn_lon<<"wn_lat.."<<wn_lat<<endl;
4499  cout<<"inside binIntersectsPix4corn.."<<"en_lon.."<<en_lon<<"en_lat.."<<en_lat<<endl;
4500  cout<<"inside binIntersectsPix4corn.."<<"es_lon.."<<es_lon<<"es_lat.."<<es_lat<<endl;*/
4501  pc++;
4502  }
4503  }
4504  }
4505  }
4506  }//end else
4507  ingeom = 0, binAreagrid = 0., binAreapix = 0, intersectArea = 0., pc = 1;
4508  //lower left bin
4509  ws_lat = lat_cgd[rowc - 1][colc - 1];
4510  ws_lon = lon_cgd[rowc - 1][colc - 1];
4511  wn_lat = lat_cgd[rowc][colc - 1];
4512  wn_lon = lon_cgd[rowc][colc - 1];
4513  en_lat = lat_cgd[rowc][colc];
4514  en_lon = lon_cgd[rowc][colc];
4515  es_lat = lat_cgd[rowc - 1][colc];
4516  es_lon = lon_cgd[rowc - 1][colc];
4517 
4518  ws_lon_str = std::to_string(ws_lon);
4519  ws_lat_str = std::to_string(ws_lat);
4520  wn_lon_str = std::to_string(wn_lon);
4521  wn_lat_str = std::to_string(wn_lat);
4522  en_lon_str = std::to_string(en_lon);
4523  en_lat_str = std::to_string(en_lat);
4524  es_lon_str = std::to_string(es_lon);
4525  es_lat_str = std::to_string(es_lat);
4526  gridstr = "POLYGON((" + ws_lon_str + " " + ws_lat_str + "," + wn_lon_str + " " + wn_lat_str + "," + en_lon_str + " " + en_lat_str + "," + es_lon_str + " " + es_lat_str + "," + ws_lon_str + " " + ws_lat_str + "))";
4527  bg::read_wkt(gridstr, gridPoly);
4528 
4529 
4530  ingeom = within(pixelPoly, gridPoly);
4531  // cout<<"ingeom..lower.left"<<ingeom<<endl;
4532  binAreagrid = bg::area(gridPoly);
4533  binAreapix = bg::area(pixelPoly);//area in m2 --Andoyer method --- DIVIDE BY 10^6 FOR KM2
4534  // cout<<"binAreagrid.."<<binAreagrid<<"binAreapix.."<<binAreapix<<endl;
4535 
4536  if (ingeom > 0) { //pixel fully inside the grid cell
4537  // cout<<"pixel full inside gridcell-- binarea.."<<binArea<<endl;
4538  intersectArea = binAreapix;
4539  result = true;
4540  areaFracBox[0][0] = intersectArea / binAreagrid;
4541  }
4542  else {
4543  if (!bg::disjoint(pixelPoly, gridPoly) && binAreagrid > 0) {
4544  std::deque<Polygon_t> output;
4545  if (bg::intersection(pixelPoly, gridPoly, output)) {
4546  // cout<<"partial pixel inside gridcell--binarea.."<<binArea<<endl;
4547  BOOST_FOREACH(Polygon_t const& p, output)
4548  {
4549  intersectArea = bg::area(p);
4550  if (intersectArea > 0.0 && pc == 1) {
4551  result = true;
4552  areaFracBox[0][0] = intersectArea / binAreagrid;
4553  if (intersectArea / binAreagrid < 0.000001) areaFracBox[0][0] = 0.0;
4554 
4555  /* cout<<"binAreapix..."<<binAreapix<<"binAreagrid..."<<binAreagrid<<endl;
4556  cout<<"partial pixel inside gridcell--areaFracBox[0][0].."<<areaFracBox[0][0]<<endl;
4557  cout<<"inside binIntersectsPix4corn.."<<"ws_lon.."<<ws_lon<<"ws_lat.."<<ws_lat<<endl;
4558  cout<<"inside binIntersectsPix4corn.."<<"wn_lon.."<<wn_lon<<"wn_lat.."<<wn_lat<<endl;
4559  cout<<"inside binIntersectsPix4corn.."<<"en_lon.."<<en_lon<<"en_lat.."<<en_lat<<endl;
4560  cout<<"inside binIntersectsPix4corn.."<<"es_lon.."<<es_lon<<"es_lat.."<<es_lat<<endl;*/
4561  pc++;
4562  }
4563  }
4564  }
4565  }
4566  }//end else
4567  ingeom = 0, binAreagrid = 0, binAreapix = 0, intersectArea = 0., pc = 1;
4568  //lower right bin
4569  ws_lat = lat_cgd[rowc - 1][colc + 1];
4570  ws_lon = lon_cgd[rowc - 1][colc + 1];
4571  wn_lat = lat_cgd[rowc][colc + 1];
4572  wn_lon = lon_cgd[rowc][colc + 1];
4573  en_lat = lat_cgd[rowc][colc + 2];
4574  en_lon = lon_cgd[rowc][colc + 2];
4575  es_lat = lat_cgd[rowc - 1][colc + 2];
4576  es_lon = lon_cgd[rowc - 1][colc + 2];
4577 
4578  ws_lon_str = std::to_string(ws_lon);
4579  ws_lat_str = std::to_string(ws_lat);
4580  wn_lon_str = std::to_string(wn_lon);
4581  wn_lat_str = std::to_string(wn_lat);
4582  en_lon_str = std::to_string(en_lon);
4583  en_lat_str = std::to_string(en_lat);
4584  es_lon_str = std::to_string(es_lon);
4585  es_lat_str = std::to_string(es_lat);
4586  gridstr = "POLYGON((" + ws_lon_str + " " + ws_lat_str + "," + wn_lon_str + " " + wn_lat_str + "," + en_lon_str + " " + en_lat_str + "," + es_lon_str + " " + es_lat_str + "," + ws_lon_str + " " + ws_lat_str + "))";
4587  bg::read_wkt(gridstr, gridPoly);
4588 
4589  ingeom = within(pixelPoly, gridPoly);
4590  // cout<<"ingeom..lower.right "<<ingeom<<endl;
4591  binAreagrid = bg::area(gridPoly);
4592  binAreapix = bg::area(pixelPoly);//area in m2 --Andoyer method --- DIVIDE BY 10^6 FOR KM2
4593  // cout<<"binAreagrid.."<<binAreagrid<<"binAreapix.."<<binAreapix<<endl;
4594 
4595  if (ingeom > 0) { //pixel fully inside the grid cell
4596  // cout<<"pixel full inside gridcell-- binarea.."<<binArea<<endl;
4597  intersectArea = binAreapix;
4598  result = true;
4599  areaFracBox[0][2] = intersectArea / binAreagrid;
4600  }
4601  else {
4602  if (!bg::disjoint(pixelPoly, gridPoly) && binAreagrid > 0) {
4603  std::deque<Polygon_t> output;
4604  if (bg::intersection(pixelPoly, gridPoly, output)) {
4605  // cout<<"partial pixel inside gridcell--binarea.."<<binArea<<endl;
4606  BOOST_FOREACH(Polygon_t const& p, output)
4607  {
4608  intersectArea = bg::area(p);
4609  if (intersectArea > 0.0 && pc == 1) {
4610  result = true;
4611  areaFracBox[0][2] = intersectArea / binAreagrid;
4612  if (intersectArea / binAreagrid < 0.000001) areaFracBox[0][2] = 0.0;
4613 
4614  /* cout<<"binAreapix..."<<binAreapix<<"binAreagrid..."<<binAreagrid<<endl;
4615  cout<<"partial pixel inside gridcell--areaFracBox[0][2].."<<areaFracBox[0][2]<<endl;
4616  cout<<"inside binIntersectsPix4corn.."<<"ws_lon.."<<ws_lon<<"ws_lat.."<<ws_lat<<endl;
4617  cout<<"inside binIntersectsPix4corn.."<<"wn_lon.."<<wn_lon<<"wn_lat.."<<wn_lat<<endl;
4618  cout<<"inside binIntersectsPix4corn.."<<"en_lon.."<<en_lon<<"en_lat.."<<en_lat<<endl;
4619  cout<<"inside binIntersectsPix4corn.."<<"es_lon.."<<es_lon<<"es_lat.."<<es_lat<<endl;*/
4620  pc++;
4621  }
4622  }
4623  }
4624  }
4625  }//end else
4626 
4627 
4628  return result;
4629  }
4630 
4631 
4632 
4633  bool L1C::binIntersectsPix4corn(int32_t row, int32_t col, double** lat_cgd, double** lon_cgd, Polygon_t& pixelPoly, double& areaFrac) {
4634  bool result = false;
4635  float ws_lat, wn_lat, es_lat, en_lat, ws_lon, wn_lon, es_lon, en_lon;
4636  // shape->rowcol2bounds(row, col, n, s, e, w);
4637  ws_lat = lat_cgd[row][col];
4638  ws_lon = lon_cgd[row][col];
4639  wn_lat = lat_cgd[row + 1][col];
4640  wn_lon = lon_cgd[row + 1][col];
4641  en_lat = lat_cgd[row + 1][col + 1];
4642  en_lon = lon_cgd[row + 1][col + 1];
4643  es_lat = lat_cgd[row][col + 1];
4644  es_lon = lon_cgd[row][col + 1];
4645 
4646  // Box_t box(Point_t(w,s), Point_t(e,n));
4647  Polygon_t gridPoly;
4648  bg::append(gridPoly.outer(), Point_t(ws_lon, ws_lat));
4649  bg::append(gridPoly.outer(), Point_t(wn_lon, wn_lat));
4650  bg::append(gridPoly.outer(), Point_t(en_lon, en_lat));
4651  bg::append(gridPoly.outer(), Point_t(es_lon, es_lat));
4652  bg::append(gridPoly.outer(), Point_t(ws_lon, ws_lat));
4653 
4654  cout << "inside binIntersectsPix4corn.." << "ws_lon.." << ws_lon << "ws_lat.." << ws_lat << endl;
4655  cout << "inside binIntersectsPix4corn.." << "wn_lon.." << wn_lon << "wn_lat.." << wn_lat << endl;
4656  cout << "inside binIntersectsPix4corn.." << "en_lon.." << en_lon << "en_lat.." << en_lat << endl;
4657  cout << "inside binIntersectsPix4corn.." << "es_lon.." << es_lon << "es_lat.." << es_lat << endl;
4658 
4659  areaFrac = 0;
4660 
4661  if (!bg::disjoint(gridPoly, pixelPoly)) {
4662  std::deque<Polygon_t> output;
4663  if (bg::intersection(pixelPoly, gridPoly, output)) {
4664  // double binArea = (n-s) * (e-w);
4665  double binArea = bg::area(gridPoly);
4666  cout << "binarea.." << binArea << endl;
4667 
4668  BOOST_FOREACH(Polygon_t const& p, output)
4669  {
4670  double intersectArea = bg::area(p);
4671  if (intersectArea > 0.0) {
4672  result = true;
4673  areaFrac += intersectArea / binArea;
4674  }
4675  }
4676  }
4677  }
4678  return result;
4679  }
4680 
4681  //modified method from l2bin-----
4682  //2 bounds in pixel
4683  //original modified nIntersectsPixelbinIntersectsPixel with grid L1C mask of 3x3 bins
4684 
4685  bool L1C::binIntersectsPix2corn2(int32_t row, int32_t col, double** lat_cgd, double** lon_cgd, Box_t& pixelBox, double areaFracBox[3][3]) {
4686  bool result = false;
4687  double n, s, e, w;
4688  int ar = 0, ac = 0;
4689 
4690  Box_t gridBox;
4691  bool ingeom;
4692 
4693  //TEST
4694  s = -75.8635;
4695  w = -132.772;
4696  n = -75.8245;
4697  e = -132.616;
4698 
4699  pixelBox.min_corner().set<0>(w);
4700  pixelBox.min_corner().set<1>(s);
4701  pixelBox.max_corner().set<0>(e);
4702  pixelBox.max_corner().set<1>(n);
4703  //center
4704  s = lat_cgd[row][col];
4705  n = lat_cgd[row + 1][col + 1];
4706  w = lon_cgd[row][col];
4707  e = lon_cgd[row + 1][col + 1];
4708 
4709  gridBox.min_corner().set<0>(w);
4710  gridBox.min_corner().set<1>(s);
4711  gridBox.max_corner().set<0>(e);
4712  gridBox.max_corner().set<1>(n);
4713 
4714  ingeom = within(pixelBox, gridBox);
4715  cout << "ingeom..center." << ingeom << "n.." << n << "s.." << s << "w.." << w << "e.." << e << endl;
4716 
4717  if (!bg::disjoint(pixelBox, gridBox)) {
4718  Box_t output;
4719  if (bg::intersection(pixelBox, gridBox, output)) {
4720  double intersectArea = bg::area(output);
4721  if (intersectArea > 0) {
4722  result = true;
4723  double binArea = (n - s) * (e - w);
4724  areaFracBox[1][1] = intersectArea / binArea;
4725  if (intersectArea / binArea < 0.000001) areaFracBox[ar][ac] = 0.0;
4726  }
4727  }
4728  }
4729 
4730 
4731  //left
4732  s = lat_cgd[row][col - 1];
4733  n = lat_cgd[row + 1][col];
4734  w = lon_cgd[row][col - 1];
4735  e = lon_cgd[row + 1][col];
4736 
4737  gridBox.min_corner().set<0>(w);
4738  gridBox.min_corner().set<1>(s);
4739  gridBox.max_corner().set<0>(e);
4740  gridBox.max_corner().set<1>(n);
4741 
4742  ingeom = within(pixelBox, gridBox);
4743  cout << "ingeom..left." << ingeom << "n.." << n << "s.." << s << "w.." << w << "e.." << e << endl;
4744 
4745  if (!bg::disjoint(pixelBox, gridBox)) {
4746  Box_t output;
4747  if (bg::intersection(pixelBox, gridBox, output)) {
4748  double intersectArea = bg::area(output);
4749  if (intersectArea > 0) {
4750  result = true;
4751  double binArea = (n - s) * (e - w);
4752  areaFracBox[1][0] = intersectArea / binArea;
4753  if (intersectArea / binArea < 0.000001) areaFracBox[ar][ac] = 0.0;
4754  }
4755  }
4756  }
4757  //right
4758  s = lat_cgd[row][col + 1];
4759  n = lat_cgd[row + 1][col + 2];
4760  w = lon_cgd[row][col + 1];
4761  e = lon_cgd[row + 1][col + 2];
4762 
4763  gridBox.min_corner().set<0>(w);
4764  gridBox.min_corner().set<1>(s);
4765  gridBox.max_corner().set<0>(e);
4766  gridBox.max_corner().set<1>(n);
4767 
4768  ingeom = within(pixelBox, gridBox);
4769  cout << "ingeom..right." << ingeom << "n.." << n << "s.." << s << "w.." << w << "e.." << e << endl;
4770  if (!bg::disjoint(pixelBox, gridBox)) {
4771  Box_t output;
4772  if (bg::intersection(pixelBox, gridBox, output)) {
4773  double intersectArea = bg::area(output);
4774  if (intersectArea > 0) {
4775  result = true;
4776  double binArea = (n - s) * (e - w);
4777  areaFracBox[1][2] = intersectArea / binArea;
4778  if (intersectArea / binArea < 0.000001) areaFracBox[ar][ac] = 0.0;
4779  }
4780  }
4781  }
4782 
4783  //up center
4784  s = lat_cgd[row + 1][col];
4785  n = lat_cgd[row + 2][col + 1];
4786  w = lon_cgd[row + 1][col];
4787  e = lon_cgd[row + 2][col + 1];
4788 
4789  gridBox.min_corner().set<0>(w);
4790  gridBox.min_corner().set<1>(s);
4791  gridBox.max_corner().set<0>(e);
4792  gridBox.max_corner().set<1>(n);
4793 
4794  ingeom = within(pixelBox, gridBox);
4795  cout << "ingeom..upcenter." << ingeom << "n.." << n << "s.." << s << "w.." << w << "e.." << e << endl;
4796  if (!bg::disjoint(pixelBox, gridBox)) {
4797  Box_t output;
4798  if (bg::intersection(pixelBox, gridBox, output)) {
4799  double intersectArea = bg::area(output);
4800  if (intersectArea > 0) {
4801  result = true;
4802  double binArea = (n - s) * (e - w);
4803  areaFracBox[2][1] = intersectArea / binArea;
4804  if (intersectArea / binArea < 0.000001) areaFracBox[ar][ac] = 0.0;
4805  }
4806  }
4807  }
4808 
4809  //up left
4810  s = lat_cgd[row + 1][col - 1];
4811  n = lat_cgd[row + 2][col];
4812  w = lon_cgd[row + 1][col - 1];
4813  e = lon_cgd[row + 2][col];
4814  gridBox.min_corner().set<0>(w);
4815  gridBox.min_corner().set<1>(s);
4816  gridBox.max_corner().set<0>(e);
4817  gridBox.max_corner().set<1>(n);
4818 
4819  ingeom = within(pixelBox, gridBox);
4820  cout << "ingeom..upleft." << ingeom << "n.." << n << "s.." << s << "w.." << w << "e.." << e << endl;
4821  if (!bg::disjoint(pixelBox, gridBox)) {
4822  Box_t output;
4823  if (bg::intersection(pixelBox, gridBox, output)) {
4824  double intersectArea = bg::area(output);
4825  if (intersectArea > 0) {
4826  result = true;
4827  double binArea = (n - s) * (e - w);
4828  areaFracBox[2][0] = intersectArea / binArea;
4829  if (intersectArea / binArea < 0.000001) areaFracBox[ar][ac] = 0.0;
4830  }
4831  }
4832  }
4833 
4834  //upright
4835  s = lat_cgd[row + 1][col + 1];
4836  n = lat_cgd[row + 2][col + 2];
4837  w = lon_cgd[row + 1][col + 1];
4838  e = lon_cgd[row + 2][col + 2];
4839  gridBox.min_corner().set<0>(w);
4840  gridBox.min_corner().set<1>(s);
4841  gridBox.max_corner().set<0>(e);
4842  gridBox.max_corner().set<1>(n);
4843 
4844  ingeom = within(pixelBox, gridBox);
4845  cout << "ingeom..upright." << ingeom << "n.." << n << "s.." << s << "w.." << w << "e.." << e << endl;
4846  if (!bg::disjoint(pixelBox, gridBox)) {
4847  Box_t output;
4848  if (bg::intersection(pixelBox, gridBox, output)) {
4849  double intersectArea = bg::area(output);
4850  if (intersectArea > 0) {
4851  result = true;
4852  double binArea = (n - s) * (e - w);
4853  areaFracBox[2][2] = intersectArea / binArea;
4854  if (intersectArea / binArea < 0.000001) areaFracBox[ar][ac] = 0.0;
4855  }
4856  }
4857  }
4858 
4859 
4860  //down center
4861  s = lat_cgd[row - 1][col];
4862  n = lat_cgd[row][col + 1];
4863  w = lon_cgd[row - 1][col];
4864  e = lon_cgd[row][col + 1];
4865 
4866  gridBox.min_corner().set<0>(w);
4867  gridBox.min_corner().set<1>(s);
4868  gridBox.max_corner().set<0>(e);
4869  gridBox.max_corner().set<1>(n);
4870  ingeom = within(pixelBox, gridBox);
4871  cout << "ingeom..downcenter." << ingeom << "n.." << n << "s.." << s << "w.." << w << "e.." << e << endl;
4872  if (!bg::disjoint(pixelBox, gridBox)) {
4873  Box_t output;
4874  if (bg::intersection(pixelBox, gridBox, output)) {
4875  double intersectArea = bg::area(output);
4876  if (intersectArea > 0) {
4877  result = true;
4878  double binArea = (n - s) * (e - w);
4879  areaFracBox[0][1] = intersectArea / binArea;
4880  if (intersectArea / binArea < 0.000001) areaFracBox[ar][ac] = 0.0;
4881  }
4882  }
4883  }
4884 
4885  //down left
4886  s = lat_cgd[row - 1][col - 1];
4887  n = lat_cgd[row][col];
4888  w = lon_cgd[row - 1][col - 1];
4889  e = lon_cgd[row][col];
4890  gridBox.min_corner().set<0>(w);
4891  gridBox.min_corner().set<1>(s);
4892  gridBox.max_corner().set<0>(e);
4893  gridBox.max_corner().set<1>(n);
4894 
4895  ingeom = within(pixelBox, gridBox);
4896  cout << "ingeom..downleft." << ingeom << "n.." << n << "s.." << s << "w.." << w << "e.." << e << endl;
4897  if (!bg::disjoint(pixelBox, gridBox)) {
4898  Box_t output;
4899  if (bg::intersection(pixelBox, gridBox, output)) {
4900  double intersectArea = bg::area(output);
4901  if (intersectArea > 0) {
4902  result = true;
4903  double binArea = (n - s) * (e - w);
4904  areaFracBox[0][0] = intersectArea / binArea;
4905  if (intersectArea / binArea < 0.000001) areaFracBox[ar][ac] = 0.0;
4906  }
4907  }
4908  }
4909  //down right
4910  s = lat_cgd[row - 1][col + 1];
4911  n = lat_cgd[row][col + 2];
4912  w = lon_cgd[row - 1][col + 1];
4913  e = lon_cgd[row][col + 2];
4914 
4915  gridBox.min_corner().set<0>(w);
4916  gridBox.min_corner().set<1>(s);
4917  gridBox.max_corner().set<0>(e);
4918  gridBox.max_corner().set<1>(n);
4919  ingeom = within(pixelBox, gridBox);
4920  cout << "ingeom..downright." << ingeom << "n.." << n << "s.." << s << "w.." << w << "e.." << e << endl;
4921  if (!bg::disjoint(pixelBox, gridBox)) {
4922  Box_t output;
4923  if (bg::intersection(pixelBox, gridBox, output)) {
4924  double intersectArea = bg::area(output);
4925  if (intersectArea > 0) {
4926  result = true;
4927  double binArea = (n - s) * (e - w);
4928  areaFracBox[0][2] = intersectArea / binArea;
4929  if (intersectArea / binArea < 0.000001) areaFracBox[ar][ac] = 0.0;
4930  }
4931  }
4932  }
4933 
4934  if (n < s) { //this is happening in right side terminal pixels such as pixel 1254
4935  n = lat_cgd[row][col];
4936  s = lat_cgd[row + 1][col + 1];
4937  }
4938  if (e < w) {
4939  e = lon_cgd[row][col];
4940  w = lon_cgd[row + 1][col + 1];
4941  }
4942 
4943  return result;
4944  }
4945 
4946  //2 bounds in pixel
4947  //original nIntersectsPixelbinIntersectsPixel
4948  bool L1C::binIntersectsPix2corn(int32_t row, int32_t col, double** lat_cgd, double** lon_cgd, Box_t& pixelBox, double& areaFrac) {
4949  bool result = false;
4950  float n, s, e, w;
4951 
4952  s = lat_cgd[row][col];
4953  n = lat_cgd[row + 1][col + 1];
4954  w = lon_cgd[row][col];
4955  e = lon_cgd[row + 1][col + 1];
4956 
4957  if (n < s) { //this is happening in right side terminal pixels such as pixel 1254
4958  n = lat_cgd[row][col];
4959  s = lat_cgd[row + 1][col + 1];
4960  }
4961  if (e < w) {
4962  e = lon_cgd[row][col];
4963  w = lon_cgd[row + 1][col + 1];
4964  }
4965 
4966  cout << "south gridcorn.." << s << "north gridcorn.." << n << "west gridcorn.." << w << "east gridcorn" << e << endl;
4967 
4968  Box_t box(Point_t(w, s), Point_t(e, n));//x = longitude, y = latitude
4969  areaFrac = 0;
4970 
4971  if (!bg::disjoint(box, pixelBox)) {
4972  Box_t output;
4973  if (bg::intersection(box, pixelBox, output)) {
4974  double intersectArea = bg::area(output);
4975  if (intersectArea > 0) {
4976  result = true;
4977  double binArea = (n - s) * (e - w);
4978  areaFrac = intersectArea / binArea;
4979  }
4980  }
4981  }
4982  return result;
4983  }
4984 
4985 
4986 
4987 
4988 
4989 int L1C::create_SOCEA(int swtd,L1C_input* l1cinput, l1c_filehandle* l1cfile,float** lat_gd, float **lon_gd){
4990 
4991  int32_t num_gridlines, nbinx;
4992  int ncid_out,x_dimid, y_dimid, varid1, varid2, status;
4993  int NDIMS=2;
4994  int dimids[NDIMS];
4995  int32_t NX, NY;
4996  int16_t selyear = -1, selmon = -1, selday = -1;
4997  int grp_coor;
4998  const char* filename_lt;
4999 
5000 // float **lt_out=nullptr;
5001  int NVIEWS, NBANDS,v_dimid,b_dimid,asc_mode=-1;
5002  string senstr,tswt_ini,tswt_end,tswt_ini_file;
5003 
5004  if(l1cinput->sensor==1){
5005  senstr="SPEXone";
5006  l1cfile->nbinx=20;
5007  }
5008  else if (l1cinput->sensor==2){
5009  senstr="OCI";
5010  l1cfile->nbinx=514;
5011  }
5012  else if (l1cinput->sensor==3){
5013  senstr="HARP2";
5014  l1cfile->nbinx=452;
5015  }
5016  else{cout<<"sensor by default is OCI option 2....."<<endl;
5017  senstr="OCI";
5018  l1cfile->nbinx=514;
5019  }
5020 
5021 
5022 
5023 
5024 
5025  //compute azimuth angle for each along-track position (nadir pixel or centered swath pixel) of the swath
5026  //azimuth angle in rads
5027  //lon+540/360-180 is a normalization factor for -180 to 180 degrees
5028  num_gridlines = l1cfile->num_gridlines;
5029  num_pixels = l1cfile->npix;
5030  nbinx = l1cfile->nbinx;
5031 
5032  cout<<"# gridlines.."<<num_gridlines<<endl;
5033 
5034  tswt_ini=l1cfile->tswt_ini;
5035  tswt_end=l1cfile->tswt_end;
5036  tswt_ini_file=l1cfile->tswt_ini_file;
5037 
5038  //big loop
5039 
5040 
5041  asc_mode=l1cfile->orb_dir;
5042 
5043 
5044 //---- writing results -------------------------------------------
5045 //--------------------------------------------------------------
5046 
5047  selday = l1cinput->selday;
5048  selmon = l1cinput->selmon;
5049  selyear = l1cinput->selyear;
5050 
5051  std::string timestr,missionstr,fname_out, pathstr,monstr, daystr, yearstr, prodstr, gdstr, swtstr, swtnum, extstr,ofilestr,dirstr;
5052 
5053  if(asc_mode==1) dirstr="Ascending";
5054  else if(asc_mode==0) dirstr="Descending";
5055 
5056 
5057 
5058  pathstr = "out/";
5059  missionstr="PACE";
5060  monstr = std::to_string(selmon);
5061  daystr = std::to_string(selday);
5062  yearstr = std::to_string(selyear);
5063  timestr="T00:00:00Z";
5064  prodstr = "L1Cgrid_";
5065  swtstr = "_swt";
5066  swtnum = std::to_string(swtd);
5067  extstr = ".nc";
5068  ofilestr=std::string(l1cinput->ofile);
5069 
5070 // fname_out = pathstr + ofilestr+"_"+ prodstr+senstr+swtstr+swtnum+extstr;
5071  fname_out=pathstr+"PACE_"+senstr+"."+tswt_ini_file+".L1C.5.2km.nc";
5072  // string datestr=date;
5073 
5074  auto t = std::time(nullptr);
5075  auto tm = *std::localtime(&t);
5076  std::ostringstream oss,oss2;
5077  oss << std::put_time(&tm, "%d-%m-%Y %H-%M-%S") << std::endl;
5078  // cout<<"current datetime.n UTC."<<datestr<<endl;
5079  auto datestr = oss.str();
5080  cout<<"date.."<<datestr.substr(0,2)<<endl;
5081 
5082  time_t rawtime;
5083  time (&rawtime);
5084  string datestr2=ctime (&rawtime);
5085 
5086 
5087 // oss2<<system("date")<<endl;
5088 // string datestr2=oss2.str();
5089  cout<<"date.."<<datestr2.substr(0,10)<<endl;
5090 // exit(1);
5091 
5092 
5093 
5094 
5095  string ATT_NAME="Units", ATT_VAL="degrees",GATT_NAME1="Title",GATT_VAL1="PACE OCI Level-1C Data",GATT_NAME2="instrument",GATT_VAL2="OCI",GATT_NAME3="processing_version",GATT_VAL3="V1.0",GATT_NAME4="Conventions",GATT_VAL4="CF-1.6";
5096  string GATT_NAME5="institution",GATT_VAL5="NASA Goddard Space Flight Center, Ocean Biology Processing Group",GATT_NAME6="license",GATT_VAL6="http://science.nasa.gov/earth-science/earth-science-data/data-information-policy/";
5097  string GATT_NAME7="naming_authority",GATT_VAL7="gov.nasa.gsfc.sci.oceancolor",GATT_NAME8="keywords_vocabulary",GATT_VAL8="NASA Global Change Master Directory (GCMD) Science Keywords";
5098  string GATT_NAME9="stdname_vocabulary",GATT_VAL9="NetCDF Climate and Forecast (CF) Metadata Convention",GATT_NAME10="creator_name",GATT_VAL10="NASA/GSFC",GATT_NAME11="creator_email",GATT_VAL11="data@oceancolor.gsfc.nasa.gov";
5099  string GATT_NAME12="creator_url",GATT_VAL12="http://oceancolor.gsfc.nasa.gov",GATT_NAME13="project",GATT_VAL13="PACE Project",GATT_NAME14="publisher_name",GATT_VAL14="NASA/GSFC";
5100  string GATT_NAME15="publisher_email",GATT_VAL15="data@oceancolor.gsfc.nasa.gov",GATT_NAME16="publisher_url",GATT_VAL16="http://oceancolor.gsfc.nasa.gov",GATT_NAME17="processing_level",GATT_VAL17="L1C";
5101  string GATT_NAME18="cdm_data_type",GATT_VAL18="swath",GATT_NAME19="orbit_number",GATT_VAL19="xxx",GATT_NAME20="history",GATT_VAL20="",GATT_NAME21="CDL_version_date",GATT_VAL21="2021-09-10",GATT_NAME22="product_name",GATT_VAL22=fname_out;
5102  string GATT_NAME23="startDirection",GATT_VAL23=dirstr,GATT_NAME24="endDirection",GATT_VAL24=dirstr,GATT_NAME25="time_coverage_start",GATT_VAL25=tswt_ini,GATT_NAME26="time_coverage_end",GATT_VAL26=tswt_end,GATT_NAME27="date_created",GATT_VAL27="2022-03-25T15:12:41Z",GATT_NAME28="sun_earth_distance",GATT_VAL28="0.990849042172323",GATT_NAME29="terrain_data_source",GATT_VAL29="",GATT_NAME30="spectral_response_function",GATT_VAL30="",GATT_NAME31="systematic_uncertainty_model",GATT_VAL31="",GATT_NAME32="nadir_bin",GATT_VAL32="12345",GATT_NAME33="bin_size_at_nadir",GATT_VAL33="5.2km2";
5103 
5104 
5105  l1cfile->gridname = fname_out.c_str();
5106  filename_lt = fname_out.c_str();
5107 
5108  cout<<"creating file for L1C coor..."<<filename_lt<<endl;
5109 
5110 
5111  if ((status = nc_create(filename_lt, NC_CLOBBER | NC_NETCDF4, &ncid_out)))
5112  check_err(status, __LINE__, __FILE__);
5113  //define dims
5114  // Define the dimensions,vars and attributes at the root level
5115  NY = num_gridlines;
5116  NX = nbinx;
5117 
5118  if(l1cinput->sensor==1){
5119  senstr="SPEXone";
5120  GATT_VAL2="SPEXone";
5121  GATT_VAL32="3567";
5122  NVIEWS=5;
5123  NBANDS=400;
5124  }
5125  else if (l1cinput->sensor==2){
5126  senstr="OCI";
5127  GATT_VAL2="OCI";
5128  GATT_VAL32="635";
5129  NVIEWS=2;
5130  NBANDS=249;
5131  }
5132  else if (l1cinput->sensor==3){
5133  senstr="HARP2";
5134  GATT_VAL2="HARP2";
5135  GATT_VAL32="127";
5136  NVIEWS=90;
5137  NBANDS=1;
5138  }
5139  else{
5140  cout<<"sensor by default is OCI option 2....."<<endl;
5141  senstr="OCI";
5142  GATT_VAL2="OCI";
5143  GATT_VAL32="635";
5144  NVIEWS=2;
5145  NBANDS=249;
5146  }
5147 
5148 // lt_out = allocate2d_float(NY, NX);
5149  //DEF DIMENSIONS
5150  if ((status = nc_def_dim(ncid_out, "bins_across_track", NX, &x_dimid)))
5151  check_err(status, __LINE__, __FILE__);
5152  if ((status = nc_def_dim(ncid_out, "bins_along_track", NY, &y_dimid)))
5153  check_err(status, __LINE__, __FILE__);
5154  //dims for output var
5155  dimids[0] = y_dimid;
5156  dimids[1] = x_dimid;
5157  NDIMS=2;
5158  if ((status = nc_def_dim(ncid_out, "number_of_views", NVIEWS, &v_dimid)))
5159  check_err(status, __LINE__, __FILE__);
5160  if ((status = nc_def_dim(ncid_out, "intensity_bands_per_view", NBANDS, &b_dimid)))
5161  check_err(status, __LINE__, __FILE__);
5162  //define attributes
5163 // if (nc_put_att_text(ncid_out, varid1, ATT_NAME.c_str(), strlen(ATT_VAL.c_str()), ATT_VAL.c_str()))
5164 // check_err(status, __LINE__, __FILE__);
5165 // if (nc_put_att_text(ncid_out, varid2, ATT_NAME.c_str(), strlen(ATT_VAL.c_str()), ATT_VAL.c_str()))
5166 // check_err(status, __LINE__, __FILE__);
5167  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME1.c_str(), strlen(GATT_VAL1.c_str()),
5168  GATT_VAL1.c_str()))
5169  check_err(status, __LINE__, __FILE__);
5170  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME2.c_str(), strlen(GATT_VAL2.c_str()),
5171  GATT_VAL2.c_str()))
5172  check_err(status, __LINE__, __FILE__);
5173  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME3.c_str(), strlen(GATT_VAL3.c_str()),
5174  GATT_VAL3.c_str()))
5175  check_err(status, __LINE__, __FILE__);
5176  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME4.c_str(), strlen(GATT_VAL4.c_str()),
5177  GATT_VAL4.c_str()))
5178  check_err(status, __LINE__, __FILE__);
5179  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME5.c_str(), strlen(GATT_VAL5.c_str()),
5180  GATT_VAL5.c_str()))
5181  check_err(status, __LINE__, __FILE__);
5182  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME6.c_str(), strlen(GATT_VAL6.c_str()),
5183  GATT_VAL6.c_str()))
5184  check_err(status, __LINE__, __FILE__);
5185  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME7.c_str(), strlen(GATT_VAL7.c_str()),
5186  GATT_VAL7.c_str()))
5187  check_err(status, __LINE__, __FILE__);
5188  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME8.c_str(), strlen(GATT_VAL8.c_str()),
5189  GATT_VAL8.c_str()))
5190  check_err(status, __LINE__, __FILE__);
5191  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME9.c_str(), strlen(GATT_VAL9.c_str()),
5192  GATT_VAL9.c_str()))
5193  check_err(status, __LINE__, __FILE__);
5194  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME10.c_str(), strlen(GATT_VAL10.c_str()),
5195  GATT_VAL10.c_str()))
5196  check_err(status, __LINE__, __FILE__);
5197  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME11.c_str(), strlen(GATT_VAL11.c_str()),
5198  GATT_VAL11.c_str()))
5199  check_err(status, __LINE__, __FILE__);
5200  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME12.c_str(), strlen(GATT_VAL12.c_str()),
5201  GATT_VAL12.c_str()))
5202  check_err(status, __LINE__, __FILE__);
5203  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME13.c_str(), strlen(GATT_VAL13.c_str()),
5204  GATT_VAL13.c_str()))
5205  check_err(status, __LINE__, __FILE__);
5206  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME14.c_str(), strlen(GATT_VAL14.c_str()),
5207  GATT_VAL14.c_str()))
5208  check_err(status, __LINE__, __FILE__);
5209  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME15.c_str(), strlen(GATT_VAL15.c_str()),
5210  GATT_VAL15.c_str()))
5211  check_err(status, __LINE__, __FILE__);
5212  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME16.c_str(), strlen(GATT_VAL16.c_str()),
5213  GATT_VAL16.c_str()))
5214  check_err(status, __LINE__, __FILE__);
5215  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME17.c_str(), strlen(GATT_VAL17.c_str()),
5216  GATT_VAL17.c_str()))
5217  check_err(status, __LINE__, __FILE__);
5218  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME18.c_str(), strlen(GATT_VAL18.c_str()),
5219  GATT_VAL18.c_str()))
5220  check_err(status, __LINE__, __FILE__);
5221  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME19.c_str(), strlen(GATT_VAL19.c_str()),
5222  GATT_VAL19.c_str()))
5223  check_err(status, __LINE__, __FILE__);
5224  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME20.c_str(), strlen(GATT_VAL20.c_str()),
5225  GATT_VAL20.c_str()))
5226  check_err(status, __LINE__, __FILE__);
5227  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME21.c_str(), strlen(GATT_VAL21.c_str()),
5228  GATT_VAL21.c_str()))
5229  check_err(status, __LINE__, __FILE__);
5230  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME22.c_str(), strlen(GATT_VAL22.c_str()),
5231  GATT_VAL22.c_str()))
5232  check_err(status, __LINE__, __FILE__);
5233  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME23.c_str(), strlen(GATT_VAL23.c_str()),
5234  GATT_VAL23.c_str()))
5235  check_err(status, __LINE__, __FILE__);
5236  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME24.c_str(), strlen(GATT_VAL24.c_str()),
5237  GATT_VAL24.c_str()))
5238  check_err(status, __LINE__, __FILE__);
5239  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME25.c_str(), strlen(GATT_VAL25.c_str()),
5240  GATT_VAL25.c_str()))
5241  check_err(status, __LINE__, __FILE__);
5242  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME26.c_str(), strlen(GATT_VAL26.c_str()),
5243  GATT_VAL26.c_str()))
5244  check_err(status, __LINE__, __FILE__);
5245  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME27.c_str(), strlen(GATT_VAL27.c_str()),
5246  GATT_VAL27.c_str()))
5247  check_err(status, __LINE__, __FILE__);
5248  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME28.c_str(), strlen(GATT_VAL28.c_str()),
5249  GATT_VAL28.c_str()))
5250  check_err(status, __LINE__, __FILE__);
5251  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME29.c_str(), strlen(GATT_VAL29.c_str()),
5252  GATT_VAL29.c_str()))
5253  check_err(status, __LINE__, __FILE__);
5254  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME30.c_str(), strlen(GATT_VAL30.c_str()),
5255  GATT_VAL30.c_str()))
5256  check_err(status, __LINE__, __FILE__);
5257  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME31.c_str(), strlen(GATT_VAL31.c_str()),
5258  GATT_VAL31.c_str()))
5259  check_err(status, __LINE__, __FILE__);
5260  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME32.c_str(), strlen(GATT_VAL32.c_str()),
5261  GATT_VAL32.c_str()))
5262  check_err(status, __LINE__, __FILE__);
5263  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME33.c_str(), strlen(GATT_VAL33.c_str()),
5264  GATT_VAL33.c_str()))
5265  check_err(status, __LINE__, __FILE__);
5266 
5267  //define groups check_err(status, __LINE__, __FILE__);
5268  if ((status = nc_def_grp(ncid_out, "geolocation_data", &grp_coor))) //netcdf-4
5269  check_err(status, __LINE__, __FILE__);
5270  //def var
5271  if ((status = nc_def_var(grp_coor, "latitude", NC_FLOAT, NDIMS,
5272  dimids, &varid1)))
5273  check_err(status, __LINE__, __FILE__);
5274  if ((status = nc_def_var(grp_coor, "longitude", NC_FLOAT, NDIMS,
5275  dimids, &varid2)))
5276  check_err(status, __LINE__, __FILE__);
5277  //leave define mode-----------------------
5278  if ((status = nc_enddef(grp_coor))) //done def vars etc
5279  check_err(status, __LINE__, __FILE__);
5280 
5281 
5282  //writing the whole thing
5283  if ((status = nc_put_var_float(grp_coor, varid1, &lat_gd[0][0])))
5284  check_err(status, __LINE__, __FILE__);
5285 
5286  if ((status = nc_put_var_float(grp_coor, varid2, &lon_gd[0][0])))
5287  check_err(status, __LINE__, __FILE__);
5288 
5289 
5290 
5291 //define attributes of vars in groups
5292 //UNITS in degrees ----
5293  if (nc_put_att_text(grp_coor, varid1, ATT_NAME.c_str(), strlen(ATT_VAL.c_str()), ATT_VAL.c_str()))
5294  check_err(status, __LINE__, __FILE__);
5295  check_err(status, __LINE__, __FILE__);
5296  if (nc_put_att_text(grp_coor, varid2, ATT_NAME.c_str(), strlen(ATT_VAL.c_str()), ATT_VAL.c_str()))
5297  check_err(status, __LINE__, __FILE__);
5298 
5299 
5300 //close file
5301  if ((status = nc_close(ncid_out)))
5302  check_err(status, __LINE__, __FILE__);
5303 
5304 
5305 
5306 
5307 
5308  return 0;
5309 }
5310 
5311 
5312 
5313 
5314 
5315 
5316 int L1C::search_SOCEA(L1C_input* l1cinput, l1c_filehandle* l1cfile, float** lat, float **lon, double *time_mgv, float ect,float loncross) {
5317 int32_t irow=-1,icol=-1;
5318 float binsize=5.2, rem=6371,oang,xmm=0.001065,omeg=2 * M_PI / 86400,xinc=98.1111,rom=7054.5;
5319 float senview=20,oview;//viewing angle of the sensor, OCI, -20 degrees south, +20 degrees north
5320 double delt;
5321 float lonet,yaws=3.84,xinct,ata,cp;
5322 
5323 
5324 //OCI Nrow=4000, Ncol=514
5325 
5326 //ect is equatorial crossing time
5327  delt=time_mgv[0]-ect;//first gridline
5328  oview= asin(rom*sin(senview*M_PI/180.)/rem) - senview*M_PI/180.; // Along-track orbit angle for view
5329  oang=xmm-omeg*cos(xinc*M_PI/180.)*delt + oview; //orbit angle from equator
5330  irow = round(oang*rem/binsize);
5331 
5332 cout<<"row number..."<<irow+1<<endl;
5333 
5334 // Orbit normal
5335  lonet = (loncross + yaws*sin(2*oang)/2)*M_PI/180. - delt*omeg;
5336  xinct = (xinc + yaws*(1+cos(2*oang))/2)*M_PI/180.;
5337  float on[3];
5338  on[0] = sin(xinct)*sin(lonet);
5339  on[1] = -sin(xinct)*cos(lonet);
5340  on[2] = cos(xinct);
5341 
5342 
5343 // Compute lat/lon to subsatellite track angle and column number
5344  float xll[3];
5345  xll[0] = cos(lon[0][0]*M_PI/180.)*cos(lat[0][0]*M_PI/180.);
5346  xll[1] = sin(lon[0][0]*M_PI/180.)*cos(lat[0][0]*M_PI/180.);
5347  xll[2] = sin(lat[0][0]*M_PI/180.);
5348 
5349  cp = on[0]*xll[0] + on[1]*xll[1] + on[2]*xll[2];//dot product of vectors position and orbit normal L and N respectively
5350  ata = acos(cp) - M_PI/2.;
5351  icol = round(ata*rem/binsize);
5352 
5353 cout<<"col number..."<<icol+1<<endl;
5354 
5355 
5356 return 0;
5357 }
5358 
5359 
5360 
5361 
5362  //this is the Fred method for finding row/col of L1C grid for specific location
5363  //this works pixel by pixel---
5364  void L1C::search_rc_l1c(L1C_input* l1cinput, l1c_filehandle* l1cfile, float lat_pix, float lon_pix, double dtime_pix, float lon_eqc, short* rowindex, short* colindex, short Nneg) {
5365 
5366  //dtime = time offset with respect to the equator in seconds---
5367  float wo = 0.001065, oangle, oangler, we = 2 * M_PI / 86400, incli = 98.111; //woin radians/second PACE orbit mean motion, we= earth rotation, 460 m/s or 1 rotation in in 86400 s, orbit inclination is in degrees
5368  float binres, all, all2, Ro = 7054.5, va;//Ro is the orbit radius in km, Re is the earth radius in km, va is the view angle
5369  short Nr, Nc;
5370  float gamma, dlon, sva, LcpN, dincli, phi_yaw = 3.83 * M_PI / 180;//phiyaw is the amplitude yaw steering angle, theta is the orbit angle from the equatorial crossing
5371  double n11, n12, n13, l11, l12, l13;
5372 
5373  incli = incli * M_PI / 180;
5374  binres = (l1cinput->gres);//grid resolution in km
5375 
5376  //estimating row number---
5377 
5378  //computing orbit angle
5379  oangle = wo * dtime_pix;
5380  //adjustment by earth rotation
5381  oangler = oangle - we * cos(incli) * dtime_pix;
5382 
5383  //cout<<"search_rc_l1c.."<<"dtime_pix..."<<dtime_pix<<"oangler.."<<oangler<<endl;
5384 
5385 
5386  //sensor along-track view angle in radians
5387  //O-P O-S angle
5388  dlon = (lon_eqc - lon_pix) * M_PI / 180;
5389  lon_eqc = lon_eqc * M_PI / 180;
5390 
5391  gamma = acos((lat_pix * M_PI / 180) * cos(dlon));
5392  all2 = Ro * sqrt(1 + (Re / Ro) * (Re / Ro) - 2 * (Re / Ro) * cos(gamma));
5393 
5394  //from soler et al. ISSN0733-9453/94/0003-0115/$2.00+ $.25per page.PaperNo. 7382.ournalofSurveyingEngineering,Vol. 120,No. 3, August,1994.
5395  sva = acos((Ro / all2) * sin(gamma));
5396  va = 180 - sva * 180 / M_PI - gamma * 180 / M_PI;
5397  va = va * M_PI / 180.;
5398 
5399 
5400  //computing along-track length
5401  all = asin(Ro * sin(va) / Re) - va;
5402 
5403  //relative row number---
5404  Nr = (oangler + all) * Re / binres;
5405  //Nr=Nr+round(num_gridlines/2);
5406  Nr = Nr + Nneg;
5407 
5408  *rowindex = Nr;
5409 
5410  //column estimation
5411  //HARP-SPEX-one are push-broom, OCI is whisk-broom so small time difference between pixels which is ignored
5412 
5413  //position vector L
5414  //N vector normal to position and velocity, this is orbit normal vector
5415 
5416  //computing N
5417  dincli = phi_yaw * cos(oangle) * cos(oangle);
5418 
5419  n11 = sin(incli + dincli) * sin(lon_eqc - we * dtime_pix + dlon);
5420  n12 = -sin(incli + dincli) * cos(lon_eqc - we * dtime_pix + dlon);
5421  n13 = cos(incli + dincli);
5422 
5423  //computing L
5424  l11 = cos(lon_pix * M_PI / 180) * cos(lat_pix * M_PI / 180);
5425  l12 = sin(lon_pix * M_PI / 180) * cos(lat_pix * M_PI / 180);
5426  l13 = sin(lat_pix * M_PI / 180);
5427 
5428  //column number estimation
5429  LcpN = n11 * l11 + n12 * l12 + n13 * l13;//cross product of vectors position and orbit normal L and N respectively
5430  Nc = (acos(LcpN) - 0.5 * M_PI) * Re / binres;
5431  *colindex = Nc;
5432 
5433  //cout<<"row..#.."<<Nr<<"col...#.."<<Nc<<endl;
5434  //cout<<"search_rc_l1c.."<<"gamma..."<<gamma<<"va.."<<va<<"all...."<<all<<"all2..."<<all2<<endl;
5435 
5436  }
5437 
5438 
5439 
5440  void L1C::sbs2_sort_latgd(l1c_filehandle* l1cfile, float** lat_gd, float** lat_asort, short** index_xy) {
5441 
5442  int32_t NY1 = -1, NY2 = -1,nbinx;
5443 
5444  nbinx = l1cfile->nbinx;
5445  NY1 = l1cfile->NY1;
5446  NY2 = l1cfile->NY2;
5447 
5448  cout << "NY1.." << NY1 << "NY2.." << NY2 << endl;
5449 
5450 
5451  //define 1-D vector to sort 1 col L1C grid at the time---
5452  vector<pair<float, int> > vp;
5453 
5454  //fill vector with lat_gd column--
5455  cout << "*********** SORTING LAT/LON GRIDPOINTS AND TRACKING INDEXES ********************" << endl;
5456 
5457  for (int col = 0;col < nbinx;col++) {
5458  for (int row = NY1;row < NY2 + 1;row++) {
5459  vp.push_back(make_pair(lat_gd[row][col] + 90., row));
5460  }//ading 90 degrees so it is 0-180 degrees always positive latitude
5461 //sort
5462  stable_sort(vp.begin(), vp.end());
5463  //display lat in order along with its gridpoint index--
5464  // cout << "Lat value\t"
5465  // << "index" << endl;
5466  for (unsigned int i = 0; i < vp.size(); i++) {
5467  // cout << vp[i].first << "\t "<< vp[i].second << endl;
5468 
5469  lat_asort[i][col] = vp[i].first;
5470  index_xy[i][col] = vp[i].second;
5471  }
5472  vp.clear();//clear col
5473  }
5474 
5475 
5476  }
5477 
5478 
5479 
5480 
5481  //saddleback search algo improved
5482  //this approach is actually based on a radius search distance rather than a polygon pixel shape. This must be improved
5483  bool L1C::sbs2_l1c(L1C_input* l1cinput, int32_t ydim, int32_t xdim, float** alat, short** alat_index, float latpix, float lonpix, float** lon_gd, short* rowindex, short* colindex)
5484  {
5485  //pixval can be latpix or lonpix
5486  //flag_coor 0 latitude, 1 longitude
5487  //mat is is the sorted matrix in ascending order
5488  //mat_index IS THE ORIGINAL INDEX of lat or lon values L1C gridpoint
5489  //this INDEXING MAY CHANGE BETWEEN COLUMNS OR ACROSS GRIDLINES!!!
5490 
5491  short i = ydim - 1, j = 0, erow, ecol; //set indexes for bottom left element
5492  float diflon, diflat, diflat2, dtogd, dtogd2, binres, londegkm;
5493  float latpos, lonpos, lonpos_gd;
5494 
5495 
5496  binres = (l1cinput->gres) * 1000; //L1C grid resolution in meters
5497 
5498  while ((i - 1) >= 0 && j < xdim)
5499  {
5500  latpos = latpix + 90;//convert -90,+90 to lat 0-180
5501 
5502  if (latpos >= alat[i - 1][j] && latpos <= alat[i][j]) {
5503  //check coor difference with respect to center gridpoint--
5504  diflat = abs(latpos - alat[i][j]);
5505  diflat2 = abs(latpos - alat[i - 1][j]);
5506  //check lat distance to gridpoint-
5507  dtogd = diflat * 111.321 * 1000;
5508  dtogd2 = diflat2 * 111.321 * 1000;
5509 
5510  if (dtogd < dtogd2 && dtogd <= binres / 2) {
5511  erow = alat_index[i][j];
5512 }
5513  else if (dtogd2 < dtogd && dtogd2 <= binres / 2) {
5514  erow = alat_index[i - 1][j];
5515 }
5516 
5517  //check longitude estimate
5518  if (lonpix < 0.) lonpos = lonpix + 180;else lonpos = lonpix;//longitude between 0 and 360
5519  if (lon_gd[erow][j] < 0.) lonpos_gd = lon_gd[erow][j] + 180;else lonpos_gd = lon_gd[erow][j];
5520 
5521  diflon = abs(lonpos - lonpos_gd);
5522  londegkm = cos(latpix * degrad) * 111.321;
5523  dtogd = diflon * londegkm * 1000;
5524 
5525  if (dtogd <= binres / 2) {
5526  ecol = j;
5527  *rowindex = erow;
5528  *colindex = ecol;
5529  return true;
5530  }
5531  else j++;//go to next col
5532 
5533  } //end if lat bracket
5534 
5535  if (alat[i][j] > latpos && alat[i - 1][j] > latpos) { //pixval < mat
5536  i--;
5537 
5538  }
5539  if (i == 0) return false;
5540 
5541  if (alat[i][j] < latpos && alat[i - 1][j] < latpos) {
5542  j++;
5543 
5544  if (j == xdim) return false;
5545  }
5546  if (i == 0 | j == xdim) return false;
5547 
5548  //the sorting is done over the rows for each column so row order is actually changing!!
5549 
5550  }//end while
5551 
5552  return false;
5553  }
5554 
5555  double L1C::binL1C_pixelpoly(l1c_filehandle* l1cfile, L1C_input* l1cinput, l1c_str* l1cstr, short gd_row, short gd_col, int32_t pix) {
5556  int32_t inpix = 0;
5557  string str, pathstr, senstr, monstr, daystr, yearstr, prodstr, swtstr, granstr, swtnum, extstr, fname_out;
5558  float Re = 6378;
5559  float aterm = 0.;
5560  string gridname, azeast_name;
5561  float azpix, azpixc;
5562  float deltaphi, deltalam, bterm, dist_u, dist_v;
5563  double lat_cnw, lat_cne, lat_csw, lat_cse, lon_cnw, lon_cne, lon_csw, lon_cse;
5564  float theta, thetares, dist_corn, thetagrad;
5565  string ws_lon_str, ws_lat_str, wn_lon_str, wn_lat_str, en_lon_str, en_lat_str, es_lon_str, es_lat_str, pixstr;
5566  double bintemp = 0;
5567 
5568  Geodesic geod(Constants::WGS84_a(), Constants::WGS84_f());
5569 
5570 
5571  //************ BINNING ***************************
5572  //assign identified pixel to Lt and bin stat arrays-----
5573 
5574  Polygon_t pixelPoly;
5575  Polygon_t gridPoly;
5576 
5577  inpix++;
5578  deltaphi = (l1cstr->latpix[pix] - l1cstr->latpix[pix + 1]) * degrad;
5579  deltalam = (l1cstr->lonpix[pix] - l1cstr->lonpix[pix + 1]) * degrad;
5580  aterm = sin(deltaphi / 2) * sin(deltaphi / 2) + cos(l1cstr->latpix[pix] * degrad) * cos(l1cstr->latpix[pix + 1] * degrad) * sin(deltalam / 2) * sin(deltalam / 2);
5581  bterm = 2 * atan2(sqrt(aterm), sqrt(1 - aterm));
5582  dist_u = Re * bterm; //horizontal distance Harversine in km
5583  //along-track distance
5584  deltaphi = (l1cstr->latpix[pix] - l1cstr->latpix2[pix]) * degrad;
5585  deltalam = (l1cstr->lonpix[pix] - l1cstr->lonpix2[pix]) * degrad;
5586  aterm = sin(deltaphi / 2) * sin(deltaphi / 2) + cos(l1cstr->latpix[pix] * degrad) * cos(l1cstr->latpix2[pix] * degrad) * sin(deltalam / 2) * sin(deltalam / 2);
5587  bterm = 2 * atan2(sqrt(aterm), sqrt(1 - aterm));
5588  dist_v = Re * bterm;
5589  //pixel azimuth
5590  azpix = atan2(sin(deltalam) * cos(l1cstr->latpix2[pix] * degrad), cos(l1cstr->latpix[pix] * degrad) * sin(l1cstr->latpix2[pix] * degrad) - sin(l1cstr->latpix[pix] * degrad) * cos(l1cstr->latpix2[pix] * degrad) * cos(deltaphi));
5591  if (azpix > M_PI || azpix < -M_PI) {
5592  cout << "problem with BEARING in across-gridline method...az<-180 or >180...." << "azpixc in degrees.." << azpix * 180 / M_PI << endl;
5593  exit(1);
5594  }
5595  azpix = azpix * 180. / M_PI;
5596 
5597  // cout<<"line.."<<sline+1<<"pix #:.."<<pix+1<<"pix size.U in km."<<dist_u<<"pixsize.V in km."<<dist_v<<"azpix before pix_corners4_l1c....in degrees."<<azpix<<endl;
5598  // cout<<"FOUND grid cell!!-----row.."<<gd_row<<"col.."<<gd_col<<"latpix.."<<l1cstr->latpix[pix]<<"lonpix.."<<l1cstr->lonpix[pix]<<"latpix2.."<<l1cstr->latpix2[pix]<<"lonpix2.."<<l1cstr->lonpix2[pix]<<endl;
5599 
5600  //******* M_PIXEL CORNERS ***********************************************************************************************
5601  dist_corn = 0.5 * (sqrt(dist_u * dist_u + dist_v * dist_v)) * 1000;//distane center to corner in meters
5602  theta = atan2(dist_v, dist_u);
5603  thetagrad = 2 * theta * 180 / M_PI;
5604  thetares = (M_PI / 2 - theta) * 180 / M_PI;
5605  //nw corner
5606  azpixc = (azpix - thetares) * degrad;//pixel bearing
5607  if (azpixc<-M_PI || azpixc>M_PI) { cout << "error in nw corner..azpixc" << azpixc << endl;exit(1); }
5608  azpixc = azpixc * 180 / M_PI;
5609  // cout<<"azpixc nw...."<<azpixc<<endl;
5610  geod.Direct(l1cstr->latpix[pix], l1cstr->lonpix[pix], azpixc, dist_corn, lat_cnw, lon_cnw);
5611  //ne corner (sw-180)
5612  azpixc = (azpix + thetares) * degrad;//pixel bearing
5613  if (azpixc<-M_PI || azpixc>M_PI) { cout << "error in ne corner..azpixc" << azpixc << endl;exit(1); }
5614  azpixc = azpixc * 180 / M_PI;
5615  // cout<<"azpixc ne...."<<azpixc<<endl;
5616  geod.Direct(l1cstr->latpix[pix], l1cstr->lonpix[pix], azpixc, dist_corn, lat_cne, lon_cne);
5617  //sw corner
5618  azpixc = (azpix - thetares - thetagrad) * degrad;//pixel bearing
5619  if (azpixc<-M_PI || azpixc>M_PI) { cout << "error in sw corner..azpixc" << azpixc << endl;exit(1); }
5620  azpixc = azpixc * 180 / M_PI;
5621  // cout<<"azpixc sw....."<<azpixc<<endl;
5622  geod.Direct(l1cstr->latpix[pix], l1cstr->lonpix[pix], azpixc, dist_corn, lat_csw, lon_csw);
5623  //se corner (nw-180)
5624  azpixc = (azpix + thetares + thetagrad) * degrad;//pixel bearingi
5625  if (azpixc<-M_PI || azpixc>M_PI) { cout << "error in se corner..azpixc" << azpixc << endl;exit(1); }
5626  azpixc = (azpix + 45 + 90) * degrad;//pixel bearing
5627  azpixc = azpixc * 180 / M_PI;
5628  // cout<<"azpix se...."<<azpixc<<endl;
5629  geod.Direct(l1cstr->latpix[pix], l1cstr->lonpix[pix], azpixc, dist_corn, lat_cse, lon_cse);
5630 
5631 
5632  bg::append(pixelPoly.outer(), Point_t(lon_csw, lat_csw));
5633  bg::append(pixelPoly.outer(), Point_t(lon_cnw, lat_cnw));
5634  bg::append(pixelPoly.outer(), Point_t(lon_cne, lat_cne));
5635  bg::append(pixelPoly.outer(), Point_t(lon_cse, lat_cse));
5636  bg::append(pixelPoly.outer(), Point_t(lon_csw, lat_csw));
5637  // make sure the polygon is defined properly
5638  bg::correct(pixelPoly);
5639 
5640  try {
5641  bintemp = bg::area(pixelPoly);
5642  if (bintemp <= 0)
5643  throw(bintemp);
5644  }
5645  catch (double binareapix) {
5646 
5647  cout << "we have an exception calculating pixel polygon area!!!!!!!!!!" << binareapix << endl;
5648  }
5649 
5650  return bintemp;
5651 
5652  }
5653 
5654 //OPEN L1C grid
5655  int32_t L1C::openL1Cgrid(int swtd,l1c_str *l1cstr,l1c_filehandle *l1cfile,L1C_input *l1cinput,int16_t* swtd_id,int16_t* file_id, int16_t* nfiles_swt,float **lat_gd, float **lon_gd,float *az_east,float **lat_asort,short **index_xy){
5656  size_t ybins,xbins;
5657  int32_t num_gridlines, nbinx;//number of gridlines to be processed
5658  std::string str;
5659  const char* ptstr;
5660  int status,ncid_az,ncid_grid,x_dimid,y_dimid,azId;
5661  int32_t NY = -1, NX = -1, NY1 = -1, NY2 = -1,c1 = 1;
5662  char* ifile_char;
5663  std::string ifile_str;
5664  float mean_az_east;
5665  int16_t selyear = -1, selmon = -1, selday = -1;
5666  string gridname, azeast_name;
5667  int geoGrp;
5668  float sum=0,tot=0;
5669  char tmp[256];
5670 
5671  Geodesic geod(Constants::WGS84_a(), Constants::WGS84_f());
5672 
5673  //random seed
5674  srand((unsigned int)time(NULL));
5675 
5676 
5677 
5678 
5679  num_gridlines = 4000;
5680  num_pixels = l1cfile->npix;
5681  num_scans=l1cfile->nscan;
5682 
5683  // num_frames=l1cfile->nframes;
5684 
5685  cout<<"Opening L1C grid........................................................................."<<endl;
5686 
5687  //allocate mem for lat/lon/azeast pointers---
5688  selday = l1cinput->selday;
5689  selmon = l1cinput->selmon;
5690  selyear = l1cinput->selyear;
5691 
5692  std::string fname_out, pathstr, senstr, monstr, daystr, yearstr, prodstr, gdstr, swtstr, swtnum, extstr, granstr,timestr,azstr,missionstr,ofilestr;
5693 
5694  missionstr="PACE";
5695  senstr = "OCIS";
5696  monstr = std::to_string(selmon);
5697  daystr = std::to_string(selday);
5698  yearstr = std::to_string(selyear);
5699  timestr="T00:00:00Z";
5700  prodstr = "L1Cgrid";
5701  swtstr = "_swt";
5702  extstr = ".nc";
5703 
5704  if (l1cfile->l1c_pflag >= 3) {
5705  swtd = l1cfile->swtnum;
5706  swtnum = std::to_string(swtd);
5707  cout << "swtnum.." << swtnum << endl;
5708  }
5709  else swtnum = std::to_string(swtd);
5710 
5711 
5712  getcwd(tmp, 256);
5713  pathstr=tmp;
5714 
5715 //open lat/lon L1C grid --------------------------------------
5716  //PACE_OCIS.2019321T00:00:00ZL1Cgrid.nc
5717  ofilestr=std::string(l1cinput->ofile);
5718  gridname = pathstr + "/out/" +ofilestr + "_"+prodstr+extstr;
5719 
5720  cout<<"gridname.."<<gridname<<endl;
5721 
5722  //open file
5723  ifile_str = l1cinput->files[0];
5724  ifile_char = &ifile_str[0];
5725  file_format format = getFormat(ifile_char);
5726  // format.type=FT_HARP;
5727 
5728  if(format.type==FT_SPEXONE || format.type==FT_HARP){
5729  ptstr="/accounts/mamontes/images/OCIS/sean/out/PACE_OCIS.2019321T00:00:00ZL1Cgrid.nc";
5730  cout<<"ptstr..."<<ptstr<<endl;
5731  }
5732  else {//legacy sensors
5733  ptstr = gridname.c_str();
5734  }
5735 
5736  status = nc_open(ptstr, NC_NOWRITE, &ncid_grid);
5737  if (status != NC_NOERR) {
5738  fprintf(stderr, "nc_open error.\n");
5739  exit(EXIT_FAILURE);
5740  }
5741  //groups
5742  status = nc_inq_grp_ncid(ncid_grid, "geolocation_data", &geoGrp);
5743  check_err(status, __LINE__, __FILE__);
5744 
5745  status = nc_inq_dimid(ncid_grid, "bins_along_track", &y_dimid);
5746  check_err(status, __LINE__, __FILE__);
5747  nc_inq_dimlen(ncid_grid, y_dimid, &ybins);
5748  status = nc_inq_dimid(ncid_grid, "bins_across_track", &x_dimid);
5749  check_err(status, __LINE__, __FILE__);
5750 
5751  nc_inq_dimlen(ncid_grid, x_dimid, &xbins);
5752  nc_inq_dimlen(ncid_grid, y_dimid, &ybins);
5753 
5754  //************************************************************
5755  //mem allocation for geolocation pointers---
5756  num_gridlines=ybins;
5757  nbinx=xbins;
5758 
5759  cout<<"num_gridlines"<<num_gridlines<<"nbinx"<<nbinx<<endl;
5760 
5761  status = nc_inq_varid(geoGrp, "latitude", &latId);//scans x velements
5762  check_err(status, __LINE__, __FILE__);
5763  status = nc_inq_varid(geoGrp, "longitude", &lonId);//scans x velements
5764  check_err(status, __LINE__, __FILE__);
5765  status = nc_get_var_float(geoGrp, latId, &lat_gd[0][0]);
5766  check_err(status, __LINE__, __FILE__);
5767  status = nc_get_var_float(geoGrp, lonId, &lon_gd[0][0]);
5768  check_err(status, __LINE__, __FILE__);
5769 //close file
5770  if ((status = nc_close(ncid_grid)))
5771  check_err(status, __LINE__, __FILE__);
5772 
5773 
5774  //open az_east ------
5775  //PACE_OCIS.2019321T00:00:00Zaz_east.nc
5776  prodstr = "az_east";
5777 // cout << "Current working directory: " << tmp << endl;
5778 // azstr= pathstr + "/out/"+missionstr + "_" + senstr + "." + yearstr + monstr + daystr + timestr + prodstr+extstr;
5779  azstr= pathstr + "/out/"+ofilestr +"_"+ prodstr+extstr;
5780 
5781  if(format.type==FT_SPEXONE || format.type==FT_HARP){
5782  ptstr="/accounts/mamontes/images/OCIS/sean/out/PACE_OCIS.2019321T00:00:00Zaz_east.nc";
5783  }
5784  else{
5785  ptstr = azstr.c_str();
5786  }
5787  cout <<"Opening file with azimuth east values in degrees............" << ptstr << endl;
5788  // ptstr="/accounts/mamontes/images/OCIS/sean/out/PACE_OCIS.2019321T00:00:00Zaz_east.nc";
5789 
5790  status = nc_open(ptstr, NC_NOWRITE, &ncid_az);
5791  if (status != NC_NOERR) {
5792  fprintf(stderr, "nc_open error.\n");
5793  exit(EXIT_FAILURE);
5794  }
5795  status = nc_inq_dimid(ncid_az, "bins_along_track", &y_dimid);
5796  check_err(status, __LINE__, __FILE__);
5797  nc_inq_dimlen(ncid_az, y_dimid, &ybins);
5798 
5799  status = nc_inq_varid(ncid_az, "az_east", &azId);//scans x velements
5800  check_err(status, __LINE__, __FILE__);
5801  status = nc_get_var_float(ncid_az, azId, &az_east[0]);
5802  check_err(status, __LINE__, __FILE__);
5803 
5804  for(size_t i=0;i<ybins;i++){
5805  sum = az_east[i];
5806  tot += sum;
5807  }
5808 //close file
5809  if ((status = nc_close(ncid_az)))
5810  check_err(status, __LINE__, __FILE__);
5811 
5812  //using swath-averaged az_east for nadir pixels rather than along-track az_east pixel-by-pixel
5813  mean_az_east = tot / (ybins);
5814 
5815  l1cfile->mean_az_east=mean_az_east; //in degrees
5816  cout<<"mean_az_east in degrees...."<<mean_az_east<<endl;
5817 
5818 
5819 
5820  //recompute number of gridlines based on lat limits -80 to 80 degrees
5821  //asc orbit goes from negative to positive latitude....
5822  NY = num_gridlines;
5823  NX = nbinx;
5824  for (int i = 0; i < NY; i++) {
5825  for (int j = 0; j < NX; j++) {
5826  if (lat_gd[i][j] >= -80.) c1++;
5827  if (c1 == nbinx) {
5828  NY1 = i;
5829  }
5830  }
5831  if (NY1 >= 0) break;
5832  c1 = 1;
5833  }
5834 
5835 
5836  for (int i = 0;i < NY; i++) {
5837  // cout<<"i.."<<i<<"lat_gd[i][j]..."<<lat_gd[i][nadpix]<<endl;
5838  for (int j = 0; j < NX; j++) {
5839  if (lat_gd[i][j] >= 80.) {
5840  NY2 = i - 1;
5841  }
5842  }
5843 
5844  if (NY2 >= 0) break;
5845  }
5846 
5847  // cout<<"gridlines limited to -80 to 80 degrees of latitutde.."<<"gdline ini.."<<NY1<<"gdline end.."<<NY2<<endl;
5848 
5849  l1cfile->NY1 = NY1;
5850  l1cfile->NY2 = NY2;
5851 
5852  cout << "NY.." << NY << "NY1.." << NY1 << "NY2.." << NY2 << endl;
5853 
5854  num_gridlines = NY2 - NY1 + 1;//this is the # gridlines after -80 to 80 lat constraint---
5855 
5856  cout<<"numgridlines after restriction lat"<<num_gridlines<<endl;
5857  l1cfile->num_gridlines=num_gridlines;
5858 
5859 
5860  //*********** SORTING LAT/LON ASCENDING AND TRACK INDEXES ****************************
5861  //***********************************************************************************
5862 
5863  //Create index matrix for i and j of each lat and lon L1C grid (-80 to 80)
5864  //num_gridlines x nbinx
5865 
5866  //define 1-D vector to sort 1 col L1C grid at the time---
5867  vector<pair<float, int> > vp;
5868 
5869  //fill vector with lat_gd column--
5870  cout << "*********** SORTING LAT/LON GRIDPOINTS AND TRACKING INDEXES ********************" << endl;
5871 
5872 
5873  for (int col = 0;col < nbinx;col++) {
5874  for (int row = NY1;row < NY2 + 1;row++) {
5875  vp.push_back(make_pair(lat_gd[row][col] + 90., row));
5876  }
5877  //sort
5878  stable_sort(vp.begin(), vp.end());
5879 
5880  for (unsigned int i = 0; i < vp.size(); i++) {
5881  lat_asort[i][col] = vp[i].first;
5882  index_xy[i][col] = vp[i].second;
5883  }
5884  vp.clear();
5885  }
5886 
5887  cout<<"ok after sorting.............................."<<endl;
5888  return 0;
5889  }
5890 
5891 
5892 
5893 int32_t L1C::binL1C_sbs_line_l2(int swtd,L1C *l1c,l2_str *l2str,l1c_filehandle *l1cfile,L1C_input *l1cinput,int16_t* swtd_id,int16_t* file_id, int16_t* nfiles_swt,float **lat_gd, float **lon_gd,float *az_east,float **lat_asort,short **index_xy,float ****binmean_prod,int ****bincount,size_t sline,int granid){
5894 
5895  int32_t num_gridlines, nbinx;//number of gridlines to be processed
5896  std::string str,ofilestr;
5897  int status, ncid_out,p_dimid,v_dimid,x_dimid,y_dimid,varid1,varid2, varid_count,varid_prod,NDIMS,NDIMS3;
5898  int32_t bin_xpix, bin_ypix;
5899  int dimids[2],dimids3[4];
5900  const char* filename_lt;
5901  int32_t NY = -1, NX = -1, NY1 = -1, NY2 = -1;
5902  float****data_out2=nullptr,** lat_out=nullptr, ** lon_out=nullptr;
5903  int ****data_out=nullptr;
5904  int flag_inpix;//first index file id, second index line #
5905  bool boolbin1;
5906  char* ifile_char;
5907  std::string ifile_str;
5908  int16_t selyear = -1, selmon = -1, selday = -1;
5909  string gridname, azeast_name;
5910  int grp_obs,grp_coor;
5911  size_t NVIEWS=-1,NL2PRODS=-1;
5912  int view=0;
5913  short gd_row, gd_col;
5914  std::string fname_out, pathstr, senstr, monstr, daystr, yearstr, prodstr, gdstr, swtstr, swtnum, extstr, granstr,timestr,azstr,missionstr;
5915  size_t iprod;
5916 
5917  Geodesic geod(Constants::WGS84_a(), Constants::WGS84_f());
5918 
5919  //random seed
5920  srand((unsigned int)time(NULL));
5921 
5922  num_gridlines = l1cfile->num_gridlines;
5923  nbinx = l1cfile->nbinx;
5924  num_pixels = l1cfile->npix;
5925  num_scans=l1cfile->nscan;
5926  num_pixels=l1cfile->npix;
5927 
5928  ifile_str = l1cinput->files[0];
5929  ifile_char = &ifile_str[0];
5930  file_format format = getFormat(ifile_char);
5931 
5932 
5933  //allocate mem for lat/lon/azeast pointers---
5934  //determine # of gd groups to be processede
5935  //gdlines_group=num_gridlines;//ONE BIG GROUP
5936 
5937  //--NORMALIZED gridline longitude is -180 to 180 degrees before comparison with longitude extracted from image pixels---
5938  for (int i = 0; i < num_gridlines; i++) {
5939  for (int j = 0; j < nbinx; j++) {
5940  if (lon_gd[i][j] < -180.)lon_gd[i][j] += 360.;
5941  if (lon_gd[i][j] > 180.)lon_gd[i][j] -= 360.;
5942  }
5943  }
5944 
5945 //********* LOOP FILES ************************************
5946 
5947  //radiance variables
5948  if(format.type==FT_SPEXONE){
5949  NVIEWS= 5;//should be 5 but only provided 1
5950  }
5951  else if(format.type==FT_HARP){
5952  NVIEWS= 1;//HARP-2 10 but 60 for 669 nm
5953  }
5954  else{//OCIS
5955  NVIEWS= l1cfile->n_views;//for OCI
5956  NL2PRODS=l2str->nl2prod;
5957  }
5958 
5959 
5960 
5961 //BIG SCANLINE LOOP----------------------------------
5962  //********************************************************************************
5963  //-----reading line by line-----------------------------------
5964 
5965  //*********** BIG LOOP M_PIXEL *****************************************************************
5966  for (unsigned int pix = 0;pix < num_pixels;pix++) {
5967  gd_row=0,gd_col=0;
5968  flag_inpix = 0;
5969  iprod=0;
5970 
5971  // cout<<"pix..."<<pix+1<<"latpix..."<<l1cstr->latpix[pix]<<"lonpix..."<<l1cstr->lonpix[pix]<<"sensor azimuth.."<<l1cstr->senazpix[pix]/100<<endl;
5972 
5973  boolbin1 = sbs2_l1c(l1cinput, num_gridlines, nbinx, lat_asort, index_xy, l2str->latpix[pix], l2str->lonpix[pix], lon_gd, &gd_row, &gd_col);
5974 
5975  bin_ypix = gd_row + 1;
5976  bin_xpix = gd_col + 1;
5977  // cout<<"boolbin1.."<<boolbin1<<"bin_ypix............................."<<bin_ypix<<"bin_xpix........................."<<bin_xpix<<endl;
5978 
5979  if (boolbin1 == 1) flag_inpix = 1;
5980  //************ BINNING ***************************
5981  //assign identified pixel to Lt and bin stat arrays-----
5982 
5983 
5984  if (flag_inpix == 1 && bin_xpix >= 1 && bin_ypix >= 1 && bin_xpix <= nbinx && bin_ypix <= num_gridlines && l2str->latpix[pix]>=l1cinput->binlatmin && l2str->latpix[pix]<=l1cinput->binlatmax && l2str->lonpix[pix]>=l1cinput->binlonmin && l2str->lonpix[pix]<=l1cinput->binlonmax) {
5985  INPIX++;
5986  if(format.type==FT_SPEXONE){
5987  view=0;
5988  /* while (sb<NBANDS) {
5989  if (l1cstr->Lt[pix][ib] > 0.) {
5990  binmean_Lt[view][ib][bin_ypix - 1][bin_xpix - 1] = binmean_Lt[view][ib][bin_ypix - 1][bin_xpix - 1] + l1cstr->Lt[pix][ib];
5991  bincount[view][ib][bin_ypix - 1][bin_xpix - 1] += 1;
5992  }
5993  ib++;
5994  sb++;
5995  }//end while intensity bands
5996  */
5997  }
5998 
5999  else if(format.type==FT_HARP){
6000  view=0;
6001  /* if (l1cstr->Lt[pix][ib] > 0.) {
6002  binmean_Lt[view][ib][bin_ypix - 1][bin_xpix - 1] = binmean_Lt[view][ib][bin_ypix - 1][bin_xpix - 1] + l1cstr->Lt[pix][ib];
6003  bincount[view][ib][bin_ypix - 1][bin_xpix - 1] += 1;
6004  }
6005  ib++;
6006  sb++;*/
6007  }
6008  else{ //OCIS
6009 
6010  if(l2str->tilt[sline]<=0) view=0; else view=1;
6011  while (iprod<NL2PRODS) {
6012  // cout<<"binning OCIS L2 products........................................................................................................."<<endl;
6013  // cout<<"l2str->l2prod[iprod][pix]..."<<l2str->l2prod[iprod][pix]<<endl;
6014  if (l2str->l2prod[iprod][pix] > 0.) {
6015  cout<<"**********************************************************************************************************************************************************"<<endl;
6016  cout<<"l2str->l2prod[iprod][pix]..."<<l2str->l2prod[iprod][pix]*l2str->slopeprod[iprod]+l2str->offsetprod[iprod]<<"bin_ypix.."<<bin_ypix<<"bin_xpix.."<<bin_xpix<<endl;
6017  cout<<"pix..."<<pix+1<<"latpix..."<<l2str->latpix[pix]<<"lonpix..."<<l2str->lonpix[pix]<<endl;
6018  cout<<"**********************************************************************************************************************************************************"<<endl;
6019 
6020  binmean_prod[view][iprod][bin_ypix - 1][bin_xpix - 1] = binmean_prod[view][iprod][bin_ypix - 1][bin_xpix - 1] + l2str->l2prod[iprod][pix]*l2str->slopeprod[iprod]+l2str->offsetprod[iprod];
6021  bincount[view][iprod][bin_ypix - 1][bin_xpix - 1] += 1;
6022  }
6023  iprod++;
6024 
6025  }//end products
6026 
6027  }
6028 
6029  }//end if INPIX==1
6030 
6031 
6032 
6033  //********** pixel AREA WEIGHTING ************************
6034  if (flag_inpix == 0) OUTPIX++;
6035 
6036  TOTPIX++;
6037 
6038  }//end pixels loop
6039 
6040 
6041  //END OF FILE--****** reset starting sline index if last line processed and within k box
6042  //go for another granule if it is not the last one---------------
6043 
6044  //***** skip lines and files if sline is not within k group ********
6045  //increase k and screen files and lines again starting from the last binning
6046 
6047 
6048  //**********************************************************************************************************************************
6049  //writing each granule ---------------------------------
6050  //*****************************************************************************
6051 
6052  if (sline==num_scans-1) {
6053  cout << "writing file #....................................................................................................................." <<l1cfile->l1b_name<< endl;
6054  //write mean Lt as nc file---
6055  //**********************************************************************
6056  //**********************************************************************8
6057  //create Lt file
6058  pathstr = "out/";
6059  missionstr="PACE";
6060  senstr = "OCIS_";
6061  timestr="T00:00:00Z";
6062  selday = l1cinput->selday;
6063  selmon = l1cinput->selmon;
6064  selyear = l1cinput->selyear;
6065  monstr = std::to_string(selmon);
6066  daystr = std::to_string(selday);
6067  yearstr = std::to_string(selyear);
6068  prodstr = "binL2_sbs_LINEBYLINE";
6069  swtstr = "_swt";
6070  granstr = "_" + std::to_string(granid);
6071 
6072 
6073  if (l1cfile->l1c_pflag >= 3) {
6074  swtd = l1cfile->swtnum;
6075  swtnum = std::to_string(swtd);
6076  cout << "swtnum.." << swtnum << endl;
6077  }
6078  else swtnum = std::to_string(swtd);
6079 
6080  extstr = ".nc";
6081  string GATT_NAME1,GATT_VAL1,GATT_NAME2,GATT_VAL2;
6082 
6083  if(format.type==FT_SPEXONE){
6084  senstr = "SPEXONE";
6085  GATT_NAME1="Title",GATT_VAL1="PACE SPEXone Level-1C Data",GATT_NAME2="instrument",GATT_VAL2="SPEXone";
6086  }
6087  else//OCIS
6088  {
6089  senstr = "OCI";
6090  GATT_NAME1="Title",GATT_VAL1="PACE OCI Level-1C Data",GATT_NAME2="instrument",GATT_VAL2="OCI";
6091  }
6092 
6093  // fname_out = pathstr + missionstr + "_" + senstr + "." + yearstr + monstr + daystr + timestr + prodstr+granstr+extstr;
6094  ofilestr=std::string(l1cinput->ofile);
6095  fname_out = pathstr + ofilestr+"_"+ prodstr+granstr+extstr;
6096 
6097  string ATT_NAME="Units", ATT_VAL="degrees",GATT_NAME3="processing_version",GATT_VAL3="V1.0",GATT_NAME4="Conventions",GATT_VAL4="CF-1.6";
6098  string GATT_NAME5="institution",GATT_VAL5="NASA Goddard Space Flight Center, Ocean Biology Processing Group",GATT_NAME6="license",GATT_VAL6="http://science.nasa.gov/earth-science/earth-science-data/data-information-policy/";
6099  string GATT_NAME7="naming_authority",GATT_VAL7="gov.nasa.gsfc.sci.oceancolor",GATT_NAME8="keywords_vocabulary",GATT_VAL8="NASA Global Change Master Directory (GCMD) Science Keywords";
6100  string GATT_NAME9="stdname_vocabulary",GATT_VAL9="NetCDF Climate and Forecast (CF) Metadata Convention",GATT_NAME10="creator_name",GATT_VAL10="NASA/GSFC",GATT_NAME11="creator_email",GATT_VAL11="data@oceancolor.gsfc.nasa.gov";
6101  string GATT_NAME12="creator_url",GATT_VAL12="http://oceancolor.gsfc.nasa.gov",GATT_NAME13="project",GATT_VAL13="PACE Project",GATT_NAME14="publisher_name",GATT_VAL14="NASA/GSFC";
6102  string GATT_NAME15="publisher_email",GATT_VAL15="data@oceancolor.gsfc.nasa.gov",GATT_NAME16="publisher_url",GATT_VAL16="http://oceancolor.gsfc.nasa.gov",GATT_NAME17="processing_level",GATT_VAL17="L1C";
6103  string GATT_NAME18="cdm_data_type",GATT_VAL18="swath",GATT_NAME19="orbit_number",GATT_VAL19="12345",GATT_NAME20="history",GATT_VAL20="",GATT_NAME21="CDL_version_date",GATT_VAL21="2021-09-10",GATT_NAME22="product_name",GATT_VAL22=fname_out;
6104  string GATT_NAME23="startDirection",GATT_VAL23="Ascending",GATT_NAME24="endDirection",GATT_VAL24="Ascending",GATT_NAME25="time_coverage_start",GATT_VAL25=yearstr+"-"+monstr+"-"+daystr+"-"+timestr,GATT_NAME26="time_coverage_end",GATT_VAL26=yearstr+"-"+monstr+"-"+daystr+"-"+timestr,GATT_NAME27="date{_created",GATT_VAL27="2021-09-10T15:12:41Z",GATT_NAME28="sun_earth_distance",GATT_VAL28="0.990849042172323",GATT_NAME29="terrain_data_source",GATT_VAL29="",GATT_NAME30="spectral_response_function",GATT_VAL30="",GATT_NAME31="systematic_uncertainty_model",GATT_VAL31="",GATT_NAME32="nadir_bin",GATT_VAL32="12345",GATT_NAME33="bin_size_at_nadir",GATT_VAL33="5.2km2",GATT_NAME34="L2_products",GATT_VAL34=l1cinput->l2prod;
6105 
6106  l1cfile->gridname = fname_out.c_str();
6107  filename_lt = fname_out.c_str();
6108  cout<<"filename_lt.."<<filename_lt<<endl;
6109 
6110  if ((status = nc_create(filename_lt, NC_CLOBBER | NC_NETCDF4, &ncid_out)))
6111  check_err(status, __LINE__, __FILE__);
6112  //define dims
6113  // Define the dimensions,vars and attributes at the root level
6114  NDIMS=2;
6115  NDIMS3=4;
6116  NY = num_gridlines;
6117  NX = nbinx;
6118  //NVIEWS= 2;//for OCI
6119  // NBANDS=249;//for OCI
6120 
6121  NY1 = l1cfile->NY1;//these are indexes not line #!!!!!!!!!!!!!!!!!
6122  NY2 = l1cfile->NY2;
6123  cout << "rowgrid ini.." << NY1 << "rowgrid end.." << NY2 << endl;
6124  NY = NY2 - NY1 + 1;
6125  cout << "NY.." << NY << "NX.." << NX << "NY1.."<<NY1<<"NY2.."<<NY2<<endl;
6126 
6127  //DEF DIMENSIONS
6128  if ((status = nc_def_dim(ncid_out, "bins_across_track", NX, &x_dimid)))
6129  check_err(status, __LINE__, __FILE__);
6130  if ((status = nc_def_dim(ncid_out, "bins_along_track", NY, &y_dimid)))
6131  check_err(status, __LINE__, __FILE__);
6132  //dims for output var
6133  dimids[0] = y_dimid;
6134  dimids[1] = x_dimid;
6135 
6136  if ((status = nc_def_dim(ncid_out, "number_of_views", NVIEWS, &v_dimid)))
6137  check_err(status, __LINE__, __FILE__);
6138  if ((status = nc_def_dim(ncid_out, "l2_products", NL2PRODS, &p_dimid)))
6139  check_err(status, __LINE__, __FILE__);
6140 
6141  dimids3[0] = y_dimid;
6142  dimids3[1] = x_dimid;
6143  dimids3[2] = v_dimid;//
6144  dimids3[3] = p_dimid;
6145 
6146  //define attributes
6147  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME1.c_str(), strlen(GATT_VAL1.c_str()),
6148  GATT_VAL1.c_str()))
6149  check_err(status, __LINE__, __FILE__);
6150  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME2.c_str(), strlen(GATT_VAL2.c_str()),
6151  GATT_VAL2.c_str()))
6152  check_err(status, __LINE__, __FILE__);
6153  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME3.c_str(), strlen(GATT_VAL3.c_str()),
6154  GATT_VAL3.c_str()))
6155  check_err(status, __LINE__, __FILE__);
6156  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME4.c_str(), strlen(GATT_VAL4.c_str()),
6157  GATT_VAL4.c_str()))
6158  check_err(status, __LINE__, __FILE__);
6159  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME5.c_str(), strlen(GATT_VAL5.c_str()),
6160  GATT_VAL5.c_str()))
6161  check_err(status, __LINE__, __FILE__);
6162  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME6.c_str(), strlen(GATT_VAL6.c_str()),
6163  GATT_VAL6.c_str()))
6164  check_err(status, __LINE__, __FILE__);
6165  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME7.c_str(), strlen(GATT_VAL7.c_str()),
6166  GATT_VAL7.c_str()))
6167  check_err(status, __LINE__, __FILE__);
6168  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME8.c_str(), strlen(GATT_VAL8.c_str()),
6169  GATT_VAL8.c_str()))
6170  check_err(status, __LINE__, __FILE__);
6171  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME9.c_str(), strlen(GATT_VAL9.c_str()),
6172  GATT_VAL9.c_str()))
6173  check_err(status, __LINE__, __FILE__);
6174  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME10.c_str(), strlen(GATT_VAL10.c_str()),
6175  GATT_VAL10.c_str()))
6176  check_err(status, __LINE__, __FILE__);
6177  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME11.c_str(), strlen(GATT_VAL11.c_str()),
6178  GATT_VAL11.c_str()))
6179  check_err(status, __LINE__, __FILE__);
6180  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME12.c_str(), strlen(GATT_VAL12.c_str()),
6181  GATT_VAL12.c_str()))
6182  check_err(status, __LINE__, __FILE__);
6183  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME13.c_str(), strlen(GATT_VAL13.c_str()),
6184  GATT_VAL13.c_str()))
6185  check_err(status, __LINE__, __FILE__);
6186  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME14.c_str(), strlen(GATT_VAL14.c_str()),
6187  GATT_VAL14.c_str()))
6188  check_err(status, __LINE__, __FILE__);
6189  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME15.c_str(), strlen(GATT_VAL15.c_str()),
6190  GATT_VAL15.c_str()))
6191  check_err(status, __LINE__, __FILE__);
6192  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME16.c_str(), strlen(GATT_VAL16.c_str()),
6193  GATT_VAL16.c_str()))
6194  check_err(status, __LINE__, __FILE__);
6195  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME17.c_str(), strlen(GATT_VAL17.c_str()),
6196  GATT_VAL17.c_str()))
6197  check_err(status, __LINE__, __FILE__);
6198  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME18.c_str(), strlen(GATT_VAL18.c_str()),
6199  GATT_VAL18.c_str()))
6200  check_err(status, __LINE__, __FILE__);
6201  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME19.c_str(), strlen(GATT_VAL19.c_str()),
6202  GATT_VAL19.c_str()))
6203  check_err(status, __LINE__, __FILE__);
6204  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME20.c_str(), strlen(GATT_VAL20.c_str()),
6205  GATT_VAL20.c_str()))
6206  check_err(status, __LINE__, __FILE__);
6207  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME21.c_str(), strlen(GATT_VAL21.c_str()),
6208  GATT_VAL21.c_str()))
6209  check_err(status, __LINE__, __FILE__);
6210  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME22.c_str(), strlen(GATT_VAL22.c_str()),
6211  GATT_VAL22.c_str()))
6212  check_err(status, __LINE__, __FILE__);
6213  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME23.c_str(), strlen(GATT_VAL23.c_str()),
6214  GATT_VAL23.c_str()))
6215  check_err(status, __LINE__, __FILE__);
6216  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME24.c_str(), strlen(GATT_VAL24.c_str()),
6217  GATT_VAL24.c_str()))
6218  check_err(status, __LINE__, __FILE__);
6219  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME25.c_str(), strlen(GATT_VAL25.c_str()),
6220  GATT_VAL25.c_str()))
6221  check_err(status, __LINE__, __FILE__);
6222  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME26.c_str(), strlen(GATT_VAL26.c_str()),
6223  GATT_VAL26.c_str()))
6224  check_err(status, __LINE__, __FILE__);
6225  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME27.c_str(), strlen(GATT_VAL27.c_str()),
6226  GATT_VAL27.c_str()))
6227  check_err(status, __LINE__, __FILE__);
6228  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME28.c_str(), strlen(GATT_VAL28.c_str()),
6229  GATT_VAL28.c_str()))
6230  check_err(status, __LINE__, __FILE__);
6231  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME29.c_str(), strlen(GATT_VAL29.c_str()),
6232  GATT_VAL29.c_str()))
6233  check_err(status, __LINE__, __FILE__);
6234  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME30.c_str(), strlen(GATT_VAL30.c_str()),
6235  GATT_VAL30.c_str()))
6236  check_err(status, __LINE__, __FILE__);
6237  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME31.c_str(), strlen(GATT_VAL31.c_str()),
6238  GATT_VAL31.c_str()))
6239  check_err(status, __LINE__, __FILE__);
6240  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME32.c_str(), strlen(GATT_VAL32.c_str()),
6241  GATT_VAL32.c_str()))
6242  check_err(status, __LINE__, __FILE__);
6243  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME33.c_str(), strlen(GATT_VAL33.c_str()),
6244  GATT_VAL33.c_str()))
6245  check_err(status, __LINE__, __FILE__);
6246  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME34.c_str(), strlen(GATT_VAL34.c_str()),
6247  GATT_VAL34.c_str()))
6248  check_err(status, __LINE__, __FILE__);
6249 
6250  //define groups check_err(status, __LINE__, __FILE__);
6251  if ((status = nc_def_grp(ncid_out, "geolocation_data", &grp_coor))) //netcdf-4
6252  check_err(status, __LINE__, __FILE__);
6253  //def var grp1
6254  if ((status = nc_def_var(grp_coor, "latitude", NC_FLOAT, NDIMS,
6255  dimids, &varid1)))
6256  check_err(status, __LINE__, __FILE__);
6257  if ((status = nc_def_var(grp_coor, "longitude", NC_FLOAT, NDIMS,
6258  dimids, &varid2)))
6259  check_err(status, __LINE__, __FILE__);
6260 
6261  //leave define mode-----------------------
6262  if ((status = nc_enddef(grp_coor))) //done def vars etc
6263  check_err(status, __LINE__, __FILE__);
6264 
6265 
6266  if ((status = nc_def_grp(ncid_out, "observation_data", &grp_obs))) //netcdf-4
6267  check_err(status, __LINE__, __FILE__);
6268  //def var grp2
6269  //counts and Lt
6270  if ((status = nc_def_var(grp_obs, "obs_per_view", NC_INT, NDIMS3,
6271  dimids3, &varid_count)))
6272  check_err(status, __LINE__, __FILE__);
6273  if ((status = nc_def_var(grp_obs, "l2_product", NC_FLOAT, NDIMS3,
6274  dimids3, &varid_prod)))
6275  check_err(status, __LINE__, __FILE__);
6276 
6277  //leave define mode-----------------------
6278  if ((status = nc_enddef(grp_obs))) //done def vars etc
6279  check_err(status, __LINE__, __FILE__);
6280 
6281 
6282  lat_out = allocate2d_float(NY, NX);
6283  lon_out = allocate2d_float(NY, NX);
6284 
6285  int c = 0;
6286 
6287  for (int i = NY1; i < NY2 + 1; i++) {
6288  for (int j = 0; j < NX; j++) {
6289  lat_out[NY - 1 - c][NX - 1 - j] = lat_gd[i][j];
6290  lon_out[NY - 1 - c][j] = lon_gd[i][j];
6291  }
6292  c++;
6293  }
6294 
6295  if ((status = nc_put_var_float(grp_coor, varid1, &lat_out[0][0])))
6296  check_err(status, __LINE__, __FILE__);
6297 
6298  if ((status = nc_put_var_float(grp_coor, varid2, &lon_out[0][0])))
6299  check_err(status, __LINE__, __FILE__);
6300 
6301 
6302  //alloc mem for output variables obs_per_view and I as part of the observation_data group
6303  data_out = allocate4d_int(NY, NX,NVIEWS,NL2PRODS);
6304  data_out2 = allocate4d_float(NY, NX,NVIEWS,NL2PRODS);
6305 
6306  //BINCOUNT ARRAY
6307 
6308  c = 0;
6309  for (size_t v = 0; v < NVIEWS; v++) {
6310  for (size_t p = 0;p <NL2PRODS;p++) {
6311  for (int i = NY1; i < NY2 + 1; i++) {
6312  for (int j = 0; j < NX; j++) {
6313  if(bincount[v][p][i][j]>0)
6314  data_out[NY - 1 - c][NX - 1 - j][v][p]+=bincount[v][p][i][j];
6315  else
6316  data_out[NY - 1 - c][NX - 1 - j][v][p]+=0;
6317  }
6318  }
6319  c++;
6320  }
6321  c=0;
6322  }
6323 
6324 
6325  cout << "writing countbin for all L2 products ."<< endl;
6326  if ((status = nc_put_var_int(grp_obs, varid_count, &data_out[0][0][0][0])))
6327  check_err(status, __LINE__, __FILE__);
6328 
6329  // l2 products ARRAYS
6330  c=0;
6331  for (size_t v = 0;v <NVIEWS;v++) {
6332  for (size_t p = 0; p <NL2PRODS; p++) {
6333  for (int i = NY1; i < NY2 + 1; i++) {
6334  for (int j = 0; j < NX; j++) {
6335  if (bincount[v][p][i][j] > 0)
6336  data_out2[NY - 1 - c][NX - 1 - j][v][p] = binmean_prod[v][p][i][j] / bincount[v][p][i][j];
6337  else data_out2[NY - 1 - c][NX - 1 - j][v][p] = NAN;
6338  }
6339  c++;
6340  }
6341  c=0;
6342  }//end views
6343  }//end for bands
6344 
6345  cout << "writing L2 products .."<< endl;
6346  if ((status = nc_put_var_float(grp_obs, varid_prod, &data_out2[0][0][0][0])))
6347  check_err(status, __LINE__, __FILE__);
6348 
6349  delete [] (data_out);
6350  delete [] (data_out2);
6351  delete[](lat_out);
6352  delete[](lon_out);
6353 
6354  if ((status = nc_close(ncid_out)))
6355  check_err(status, __LINE__, __FILE__);
6356 
6357  lat_out = nullptr;;
6358  lon_out = nullptr;
6359  data_out = nullptr;
6360  data_out2 = nullptr;
6361 
6362  cout << "number of files per swath.." << nfiles_swt[swtd - 1] << "for swath.." << swtd << endl;
6363  cout << "total inpix.." << INPIX << "total pix.." << TOTPIX << endl;
6364  printf("*** SUCCESS writing bincount and binLt rasters as nc..!\n");
6365  cout<<"LINE-BY-LINE sbs binning method....."<<endl;
6366  }//end writing file
6367 
6368 
6369 return 0;
6370 }
6371 
6372 
6373 
6374 int32_t L1C::binL1C_sbs_line(int swtd,L1C *l1c,l1c_str *l1cstr,l1c_filehandle *l1cfile,L1C_input *l1cinput,int16_t* swtd_id,int16_t* file_id, int16_t* nfiles_swt,float **lat_gd, float **lon_gd,float *az_east,float **lat_asort,short **index_xy,float ****binmean_Lt,int ****bincount,size_t sline,int granid){
6375 
6376  int32_t num_gridlines, nbinx;//number of gridlines to be processed
6377  std::string str,ofilestr;
6378  int status, ncid_out,b_dimid,v_dimid,x_dimid,y_dimid,varid1,varid2, varid_count,varid_lt,NDIMS,NDIMS2,NDIMS3;
6379  int32_t bin_xpix, bin_ypix;
6380  int dimids[2],dimids2[3],dimids3[4];
6381  const char* filename_lt;
6382  int32_t NY = -1, NX = -1, NY1 = -1, NY2 = -1;
6383  float****data_out2=nullptr,** lat_out=nullptr, ** lon_out=nullptr;
6384  int ***data_out=nullptr;
6385  int flag_inpix;//first index file id, second index line #
6386  bool boolbin1;
6387  char* ifile_char;
6388  std::string ifile_str;
6389  int16_t selyear = -1, selmon = -1, selday = -1;
6390  string gridname, azeast_name;
6391  int grp_obs,grp_coor;
6392  size_t sb=0,bb = 0, rb = 0, swb = 0,ib=0, NVIEWS=-1,NBANDS=-1,NBANDS_POL=-1;
6393  int view=0;
6394  short gd_row, gd_col;
6395  std::string fname_out, pathstr, senstr, monstr, daystr, yearstr, prodstr, gdstr, swtstr, swtnum, extstr, granstr,timestr,azstr,missionstr;
6396 
6397 
6398 
6399  Geodesic geod(Constants::WGS84_a(), Constants::WGS84_f());
6400 
6401  //random seed
6402  srand((unsigned int)time(NULL));
6403  //nadir pixel ofr OCI
6404  int nadpix = l1cfile->nadpix;
6405  // cout<<"nadpix index......"<<nadpix<<endl;
6406 
6407  num_gridlines = l1cfile->num_gridlines;
6408  nbinx = l1cfile->nbinx;
6409  num_pixels = l1cfile->npix;
6410  num_scans=l1cfile->nscan;
6411  num_pixels=l1cfile->npix;
6412 
6413  ifile_str = l1cinput->files[0];
6414  ifile_char = &ifile_str[0];
6415  file_format format = getFormat(ifile_char);
6416  // num_frames=l1cfile->nframes;
6417 
6418 
6419 // cout<<"binning Lt using sbs2 method and composite indexes for arrays..................................................................."<<endl;
6420 
6421  //allocate mem for lat/lon/azeast pointers---
6422  //determine # of gd groups to be processede
6423  //gdlines_group=num_gridlines;//ONE BIG GROUP
6424 
6425  //--NORMALIZED gridline longitude is -180 to 180 degrees before comparison with longitude extracted from image pixels---
6426  for (int i = 0; i < num_gridlines; i++) {
6427  for (int j = 0; j < nbinx; j++) {
6428  if (lon_gd[i][j] < -180.)lon_gd[i][j] += 360.;
6429  if (lon_gd[i][j] > 180.)lon_gd[i][j] -= 360.;
6430  }
6431  }
6432 
6433 //********* LOOP FILES ************************************
6434 
6435  //radiance variables
6436  if(format.type==FT_SPEXONE){
6437  NVIEWS= 1;//should be 5 but only provided 1
6438  NBANDS=400;
6439  NBANDS_POL=50;
6440  cout << "#total number of Intensity bands per view.." << NBANDS << endl;
6441  cout << "#total number of Polarization bands per view.." << NBANDS_POL << endl;
6442  }
6443  else if(format.type==FT_HARP){
6444  NVIEWS= 1;//HARP-2 10 but 60 for 669 nm
6445  NBANDS=1;//
6446  NBANDS_POL=1;
6447  cout << "#total number of Intensity bands per view.." << NBANDS << endl;
6448  cout << "#total number of Polarization bands per view.." << NBANDS_POL << endl;
6449  }
6450  else{//OCIS
6451  NVIEWS= l1cfile->n_views;//for OCI
6452  NBANDS=l1cfile->nbands;//for OCI
6453  num_blue_bands=l1cfile->nband_blue;
6454  num_red_bands=l1cfile->nband_red;
6455  num_SWIR_bands=l1cfile->nband_swir;
6456  }
6457 
6458 //BIG SCANLINE LOOP----------------------------------
6459  //********************************************************************************
6460  //-----reading line by line-----------------------------------
6461 
6462  //*********** BIG LOOP M_PIXEL *****************************************************************
6463  for (unsigned int pix = 0;pix < num_pixels;pix++) {
6464  sb=0,bb=0,rb=0,swb=0,ib=0;
6465  gd_row=0,gd_col=0;
6466  flag_inpix = 0;
6467 
6468  // cout<<"pix..."<<pix+1<<"latpix..."<<l1cstr->latpix[pix]<<"lonpix..."<<l1cstr->lonpix[pix]<<"sensor azimuth.."<<l1cstr->senazpix[pix]/100<<endl;
6469 
6470  boolbin1 = sbs2_l1c(l1cinput, num_gridlines, nbinx, lat_asort, index_xy, l1cstr->latpix[pix], l1cstr->lonpix[pix], lon_gd, &gd_row, &gd_col);
6471 
6472  bin_ypix = gd_row + 1;
6473  bin_xpix = gd_col + 1;
6474  // cout<<"boolbin1.."<<boolbin1<<"bin_ypix.."<<bin_ypix<<"bin_xpix.."<<bin_xpix<<endl;
6475 
6476  if (boolbin1 == 1) flag_inpix = 1;
6477  //************ BINNING ***************************
6478  //assign identified pixel to Lt and bin stat arrays-----
6479 
6480 
6481  if (flag_inpix == 1 && bin_xpix >= 1 && bin_ypix >= 1 && bin_xpix <= nbinx && bin_ypix <= num_gridlines && l1cstr->latpix[pix]>=l1cinput->binlatmin && l1cstr->latpix[pix]<=l1cinput->binlatmax && l1cstr->lonpix[pix]>=l1cinput->binlonmin && l1cstr->lonpix[pix]<=l1cinput->binlonmax) {
6482  INPIX++;
6483  if(format.type==FT_SPEXONE){
6484  view=0;
6485  while (sb<NBANDS) {
6486  if (l1cstr->Lt[pix][ib] > 0.) {
6487  binmean_Lt[view][ib][bin_ypix - 1][bin_xpix - 1] = binmean_Lt[view][ib][bin_ypix - 1][bin_xpix - 1] + l1cstr->Lt[pix][ib];
6488  bincount[view][ib][bin_ypix - 1][bin_xpix - 1] += 1;
6489  }
6490  ib++;
6491  sb++;
6492  }//end while intensity bands
6493 
6494 
6495 
6496 /* while (sb<num_blue_bands) {
6497  if (Lt_pix2[bb][pix] > 0.) {
6498  binmean_Lt[view][sb][bin_ypix - 1][bin_xpix - 1] = binmean_Lt[view][sb][bin_ypix - 1][bin_xpix - 1] + Lt_pix2[bb][pix];
6499  bincount[view][sb][bin_ypix - 1][bin_xpix - 1] += 1;
6500  }
6501  bb++;
6502  sb++;
6503  }//end while polarization bands
6504 */
6505 
6506  }
6507 
6508  else if(format.type==FT_HARP){
6509  view=0,sb=0;
6510  if (l1cstr->Lt[pix][ib] > 0.) {
6511  binmean_Lt[view][ib][bin_ypix - 1][bin_xpix - 1] = binmean_Lt[view][ib][bin_ypix - 1][bin_xpix - 1] + l1cstr->Lt[pix][ib];
6512  bincount[view][ib][bin_ypix - 1][bin_xpix - 1] += 1;
6513  }
6514  ib++;
6515  sb++;
6516  }
6517  else{ //OCIS
6518  //BLUE---
6519  if(l1cstr->senazpix[nadpix]/100<0) view=0; else view=1;
6520  while (sb<num_blue_bands) {
6521  if (l1cstr->Lt_blue[bb][pix] > 0.) {
6522  // cout<<"Lt_pix[pix][ib]..."<<l1cstr->Lt_blue[bb][pix]<<"bin_ypix.."<<bin_ypix<<"bin_xpix.."<<bin_xpix<<endl;
6523  // cout<<"pix..."<<pix+1<<"latpix..."<<l1cstr->latpix[pix]<<"lonpix..."<<l1cstr->lonpix[pix]<<"sensor azimuth pixel.."<<l1cstr->senazpix[pix]/100<<endl;
6524 
6525  binmean_Lt[view][sb][bin_ypix - 1][bin_xpix - 1] = binmean_Lt[view][sb][bin_ypix - 1][bin_xpix - 1] + l1cstr->Lt_blue[bb][pix];
6526  bincount[view][sb][bin_ypix - 1][bin_xpix - 1] += 1;
6527  }
6528  bb++;
6529  sb++;
6530  }//end while blue band band
6531 
6532  //RED---
6533  while (sb <num_blue_bands+num_red_bands) {
6534  if (l1cstr->Lt_red[rb][pix] > 0.) {
6535  binmean_Lt[view][sb][bin_ypix - 1][bin_xpix - 1] = binmean_Lt[view][sb][bin_ypix - 1][bin_xpix - 1] + l1cstr->Lt_red[rb][pix];
6536  bincount[view][sb][bin_ypix - 1][bin_xpix - 1] += 1;
6537  }
6538  rb++;
6539  sb++;
6540  }//end red bands
6541 
6542  //SWIR----
6543  while (sb <num_blue_bands + num_red_bands + num_SWIR_bands) {
6544  if (l1cstr->Lt_SWIR[swb][pix] > 0.) {
6545  binmean_Lt[view][sb][bin_ypix - 1][bin_xpix - 1] = binmean_Lt[view][sb][bin_ypix - 1][bin_xpix - 1] + l1cstr->Lt_SWIR[swb][pix];
6546  bincount[view][sb][bin_ypix - 1][bin_xpix - 1] += 1;
6547  }
6548  swb++;
6549  sb++;
6550  }//end swir bands
6551  }
6552 
6553  }//end if INPIX==1
6554 
6555 
6556 
6557  //********** pixel AREA WEIGHTING ************************
6558  if (flag_inpix == 0) OUTPIX++;
6559 
6560  TOTPIX++;
6561 
6562  }//end pixels loop
6563 
6564 
6565  //END OF FILE--****** reset starting sline index if last line processed and within k box
6566  //go for another granule if it is not the last one---------------
6567 
6568  //***** skip lines and files if sline is not within k group ********
6569  //increase k and screen files and lines again starting from the last binning
6570 
6571 
6572  //**********************************************************************************************************************************
6573  //writing each granule ---------------------------------
6574  //*****************************************************************************
6575 
6576  if (sline==num_scans-1) {
6577  cout << "writing file #....................................................................................................................." <<l1cfile->l1b_name<< endl;
6578  //write mean Lt as nc file---
6579  //**********************************************************************
6580  //**********************************************************************8
6581  //create Lt file
6582  pathstr = "out/";
6583  missionstr="PACE";
6584  senstr = "OCIS_";
6585  timestr="T00:00:00Z";
6586  selday = l1cinput->selday;
6587  selmon = l1cinput->selmon;
6588  selyear = l1cinput->selyear;
6589  monstr = std::to_string(selmon);
6590  daystr = std::to_string(selday);
6591  yearstr = std::to_string(selyear);
6592  prodstr = "binLt_sbs_LINEBYLINE";
6593  swtstr = "_swt";
6594  granstr = "_" + std::to_string(granid);
6595 
6596 
6597  if (l1cfile->l1c_pflag >= 3) {
6598  swtd = l1cfile->swtnum;
6599  swtnum = std::to_string(swtd);
6600  cout << "swtnum.." << swtnum << endl;
6601  }
6602  else swtnum = std::to_string(swtd);
6603 
6604  extstr = ".nc";
6605  string GATT_NAME1,GATT_VAL1,GATT_NAME2,GATT_VAL2;
6606 
6607  if(format.type==FT_SPEXONE){
6608  senstr = "SPEXONE";
6609  GATT_NAME1="Title",GATT_VAL1="PACE SPEXone Level-1C Data",GATT_NAME2="instrument",GATT_VAL2="SPEXone";
6610  }
6611  else//OCIS
6612  {
6613  senstr = "OCI";
6614  GATT_NAME1="Title",GATT_VAL1="PACE OCI Level-1C Data",GATT_NAME2="instrument",GATT_VAL2="OCI";
6615  }
6616 
6617  // fname_out = pathstr + missionstr + "_" + senstr + "." + yearstr + monstr + daystr + timestr + prodstr+granstr+extstr;
6618  ofilestr=std::string(l1cinput->ofile);
6619  fname_out = pathstr + ofilestr+"_"+ prodstr+granstr+extstr;
6620 
6621  string ATT_NAME="Units", ATT_VAL="degrees",GATT_NAME3="processing_version",GATT_VAL3="V1.0",GATT_NAME4="Conventions",GATT_VAL4="CF-1.6";
6622  string GATT_NAME5="institution",GATT_VAL5="NASA Goddard Space Flight Center, Ocean Biology Processing Group",GATT_NAME6="license",GATT_VAL6="http://science.nasa.gov/earth-science/earth-science-data/data-information-policy/";
6623  string GATT_NAME7="naming_authority",GATT_VAL7="gov.nasa.gsfc.sci.oceancolor",GATT_NAME8="keywords_vocabulary",GATT_VAL8="NASA Global Change Master Directory (GCMD) Science Keywords";
6624  string GATT_NAME9="stdname_vocabulary",GATT_VAL9="NetCDF Climate and Forecast (CF) Metadata Convention",GATT_NAME10="creator_name",GATT_VAL10="NASA/GSFC",GATT_NAME11="creator_email",GATT_VAL11="data@oceancolor.gsfc.nasa.gov";
6625  string GATT_NAME12="creator_url",GATT_VAL12="http://oceancolor.gsfc.nasa.gov",GATT_NAME13="project",GATT_VAL13="PACE Project",GATT_NAME14="publisher_name",GATT_VAL14="NASA/GSFC";
6626  string GATT_NAME15="publisher_email",GATT_VAL15="data@oceancolor.gsfc.nasa.gov",GATT_NAME16="publisher_url",GATT_VAL16="http://oceancolor.gsfc.nasa.gov",GATT_NAME17="processing_level",GATT_VAL17="L1C";
6627  string GATT_NAME18="cdm_data_type",GATT_VAL18="swath",GATT_NAME19="orbit_number",GATT_VAL19="12345",GATT_NAME20="history",GATT_VAL20="",GATT_NAME21="CDL_version_date",GATT_VAL21="2021-09-10",GATT_NAME22="product_name",GATT_VAL22=fname_out;
6628  string GATT_NAME23="startDirection",GATT_VAL23="Ascending",GATT_NAME24="endDirection",GATT_VAL24="Ascending",GATT_NAME25="time_coverage_start",GATT_VAL25=yearstr+"-"+monstr+"-"+daystr+"-"+timestr,GATT_NAME26="time_coverage_end",GATT_VAL26=yearstr+"-"+monstr+"-"+daystr+"-"+timestr,GATT_NAME27="date{_created",GATT_VAL27="2021-09-10T15:12:41Z",GATT_NAME28="sun_earth_distance",GATT_VAL28="0.990849042172323",GATT_NAME29="terrain_data_source",GATT_VAL29="",GATT_NAME30="spectral_response_function",GATT_VAL30="",GATT_NAME31="systematic_uncertainty_model",GATT_VAL31="",GATT_NAME32="nadir_bin",GATT_VAL32="12345",GATT_NAME33="bin_size_at_nadir",GATT_VAL33="5.2km2";
6629 
6630  l1cfile->gridname = fname_out.c_str();
6631  filename_lt = fname_out.c_str();
6632  cout<<"filename_lt.."<<filename_lt<<endl;
6633 
6634  if ((status = nc_create(filename_lt, NC_CLOBBER | NC_NETCDF4, &ncid_out)))
6635  check_err(status, __LINE__, __FILE__);
6636  //define dims
6637  // Define the dimensions,vars and attributes at the root level
6638  NDIMS=2;
6639  NDIMS2=3;
6640  NDIMS3=4;
6641  NY = num_gridlines;
6642  NX = nbinx;
6643  //NVIEWS= 2;//for OCI
6644  // NBANDS=249;//for OCI
6645 
6646  NY1 = l1cfile->NY1;//these are indexes not line #!!!!!!!!!!!!!!!!!
6647  NY2 = l1cfile->NY2;
6648  cout << "rowgrid ini.." << NY1 << "rowgrid end.." << NY2 << endl;
6649  NY = NY2 - NY1 + 1;
6650  cout << "NY.." << NY << "NX.." << NX << "NY1.."<<NY1<<"NY2.."<<NY2<<endl;
6651 
6652  //DEF DIMENSIONS
6653  if ((status = nc_def_dim(ncid_out, "bins_across_track", NX, &x_dimid)))
6654  check_err(status, __LINE__, __FILE__);
6655  if ((status = nc_def_dim(ncid_out, "bins_along_track", NY, &y_dimid)))
6656  check_err(status, __LINE__, __FILE__);
6657  //dims for output var
6658  dimids[0] = y_dimid;
6659  dimids[1] = x_dimid;
6660 
6661  if ((status = nc_def_dim(ncid_out, "number_of_views", NVIEWS, &v_dimid)))
6662  check_err(status, __LINE__, __FILE__);
6663  if ((status = nc_def_dim(ncid_out, "intensity_bands_per_view", NBANDS, &b_dimid)))
6664  check_err(status, __LINE__, __FILE__);
6665 
6666  dimids2[0] = y_dimid;
6667  dimids2[1] = x_dimid;
6668  dimids2[2] = v_dimid;//#o
6669 
6670  dimids3[0] = y_dimid;
6671  dimids3[1] = x_dimid;
6672  dimids3[2] = v_dimid;//
6673  dimids3[3] = b_dimid;
6674 
6675  //define attributes
6676  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME1.c_str(), strlen(GATT_VAL1.c_str()),
6677  GATT_VAL1.c_str()))
6678  check_err(status, __LINE__, __FILE__);
6679  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME2.c_str(), strlen(GATT_VAL2.c_str()),
6680  GATT_VAL2.c_str()))
6681  check_err(status, __LINE__, __FILE__);
6682  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME3.c_str(), strlen(GATT_VAL3.c_str()),
6683  GATT_VAL3.c_str()))
6684  check_err(status, __LINE__, __FILE__);
6685  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME4.c_str(), strlen(GATT_VAL4.c_str()),
6686  GATT_VAL4.c_str()))
6687  check_err(status, __LINE__, __FILE__);
6688  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME5.c_str(), strlen(GATT_VAL5.c_str()),
6689  GATT_VAL5.c_str()))
6690  check_err(status, __LINE__, __FILE__);
6691  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME6.c_str(), strlen(GATT_VAL6.c_str()),
6692  GATT_VAL6.c_str()))
6693  check_err(status, __LINE__, __FILE__);
6694  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME7.c_str(), strlen(GATT_VAL7.c_str()),
6695  GATT_VAL7.c_str()))
6696  check_err(status, __LINE__, __FILE__);
6697  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME8.c_str(), strlen(GATT_VAL8.c_str()),
6698  GATT_VAL8.c_str()))
6699  check_err(status, __LINE__, __FILE__);
6700  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME9.c_str(), strlen(GATT_VAL9.c_str()),
6701  GATT_VAL9.c_str()))
6702  check_err(status, __LINE__, __FILE__);
6703  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME10.c_str(), strlen(GATT_VAL10.c_str()),
6704  GATT_VAL10.c_str()))
6705  check_err(status, __LINE__, __FILE__);
6706  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME11.c_str(), strlen(GATT_VAL11.c_str()),
6707  GATT_VAL11.c_str()))
6708  check_err(status, __LINE__, __FILE__);
6709  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME12.c_str(), strlen(GATT_VAL12.c_str()),
6710  GATT_VAL12.c_str()))
6711  check_err(status, __LINE__, __FILE__);
6712  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME13.c_str(), strlen(GATT_VAL13.c_str()),
6713  GATT_VAL13.c_str()))
6714  check_err(status, __LINE__, __FILE__);
6715  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME14.c_str(), strlen(GATT_VAL14.c_str()),
6716  GATT_VAL14.c_str()))
6717  check_err(status, __LINE__, __FILE__);
6718  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME15.c_str(), strlen(GATT_VAL15.c_str()),
6719  GATT_VAL15.c_str()))
6720  check_err(status, __LINE__, __FILE__);
6721  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME16.c_str(), strlen(GATT_VAL16.c_str()),
6722  GATT_VAL16.c_str()))
6723  check_err(status, __LINE__, __FILE__);
6724  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME17.c_str(), strlen(GATT_VAL17.c_str()),
6725  GATT_VAL17.c_str()))
6726  check_err(status, __LINE__, __FILE__);
6727  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME18.c_str(), strlen(GATT_VAL18.c_str()),
6728  GATT_VAL18.c_str()))
6729  check_err(status, __LINE__, __FILE__);
6730  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME19.c_str(), strlen(GATT_VAL19.c_str()),
6731  GATT_VAL19.c_str()))
6732  check_err(status, __LINE__, __FILE__);
6733  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME20.c_str(), strlen(GATT_VAL20.c_str()),
6734  GATT_VAL20.c_str()))
6735  check_err(status, __LINE__, __FILE__);
6736  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME21.c_str(), strlen(GATT_VAL21.c_str()),
6737  GATT_VAL21.c_str()))
6738  check_err(status, __LINE__, __FILE__);
6739  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME22.c_str(), strlen(GATT_VAL22.c_str()),
6740  GATT_VAL22.c_str()))
6741  check_err(status, __LINE__, __FILE__);
6742  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME23.c_str(), strlen(GATT_VAL23.c_str()),
6743  GATT_VAL23.c_str()))
6744  check_err(status, __LINE__, __FILE__);
6745  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME24.c_str(), strlen(GATT_VAL24.c_str()),
6746  GATT_VAL24.c_str()))
6747  check_err(status, __LINE__, __FILE__);
6748  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME25.c_str(), strlen(GATT_VAL25.c_str()),
6749  GATT_VAL25.c_str()))
6750  check_err(status, __LINE__, __FILE__);
6751  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME26.c_str(), strlen(GATT_VAL26.c_str()),
6752  GATT_VAL26.c_str()))
6753  check_err(status, __LINE__, __FILE__);
6754  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME27.c_str(), strlen(GATT_VAL27.c_str()),
6755  GATT_VAL27.c_str()))
6756  check_err(status, __LINE__, __FILE__);
6757  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME28.c_str(), strlen(GATT_VAL28.c_str()),
6758  GATT_VAL28.c_str()))
6759  check_err(status, __LINE__, __FILE__);
6760  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME29.c_str(), strlen(GATT_VAL29.c_str()),
6761  GATT_VAL29.c_str()))
6762  check_err(status, __LINE__, __FILE__);
6763  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME30.c_str(), strlen(GATT_VAL30.c_str()),
6764  GATT_VAL30.c_str()))
6765  check_err(status, __LINE__, __FILE__);
6766  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME31.c_str(), strlen(GATT_VAL31.c_str()),
6767  GATT_VAL31.c_str()))
6768  check_err(status, __LINE__, __FILE__);
6769  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME32.c_str(), strlen(GATT_VAL32.c_str()),
6770  GATT_VAL32.c_str()))
6771  check_err(status, __LINE__, __FILE__);
6772  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME33.c_str(), strlen(GATT_VAL33.c_str()),
6773  GATT_VAL33.c_str()))
6774  check_err(status, __LINE__, __FILE__);
6775 
6776  //define groups check_err(status, __LINE__, __FILE__);
6777  if ((status = nc_def_grp(ncid_out, "geolocation_data", &grp_coor))) //netcdf-4
6778  check_err(status, __LINE__, __FILE__);
6779  //def var grp1
6780  if ((status = nc_def_var(grp_coor, "latitude", NC_FLOAT, NDIMS,
6781  dimids, &varid1)))
6782  check_err(status, __LINE__, __FILE__);
6783  if ((status = nc_def_var(grp_coor, "longitude", NC_FLOAT, NDIMS,
6784  dimids, &varid2)))
6785  check_err(status, __LINE__, __FILE__);
6786 
6787  //leave define mode-----------------------
6788  if ((status = nc_enddef(grp_coor))) //done def vars etc
6789  check_err(status, __LINE__, __FILE__);
6790 
6791 
6792  if ((status = nc_def_grp(ncid_out, "observation_data", &grp_obs))) //netcdf-4
6793  check_err(status, __LINE__, __FILE__);
6794  //def var grp2
6795  //counts and Lt
6796  if ((status = nc_def_var(grp_obs, "obs_per_view", NC_INT, NDIMS2,
6797  dimids2, &varid_count)))
6798  check_err(status, __LINE__, __FILE__);
6799  if ((status = nc_def_var(grp_obs, "I", NC_FLOAT, NDIMS3,
6800  dimids3, &varid_lt)))
6801  check_err(status, __LINE__, __FILE__);
6802 
6803  //leave define mode-----------------------
6804  if ((status = nc_enddef(grp_obs))) //done def vars etc
6805  check_err(status, __LINE__, __FILE__);
6806 
6807 
6808  lat_out = allocate2d_float(NY, NX);
6809  lon_out = allocate2d_float(NY, NX);
6810 
6811  int c = 0;
6812 
6813  for (int i = NY1; i < NY2 + 1; i++) {
6814  for (int j = 0; j < NX; j++) {
6815  lat_out[NY - 1 - c][NX - 1 - j] = lat_gd[i][j];
6816  lon_out[NY - 1 - c][j] = lon_gd[i][j];
6817  }
6818  c++;
6819  }
6820 
6821 
6822  if ((status = nc_put_var_float(grp_coor, varid1, &lat_out[0][0])))
6823  check_err(status, __LINE__, __FILE__);
6824 
6825  if ((status = nc_put_var_float(grp_coor, varid2, &lon_out[0][0])))
6826  check_err(status, __LINE__, __FILE__);
6827 
6828 
6829  //alloc mem for output variables obs_per_view and I as part of the observation_data group
6830  data_out = allocate3d_int(NY, NX,NVIEWS);
6831  data_out2 = allocate4d_float(NY, NX,NVIEWS,NBANDS);
6832 
6833  //BINCOUNT ARRAY
6834  for (size_t v = 0; v < NVIEWS; v++) {
6835  for (int i = NY1; i < NY2 + 1; i++) {
6836  for (int j = 0; j < NX; j++) {
6837  data_out[i][j][v]=0;
6838  }}}
6839 
6840 
6841 
6842  c = 0;
6843  for (size_t v = 0; v < NVIEWS; v++) {
6844  for (int i = NY1; i < NY2 + 1; i++) {
6845  for (int j = 0; j < NX; j++) {
6846  for (sb = 0;sb < NBANDS;sb++) {
6847  if(bincount[v][sb][i][j]>0)
6848  data_out[NY - 1 - c][NX - 1 - j][v]+=bincount[v][sb][i][j];
6849  else
6850  data_out[NY - 1 - c][NX - 1 - j][v]+=0;
6851  }
6852  }
6853  c++;
6854  }
6855  c=0;
6856  }
6857 
6858 
6859 
6860  cout << "writing countbin for all band ."<< endl;
6861  if ((status = nc_put_var_int(grp_obs, varid_count, &data_out[0][0][0])))
6862  check_err(status, __LINE__, __FILE__);
6863 
6864  // LT ARRAYS
6865  c=0;
6866  for (size_t b = 0;b <NBANDS;b++) {
6867  for (size_t v = 0; v < NVIEWS; v++) {
6868  for (int i = NY1; i < NY2 + 1; i++) {
6869  for (int j = 0; j < NX; j++) {
6870  if (bincount[v][b][i][j] > 0)
6871  data_out2[NY - 1 - c][NX - 1 - j][v][b] = binmean_Lt[v][b][i][j] / bincount[v][b][i][j];
6872  else data_out2[NY - 1 - c][NX - 1 - j][v][b] = NAN;
6873  }
6874  c++;
6875  }
6876  c=0;
6877  }//end views
6878  }//end for bands
6879 
6880  cout << "writing Lt for all bands.."<< endl;
6881  if ((status = nc_put_var_float(grp_obs, varid_lt, &data_out2[0][0][0][0])))
6882  check_err(status, __LINE__, __FILE__);
6883 
6884  delete [] (data_out);
6885  delete [] (data_out2);
6886  delete[](lat_out);
6887  delete[](lon_out);
6888 
6889  if ((status = nc_close(ncid_out)))
6890  check_err(status, __LINE__, __FILE__);
6891 
6892  lat_out = nullptr;;
6893  lon_out = nullptr;
6894  data_out = nullptr;
6895  data_out2 = nullptr;
6896 
6897  cout << "number of files per swath.." << nfiles_swt[swtd - 1] << "for swath.." << swtd << endl;
6898  cout << "total inpix.." << INPIX << "total pix.." << TOTPIX << endl;
6899  printf("*** SUCCESS writing bincount and binLt rasters as nc..!\n");
6900  cout<<"LINE-BY-LINE sbs binning method....."<<endl;
6901  }//end writing file
6902 
6903 
6904  cout<<"number of binned pixels..."<<INPIX<<endl;
6905  return 0;
6906  }
6907 
6908  int32_t L1C::binL1C_wgranule_aw2(int swtd, l1c_filehandle* l1cfile, L1C_input* l1cinput, l1c_str* l1cstr, float** lat_gd, float** lon_gd, float* az_east, float** Ltfracsum, float** areabinsum, float** nobs_perbin, size_t sline) {
6909  size_t num_scans;
6910  int32_t num_gridlines, nbinx, n_files, inpix = 0, outpix = 0, totpix = 0;
6911  float minv = 0., maxv = 0.;
6912  int16_t fi = 0;
6913  string str, pathstr, senstr, monstr, daystr, yearstr, prodstr, swtstr, granstr, swtnum, extstr, fname_out;
6914  int status, ncid_out, x_dimid, y_dimid, varid, varid2, varid3,NDIMS;
6915  float Re = 6378;
6916  float latmin_swt = 100, latmax_swt = 0, lonmin_swt = 0, lonmax_swt = 0;
6917  int dimids[2];
6918  const char* filename_lt;
6919  int32_t NY = -1, NX = -1, NY1 = -1, NY2 = -1, c1 = 1;
6920  float** lat_out, ** lon_out;
6921  float aterm = 0.;
6922  short** index_xy;
6923  float** lat_asort;
6924  bool boolbin1;
6925  int num_pixels;
6926  int16_t selyear = -1, selmon = -1, selday = -1;
6927  string gridname, azeast_name;
6928  float azpix, azpixc;
6929  double** latcornBox = nullptr, ** loncornBox = nullptr;
6930  float deltaphi, deltalam, bterm, dist_u, dist_v;
6931  double lat_cnw, lat_cne, lat_csw, lat_cse, lon_cnw, lon_cne, lon_csw, lon_cse;
6932  float theta, thetares, dist_corn, thetagrad;
6933  double intersectArea = 0, binAreapix = 0, binAreagrid = 0.;
6934  bool ingeom = false;
6935  int pc;
6936  short gd_row = 0, gd_col = 0;
6937  int findex = 0;
6938  int bb = 0, rb = 0, swb = 0;
6939  int grp_root, grp_blue, grp_red, grp_swir, grp_coor, pix;
6940  float **data_out,**data_out2,**data_out3;
6941  int flag_inpix;
6942  string ws_lon_str, ws_lat_str, wn_lon_str, wn_lat_str, en_lon_str, en_lat_str, es_lon_str, es_lat_str, pixstr;
6943 
6944  Geodesic geod(Constants::WGS84_a(), Constants::WGS84_f());
6945 
6946  srand((unsigned int)time(NULL));
6947 
6948  num_gridlines = l1cfile->num_gridlines;
6949  num_scans = l1cfile->nscan;
6950  nbinx = l1cfile->nbinx;
6951  num_pixels = l1cfile->npix;
6952  n_files = l1cfile->ifiles.size();
6953  size_t sfiles = 0;
6954 
6955  latcornBox = allocate2d_double(4, 9);//4 corners, 9 grid cells
6956  loncornBox = allocate2d_double(4, 9);
6957 
6958 
6959  if (l1cfile->selgran[0] < 0)//process all granules
6960  {
6961  for (unsigned int j = 0;j < sfiles;j++) l1cfile->selgran[j] = j + 1;
6962  }
6963  else {
6964  while (l1cfile->selgran[sfiles] >0) {
6965  cout << "selected granule #..........................." << l1cfile->selgran[sfiles] << endl;
6966  sfiles++;
6967  }
6968  }
6969 
6970  //determine crossing time of the swath
6971  cout << "nfiles.for the swath." << n_files << endl;
6972 
6973  //determine # of gd groups to be processede
6974  //gdlines_group=num_gridlines;//ONE BIG GROUP
6975  //--NORMALIZED gridline longitude is -180 to 180 degrees before comparison with longitude extracted from image pixels---
6976  for (int i = 0; i < num_gridlines; i++) {
6977  for (int j = 0; j < nbinx; j++) {
6978  if (lon_gd[i][j] < -180.)lon_gd[i][j] += 360.;
6979  if (lon_gd[i][j] > 180.)lon_gd[i][j] -= 360.;
6980  }
6981  }
6982  //get min/max lat/lon of the swath
6983  // Assume first element as maximum and minimum
6984  maxv = lat_gd[0][0];
6985  minv = lat_gd[0][0];
6986 
6987  //Find maximum and minimum in all array elements.
6988  for (int i = 0; i < num_gridlines; i++) {
6989  for (int j = 0; j < nbinx; j++) {
6990  if (lat_gd[i][j] > maxv)
6991  maxv = lat_gd[i][j];
6992  if (lat_gd[i][j] < minv)
6993  minv = lat_gd[i][j];
6994  }
6995  }
6996  latmin_swt = minv;
6997  latmax_swt = maxv;
6998  maxv = lon_gd[0][0];
6999  minv = lon_gd[0][0];
7000  //Find maximum and minimum in all array elements.
7001  for (int i = 0; i < num_gridlines; i++) {
7002  for (int j = 0; j < nbinx; j++) {
7003  if (lon_gd[i][j] > maxv)
7004  maxv = lon_gd[i][j];
7005  if (lon_gd[i][j] < minv)
7006  minv = lon_gd[i][j];
7007  }
7008  }
7009  lonmin_swt = minv;
7010  lonmax_swt = maxv;
7011 
7012  //check lat bound min/max of each gd group---
7013  int k = 0;
7014 
7015  //recompute number of gridlines based on lat limits -80 to 80 degrees
7016  //asc orbit goes from negative to positive latitude....
7017  NY = num_gridlines;
7018  NX = nbinx;
7019  for (int i = 0; i < NY; i++) {
7020  for (int j = 0; j < NX; j++) {
7021  if (lat_gd[i][j] >= -80.) c1++;
7022  if (c1 == nbinx) {
7023  NY1 = i;
7024  }
7025  }
7026  if (NY1 >= 0) break;
7027  c1 = 1;
7028  }
7029 
7030 
7031  for (int i = 0;i < NY; i++) {
7032  // cout<<"i.."<<i<<"lat_gd[i][j]..."<<lat_gd[i][nadpix]<<endl;
7033  for (int j = 0; j < NX; j++) {
7034  if (lat_gd[i][j] >= 80.) {
7035  NY2 = i - 1;
7036  }
7037  }
7038 
7039  if (NY2 >= 0) break;
7040  }
7041 
7042  // cout<<"gridlines limited to -80 to 80 degrees of latitutde.."<<"gdline ini.."<<NY1<<"gdline end.."<<NY2<<endl;
7043 
7044  l1cfile->NY1 = NY1;
7045  l1cfile->NY2 = NY2;
7046 
7047  cout << "NY.." << NY << "NY1.." << NY1 << "NY2.." << NY2 << endl;
7048 
7049 
7050  num_gridlines = NY2 - NY1 + 1;//this is the # gridlines after -80 to 80 lat constraint---
7051 
7052  num_blue_bands = l1cfile->nband_blue;//this includes uv + visible bands
7053  num_red_bands = l1cfile->nband_red;
7054  num_SWIR_bands = l1cfile->nband_swir;
7055 
7056  //*********** SORTING LAT/LON ASCENDING AND TRACK INDEXES ****************************
7057  //***********************************************************************************
7058 
7059  //Create index matrix for i and j of each lat and lon L1C grid (-80 to 80)
7060  //num_gridlines x nbinx
7061  index_xy = allocate2d_short(num_gridlines, nbinx);
7062  lat_asort = allocate2d_float(num_gridlines, nbinx);
7063  // lon_asort=allocate2d_float(num_gridlines,nbinx);
7064  //fill indexe
7065 
7066  //define 1-D vector to sort 1 col L1C grid at the time---
7067  vector<pair<float, int> > vp;
7068 
7069  //fill vector with lat_gd column--
7070  cout << "*********** SORTING LAT/LON GRIDPOINTS AND TRACKING INDEXES ********************" << endl;
7071 
7072  for (int col = 0;col < nbinx;col++) {
7073  for (int row = NY1;row < NY2 + 1;row++) {
7074  vp.push_back(make_pair(lat_gd[row][col] + 90., row));
7075  }
7076  //sort
7077  stable_sort(vp.begin(), vp.end());
7078  //display lat in order along with its gridpoint index--
7079  // cout << "Lat value\t"
7080  // << "index" << endl;
7081  for (unsigned int i = 0; i < vp.size(); i++) {
7082  lat_asort[i][col] = vp[i].first;
7083  index_xy[i][col] = vp[i].second;
7084  }
7085  vp.clear();
7086  }
7087 
7088 
7089  fi = l1cfile->selgran[0];
7090  str = l1cfile->ifiles[fi - 1];
7091 
7092 
7093  for (pix = 0;pix < num_pixels;pix++) {
7094  if (l1cstr->latpix[pix] < latmin_swt) latmin_swt = l1cstr->latpix[pix];
7095  if (l1cstr->latpix[pix] > latmax_swt) latmax_swt = l1cstr->latpix[pix];
7096  if (l1cstr->lonpix[pix] < lonmin_swt) lonmin_swt = l1cstr->lonpix[pix];
7097  if (l1cstr->lonpix[pix] > lonmax_swt) lonmax_swt = l1cstr->lonpix[pix];
7098  }
7099 
7100 
7101  // cout<<"Processing line #..."<<sline+1<<endl;
7102 
7103 //*********** BIG LOOP M_PIXEL *****************************************************************
7104  for (pix = 0;pix < num_pixels;pix++) {
7105 
7106  bb = 0, rb = 0, swb = 0, gd_row = 0, gd_col = 0;
7107  flag_inpix = 0;
7108 
7109  latcornBox = allocate2d_double(4, 9);//4 corners, 9 grid cells
7110  loncornBox = allocate2d_double(4, 9);
7111 
7112  for (int i = 0;i < 4;i++) {
7113  for (int j = 0;j < 9;j++) {
7114  latcornBox[i][j] = 0.;
7115  loncornBox[i][j] = 0.;
7116  }
7117 }
7118 
7119 // cout << "sline.aw2." << sline + 1 << "pix.." << pix + 1 << endl;
7120  boolbin1 = sbs2_l1c(l1cinput, num_gridlines, nbinx, lat_asort, index_xy, l1cstr->latpix[pix], l1cstr->lonpix[pix], lon_gd, &gd_row, &gd_col);
7121 
7122  // if (sline % 1 == 0){ cout<<"LINE NUMBER------------------------------------------------------------------------------------------------------------------------#"<<sline+1<<"pix #........"<<pix+1<<endl;
7123 // cout << "boolbin1..." << boolbin1 << "row.." << gd_row << "col..." << gd_col << "latpix..." << l1cstr->latpix[pix] << "lonpix..." << l1cstr->lonpix[pix] << endl;
7124 // cout << "latasort.." << lat_asort[0][0] << "index_xy.." << index_xy[0][0] << endl;
7125 
7126 
7127 
7128  if (boolbin1 == 1) flag_inpix = 1;
7129  //************ BINNING ***************************
7130  //assign identified pixel to Lt and bin stat arrays-----
7131 
7132 
7133  if (flag_inpix == 1 && gd_row >= 2 && gd_col >= 2 && gd_row <= nbinx - 3 && gd_col <= num_gridlines - 3) {
7134  Polygon_t pixelPoly;
7135  Polygon_t gridPoly;
7136 
7137  inpix++;
7138  deltaphi = (l1cstr->latpix[pix] - l1cstr->latpix[pix + 1]) * degrad;
7139  deltalam = (l1cstr->lonpix[pix] - l1cstr->lonpix[pix + 1]) * degrad;
7140  aterm = sin(deltaphi / 2) * sin(deltaphi / 2) + cos(l1cstr->latpix[pix] * degrad) * cos(l1cstr->latpix[pix + 1] * degrad) * sin(deltalam / 2) * sin(deltalam / 2);
7141  bterm = 2 * atan2(sqrt(aterm), sqrt(1 - aterm));
7142  dist_u = Re * bterm; //horizontal distance Harversine in km
7143  //along-track distance
7144  deltaphi = (l1cstr->latpix[pix] - l1cstr->latpix2[pix]) * degrad;
7145  deltalam = (l1cstr->lonpix[pix] - l1cstr->lonpix2[pix]) * degrad;
7146  aterm = sin(deltaphi / 2) * sin(deltaphi / 2) + cos(l1cstr->latpix[pix] * degrad) * cos(l1cstr->latpix2[pix] * degrad) * sin(deltalam / 2) * sin(deltalam / 2);
7147  bterm = 2 * atan2(sqrt(aterm), sqrt(1 - aterm));
7148  dist_v = Re * bterm;
7149  //pixel azimuth
7150  azpix = atan2(sin(deltalam) * cos(l1cstr->latpix2[pix] * degrad), cos(l1cstr->latpix[pix] * degrad) * sin(l1cstr->latpix2[pix] * degrad) - sin(l1cstr->latpix[pix] * degrad) * cos(l1cstr->latpix2[pix] * degrad) * cos(deltaphi));
7151  if (azpix > M_PI || azpix < -M_PI) {
7152  cout << "problem with BEARING in across-gridline method...az<-180 or >180...." << "azpixc in degrees.." << azpix * 180 / M_PI << endl;
7153  exit(1);
7154  }
7155  azpix = azpix * 180. / M_PI;
7156 
7157  // cout<<"line.."<<sline+1<<"pix #:.."<<pix+1<<"pix size.U in km."<<dist_u<<"pixsize.V in km."<<dist_v<<"azpix before pix_corners4_l1c....in degrees."<<azpix<<endl;
7158  // cout<<"FOUND grid cell!!-----row.."<<gd_row<<"col.."<<gd_col<<"latpix.."<<l1cstr->latpix[pix]<<"lonpix.."<<l1cstr->lonpix[pix]<<"latpix2.."<<l1cstr->latpix2[pix]<<"lonpix2.."<<l1cstr->lonpix2[pix]<<endl;
7159 
7160  //******* M_PIXEL CORNERS ***********************************************************************************************
7161  dist_corn = 0.5 * (sqrt(dist_u * dist_u + dist_v * dist_v)) * 1000;//distane center to corner in meters
7162  theta = atan2(dist_v, dist_u);
7163  thetagrad = 2 * theta * 180 / M_PI;
7164  thetares = (M_PI / 2 - theta) * 180 / M_PI;
7165  //nw corner
7166  azpixc = (azpix - thetares) * degrad;//pixel bearing
7167  if (azpixc<-M_PI || azpixc>M_PI) { cout << "error in nw corner..azpixc" << azpixc << endl;exit(1); }
7168  azpixc = azpixc * 180 / M_PI;
7169  // cout<<"azpixc nw...."<<azpixc<<endl;
7170  geod.Direct(l1cstr->latpix[pix], l1cstr->lonpix[pix], azpixc, dist_corn, lat_cnw, lon_cnw);
7171  //ne corner (sw-180)
7172  azpixc = (azpix + thetares) * degrad;//pixel bearing
7173  if (azpixc<-M_PI || azpixc>M_PI) { cout << "error in ne corner..azpixc" << azpixc << endl;exit(1); }
7174  azpixc = azpixc * 180 / M_PI;
7175  // cout<<"azpixc ne...."<<azpixc<<endl;
7176  geod.Direct(l1cstr->latpix[pix], l1cstr->lonpix[pix], azpixc, dist_corn, lat_cne, lon_cne);
7177  //sw corner
7178  azpixc = (azpix - thetares - thetagrad) * degrad;//pixel bearing
7179  if (azpixc<-M_PI || azpixc>M_PI) { cout << "error in sw corner..azpixc" << azpixc << endl;exit(1); }
7180  azpixc = azpixc * 180 / M_PI;
7181  // cout<<"azpixc sw....."<<azpixc<<endl;
7182  geod.Direct(l1cstr->latpix[pix], l1cstr->lonpix[pix], azpixc, dist_corn, lat_csw, lon_csw);
7183  //se corner (nw-180)
7184  azpixc = (azpix + thetares + thetagrad) * degrad;//pixel bearingi
7185  if (azpixc<-M_PI || azpixc>M_PI) { cout << "error in se corner..azpixc" << azpixc << endl;exit(1); }
7186  azpixc = (azpix + 45 + 90) * degrad;//pixel bearing
7187  azpixc = azpixc * 180 / M_PI;
7188  // cout<<"azpix se...."<<azpixc<<endl;
7189  geod.Direct(l1cstr->latpix[pix], l1cstr->lonpix[pix], azpixc, dist_corn, lat_cse, lon_cse);
7190 
7191 
7192 
7193  // cout<<"sline................................................................................................................"<<sline+1<<endl;
7194  // cout<<"sline.."<<sline+1<<"dist_corn.."<<dist_corn<<"lat_cnw.."<<lat_cnw<<"lon_cnw.."<<lon_cnw<<"lat_cne.."<<lat_cne<<"lon_cne.."<<lon_cne<<"lat_csw.."<<lat_csw<<"lon_csw.."<<lon_csw<<"lat_cse.."<<lat_cse<<"lon_cse.."<<lon_cse<<endl;
7195 
7196  // ws_lon_str=std::to_string(lon_csw);
7197  // ws_lat_str=std::to_string(lat_csw);
7198  // wn_lon_str=std::to_string(lon_cnw);
7199  // wn_lat_str=std::to_string(lat_cnw);
7200  // en_lon_str=std::to_string(lon_cne);
7201  // en_lat_str=std::to_string(lat_cne);
7202  // es_lon_str=std::to_string(lon_cse);
7203  // es_lat_str=std::to_string(lat_cse);
7204 
7205  // pixstr="POLYGON(("+ws_lon_str+" "+ws_lat_str+","+wn_lon_str+" "+wn_lat_str+","+en_lon_str+" "+en_lat_str+","+es_lon_str+" "+es_lat_str+","+ws_lon_str+" "+ws_lat_str+"))";
7206  // bg::read_wkt(pixstr,pixelPoly);
7207 
7208  bg::append(pixelPoly.outer(), Point_t(lon_csw, lat_csw));
7209  bg::append(pixelPoly.outer(), Point_t(lon_cnw, lat_cnw));
7210  bg::append(pixelPoly.outer(), Point_t(lon_cne, lat_cne));
7211  bg::append(pixelPoly.outer(), Point_t(lon_cse, lat_cse));
7212  bg::append(pixelPoly.outer(), Point_t(lon_csw, lat_csw));
7213 
7214 
7215 
7216  // make sure the polygon is defined properly
7217  bg::correct(pixelPoly);
7218 
7219  if (lon_csw > lon_cse || lon_cnw > lon_cne || lat_csw > lat_cnw || lat_cse > lat_cne) {
7220  cout << "lon_csw>lon_cse | lon_cnw>lon_cne | lat_csw>lat_cnw | lat_cse>lat_cne//" << lon_csw << lon_cse << lon_cnw << lon_cne << lat_csw << lat_cnw << lat_cse << lat_cne << endl;
7221  cout << "corners are switched for pixel.." << pix + 1 << endl;
7222  }
7223 
7224 
7225  lon_csw = 0, lat_csw = 0, lon_cnw = 0, lat_cnw = 0, lon_cne = 0, lat_cne = 0, lon_cse = 0, lat_cse = 0;
7226  // cout<<"azpixc nw...."<<azpixc<<"lat.."<<l1cstr->latpix[pix]<<"lon.."<<l1cstr->lonpix[pix]<<"dist_corn.."<<dist_corn<<"lat_cnw.."<<lat_cnw<<"lon_cnw.."<<lon_cnw<<endl;
7227 
7228 
7229  if (gd_row >= 1 && gd_col >= 1 && gd_row < num_gridlines - 1 && gd_col < nbinx - 1) {
7230 
7231  // cout<<"sline.."<<sline<<"gd_row.."<<gd_row<<"gd_col.."<<gd_col<<"bb.."<<bb<<endl;
7232  gwindowTopix_l1c(l1cfile, l1cinput, gd_row, gd_col, lat_gd, lon_gd, latcornBox, loncornBox);
7233 
7234 
7235  for (int i = 0;i < 9;i++) { //for each intersection
7236  // corn1_lon_str=std::to_string(loncornBox[0][i]);
7237  // corn1_lat_str=std::to_string(latcornBox[0][i]);
7238  // corn2_lon_str=std::to_string(loncornBox[1][i]);
7239  // corn2_lat_str=std::to_string(latcornBox[1][i]);
7240  // corn3_lon_str=std::to_string(loncornBox[2][i]);
7241  // corn3_lat_str=std::to_string(latcornBox[2][i]);
7242  // corn4_lon_str=std::to_string(loncornBox[3][i]);
7243  // corn4_lat_str=std::to_string(latcornBox[3][i]);
7244  // gridstr="POLYGON(("+corn1_lon_str+" "+corn1_lat_str+","+corn2_lon_str+" "+corn2_lat_str+","+corn3_lon_str+" "+corn3_lat_str+","+corn4_lon_str+" "+corn4_lat_str+","+corn1_lon_str+" "+corn1_lat_str+"))";
7245  // bg::read_wkt(gridstr,gridPoly);
7246 
7247 
7248  bg::append(gridPoly.outer(), Point_t(loncornBox[0][i], latcornBox[0][i]));
7249  bg::append(gridPoly.outer(), Point_t(loncornBox[1][i], latcornBox[1][i]));
7250  bg::append(gridPoly.outer(), Point_t(loncornBox[2][i], latcornBox[2][i]));
7251  bg::append(gridPoly.outer(), Point_t(loncornBox[3][i], latcornBox[3][i]));
7252  bg::append(gridPoly.outer(), Point_t(loncornBox[0][i], latcornBox[0][i]));
7253  bg::correct(gridPoly);
7254 
7255  ingeom = within(pixelPoly, gridPoly);
7256  binAreagrid = bg::area(gridPoly);
7257  binAreapix = bg::area(pixelPoly);//
7258 
7259  // if (sline % 10 == 0 & binAreagrid>10000000) cout<<"sline.."<<sline+1<<"pix.."<<pix+1<<"gridcell#.."<<i<<"fully inside????.."<<ingeom<<"binAreagrid..."<<binAreagrid<<"binAreapix..."<<binAreapix<<endl;
7260  //compute intersections-----
7261 //
7262  intersectArea = 0., pc = 1;
7263  if (ingeom > 0) { //pixel fully inside the grid cell
7264  intersectArea = binAreapix;
7265 
7266  if (l1cstr->Lt_blue[bb][pix] > 0.) {
7267  Ltfracsum[gd_row][gd_col] += l1cstr->Lt_blue[bb][pix] * (intersectArea / binAreagrid);
7268  areabinsum[gd_row][gd_col] += (intersectArea / binAreagrid);
7269  nobs_perbin[gd_row][gd_col] += 1;
7270  }
7271  }
7272  else {
7273  if (!bg::disjoint(pixelPoly, gridPoly) && binAreagrid > 0) {
7274  std::deque<Polygon_t> output;//this is a list
7275  if (bg::intersection(pixelPoly, gridPoly, output)) {
7276  BOOST_FOREACH(Polygon_t const& p, output)
7277  {
7278  intersectArea = bg::area(p);
7279  if (intersectArea > 0.0 && pc == 1) {
7280 
7281  if (l1cstr->Lt_blue[bb][pix] > 0.) {
7282  Ltfracsum[gd_row][gd_col] += l1cstr->Lt_blue[bb][pix] * (intersectArea / binAreagrid);
7283  areabinsum[gd_row][gd_col] += (intersectArea / binAreagrid);
7284  nobs_perbin[gd_row][gd_col] += 1;
7285  }
7286 
7287 
7288  if (intersectArea / binAreagrid < 0.000001) {
7289  Ltfracsum[gd_row][gd_col] += 0.;
7290  areabinsum[gd_row][gd_col] += 0.;
7291  nobs_perbin[gd_row][gd_col] += 0.;
7292  }
7293  pc++;
7294  }
7295  }
7296  }
7297  }
7298  }//end else
7299 
7300 // cout<<"gridcell#.."<<i<<"fully inside????.."<<ingeom<<"areafrac..."<<intersectArea / binAreagrid<<"Ltfrac..."<<Ltfracsum[gd_row][gd_col]<<"areabinsum.."<<areabinsum[gd_row][gd_col]<<"nobsperbin.."<<nobs_perbin[gd_row][gd_col]<<endl;
7301  // cout<<"sline........"<<sline+1<<"pix#.........................."<<pix+1<<"gridcell#.."<<i<<endl;
7302  }//end for intersections
7303 
7304 
7305  }//end if gdrow and gdcol are ok
7306 
7307 
7308 
7309 
7310 
7311 /*
7312  while (bb<num_blue_bands){
7313  if(l1cstr->Lt_blue[bb][pix]>0.){
7314  binmean_Lt[bb][bin_ypix-1][bin_xpix-1]=binmean_Lt[bb][bin_ypix-1][bin_xpix-1]+l1cstr->Lt_blue[bb][pix];
7315  bincount_Lt[bb][bin_ypix-1][bin_xpix-1]+=1;
7316  }
7317  bb++;
7318  }//end while blue band band
7319 //RED---
7320  while (rb<num_red_bands){
7321  if(l1cstr->Lt_red[rb][pix]>0.){
7322  binmean_Lt2[rb][bin_ypix-1][bin_xpix-1]=binmean_Lt2[rb][bin_ypix-1][bin_xpix-1]+l1cstr->Lt_red[rb][pix];
7323  bincount_Lt2[rb][bin_ypix-1][bin_xpix-1]+=1;
7324  }
7325  rb++;
7326  }//end red bands
7327 
7328 //SWIR----
7329  while (swb<num_SWIR_bands){
7330  if(l1cstr->Lt_SWIR[swb][pix]>0.){
7331  binmean_Lt3[swb][bin_ypix-1][bin_xpix-1]=binmean_Lt3[swb][bin_ypix-1][bin_xpix-1]+l1cstr->Lt_SWIR[swb][pix];
7332  bincount_Lt3[swb][bin_ypix-1][bin_xpix-1]+=1;
7333  }
7334  swb++;
7335  }//end swir bands
7336 
7337 */
7338 
7339  }//end if flag_inpix
7340 
7341 
7342 
7343 //********** pixel AREA WEIGHTING ************************
7344  if (flag_inpix == 0) outpix++;
7345 
7346  totpix++;
7347 
7348  delete[](latcornBox);
7349  delete[](loncornBox);
7350  latcornBox = nullptr;
7351  loncornBox = nullptr;
7352  }//end pixels loop
7353 
7354 //**********************************************************************************************************************************
7355 //**********************************************************************************************************************************
7356 //writing each granule ---------------------------------
7357 //*****************************************************************************
7358  if (sline == num_scans - 1) {
7359  // if(sline==num_scans-1 flag_donefile==1 | (flag_donefile==0 & k==ngroups-1)){
7360  cout << "writing file #.............................................." << l1cfile->selgran[findex] << "based on group #.." << k + 1 << endl;
7361  //write mean Lt as nc file---
7362  //**********************************************************************
7363  //**********************************************************************8
7364  //create Lt file
7365  pathstr = "out/";
7366  senstr = "OCIS_";
7367  monstr = std::to_string(selmon);
7368  daystr = std::to_string(selday);
7369  yearstr = std::to_string(selyear);
7370  prodstr = "binLt_aw2";
7371  swtstr = "_swt";
7372  granstr = "";
7373  granstr = "_" + std::to_string(l1cfile->selgran[findex]);
7374 
7375  if (l1cfile->l1c_pflag >= 3) {
7376  swtd = l1cfile->swtnum;
7377  swtnum = std::to_string(swtd);
7378  cout << "swtnum.." << swtnum << endl;
7379  }
7380  else swtnum = std::to_string(swtd);
7381  extstr = ".nc";
7382  NDIMS = 2;
7383  fname_out = pathstr + senstr + monstr + daystr + yearstr + prodstr + swtstr + swtnum + granstr + extstr;
7384  filename_lt = fname_out.c_str();
7385 
7386  if ((status = nc_create(filename_lt, NC_CLOBBER | NC_NETCDF4, &ncid_out)))
7387  check_err(status, __LINE__, __FILE__);
7388  //define dims
7389  // Define the dimensions. NetCDF will hand back an ID for each.
7390  NY = num_gridlines;
7391  NX = nbinx;
7392  NY1 = l1cfile->NY1;//these are indexes not line #!!!!!!!!!!!!!!!!!
7393  NY2 = l1cfile->NY2;
7394  cout << "rowgrid ini.." << NY1 << "rowgrid end.." << NY2 << endl;
7395  NY = NY2 - NY1 + 1;
7396  cout << "NY.." << NY << "NX.." << NX << endl;
7397  //alloc mem for data_out and assign values from lat_gdI
7398 //alloc mem for data_out and assign values from lat_gdI
7399  lat_out = allocate2d_float(NY, NX);
7400  lon_out = allocate2d_float(NY, NX);
7401 
7402  int c = 0;
7403 
7404  for (int i = NY1; i < NY2 + 1; i++) {
7405  for (int j = 0; j < NX; j++) {
7406  lat_out[NY - 1 - c][NX - 1 - j] = lat_gd[i][j];
7407  lon_out[NY - 1 - c][j] = lon_gd[i][j];
7408  }
7409  c++;
7410  }
7411 
7412  if ((status = nc_def_dim(ncid_out, "x", NX, &x_dimid)))
7413  check_err(status, __LINE__, __FILE__);
7414  if ((status = nc_def_dim(ncid_out, "y", NY, &y_dimid)))
7415  check_err(status, __LINE__, __FILE__);
7416  //dims for output var
7417  dimids[0] = y_dimid;
7418  dimids[1] = x_dimid;
7419 
7420  //define groups-----
7421  // status = nc_def_grp( *ncid, line.c_str(), &gid[ngrps]);
7422  if ((status = nc_def_grp(ncid_out, "data", &grp_root))) //netcdf-4
7423  check_err(status, __LINE__, __FILE__);
7424  if ((status = nc_def_grp(grp_root, "geo_coordinates", &grp_coor))) //netcdf-4
7425  check_err(status, __LINE__, __FILE__);
7426  if ((status = nc_def_grp(grp_root, "blue_bands", &grp_blue))) //netcdf-4
7427  check_err(status, __LINE__, __FILE__);
7428  if ((status = nc_def_grp(grp_root, "red_bands", &grp_red))) //netcdf-4
7429  check_err(status, __LINE__, __FILE__);
7430  if ((status = nc_def_grp(grp_root, "swir_bands", &grp_swir))) //netcdf-4
7431  check_err(status, __LINE__, __FILE__);
7432 
7433  //def var--------------------
7434 
7435  //loop blue channels-----
7436 
7437  string bb_num, rb_num, swb_num, bb_str = "binLt_blue_ch", rb_str = "binLt_red_ch", swb_str = "binLt_swir_ch";
7438 
7439  int varid_bb[1], varid_rb[1], varid_swb[1];
7440 
7441  for (int bb = 0;bb < 1;bb++) {
7442  bb_num = std::to_string(bb + 1);
7443  bb_num = bb_str + bb_num;
7444  if ((status = nc_def_var(grp_blue, bb_num.c_str(), NC_FLOAT, NDIMS, dimids, &varid))) check_err(status, __LINE__, __FILE__);
7445  varid_bb[bb] = varid;
7446  }
7447 
7448  for (int rb = 0;rb < 1;rb++) {
7449  rb_num = std::to_string(rb + 1);
7450  rb_num = rb_str + rb_num;
7451  if ((status = nc_def_var(grp_red, rb_num.c_str(), NC_FLOAT, NDIMS, dimids, &varid))) check_err(status, __LINE__, __FILE__);
7452  varid_rb[rb] = varid;
7453  }
7454 
7455  for (int swb = 0;swb < 1;swb++) {
7456  swb_num = std::to_string(swb + 1);
7457  swb_num = swb_str + swb_num;
7458  if ((status = nc_def_var(grp_swir, swb_num.c_str(), NC_FLOAT, NDIMS, dimids, &varid))) check_err(status, __LINE__, __FILE__);
7459  varid_swb[swb] = varid;
7460  }
7461  //lat/lon
7462  if ((status = nc_def_var(grp_coor, "lat_gd", NC_FLOAT, NDIMS,
7463  dimids, &varid2)))
7464  check_err(status, __LINE__, __FILE__);
7465  if ((status = nc_def_var(grp_coor, "lon_gd", NC_FLOAT, NDIMS,
7466  dimids, &varid3)))
7467  check_err(status, __LINE__, __FILE__);
7468  //leave define mode-----------------------
7469  if ((status = nc_enddef(ncid_out))) //done def vars etc
7470  check_err(status, __LINE__, __FILE__);
7471 
7472  //assign variable data------------------------
7473  if ((status = nc_put_var_float(grp_coor, varid2, &lat_out[0][0])))
7474  check_err(status, __LINE__, __FILE__);
7475 
7476  if ((status = nc_put_var_float(grp_coor, varid3, &lon_out[0][0])))
7477  check_err(status, __LINE__, __FILE__);
7478  //blue
7479 
7480  // for(bb=0;bb<num_blue_bands;bb++){
7481  bb = 0;
7482  data_out = allocate2d_float(NY, NX);
7483  c = 0;
7484  for (int i = NY1; i < NY2 + 1; i++) {
7485  for (int j = 0; j < NX; j++) {
7486  data_out[NY - 1 - c][NX - 1 - j] = 0.;
7487  }
7488  c++;
7489  }
7490  c = 0;
7491  for (int i = NY1; i < NY2 + 1; i++) {
7492  for (int j = 0; j < NX; j++) {
7493  if (nobs_perbin[i][j] > 0)
7494  data_out[NY - 1 - c][NX - 1 - j] = Ltfracsum[i][j] / nobs_perbin[i][j];
7495  else data_out[NY - 1 - c][NX - 1 - j] = NAN;
7496  }
7497  c++;
7498  }
7499  cout << "writing blue band#.." << bb + 1 << endl;
7500  if ((status = nc_put_var_float(grp_blue, varid_bb[bb], &data_out[0][0])))
7501  check_err(status, __LINE__, __FILE__);
7502 
7503 
7504  delete[](data_out);
7505  // }//end blue bands
7506  //red
7507  // for(rb=0;rb<num_red_bands;rb++){
7508  rb = 0;
7509  data_out2 = allocate2d_float(NY, NX);
7510  c = 0;
7511  for (int i = NY1; i < NY2 + 1; i++) {
7512  for (int j = 0; j < NX; j++) {
7513  data_out2[NY - 1 - c][NX - 1 - j] = 0.;
7514  }
7515  c++;
7516  }
7517  c = 0;
7518  for (int i = NY1; i < NY2 + 1; i++) {
7519  for (int j = 0; j < NX; j++) {
7520  if (nobs_perbin[i][j] > 0)
7521  data_out2[NY - 1 - c][NX - 1 - j] = Ltfracsum[i][j] / nobs_perbin[i][j];
7522  else data_out2[NY - 1 - c][NX - 1 - j] = NAN;
7523  }
7524  c++;
7525  }
7526  cout << "writing red band#.." << rb + 1 << endl;
7527  if ((status = nc_put_var_float(grp_red, varid_rb[rb], &data_out2[0][0])))
7528  check_err(status, __LINE__, __FILE__);
7529 
7530  delete[](data_out2);
7531  // }//end red bands
7532 
7533 
7534  //swir
7535  // for(swb=0;swb<num_SWIR_bands;swb++){
7536  swb = 0;
7537  data_out3 = allocate2d_float(NY, NX);
7538  c = 0;
7539  for (int i = NY1; i < NY2 + 1; i++) {
7540  for (int j = 0; j < NX; j++) {
7541  data_out3[NY - 1 - c][NX - 1 - j] = 0.;
7542  }
7543  c++;
7544  }
7545  c = 0;
7546  for (int i = NY1; i < NY2 + 1; i++) {
7547  for (int j = 0; j < NX; j++) {
7548  if (nobs_perbin[i][j] > 0)
7549  data_out3[NY - 1 - c][NX - 1 - j] = Ltfracsum[i][j] / nobs_perbin[i][j];
7550  else data_out3[NY - 1 - c][NX - 1 - j] = NAN;
7551  }
7552  c++;
7553  }
7554  cout << "writing SWIR band#.." << swb + 1 << endl;
7555  if ((status = nc_put_var_float(grp_swir, varid_swb[swb], &data_out3[0][0])))
7556  check_err(status, __LINE__, __FILE__);
7557 
7558  delete[](data_out3);
7559  // }//end swir bands
7560 
7561  if ((status = nc_close(ncid_out)))
7562  check_err(status, __LINE__, __FILE__);
7563 
7564  delete[](lat_out);
7565  delete[](lon_out);
7566 
7567  lat_out = nullptr;;
7568  lon_out = nullptr;
7569  data_out = nullptr;
7570  data_out2 = nullptr;
7571  data_out3 = nullptr;
7572 
7573  printf("*** SUCCESS writing bincount and binLt rasters as nc..!\n");
7574  cout << "finish processing swath eq crossing day..." << swtd << endl;
7575  cout << "done writing Lt to nc file.." << endl;
7576  }//end writing file
7577 
7578 
7579 // cout<<"group k at the end of big loop"<<k+1<<endl;
7580 // }//groups
7581 
7582 // cout<<"number of files per swath.."<<nfiles_swt[swtd-1]<<"for swath.."<<swtd<<endl;
7583  cout << "total inpix.." << inpix << "total pix.." << totpix << endl;
7584  // cout<<"binned pixels.."<<inpix<<"as %.."<<(inpix/(num_pixels*num_scans*n_files*nfiles_swt[swtd-1]))*100<<endl;
7585  delete[](lat_asort);
7586  delete[](index_xy);
7587 
7588  lat_asort = nullptr;
7589  index_xy = nullptr;
7590 
7591 
7592 
7593  return 0;
7594  }
7595 
7596 
7597 
7598 
7599 
7600 
7601 
7602  int32_t L1C::binL1C_wgranule_aw(int swtd, l1c_filehandle* l1cfile, L1C_input* l1cinput, int16_t* swtd_id, int16_t* odir, int16_t* file_id, int16_t* nfiles_swt) {
7603  int32_t gdlines_group,ngroups = 0,num_gridlines, nbinx, inpix = 0, outpix = 0, totpix = 0, n_gdlines;//number of gridlines to be processed
7604  float minv = 0., maxv = 0.;
7605  int16_t fi = 0;
7606 
7607  std::string str;
7608  const char* ptstr;
7609  int dimid, status, ncid_out, x_dimid, y_dimid, varid, varid2, varid3, varid4, varid5, varid6, varid7, varid8, NDIMS;
7610  size_t start[] = { 0, 0 }, start2[] = { 0, 0, 0 }, start3[] = { 0, 0 };
7611  size_t count[] = { 1, 1 }, count2[] = { 1, 1, 1 }, count3[] = { 1, 1, 1 }, count4[] = { 1, 1, 1 };
7612 
7613  float* latpix, * lonpix, * latpix2, * lonpix2, ** Lt_pix, ** Lt_pix2, ** Lt_pix3;
7614  float Re = 6378;
7615  float latmin_swt = 100, latmax_swt = 0, lonmin_swt = 0, lonmax_swt = 0;
7616  int dimids[2];
7617  const char* filename_lt;
7618  int32_t NY = -1, NX = -1, NY1 = -1, NY2 = -1, c1 = 1;
7619  float** lat_out, ** lon_out;
7620 
7621  ;
7622  float aterm = 0.;
7623  int last_file, last_sline, flag_inpix, flag_donefile;;//first index file id, second index line #
7624  short** index_xy;
7625  float** lat_asort;
7626  bool boolbin1;
7627  int16_t selyear = -1, selmon = -1, selday = -1;
7628  float** lat_gd, ** lon_gd, * az_east;
7629  string gridname, azeast_name;
7630 
7631  double gres = (l1cinput->gres) * 1000, dlamin, dlamax, dlomin, dlomax;
7632  float azpix, azpixc, ** nobs_perbin;
7633  double** Ltfracsum, ** areabinsum;
7634  double** latcornBox, ** loncornBox;
7635  float deltaphi, deltalam, bterm, dist_u, dist_v;
7636  double lat_cnw, lat_cne, lat_csw, lat_cse, lon_cnw, lon_cne, lon_csw, lon_cse;
7637  float theta, thetares, dist_corn, thetagrad;
7638  string corn1_lon_str, corn2_lon_str, corn3_lon_str, corn4_lon_str, corn1_lat_str, corn2_lat_str, corn3_lat_str, corn4_lat_str, gridstr;
7639 
7640  double intersectArea = 0, binAreapix = 0, binAreagrid = 0.;
7641  bool ingeom = false;
7642  int pc;
7643  short gd_row, gd_col;
7644  float **dlatb_g=nullptr,**dlonb_g=nullptr;
7645 
7646  Polygon_t pixelPoly;
7647  Polygon_t gridPoly;
7648  Geodesic geod(Constants::WGS84_a(), Constants::WGS84_f());
7649 
7650  //random seed
7651  srand((unsigned int)time(NULL));
7652  //nadir pixel ofr OCI
7653  int nadpix = l1cfile->nadpix;
7654 
7655  num_gridlines = l1cfile->num_gridlines;
7656  nbinx = l1cfile->nbinx;
7657  num_pixels = l1cfile->npix;
7658 
7659  size_t sfiles = 0;
7660 
7661  if (l1cfile->selgran[0] < 0)//process all granules
7662  {
7663  sfiles = nfiles_swt[swtd - 1];
7664  for (unsigned int j = 0;j < sfiles;j++) l1cfile->selgran[j] = j + 1;
7665  }
7666  else {
7667  while (l1cfile->selgran[sfiles] > 0) {
7668  cout << "selected granule #..........................." << l1cfile->selgran[sfiles] << endl;
7669  sfiles++;
7670  }
7671  }
7672 
7673  //allocate mem for lat/lon/azeast pointers---
7674  selday = l1cinput->selday;
7675  selmon = l1cinput->selmon;
7676  selyear = l1cinput->selyear;
7677 
7678  std::string fname_out, pathstr, senstr, monstr, daystr, yearstr, prodstr, gdstr, swtstr, swtnum, extstr, granstr;
7679 
7680  pathstr = "out/";
7681  senstr = "OCIS_";
7682  monstr = std::to_string(selmon);
7683  daystr = std::to_string(selday);
7684  yearstr = std::to_string(selyear);
7685  prodstr = "L1Cgrid";
7686  swtstr = "_swt";
7687  extstr = ".csv";
7688 
7689  if (l1cfile->l1c_pflag >= 3) {
7690  swtd = l1cfile->swtnum;
7691  swtnum = std::to_string(swtd);
7692  cout << "swtnum.." << swtnum << endl;
7693  }
7694  else swtnum = std::to_string(swtd);
7695 
7696  gridname = pathstr + senstr + monstr + daystr + yearstr + prodstr + swtstr + swtnum + extstr;
7697 
7698  prodstr = "az_east";
7699  azeast_name = pathstr + senstr + monstr + daystr + yearstr + prodstr + swtstr + swtnum + extstr;
7700  cout << "gridname.." << gridname << "azeast-name.." << azeast_name << endl;
7701 
7702  //************ OPENING **************************************
7703  //*** AZ_EAST *****************
7704  std::string line;
7705  stringstream ss;
7706  std::string temp;
7707  std::vector<std::string> parts;
7708  ifstream fin(azeast_name);
7709  int cline = 0;
7710  while (getline(fin, line))
7711  {
7712  // load line in stringstream
7713  ss << line;
7714  getline(ss, temp, ',');
7715  parts.push_back(temp);
7716  // cout<<parts[cline]<<endl;
7717  ss.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
7718  ss.clear();
7719  cline++;
7720  }
7721  //minus -1 cause the header
7722  cout << "size of azeast minus heading row..= num_gridlines." << parts.size() - 1 << "nbinx.." << nbinx << endl;
7723  num_gridlines = parts.size() - 1;
7724  //**LAT_GD *******************
7725  ifstream fin2(gridname);
7726  std::vector<std::string> tokens_lon, tokens_lat;
7727  std::string token;
7728  cline = 0;
7729  int fcol = 0;
7730  while (getline(fin2, line))
7731  {
7732  // load line in stringstream
7733  istringstream iss(line);
7734  while (getline(iss, token, ','))
7735  {
7736  cline++;
7737  if (fcol == 0 && cline > 2) {
7738  tokens_lon.push_back(token);fcol++;
7739 }
7740  else if (fcol == 1 && cline > 2)
7741  tokens_lat.push_back(token);
7742 
7743  }
7744  fcol = 0;
7745  }
7746 
7747 
7748 //here the num gridlines is 1 less cause the rounding of nbinx
7749  cout << "size of gridline minus heading row..= num_gridlines." << (tokens_lon.size() - 1) / nbinx << "nbinx.." << nbinx << endl;
7750 
7751  //************************************************************
7752  //mem allocation for geolocation pointers and binning pointers---
7753  az_east = (float*)calloc(num_gridlines , sizeof(float));
7754  lat_gd = allocate2d_float(num_gridlines, nbinx);
7755  lon_gd = allocate2d_float(num_gridlines, nbinx);
7756 
7757  //Initialize pointers-----
7758  for (int i = 0;i < num_gridlines;i++) {
7759  for (int j = 0;j < nbinx;j++) {
7760  lat_gd[i][j] = 0.;
7761  lon_gd[i][j] = 0.;
7762  }
7763  az_east[i] = 0.;
7764  }
7765 
7766 
7767  float sum = 0, tot = 0;
7768  for (int j = 0;j < num_gridlines;j++) {
7769  // cout<<"j.."<<j<<"az_east"<<std::stof(parts[j+1])<<endl;
7770  az_east[j] = std::stof(parts[j + 1]);//first line is the header
7771  sum = az_east[j];
7772  tot += sum;
7773  }
7774  parts.clear();
7775 
7776 
7777 
7778  //using swath-averaged az_east for nadir pixels rather than along-track az_east pixel-by-pixel
7779  float mean_az_east = tot / (num_gridlines - 1);
7780  cout << "mean_az_east..." << mean_az_east << "numgridlines.." << num_gridlines << endl;
7781  // exit(1);
7782  for (int j = 0;j < num_gridlines;j++) {
7783  az_east[j] = mean_az_east;
7784  }
7785 
7786  l1cfile->mean_az_east = mean_az_east;
7787 
7788  int ip = 0;
7789  for (int j = 0;j < num_gridlines;j++) {
7790  for (int k = 0;k < nbinx;k++) {
7791  lat_gd[j][k] = std::stof(tokens_lat[ip]);
7792  lon_gd[j][k] = std::stof(tokens_lon[ip]);
7793  ip++;
7794  }
7795 }
7796  tokens_lon.clear();
7797  tokens_lat.clear();
7798 
7799  //determine # of gd groups to be processede
7800  //gdlines_group=num_gridlines;//ONE BIG GROUP
7801  gdlines_group = 250;
7802 
7803  if (num_gridlines <= gdlines_group) {
7804  gdlines_group = num_gridlines;
7805  cout << "WARNING********************* number_gridlines<=gdlines_group THEN gdlines_group=num_gridlines **************" << endl;
7806  }
7807  ngroups = floor(num_gridlines / gdlines_group);
7808  cout << "TOTAL # of gd groups.(ALL LATs...." << ngroups << endl;
7809 
7810  //--NORMALIZED gridline longitude is -180 to 180 degrees before comparison with longitude extracted from image pixels---
7811  for (int i = 0; i < num_gridlines; i++) {
7812  for (int j = 0; j < nbinx; j++) {
7813  if (lon_gd[i][j] < -180.)lon_gd[i][j] += 360.;
7814  if (lon_gd[i][j] > 180.)lon_gd[i][j] -= 360.;
7815  }
7816 }
7817  //get min/max lat/lon of the swath
7818  // Assume first element as maximum and minimum
7819  maxv = lat_gd[0][0];
7820  minv = lat_gd[0][0];
7821 
7822  //Find maximum and minimum in all array elements.
7823  for (int i = 0; i < num_gridlines; i++) {
7824  for (int j = 0; j < nbinx; j++) {
7825  if (lat_gd[i][j] > maxv)
7826  maxv = lat_gd[i][j];
7827  if (lat_gd[i][j] < minv)
7828  minv = lat_gd[i][j];
7829  }
7830 }
7831 
7832 
7833  maxv = lon_gd[0][0];
7834  minv = lon_gd[0][0];
7835  //Find maximum and minimum in all array elements.
7836  for (int i = 0; i < num_gridlines; i++) {
7837  for (int j = 0; j < nbinx; j++) {
7838  if (lon_gd[i][j] > maxv)
7839  maxv = lon_gd[i][j];
7840  if (lon_gd[i][j] < minv)
7841  minv = lon_gd[i][j];
7842  }
7843  }
7844 
7845 
7846 
7847  cout << "swath #.." << swtd << endl;
7848 
7849  //check lat bound min/max of each gd group---
7850  int k = 0, i = 0;
7851 
7852  dlatb_g = allocate2d_float(ngroups + 1, 2);
7853  dlonb_g = allocate2d_float(ngroups + 1, 2);
7854 
7855  //recompute number of gridlines based on lat limits -80 to 80 degrees
7856  //asc orbit goes from negative to positive latitude....
7857  NY = num_gridlines;
7858  NX = nbinx;
7859  for (int i = 0; i < NY; i++) {
7860  for (int j = 0; j < NX; j++) {
7861  if (lat_gd[i][j] >= -80.) c1++;
7862  if (c1 == nbinx) {
7863  NY1 = i;
7864  }
7865  }
7866  if (NY1 >= 0) break;
7867  c1 = 1;
7868  }
7869 
7870 
7871  for (int i = 0;i < NY; i++) {
7872  // cout<<"i.."<<i<<"lat_gd[i][j]..."<<lat_gd[i][nadpix]<<endl;
7873  for (int j = 0; j < NX; j++) {
7874  if (lat_gd[i][j] >= 80.) {
7875  NY2 = i - 1;
7876  }
7877  }
7878 
7879  if (NY2 >= 0) break;
7880  }
7881 
7882  // cout<<"gridlines limited to -80 to 80 degrees of latitutde.."<<"gdline ini.."<<NY1<<"gdline end.."<<NY2<<endl;
7883 
7884  l1cfile->NY1 = NY1;
7885  l1cfile->NY2 = NY2;
7886 
7887  cout << "NY.." << NY << "NY1.." << NY1 << "NY2.." << NY2 << endl;
7888 
7889 
7890 
7891  num_gridlines = NY2 - NY1 + 1;//this is the # gridlines after -80 to 80 lat constraint---
7892  cout<<"num_gridlines after restriction for sbs2 search.."<<num_gridlines<<endl;
7893  ngroups = floor(num_gridlines / gdlines_group);
7894  cout << "gdlines will start in gline.." << i + 1 << "ROUNDED ngroups after adjusting beginning.for constraint lat (-80 to 80)" << ngroups << endl;
7895 
7896 
7897 
7898 
7899  //for each 'grid' group scan the swath files to see if there are scanlines within--
7900  //if that is case check the across-bin number position (0 to binx-1) based on latnad and lonnad values---
7901  last_file = 0;
7902  last_sline = 0;
7903  flag_donefile = 0;
7904 
7905  num_blue_bands = 120;
7906  num_red_bands = 120;
7907  num_SWIR_bands = 9;
7908 
7909  if (num_gridlines > ngroups * gdlines_group) ngroups += 1;
7910 
7911 
7912  //*********** SORTING LAT/LON ASCENDING AND TRACK INDEXES ****************************
7913  //***********************************************************************************
7914 
7915  //Create index matrix for i and j of each lat and lon L1C grid (-80 to 80)
7916  //num_gridlines x nbinx
7917  index_xy = allocate2d_short(num_gridlines, nbinx);
7918  lat_asort = allocate2d_float(num_gridlines, nbinx);
7919 
7920  //fill indexe
7921 
7922  //define 1-D vector to sort 1 col L1C grid at the time---
7923  vector<pair<float, int> > vp;
7924 
7925  //fill vector with lat_gd column--
7926  cout << "*********** SORTING LAT/LON GRIDPOINTS AND TRACKING INDEXES ********************" << endl;
7927 
7928  for (int col = 0;col < nbinx;col++) {
7929  for (int row = NY1;row < NY2 + 1;row++) {
7930  vp.push_back(make_pair(lat_gd[row][col] + 90., row));
7931  }
7932  //sort
7933  stable_sort(vp.begin(), vp.end());
7934  //display lat in order along with its gridpoint index--
7935  // cout << "Lat value\t"
7936  // << "index" << endl;
7937  for (unsigned int i = 0; i < vp.size(); i++) {
7938  // cout << vp[i].first << "\t"
7939  // << vp[i].second << endl;
7940  lat_asort[i][col] = vp[i].first;
7941  index_xy[i][col] = vp[i].second;
7942  }
7943  vp.clear();
7944  }
7945 
7946  //saddleback search
7947 
7948  cout << "num_gridlines...." << num_gridlines << "ngroups.." << ngroups << endl;
7949 
7950 
7951  //****************************************************************************************************
7952  //************* BIG LOOP GROUPS ***************************************
7953  cout << "Number of granules to be L1C processed........................................." << sfiles << endl;
7954 
7955 
7956  for (k = 0;k < ngroups;k++) {
7957 
7958  //total gridlines for k groups-----
7959  n_gdlines = (k + 1) * gdlines_group;
7960  cout << "screening k group.." << k + 1 << "last_file.." << last_file << "last_line.." << last_sline << endl;
7961  cout << "number of gridlines so far..." << n_gdlines << endl;
7962  //***** compute deltas for lat_gd index 256 and 257 *******************
7963 
7964  //compute delta_lat and delta_lon based on binres/2 for lower and upper corners of 'nadir' gridpoints of 256 and 257 indexes -----------------
7965  //we need nadir 256 and 257 lat/lon coordinates to compute -delta and +delta, respectively
7966  //we need azimuth and backazimuth and binres/2 to compute deltas ---
7967 
7968  //index 256
7969  geod.Direct(lat_gd[n_gdlines - gdlines_group][256], lon_gd[n_gdlines - gdlines_group][256], az_east[n_gdlines - gdlines_group], gres, dlamin, dlomin);
7970  geod.Direct(lat_gd[n_gdlines - 1][257], lon_gd[n_gdlines - 1][257], az_east[n_gdlines - 1], gres, dlamax, dlomax);
7971 
7972  cout << "dlamin.." << dlamin << "dlomin.." << dlomin << "dlamax.." << dlamax << "dlomax.." << dlomax << endl;
7973 
7974  dlatb_g[k][0] = dlamin;//in DEGREES!!
7975  dlatb_g[k][1] = dlamax;
7976  dlonb_g[k][0] = dlomin;
7977  dlonb_g[k][1] = dlomax;
7978 
7979  //********* LOOP FILES ************************************
7980  for (unsigned int findex = last_file;findex < sfiles;findex++) {
7981 
7982  cout << "Scanning lines in file.. for crossing swath..." << swtd << "selected granule #.." << l1cfile->selgran[findex] << "swt_id.." << swtd_id[findex] << "grid group.." << k + 1 << endl;
7983 
7984  if (last_sline == 0) { // binmean_Lt==NULL | bincount==NULL | binmean_Lt2==NULL | bincount2==NULL | binmean_Lt3==NULL | bincount3==NULL){
7985 
7986  cout << "first allocation of memory for grid bins of file #..." << l1cfile->selgran[findex] << endl;
7987 
7988 
7989  Ltfracsum = allocate2d_double(num_gridlines, nbinx);
7990  areabinsum = allocate2d_double(num_gridlines, nbinx);
7991  nobs_perbin = allocate2d_float(num_gridlines, nbinx);
7992 
7993  }//end f last line allocating bin arrays
7994 
7995 
7996  fi = l1cfile->selgran[findex];
7997  str = l1cfile->ifiles[fi - 1];
7998  ptstr = str.c_str();
7999  cout << "opening filename............" << ptstr << endl;
8000  status = nc_open(ptstr, NC_NOWRITE, &ncid_L1B);
8001  if (status != NC_NOERR) {
8002  fprintf(stderr, "-E- Error nc_open.\n");
8003  exit(EXIT_FAILURE);
8004  }
8005  //Open dimensions
8006  status = nc_inq_dimid(ncid_L1B, "number_of_scans", &dimid);
8007  if (status != NC_NOERR) {
8008  fprintf(stderr, "-E- Error reading number_of_scans.\n");
8009  exit(EXIT_FAILURE);
8010  }
8011  nc_inq_dimlen(ncid_L1B, dimid, &num_scans);
8012 
8013  //read line-by-line lat/lon/Lt
8014  status = nc_inq_grp_ncid(ncid_L1B, "geolocation_data", &geoGrp);
8015  check_err(status, __LINE__, __FILE__);
8016  status = nc_inq_grp_ncid(ncid_L1B, "observation_data", &obsGrp);
8017  check_err(status, __LINE__, __FILE__);
8018  //open geo data
8019  status = nc_inq_varid(geoGrp, "latitude", &latId);//scans x velements
8020  check_err(status, __LINE__, __FILE__);
8021  status = nc_inq_varid(geoGrp, "longitude", &lonId);//scans x velements
8022  check_err(status, __LINE__, __FILE__);
8023  status = nc_inq_varid(obsGrp, "Lt_blue", &Lt_blueId);
8024  check_err(status, __LINE__, __FILE__);
8025  status = nc_inq_varid(obsGrp, "Lt_red", &Lt_redId);
8026  check_err(status, __LINE__, __FILE__);
8027  status = nc_inq_varid(obsGrp, "Lt_SWIR", &Lt_SWIRId);
8028  check_err(status, __LINE__, __FILE__);
8029 
8030 
8031  // num_blue_bands
8032  status = nc_inq_dimid(ncid_L1B, "blue_bands", &dimid);
8033  if (status != NC_NOERR) {
8034  fprintf(stderr, "-E- Error reading num_blue_bands.\n");
8035  exit(EXIT_FAILURE);
8036  }
8037  nc_inq_dimlen(ncid_L1B, dimid, &num_blue_bands);
8038 
8039  // num_red_bands
8040  status = nc_inq_dimid(ncid_L1B, "red_bands", &dimid);
8041  if (status != NC_NOERR) {
8042  fprintf(stderr, "-E- Error reading num_red_bands.\n");
8043  exit(EXIT_FAILURE);
8044  }
8045  nc_inq_dimlen(ncid_L1B, dimid, &num_red_bands);
8046 
8047  // num_SWIR_bands
8048  status = nc_inq_dimid(ncid_L1B, "SWIR_bands", &dimid);
8049  if (status != NC_NOERR) {
8050  fprintf(stderr, "-E- Error reading num_SWIR_bands.\n");
8051  exit(EXIT_FAILURE);
8052  }
8053  nc_inq_dimlen(ncid_L1B, dimid, &num_SWIR_bands);
8054 
8055  //assigning mem for Lt of different bands **********************
8056  latpix = (float*)calloc(num_pixels , sizeof(float));
8057  lonpix = (float*)calloc(num_pixels , sizeof(float));
8058  latpix2 = (float*)calloc(num_pixels , sizeof(float));
8059  lonpix2 = (float*)calloc(num_pixels , sizeof(float));
8060 
8061  Lt_pix = allocate2d_float(num_blue_bands, num_pixels);//blue bands
8062  Lt_pix2 = allocate2d_float(num_red_bands, num_pixels);//red bands
8063  Lt_pix3 = allocate2d_float(num_SWIR_bands, num_pixels);//SWIR bands
8064 
8065  cout << "#blue bands.." << num_blue_bands << endl;
8066  cout << "#red bands.." << num_red_bands << endl;
8067  cout << "#swir bands.." << num_SWIR_bands << endl;
8068 
8069  //********************************************************************************
8070  //-----reading line by line-----------------------------------
8071  for (unsigned int sline = last_sline;sline < num_scans;sline++) {
8072  //lat and lon--
8073  start[0] = sline;
8074  start[1] = 0;
8075  start3[0] = sline + 1;
8076  start3[1] = 0;
8077 
8078  count[0] = 1;
8079  count[1] = num_pixels; // 1 line at a time
8080 
8081  status = nc_get_vara_float(geoGrp, latId, start, count, latpix);
8082  status = nc_get_vara_float(geoGrp, lonId, start, count, lonpix);
8083  status = nc_get_vara_float(geoGrp, latId, start3, count, latpix2);
8084  status = nc_get_vara_float(geoGrp, lonId, start3, count, lonpix2);
8085 
8086  //Lt
8087  start2[0] = 0;
8088  start2[1] = sline;
8089  start2[2] = 0;
8090 
8091  count2[0] = num_blue_bands;
8092  count2[1] = 1; // 1 line at a time
8093  count2[2] = num_pixels;
8094 
8095  count3[0] = num_red_bands;
8096  count3[1] = 1; // 1 line at a time
8097  count3[2] = num_pixels;
8098  count4[0] = num_SWIR_bands;
8099  count4[1] = 1; // 1 line at a time
8100  count4[2] = num_pixels;
8101 
8102  status = nc_get_vara_float(obsGrp, Lt_blueId, start2, count2, Lt_pix[0]);
8103  status = nc_get_vara_float(obsGrp, Lt_redId, start2, count3, Lt_pix2[0]);
8104  status = nc_get_vara_float(obsGrp, Lt_SWIRId, start2, count4, Lt_pix3[0]);
8105 
8106  for (unsigned int pix = 0;pix < num_pixels;pix++) {
8107  if (latpix[pix] < latmin_swt) latmin_swt = latpix[pix];
8108  if (latpix[pix] > latmax_swt) latmax_swt = latpix[pix];
8109  if (lonpix[pix] < lonmin_swt) lonmin_swt = lonpix[pix];
8110  if (lonpix[pix] > lonmax_swt) lonmax_swt = lonpix[pix];
8111  }
8112  // int band = 0;
8113  dlamin = 0.;dlamax = 0.;
8114  //inside the 'k' box??----- ascending ----------
8115  if (latpix[nadpix] >= dlatb_g[k][0] && latpix[nadpix] <= dlatb_g[k][1]) {
8116 
8117  if (sline % 100 == 0) cout << "EVERY 100 gds..for k group.." << k + 1 << "file number #.." << l1cfile->selgran[findex] << "sline..." << sline + 1 << "# of binned pix.." << inpix << "outpix.." << outpix << endl;
8118 
8119  //*********** BIG LOOP M_PIXEL *****************************************************************
8120  for (unsigned int pix = 0;pix < num_pixels;pix++) {
8121 
8122 
8123  flag_inpix = 0;
8124 
8125  boolbin1 = sbs2_l1c(l1cinput, num_gridlines, nbinx, lat_asort, index_xy, latpix[pix], lonpix[pix], lon_gd, &gd_row, &gd_col);
8126 
8127 
8128 
8129  // cout<<"ok after sbs2_l1c"<<"boolbin1.."<<boolbin1<<"pix.."<<pix+1<<endl;
8130 
8131  if (boolbin1 == 1) flag_inpix = 1;
8132  //************ BINNING ***************************
8133  //assign identified pixel to Lt and bin stat arrays-----
8134  // if(flag_inpix==1 & bin_xpix>=1 & bin_ypix>=1 & bin_xpix<=nbinx & bin_ypix<=num_gridlines){
8135  if (flag_inpix == 1 && gd_row >= 2 && gd_col >= 2 && gd_row <= nbinx - 3 && gd_col <= num_gridlines - 3) {
8136 
8137  inpix++;
8138 
8139  deltaphi = (latpix[pix] - latpix[pix + 1]) * degrad;
8140  deltalam = (lonpix[pix] - lonpix[pix + 1]) * degrad;
8141  aterm = sin(deltaphi / 2) * sin(deltaphi / 2) + cos(latpix[pix] * degrad) * cos(latpix[pix + 1] * degrad) * sin(deltalam / 2) * sin(deltalam / 2);
8142  bterm = 2 * atan2(sqrt(aterm), sqrt(1 - aterm));
8143  dist_u = Re * bterm; //horizontal distance Harversine in km
8144  //along-track distance
8145  deltaphi = (latpix[pix] - latpix2[pix]) * degrad;
8146  deltalam = (lonpix[pix] - lonpix2[pix]) * degrad;
8147  aterm = sin(deltaphi / 2) * sin(deltaphi / 2) + cos(latpix[pix] * degrad) * cos(latpix2[pix] * degrad) * sin(deltalam / 2) * sin(deltalam / 2);
8148  bterm = 2 * atan2(sqrt(aterm), sqrt(1 - aterm));
8149  dist_v = Re * bterm;
8150  //pixel azimuth
8151  azpix = atan2(sin(deltalam) * cos(latpix2[pix] * degrad), cos(latpix[pix] * degrad) * sin(latpix2[pix] * degrad) - sin(latpix[pix] * degrad) * cos(latpix2[pix] * degrad) * cos(deltaphi));
8152  if (azpix > M_PI || azpix < -M_PI) {
8153  cout << "problem with BEARING in across-gridline method...az<-180 or >180...." << "azpixc in degrees.." << azpix * 180 / M_PI << endl;
8154  exit(1);
8155  }
8156  azpix = azpix * 180. / M_PI;
8157 
8158  // cout<<"line.."<<sline+1<<"pix #:.."<<pix+1<<"pix size.U in km."<<dist_u<<"pixsize.V in km."<<dist_v<<"azpix before pix_corners4_l1c....in degrees."<<azpix<<endl;
8159 
8160 
8161  //******* M_PIXEL CORNERS ***********************************************************************************************
8162  dist_corn = 0.5 * (sqrt(dist_u * dist_u + dist_v * dist_v)) * 1000;//distane center to corner in meters
8163  theta = atan2(dist_v, dist_u);
8164  thetagrad = 2 * theta * 180 / M_PI;
8165  thetares = (M_PI / 2 - theta) * 180 / M_PI;
8166  //nw corner
8167  azpixc = (azpix - thetares) * degrad;//pixel bearing
8168  if (azpixc<-M_PI || azpixc>M_PI) { cout << "error in nw corner..azpixc" << azpixc << endl;exit(1); }
8169  azpixc = azpixc * 180 / M_PI;
8170  geod.Direct(latpix[pix], lonpix[pix], azpixc, dist_corn, lat_cnw, lon_cnw);
8171  //ne corner (sw-180)
8172  azpixc = (azpix + thetares) * degrad;//pixel bearing
8173  if (azpixc<-M_PI || azpixc>M_PI) { cout << "error in ne corner..azpixc" << azpixc << endl;exit(1); }
8174  azpixc = azpixc * 180 / M_PI;
8175  // cout<<"azpixc ne...."<<azpixc<<endl;
8176  geod.Direct(latpix[pix], lonpix[pix], azpixc, dist_corn, lat_cne, lon_cne);
8177  //sw corner
8178  azpixc = (azpix - thetares - thetagrad) * degrad;//pixel bearing
8179  if (azpixc<-M_PI || azpixc>M_PI) { cout << "error in sw corner..azpixc" << azpixc << endl;exit(1); }
8180  azpixc = azpixc * 180 / M_PI;
8181  // cout<<"azpixc sw....."<<azpixc<<endl;
8182  geod.Direct(latpix[pix], lonpix[pix], azpixc, dist_corn, lat_csw, lon_csw);
8183  //se corner (nw-180)
8184  azpixc = (azpix + thetares + thetagrad) * degrad;//pixel bearingi
8185  if (azpixc<-M_PI || azpixc>M_PI) { cout << "error in se corner..azpixc" << azpixc << endl;exit(1); }
8186  // azpixc=(azpix+45+90)*degrad;//pixel bearing
8187  azpixc = azpixc * 180 / M_PI;
8188  // cout<<"azpix se...."<<azpixc<<endl;
8189  geod.Direct(latpix[pix], lonpix[pix], azpixc, dist_corn, lat_cse, lon_cse);
8190 
8191  std::string ws_lon_str, ws_lat_str, wn_lon_str, wn_lat_str, en_lon_str, en_lat_str, es_lon_str, es_lat_str, pixstr;
8192 
8193  ws_lon_str = std::to_string(lon_csw);
8194  ws_lat_str = std::to_string(lat_csw);
8195  wn_lon_str = std::to_string(lon_cnw);
8196  wn_lat_str = std::to_string(lat_cnw);
8197  en_lon_str = std::to_string(lon_cne);
8198  en_lat_str = std::to_string(lat_cne);
8199  es_lon_str = std::to_string(lon_cse);
8200  es_lat_str = std::to_string(lat_cse);
8201 
8202  pixstr = "POLYGON((" + ws_lon_str + " " + ws_lat_str + "," + wn_lon_str + " " + wn_lat_str + "," + en_lon_str + " " + en_lat_str + "," + es_lon_str + " " + es_lat_str + "," + ws_lon_str + " " + ws_lat_str + "))";
8203  bg::read_wkt(pixstr, pixelPoly);
8204  cout<<"pixelpoly created"<<endl;
8205 
8206  if (lon_csw > lon_cse || lon_cnw > lon_cne || lat_csw > lat_cnw || lat_cse > lat_cne) {
8207  cout << "lon_csw>lon_cse | lon_cnw>lon_cne | lat_csw>lat_cnw | lat_cse>lat_cne//" << lon_csw << lon_cse << lon_cnw << lon_cne << lat_csw << lat_cnw << lat_cse << lat_cne << endl;
8208  cout << "corners are switched for pixel.." << pix + 1 << endl;
8209  }
8210 
8211  // cout<<"azpixc nw...."<<azpixc<<"lat.."<<latpix[pix]<<"lon.."<<lonpix[pix]<<"dist_corn.."<<dist_corn<<"lat_cnw.."<<lat_cnw<<"lon_cnw.."<<lon_cnw<<endl;
8212 
8213  if (gd_row >= 1 && gd_col >= 1 && gd_row < num_gridlines - 1 && gd_col < nbinx - 1) {
8214  latcornBox = allocate2d_double(4, 9);//4 corners, 9 grid cells
8215  loncornBox = allocate2d_double(4, 9);
8216 
8217  cout<<"before gwindowTopix_l1c(.."<<"pix.."<<pix<<endl;
8218  gwindowTopix_l1c(l1cfile, l1cinput, gd_row, gd_col, lat_gd, lon_gd, latcornBox, loncornBox);
8219  cout<<"after gwindowTopix_l1c(.."<<endl;
8220  for (int i = 0;i < 9;i++) {
8221  corn1_lon_str = std::to_string(loncornBox[0][i]);
8222  corn1_lat_str = std::to_string(latcornBox[0][i]);
8223  corn2_lon_str = std::to_string(loncornBox[1][i]);
8224  corn2_lat_str = std::to_string(latcornBox[1][i]);
8225  corn3_lon_str = std::to_string(loncornBox[2][i]);
8226  corn3_lat_str = std::to_string(latcornBox[2][i]);
8227  corn4_lon_str = std::to_string(loncornBox[3][i]);
8228  corn4_lat_str = std::to_string(latcornBox[3][i]);
8229  gridstr = "POLYGON((" + corn1_lon_str + " " + corn1_lat_str + "," + corn2_lon_str + " " + corn2_lat_str + "," + corn3_lon_str + " " + corn3_lat_str + "," + corn4_lon_str + " " + corn4_lat_str + "," + corn1_lon_str + " " + corn1_lat_str + "))";
8230  bg::read_wkt(gridstr, gridPoly);
8231  cout<<"gridpoly created"<<endl;
8232  ingeom = within(pixelPoly, gridPoly);
8233  binAreagrid = bg::area(gridPoly);
8234  binAreapix = bg::area(pixelPoly);//
8235  cout<<"gridcell#.."<<i<<"fully inside????.."<<ingeom<<"binAreagrid..."<<binAreagrid<<"binAreapix..."<<binAreapix<<endl;
8236 
8237 
8238 
8239 
8240  //compute intersections-----
8241  // areabinBox[1][0]= binAreagrid;
8242  intersectArea = 0., pc = 1;
8243  if (ingeom > 0) { //pixel fully inside the grid cell
8244 
8245  intersectArea = binAreapix;
8246 
8247  if (Lt_pix[0][pix] > 0.) {
8248  Ltfracsum[gd_row][gd_col] += Lt_pix[0][pix] * (intersectArea / binAreagrid);
8249  areabinsum[gd_row][gd_col] += (intersectArea / binAreagrid);
8250  nobs_perbin[gd_row][gd_col] += 1;
8251  }
8252 
8253  }
8254  else {
8255  if (!bg::disjoint(pixelPoly, gridPoly) && binAreagrid > 0) {
8256  std::deque<Polygon_t> output;//this is a list
8257  if (bg::intersection(pixelPoly, gridPoly, output)) {
8258  BOOST_FOREACH(Polygon_t const& p, output)
8259  {
8260  intersectArea = bg::area(p);
8261  if (intersectArea > 0.0 && pc == 1) {
8262 
8263  if (Lt_pix[0][pix] > 0.) {
8264  Ltfracsum[gd_row][gd_col] += Lt_pix[0][pix] * (intersectArea / binAreagrid);
8265  areabinsum[gd_row][gd_col] += (intersectArea / binAreagrid);
8266  // nobs_perbin[gd_row][gd_col]+=1;
8267  }
8268 
8269 
8270  if (intersectArea / binAreagrid < 0.000001) Ltfracsum[gd_row][gd_col] += 0.;
8271  pc++;
8272  }
8273  }
8274  }
8275  }
8276  }//end else
8277 
8278 
8279  }//end for
8280 
8281  delete [](latcornBox);
8282  delete [](loncornBox);
8283  latcornBox = nullptr;
8284  loncornBox = nullptr;
8285  }//end gdrow gdcol
8286  //***************************************************
8287  // exit(1);
8288  }//end if flaf_inpix
8289 
8290  //********** pixel AREA WEIGHTING ************************
8291  if (flag_inpix == 0) outpix++;
8292  totpix++;
8293 
8294  }//end pixels loop
8295 
8296  //END OF FILE--****** reset starting sline index if last line processed and within k box
8297  //go for another granule if it is not the last one---------------
8298  if (sline == num_scans - 1) {
8299  flag_donefile = 1;
8300  cout << "end of file..." << l1cfile->selgran[findex] << endl;
8301  last_sline = 0;
8302  if (findex >= sfiles - 1) {
8303  cout << "done with last granule of the input list........................." << endl;
8304  k = ngroups;
8305  break;
8306  }
8307 
8308  }//end of file/last file? sliine=num_scans-1
8309  else flag_donefile = 0;
8310 
8311  }//end latpix nadir of line x inside grid group?
8312 
8313  //***** skip lines and files if sline is not within k group ********
8314  //increase k and screen files and lines again starting from the last binning
8315 
8316  if (latpix[nadpix] > lat_gd[n_gdlines - 1][257] && k < ngroups - 1) { //else limits
8317  cout << "moving to the next k group...scanning again files/slines.." << endl;
8318  cout << "file index.." << findex << "last sline index.." << sline << endl;
8319  last_file = findex;
8320  last_sline = sline;
8321  findex = sfiles;
8322  sline = num_scans - 1;
8323  }//end if lat >grid lat--IF outside the box
8324 
8325  if (sline + 1 % 100 == 0) cout << "for k group.." << k + 1 << "selected granule #.." << l1cfile->selgran[findex] << "sline..." << sline + 1 << "# of binned pix.." << inpix << "totpix.." << totpix << "outpix.." << outpix << endl;
8326  cout << "sline.." << sline + 1 << endl;
8327 
8328 
8329  // exit(1);
8330 
8331  }//end for scanlines
8332 
8333  cout << "closing L1B file......." << ptstr << endl;
8334  status = nc_close(ncid_L1B);
8335  check_err(status, __LINE__, __FILE__);
8336 
8337  delete [](latpix);
8338  delete [](lonpix);
8339  delete [](latpix2);
8340  delete [](lonpix2);
8341  delete [](Lt_pix);
8342  delete [](Lt_pix2);
8343  delete [](Lt_pix3);
8344 
8345 
8346 
8347  //writing each granule ---------------------------------
8348  if (flag_donefile == 1 || (flag_donefile == 0 && k == ngroups - 1)) { //if file completed and last group to be processed
8349  cout << "writing file #.............................................." << l1cfile->selgran[findex] << "based on group #.." << k + 1 << endl;
8350  //write mean Lt as nc file---
8351  //**********************************************************************
8352  //**********************************************************************8
8353  //create Lt file
8354  pathstr = "out/";
8355  senstr = "OCIS_";
8356  monstr = std::to_string(selmon);
8357  daystr = std::to_string(selday);
8358  yearstr = std::to_string(selyear);
8359  prodstr = "binLt_aw";
8360  swtstr = "_swt";
8361  granstr = "";
8362  granstr = "_" + std::to_string(l1cfile->selgran[findex]);
8363 
8364  if (l1cfile->l1c_pflag >= 3) {
8365  swtd = l1cfile->swtnum;
8366  swtnum = std::to_string(swtd);
8367  cout << "swtnum.." << swtnum << endl;
8368  }
8369  else swtnum = std::to_string(swtd);
8370  extstr = ".nc";
8371  NDIMS = 2;
8372  fname_out = pathstr + senstr + monstr + daystr + yearstr + prodstr + swtstr + swtnum + granstr + extstr;
8373  filename_lt = fname_out.c_str();
8374  if ((status = nc_create(filename_lt, NC_CLOBBER, &ncid_out)))
8375  check_err(status, __LINE__, __FILE__);
8376  //define dims
8377  // Define the dimensions. NetCDF will hand back an ID for each.
8378  NY = num_gridlines;
8379  NX = nbinx;
8380  NY1 = l1cfile->NY1;//these are indexes not line #!!!!!!!!!!!!!!!!!
8381  NY2 = l1cfile->NY2;
8382  cout << "rowgrid ini.." << NY1 << "rowgrid end.." << NY2 << endl;
8383  NY = NY2 - NY1 + 1;
8384  cout << "NY.." << NY << "NX.." << NX << endl;
8385  //alloc mem for data_out and assign values from lat_gdI
8386  //NX AND NY are inverted for visualization in SeaDAS
8387  // data_out = allocate2d_float(NY,NX);
8388  // data_out2 = allocate2d_float(NY,NX);
8389  // data_out3 = allocate2d_float(NY,NX);
8390  // data_out4 = allocate2d_float(NY,NX);
8391  // data_out5 = allocate2d_float(NY,NX);
8392  // data_out6 = allocate2d_float(NY,NX);
8393  lat_out = allocate2d_float(NY, NX);
8394  lon_out = allocate2d_float(NY, NX);
8395 
8396  int c = 0;
8397  for (int i = NY1; i < NY2 + 1; i++) {
8398  for (int j = 0; j < NX; j++) {
8399  lat_out[NY - 1 - c][NX - 1 - j] = lat_gd[i][j];
8400  lon_out[NY - 1 - c][j] = lon_gd[i][j];
8401  //blue
8402  // if (nobs_perbin[i][j]>0)
8403  // data_out[NY-1-c][NX-1-j]=Ltfracsum[i][j]/areabinsum[i][j];
8404  // else
8405  // data_out[NY-1-c][NX-1-j]=NAN;
8406  //blue
8407  /* if (nobs_perbin[i][j]>0)
8408  data_out3[NY-1-c][NX-1-j]=areabinsum[i][j];
8409  else
8410  data_out3[NY-1-c][NX-1-j]=NAN;*/
8411 
8412 
8413  //swir
8414 
8415  /* if (bincount3[i][j]>0)
8416  data_out5[NY-1-c][NX-1-j]=binmean_Lt3[i][j]/bincount3[i][j];
8417  else
8418  data_out5[NY-1-c][NX-1-j]=NAN;
8419  */
8420 
8421  //nobs pointers
8422  // data_out2[NY-1-c][NX-1-j]=nobs_perbin[i][j];
8423  // data_out4[NY-1-c][NX-1-j]=bincount2[i][j];
8424  // data_out6[NY-1-c][NX-1-j]=bincount3[i][j];
8425  }
8426  c++;
8427  }
8428 
8429 
8430 
8431  if ((status = nc_def_dim(ncid_out, "x", NX, &x_dimid)))
8432  check_err(status, __LINE__, __FILE__);
8433  if ((status = nc_def_dim(ncid_out, "y", NY, &y_dimid)))
8434  check_err(status, __LINE__, __FILE__);
8435  //dims for output var
8436  dimids[0] = y_dimid;
8437  dimids[1] = x_dimid;
8438  //def var
8439  //blue
8440  if ((status = nc_def_var(ncid_out, "binLt_blue", NC_FLOAT, NDIMS,
8441  dimids, &varid)))
8442  check_err(status, __LINE__, __FILE__);
8443  if ((status = nc_def_var(ncid_out, "bincount_blue", NC_FLOAT, NDIMS,
8444  dimids, &varid4)))
8445  check_err(status, __LINE__, __FILE__);
8446  //red
8447  if ((status = nc_def_var(ncid_out, "binLt_red", NC_FLOAT, NDIMS,
8448  dimids, &varid5)))
8449  check_err(status, __LINE__, __FILE__);
8450  if ((status = nc_def_var(ncid_out, "bincount_red", NC_FLOAT, NDIMS,
8451  dimids, &varid6)))
8452  check_err(status, __LINE__, __FILE__);
8453  //swir
8454  if ((status = nc_def_var(ncid_out, "binLt_swir", NC_FLOAT, NDIMS,
8455  dimids, &varid7)))
8456  check_err(status, __LINE__, __FILE__);
8457  if ((status = nc_def_var(ncid_out, "bincount_swir", NC_FLOAT, NDIMS,
8458  dimids, &varid8)))
8459  check_err(status, __LINE__, __FILE__);
8460  //lat/lon
8461  if ((status = nc_def_var(ncid_out, "lat_gd", NC_FLOAT, NDIMS,
8462  dimids, &varid2)))
8463  check_err(status, __LINE__, __FILE__);
8464  if ((status = nc_def_var(ncid_out, "lon_gd", NC_FLOAT, NDIMS,
8465  dimids, &varid3)))
8466  check_err(status, __LINE__, __FILE__);
8467  if ((status = nc_enddef(ncid_out))) //done def vars etc
8468  check_err(status, __LINE__, __FILE__);
8469  //writing the whole thing
8470  if ((status = nc_put_var_float(ncid_out, varid2, &lat_out[0][0])))
8471  check_err(status, __LINE__, __FILE__);
8472  if ((status = nc_put_var_float(ncid_out, varid3, &lon_out[0][0])))
8473  check_err(status, __LINE__, __FILE__);
8474 
8475  //blue
8476  /*
8477  if ((status = nc_put_var_float(ncid_out, varid, &data_out[0][0])))
8478  check_err(status, __LINE__, __FILE__);
8479  if ((status = nc_put_var_float(ncid_out, varid4, &data_out2[0][0])))
8480  check_err(status, __LINE__, __FILE__);
8481  */
8482  //red
8483  // if ((status = nc_put_var_float(ncid_out, varid5, &data_out3[0][0])))
8484  // check_err(status, __LINE__, __FILE__);
8485  /*
8486  if ((status = nc_put_var_float(ncid_out, varid6, &data_out4[0][0])))
8487  check_err(status, __LINE__, __FILE__);
8488  //swir
8489  if ((status = nc_put_var_float(ncid_out, varid7, &data_out5[0][0])))
8490  check_err(status, __LINE__, __FILE__);
8491  if ((status = nc_put_var_float(ncid_out, varid8, &data_out6[0][0])))
8492  check_err(status, __LINE__, __FILE__);
8493  */
8494 
8495  if ((status = nc_close(ncid_out)))
8496  check_err(status, __LINE__, __FILE__);
8497 
8498  delete[](lat_out);
8499  delete[](lon_out);
8500 
8501  // delete [] (data_out);
8502  // delete [] (data_out2);
8503  // delete [] (data_out3);
8504 
8505  /* delete [] (data_out4);
8506  delete [] (data_out5);
8507  delete [] (data_out6);
8508 
8509  delete [] (bincount);
8510  delete [] (binmean_Lt);
8511  delete [] (bincount2);
8512  delete [] (binmean_Lt2);
8513  delete [] (bincount3);
8514  delete [] (binmean_Lt3);
8515  */
8516 
8517  delete[](Ltfracsum);
8518  delete[](areabinsum);
8519  delete[](nobs_perbin);
8520 
8521 
8522  lat_out = nullptr;;
8523  lon_out = nullptr;
8524  // data_out=nullptr;
8525  // data_out2=nullptr;
8526  // data_out3=nullptr;
8527 
8528  /* data_out4=nullptr;
8529  data_out5=nullptr;
8530  data_out6=nullptr;
8531 
8532  bincount=nullptr;
8533  binmean_Lt=nullptr;
8534  bincount2=nullptr;
8535  binmean_Lt2=nullptr;
8536  bincount3=nullptr;
8537  binmean_Lt3=nullptr;
8538  */
8539 
8540  Ltfracsum = nullptr;
8541  areabinsum = nullptr;
8542  nobs_perbin = nullptr;
8543 
8544  flag_donefile = 0;
8545  }//end writing file
8546  }//end for files
8547 
8548  cout << "group k at the end of big loop" << k + 1 << endl;
8549 
8550  }//groups
8551 
8552  cout << "number of files per swath.." << nfiles_swt[swtd - 1] << "for swath.." << swtd << endl;
8553  cout << "total inpix.." << inpix << "total pix.." << totpix << endl;
8554 
8555  delete [](dlatb_g);
8556  delete [](dlonb_g);
8557  delete [](lat_asort);
8558  delete [](index_xy);
8559  delete [](az_east);
8560  delete [](lat_gd);
8561  delete [](lon_gd);
8562 
8563 
8564  printf("*** SUCCESS writing AW bincount and binLt rasters as nc..!\n");
8565 
8566  return(0);
8567  }
8568 
8569 
8570 
8571 
8572 
8573 
8574  //similar to w2 version byt hyperspectral-including FRED search L1C row/col algo
8575  int32_t L1C::binL1C_wgranule4(int swtd, l1c_filehandle* l1cfile, L1C_input* l1cinput, int16_t* swtd_id, int16_t* odir, int16_t* file_id, int16_t* nfiles_swt) {
8576  int32_t gdlines_group,ngroups = 0, num_gridlines, nbinx, n_files, inpix = 0, outpix = 0, totpix = 0, n_gdlines;//number of gridlines to be processed
8577  float minv = 0., maxv = 0.;
8578  int16_t fi = 0;
8579  std::string str;
8580  const char* ptstr;
8581  int dimid, status, ncid_out, x_dimid, y_dimid, varid, varid2, varid3,NDIMS;
8582  size_t start[] = { 0, 0 };
8583  size_t count[] = { 1, 1 };
8584  size_t start2[] = { 0, 0, 0 };
8585  size_t count2[] = { 1, 1, 1 }, count3[] = { 1, 1, 1 }, count4[] = { 1, 1, 1 };
8586  int32_t bin_xpix, bin_ypix;
8587  float* latpix, * lonpix, ** Lt_pix, ** Lt_pix2, ** Lt_pix3;
8588 
8589  float latmin_swt = 100, latmax_swt = 0, lonmin_swt = 0, lonmax_swt = 0;
8590  int dimids[2];
8591  const char* filename_lt;
8592  int32_t NY = -1, NX = -1, NY1 = -1, NY2 = -1, c1 = 1;
8593  float** data_out, ** data_out2, ** data_out3, ** lat_out, ** lon_out;
8594 
8595  int last_file, last_sline, flag_inpix,flag_donefile;;//first index file id, second index line #
8596  short** index_xy;
8597  float** lat_asort;
8598  bool boolbin1=0;
8599  int16_t selyear = -1, selmon = -1, selday = -1;
8600  float** lat_gd, ** lon_gd, * az_east;
8601  string gridname, azeast_name;
8602  float*** bincount = NULL, *** bincount2 = NULL, *** bincount3 = NULL, *** binmean_Lt = nullptr, *** binmean_Lt2 = nullptr, *** binmean_Lt3 = nullptr;
8603  double gres = (l1cinput->gres) * 1000, dlamin, dlamax, dlomin, dlomax;
8604  int grp_root, grp_blue, grp_red, grp_swir, grp_coor, scGrp;
8605  unsigned int bb = 0, rb = 0, swb = 0;
8606  float lon_eqc = -1;
8607  double time_eqc = -1, toffset_pix = -999.;
8608  short Nneg = -1;
8609  unsigned int sline;
8610  float **dlonb_g,**dlatb_g;
8611 
8612  Geodesic geod(Constants::WGS84_a(), Constants::WGS84_f());
8613 
8614 
8615 
8616  //random seed
8617  srand((unsigned int)time(NULL));
8618  //nadir pixel ofr OCI
8619  int nadpix = l1cfile->nadpix;
8620 
8621 
8622  num_gridlines = 4000;
8623 
8624  nbinx = l1cfile->nbinx;
8625  num_pixels = l1cfile->npix;
8626  n_files = l1cfile->ifiles.size();
8627  size_t sfiles = 0;
8628 
8629  if (l1cfile->selgran[0] < 0)//process all granules
8630  {
8631  sfiles = nfiles_swt[swtd - 1];
8632  for (unsigned int j = 0;j < sfiles;j++) l1cfile->selgran[j] = j + 1;
8633  }
8634  else {
8635  while (l1cfile->selgran[sfiles] > 0) {
8636  cout << "selected granule #..........................." << l1cfile->selgran[sfiles] << endl;
8637  sfiles++;
8638  }
8639  }
8640 
8641 
8642 
8643 
8644  //determine crossing time of the swath
8645  cout << "nfiles.for the swath." << n_files << endl;
8646  for (int i = 0;i < n_files;i++) {
8647  str = l1cfile->ifiles[i];
8648  ptstr = str.c_str();
8649  cout << "checking crossing time for file...." << ptstr << endl;
8650 
8651  //computation of equatorial crossing time
8652  if (status = ect_sf(ptstr, l1cfile,l1cinput) > 1) {
8653  cout << "problems checking crossing time...for file.." << ptstr << endl;
8654  exit(1);
8655 }
8656 
8657  if (l1cfile->orbit_node_lon > -999. | l1cfile->eqt > 0.) {
8658  lon_eqc = l1cfile->orbit_node_lon;
8659  time_eqc = l1cfile->eqt;
8660  break;
8661  }
8662  }
8663 
8664  cout << "time equat crossing..." << time_eqc << "longitude at crossing time..." << lon_eqc << endl;
8665 
8666 
8667  // exit(1);
8668 
8669 
8670 
8671 
8672 
8673  //allocate mem for lat/lon/azeast pointers---
8674  selday = l1cinput->selday;
8675  selmon = l1cinput->selmon;
8676  selyear = l1cinput->selyear;
8677 
8678  std::string fname_out, pathstr, senstr, monstr, daystr, yearstr, prodstr, gdstr, swtstr, swtnum, extstr, granstr;
8679 
8680  pathstr = "out/";
8681  senstr = "OCIS_";
8682  monstr = std::to_string(selmon);
8683  daystr = std::to_string(selday);
8684  yearstr = std::to_string(selyear);
8685  prodstr = "L1Cgrid";
8686  swtstr = "_swt";
8687  extstr = ".csv";
8688 
8689  if (l1cfile->l1c_pflag >= 3) {
8690  swtd = l1cfile->swtnum;
8691  swtnum = std::to_string(swtd);
8692  cout << "swtnum.." << swtnum << endl;
8693  }
8694  else swtnum = std::to_string(swtd);
8695 
8696  gridname = pathstr + senstr + monstr + daystr + yearstr + prodstr + swtstr + swtnum + extstr;
8697 
8698  prodstr = "az_east";
8699  azeast_name = pathstr + senstr + monstr + daystr + yearstr + prodstr + swtstr + swtnum + extstr;
8700  cout << "gridname.." << gridname << "azeast-name.." << azeast_name << endl;
8701 
8702  //************ OPENING **************************************
8703  //*** AZ_EAST *****************
8704  //*** AZ_EAST *****************
8705  std::string line;
8706  stringstream ss;
8707  std::string temp;
8708  std::vector<std::string> parts;
8709  ifstream fin(azeast_name);
8710  int cline = 0;
8711  while (getline(fin, line))
8712  {
8713  // load line in stringstream
8714  ss << line;
8715  getline(ss, temp, ',');
8716  parts.push_back(temp);
8717  ss.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
8718  ss.clear();
8719  cline++;
8720  }
8721  //minus -1 cause the header
8722  cout << "size of azeast minus heading row..= num_gridlines." << parts.size() - 1 << "nbinx.." << nbinx << endl;
8723  num_gridlines = parts.size() - 1;
8724 
8725 
8726  //**LAT_GD *******************
8727  ifstream fin2(gridname);
8728  std::vector<std::string> tokens_lon, tokens_lat;
8729  std::string token;
8730  cline = 0;
8731  int fcol = 0;
8732  while (getline(fin2, line))
8733  {
8734  // load line in stringstream
8735  istringstream iss(line);
8736  while (getline(iss, token, ','))
8737  {
8738  cline++;
8739  if (fcol == 0 && cline > 2) {
8740  tokens_lon.push_back(token);fcol++;
8741 }
8742  else if (fcol == 1 && cline > 2)
8743  tokens_lat.push_back(token);
8744 
8745  }
8746  fcol = 0;
8747  }
8748 
8749 
8750 
8751 
8752  cout << "size of gridline minus heading row..= num_gridlines." << (tokens_lon.size() - 1) / nbinx << "nbinx.." << nbinx << endl;
8753 
8754 
8755  //************************************************************
8756  //mem allocation for geolcoation pointers---
8757  az_east = (float*)malloc(num_gridlines * sizeof(float));
8758  lat_gd = allocate2d_float(num_gridlines, nbinx);
8759  lon_gd = allocate2d_float(num_gridlines, nbinx);
8760 
8761  float sum = 0, tot = 0;
8762  for (int j = 0;j < num_gridlines;j++) {
8763  // cout<<"j.."<<j<<"az_east"<<std::stof(parts[j+1])<<endl;
8764  az_east[j] = std::stof(parts[j + 1]);//first line is the header
8765  sum = az_east[j];
8766  tot += sum;
8767  }
8768  parts.clear();
8769 
8770 
8771 
8772  //using swath-averaged az_east for nadir pixels rather than along-track az_east pixel-by-pixel
8773  float mean_az_east = tot / (num_gridlines - 1);
8774  cout << "mean_az_east..." << mean_az_east << "numgridlines.." << num_gridlines << endl;
8775  // exit(1);
8776  for (int j = 0;j < num_gridlines;j++) {
8777  az_east[j] = mean_az_east;
8778  }
8779  int ip = 0;
8780  for (int j = 0;j < num_gridlines;j++) {
8781  for (int k = 0;k < nbinx;k++) {
8782  lat_gd[j][k] = std::stof(tokens_lat[ip]);
8783  lon_gd[j][k] = std::stof(tokens_lon[ip]);
8784  // if(ip % nbinx == 0) cout<<"ip.."<<ip<<"gdline.."<<j+1<<"binx.."<<k+1<<"latgd.."<<std::stof(tokens_lat[ip])<<"longd.."<<std::stof(tokens_lon[ip])<<endl;
8785  ip++;
8786 
8787  //compute Nneg
8788  if (odir[0] > 0 && lat_gd[j][k] > 0 && Nneg < 0) {//ascending orbit
8789  if (k > 0) Nneg = j + 1;
8790  else Nneg = j;
8791  cout << "number of lines with negative latitude...." << Nneg << "for orbit direction..." << odir[0] << "latitude..." << lat_gd[j][k] << endl;
8792  // exit(1);
8793  }
8794 
8795  }
8796  }
8797  tokens_lon.clear();
8798  tokens_lat.clear();
8799 
8800  //determine # of gd groups to be processede
8801  //gdlines_group=num_gridlines;//ONE BIG GROUP
8802  gdlines_group = 250;
8803 
8804  if (num_gridlines <= gdlines_group) {
8805  gdlines_group = num_gridlines;
8806  cout << "WARNING********************* number_gridlines<=gdlines_group THEN gdlines_group=num_gridlines **************" << endl;
8807  }
8808 
8809  ngroups = floor(num_gridlines / gdlines_group);
8810  cout << "TOTAL # of gd groups.(ALL LATs...." << ngroups << endl;
8811 
8812  //--NORMALIZED gridline longitude is -180 to 180 degrees before comparison with longitude extracted from image pixels---
8813  for (int i = 0; i < num_gridlines; i++) {
8814  for (int j = 0; j < nbinx; j++) {
8815  if (lon_gd[i][j] < -180.)lon_gd[i][j] += 360.;
8816  if (lon_gd[i][j] > 180.)lon_gd[i][j] -= 360.;
8817  }
8818 }
8819  //get min/max lat/lon of the swath
8820  // Assume first element as maximum and minimum
8821  maxv = lat_gd[0][0];
8822  minv = lat_gd[0][0];
8823 
8824  //Find maximum and minimum in all array elements.
8825  for (int i = 0; i < num_gridlines; i++) {
8826  for (int j = 0; j < nbinx; j++) {
8827  if (lat_gd[i][j] > maxv)
8828  maxv = lat_gd[i][j];
8829  if (lat_gd[i][j] < minv)
8830  minv = lat_gd[i][j];
8831  }
8832 }
8833 
8834 
8835  maxv = lon_gd[0][0];
8836  minv = lon_gd[0][0];
8837  //Find maximum and minimum in all array elements.
8838  for (int i = 0; i < num_gridlines; i++) {
8839  for (int j = 0; j < nbinx; j++) {
8840  if (lon_gd[i][j] > maxv)
8841  maxv = lon_gd[i][j];
8842  if (lon_gd[i][j] < minv)
8843  minv = lon_gd[i][j];
8844  }
8845  }
8846 
8847 
8848 
8849  cout << "swath #.." << swtd << endl;
8850 
8851  //check lat bound min/max of each gd group---
8852  int k = 0, i = 0;
8853 
8854  dlatb_g = allocate2d_float(ngroups + 1, 2);
8855  dlonb_g = allocate2d_float(ngroups + 1, 2);
8856 
8857  //recompute number of gridlines based on lat limits -80 to 80 degrees
8858  //asc orbit goes from negative to positive latitude....
8859  NY = num_gridlines;
8860  NX = nbinx;
8861  for (int i = 0; i < NY; i++) {
8862  for (int j = 0; j < NX; j++) {
8863  if (lat_gd[i][j] >= -80.) c1++;
8864  if (c1 == nbinx) {
8865  NY1 = i;
8866  }
8867  }
8868  if (NY1 >= 0) break;
8869  c1 = 1;
8870  }
8871 
8872 
8873  for (int i = 0;i < NY; i++) {
8874  // cout<<"i.."<<i<<"lat_gd[i][j]..."<<lat_gd[i][nadpix]<<endl;
8875  for (int j = 0; j < NX; j++) {
8876  if (lat_gd[i][j] >= 80.) {
8877  NY2 = i - 1;
8878  }
8879  }
8880 
8881  if (NY2 >= 0) break;
8882  }
8883 
8884  // cout<<"gridlines limited to -80 to 80 degrees of latitutde.."<<"gdline ini.."<<NY1<<"gdline end.."<<NY2<<endl;
8885 
8886  l1cfile->NY1 = NY1;
8887  l1cfile->NY2 = NY2;
8888 
8889  cout << "NY.." << NY << "NY1.." << NY1 << "NY2.." << NY2 << endl;
8890 
8891 
8892 
8893  num_gridlines = NY2 - NY1 + 1;//this is the # gridlines after -80 to 80 lat constraint---
8894  ngroups = floor(num_gridlines / gdlines_group);
8895  cout << "gdlines will start in gline.." << i + 1 << "ROUNDED ngroups after adjusting beginning.for constraint lat (-80 to 80)" << ngroups << endl;
8896 
8897  //for each 'grid' group scan the swath files to see if there are scanlines within--
8898  //if that is case check the across-bin number position (0 to binx-1) based on latnad and lonnad values---
8899  last_file = 0;
8900  last_sline = 0;
8901  flag_donefile = 0;
8902 
8903  num_blue_bands = 120;
8904  num_red_bands = 120;
8905  num_SWIR_bands = 9;
8906 
8907  if (num_gridlines > ngroups * gdlines_group) ngroups += 1;
8908 
8909 
8910  //*********** SORTING LAT/LON ASCENDING AND TRACK INDEXES ****************************
8911  //***********************************************************************************
8912 
8913  //Create index matrix for i and j of each lat and lon L1C grid (-80 to 80)
8914  //num_gridlines x nbinx
8915  index_xy = allocate2d_short(num_gridlines, nbinx);
8916  lat_asort = allocate2d_float(num_gridlines, nbinx);
8917  // lon_asort=allocate2d_float(num_gridlines,nbinx);
8918  //fill indexe
8919 
8920  //define 1-D vector to sort 1 col L1C grid at the time---
8921  vector<pair<float, int> > vp;
8922 
8923  //fill vector with lat_gd column--
8924  cout << "*********** SORTING LAT/LON GRIDPOINTS AND TRACKING INDEXES ********************" << endl;
8925 
8926  for (int col = 0;col < nbinx;col++) {
8927  for (int row = NY1;row < NY2 + 1;row++) {
8928  vp.push_back(make_pair(lat_gd[row][col] + 90., row));
8929  }
8930  //sort
8931  stable_sort(vp.begin(), vp.end());
8932  //display lat in order along with its gridpoint index--
8933  // cout << "Lat value\t"
8934  // << "index" << endl;
8935  for (unsigned int i = 0; i < vp.size(); i++) {
8936  lat_asort[i][col] = vp[i].first;
8937  index_xy[i][col] = vp[i].second;
8938  }
8939  vp.clear();
8940  }
8941 
8942  //saddleback search
8943  short gd_row, gd_col;
8944 
8945  cout << "num_gridlines...." << num_gridlines << "ngroups.." << ngroups << endl;
8946 
8947 
8948  //****************************************************************************************************
8949  //************* BIG LOOP GROUPS ***************************************
8950  cout << "Number of granules to be L1C processed........................................." << sfiles << endl;
8951 
8952  for (k = 0;k < ngroups;k++) {
8953 
8954  //total gridlines for k groups-----
8955  n_gdlines = (k + 1) * gdlines_group;
8956  cout << "screening k group.." << k + 1 << "last_file.." << last_file << "last_line.." << last_sline << endl;
8957  cout << "number of gridlines so far..." << n_gdlines << endl;
8958  //***** compute deltas for lat_gd index 256 and 257 *******************
8959 
8960  //compute delta_lat and delta_lon based on binres/2 for lower and upper corners of 'nadir' gridpoints of 256 and 257 indexes -----------------
8961  //we need nadir 256 and 257 lat/lon coordinates to compute -delta and +delta, respectively
8962  //we need azimuth and backazimuth and binres/2 to compute deltas ---
8963 
8964  //index 256
8965  geod.Direct(lat_gd[n_gdlines - gdlines_group][256], lon_gd[n_gdlines - gdlines_group][256], az_east[n_gdlines - gdlines_group], gres, dlamin, dlomin);
8966  geod.Direct(lat_gd[n_gdlines - 1][257], lon_gd[n_gdlines - 1][257], az_east[n_gdlines - 1], gres, dlamax, dlomax);
8967 
8968  cout << "dlamin.." << dlamin << "dlomin.." << dlomin << "dlamax.." << dlamax << "dlomax.." << dlomax << endl;
8969 
8970  dlatb_g[k][0] = dlamin;//in DEGREES!!
8971  dlatb_g[k][1] = dlamax;
8972  dlonb_g[k][0] = dlomin;
8973  dlonb_g[k][1] = dlomax;
8974 
8975  //********* LOOP FILES ************************************
8976  for (unsigned int findex = last_file;findex < sfiles;findex++) {
8977 
8978  cout << "Scanning lines in file.. for crossing swath..." << swtd << "selected granule #.." << l1cfile->selgran[findex] << "swt_id.." << swtd_id[findex] << "grid group.." << k + 1 << endl;
8979 
8980 
8981  if (last_sline == 0 && binmean_Lt == nullptr && binmean_Lt2 == nullptr && binmean_Lt3 == nullptr) { // binmean_Lt==NULL | bincount==NULL | binmean_Lt2==NULL | bincount2==NULL | binmean_Lt3==NULL | bincount3==NULL){
8982 
8983  cout << "first allocation of memory for grid bins of file #..." << l1cfile->selgran[findex] << endl;
8984 
8985  // cout<<"findex.."<<findex<<"blue bands"<<num_blue_bands<<"red bands.."<<num_red_bands<<"swir bands..."<<num_SWIR_bands<<"nbinx.."<<nbinx<<endl;
8986 
8987  binmean_Lt = allocate3d_float(num_blue_bands, num_gridlines, nbinx);
8988  bincount = allocate3d_float(num_blue_bands, num_gridlines, nbinx);
8989  binmean_Lt2 = allocate3d_float(num_red_bands, num_gridlines, nbinx);
8990  bincount2 = allocate3d_float(num_red_bands, num_gridlines, nbinx);
8991  binmean_Lt3 = allocate3d_float(num_SWIR_bands, num_gridlines, nbinx);
8992  bincount3 = allocate3d_float(num_SWIR_bands, num_gridlines, nbinx);
8993 
8994  for (unsigned int k = 0;k < num_blue_bands;k++) {
8995  for (int i = 0; i < num_gridlines; i++) {
8996  for (int j = 0; j < nbinx; j++) {
8997  bincount[k][i][j] = 0.;
8998  binmean_Lt[k][i][j] = 0.;
8999  }
9000 }
9001 }
9002 
9003  for (unsigned int k = 0;k < num_red_bands;k++) {
9004  for (int i = 0; i < num_gridlines; i++) {
9005  for (int j = 0; j < nbinx; j++) {
9006  bincount2[k][i][j] = 0.;
9007  binmean_Lt2[k][i][j] = 0.;
9008  }
9009 }
9010 }
9011 
9012  for (unsigned int k = 0;k < num_SWIR_bands;k++) {
9013  for (int i = 0; i < num_gridlines; i++) {
9014  for (int j = 0; j < nbinx; j++) {
9015  bincount3[k][i][j] = 0.;
9016  binmean_Lt3[k][i][j] = 0.;
9017  }
9018 }
9019 }
9020  }//end allocating bin arrays
9021 
9022 
9023  fi = l1cfile->selgran[findex];
9024  str = l1cfile->ifiles[fi - 1];
9025  ptstr = str.c_str();
9026 
9027  cout << "opening filename............" << ptstr << endl;
9028 
9029  status = nc_open(ptstr, NC_NOWRITE, &ncid_L1B);
9030  if (status != NC_NOERR) {
9031  fprintf(stderr, "nc_open.\n");
9032  exit(EXIT_FAILURE);
9033 }
9034  //Open dimensions
9035  status = nc_inq_dimid(ncid_L1B, "number_of_scans", &dimid);
9036  if (status != NC_NOERR) {
9037  fprintf(stderr, "-E- Error reading number_of_scans.\n");
9038  exit(EXIT_FAILURE);
9039  }
9040  nc_inq_dimlen(ncid_L1B, dimid, &num_scans);
9041 
9042  //read line-by-line lat/lon/Lt
9043  status = nc_inq_grp_ncid(ncid_L1B, "geolocation_data", &geoGrp);
9044  check_err(status, __LINE__, __FILE__);
9045  status = nc_inq_grp_ncid(ncid_L1B, "observation_data", &obsGrp);
9046  check_err(status, __LINE__, __FILE__);
9047  status = nc_inq_grp_ncid(ncid_L1B, "scan_line_attributes", &scGrp);
9048  check_err(status, __LINE__, __FILE__);
9049 
9050  //open time
9051  status = nc_inq_varid(scGrp, "time", &otId);
9052  check_err(status, __LINE__, __FILE__);
9053  //open geo data
9054  status = nc_inq_varid(geoGrp, "latitude", &latId);//scans x velements
9055  check_err(status, __LINE__, __FILE__);
9056  status = nc_inq_varid(geoGrp, "longitude", &lonId);//scans x velements
9057  check_err(status, __LINE__, __FILE__);
9058  status = nc_inq_varid(obsGrp, "Lt_blue", &Lt_blueId);
9059  check_err(status, __LINE__, __FILE__);
9060  status = nc_inq_varid(obsGrp, "Lt_red", &Lt_redId);
9061  check_err(status, __LINE__, __FILE__);
9062  status = nc_inq_varid(obsGrp, "Lt_SWIR", &Lt_SWIRId);
9063  check_err(status, __LINE__, __FILE__);
9064 
9065  // num_blue_bands
9066  status = nc_inq_dimid(ncid_L1B, "blue_bands", &dimid);
9067  if (status != NC_NOERR) {
9068  fprintf(stderr, "-E- Error reading num_blue_bands.\n");
9069  exit(EXIT_FAILURE);
9070  }
9071  nc_inq_dimlen(ncid_L1B, dimid, &num_blue_bands);
9072 
9073  // num_red_bands
9074  status = nc_inq_dimid(ncid_L1B, "red_bands", &dimid);
9075  if (status != NC_NOERR) {
9076  fprintf(stderr, "-E- Error reading num_red_bands.\n");
9077  exit(EXIT_FAILURE);
9078  }
9079  nc_inq_dimlen(ncid_L1B, dimid, &num_red_bands);
9080 
9081  // num_SWIR_bands
9082  status = nc_inq_dimid(ncid_L1B, "SWIR_bands", &dimid);
9083  if (status != NC_NOERR) {
9084  fprintf(stderr, "-E- Error reading num_SWIR_bands.\n");
9085  exit(EXIT_FAILURE);
9086  }
9087  nc_inq_dimlen(ncid_L1B, dimid, &num_SWIR_bands);
9088  //assigning mem for Lt of different bands **********************
9089 
9090  double* orb_time = new double[num_scans]();
9091  status = nc_get_var_double(scGrp, otId, orb_time);
9092 
9093  /* for(int s=0;s<num_scans;s++)
9094  cout<<"orb time..."<<orb_time[s]<<"for scanline..."<<s+1<<endl;
9095  exit(1);
9096  */
9097 
9098 
9099  latpix = (float*)malloc(num_pixels * sizeof(float));
9100  lonpix = (float*)malloc(num_pixels * sizeof(float));
9101  Lt_pix = allocate2d_float(num_blue_bands, num_pixels);//blue bands
9102  Lt_pix2 = allocate2d_float(num_red_bands, num_pixels);//red bands
9103  Lt_pix3 = allocate2d_float(num_SWIR_bands, num_pixels);//SWIR bands
9104 
9105  cout << "#blue bands.." << num_blue_bands << endl;
9106  cout << "#red bands.." << num_red_bands << endl;
9107  cout << "#swir bands.." << num_SWIR_bands << endl;
9108  //********************************************************************************
9109  //-----reading line by line-----------------------------------
9110  for (sline = last_sline;sline < num_scans;sline++) {
9111 
9112 
9113  //compute time offset for each pixel of that line--assuming all pixels across-track have the same nadir time (along-track)
9114  toffset_pix = orb_time[sline] - time_eqc;
9115 
9116 
9117 
9118  //lat and lon--
9119  start[0] = sline;
9120  start[1] = 0;
9121  count[0] = 1;
9122  count[1] = num_pixels; // 1 line at a time
9123 
9124  status = nc_get_vara_float(geoGrp, latId, start, count, latpix);
9125  status = nc_get_vara_float(geoGrp, lonId, start, count, lonpix);
9126 
9127  //****************************blue bands *********************************************************************
9128  //loop blue bands------------
9129  //*************************************************************************************************************
9130  //Lt
9131 
9132  start2[0] = 0;
9133  start2[1] = sline;
9134  start2[2] = 0;
9135 
9136  count2[0] = num_blue_bands;
9137  count2[1] = 1; // 1 line at a time
9138  count2[2] = num_pixels;
9139 
9140  count3[0] = num_red_bands;
9141  count3[1] = 1; // 1 line at a time
9142  count3[2] = num_pixels;
9143 
9144  count4[0] = num_SWIR_bands;
9145  count4[1] = 1; // 1 line at a time
9146  count4[2] = num_pixels;
9147 
9148  status = nc_get_vara_float(obsGrp, Lt_blueId, start2, count2, Lt_pix[0]);
9149  status = nc_get_vara_float(obsGrp, Lt_redId, start2, count3, Lt_pix2[0]);
9150  status = nc_get_vara_float(obsGrp, Lt_SWIRId, start2, count4, Lt_pix3[0]);
9151 
9152  /* for(int bb=0;bb<num_blue_bands;bb++){
9153  cout<<"processing blue band #.........................................................................."<<bb+1<<"of total blue bands #.."<<num_blue_bands<<endl;
9154  cout<<"Lt_pix at pix =0..."<<Lt_pix[bb][0]<<"Lt_pix at pix =1..."<<Lt_pix[bb][1]<<endl;
9155  }
9156  exit(1);
9157  */
9158 
9159  for (unsigned int pix = 0;pix < num_pixels;pix++) {
9160  if (latpix[pix] < latmin_swt) latmin_swt = latpix[pix];
9161  if (latpix[pix] > latmax_swt) latmax_swt = latpix[pix];
9162  if (lonpix[pix] < lonmin_swt) lonmin_swt = lonpix[pix];
9163  if (lonpix[pix] > lonmax_swt) lonmax_swt = lonpix[pix];
9164  }
9165 
9166  //cout<<"latpix[nadpix]..."<<latpix[nadpix]<<"lonpix[nadpix]..."<<lonpix[nadpix]<<endl;
9167  // cout<<"dlatb_g[k][0]...."<<dlatb_g[k][0]<<"dlatb_g[k][1]...."<<dlatb_g[k][1]<<endl;
9168 
9169  dlamin = 0.;dlamax = 0.;
9170 
9171 
9172  //inside the 'k' box??----- ascending ----------
9173  if (latpix[nadpix] >= dlatb_g[k][0] && latpix[nadpix] <= dlatb_g[k][1]) {
9174 
9175  if (sline % 100 == 0) cout << "EVERY 100 gds..for k group.." << k + 1 << "file number #.." << l1cfile->selgran[findex] << "sline..." << sline + 1 << "# of binned pix.." << inpix << "outpix.." << outpix << endl;
9176 
9177  //*********** BIG LOOP M_PIXEL *****************************************************************
9178  for (unsigned int pix = 0;pix < num_pixels;pix++) {
9179 
9180  bb = 0, rb = 0, swb = 0;
9181  flag_inpix = 0, bin_xpix = -1, bin_ypix = -1;
9182 
9183  // cout<<"LINE NUMBER------------------------------------------------------------------------------------------------------------------------#"<<sline+1<<"pix #........"<<pix+1<<endl;
9184  search_rc_l1c(l1cinput, l1cfile, latpix[pix], lonpix[pix], toffset_pix, lon_eqc, &gd_row, &gd_col, Nneg);
9185 
9186  // boolbin1=sbs2_l1c(l1cinput,num_gridlines,nbinx,lat_asort,index_xy,latpix[pix],lonpix[pix],lon_gd,&gd_row, &gd_col);
9187  if(gd_row>=0 && gd_col>=0) boolbin1=1;
9188 
9189  bin_ypix = gd_row + 1;
9190  bin_xpix = gd_col + 1;
9191 
9192  // cout<<"pix..."<<pix+1<<"latpix..."<<latpix[pix]<<"lonpix..."<<lonpix[pix]<<endl;
9193 
9194  if (boolbin1 == 1) flag_inpix = 1;
9195  //************ BINNING ***************************
9196  //assign identified pixel to Lt and bin stat arrays-----
9197  //BLUE---
9198  if (flag_inpix == 1 && bin_xpix >= 1 && bin_ypix >= 1 && bin_xpix <= nbinx && bin_ypix <= num_gridlines) {
9199  inpix++;
9200  while (bb < num_blue_bands) {
9201  if (Lt_pix[bb][pix] > 0.) {
9202  binmean_Lt[bb][bin_ypix - 1][bin_xpix - 1] = binmean_Lt[bb][bin_ypix - 1][bin_xpix - 1] + Lt_pix[bb][pix];
9203  bincount[bb][bin_ypix - 1][bin_xpix - 1] += 1;
9204  }
9205  bb++;
9206  }//end while blue band band
9207  //RED---
9208  while (rb < num_red_bands) {
9209  if (Lt_pix2[rb][pix] > 0.) {
9210  binmean_Lt2[rb][bin_ypix - 1][bin_xpix - 1] = binmean_Lt2[rb][bin_ypix - 1][bin_xpix - 1] + Lt_pix2[rb][pix];
9211  bincount2[rb][bin_ypix - 1][bin_xpix - 1] += 1;
9212  }
9213  rb++;
9214  }//end red bands
9215 
9216  //SWIR----
9217  while (swb < num_SWIR_bands) {
9218  if (Lt_pix3[swb][pix] > 0.) {
9219  binmean_Lt3[swb][bin_ypix - 1][bin_xpix - 1] = binmean_Lt3[swb][bin_ypix - 1][bin_xpix - 1] + Lt_pix3[swb][pix];
9220  bincount3[swb][bin_ypix - 1][bin_xpix - 1] += 1;
9221  }
9222  swb++;
9223  }//end swir bands
9224 
9225  }//end if inpix
9226 
9227  //********** pixel AREA WEIGHTING ************************
9228  if (flag_inpix == 0) outpix++;
9229 
9230  totpix++;
9231 
9232  }//end pixels loop
9233 
9234 
9235 
9236 
9237  //END OF FILE--****** reset starting sline index if last line processed and within k box
9238  //go for another granule if it is not the last one---------------
9239  if (sline == num_scans - 1) {
9240  flag_donefile = 1;
9241  cout << "end of file..." << l1cfile->selgran[findex] << endl;
9242  last_sline = 0;
9243  if (findex >= sfiles - 1) {
9244  cout << "done with last granule of the input list........................." << endl;
9245  // findex=sfiles;
9246  k = ngroups;
9247  break;
9248  }
9249 
9250  }//end of file/last file? sliine=num_scans-1
9251  else flag_donefile = 0;
9252 
9253  }//end latpix nadir of line x inside grid group?
9254 
9255  //***** skip lines and files if sline is not within k group ********
9256  //increase k and screen files and lines again starting from the last binning
9257 
9258  if (latpix[nadpix] > lat_gd[n_gdlines - 1][257] && k < ngroups - 1) { //else limits
9259  cout << "moving to the next k group...scanning again files/slines.." << endl;
9260  cout << "file index.." << findex << "last sline index.." << sline << endl;
9261  last_file = findex;
9262  last_sline = sline;
9263  findex = sfiles;
9264  sline = num_scans - 1;
9265  }//end if lat >grid lat--IF outside the box
9266  if (sline + 1 % 100 == 0) cout << "for k group.." << k + 1 << "selected granule #.." << l1cfile->selgran[findex] << "sline..." << sline + 1 << "# of binned pix.." << inpix << "totpix.." << totpix << "outpix.." << outpix << endl;
9267  }//end for scanlines
9268 
9269  cout << "closing L1B file......." << ptstr << endl;
9270  status = nc_close(ncid_L1B);
9271  check_err(status, __LINE__, __FILE__);
9272 
9273  delete[](latpix);
9274  delete[](lonpix);
9275  delete[](Lt_pix);
9276  delete[](Lt_pix2);
9277  delete[](Lt_pix3);
9278  delete[](orb_time);
9279 
9280 
9281 
9282 
9283  //**********************************************************************************************************************************
9284  //**********************************************************************************************************************************
9285  //writing each granule ---------------------------------
9286  //*****************************************************************************
9287 
9288  if (flag_donefile == 1 | (flag_donefile == 0 && k == ngroups - 1)) {
9289  cout << "writing file #.............................................." << l1cfile->selgran[findex] << "based on group #.." << k + 1 << endl;
9290  //write mean Lt as nc file---
9291  //**********************************************************************
9292  //**********************************************************************8
9293  //create Lt file
9294  pathstr = "out/";
9295  senstr = "OCIS_";
9296  monstr = std::to_string(selmon);
9297  daystr = std::to_string(selday);
9298  yearstr = std::to_string(selyear);
9299  prodstr = "binLt_orb";
9300  swtstr = "_swt";
9301  granstr = "";
9302  granstr = "_" + std::to_string(l1cfile->selgran[findex]);
9303 
9304  if (l1cfile->l1c_pflag >= 3) {
9305  swtd = l1cfile->swtnum;
9306  swtnum = std::to_string(swtd);
9307  cout << "swtnum.." << swtnum << endl;
9308  }
9309  else swtnum = std::to_string(swtd);
9310  extstr = ".nc";
9311  NDIMS = 2;
9312  fname_out = pathstr + senstr + monstr + daystr + yearstr + prodstr + swtstr + swtnum + granstr + extstr;
9313  filename_lt = fname_out.c_str();
9314 
9315  /* try
9316  {
9317  cout<<"Opening file \"firstFile.nc\" with NcFile::replace"<<endl;
9318  NcFile ncFile("firstFile.nc",NcFile::replace);
9319  NcGroup groupA(ncFile.addGroup("groupA"));
9320  }
9321 
9322  catch (NcException& e)
9323  {
9324  cout << "unknown error"<<endl;
9325  e.what();
9326  }
9327  exit(1);
9328  */
9329 
9330  if ((status = nc_create(filename_lt, NC_CLOBBER | NC_NETCDF4, &ncid_out)))
9331  check_err(status, __LINE__, __FILE__);
9332  //define dims
9333  // Define the dimensions. NetCDF will hand back an ID for each.
9334  NY = num_gridlines;
9335  NX = nbinx;
9336  NY1 = l1cfile->NY1;//these are indexes not line #!!!!!!!!!!!!!!!!!
9337  NY2 = l1cfile->NY2;
9338  cout << "rowgrid ini.." << NY1 << "rowgrid end.." << NY2 << endl;
9339  NY = NY2 - NY1 + 1;
9340  cout << "NY.." << NY << "NX.." << NX << endl;
9341  //alloc mem for data_out and assign values from lat_gdI
9342  //alloc mem for data_out and assign values from lat_gdI
9343  //NX AND NY are inverted for visualization in SeaDAS
9344 
9345  // data_out=allocate2d_float(NY,NX);
9346 
9347  /* data_out2 = allocate2d_float(NY,NX);
9348  data_out3 = allocate2d_float(NY,NX);
9349  dcfrossata_out4 = allocate2d_float(NY,NX);
9350  data_out5 = allocate2d_float(NY,NX);
9351  data_out6 = allocate2d_float(NY,NX);
9352  */
9353  lat_out = allocate2d_float(NY, NX);
9354  lon_out = allocate2d_float(NY, NX);
9355 
9356  int c = 0;
9357 
9358  for (int i = NY1; i < NY2 + 1; i++) {
9359  for (int j = 0; j < NX; j++) {
9360  lat_out[NY - 1 - c][NX - 1 - j] = lat_gd[i][j];
9361  lon_out[NY - 1 - c][j] = lon_gd[i][j];
9362  }
9363  c++;
9364  }
9365 
9366  //blue
9367  /* c=0;
9368  for(bb=0;bb<num_blue_bands;bb++){
9369  for(int i=NY1; i<NY2+1; i++){
9370  for(int j=0; j<NX; j++){
9371  if (bincount[bb][i][j]>0)
9372  data_out[NY-1-c][NX-1-j]=binmean_Lt[bb][i][j]/bincount[bb][i][j];
9373  else data_out[NY-1-c][NX-1-j]=NAN;
9374  }
9375  c++;
9376  }
9377  }//end bands
9378  */
9379 
9380 
9381  //red
9382  /* if (bincount2[i][j]>0)
9383  data_out3[NY-1-c][NX-1-j]=binmean_Lt2[i][j]/bincount2[i][j];
9384  else
9385  data_out3[NY-1-c][NX-1-j]=NAN;
9386  //swir
9387  if (bincount3[i][j]>0)
9388  data_out5[NY-1-c][NX-1-j]=binmean_Lt3[i][j]/bincount3[i][j];
9389  else
9390  data_out5[NY-1-c][NX-1-j]=NAN;
9391 
9392  data_out2[NY-1-c][NX-1-j]=bincount[i][j];
9393  data_out4[NY-1-c][NX-1-j]=bincount2[i][j];
9394  data_out6[NY-1-c][NX-1-j]=bincount3[i][j];
9395  */
9396 
9397  // }
9398  // c++;
9399  // }
9400  // }//end bands
9401 
9402  if ((status = nc_def_dim(ncid_out, "x", NX, &x_dimid)))
9403  check_err(status, __LINE__, __FILE__);
9404  if ((status = nc_def_dim(ncid_out, "y", NY, &y_dimid)))
9405  check_err(status, __LINE__, __FILE__);
9406  //dims for output var
9407  dimids[0] = y_dimid;
9408  dimids[1] = x_dimid;
9409 
9410  //define groups-----
9411  // status = nc_def_grp( *ncid, line.c_str(), &gid[ngrps]);
9412  if ((status = nc_def_grp(ncid_out, "data", &grp_root))) //netcdf-4
9413  check_err(status, __LINE__, __FILE__);
9414  if ((status = nc_def_grp(grp_root, "geo_coordinates", &grp_coor))) //netcdf-4
9415  check_err(status, __LINE__, __FILE__);
9416  if ((status = nc_def_grp(grp_root, "blue_bands", &grp_blue))) //netcdf-4
9417  check_err(status, __LINE__, __FILE__);
9418  if ((status = nc_def_grp(grp_root, "red_bands", &grp_red))) //netcdf-4
9419  check_err(status, __LINE__, __FILE__);
9420  if ((status = nc_def_grp(grp_root, "swir_bands", &grp_swir))) //netcdf-4
9421  check_err(status, __LINE__, __FILE__);
9422 
9423  //def var--------------------
9424 
9425  //loop blue channels-----
9426 
9427  string bb_num, rb_num, swb_num, bb_str = "binLt_blue_ch", rb_str = "binLt_red_ch", swb_str = "binLt_swir_ch";
9428 
9429  int varid_bb[num_blue_bands], varid_rb[num_red_bands], varid_swb[num_SWIR_bands];
9430 
9431  for (bb = 0;bb < num_blue_bands;bb++) {
9432  bb_num = std::to_string(bb + 1);
9433  bb_num = bb_str + bb_num;
9434  if ((status = nc_def_var(grp_blue, bb_num.c_str(), NC_FLOAT, NDIMS, dimids, &varid))) check_err(status, __LINE__, __FILE__);
9435  varid_bb[bb] = varid;
9436  }
9437 
9438  for (rb = 0;rb < num_red_bands;rb++) {
9439  rb_num = std::to_string(rb + 1);
9440  rb_num = rb_str + rb_num;
9441  if ((status = nc_def_var(grp_red, rb_num.c_str(), NC_FLOAT, NDIMS, dimids, &varid))) check_err(status, __LINE__, __FILE__);
9442  varid_rb[rb] = varid;
9443  }
9444 
9445  for (swb = 0;swb < num_SWIR_bands;swb++) {
9446  swb_num = std::to_string(swb + 1);
9447  swb_num = swb_str + swb_num;
9448  if ((status = nc_def_var(grp_swir, swb_num.c_str(), NC_FLOAT, NDIMS, dimids, &varid))) check_err(status, __LINE__, __FILE__);
9449  varid_swb[swb] = varid;
9450  }
9451 
9452  // if ((status = nc_def_var(grp_blue,"whatever", NC_FLOAT, NDIMS,
9453  // dimids, &varid)))
9454 
9455 
9456 
9457  // if ((status = nc_def_var(ncid_out, "bincount_blue", NC_FLOAT, NDIMS,
9458  // dimids, &varid4)))
9459  // check_err(status, __LINE__, __FILE__);
9460  //red
9461  /* if ((status = nc_def_var(ncid_out, "binLt_red", NC_FLOAT, NDIMS,
9462  dimids, &varid5)))
9463  check_err(status, __LINE__, __FILE__);
9464  if ((status = nc_def_var(ncid_out, "bincount_red", NC_FLOAT, NDIMS,
9465  dimids, &varid6)))
9466  check_err(status, __LINE__, __FILE__);
9467  //swir
9468  if ((status = nc_def_var(ncid_out, "binLt_swir", NC_FLOAT, NDIMS,
9469  dimids, &varid7)))
9470  check_err(status, __LINE__, __FILE__);
9471  if ((status = nc_def_var(ncid_out, "bincount_swir", NC_FLOAT, NDIMS,
9472  dimids, &varid8)))
9473  check_err(status, __LINE__, __FILE__);
9474  */
9475 
9476  //lat/lon
9477  if ((status = nc_def_var(grp_coor, "lat_gd", NC_FLOAT, NDIMS,
9478  dimids, &varid2)))
9479  check_err(status, __LINE__, __FILE__);
9480  if ((status = nc_def_var(grp_coor, "lon_gd", NC_FLOAT, NDIMS,
9481  dimids, &varid3)))
9482  check_err(status, __LINE__, __FILE__);
9483  //leave define mode-----------------------
9484  if ((status = nc_enddef(ncid_out))) //done def vars etc
9485  check_err(status, __LINE__, __FILE__);
9486 
9487  //assign variable data------------------------
9488  /* start2[0]=0;
9489  start2[1]=0;
9490  start2[2]=0;
9491 
9492  count2[0]=1;
9493  count2[1]=NY;
9494  count2[2]=NX;
9495 
9496 
9497  float lat_data[NY][NX];
9498 
9499  for (int i=0;i<NY;i++){
9500  for (int j=0;j<NX;j++){
9501  lat_data[i][j]=lat_out[i][j];
9502  }}
9503 
9504  */
9505  // if((status = nc_put_vara_float(ncid_out,varid2,start2,count2,&lat_out[0][0])))
9506  // check_err(status, __LINE__, __FILE__);
9507  // if((status = nc_put_vara(grp_coor,varid3,start,count,lon_out)));
9508  // check_err(status, __LINE__, __FILE__);
9509  // if((status = nc_put_vara(grp_blue,varid,start,count,data_out)));
9510  // check_err(status, __LINE__, __FILE__);
9511 
9512  if ((status = nc_put_var_float(grp_coor, varid2, &lat_out[0][0])))
9513  check_err(status, __LINE__, __FILE__);
9514 
9515  if ((status = nc_put_var_float(grp_coor, varid3, &lon_out[0][0])))
9516  check_err(status, __LINE__, __FILE__);
9517  //blue
9518 
9519  for (bb = 0;bb < num_blue_bands;bb++) {
9520  data_out = allocate2d_float(NY, NX);
9521  c = 0;
9522  for (int i = NY1; i < NY2 + 1; i++) {
9523  for (int j = 0; j < NX; j++) {
9524  data_out[NY - 1 - c][NX - 1 - j] = 0.;
9525  }
9526  c++;
9527  }
9528  c = 0;
9529  for (int i = NY1; i < NY2 + 1; i++) {
9530  for (int j = 0; j < NX; j++) {
9531  if (bincount[bb][i][j] > 0)
9532  data_out[NY - 1 - c][NX - 1 - j] = binmean_Lt[bb][i][j] / bincount[bb][i][j];
9533  else data_out[NY - 1 - c][NX - 1 - j] = NAN;
9534  }
9535  c++;
9536  }
9537  cout << "writing blue band#.." << bb + 1 << endl;
9538  if ((status = nc_put_var_float(grp_blue, varid_bb[bb], &data_out[0][0])))
9539  check_err(status, __LINE__, __FILE__);
9540 
9541 
9542  delete[](data_out);
9543  }//end blue bands
9544 
9545 
9546  //red
9547  for (rb = 0;rb < num_red_bands;rb++) {
9548  data_out2 = allocate2d_float(NY, NX);
9549  c = 0;
9550  for (int i = NY1; i < NY2 + 1; i++) {
9551  for (int j = 0; j < NX; j++) {
9552  data_out2[NY - 1 - c][NX - 1 - j] = 0.;
9553  }
9554  c++;
9555  }
9556  c = 0;
9557  for (int i = NY1; i < NY2 + 1; i++) {
9558  for (int j = 0; j < NX; j++) {
9559  if (bincount2[rb][i][j] > 0)
9560  data_out2[NY - 1 - c][NX - 1 - j] = binmean_Lt2[rb][i][j] / bincount2[rb][i][j];
9561  else data_out2[NY - 1 - c][NX - 1 - j] = NAN;
9562  }
9563  c++;
9564  }
9565  cout << "writing red band#.." << rb + 1 << endl;
9566  if ((status = nc_put_var_float(grp_red, varid_rb[rb], &data_out2[0][0])))
9567  check_err(status, __LINE__, __FILE__);
9568 
9569  delete[](data_out2);
9570  }//end red bands
9571 
9572 
9573  //swir
9574  for (swb = 0;swb < num_SWIR_bands;swb++) {
9575  data_out3 = allocate2d_float(NY, NX);
9576  c = 0;
9577  for (int i = NY1; i < NY2 + 1; i++) {
9578  for (int j = 0; j < NX; j++) {
9579  data_out3[NY - 1 - c][NX - 1 - j] = 0.;
9580  }
9581  c++;
9582  }
9583  c = 0;
9584  for (int i = NY1; i < NY2 + 1; i++) {
9585  for (int j = 0; j < NX; j++) {
9586  if (bincount3[swb][i][j] > 0)
9587  data_out3[NY - 1 - c][NX - 1 - j] = binmean_Lt3[swb][i][j] / bincount3[swb][i][j];
9588  else data_out3[NY - 1 - c][NX - 1 - j] = NAN;
9589  }
9590  c++;
9591  }
9592  cout << "writing SWIR band#.." << swb + 1 << endl;
9593  if ((status = nc_put_var_float(grp_swir, varid_swb[swb], &data_out3[0][0])))
9594  check_err(status, __LINE__, __FILE__);
9595 
9596  delete[](data_out3);
9597  }//end red bands
9598 
9599 
9600  /* if ((status = nc_put_var_float(ncid_out, varid4, &data_out2[0][0])))
9601  check_err(status, __LINE__, __FILE__);
9602  //red
9603  if ((status = nc_put_var_float(ncid_out, varid5, &data_out3[0][0])))
9604  check_err(status, __LINE__, __FILE__);
9605  if ((status = nc_put_var_float(ncid_out, varid6, &data_out4[0][0])))
9606  check_err(status, __LINE__, __FILE__);
9607  //swir
9608  if ((status = nc_put_var_float(ncid_out, varid7, &data_out5[0][0])))
9609  check_err(status, __LINE__, __FILE__);
9610  if ((status = nc_put_var_float(ncid_out, varid8, &data_out6[0][0])))
9611  check_err(status, __LINE__, __FILE__);
9612  */
9613 
9614  if ((status = nc_close(ncid_out)))
9615  check_err(status, __LINE__, __FILE__);
9616 
9617  delete[](lat_out);
9618  delete[](lon_out);
9619  // delete [] (data_out);
9620 
9621 
9622  /* delete [] (data_out2);
9623  delete [] (data_out3);
9624  delete [] (data_out4);
9625  delete [] (data_out5);
9626  delete [] (data_out6);
9627  */
9628  delete[](bincount);
9629  delete[](binmean_Lt);
9630  delete[](bincount2);
9631  delete[](binmean_Lt2);
9632  delete[](bincount3);
9633  delete[](binmean_Lt3);
9634 
9635  lat_out = nullptr;;
9636  lon_out = nullptr;
9637  data_out = nullptr;
9638  data_out2 = nullptr;
9639  data_out3 = nullptr;
9640 
9641 
9642 
9643 
9644  bincount = nullptr;
9645  binmean_Lt = nullptr;
9646  bincount2 = nullptr;
9647  binmean_Lt2 = nullptr;
9648  bincount3 = nullptr;
9649  binmean_Lt3 = nullptr;
9650 
9651  flag_donefile = 0;
9652  }//end writing file
9653  }//end for files
9654 
9655  cout << "group k at the end of big loop" << k + 1 << endl;
9656 
9657  }//groups
9658 
9659  cout << "number of files per swath.." << nfiles_swt[swtd - 1] << "for swath.." << swtd << endl;
9660  cout << "total inpix.." << inpix << "total pix.." << totpix << endl;
9661  // cout<<"binned pixels.."<<inpix<<"as %.."<<(inpix/(num_pixels*num_scans*n_files*nfiles_swt[swtd-1]))*100<<endl;
9662  delete[](lat_asort);
9663  // delete [] (lon_asort);
9664  delete[](index_xy);
9665  // delete [] (index_xy2);
9666  delete[](dlatb_g);
9667  delete[](dlonb_g);
9668 
9669  delete[](lat_gd);
9670  delete[](lon_gd);
9671  delete[](az_east);
9672 
9673  printf("*** SUCCESS writing bincount and binLt rasters as nc..!\n");
9674  cout << "finish processing swath eq crossing day..." << swtd << endl;
9675  cout << "done writing Lt to nc file.." << endl;
9676 
9677  return (0);
9678  }
9679 
9680 
9681  //similar to version 6 but including HARP
9682  int32_t L1C::binL1C_wgranule7(int swtd, l1c_filehandle* l1cfile, L1C_input* l1cinput, int16_t* swtd_id, int16_t* odir, int16_t* file_id, int16_t* nfiles_swt) {
9683  size_t ybins,xbins;
9684  int32_t gdlines_group, ngroups = 0, num_gridlines,nbinx2, nbinx, inpix = 0, outpix = 0, totpix = 0, n_gdlines;//number of gridlines to be processed
9685  float minv = 0., maxv = 0., ** dlatb_g, ** dlonb_g;
9686  int16_t fi = 0;
9687  std::string str;
9688  const char* ptstr;
9689  int dimid, dimid2,dimid3,status, ncid_out,ncid_az,ncid_grid,b_dimid,v_dimid,x_dimid,y_dimid,varid1,varid2, varid_count,varid_lt,azId,NDIMS,NDIMS2,NDIMS3,senazId;
9690  int blueGrp,v1Grp,dimidv,dimidx,dimidy,dimidf;
9691  size_t start[] = { 0, 0 };
9692  size_t count[] = { 1, 1 };
9693  size_t start2[] = { 0, 0, 0 };
9694  size_t count2[] = { 1, 1, 1 }, count3[] = { 1, 1, 1 }, count4[] = { 1, 1, 1 };
9695  int32_t bin_xpix, bin_ypix;
9696  float* latpix=nullptr, * lonpix=nullptr, ** Lt_pix=nullptr, ** Lt_pix2=nullptr, ** Lt_pix3=nullptr,*Lt_pix4=nullptr,mean_az_east,*senazpix=nullptr;
9697 
9698 
9699  float latmin_swt = 100, latmax_swt = 0, lonmin_swt = 0, lonmax_swt = 0;
9700  int dimids[2],dimids2[3],dimids3[4];
9701  const char* filename_lt;
9702  int32_t NY = -1, NX = -1, NY1 = -1, NY2 = -1,c1 = 1;
9703  float****data_out2=nullptr,** lat_out, ** lon_out;
9704  int ***data_out=nullptr;
9705  int last_file, last_sline, flag_inpix, flag_donefile;;//first index file id, second index line #
9706  short** index_xy;
9707  float** lat_asort;
9708  bool boolbin1;
9709  char* ifile_char;
9710  std::string ifile_str;
9711 
9712  int16_t selyear = -1, selmon = -1, selday = -1;
9713  float** lat_gd, ** lon_gd, * az_east;
9714  string gridname, azeast_name;
9715  float**** binmean_Lt = nullptr;
9716  int ****bincount=nullptr;
9717  double gres = (l1cinput->gres) * 1000, dlamin, dlamax, dlomin, dlomax;
9718  int grp_obs,grp_coor,geoGrp,obsGrp,navGrp; ;
9719  size_t sb=0,bb = 0, rb = 0, swb = 0,ib=0, NVIEWS=-1,NBANDS=-1,NBANDS_POL=-1;
9720  int view;
9721  float sum=0,tot=0;
9722  char tmp[256];
9723  short gd_row, gd_col;
9724  float ***latframe1=nullptr,***latframe2=nullptr,***latframe3=nullptr,***lonframe1=nullptr,***lonframe2=nullptr,***lonframe3=nullptr;
9725  int ibin_ini=-1,ibin_end=-1;
9726 
9727 
9728 
9729  Geodesic geod(Constants::WGS84_a(), Constants::WGS84_f());
9730 
9731  //random seed
9732  srand((unsigned int)time(NULL));
9733  //nadir pixel ofr OCI
9734  int nadpix = l1cfile->nadpix;
9735 
9736 
9737  num_gridlines = 4000;
9738  nbinx2 = l1cfile->nbinx;
9739  num_pixels = l1cfile->npix;
9740  num_scans=l1cfile->nscan;
9741  num_pixels=l1cfile->npix;
9742 
9743 
9744  size_t sfiles = 0;
9745 
9746  if (l1cfile->selgran[0] < 0)//process all granules
9747  {
9748  sfiles = nfiles_swt[swtd - 1];
9749  for (unsigned int j = 0;j < sfiles;j++) l1cfile->selgran[j] = j + 1;
9750  }
9751  else {
9752  while (l1cfile->selgran[sfiles] > 0) {
9753  cout << "selected granule #..........................." << l1cfile->selgran[sfiles] << endl;
9754  sfiles++;
9755  }
9756  }
9757 
9758  cout<<"binning Lt using sbs2 method and composite indexes for arrays..................................................................."<<endl;
9759 
9760 
9761  //allocate mem for lat/lon/azeast pointers---
9762  selday = l1cinput->selday;
9763  selmon = l1cinput->selmon;
9764  selyear = l1cinput->selyear;
9765 
9766  std::string fname_out, pathstr, senstr, monstr, daystr, yearstr, prodstr, gdstr, swtstr, swtnum, extstr, granstr,timestr,azstr,missionstr;
9767 
9768  missionstr="PACE";
9769  senstr = "OCIS";
9770  monstr = std::to_string(selmon);
9771  daystr = std::to_string(selday);
9772  yearstr = std::to_string(selyear);
9773  timestr="T00:00:00Z";
9774  prodstr = "L1Cgrid";
9775  swtstr = "_swt";
9776  extstr = ".nc";
9777 
9778  if (l1cfile->l1c_pflag >= 3) {
9779  swtd = l1cfile->swtnum;
9780  swtnum = std::to_string(swtd);
9781  cout << "swtnum.." << swtnum << endl;
9782  }
9783  else swtnum = std::to_string(swtd);
9784 
9785 
9786  getcwd(tmp, 256);
9787  pathstr=tmp;
9788 
9789 //open lat/lon L1C grid --------------------------------------
9790  //PACE_OCIS.2019321T00:00:00ZL1Cgrid.nc
9791  prodstr = "L1Cgrid";
9792  gridname = pathstr + "/out/"+missionstr + "_" + senstr + "." + yearstr + monstr + daystr + timestr + prodstr+extstr;
9793 
9794  //open file
9795  ifile_str = l1cinput->files[0];
9796  ifile_char = &ifile_str[0];
9797  file_format format = getFormat(ifile_char);
9798  // format.type=FT_HARP;
9799 
9800  cout<<"forma type.."<<format.type<<endl;
9801 
9802  if(format.type==FT_SPEXONE | format.type==FT_HARP){
9803  ptstr="/accounts/mamontes/images/OCIS/sean/out/PACE_OCIS.2019321T00:00:00ZL1Cgrid.nc";
9804  cout<<"ptstr..."<<ptstr<<endl;
9805  }
9806  else {//legacy sensors
9807  ptstr = gridname.c_str();
9808  }
9809 
9810  status = nc_open(ptstr, NC_NOWRITE, &ncid_grid);
9811  if (status != NC_NOERR) {
9812  fprintf(stderr, "nc_open error.\n");
9813  exit(EXIT_FAILURE);
9814  }
9815  //groups
9816  status = nc_inq_grp_ncid(ncid_grid, "geolocation_data", &geoGrp);
9817  check_err(status, __LINE__, __FILE__);
9818 
9819  status = nc_inq_dimid(ncid_grid, "bins_along_track", &y_dimid);
9820  check_err(status, __LINE__, __FILE__);
9821  nc_inq_dimlen(ncid_grid, y_dimid, &ybins);
9822  status = nc_inq_dimid(ncid_grid, "bins_across_track", &x_dimid);
9823  check_err(status, __LINE__, __FILE__);
9824 
9825  nc_inq_dimlen(ncid_grid, x_dimid, &xbins);
9826  nc_inq_dimlen(ncid_grid, y_dimid, &ybins);
9827 
9828  //************************************************************
9829  //mem allocation for geolocation pointers---
9830  num_gridlines=ybins;
9831  nbinx=xbins;
9832 
9833  cout<<"num_gridlines"<<num_gridlines<<"nbinx"<<nbinx<<endl;
9834  az_east = (float*)calloc(num_gridlines , sizeof(float));
9835  lat_gd = allocate2d_float(num_gridlines, nbinx);
9836  lon_gd = allocate2d_float(num_gridlines, nbinx);
9837 
9838  status = nc_inq_varid(geoGrp, "latitude", &latId);//scans x velements
9839  check_err(status, __LINE__, __FILE__);
9840  status = nc_inq_varid(geoGrp, "longitude", &lonId);//scans x velements
9841  check_err(status, __LINE__, __FILE__);
9842  status = nc_get_var_float(geoGrp, latId, &lat_gd[0][0]);
9843  check_err(status, __LINE__, __FILE__);
9844  status = nc_get_var_float(geoGrp, lonId, &lon_gd[0][0]);
9845  check_err(status, __LINE__, __FILE__);
9846 //close file
9847  if ((status = nc_close(ncid_grid)))
9848  check_err(status, __LINE__, __FILE__);
9849 
9850 
9851  //open az_east ------
9852  //PACE_OCIS.2019321T00:00:00Zaz_east.nc
9853  prodstr = "az_east";
9854 // cout << "Current working directory: " << tmp << endl;
9855  azstr= pathstr + "/out/"+missionstr + "_" + senstr + "." + yearstr + monstr + daystr + timestr + prodstr+extstr;
9856 
9857  if(format.type==FT_SPEXONE| format.type==FT_HARP){
9858  ptstr="/accounts/mamontes/images/OCIS/sean/out/PACE_OCIS.2019321T00:00:00Zaz_east.nc";
9859  }
9860  else{
9861  ptstr = azstr.c_str();
9862  }
9863  cout <<"Opening file with azimuth east values in degrees............" << ptstr << endl;
9864  // ptstr="/accounts/mamontes/images/OCIS/sean/out/PACE_OCIS.2019321T00:00:00Zaz_east.nc";
9865 
9866  status = nc_open(ptstr, NC_NOWRITE, &ncid_az);
9867  if (status != NC_NOERR) {
9868  fprintf(stderr, "nc_open error.\n");
9869  exit(EXIT_FAILURE);
9870  }
9871  status = nc_inq_dimid(ncid_az, "bins_along_track", &y_dimid);
9872  check_err(status, __LINE__, __FILE__);
9873  nc_inq_dimlen(ncid_az, y_dimid, &ybins);
9874 
9875  status = nc_inq_varid(ncid_az, "az_east", &azId);//scans x velements
9876  check_err(status, __LINE__, __FILE__);
9877  status = nc_get_var_float(ncid_az, azId, &az_east[0]);
9878  check_err(status, __LINE__, __FILE__);
9879 
9880  for(size_t i=0;i<ybins;i++){
9881  sum = az_east[i];
9882  tot += sum;
9883  }
9884 //close file
9885  if ((status = nc_close(ncid_az)))
9886  check_err(status, __LINE__, __FILE__);
9887 
9888  //using swath-averaged az_east for nadir pixels rather than along-track az_east pixel-by-pixel
9889  mean_az_east = tot / (ybins);
9890 
9891  l1cfile->mean_az_east=mean_az_east; //in degrees
9892  cout<<"mean_az_east in degrees...."<<mean_az_east<<endl;
9893 
9894 
9895 
9896  //determine # of gd groups to be processede
9897  //gdlines_group=num_gridlines;//ONE BIG GROUP
9898  gdlines_group = 250;
9899 
9900  if (num_gridlines <= gdlines_group) {
9901  gdlines_group = num_gridlines;
9902  cout << "WARNING********************* number_gridlines<=gdlines_group THEN gdlines_group=num_gridlines **************" << endl;
9903  }
9904 
9905  ngroups = floor(num_gridlines / gdlines_group);
9906  cout << "TOTAL # of gd groups.(ALL LATs...." << ngroups << endl;
9907 
9908  //--NORMALIZED gridline longitude is -180 to 180 degrees before comparison with longitude extracted from image pixels---
9909  for (int i = 0; i < num_gridlines; i++) {
9910  for (int j = 0; j < nbinx; j++) {
9911  if (lon_gd[i][j] < -180.)lon_gd[i][j] += 360.;
9912  if (lon_gd[i][j] > 180.)lon_gd[i][j] -= 360.;
9913  }
9914  }
9915  //get min/max lat/lon of the swath
9916  // Assume first element as maximum and minimum
9917  maxv = lat_gd[0][0];
9918  minv = lat_gd[0][0];
9919 
9920  //Find maximum and minimum in all array elements.
9921  for (int i = 0; i < num_gridlines; i++) {
9922  for (int j = 0; j < nbinx; j++) {
9923  if (lat_gd[i][j] > maxv)
9924  maxv = lat_gd[i][j];
9925  if (lat_gd[i][j] < minv)
9926  minv = lat_gd[i][j];
9927  }
9928  }
9929 
9930 
9931  maxv = lon_gd[0][0];
9932  minv = lon_gd[0][0];
9933  //Find maximum and minimum in all array elements.
9934  for (int i = 0; i < num_gridlines; i++) {
9935  for (int j = 0; j < nbinx; j++) {
9936  if (lon_gd[i][j] > maxv)
9937  maxv = lon_gd[i][j];
9938  if (lon_gd[i][j] < minv)
9939  minv = lon_gd[i][j];
9940  }
9941  }
9942 
9943 
9944 
9945  cout << "swath #.." << swtd << endl;
9946 
9947  //check lat bound min/max of each gd group---
9948  int k = 0, i = 0;
9949 
9950  dlatb_g = allocate2d_float(ngroups + 1, 2);
9951  dlonb_g = allocate2d_float(ngroups + 1, 2);
9952 
9953  //recompute number of gridlines based on lat limits -80 to 80 degrees
9954  //asc orbit goes from negative to positive latitude....
9955  NY = num_gridlines;
9956  NX = nbinx;
9957  for (int i = 0; i < NY; i++) {
9958  for (int j = 0; j < NX; j++) {
9959  if (lat_gd[i][j] >= -80.) c1++;
9960  if (c1 == nbinx) {
9961  NY1 = i;
9962  }
9963  }
9964  if (NY1 >= 0) break;
9965  c1 = 1;
9966  }
9967 
9968 
9969  for (int i = 0;i < NY; i++) {
9970  // cout<<"i.."<<i<<"lat_gd[i][j]..."<<lat_gd[i][nadpix]<<endl;
9971  for (int j = 0; j < NX; j++) {
9972  if (lat_gd[i][j] >= 80.) {
9973  NY2 = i - 1;
9974  }
9975  }
9976 
9977  if (NY2 >= 0) break;
9978  }
9979 
9980  // cout<<"gridlines limited to -80 to 80 degrees of latitutde.."<<"gdline ini.."<<NY1<<"gdline end.."<<NY2<<endl;
9981 
9982  l1cfile->NY1 = NY1;
9983  l1cfile->NY2 = NY2;
9984 
9985  cout << "NY.." << NY << "NY1.." << NY1 << "NY2.." << NY2 << endl;
9986 
9987 
9988 
9989  num_gridlines = NY2 - NY1 + 1;//this is the # gridlines after -80 to 80 lat constraint---
9990 
9991  cout<<"numgridlines after restriction lat"<<num_gridlines<<endl;
9992 
9993  ngroups = floor(num_gridlines / gdlines_group);
9994  cout << "gdlines will start in gline.." << i + 1 << "ROUNDED ngroups after adjusting beginning.for constraint lat (-80 to 80)" << ngroups << endl;
9995 
9996  //for each 'grid' group scan the swath files to see if there are scanlines within--
9997  //if that is case check the across-bin number position (0 to binx-1) based on latnad and lonnad values---
9998  last_file = 0;
9999  last_sline = 0;
10000  flag_donefile = 0;
10001 
10002  if (num_gridlines > ngroups * gdlines_group) ngroups += 1;
10003 
10004 
10005  //*********** SORTING LAT/LON ASCENDING AND TRACK INDEXES ****************************
10006  //***********************************************************************************
10007 
10008  //Create index matrix for i and j of each lat and lon L1C grid (-80 to 80)
10009  //num_gridlines x nbinx
10010  index_xy = allocate2d_short(num_gridlines, nbinx);
10011  lat_asort = allocate2d_float(num_gridlines, nbinx);
10012  // lon_asort=allocate2d_float(num_gridlines,nbinx);
10013  //fill indexe
10014 
10015  //define 1-D vector to sort 1 col L1C grid at the time---
10016  vector<pair<float, int> > vp;
10017 
10018  //fill vector with lat_gd column--
10019  cout << "*********** SORTING LAT/LON GRIDPOINTS AND TRACKING INDEXES ********************" << endl;
10020 
10021  for (int col = 0;col < nbinx;col++) {
10022  for (int row = NY1;row < NY2 + 1;row++) {
10023  vp.push_back(make_pair(lat_gd[row][col] + 90., row));
10024  }
10025  //sort
10026  stable_sort(vp.begin(), vp.end());
10027  //display lat in order along with its gridpoint index--
10028  // cout << "Lat value\t"
10029  // << "index" << endl;
10030  for (unsigned int i = 0; i < vp.size(); i++) {
10031  lat_asort[i][col] = vp[i].first;
10032  index_xy[i][col] = vp[i].second;
10033  }
10034  vp.clear();
10035  }
10036 
10037  cout << "num_gridlines...." << num_gridlines << "ngroups.." << ngroups << endl;
10038 
10039 
10040  //****************************************************************************************************
10041  //************* BIG LOOP GROUPS ***************************************
10042  cout << "Number of granules to be L1C processed........................................." << sfiles << endl;
10043 
10044 //**********BIG LOOP GROUPS ********************
10045  for (k = 0;k < ngroups;k++) {
10046 
10047  //total gridlines for k groups-----
10048  n_gdlines = (k + 1) * gdlines_group;
10049  cout << "screening k group.." << k + 1 << "last_file.." << last_file << "last_line.." << last_sline << endl;
10050  cout << "number of gridlines so far..." << n_gdlines << endl;
10051  //***** compute deltas for lat_gd index 256 and 257 *******************
10052 
10053  //compute delta_lat and delta_lon based on binres/2 for lower and upper corners of 'nadir' gridpoints of 256 and 257 indexes -----------------
10054  //we need nadir 256 and 257 lat/lon coordinates to compute -delta and +delta, respectively
10055  //we need azimuth and backazimuth and binres/2 to compute deltas ---
10056 
10057  //index 256
10058  geod.Direct(lat_gd[n_gdlines - gdlines_group][256], lon_gd[n_gdlines - gdlines_group][256], az_east[n_gdlines - gdlines_group], gres, dlamin, dlomin);
10059  geod.Direct(lat_gd[n_gdlines - 1][257], lon_gd[n_gdlines - 1][257], az_east[n_gdlines - 1], gres, dlamax, dlomax);
10060 
10061  cout << "dlamin.." << dlamin << "dlomin.." << dlomin << "dlamax.." << dlamax << "dlomax.." << dlomax << endl;
10062 
10063  dlatb_g[k][0] = dlamin;//in DEGREES!!
10064  dlatb_g[k][1] = dlamax;
10065  dlonb_g[k][0] = dlomin;
10066  dlonb_g[k][1] = dlomax;
10067 
10068 //********* LOOP FILES ************************************
10069  for (unsigned int findex = last_file;findex < sfiles;findex++) {
10070 
10071  cout << "Scanning lines in file.. for crossing swath..." << swtd << "selected granule #.." << l1cfile->selgran[findex] << "swt_id.." << swtd_id[findex] << "grid group.." << k + 1 << endl;
10072 
10073  fi = l1cfile->selgran[findex];
10074  str = l1cfile->ifiles[fi - 1];
10075  ptstr = str.c_str();
10076 
10077  cout << "opening filename............" << ptstr << endl;
10078 
10079  status = nc_open(ptstr, NC_NOWRITE, &ncid_L1B);
10080  if (status != NC_NOERR) {
10081  fprintf(stderr, "nc_open error.\n");
10082  exit(EXIT_FAILURE);
10083  }
10084  //Open dimensions
10085 
10086  if(format.type==FT_SPEXONE){
10087  status = nc_inq_dimid(ncid_L1B, "bins_along_track", &dimid);
10088  if (status != NC_NOERR) {
10089  fprintf(stderr, "-E- Error reading number_of_scans.\n");
10090  exit(EXIT_FAILURE); }
10091  status = nc_inq_dimid(ncid_L1B, "spatial_samples_per_image", &dimid2);
10092  if (status != NC_NOERR) {
10093  fprintf(stderr, "-E- Error reading spatial_samples_per_image.\n");
10094  exit(EXIT_FAILURE); }
10095  status = nc_inq_dimid(ncid_L1B, "intensity_bands_per_view", &dimid3);
10096  if (status != NC_NOERR) {
10097  fprintf(stderr, "-E- Error reading intensity_bands_per_view.\n");
10098  exit(EXIT_FAILURE); }
10099  // spatial_samples_per_image, intensity_bands_per_view
10100  //
10101  nc_inq_dimlen(ncid_L1B, dimid, &num_scans);
10102  }
10103  else if(format.type==FT_HARP){
10104  status = nc_inq_grp_ncid(ncid_L1B, "blue", &blueGrp);
10105  if (status != NC_NOERR) {
10106  fprintf(stderr, "-E- Error reading group blue.\n");
10107  exit(EXIT_FAILURE);
10108  }
10109  status = nc_inq_dimid(blueGrp,"Views", &dimidv);
10110  if (status != NC_NOERR) {
10111  fprintf(stderr, "-E- Error reading dimensions number_of views.\n");
10112  exit(EXIT_FAILURE);
10113  }
10114  //reading subgroup view1
10115  status = nc_inq_grp_ncid(blueGrp, "View01", &v1Grp);
10116  if (status != NC_NOERR) {
10117  fprintf(stderr, "-E- Error reading subgroup view 1 --blue.\n");
10118  exit(EXIT_FAILURE);
10119  }
10120  //lines and pixels
10121  status = nc_inq_dimid(v1Grp,"Swath_Pixels", &dimidx);
10122  if (status != NC_NOERR) {
10123  fprintf(stderr, "-E- Error reading # pixel dimensions view01.\n");
10124  exit(EXIT_FAILURE);
10125  }
10126  status = nc_inq_dimid(v1Grp,"Swath_Lines", &dimidy);
10127  if (status != NC_NOERR) {
10128  fprintf(stderr, "-E- Error reading # lines dimensions view01.\n");
10129  exit(EXIT_FAILURE);
10130  }
10131  status = nc_inq_grp_ncid(ncid_L1B, "navigation", &navGrp);
10132  if (status != NC_NOERR) {
10133  fprintf(stderr, "-E- Error reading group navigation.\n");
10134  exit(EXIT_FAILURE);
10135  }
10136  status = nc_inq_dimid(navGrp,"Vector_Elements", &dimidf);
10137  if (status != NC_NOERR) {
10138  fprintf(stderr, "-E- Error reading # frames dimensions view01.\n");
10139  exit(EXIT_FAILURE);
10140  }
10141 
10142  nc_inq_dimlen(v1Grp, dimidv, &nviews);
10143  nc_inq_dimlen(v1Grp, dimidy, &num_scans);
10144  nc_inq_dimlen(v1Grp, dimidx, &num_pixels);
10145  nc_inq_dimlen(navGrp, dimidf, &num_frames);
10146 
10147  cout<<"# views.."<<nviews<<"# scans.."<<num_scans<<"# pixels.."<<num_pixels<<"num_frames..."<<num_frames<<endl;
10148  }
10149  else{//OCIS
10150  status = nc_inq_dimid(ncid_L1B, "number_of_scans", &dimid);
10151  if (status != NC_NOERR) {
10152  fprintf(stderr, "-E- Error reading number_of_scans.\n");
10153  exit(EXIT_FAILURE);
10154  }
10155  nc_inq_dimlen(ncid_L1B, dimid, &num_scans);
10156 
10157  }
10158 
10159 
10160 
10161  //read line-by-line lat/lon/Lt
10162  if(format.type==FT_SPEXONE){
10163  status = nc_inq_grp_ncid(ncid_L1B, "GEOLOCATION_DATA", &geoGrp);
10164  check_err(status, __LINE__, __FILE__);
10165  status = nc_inq_grp_ncid(ncid_L1B, "OBSERVATION_DATA", &obsGrp);
10166  check_err(status, __LINE__, __FILE__);
10167  status = nc_inq_varid(geoGrp, "sensor_azimuth", &senazId);
10168  check_err(status, __LINE__, __FILE__);
10169  status = nc_inq_varid(geoGrp, "latitude", &latId);
10170  check_err(status, __LINE__, __FILE__);
10171  status = nc_inq_varid(geoGrp, "longitude", &lonId);
10172  check_err(status, __LINE__, __FILE__);
10173  }
10174  else if(format.type==FT_HARP){
10175  //get latitude and longitude
10176  status = nc_inq_varid(v1Grp, "Latitude", &latId);
10177  check_err(status, __LINE__, __FILE__);
10178  status = nc_inq_varid(v1Grp, "Longitude", &lonId);
10179  check_err(status, __LINE__, __FILE__);
10180  status = nc_inq_varid(navGrp, "FrameID", &frameId);
10181  check_err(status, __LINE__, __FILE__);
10182 
10183  /*
10184  latframe1 = allocate3d_float(num_frames,num_scans, num_pixels);
10185  lonframe1 = allocate3d_float(num_frames,num_scans, num_pixels);
10186  latframe2 = allocate3d_float(num_frames,num_scans, num_pixels);
10187  lonframe2 = allocate3d_float(num_frames,num_scans, num_pixels);
10188  latframe3 = allocate3d_float(num_frames,num_scans, num_pixels);
10189  lonframe3 = allocate3d_float(num_frames,num_scans, num_pixels);
10190 
10191  //sensor1--0 degrees polariz
10192  status = nc_inq_grp_ncid(ncid_L1B, "Sensor1", &sen1Grp);
10193  check_err(status, __LINE__, __FILE__);
10194  status = nc_inq_varid(sen1Grp, "Latitude", &latId1);//scans x velements
10195  check_err(status, __LINE__, __FILE__);
10196  status = nc_get_var_float(sen1Grp, latId1, &latframe1[0][0][0]);
10197  check_err(status, __LINE__, __FILE__);
10198  status = nc_inq_varid(sen1Grp, "Longitude", &lonId1);
10199  check_err(status, __LINE__, __FILE__);
10200  status = nc_get_var_float(sen1Grp, lonId1, &lonframe1[0][0][0]);
10201  check_err(status, __LINE__, __FILE__);
10202 
10203 
10204  //sensor2--45 degrees poilar
10205  status = nc_inq_grp_ncid(ncid_L1B, "Sensor2", &sen2Grp);
10206  check_err(status, __LINE__, __FILE__);
10207  status = nc_inq_varid(sen2Grp, "Latitude", &latId2);//scans x velements
10208  check_err(status, __LINE__, __FILE__);
10209  status = nc_get_var_float(sen2Grp, latId2, &latframe2[0][0][0]);
10210  check_err(status, __LINE__, __FILE__);
10211  status = nc_inq_varid(sen2Grp, "Longitude", &lonId2);
10212  check_err(status, __LINE__, __FILE__);
10213  status = nc_get_var_float(sen2Grp, lonId2, &lonframe2[0][0][0]);
10214  check_err(status, __LINE__, __FILE__);
10215 
10216  //sensor3--90 degrees pola
10217  status = nc_inq_grp_ncid(ncid_L1B, "Sensor3", &sen3Grp);
10218  check_err(status, __LINE__, __FILE__);
10219  status = nc_inq_varid(sen3Grp, "Latitude", &latId3);//scans x velements
10220  check_err(status, __LINE__, __FILE__);
10221  status = nc_get_var_float(sen3Grp, latId3, &latframe3[0][0][0]);
10222  check_err(status, __LINE__, __FILE__);
10223  status = nc_inq_varid(sen3Grp, "Longitude", &lonId3);
10224  check_err(status, __LINE__, __FILE__);
10225  status = nc_get_var_float(sen3Grp, lonId3, &lonframe3[0][0][0]);
10226  check_err(status, __LINE__, __FILE__);
10227 
10228 
10229  */
10230  }
10231  else{//legacy sensors
10232  status = nc_inq_grp_ncid(ncid_L1B, "geolocation_data", &geoGrp);
10233  check_err(status, __LINE__, __FILE__);
10234  status = nc_inq_grp_ncid(ncid_L1B, "observation_data", &obsGrp);
10235  check_err(status, __LINE__, __FILE__);
10236  status = nc_inq_varid(geoGrp, "sensor_azimuth", &senazId);
10237  check_err(status, __LINE__, __FILE__);
10238  status = nc_inq_varid(geoGrp, "latitude", &latId);
10239  check_err(status, __LINE__, __FILE__);
10240  status = nc_inq_varid(geoGrp, "longitude", &lonId);
10241  check_err(status, __LINE__, __FILE__);
10242  }
10243 
10244  //radiance variables
10245  if(format.type==FT_SPEXONE){
10246  NVIEWS= 1;//should be 5 but only provided 1
10247  NBANDS=400;
10248  NBANDS_POL=50;
10249  status = nc_inq_varid(obsGrp, "I", &I_Id);
10250  check_err(status, __LINE__, __FILE__);
10251  status = nc_inq_varid(obsGrp, "I_polsample", &Ipol_Id);
10252  check_err(status, __LINE__, __FILE__);
10253 
10254  cout << "#total number of Intensity bands per view.." << NBANDS << endl;
10255  cout << "#total number of Polarization bands per view.." << NBANDS_POL << endl;
10256  }
10257  else if(format.type==FT_HARP){
10258  NVIEWS= 1;//HARP-2 10 but 60 for 669 nm
10259  NBANDS=1;//
10260  NBANDS_POL=1;
10261  status = nc_inq_varid(v1Grp, "I", &I_Id);
10262  check_err(status, __LINE__, __FILE__);
10263  /*
10264  status = nc_inq_varid(obsGrp, "I", &I_Id);
10265  check_err(status, __LINE__, __FILE__);
10266  status = nc_inq_varid(obsGrp, "I_polsample", &Ipol_Id);
10267  check_err(status, __LINE__, __FILE__);
10268  */
10269  cout << "#total number of Intensity bands per view.." << NBANDS << endl;
10270  cout << "#total number of Polarization bands per view.." << NBANDS_POL << endl;
10271  }
10272  else{//OCIS
10273  NVIEWS= 2;//for OCI
10274  NBANDS=249;//for OCI
10275  status = nc_inq_varid(obsGrp, "Lt_blue", &Lt_blueId);
10276  check_err(status, __LINE__, __FILE__);
10277  status = nc_inq_varid(obsGrp, "Lt_red", &Lt_redId);
10278  check_err(status, __LINE__, __FILE__);
10279  status = nc_inq_varid(obsGrp, "Lt_SWIR", &Lt_SWIRId);
10280  check_err(status, __LINE__, __FILE__);
10281  // num_blue_bands
10282  status = nc_inq_dimid(ncid_L1B, "blue_bands", &dimid);
10283  if (status != NC_NOERR) {
10284  fprintf(stderr, "-E- Error reading num_blue_bands.\n");
10285  exit(EXIT_FAILURE);
10286  }
10287  nc_inq_dimlen(ncid_L1B, dimid, &num_blue_bands);
10288 
10289  // num_red_bands
10290  status = nc_inq_dimid(ncid_L1B, "red_bands", &dimid);
10291  if (status != NC_NOERR) {
10292  fprintf(stderr, "-E- Error reading num_red_bands.\n");
10293  exit(EXIT_FAILURE);
10294  }
10295  nc_inq_dimlen(ncid_L1B, dimid, &num_red_bands);
10296 
10297  // num_SWIR_bands
10298  status = nc_inq_dimid(ncid_L1B, "SWIR_bands", &dimid);
10299  if (status != NC_NOERR) {
10300  fprintf(stderr, "-E- Error reading num_SWIR_bands.\n");
10301  exit(EXIT_FAILURE);
10302  }
10303  nc_inq_dimlen(ncid_L1B, dimid, &num_SWIR_bands);
10304  cout << "#blue bands.." << num_blue_bands << endl;
10305  cout << "#red bands.." << num_red_bands << endl;
10306  cout << "#swir bands.." << num_SWIR_bands << endl;
10307  nbands=num_blue_bands+num_red_bands+num_SWIR_bands;
10308  cout << "#total number of bands.." << nbands << endl;
10309  }
10310 
10311  cout<<"#gridlines.."<<num_gridlines<<"# binx2.."<<nbinx2<<"number of scans.."<<num_scans<<"# pixels.."<<num_pixels<<endl;
10312  cout<<"num of views.."<<NVIEWS<<"number of bands.."<<NBANDS<<endl;
10313 
10314 
10315 
10316 
10317  if (last_sline == 0 && binmean_Lt == nullptr) { // binmean_Lt==NULL | bincount==NULL | binmean_Lt2==NULL | bincount2==NULL | binmean_Lt3==NULL | bincount3==NULL){
10318 
10319  cout << "first allocation of memory for grid bins of file #..." << l1cfile->selgran[findex] << endl;
10320 
10321  // cout<<"findex.."<<findex<<"blue bands"<<num_blue_bands<<"red bands.."<<num_red_bands<<"swir bands..."<<num_SWIR_bands<<"nbinx.."<<nbinx<<endl;
10322  binmean_Lt = allocate4d_float(NVIEWS,NBANDS,num_gridlines,nbinx2);
10323  bincount = allocate4d_int(NVIEWS,NBANDS,num_gridlines,nbinx2);//all bands together, only 1 view for OCI
10324 
10325  // binmean_Lt = allocate3d_float(num_gridlines,nbinx,nbands);
10326  // bincount = allocate3d_int(num_gridlines,nbinx,nbands);//all bands together, only 1 view for OCI
10327  for(size_t v=0;v<NVIEWS;v++){
10328  for(size_t b=0;b<NBANDS;b++){
10329  for(int j=0;j<num_gridlines;j++){
10330  for(int i=0;i<nbinx2;i++){
10331  binmean_Lt[v][b][j][i]=0.;
10332  bincount[v][b][j][i]=0;
10333  }}}}
10334 
10335  }//end if first time allocating mem for binning arrays
10336 
10337  if(format.type==FT_SPEXONE){
10338  //assigning mem for Lt of different bands **********************
10339  latpix = (float*)calloc(num_pixels , sizeof(float));
10340  lonpix = (float*)calloc(num_pixels , sizeof(float));
10341  Lt_pix = allocate2d_float(num_pixels,NBANDS);//blue bands
10342  Lt_pix2 = allocate2d_float(num_pixels,NBANDS_POL);//red bands
10343  }
10344  else if(format.type==FT_HARP){
10345  latpix = (float*)calloc(num_pixels , sizeof(float));
10346  lonpix = (float*)calloc(num_pixels , sizeof(float));
10347  Lt_pix4 = (float*)calloc(num_pixels , sizeof(float));
10348  }
10349  else{
10350  senazpix=(float*)calloc(num_pixels , sizeof(float));
10351  latpix = (float*)calloc(num_pixels , sizeof(float));
10352  lonpix = (float*)calloc(num_pixels , sizeof(float));
10353  Lt_pix = allocate2d_float(num_blue_bands, num_pixels);//blue bands
10354  Lt_pix2 = allocate2d_float(num_red_bands, num_pixels);//red bands
10355  Lt_pix3 = allocate2d_float(num_SWIR_bands, num_pixels);//S
10356  }
10357 
10358 //BIG SCANLINE LOOP----------------------------------
10359  //********************************************************************************
10360  //-----reading line by line-----------------------------------
10361 
10362  for (unsigned int sline = last_sline;sline < num_scans;sline++) {
10363 
10364  //lat and lon--
10365  start[0] = sline;
10366  start[1] = 0;
10367  count[0] = 1;
10368  count[1] = num_pixels; // 1 line at a time
10369  if(format.type==FT_SPEXONE){
10370  status = nc_get_vara_float(geoGrp, latId, start, count, latpix);
10371  status = nc_get_vara_float(geoGrp, lonId, start, count, lonpix);
10372  }
10373  else if(format.type==FT_HARP){
10374  status = nc_get_vara_float(v1Grp, latId, start, count, latpix);
10375  status = nc_get_vara_float(v1Grp, lonId, start, count, lonpix);
10376  }
10377  else{ //OCIS
10378  status = nc_get_vara_float(geoGrp, senazId, start, count, senazpix);//-1800 to + 1800 s means s as scaled
10379  status = nc_get_vara_float(geoGrp, latId, start, count, latpix);
10380  status = nc_get_vara_float(geoGrp, lonId, start, count, lonpix);
10381  }
10382 
10383  //Lt
10384 
10385  if(format.type==FT_SPEXONE){
10386  start2[0] = sline;
10387  start2[1] = 0;
10388  start2[2] = 0;
10389 
10390  count2[0] = 1;
10391  count2[1] = num_pixels; // 1 line at a time
10392  count2[2] = NBANDS;
10393 
10394  count3[0] = 1;
10395  count3[1] = num_pixels; // 1 line at a time
10396  count3[2] = NBANDS_POL;
10397 
10398  status = nc_get_vara_float(obsGrp, Lt_blueId, start2, count2, Lt_pix[0]);//all intensity bands
10399  status = nc_get_vara_float(obsGrp, Lt_redId, start2, count3, Lt_pix2[0]);//all poalrized bands
10400  }
10401  //Lt_pix4
10402  else if (format.type==FT_HARP){
10403  status = nc_get_vara_float(v1Grp, I_Id, start, count, Lt_pix4);//blue band
10404  }
10405  else{ //OCIS
10406  start2[0] = 0;
10407  start2[1] = sline;
10408  start2[2] = 0;
10409 
10410  count2[0] = num_blue_bands;
10411  count2[1] = 1; // 1 line at a time
10412  count2[2] = num_pixels;
10413 
10414  count3[0] = num_red_bands;
10415  count3[1] = 1; // 1 line at a time
10416  count3[2] = num_pixels;
10417 
10418  count4[0] = num_SWIR_bands;
10419  count4[1] = 1; // 1 line at a time
10420  count4[2] = num_pixels;
10421 
10422  status = nc_get_vara_float(obsGrp, Lt_blueId, start2, count2, Lt_pix[0]);
10423  status = nc_get_vara_float(obsGrp, Lt_redId, start2, count3, Lt_pix2[0]);
10424  status = nc_get_vara_float(obsGrp, Lt_SWIRId, start2, count4, Lt_pix3[0]);
10425  }
10426 
10427 
10428  /* for(int bb=0;bb<num_blue_bands;bb++){
10429  cout<<"processing blue band #.........................................................................."<<bb+1<<"of total blue bands #.."<<num_blue_bands<<endl;
10430  cout<<"Lt_pix at pix =0..."<<Lt_pix[bb][0]<<"Lt_pix at pix =1..."<<Lt_pix[bb][1]<<endl;
10431  }
10432  exit(1);
10433  */
10434 
10435  for (unsigned int pix = 0;pix < num_pixels;pix++) {
10436  if (latpix[pix] < latmin_swt) latmin_swt = latpix[pix];
10437  if (latpix[pix] > latmax_swt) latmax_swt = latpix[pix];
10438  if (lonpix[pix] < lonmin_swt) lonmin_swt = lonpix[pix];
10439  if (lonpix[pix] > lonmax_swt) lonmax_swt = lonpix[pix];
10440 
10441  // cout<<"senazpix (sensor azimuth)...in degrees."<<senazpix[pix]/100<<"at pix #..."<<pix+1<<"latpix.."<<latpix[pix]<<endl;
10442  }
10443 
10444 
10445 
10446  // cout<<"nadpix..."<<nadpix<<"latpix[nadpix]..."<<latpix[nadpix]<<"lonpix[nadpix]..."<<lonpix[nadpix]<<endl;
10447  // cout<<"dlatb_g[k][0]...."<<dlatb_g[k][0]<<"dlatb_g[k][1]...."<<dlatb_g[k][1]<<endl;
10448  // cout<<"senazpix (sensor azimuth)...in degrees."<<senazpix[nadpix]/100<<"at line #..."<<sline+1<<"latpix[nadpix].."<<latpix[nadpix]<<endl;
10449 
10450  dlamin = 0.;dlamax = 0.;
10451 
10452  //inside the 'k' box??----- ascending ----------
10453  if (latpix[nadpix] >= dlatb_g[k][0] && latpix[nadpix] <= dlatb_g[k][1]) {
10454 
10455  if (sline % 100 == 0) cout << "EVERY 100 gds..for k group.." << k + 1 << "file number #.." << l1cfile->selgran[findex] << "sline..." << sline + 1 << "# of binned pix.." << inpix << "outpix.." << outpix << endl;
10456 
10457  //*********** BIG LOOP M_PIXEL *****************************************************************
10458  for (unsigned int pix = 0;pix < num_pixels;pix++) {
10459 
10460  sb=0,bb=0,rb=0,swb=0,ib=0;
10461  gd_row=0,gd_col=0;
10462  flag_inpix = 0;
10463 
10464  boolbin1 = sbs2_l1c(l1cinput, num_gridlines, nbinx, lat_asort, index_xy, latpix[pix], lonpix[pix], lon_gd, &gd_row, &gd_col);
10465 
10466  bin_ypix = gd_row + 1;
10467  bin_xpix = gd_col + 1;
10468 
10469  // cout<<"pix..."<<pix+1<<"latpix..."<<latpix[pix]<<"lonpix..."<<lonpix[pix]<<endl;
10470 
10471  if (boolbin1 == 1) flag_inpix = 1;
10472  //************ BINNING ***************************
10473  //assign identified pixel to Lt and bin stat arrays-----
10474 
10475  //BLUE---
10476  if (flag_inpix == 1 && bin_xpix >= 1 && bin_ypix >= 1 && bin_xpix <= nbinx && bin_ypix <= num_gridlines) {
10477  inpix++;
10478  if(format.type==FT_SPEXONE){
10479  view=0;
10480  while (sb<NBANDS) {
10481  if (Lt_pix[pix][ib] > 0.) {
10482  // cout<<"Lt_pix[pix][ib]..."<<Lt_pix[pix][ib]<<"bin_ypix.."<<bin_ypix<<"bin_xpix.."<<bin_xpix<<endl;
10483  binmean_Lt[view][ib][bin_ypix - 1][bin_xpix - 1] = binmean_Lt[view][ib][bin_ypix - 1][bin_xpix - 1] + Lt_pix[pix][ib];
10484  bincount[view][ib][bin_ypix - 1][bin_xpix - 1] += 1;
10485  }
10486  ib++;
10487  sb++;
10488  }//end while intensity bands
10489 
10490 /* while (sb<num_blue_bands) {
10491  if (Lt_pix2[bb][pix] > 0.) {
10492  binmean_Lt[view][sb][bin_ypix - 1][bin_xpix - 1] = binmean_Lt[view][sb][bin_ypix - 1][bin_xpix - 1] + Lt_pix2[bb][pix];
10493  bincount[view][sb][bin_ypix - 1][bin_xpix - 1] += 1;
10494  }
10495  bb++;
10496  sb++;
10497  }//end while polarization bands
10498 */
10499  }
10500  if(format.type==FT_HARP){
10501  view=0,sb=0;
10502  if (Lt_pix4[pix] > 0.) {
10503  // cout<<"Lt_pix[pix][ib]..."<<Lt_pix[pix][ib]<<"bin_ypix.."<<bin_ypix<<"bin_xpix.."<<bin_xpix<<endl;
10504  binmean_Lt[view][ib][bin_ypix - 1][bin_xpix - 1] = binmean_Lt[view][ib][bin_ypix - 1][bin_xpix - 1] + Lt_pix4[pix];
10505  bincount[view][ib][bin_ypix - 1][bin_xpix - 1] += 1;
10506  }
10507  ib++;
10508  sb++;
10509  }
10510  else{ //OCIS
10511  if(senazpix[nadpix]/100<0) view=0; else view=1;
10512  while (sb<num_blue_bands) {
10513  if (Lt_pix[bb][pix] > 0.) {
10514  binmean_Lt[view][sb][bin_ypix - 1][bin_xpix - 1] = binmean_Lt[view][sb][bin_ypix - 1][bin_xpix - 1] + Lt_pix[bb][pix];
10515  bincount[view][sb][bin_ypix - 1][bin_xpix - 1] += 1;
10516  }
10517  bb++;
10518  sb++;
10519  }//end while blue band band
10520 
10521  //RED---
10522  while (sb <num_blue_bands+num_red_bands) {
10523  if (Lt_pix2[rb][pix] > 0.) {
10524  binmean_Lt[view][sb][bin_ypix - 1][bin_xpix - 1] = binmean_Lt[view][sb][bin_ypix - 1][bin_xpix - 1] + Lt_pix2[rb][pix];
10525  bincount[view][sb][bin_ypix - 1][bin_xpix - 1] += 1;
10526  }
10527  rb++;
10528  sb++;
10529  }//end red bands
10530 
10531  //SWIR----
10532  while (sb <num_blue_bands + num_red_bands + num_SWIR_bands) {
10533  if (Lt_pix3[swb][pix] > 0.) {
10534  binmean_Lt[view][sb][bin_ypix - 1][bin_xpix - 1] = binmean_Lt[view][sb][bin_ypix - 1][bin_xpix - 1] + Lt_pix3[swb][pix];
10535  bincount[view][sb][bin_ypix - 1][bin_xpix - 1] += 1;
10536  }
10537  swb++;
10538  sb++;
10539  }//end swir bands
10540  }
10541 
10542  }//end if inpix==1
10543 
10544 
10545 
10546  //********** pixel AREA WEIGHTING ************************
10547  if (flag_inpix == 0) outpix++;
10548 
10549  totpix++;
10550 
10551  }//end pixels loop
10552 
10553 
10554  //END OF FILE--****** reset starting sline index if last line processed and within k box
10555  //go for another granule if it is not the last one---------------
10556  if (sline == num_scans - 1) {
10557  flag_donefile = 1;
10558  cout << "end of file..." << l1cfile->selgran[findex] << endl;
10559  last_sline = 0;
10560  if (findex >= sfiles - 1) {
10561  cout << "done with last granule of the input list........................." << endl;
10562  // findex=sfiles;
10563  k = ngroups;
10564  break;
10565  }
10566 
10567  }//end of file/last file? sliine=num_scans-1
10568  else flag_donefile = 0;
10569 
10570  }//end latpix nadir of line x inside grid group?
10571 
10572  //***** skip lines and files if sline is not within k group ********
10573  //increase k and screen files and lines again starting from the last binning
10574 
10575  if (latpix[nadpix] > lat_gd[n_gdlines - 1][257] && k < ngroups - 1) { //else limits
10576  if(format.type==FT_SPEXONE){
10577  cout << "moving to the next k group...scanning again files/slines.." << endl;
10578  cout << "group #.."<<k+1<<"file index.." << findex << "sline index.." << sline << endl;
10579  last_file = findex;
10580  last_sline = sline;
10581  findex = sfiles;
10582  sline = num_scans - 1;
10583  }
10584  else{ //OCIS
10585  cout << "moving to the next k group...scanning again files/slines.." << endl;
10586  cout << "file index.." << findex << "last sline index.." << sline << endl;
10587  last_file = findex;
10588  last_sline = sline;
10589  findex = sfiles;
10590  sline = num_scans - 1;
10591  }
10592  }//end if lat >grid lat--IF outside the box
10593 
10594  if (sline + 1 % 100 == 0) cout << "for k group.." << k + 1 << "selected granule #.." << l1cfile->selgran[findex] << "sline..." << sline + 1 << "# of binned pix.." << inpix << "totpix.." << totpix << "outpix.." << outpix << endl;
10595  }//end for scanlines
10596 
10597  cout << "closing L1B file......." << ptstr << endl;
10598  status = nc_close(ncid_L1B);
10599  check_err(status, __LINE__, __FILE__);
10600 
10601  if (latpix != nullptr)
10602  delete[](latpix);
10603  if (lonpix != nullptr)
10604  delete[](lonpix);
10605  if (Lt_pix != nullptr)
10606  delete[](Lt_pix);
10607  if (Lt_pix2 != nullptr)
10608  delete[](Lt_pix2);
10609  if (Lt_pix3 != nullptr)
10610  delete[](Lt_pix3);
10611  if (senazpix != nullptr)
10612  delete [](senazpix);
10613 
10614  if(latframe1!=nullptr)
10615  delete [](latframe1);
10616  if(latframe2!=nullptr)
10617  delete [](latframe2);
10618  if(latframe3!=nullptr)
10619  delete [](latframe3);
10620  if(lonframe1!=nullptr)
10621  delete [](lonframe1);
10622  if(lonframe2!=nullptr)
10623  delete [](lonframe2);
10624  if(lonframe3!=nullptr)
10625  delete [](lonframe3);
10626  if (Lt_pix4 != nullptr)
10627  delete[](Lt_pix4);
10628 
10629  //**********************************************************************************************************************************
10630  //**********************************************************************************************************************************
10631  //writing each granule ---------------------------------
10632  //*****************************************************************************
10633 
10634  if (flag_donefile == 1 | (flag_donefile == 0 && k == ngroups - 1)) {
10635  cout << "writing file #....................................................................................................................." << l1cfile->selgran[findex] << "based on group #.." << k + 1 << endl;
10636 
10637  // exit(1);
10638 
10639  //write mean Lt as nc file---
10640  //**********************************************************************
10641  //**********************************************************************8
10642  //create Lt file
10643  pathstr = "out/";
10644  senstr = "OCIS_";
10645  monstr = std::to_string(selmon);
10646  daystr = std::to_string(selday);
10647  yearstr = std::to_string(selyear);
10648  prodstr = "binLt_sbs";
10649  swtstr = "_swt";
10650  granstr = "";
10651  granstr = "_" + std::to_string(l1cfile->selgran[findex]);
10652 
10653  if (l1cfile->l1c_pflag >= 3) {
10654  swtd = l1cfile->swtnum;
10655  swtnum = std::to_string(swtd);
10656  cout << "swtnum.." << swtnum << endl;
10657  }
10658  else swtnum = std::to_string(swtd);
10659 
10660  extstr = ".nc";
10661  string GATT_NAME1,GATT_VAL1,GATT_NAME2,GATT_VAL2;
10662 
10663  if(format.type==FT_SPEXONE){
10664  senstr = "SPEXONE";
10665  GATT_NAME1="Title",GATT_VAL1="PACE SPEXone Level-1C Data",GATT_NAME2="instrument",GATT_VAL2="SPEXone";
10666  ibin_ini=279;//initial index gridlines
10667  ibin_end=319;//initial index gridlines
10668  }
10669  if(format.type==FT_HARP){
10670  senstr = "HARP2";
10671  GATT_NAME1="Title",GATT_VAL1="PACE HARP Level-1C Data",GATT_NAME2="instrument",GATT_VAL2="HARP";
10672  ibin_ini=0;//initial index gridlines
10673  ibin_end=599;//initial index gridlines
10674  }
10675  else//OCIS
10676  {
10677  senstr = "OCI";
10678  GATT_NAME1="Title",GATT_VAL1="PACE OCI Level-1C Data",GATT_NAME2="instrument",GATT_VAL2="OCI";
10679  ibin_ini=92;//initial index gridlines
10680  ibin_end=506;//initial index gridlines
10681  }
10682 
10683 
10684 
10685  fname_out = pathstr + missionstr + "_" + senstr + "." + yearstr + monstr + daystr + timestr + prodstr+granstr+extstr;
10686 
10687  string ATT_NAME="Units", ATT_VAL="degrees",GATT_NAME3="processing_version",GATT_VAL3="V1.0",GATT_NAME4="Conventions",GATT_VAL4="CF-1.6";
10688  string GATT_NAME5="institution",GATT_VAL5="NASA Goddard Space Flight Center, Ocean Biology Processing Group",GATT_NAME6="license",GATT_VAL6="http://science.nasa.gov/earth-science/earth-science-data/data-information-policy/";
10689  string GATT_NAME7="naming_authority",GATT_VAL7="gov.nasa.gsfc.sci.oceancolor",GATT_NAME8="keywords_vocabulary",GATT_VAL8="NASA Global Change Master Directory (GCMD) Science Keywords";
10690  string GATT_NAME9="stdname_vocabulary",GATT_VAL9="NetCDF Climate and Forecast (CF) Metadata Convention",GATT_NAME10="creator_name",GATT_VAL10="NASA/GSFC",GATT_NAME11="creator_email",GATT_VAL11="data@oceancolor.gsfc.nasa.gov";
10691  string GATT_NAME12="creator_url",GATT_VAL12="http://oceancolor.gsfc.nasa.gov",GATT_NAME13="project",GATT_VAL13="PACE Project",GATT_NAME14="publisher_name",GATT_VAL14="NASA/GSFC";
10692  string GATT_NAME15="publisher_email",GATT_VAL15="data@oceancolor.gsfc.nasa.gov",GATT_NAME16="publisher_url",GATT_VAL16="http://oceancolor.gsfc.nasa.gov",GATT_NAME17="processing_level",GATT_VAL17="L1C";
10693  string GATT_NAME18="cdm_data_type",GATT_VAL18="swath",GATT_NAME19="orbit_number",GATT_VAL19="12345",GATT_NAME20="history",GATT_VAL20="",GATT_NAME21="CDL_version_date",GATT_VAL21="2021-09-10",GATT_NAME22="product_name",GATT_VAL22=fname_out;
10694  string GATT_NAME23="startDirection",GATT_VAL23="Ascending",GATT_NAME24="endDirection",GATT_VAL24="Ascending",GATT_NAME25="time_coverage_start",GATT_VAL25=yearstr+"-"+monstr+"-"+daystr+"-"+timestr,GATT_NAME26="time_coverage_end",GATT_VAL26=yearstr+"-"+monstr+"-"+daystr+"-"+timestr,GATT_NAME27="date{_created",GATT_VAL27="2021-09-10T15:12:41Z",GATT_NAME28="sun_earth_distance",GATT_VAL28="0.990849042172323",GATT_NAME29="terrain_data_source",GATT_VAL29="",GATT_NAME30="spectral_response_function",GATT_VAL30="",GATT_NAME31="systematic_uncertainty_model",GATT_VAL31="",GATT_NAME32="nadir_bin",GATT_VAL32="12345",GATT_NAME33="bin_size_at_nadir",GATT_VAL33="5.2km2";
10695 
10696  l1cfile->gridname = fname_out.c_str();
10697  filename_lt = fname_out.c_str();
10698 
10699  if ((status = nc_create(filename_lt, NC_CLOBBER | NC_NETCDF4, &ncid_out)))
10700  check_err(status, __LINE__, __FILE__);
10701  //define dims
10702  // Define the dimensions,vars and attributes at the root level
10703  NDIMS=2;
10704  NDIMS2=3;
10705  NDIMS3=4;
10706  NY = num_gridlines;
10707 
10708 
10709  if(format.type==FT_SPEXONE){
10710  NX = 40;
10711  }
10712  else if(format.type==FT_HARP){
10713  NX = 600;
10714  }
10715  else{//legacy such OCI
10716  NX=514;
10717  }
10718 
10719  //NVIEWS= 2;//for OCI
10720  // NBANDS=249;//for OCI
10721 
10722  NY1 = l1cfile->NY1;//these are indexes not line #!!!!!!!!!!!!!!!!!
10723  NY2 = l1cfile->NY2;
10724  cout << "rowgrid ini.." << NY1 << "rowgrid end.." << NY2 << endl;
10725  NY = NY2 - NY1 + 1;
10726  cout << "NY.." << NY << "NX.." << NX << "NY1.."<<NY1<<"NY2.."<<NY2<<endl;
10727 
10728  //DEF DIMENSIONS
10729  if ((status = nc_def_dim(ncid_out, "bins_across_track", NX, &x_dimid)))
10730  check_err(status, __LINE__, __FILE__);
10731  if ((status = nc_def_dim(ncid_out, "bins_along_track", NY, &y_dimid)))
10732  check_err(status, __LINE__, __FILE__);
10733  //dims for output var
10734  dimids[0] = y_dimid;
10735  dimids[1] = x_dimid;
10736 
10737  if ((status = nc_def_dim(ncid_out, "number_of_views", NVIEWS, &v_dimid)))
10738  check_err(status, __LINE__, __FILE__);
10739  if ((status = nc_def_dim(ncid_out, "intensity_bands_per_view", NBANDS, &b_dimid)))
10740  check_err(status, __LINE__, __FILE__);
10741 
10742  dimids2[0] = y_dimid;
10743  dimids2[1] = x_dimid;
10744  dimids2[2] = v_dimid;//#o
10745 
10746  dimids3[0] = y_dimid;
10747  dimids3[1] = x_dimid;
10748  dimids3[2] = v_dimid;//
10749  dimids3[3] = b_dimid;
10750 
10751  /* try
10752  {
10753  cout<<"Opening file \"firstFile.nc\" with NcFile::replace"<<endl;
10754  NcFile ncFile("firstFile.nc",NcFile::replace);
10755  NcGroup groupA(ncFile.addGroup("groupA"));
10756  }
10757 
10758  catch (NcException& e)
10759  {
10760  cout << "unknown error"<<endl;
10761  e.what();
10762  }
10763  exit(1);
10764  */
10765  //define attributes
10766  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME1.c_str(), strlen(GATT_VAL1.c_str()),
10767  GATT_VAL1.c_str()))
10768  check_err(status, __LINE__, __FILE__);
10769  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME2.c_str(), strlen(GATT_VAL2.c_str()),
10770  GATT_VAL2.c_str()))
10771  check_err(status, __LINE__, __FILE__);
10772  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME3.c_str(), strlen(GATT_VAL3.c_str()),
10773  GATT_VAL3.c_str()))
10774  check_err(status, __LINE__, __FILE__);
10775  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME4.c_str(), strlen(GATT_VAL4.c_str()),
10776  GATT_VAL4.c_str()))
10777  check_err(status, __LINE__, __FILE__);
10778  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME5.c_str(), strlen(GATT_VAL5.c_str()),
10779  GATT_VAL5.c_str()))
10780  check_err(status, __LINE__, __FILE__);
10781  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME6.c_str(), strlen(GATT_VAL6.c_str()),
10782  GATT_VAL6.c_str()))
10783  check_err(status, __LINE__, __FILE__);
10784  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME7.c_str(), strlen(GATT_VAL7.c_str()),
10785  GATT_VAL7.c_str()))
10786  check_err(status, __LINE__, __FILE__);
10787  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME8.c_str(), strlen(GATT_VAL8.c_str()),
10788  GATT_VAL8.c_str()))
10789  check_err(status, __LINE__, __FILE__);
10790  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME9.c_str(), strlen(GATT_VAL9.c_str()),
10791  GATT_VAL9.c_str()))
10792  check_err(status, __LINE__, __FILE__);
10793  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME10.c_str(), strlen(GATT_VAL10.c_str()),
10794  GATT_VAL10.c_str()))
10795  check_err(status, __LINE__, __FILE__);
10796  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME11.c_str(), strlen(GATT_VAL11.c_str()),
10797  GATT_VAL11.c_str()))
10798  check_err(status, __LINE__, __FILE__);
10799  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME12.c_str(), strlen(GATT_VAL12.c_str()),
10800  GATT_VAL12.c_str()))
10801  check_err(status, __LINE__, __FILE__);
10802  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME13.c_str(), strlen(GATT_VAL13.c_str()),
10803  GATT_VAL13.c_str()))
10804  check_err(status, __LINE__, __FILE__);
10805  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME14.c_str(), strlen(GATT_VAL14.c_str()),
10806  GATT_VAL14.c_str()))
10807  check_err(status, __LINE__, __FILE__);
10808  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME15.c_str(), strlen(GATT_VAL15.c_str()),
10809  GATT_VAL15.c_str()))
10810  check_err(status, __LINE__, __FILE__);
10811  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME16.c_str(), strlen(GATT_VAL16.c_str()),
10812  GATT_VAL16.c_str()))
10813  check_err(status, __LINE__, __FILE__);
10814  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME17.c_str(), strlen(GATT_VAL17.c_str()),
10815  GATT_VAL17.c_str()))
10816  check_err(status, __LINE__, __FILE__);
10817  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME18.c_str(), strlen(GATT_VAL18.c_str()),
10818  GATT_VAL18.c_str()))
10819  check_err(status, __LINE__, __FILE__);
10820  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME19.c_str(), strlen(GATT_VAL19.c_str()),
10821  GATT_VAL19.c_str()))
10822  check_err(status, __LINE__, __FILE__);
10823  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME20.c_str(), strlen(GATT_VAL20.c_str()),
10824  GATT_VAL20.c_str()))
10825  check_err(status, __LINE__, __FILE__);
10826  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME21.c_str(), strlen(GATT_VAL21.c_str()),
10827  GATT_VAL21.c_str()))
10828  check_err(status, __LINE__, __FILE__);
10829  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME22.c_str(), strlen(GATT_VAL22.c_str()),
10830  GATT_VAL22.c_str()))
10831  check_err(status, __LINE__, __FILE__);
10832  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME23.c_str(), strlen(GATT_VAL23.c_str()),
10833  GATT_VAL23.c_str()))
10834  check_err(status, __LINE__, __FILE__);
10835  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME24.c_str(), strlen(GATT_VAL24.c_str()),
10836  GATT_VAL24.c_str()))
10837  check_err(status, __LINE__, __FILE__);
10838  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME25.c_str(), strlen(GATT_VAL25.c_str()),
10839  GATT_VAL25.c_str()))
10840  check_err(status, __LINE__, __FILE__);
10841  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME26.c_str(), strlen(GATT_VAL26.c_str()),
10842  GATT_VAL26.c_str()))
10843  check_err(status, __LINE__, __FILE__);
10844  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME27.c_str(), strlen(GATT_VAL27.c_str()),
10845  GATT_VAL27.c_str()))
10846  check_err(status, __LINE__, __FILE__);
10847  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME28.c_str(), strlen(GATT_VAL28.c_str()),
10848  GATT_VAL28.c_str()))
10849  check_err(status, __LINE__, __FILE__);
10850  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME29.c_str(), strlen(GATT_VAL29.c_str()),
10851  GATT_VAL29.c_str()))
10852  check_err(status, __LINE__, __FILE__);
10853  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME30.c_str(), strlen(GATT_VAL30.c_str()),
10854  GATT_VAL30.c_str()))
10855  check_err(status, __LINE__, __FILE__);
10856  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME31.c_str(), strlen(GATT_VAL31.c_str()),
10857  GATT_VAL31.c_str()))
10858  check_err(status, __LINE__, __FILE__);
10859  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME32.c_str(), strlen(GATT_VAL32.c_str()),
10860  GATT_VAL32.c_str()))
10861  check_err(status, __LINE__, __FILE__);
10862  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME33.c_str(), strlen(GATT_VAL33.c_str()),
10863  GATT_VAL33.c_str()))
10864  check_err(status, __LINE__, __FILE__);
10865 
10866  //define groups check_err(status, __LINE__, __FILE__);
10867  if ((status = nc_def_grp(ncid_out, "geolocation_data", &grp_coor))) //netcdf-4
10868  check_err(status, __LINE__, __FILE__);
10869  //def var grp1
10870  if ((status = nc_def_var(grp_coor, "latitude", NC_FLOAT, NDIMS,
10871  dimids, &varid1)))
10872  check_err(status, __LINE__, __FILE__);
10873  if ((status = nc_def_var(grp_coor, "longitude", NC_FLOAT, NDIMS,
10874  dimids, &varid2)))
10875  check_err(status, __LINE__, __FILE__);
10876 
10877  //leave define mode-----------------------
10878  if ((status = nc_enddef(grp_coor))) //done def vars etc
10879  check_err(status, __LINE__, __FILE__);
10880 
10881 
10882  if ((status = nc_def_grp(ncid_out, "observation_data", &grp_obs))) //netcdf-4
10883  check_err(status, __LINE__, __FILE__);
10884 
10885  //def var grp2
10886  //counts and Lt
10887  if ((status = nc_def_var(grp_obs, "obs_per_view", NC_INT, NDIMS2,
10888  dimids2, &varid_count)))
10889  check_err(status, __LINE__, __FILE__);
10890  if ((status = nc_def_var(grp_obs, "I", NC_FLOAT, NDIMS3,
10891  dimids3, &varid_lt)))
10892  check_err(status, __LINE__, __FILE__);
10893 
10894  //leave define mode-----------------------
10895  if ((status = nc_enddef(grp_obs))) //done def vars etc
10896  check_err(status, __LINE__, __FILE__);
10897 
10898 
10899  lat_out = allocate2d_float(NY, NX);
10900  lon_out = allocate2d_float(NY, NX);
10901 
10902  int c = 0;
10903 
10904  for (int i = NY1; i < NY2 + 1; i++) {
10905  // for (int j = 0; j < NX; j++) {
10906  for (int j = ibin_ini; j < ibin_end; j++) {
10907  lat_out[NY - 1 - c][NX - 1 - j] = lat_gd[i][j];
10908  lon_out[NY - 1 - c][j] = lon_gd[i][j];
10909  }
10910  c++;
10911  }
10912 
10913 
10914  if ((status = nc_put_var_float(grp_coor, varid1, &lat_out[0][0])))
10915  check_err(status, __LINE__, __FILE__);
10916 
10917  if ((status = nc_put_var_float(grp_coor, varid2, &lon_out[0][0])))
10918  check_err(status, __LINE__, __FILE__);
10919 
10920 
10921  //alloc mem for output variables obs_per_view and I as part of the observation_data group
10922  data_out = allocate3d_int(NY, NX,NVIEWS);
10923  data_out2 = allocate4d_float(NY, NX,NVIEWS,NBANDS);
10924 
10925  //BINCOUNT ARRAY
10926  for (size_t v = 0; v < NVIEWS; v++) {
10927  for (int i = NY1; i < NY2 + 1; i++) {
10928  for (int j = ibin_ini; j < ibin_end; j++) {
10929  // for (int j = 0; j < NX; j++) {
10930  data_out[i][j][v]=0;
10931  }}}
10932 
10933 
10934 
10935  c = 0;
10936 
10937  for (size_t v = 0; v < NVIEWS; v++) {
10938  for (int i = NY1; i < NY2 + 1; i++) {
10939  for (int j = ibin_ini; j < ibin_end; j++) {
10940 // for (int j = 0; j < NX; j++) {
10941  for (sb = 0;sb < nbands;sb++) {
10942  if(bincount[v][sb][i][j]>0)
10943  data_out[NY - 1 - c][NX - 1 - j][v]+=bincount[v][sb][i][j];
10944  else
10945  data_out[NY - 1 - c][NX - 1 - j][v]+=0;
10946  }
10947  }
10948  c++;
10949  }
10950  c=0;
10951  }
10952 
10953 
10954 
10955  cout << "writing countbin for all band ."<< endl;
10956  if ((status = nc_put_var_int(grp_obs, varid_count, &data_out[0][0][0])))
10957  check_err(status, __LINE__, __FILE__);
10958 
10959  // LT ARRAYS
10960  c=0;
10961  for (size_t b = 0;b <NBANDS;b++) {
10962  for (size_t v = 0; v < NVIEWS; v++) {
10963  for (int i = NY1; i < NY2 + 1; i++) {
10964  for (int j = ibin_ini; j < ibin_end; j++) {
10965 // for (int j = 0; j < NX; j++) {
10966  if (bincount[v][b][i][j] > 0)
10967  data_out2[NY - 1 - c][NX - 1 - j][v][b] = binmean_Lt[v][b][i][j] / bincount[v][b][i][j];
10968  else data_out2[NY - 1 - c][NX - 1 - j][v][b] = NAN;
10969  }
10970  c++;
10971  }
10972  c=0;
10973  }//end views
10974  }//end for bands
10975 
10976 
10977 
10978  cout << "writing Lt for all bands.."<< endl;
10979  if ((status = nc_put_var_float(grp_obs, varid_lt, &data_out2[0][0][0][0])))
10980  check_err(status, __LINE__, __FILE__);
10981 
10982 
10983  delete [] (data_out);
10984  delete [] (data_out2);
10985 
10986  delete[](lat_out);
10987  delete[](lon_out);
10988 
10989  delete[](bincount);
10990  delete[](binmean_Lt);
10991 
10992  if ((status = nc_close(ncid_out)))
10993  check_err(status, __LINE__, __FILE__);
10994 
10995  lat_out = nullptr;;
10996  lon_out = nullptr;
10997  data_out = nullptr;
10998  data_out2 = nullptr;
10999  bincount = nullptr;
11000  binmean_Lt = nullptr;
11001 
11002  flag_donefile = 0;
11003  }//end writing file
11004  }//end for files loop
11005 
11006  cout << "group k at the end of big loop" << k + 1 << endl;
11007 
11008 
11009  }//groups
11010 
11011  cout << "number of files per swath.." << nfiles_swt[swtd - 1] << "for swath.." << swtd << endl;
11012  cout << "total inpix.." << inpix << "total pix.." << totpix << endl;
11013  // cout<<"binned pixels.."<<inpix<<"as %.."<<(inpix/(num_pixels*num_scans*n_files*nfiles_swt[swtd-1]))*100<<endl;
11014  delete[](lat_asort);
11015  // delete [] (lon_asort);
11016  delete[](index_xy);
11017  // delete [] (index_xy2);
11018  delete[](dlatb_g);
11019  delete[](dlonb_g);
11020 
11021  delete[](lat_gd);
11022  delete[](lon_gd);
11023  delete[](az_east);
11024 
11025  printf("*** SUCCESS writing bincount and binLt rasters as nc..!\n");
11026  cout << "finish processing swath eq crossing day..." << swtd << endl;
11027  cout << "done writing Lt to nc file.." << endl;
11028 
11029  return(0);
11030  }
11031 
11032 
11033 
11034  //similar to version 6 but including HARP
11035  int32_t L1C::binL1C_wgranule6(int swtd, l1c_filehandle* l1cfile, L1C_input* l1cinput, int16_t* swtd_id, int16_t* odir, int16_t* file_id, int16_t* nfiles_swt) {
11036  size_t ybins,xbins;
11037  int32_t gdlines_group, ngroups = 0, num_gridlines,nbinx2, nbinx, inpix = 0, outpix = 0, totpix = 0, n_gdlines;//number of gridlines to be processed
11038  float minv = 0., maxv = 0., ** dlatb_g, ** dlonb_g;
11039  int16_t fi = 0;
11040  std::string str;
11041  const char* ptstr;
11042  int dimid, dimid2,dimid3,status, ncid_out,ncid_az,ncid_grid,b_dimid,v_dimid,x_dimid,y_dimid,varid1,varid2,varid_count,varid_lt,azId,NDIMS,NDIMS2,NDIMS3,senazId;
11043  size_t start[] = { 0, 0 };
11044  size_t count[] = { 1, 1 };
11045  size_t start2[] = { 0, 0, 0 };
11046  size_t count2[] = { 1, 1, 1 }, count3[] = { 1, 1, 1 }, count4[] = { 1, 1, 1 };
11047  int32_t bin_xpix, bin_ypix;
11048  float* latpix=nullptr, * lonpix=nullptr, ** Lt_pix=nullptr, ** Lt_pix2=nullptr, ** Lt_pix3=nullptr,mean_az_east,*senazpix=nullptr;
11049 
11050  float latmin_swt = 100, latmax_swt = 0, lonmin_swt = 0, lonmax_swt = 0;
11051  int dimids[2],dimids2[3],dimids3[4];
11052  const char* filename_lt;
11053  int32_t NY = -1, NX = -1, NY1 = -1, NY2 = -1,c1 = 1;
11054  float****data_out2=nullptr,** lat_out, ** lon_out;
11055  int ***data_out=nullptr;
11056  int last_file, last_sline, flag_inpix, flag_donefile;;//first index file id, second index line #
11057  short** index_xy;
11058  float** lat_asort;
11059  bool boolbin1;
11060  char* ifile_char;
11061  std::string ifile_str;
11062 
11063  int16_t selyear = -1, selmon = -1, selday = -1;
11064  float** lat_gd, ** lon_gd, * az_east;
11065  string gridname, azeast_name;
11066  float**** binmean_Lt = nullptr;
11067  int ****bincount=nullptr;
11068  double gres = (l1cinput->gres) * 1000, dlamin, dlamax, dlomin, dlomax;
11069  int grp_obs,grp_coor,geoGrp,obsGrp;
11070  size_t sb=0,bb = 0, rb = 0, swb = 0,ib=0, NVIEWS=-1,NBANDS=-1,NBANDS_POL=-1;
11071  int view;
11072  float sum=0,tot=0;
11073  char tmp[256];
11074  short gd_row, gd_col;
11075 
11076 
11077  Geodesic geod(Constants::WGS84_a(), Constants::WGS84_f());
11078 
11079  //random seed
11080  srand((unsigned int)time(NULL));
11081  //nadir pixel ofr OCI
11082  int nadpix = l1cfile->nadpix;
11083 
11084 
11085  num_gridlines = 4000;
11086  nbinx2 = l1cfile->nbinx;
11087  num_pixels = l1cfile->npix;
11088 
11089  size_t sfiles = 0;
11090 
11091  if (l1cfile->selgran[0] < 0)//process all granules
11092  {
11093  sfiles = nfiles_swt[swtd - 1];
11094  for (unsigned int j = 0;j < sfiles;j++) l1cfile->selgran[j] = j + 1;
11095  }
11096  else {
11097  while (l1cfile->selgran[sfiles] > 0) {
11098  cout << "selected granule #..........................." << l1cfile->selgran[sfiles] << endl;
11099  sfiles++;
11100  }
11101  }
11102 
11103  cout<<"binning Lt using sbs2 method and composite indexes for arrays..................................................................."<<endl;
11104 
11105 
11106  //allocate mem for lat/lon/azeast pointers---
11107  selday = l1cinput->selday;
11108  selmon = l1cinput->selmon;
11109  selyear = l1cinput->selyear;
11110 
11111  std::string fname_out, pathstr, senstr, monstr, daystr, yearstr, prodstr, gdstr, swtstr, swtnum, extstr, granstr,timestr,azstr,missionstr;
11112 
11113  pathstr = "out/";
11114  missionstr="PACE";
11115  senstr = "OCIS";
11116  monstr = std::to_string(selmon);
11117  daystr = std::to_string(selday);
11118  yearstr = std::to_string(selyear);
11119  timestr="T00:00:00Z";
11120  prodstr = "L1Cgrid";
11121  swtstr = "_swt";
11122  extstr = ".nc";
11123 
11124  if (l1cfile->l1c_pflag >= 3) {
11125  swtd = l1cfile->swtnum;
11126  swtnum = std::to_string(swtd);
11127  cout << "swtnum.." << swtnum << endl;
11128  }
11129  else swtnum = std::to_string(swtd);
11130 
11131 
11132  getcwd(tmp, 256);
11133  pathstr=tmp;
11134 
11135 //open lat/lon L1C grid --------------------------------------
11136  //PACE_OCIS.2019321T00:00:00ZL1Cgrid.nc
11137  prodstr = "L1Cgrid";
11138  gridname = pathstr + "/out/"+missionstr + "_" + senstr + "." + yearstr + monstr + daystr + timestr + prodstr+extstr;
11139 
11140  //open file
11141  ifile_str = l1cinput->files[0];
11142  ifile_char = &ifile_str[0];
11143  file_format format = getFormat(ifile_char);
11144 
11145  if(format.type==FT_SPEXONE){
11146  senstr = "SPEXONE";
11147  ptstr="/accounts/mamontes/images/OCIS/sean/out/PACE_OCIS.2019321T00:00:00ZL1Cgrid.nc";
11148  }
11149  else{
11150  ptstr = gridname.c_str();
11151  }
11152 
11153  status = nc_open(ptstr, NC_NOWRITE, &ncid_grid);
11154  if (status != NC_NOERR) {
11155  fprintf(stderr, "nc_open error.\n");
11156  exit(EXIT_FAILURE);
11157  }
11158  //groups
11159  if(format.type==FT_SPEXONE){
11160  // status = nc_inq_grp_ncid(ncid_grid, "GEOLOCATION_DATA", &geoGrp);
11161  // check_err(status, __LINE__, __FILE__);
11162  status = nc_inq_grp_ncid(ncid_grid, "geolocation_data", &geoGrp);//using OCIS L1C grid file..
11163  check_err(status, __LINE__, __FILE__);
11164  }
11165  else{
11166  status = nc_inq_grp_ncid(ncid_grid, "geolocation_data", &geoGrp);
11167  check_err(status, __LINE__, __FILE__);
11168  }
11169 
11170  status = nc_inq_dimid(ncid_grid, "bins_along_track", &y_dimid);
11171  check_err(status, __LINE__, __FILE__);
11172  nc_inq_dimlen(ncid_grid, y_dimid, &ybins);
11173  status = nc_inq_dimid(ncid_grid, "bins_across_track", &x_dimid);
11174  check_err(status, __LINE__, __FILE__);
11175 
11176  nc_inq_dimlen(ncid_grid, x_dimid, &xbins);
11177  nc_inq_dimlen(ncid_grid, y_dimid, &ybins);
11178 
11179  //************************************************************
11180  //mem allocation for geolocation pointers---
11181  num_gridlines=ybins;
11182  nbinx=xbins;
11183 
11184  cout<<"num_gridlines"<<num_gridlines<<"nbinx"<<nbinx<<endl;
11185  az_east = (float*)calloc(num_gridlines , sizeof(float));
11186  lat_gd = allocate2d_float(num_gridlines, nbinx);
11187  lon_gd = allocate2d_float(num_gridlines, nbinx);
11188 
11189  status = nc_inq_varid(geoGrp, "latitude", &latId);//scans x velements
11190  check_err(status, __LINE__, __FILE__);
11191  status = nc_inq_varid(geoGrp, "longitude", &lonId);//scans x velements
11192  check_err(status, __LINE__, __FILE__);
11193  status = nc_get_var_float(geoGrp, latId, &lat_gd[0][0]);
11194  check_err(status, __LINE__, __FILE__);
11195  status = nc_get_var_float(geoGrp, lonId, &lon_gd[0][0]);
11196  check_err(status, __LINE__, __FILE__);
11197 //close file
11198  if ((status = nc_close(ncid_grid)))
11199  check_err(status, __LINE__, __FILE__);
11200 
11201 
11202  //open az_east ------
11203  //PACE_OCIS.2019321T00:00:00Zaz_east.nc
11204  prodstr = "az_east";
11205 // cout << "Current working directory: " << tmp << endl;
11206  azstr= pathstr + "/out/"+missionstr + "_" + senstr + "." + yearstr + monstr + daystr + timestr + prodstr+extstr;
11207 
11208  if(format.type==FT_SPEXONE){
11209  ptstr="/accounts/mamontes/images/OCIS/sean/out/PACE_OCIS.2019321T00:00:00Zaz_east.nc";
11210  }
11211  else{
11212  ptstr = azstr.c_str();
11213  }
11214  cout <<"Opening file with azimuth east values in degrees............" << ptstr << endl;
11215  // ptstr="/accounts/mamontes/images/OCIS/sean/out/PACE_OCIS.2019321T00:00:00Zaz_east.nc";
11216 
11217  status = nc_open(ptstr, NC_NOWRITE, &ncid_az);
11218  if (status != NC_NOERR) {
11219  fprintf(stderr, "nc_open error.\n");
11220  exit(EXIT_FAILURE);
11221  }
11222  status = nc_inq_dimid(ncid_az, "bins_along_track", &y_dimid);
11223  check_err(status, __LINE__, __FILE__);
11224  nc_inq_dimlen(ncid_az, y_dimid, &ybins);
11225 
11226  status = nc_inq_varid(ncid_az, "az_east", &azId);//scans x velements
11227  check_err(status, __LINE__, __FILE__);
11228  status = nc_get_var_float(ncid_az, azId, &az_east[0]);
11229  check_err(status, __LINE__, __FILE__);
11230 
11231  for(size_t i=0;i<ybins;i++){
11232  sum = az_east[i];
11233  tot += sum;
11234  }
11235 //close file
11236  if ((status = nc_close(ncid_az)))
11237  check_err(status, __LINE__, __FILE__);
11238 
11239  //using swath-averaged az_east for nadir pixels rather than along-track az_east pixel-by-pixel
11240  mean_az_east = tot / (ybins);
11241 
11242  l1cfile->mean_az_east=mean_az_east; //in degrees
11243  cout<<"mean_az_east in degrees...."<<mean_az_east<<endl;
11244 
11245 
11246 
11247  //determine # of gd groups to be processede
11248  //gdlines_group=num_gridlines;//ONE BIG GROUP
11249  gdlines_group = 250;
11250 
11251  if (num_gridlines <= gdlines_group) {
11252  gdlines_group = num_gridlines;
11253  cout << "WARNING********************* number_gridlines<=gdlines_group THEN gdlines_group=num_gridlines **************" << endl;
11254  }
11255 
11256  ngroups = floor(num_gridlines / gdlines_group);
11257  cout << "TOTAL # of gd groups.(ALL LATs...." << ngroups << endl;
11258 
11259  //--NORMALIZED gridline longitude is -180 to 180 degrees before comparison with longitude extracted from image pixels---
11260  for (int i = 0; i < num_gridlines; i++) {
11261  for (int j = 0; j < nbinx; j++) {
11262  if (lon_gd[i][j] < -180.)lon_gd[i][j] += 360.;
11263  if (lon_gd[i][j] > 180.)lon_gd[i][j] -= 360.;
11264  }
11265  }
11266  //get min/max lat/lon of the swath
11267  // Assume first element as maximum and minimum
11268  maxv = lat_gd[0][0];
11269  minv = lat_gd[0][0];
11270 
11271  //Find maximum and minimum in all array elements.
11272  for (int i = 0; i < num_gridlines; i++) {
11273  for (int j = 0; j < nbinx; j++) {
11274  if (lat_gd[i][j] > maxv)
11275  maxv = lat_gd[i][j];
11276  if (lat_gd[i][j] < minv)
11277  minv = lat_gd[i][j];
11278  }
11279  }
11280 
11281 
11282  maxv = lon_gd[0][0];
11283  minv = lon_gd[0][0];
11284  //Find maximum and minimum in all array elements.
11285  for (int i = 0; i < num_gridlines; i++) {
11286  for (int j = 0; j < nbinx; j++) {
11287  if (lon_gd[i][j] > maxv)
11288  maxv = lon_gd[i][j];
11289  if (lon_gd[i][j] < minv)
11290  minv = lon_gd[i][j];
11291  }
11292  }
11293 
11294 
11295 
11296  cout << "swath #.." << swtd << endl;
11297 
11298  //check lat bound min/max of each gd group---
11299  int k = 0, i = 0;
11300 
11301  dlatb_g = allocate2d_float(ngroups + 1, 2);
11302  dlonb_g = allocate2d_float(ngroups + 1, 2);
11303 
11304  //recompute number of gridlines based on lat limits -80 to 80 degrees
11305  //asc orbit goes from negative to positive latitude....
11306  NY = num_gridlines;
11307  NX = nbinx;
11308  for (int i = 0; i < NY; i++) {
11309  for (int j = 0; j < NX; j++) {
11310  if (lat_gd[i][j] >= -80.) c1++;
11311  if (c1 == nbinx) {
11312  NY1 = i;
11313  }
11314  }
11315  if (NY1 >= 0) break;
11316  c1 = 1;
11317  }
11318 
11319 
11320  for (int i = 0;i < NY; i++) {
11321  // cout<<"i.."<<i<<"lat_gd[i][j]..."<<lat_gd[i][nadpix]<<endl;
11322  for (int j = 0; j < NX; j++) {
11323  if (lat_gd[i][j] >= 80.) {
11324  NY2 = i - 1;
11325  }
11326  }
11327 
11328  if (NY2 >= 0) break;
11329  }
11330 
11331  // cout<<"gridlines limited to -80 to 80 degrees of latitutde.."<<"gdline ini.."<<NY1<<"gdline end.."<<NY2<<endl;
11332 
11333  l1cfile->NY1 = NY1;
11334  l1cfile->NY2 = NY2;
11335 
11336  cout << "NY.." << NY << "NY1.." << NY1 << "NY2.." << NY2 << endl;
11337 
11338 
11339 
11340  num_gridlines = NY2 - NY1 + 1;//this is the # gridlines after -80 to 80 lat constraint---
11341 
11342  cout<<"numgridlines after restriction lat"<<num_gridlines<<endl;
11343 
11344  ngroups = floor(num_gridlines / gdlines_group);
11345  cout << "gdlines will start in gline.." << i + 1 << "ROUNDED ngroups after adjusting beginning.for constraint lat (-80 to 80)" << ngroups << endl;
11346 
11347  //for each 'grid' group scan the swath files to see if there are scanlines within--
11348  //if that is case check the across-bin number position (0 to binx-1) based on latnad and lonnad values---
11349  last_file = 0;
11350  last_sline = 0;
11351  flag_donefile = 0;
11352 
11353  if (num_gridlines > ngroups * gdlines_group) ngroups += 1;
11354 
11355 
11356  //*********** SORTING LAT/LON ASCENDING AND TRACK INDEXES ****************************
11357  //***********************************************************************************
11358 
11359  //Create index matrix for i and j of each lat and lon L1C grid (-80 to 80)
11360  //num_gridlines x nbinx
11361  index_xy = allocate2d_short(num_gridlines, nbinx);
11362  lat_asort = allocate2d_float(num_gridlines, nbinx);
11363  // lon_asort=allocate2d_float(num_gridlines,nbinx);
11364  //fill indexe
11365 
11366  //define 1-D vector to sort 1 col L1C grid at the time---
11367  vector<pair<float, int> > vp;
11368 
11369  //fill vector with lat_gd column--
11370  cout << "*********** SORTING LAT/LON GRIDPOINTS AND TRACKING INDEXES ********************" << endl;
11371 
11372  for (int col = 0;col < nbinx;col++) {
11373  for (int row = NY1;row < NY2 + 1;row++) {
11374  vp.push_back(make_pair(lat_gd[row][col] + 90., row));
11375  }
11376  //sort
11377  stable_sort(vp.begin(), vp.end());
11378  //display lat in order along with its gridpoint index--
11379  // cout << "Lat value\t"
11380  // << "index" << endl;
11381  for (unsigned int i = 0; i < vp.size(); i++) {
11382  lat_asort[i][col] = vp[i].first;
11383  index_xy[i][col] = vp[i].second;
11384  }
11385  vp.clear();
11386  }
11387 
11388  cout << "num_gridlines...." << num_gridlines << "ngroups.." << ngroups << endl;
11389 
11390 
11391  //****************************************************************************************************
11392  //************* BIG LOOP GROUPS ***************************************
11393  cout << "Number of granules to be L1C processed........................................." << sfiles << endl;
11394 
11395 //**********BIG LOOP GROUPS ********************
11396  for (k = 0;k < ngroups;k++) {
11397 
11398  //total gridlines for k groups-----
11399  n_gdlines = (k + 1) * gdlines_group;
11400  cout << "screening k group.." << k + 1 << "last_file.." << last_file << "last_line.." << last_sline << endl;
11401  cout << "number of gridlines so far..." << n_gdlines << endl;
11402  //***** compute deltas for lat_gd index 256 and 257 *******************
11403 
11404  //compute delta_lat and delta_lon based on binres/2 for lower and upper corners of 'nadir' gridpoints of 256 and 257 indexes -----------------
11405  //we need nadir 256 and 257 lat/lon coordinates to compute -delta and +delta, respectively
11406  //we need azimuth and backazimuth and binres/2 to compute deltas ---
11407 
11408  //index 256
11409  geod.Direct(lat_gd[n_gdlines - gdlines_group][256], lon_gd[n_gdlines - gdlines_group][256], az_east[n_gdlines - gdlines_group], gres, dlamin, dlomin);
11410  geod.Direct(lat_gd[n_gdlines - 1][257], lon_gd[n_gdlines - 1][257], az_east[n_gdlines - 1], gres, dlamax, dlomax);
11411 
11412  cout << "dlamin.." << dlamin << "dlomin.." << dlomin << "dlamax.." << dlamax << "dlomax.." << dlomax << endl;
11413 
11414  dlatb_g[k][0] = dlamin;//in DEGREES!!
11415  dlatb_g[k][1] = dlamax;
11416  dlonb_g[k][0] = dlomin;
11417  dlonb_g[k][1] = dlomax;
11418 
11419 //********* LOOP FILES ************************************
11420  for (unsigned int findex = last_file;findex < sfiles;findex++) {
11421 
11422  cout << "Scanning lines in file.. for crossing swath..." << swtd << "selected granule #.." << l1cfile->selgran[findex] << "swt_id.." << swtd_id[findex] << "grid group.." << k + 1 << endl;
11423 
11424  fi = l1cfile->selgran[findex];
11425  str = l1cfile->ifiles[fi - 1];
11426  ptstr = str.c_str();
11427 
11428  cout << "opening filename............" << ptstr << endl;
11429 
11430  status = nc_open(ptstr, NC_NOWRITE, &ncid_L1B);
11431  if (status != NC_NOERR) {
11432  fprintf(stderr, "nc_open error.\n");
11433  exit(EXIT_FAILURE);
11434  }
11435  //Open dimensions
11436 
11437  if(format.type==FT_SPEXONE){
11438  status = nc_inq_dimid(ncid_L1B, "bins_along_track", &dimid);
11439  if (status != NC_NOERR) {
11440  fprintf(stderr, "-E- Error reading number_of_scans.\n");
11441  exit(EXIT_FAILURE); }
11442  status = nc_inq_dimid(ncid_L1B, "spatial_samples_per_image", &dimid2);
11443  if (status != NC_NOERR) {
11444  fprintf(stderr, "-E- Error reading spatial_samples_per_image.\n");
11445  exit(EXIT_FAILURE); }
11446  status = nc_inq_dimid(ncid_L1B, "intensity_bands_per_view", &dimid3);
11447  if (status != NC_NOERR) {
11448  fprintf(stderr, "-E- Error reading intensity_bands_per_view.\n");
11449  exit(EXIT_FAILURE); }
11450  // spatial_samples_per_image, intensity_bands_per_view
11451  //
11452  }
11453  else{
11454  status = nc_inq_dimid(ncid_L1B, "number_of_scans", &dimid);
11455  if (status != NC_NOERR) {
11456  fprintf(stderr, "-E- Error reading number_of_scans.\n");
11457  exit(EXIT_FAILURE);
11458  }}
11459 
11460  nc_inq_dimlen(ncid_L1B, dimid, &num_scans);
11461 
11462  //read line-by-line lat/lon/Lt
11463  if(format.type==FT_SPEXONE){
11464  status = nc_inq_grp_ncid(ncid_L1B, "GEOLOCATION_DATA", &geoGrp);
11465  check_err(status, __LINE__, __FILE__);
11466  status = nc_inq_grp_ncid(ncid_L1B, "OBSERVATION_DATA", &obsGrp);
11467  check_err(status, __LINE__, __FILE__);
11468  }
11469  else{
11470  status = nc_inq_grp_ncid(ncid_L1B, "geolocation_data", &geoGrp);
11471  check_err(status, __LINE__, __FILE__);
11472  status = nc_inq_grp_ncid(ncid_L1B, "observation_data", &obsGrp);
11473  check_err(status, __LINE__, __FILE__);
11474  }
11475 
11476 
11477  //open geo data
11478  status = nc_inq_varid(geoGrp, "sensor_azimuth", &senazId);
11479  check_err(status, __LINE__, __FILE__);
11480  status = nc_inq_varid(geoGrp, "latitude", &latId);
11481  check_err(status, __LINE__, __FILE__);
11482  status = nc_inq_varid(geoGrp, "longitude", &lonId);
11483  check_err(status, __LINE__, __FILE__);
11484 
11485  //radiance variables
11486  if(format.type==FT_SPEXONE){
11487  NVIEWS= 1;//should be 5 but only provided 1
11488  NBANDS=400;
11489  NBANDS_POL=50;
11490  status = nc_inq_varid(obsGrp, "I", &I_Id);
11491  check_err(status, __LINE__, __FILE__);
11492  status = nc_inq_varid(obsGrp, "I_polsample", &Ipol_Id);
11493  check_err(status, __LINE__, __FILE__);
11494  cout << "#total number of Intensity bands per view.." << NBANDS << endl;
11495  cout << "#total number of Polarization bands per view.." << NBANDS_POL << endl;
11496 
11497  }
11498  else{//OCIS
11499  NVIEWS= 2;//for OCI
11500  NBANDS=249;//for OCI
11501  status = nc_inq_varid(obsGrp, "Lt_blue", &Lt_blueId);
11502  check_err(status, __LINE__, __FILE__);
11503  status = nc_inq_varid(obsGrp, "Lt_red", &Lt_redId);
11504  check_err(status, __LINE__, __FILE__);
11505  status = nc_inq_varid(obsGrp, "Lt_SWIR", &Lt_SWIRId);
11506  check_err(status, __LINE__, __FILE__);
11507  // num_blue_bands
11508  status = nc_inq_dimid(ncid_L1B, "blue_bands", &dimid);
11509  if (status != NC_NOERR) {
11510  fprintf(stderr, "-E- Error reading num_blue_bands.\n");
11511  exit(EXIT_FAILURE);
11512  }
11513  nc_inq_dimlen(ncid_L1B, dimid, &num_blue_bands);
11514 
11515  // num_red_bands
11516  status = nc_inq_dimid(ncid_L1B, "red_bands", &dimid);
11517  if (status != NC_NOERR) {
11518  fprintf(stderr, "-E- Error reading num_red_bands.\n");
11519  exit(EXIT_FAILURE);
11520  }
11521  nc_inq_dimlen(ncid_L1B, dimid, &num_red_bands);
11522 
11523  // num_SWIR_bands
11524  status = nc_inq_dimid(ncid_L1B, "SWIR_bands", &dimid);
11525  if (status != NC_NOERR) {
11526  fprintf(stderr, "-E- Error reading num_SWIR_bands.\n");
11527  exit(EXIT_FAILURE);
11528  }
11529  nc_inq_dimlen(ncid_L1B, dimid, &num_SWIR_bands);
11530  cout << "#blue bands.." << num_blue_bands << endl;
11531  cout << "#red bands.." << num_red_bands << endl;
11532  cout << "#swir bands.." << num_SWIR_bands << endl;
11533  nbands=num_blue_bands+num_red_bands+num_SWIR_bands;
11534  cout << "#total number of bands.." << nbands << endl;
11535  }
11536 
11537  cout<<"#gridlines.."<<num_gridlines<<"# binx.."<<nbinx2<<"number of scans.."<<num_scans<<"# pixels..or spatial_samples_per_image in SPEXone"<<num_pixels<<endl;
11538 
11539 
11540 
11541 
11542  if (last_sline == 0 && binmean_Lt == nullptr) { // binmean_Lt==NULL | bincount==NULL | binmean_Lt2==NULL | bincount2==NULL | binmean_Lt3==NULL | bincount3==NULL){
11543 
11544  cout << "first allocation of memory for grid bins of file #..." << l1cfile->selgran[findex] << endl;
11545 
11546  // cout<<"findex.."<<findex<<"blue bands"<<num_blue_bands<<"red bands.."<<num_red_bands<<"swir bands..."<<num_SWIR_bands<<"nbinx.."<<nbinx<<endl;
11547  binmean_Lt = allocate4d_float(NVIEWS,NBANDS,num_gridlines,nbinx2);
11548  bincount = allocate4d_int(NVIEWS,NBANDS,num_gridlines,nbinx2);//all bands together, only 1 view for OCI
11549 
11550  // binmean_Lt = allocate3d_float(num_gridlines,nbinx,nbands);
11551  // bincount = allocate3d_int(num_gridlines,nbinx,nbands);//all bands together, only 1 view for OCI
11552  for(size_t v=0;v<NVIEWS;v++){
11553  for(size_t b=0;b<NBANDS;b++){
11554  for(int j=0;j<num_gridlines;j++){
11555  for(int i=0;i<nbinx2;i++){
11556  binmean_Lt[v][b][j][i]=0.;
11557  bincount[v][b][j][i]=0.;
11558  }}}}
11559 
11560  }//end if first time allocating mem for binning arrays
11561 
11562  if(format.type==FT_SPEXONE){
11563  //assigning mem for Lt of different bands **********************
11564  latpix = (float*)calloc(num_pixels , sizeof(float));
11565  lonpix = (float*)calloc(num_pixels , sizeof(float));
11566  Lt_pix = allocate2d_float(num_pixels,NBANDS);//blue bands
11567  Lt_pix2 = allocate2d_float(num_pixels,NBANDS_POL);//red bands
11568  }
11569  else{
11570  senazpix=(float*)calloc(num_pixels , sizeof(float));
11571  latpix = (float*)calloc(num_pixels , sizeof(float));
11572  lonpix = (float*)calloc(num_pixels , sizeof(float));
11573  Lt_pix = allocate2d_float(num_blue_bands, num_pixels);//blue bands
11574  Lt_pix2 = allocate2d_float(num_red_bands, num_pixels);//red bands
11575  Lt_pix3 = allocate2d_float(num_SWIR_bands, num_pixels);//S
11576  }
11577 
11578 //BIG SCANLINE LOOP----------------------------------
11579  //********************************************************************************
11580  //-----reading line by line-----------------------------------
11581  for (unsigned int sline = last_sline;sline < num_scans;sline++) {
11582 
11583  //lat and lon--
11584  start[0] = sline;
11585  start[1] = 0;
11586  count[0] = 1;
11587  count[1] = num_pixels; // 1 line at a time
11588  if(format.type==FT_SPEXONE){
11589  status = nc_get_vara_float(geoGrp, latId, start, count, latpix);
11590  status = nc_get_vara_float(geoGrp, lonId, start, count, lonpix);
11591  }
11592  else{ //OCIS
11593  status = nc_get_vara_float(geoGrp, senazId, start, count, senazpix);//-1800 to + 1800 s means s as scaled
11594  status = nc_get_vara_float(geoGrp, latId, start, count, latpix);
11595  status = nc_get_vara_float(geoGrp, lonId, start, count, lonpix);
11596  }
11597 
11598  //Lt
11599  if(format.type==FT_SPEXONE){
11600  start2[0] = sline;
11601  start2[1] = 0;
11602  start2[2] = 0;
11603 
11604  count2[0] = 1;
11605  count2[1] = num_pixels; // 1 line at a time
11606  count2[2] = NBANDS;
11607 
11608  count3[0] = 1;
11609  count3[1] = num_pixels; // 1 line at a time
11610  count3[2] = NBANDS_POL;
11611 
11612  status = nc_get_vara_float(obsGrp, Lt_blueId, start2, count2, Lt_pix[0]);//all intensity bands
11613  status = nc_get_vara_float(obsGrp, Lt_redId, start2, count3, Lt_pix2[0]);//all poalrized bands
11614  }
11615  else{ //OCIS
11616  start2[0] = 0;
11617  start2[1] = sline;
11618  start2[2] = 0;
11619 
11620  count2[0] = num_blue_bands;
11621  count2[1] = 1; // 1 line at a time
11622  count2[2] = num_pixels;
11623 
11624  count3[0] = num_red_bands;
11625  count3[1] = 1; // 1 line at a time
11626  count3[2] = num_pixels;
11627 
11628  count4[0] = num_SWIR_bands;
11629  count4[1] = 1; // 1 line at a time
11630  count4[2] = num_pixels;
11631 
11632  status = nc_get_vara_float(obsGrp, Lt_blueId, start2, count2, Lt_pix[0]);
11633  status = nc_get_vara_float(obsGrp, Lt_redId, start2, count3, Lt_pix2[0]);
11634  status = nc_get_vara_float(obsGrp, Lt_SWIRId, start2, count4, Lt_pix3[0]);
11635  }
11636 
11637 
11638  /* for(int bb=0;bb<num_blue_bands;bb++){
11639  cout<<"processing blue band #.........................................................................."<<bb+1<<"of total blue bands #.."<<num_blue_bands<<endl;
11640  cout<<"Lt_pix at pix =0..."<<Lt_pix[bb][0]<<"Lt_pix at pix =1..."<<Lt_pix[bb][1]<<endl;
11641  }
11642  exit(1);
11643  */
11644 
11645  for (unsigned int pix = 0;pix < num_pixels;pix++) {
11646  if (latpix[pix] < latmin_swt) latmin_swt = latpix[pix];
11647  if (latpix[pix] > latmax_swt) latmax_swt = latpix[pix];
11648  if (lonpix[pix] < lonmin_swt) lonmin_swt = lonpix[pix];
11649  if (lonpix[pix] > lonmax_swt) lonmax_swt = lonpix[pix];
11650 
11651  // cout<<"senazpix (sensor azimuth)...in degrees."<<senazpix[pix]/100<<"at pix #..."<<pix+1<<"latpix.."<<latpix[pix]<<endl;
11652  }
11653 
11654 
11655 
11656  // cout<<"nadpix..."<<nadpix<<"latpix[nadpix]..."<<latpix[nadpix]<<"lonpix[nadpix]..."<<lonpix[nadpix]<<endl;
11657  // cout<<"dlatb_g[k][0]...."<<dlatb_g[k][0]<<"dlatb_g[k][1]...."<<dlatb_g[k][1]<<endl;
11658  // cout<<"senazpix (sensor azimuth)...in degrees."<<senazpix[nadpix]/100<<"at line #..."<<sline+1<<"latpix[nadpix].."<<latpix[nadpix]<<endl;
11659 
11660  dlamin = 0.;dlamax = 0.;
11661 
11662  //inside the 'k' box??----- ascending ----------
11663  if (latpix[nadpix] >= dlatb_g[k][0] && latpix[nadpix] <= dlatb_g[k][1]) {
11664 
11665  if (sline % 100 == 0) cout << "EVERY 100 gds..for k group.." << k + 1 << "file number #.." << l1cfile->selgran[findex] << "sline..." << sline + 1 << "# of binned pix.." << inpix << "outpix.." << outpix << endl;
11666 
11667  //*********** BIG LOOP M_PIXEL *****************************************************************
11668  for (unsigned int pix = 0;pix < num_pixels;pix++) {
11669 
11670  sb=0,bb=0,rb=0,swb=0,ib=0;
11671  gd_row=0,gd_col=0;
11672  flag_inpix = 0;
11673 
11674  boolbin1 = sbs2_l1c(l1cinput, num_gridlines, nbinx, lat_asort, index_xy, latpix[pix], lonpix[pix], lon_gd, &gd_row, &gd_col);
11675 
11676  bin_ypix = gd_row + 1;
11677  bin_xpix = gd_col + 1;
11678 
11679  // cout<<"pix..."<<pix+1<<"latpix..."<<latpix[pix]<<"lonpix..."<<lonpix[pix]<<endl;
11680 
11681  if (boolbin1 == 1) flag_inpix = 1;
11682  //************ BINNING ***************************
11683  //assign identified pixel to Lt and bin stat arrays-----
11684 
11685  //BLUE---
11686  if (flag_inpix == 1 && bin_xpix >= 1 && bin_ypix >= 1 && bin_xpix <= nbinx && bin_ypix <= num_gridlines) {
11687  inpix++;
11688  if(format.type==FT_SPEXONE){
11689  view=0;
11690  while (sb<NBANDS) {
11691  if (Lt_pix[pix][ib] > 0.) {
11692  // cout<<"Lt_pix[pix][ib]..."<<Lt_pix[pix][ib]<<"bin_ypix.."<<bin_ypix<<"bin_xpix.."<<bin_xpix<<endl;
11693  binmean_Lt[view][ib][bin_ypix - 1][bin_xpix - 1] = binmean_Lt[view][ib][bin_ypix - 1][bin_xpix - 1] + Lt_pix[pix][ib];
11694  bincount[view][ib][bin_ypix - 1][bin_xpix - 1] += 1;
11695  }
11696  ib++;
11697  sb++;
11698  }//end while intensity bands
11699 
11700 /* while (sb<num_blue_bands) {
11701  if (Lt_pix2[bb][pix] > 0.) {
11702  binmean_Lt[view][sb][bin_ypix - 1][bin_xpix - 1] = binmean_Lt[view][sb][bin_ypix - 1][bin_xpix - 1] + Lt_pix2[bb][pix];
11703  bincount[view][sb][bin_ypix - 1][bin_xpix - 1] += 1;
11704  }
11705  bb++;
11706  sb++;
11707  }//end while polarization bands
11708 */
11709  }
11710  else{ //OCIS
11711  if(senazpix[nadpix]/100<0) view=0; else view=1;
11712  while (sb<num_blue_bands) {
11713  if (Lt_pix[bb][pix] > 0.) {
11714  binmean_Lt[view][sb][bin_ypix - 1][bin_xpix - 1] = binmean_Lt[view][sb][bin_ypix - 1][bin_xpix - 1] + Lt_pix[bb][pix];
11715  bincount[view][sb][bin_ypix - 1][bin_xpix - 1] += 1;
11716  }
11717  bb++;
11718  sb++;
11719  }//end while blue band band
11720 
11721  //RED---
11722  while (sb <num_blue_bands+num_red_bands) {
11723  if (Lt_pix2[rb][pix] > 0.) {
11724  binmean_Lt[view][sb][bin_ypix - 1][bin_xpix - 1] = binmean_Lt[view][sb][bin_ypix - 1][bin_xpix - 1] + Lt_pix2[rb][pix];
11725  bincount[view][sb][bin_ypix - 1][bin_xpix - 1] += 1;
11726  }
11727  rb++;
11728  sb++;
11729  }//end red bands
11730 
11731  //SWIR----
11732  while (sb <num_blue_bands + num_red_bands + num_SWIR_bands) {
11733  if (Lt_pix3[swb][pix] > 0.) {
11734  binmean_Lt[view][sb][bin_ypix - 1][bin_xpix - 1] = binmean_Lt[view][sb][bin_ypix - 1][bin_xpix - 1] + Lt_pix3[swb][pix];
11735  bincount[view][sb][bin_ypix - 1][bin_xpix - 1] += 1;
11736  }
11737  swb++;
11738  sb++;
11739  }//end swir bands
11740  }
11741 
11742  }//end if inpix==1
11743 
11744 
11745 
11746  //********** pixel AREA WEIGHTING ************************
11747  if (flag_inpix == 0) outpix++;
11748 
11749  totpix++;
11750 
11751  }//end pixels loop
11752 
11753 
11754 
11755 
11756  //END OF FILE--****** reset starting sline index if last line processed and within k box
11757  //go for another granule if it is not the last one---------------
11758  if (sline == num_scans - 1) {
11759  flag_donefile = 1;
11760  cout << "end of file..." << l1cfile->selgran[findex] << endl;
11761  last_sline = 0;
11762  if (findex >= sfiles - 1) {
11763  cout << "done with last granule of the input list........................." << endl;
11764  // findex=sfiles;
11765  k = ngroups;
11766  break;
11767  }
11768 
11769  }//end of file/last file? sliine=num_scans-1
11770  else flag_donefile = 0;
11771 
11772  }//end latpix nadir of line x inside grid group?
11773 
11774  //***** skip lines and files if sline is not within k group ********
11775  //increase k and screen files and lines again starting from the last binning
11776 
11777  if (latpix[nadpix] > lat_gd[n_gdlines - 1][257] && k < ngroups - 1) { //else limits
11778  if(format.type==FT_SPEXONE){
11779  cout << "moving to the next k group...scanning again files/slines.." << endl;
11780  cout << "group #.."<<k+1<<"file index.." << findex << "sline index.." << sline << endl;
11781  last_file = findex;
11782  last_sline = sline;
11783  findex = sfiles;
11784  sline = num_scans - 1;
11785  }
11786  else{ //OCIS
11787  cout << "moving to the next k group...scanning again files/slines.." << endl;
11788  cout << "file index.." << findex << "last sline index.." << sline << endl;
11789  last_file = findex;
11790  last_sline = sline;
11791  findex = sfiles;
11792  sline = num_scans - 1;
11793  }
11794  }//end if lat >grid lat--IF outside the box
11795 
11796  if (sline + 1 % 100 == 0) cout << "for k group.." << k + 1 << "selected granule #.." << l1cfile->selgran[findex] << "sline..." << sline + 1 << "# of binned pix.." << inpix << "totpix.." << totpix << "outpix.." << outpix << endl;
11797  }//end for scanlines
11798 
11799  cout << "closing L1B file......." << ptstr << endl;
11800  status = nc_close(ncid_L1B);
11801  check_err(status, __LINE__, __FILE__);
11802  if (latpix != nullptr)
11803  delete[](latpix);
11804  if (lonpix != nullptr)
11805  delete[](lonpix);
11806  if (Lt_pix != nullptr)
11807  delete[](Lt_pix);
11808  if (Lt_pix2 != nullptr)
11809  delete[](Lt_pix2);
11810  if (Lt_pix3 != nullptr)
11811  delete[](Lt_pix3);
11812  if (senazpix != nullptr)
11813  delete [](senazpix);
11814 
11815  //**********************************************************************************************************************************
11816  //**********************************************************************************************************************************
11817  //writing each granule ---------------------------------
11818  //*****************************************************************************
11819 
11820  if (flag_donefile == 1 | (flag_donefile == 0 && k == ngroups - 1)) {
11821  cout << "writing file #....................................................................................................................." << l1cfile->selgran[findex] << "based on group #.." << k + 1 << endl;
11822  //write mean Lt as nc file---
11823  //**********************************************************************
11824  //**********************************************************************8
11825  //create Lt file
11826  pathstr = "out/";
11827  senstr = "OCIS_";
11828  monstr = std::to_string(selmon);
11829  daystr = std::to_string(selday);
11830  yearstr = std::to_string(selyear);
11831  prodstr = "binLt_sbs";
11832  swtstr = "_swt";
11833  granstr = "";
11834  granstr = "_" + std::to_string(l1cfile->selgran[findex]);
11835 
11836  if (l1cfile->l1c_pflag >= 3) {
11837  swtd = l1cfile->swtnum;
11838  swtnum = std::to_string(swtd);
11839  cout << "swtnum.." << swtnum << endl;
11840  }
11841  else swtnum = std::to_string(swtd);
11842 
11843  extstr = ".nc";
11844  string GATT_NAME1,GATT_VAL1,GATT_NAME2,GATT_VAL2;
11845 
11846  if(format.type==FT_SPEXONE){
11847  senstr = "SPEXONE";
11848  GATT_NAME1="Title",GATT_VAL1="PACE SPEXone Level-1C Data",GATT_NAME2="instrument",GATT_VAL2="SPEXone";
11849  }
11850  else if(format.type==FT_HARP){
11851  senstr = "HARP2";
11852  GATT_NAME1="Title",GATT_VAL1="PACE HARP Level-1C Data",GATT_NAME2="instrument",GATT_VAL2="HARP";
11853  }
11854  else//OCIS
11855  {
11856  senstr = "OCI";
11857  GATT_NAME1="Title",GATT_VAL1="PACE OCI Level-1C Data",GATT_NAME2="instrument",GATT_VAL2="OCI";
11858  }
11859 
11860 
11861 
11862  fname_out = pathstr + missionstr + "_" + senstr + "." + yearstr + monstr + daystr + timestr + prodstr+granstr+extstr;
11863 
11864  string ATT_NAME="Units", ATT_VAL="degrees",GATT_NAME3="processing_version",GATT_VAL3="V1.0",GATT_NAME4="Conventions",GATT_VAL4="CF-1.6";
11865  string GATT_NAME5="institution",GATT_VAL5="NASA Goddard Space Flight Center, Ocean Biology Processing Group",GATT_NAME6="license",GATT_VAL6="http://science.nasa.gov/earth-science/earth-science-data/data-information-policy/";
11866  string GATT_NAME7="naming_authority",GATT_VAL7="gov.nasa.gsfc.sci.oceancolor",GATT_NAME8="keywords_vocabulary",GATT_VAL8="NASA Global Change Master Directory (GCMD) Science Keywords";
11867  string GATT_NAME9="stdname_vocabulary",GATT_VAL9="NetCDF Climate and Forecast (CF) Metadata Convention",GATT_NAME10="creator_name",GATT_VAL10="NASA/GSFC",GATT_NAME11="creator_email",GATT_VAL11="data@oceancolor.gsfc.nasa.gov";
11868  string GATT_NAME12="creator_url",GATT_VAL12="http://oceancolor.gsfc.nasa.gov",GATT_NAME13="project",GATT_VAL13="PACE Project",GATT_NAME14="publisher_name",GATT_VAL14="NASA/GSFC";
11869  string GATT_NAME15="publisher_email",GATT_VAL15="data@oceancolor.gsfc.nasa.gov",GATT_NAME16="publisher_url",GATT_VAL16="http://oceancolor.gsfc.nasa.gov",GATT_NAME17="processing_level",GATT_VAL17="L1C";
11870  string GATT_NAME18="cdm_data_type",GATT_VAL18="swath",GATT_NAME19="orbit_number",GATT_VAL19="12345",GATT_NAME20="history",GATT_VAL20="",GATT_NAME21="CDL_version_date",GATT_VAL21="2021-09-10",GATT_NAME22="product_name",GATT_VAL22=fname_out;
11871  string GATT_NAME23="startDirection",GATT_VAL23="Ascending",GATT_NAME24="endDirection",GATT_VAL24="Ascending",GATT_NAME25="time_coverage_start",GATT_VAL25=yearstr+"-"+monstr+"-"+daystr+"-"+timestr,GATT_NAME26="time_coverage_end",GATT_VAL26=yearstr+"-"+monstr+"-"+daystr+"-"+timestr,GATT_NAME27="date{_created",GATT_VAL27="2021-09-10T15:12:41Z",GATT_NAME28="sun_earth_distance",GATT_VAL28="0.990849042172323",GATT_NAME29="terrain_data_source",GATT_VAL29="",GATT_NAME30="spectral_response_function",GATT_VAL30="",GATT_NAME31="systematic_uncertainty_model",GATT_VAL31="",GATT_NAME32="nadir_bin",GATT_VAL32="12345",GATT_NAME33="bin_size_at_nadir",GATT_VAL33="5.2km2";
11872 
11873  l1cfile->gridname = fname_out.c_str();
11874  filename_lt = fname_out.c_str();
11875 
11876  if ((status = nc_create(filename_lt, NC_CLOBBER | NC_NETCDF4, &ncid_out)))
11877  check_err(status, __LINE__, __FILE__);
11878  //define dims
11879  // Define the dimensions,vars and attributes at the root level
11880  NDIMS=2;
11881  NDIMS2=3;
11882  NDIMS3=4;
11883  NY = num_gridlines;
11884  NX = nbinx;
11885  //NVIEWS= 2;//for OCI
11886  // NBANDS=249;//for OCI
11887 
11888  NY1 = l1cfile->NY1;//these are indexes not line #!!!!!!!!!!!!!!!!!
11889  NY2 = l1cfile->NY2;
11890  cout << "rowgrid ini.." << NY1 << "rowgrid end.." << NY2 << endl;
11891  NY = NY2 - NY1 + 1;
11892  cout << "NY.." << NY << "NX.." << NX << "NY1.."<<NY1<<"NY2.."<<NY2<<endl;
11893 
11894  //DEF DIMENSIONS
11895  if ((status = nc_def_dim(ncid_out, "bins_across_track", NX, &x_dimid)))
11896  check_err(status, __LINE__, __FILE__);
11897  if ((status = nc_def_dim(ncid_out, "bins_along_track", NY, &y_dimid)))
11898  check_err(status, __LINE__, __FILE__);
11899  //dims for output var
11900  dimids[0] = y_dimid;
11901  dimids[1] = x_dimid;
11902 
11903  if ((status = nc_def_dim(ncid_out, "number_of_views", NVIEWS, &v_dimid)))
11904  check_err(status, __LINE__, __FILE__);
11905  if ((status = nc_def_dim(ncid_out, "intensity_bands_per_view", NBANDS, &b_dimid)))
11906  check_err(status, __LINE__, __FILE__);
11907 
11908  dimids2[0] = y_dimid;
11909  dimids2[1] = x_dimid;
11910  dimids2[2] = v_dimid;//#o
11911 
11912  dimids3[0] = y_dimid;
11913  dimids3[1] = x_dimid;
11914  dimids3[2] = v_dimid;//
11915  dimids3[3] = b_dimid;
11916 
11917  /* try
11918  {
11919  cout<<"Opening file \"firstFile.nc\" with NcFile::replace"<<endl;
11920  NcFile ncFile("firstFile.nc",NcFile::replace);
11921  NcGroup groupA(ncFile.addGroup("groupA"));
11922  }
11923 
11924  catch (NcException& e)
11925  {
11926  cout << "unknown error"<<endl;
11927  e.what();
11928  }
11929  exit(1);
11930  */
11931  //define attributes
11932  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME1.c_str(), strlen(GATT_VAL1.c_str()),
11933  GATT_VAL1.c_str()))
11934  check_err(status, __LINE__, __FILE__);
11935  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME2.c_str(), strlen(GATT_VAL2.c_str()),
11936  GATT_VAL2.c_str()))
11937  check_err(status, __LINE__, __FILE__);
11938  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME3.c_str(), strlen(GATT_VAL3.c_str()),
11939  GATT_VAL3.c_str()))
11940  check_err(status, __LINE__, __FILE__);
11941  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME4.c_str(), strlen(GATT_VAL4.c_str()),
11942  GATT_VAL4.c_str()))
11943  check_err(status, __LINE__, __FILE__);
11944  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME5.c_str(), strlen(GATT_VAL5.c_str()),
11945  GATT_VAL5.c_str()))
11946  check_err(status, __LINE__, __FILE__);
11947  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME6.c_str(), strlen(GATT_VAL6.c_str()),
11948  GATT_VAL6.c_str()))
11949  check_err(status, __LINE__, __FILE__);
11950  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME7.c_str(), strlen(GATT_VAL7.c_str()),
11951  GATT_VAL7.c_str()))
11952  check_err(status, __LINE__, __FILE__);
11953  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME8.c_str(), strlen(GATT_VAL8.c_str()),
11954  GATT_VAL8.c_str()))
11955  check_err(status, __LINE__, __FILE__);
11956  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME9.c_str(), strlen(GATT_VAL9.c_str()),
11957  GATT_VAL9.c_str()))
11958  check_err(status, __LINE__, __FILE__);
11959  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME10.c_str(), strlen(GATT_VAL10.c_str()),
11960  GATT_VAL10.c_str()))
11961  check_err(status, __LINE__, __FILE__);
11962  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME11.c_str(), strlen(GATT_VAL11.c_str()),
11963  GATT_VAL11.c_str()))
11964  check_err(status, __LINE__, __FILE__);
11965  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME12.c_str(), strlen(GATT_VAL12.c_str()),
11966  GATT_VAL12.c_str()))
11967  check_err(status, __LINE__, __FILE__);
11968  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME13.c_str(), strlen(GATT_VAL13.c_str()),
11969  GATT_VAL13.c_str()))
11970  check_err(status, __LINE__, __FILE__);
11971  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME14.c_str(), strlen(GATT_VAL14.c_str()),
11972  GATT_VAL14.c_str()))
11973  check_err(status, __LINE__, __FILE__);
11974  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME15.c_str(), strlen(GATT_VAL15.c_str()),
11975  GATT_VAL15.c_str()))
11976  check_err(status, __LINE__, __FILE__);
11977  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME16.c_str(), strlen(GATT_VAL16.c_str()),
11978  GATT_VAL16.c_str()))
11979  check_err(status, __LINE__, __FILE__);
11980  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME17.c_str(), strlen(GATT_VAL17.c_str()),
11981  GATT_VAL17.c_str()))
11982  check_err(status, __LINE__, __FILE__);
11983  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME18.c_str(), strlen(GATT_VAL18.c_str()),
11984  GATT_VAL18.c_str()))
11985  check_err(status, __LINE__, __FILE__);
11986  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME19.c_str(), strlen(GATT_VAL19.c_str()),
11987  GATT_VAL19.c_str()))
11988  check_err(status, __LINE__, __FILE__);
11989  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME20.c_str(), strlen(GATT_VAL20.c_str()),
11990  GATT_VAL20.c_str()))
11991  check_err(status, __LINE__, __FILE__);
11992  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME21.c_str(), strlen(GATT_VAL21.c_str()),
11993  GATT_VAL21.c_str()))
11994  check_err(status, __LINE__, __FILE__);
11995  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME22.c_str(), strlen(GATT_VAL22.c_str()),
11996  GATT_VAL22.c_str()))
11997  check_err(status, __LINE__, __FILE__);
11998  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME23.c_str(), strlen(GATT_VAL23.c_str()),
11999  GATT_VAL23.c_str()))
12000  check_err(status, __LINE__, __FILE__);
12001  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME24.c_str(), strlen(GATT_VAL24.c_str()),
12002  GATT_VAL24.c_str()))
12003  check_err(status, __LINE__, __FILE__);
12004  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME25.c_str(), strlen(GATT_VAL25.c_str()),
12005  GATT_VAL25.c_str()))
12006  check_err(status, __LINE__, __FILE__);
12007  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME26.c_str(), strlen(GATT_VAL26.c_str()),
12008  GATT_VAL26.c_str()))
12009  check_err(status, __LINE__, __FILE__);
12010  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME27.c_str(), strlen(GATT_VAL27.c_str()),
12011  GATT_VAL27.c_str()))
12012  check_err(status, __LINE__, __FILE__);
12013  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME28.c_str(), strlen(GATT_VAL28.c_str()),
12014  GATT_VAL28.c_str()))
12015  check_err(status, __LINE__, __FILE__);
12016  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME29.c_str(), strlen(GATT_VAL29.c_str()),
12017  GATT_VAL29.c_str()))
12018  check_err(status, __LINE__, __FILE__);
12019  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME30.c_str(), strlen(GATT_VAL30.c_str()),
12020  GATT_VAL30.c_str()))
12021  check_err(status, __LINE__, __FILE__);
12022  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME31.c_str(), strlen(GATT_VAL31.c_str()),
12023  GATT_VAL31.c_str()))
12024  check_err(status, __LINE__, __FILE__);
12025  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME32.c_str(), strlen(GATT_VAL32.c_str()),
12026  GATT_VAL32.c_str()))
12027  check_err(status, __LINE__, __FILE__);
12028  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME33.c_str(), strlen(GATT_VAL33.c_str()),
12029  GATT_VAL33.c_str()))
12030  check_err(status, __LINE__, __FILE__);
12031 
12032  //define group1
12033  if ((status = nc_def_grp(ncid_out, "geolocation_data", &grp_coor))) //netcdf-4
12034  check_err(status, __LINE__, __FILE__);
12035  //def var grp1
12036  if ((status = nc_def_var(grp_coor, "latitude", NC_FLOAT, NDIMS,
12037  dimids, &varid1)))
12038  check_err(status, __LINE__, __FILE__);
12039  if ((status = nc_def_var(grp_coor, "longitude", NC_FLOAT, NDIMS,
12040  dimids, &varid2)))
12041  check_err(status, __LINE__, __FILE__);
12042 
12043  //leave define mode-----------------------
12044  if ((status = nc_enddef(grp_coor))) //done def vars etc
12045  check_err(status, __LINE__, __FILE__);
12046 
12047  //define group2
12048  if ((status = nc_def_grp(ncid_out, "observation_data", &grp_obs))) //netcdf-4
12049  check_err(status, __LINE__, __FILE__);
12050 
12051  //def var grp2
12052  //counts and Lt
12053  if ((status = nc_def_var(grp_obs, "obs_per_view", NC_INT, NDIMS2,
12054  dimids2, &varid_count)))
12055  check_err(status, __LINE__, __FILE__);
12056  if ((status = nc_def_var(grp_obs, "I", NC_FLOAT, NDIMS3,
12057  dimids3, &varid_lt)))
12058  check_err(status, __LINE__, __FILE__);
12059 
12060 /*
12061  if ((status = nc_def_var(grp_obs, "Igeo", NC_FLOAT, NDIMS, //first band, geolocated I for OCI test
12062  dimids, &varid3)))
12063  check_err(status, __LINE__, __FILE__);
12064  if((status = nc_put_att_text (grp_obs,varid3, "coordinates",
12065  strlen("lat lon"), "lat lon")))
12066  check_err(status, __LINE__, __FILE__);
12067 */
12068 
12069  // _CoordinateAxisType = "GeoY";_CoordinateAxisType = "GeoX";
12070  //
12071  //leave define mode-----------------------
12072  if ((status = nc_enddef(grp_obs))) //done def vars etc
12073  check_err(status, __LINE__, __FILE__);
12074 
12075 
12076  lat_out = allocate2d_float(NY, NX);
12077  lon_out = allocate2d_float(NY, NX);
12078  // Igeo_out = allocate2d_float(NY, NX);
12079 
12080  int c = 0;
12081 
12082  for (int i = NY1; i < NY2 + 1; i++) {
12083  for (int j = 0; j < NX; j++) {
12084  lat_out[NY - 1 - c][NX - 1 - j] = lat_gd[i][j];
12085  lon_out[NY - 1 - c][j] = lon_gd[i][j];
12086  // Igeo_out[i][j]=NAN;
12087  }
12088  c++;
12089  }
12090 
12091 
12092  if ((status = nc_put_var_float(grp_coor, varid1, &lat_out[0][0])))
12093  check_err(status, __LINE__, __FILE__);
12094 
12095  if ((status = nc_put_var_float(grp_coor, varid2, &lon_out[0][0])))
12096  check_err(status, __LINE__, __FILE__);
12097 
12098 
12099  //alloc mem for output variables obs_per_view and I as part of the observation_data group
12100  data_out = allocate3d_int(NY, NX,NVIEWS);
12101  data_out2 = allocate4d_float(NY, NX,NVIEWS,NBANDS);
12102 
12103  //BINCOUNT ARRAY
12104  for (size_t v = 0; v < NVIEWS; v++) {
12105  for (int i = NY1; i < NY2 + 1; i++) {
12106  for (int j = 0; j < NX; j++) {
12107  data_out[i][j][v]=0;
12108  // if(v==0 & bincount[v][0][i][j]>0) Igeo_out[NY - 1 - c][NX - 1 - j]+=binmean_Lt[v][0][i][j] / bincount[v][0][i][j];
12109  }}}
12110 
12111  cout << "writing Lt for all bands.."<< endl;
12112  // if ((status = nc_put_var_float(grp_obs, varid3, &Igeo_out[0][0])))
12113  // check_err(status, __LINE__, __FILE__);
12114 
12115 
12116  c = 0;
12117 
12118  for (size_t v = 0; v < NVIEWS; v++) {
12119  for (int i = NY1; i < NY2 + 1; i++) {
12120  for (int j = 0; j < NX; j++) {
12121  for (sb = 0;sb < nbands;sb++) {
12122  if(bincount[v][sb][i][j]>0)
12123  data_out[NY - 1 - c][NX - 1 - j][v]+=bincount[v][sb][i][j];
12124  else
12125  data_out[NY - 1 - c][NX - 1 - j][v]+=0;
12126  }
12127  }
12128  c++;
12129  }
12130  c=0;
12131  }
12132 
12133 
12134 
12135  cout << "writing countbin for all band ."<< endl;
12136  if ((status = nc_put_var_int(grp_obs, varid_count, &data_out[0][0][0])))
12137  check_err(status, __LINE__, __FILE__);
12138 
12139  // LT ARRAYS
12140  c=0;
12141  for (size_t b = 0;b <NBANDS;b++) {
12142  for (size_t v = 0; v < NVIEWS; v++) {
12143  for (int i = NY1; i < NY2 + 1; i++) {
12144  for (int j = 0; j < NX; j++) {
12145  if (bincount[v][b][i][j] > 0)
12146  data_out2[NY - 1 - c][NX - 1 - j][v][b] = binmean_Lt[v][b][i][j] / bincount[v][b][i][j];
12147  else data_out2[NY - 1 - c][NX - 1 - j][v][b] = NAN;
12148  }
12149  c++;
12150  }
12151  c=0;
12152  }//end views
12153  }//end for bands
12154 
12155 
12156 
12157  cout << "writing Lt for all bands.."<< endl;
12158  if ((status = nc_put_var_float(grp_obs, varid_lt, &data_out2[0][0][0][0])))
12159  check_err(status, __LINE__, __FILE__);
12160 
12161  // delete [] (Igeo_out);
12162  if(data_out!=nullptr)
12163  delete [] (data_out);
12164  if(data_out2!=nullptr)
12165  delete [] (data_out2);
12166  if(lat_out!=nullptr)
12167  delete[](lat_out);
12168  if(lon_out!=nullptr)
12169  delete[](lon_out);
12170  if(bincount!=nullptr)
12171  delete[](bincount);
12172  if(binmean_Lt!=nullptr)
12173  delete[](binmean_Lt);
12174 
12175  if ((status = nc_close(ncid_out)))
12176  check_err(status, __LINE__, __FILE__);
12177 
12178 
12179  lat_out = nullptr;;
12180  lon_out = nullptr;
12181  data_out = nullptr;
12182  data_out2 = nullptr;
12183  bincount = nullptr;
12184  binmean_Lt = nullptr;
12185 
12186  flag_donefile = 0;
12187  }//end writing file
12188  }//end for files loop
12189 
12190  cout << "group k at the end of big loop" << k + 1 << endl;
12191 
12192 
12193  }//groups
12194 
12195  cout << "number of files per swath.." << nfiles_swt[swtd - 1] << "for swath.." << swtd << endl;
12196  cout << "total inpix.." << inpix << "total pix.." << totpix << endl;
12197  // cout<<"binned pixels.."<<inpix<<"as %.."<<(inpix/(num_pixels*num_scans*n_files*nfiles_swt[swtd-1]))*100<<endl;
12198  delete[](lat_asort);
12199  // delete [] (lon_asort);
12200  delete[](index_xy);
12201  // delete [] (index_xy2);
12202  delete[](dlatb_g);
12203  delete[](dlonb_g);
12204 
12205  delete[](lat_gd);
12206  delete[](lon_gd);
12207  delete[](az_east);
12208 
12209  printf("*** SUCCESS writing bincount and binLt rasters as nc..!\n");
12210  cout << "finish processing swath eq crossing day..." << swtd << endl;
12211  cout << "done writing Lt to nc file.." << endl;
12212 
12213  return(0);
12214  }
12215 
12216 
12217  //similar to w3 version but band groups merged in one array with indexes following Don l1b_ocis.c convention
12218  int32_t L1C::binL1C_wgranule5(int swtd, l1c_filehandle* l1cfile, L1C_input* l1cinput, int16_t* swtd_id, int16_t* odir, int16_t* file_id, int16_t* nfiles_swt) {
12219  size_t ybins,xbins;
12220  int32_t gdlines_group, ngroups = 0, num_gridlines, nbinx, inpix = 0, outpix = 0, totpix = 0, n_gdlines;//number of gridlines to be processed
12221  float minv = 0., maxv = 0., ** dlatb_g, ** dlonb_g;
12222  int16_t fi = 0;
12223  std::string str;
12224  const char* ptstr;
12225  int dimid, status, ncid_out,ncid_az,ncid_grid,x_dimid,y_dimid, varid, varid2, varid3, azId,NDIMS;
12226  size_t start[] = { 0, 0 };
12227  size_t count[] = { 1, 1 };
12228  size_t start2[] = { 0, 0, 0 };
12229  size_t count2[] = { 1, 1, 1 }, count3[] = { 1, 1, 1 }, count4[] = { 1, 1, 1 };
12230  int32_t bin_xpix, bin_ypix;
12231  float* latpix, * lonpix, ** Lt_pix, ** Lt_pix2, ** Lt_pix3,mean_az_east;
12232 
12233  float latmin_swt = 100, latmax_swt = 0, lonmin_swt = 0, lonmax_swt = 0;
12234  int dimids[2];
12235  const char* filename_lt;
12236  int32_t NY = -1, NX = -1, NY1 = -1, NY2 = -1, c1 = 1;
12237  float** data_out, ** data_out2, ** data_out3, ** lat_out, ** lon_out;
12238  int last_file, last_sline, flag_inpix, flag_donefile;;//first index file id, second index line #
12239  short** index_xy;
12240  float** lat_asort;
12241  bool boolbin1;
12242 
12243  int16_t selyear = -1, selmon = -1, selday = -1;
12244  float** lat_gd, ** lon_gd, * az_east;
12245  string gridname, azeast_name;
12246  float*** bincount = NULL, *** bincount2 = NULL, *** bincount3 = NULL, *** binmean_Lt = nullptr, *** binmean_Lt2 = nullptr, *** binmean_Lt3 = nullptr;
12247  double gres = (l1cinput->gres) * 1000, dlamin, dlamax, dlomin, dlomax;
12248  int grp_root, grp_blue, grp_red, grp_swir, grp_coor,geoGrp;
12249  unsigned int bb = 0, rb = 0, swb = 0;
12250  float sum=0,tot=0;
12251  char tmp[256];
12252 
12253 
12254  Geodesic geod(Constants::WGS84_a(), Constants::WGS84_f());
12255 
12256 
12257 
12258  //random seed
12259  srand((unsigned int)time(NULL));
12260  //nadir pixel ofr OCI
12261  int nadpix = l1cfile->nadpix;
12262 
12263 
12264  num_gridlines = 4000;
12265  nbinx = l1cfile->nbinx;
12266  num_pixels = l1cfile->npix;
12267 
12268  size_t sfiles = 0;
12269 
12270  if (l1cfile->selgran[0] < 0)//process all granules
12271  {
12272  sfiles = nfiles_swt[swtd - 1];
12273  for (unsigned int j = 0;j < sfiles;j++) l1cfile->selgran[j] = j + 1;
12274  }
12275  else {
12276  while (l1cfile->selgran[sfiles] > 0) {
12277  cout << "selected granule #..........................." << l1cfile->selgran[sfiles] << endl;
12278  sfiles++;
12279  }
12280  }
12281 
12282  cout<<"binning Lt using sbs2 method and composite indexes for arrays..................................................................."<<endl;
12283 
12284 
12285  //allocate mem for lat/lon/azeast pointers---
12286  selday = l1cinput->selday;
12287  selmon = l1cinput->selmon;
12288  selyear = l1cinput->selyear;
12289 
12290  std::string fname_out, pathstr, senstr, monstr, daystr, yearstr, prodstr, gdstr, swtstr, swtnum, extstr, granstr,timestr,azstr,missionstr;
12291 
12292  pathstr = "out/";
12293  missionstr="PACE";
12294  senstr = "OCIS";
12295  monstr = std::to_string(selmon);
12296  daystr = std::to_string(selday);
12297  yearstr = std::to_string(selyear);
12298  timestr="T00:00:00Z";
12299  prodstr = "L1Cgrid";
12300  swtstr = "_swt";
12301  extstr = ".nc";
12302 
12303  if (l1cfile->l1c_pflag >= 3) {
12304  swtd = l1cfile->swtnum;
12305  swtnum = std::to_string(swtd);
12306  cout << "swtnum.." << swtnum << endl;
12307  }
12308  else swtnum = std::to_string(swtd);
12309 
12310 
12311  //************************************************************
12312  //mem allocation for geolcoation pointers---
12313  az_east = (float*)calloc(num_gridlines , sizeof(float));
12314  lat_gd = allocate2d_float(num_gridlines, nbinx);
12315  lon_gd = allocate2d_float(num_gridlines, nbinx);
12316 
12317  getcwd(tmp, 256);
12318  pathstr=tmp;
12319 
12320 //open lat/lon L1C grid --------------------------------------
12321  //PACE_OCIS.2019321T00:00:00ZL1Cgrid.nc
12322  prodstr = "L1Cgrid";
12323  gridname = pathstr + "/out/"+missionstr + "_" + senstr + "." + yearstr + monstr + daystr + timestr + prodstr+extstr;
12324 
12325  //open file
12326  ptstr = gridname.c_str();
12327  status = nc_open(ptstr, NC_NOWRITE, &ncid_grid);
12328  if (status != NC_NOERR) {
12329  fprintf(stderr, "nc_open error.\n");
12330  exit(EXIT_FAILURE);
12331  }
12332  //groups
12333  status = nc_inq_grp_ncid(ncid_grid, "geolocation_data", &geoGrp);
12334  check_err(status, __LINE__, __FILE__);
12335 
12336  status = nc_inq_dimid(ncid_grid, "bins_along_track", &y_dimid);
12337  check_err(status, __LINE__, __FILE__);
12338  nc_inq_dimlen(ncid_grid, y_dimid, &ybins);
12339  status = nc_inq_dimid(ncid_grid, "bins_across_track", &x_dimid);
12340  check_err(status, __LINE__, __FILE__);
12341 
12342  nc_inq_dimlen(ncid_grid, x_dimid, &xbins);
12343  nc_inq_dimlen(ncid_grid, y_dimid, &ybins);
12344 
12345  status = nc_inq_varid(geoGrp, "latitude", &latId);//scans x velements
12346  check_err(status, __LINE__, __FILE__);
12347  status = nc_inq_varid(geoGrp, "longitude", &lonId);//scans x velements
12348  check_err(status, __LINE__, __FILE__);
12349  status = nc_get_var_float(geoGrp, latId, &lat_gd[0][0]);
12350  check_err(status, __LINE__, __FILE__);
12351  status = nc_get_var_float(geoGrp, lonId, &lon_gd[0][0]);
12352  check_err(status, __LINE__, __FILE__);
12353 //close file
12354  if ((status = nc_close(ncid_grid)))
12355  check_err(status, __LINE__, __FILE__);
12356 
12357 
12358  //open az_east ------
12359  //PACE_OCIS.2019321T00:00:00Zaz_east.nc
12360  prodstr = "az_east";
12361 // cout << "Current working directory: " << tmp << endl;
12362  azstr= pathstr + "/out/"+missionstr + "_" + senstr + "." + yearstr + monstr + daystr + timestr + prodstr+extstr;
12363  ptstr = azstr.c_str();
12364  cout <<"Opening file with azimuth east values in degrees............" << ptstr << endl;
12365  // ptstr="/accounts/mamontes/images/OCIS/sean/out/PACE_OCIS.2019321T00:00:00Zaz_east.nc";
12366 
12367  status = nc_open(ptstr, NC_NOWRITE, &ncid_az);
12368  if (status != NC_NOERR) {
12369  fprintf(stderr, "nc_open error.\n");
12370  exit(EXIT_FAILURE);
12371  }
12372  status = nc_inq_dimid(ncid_az, "bins_along_track", &y_dimid);
12373  check_err(status, __LINE__, __FILE__);
12374  nc_inq_dimlen(ncid_az, y_dimid, &ybins);
12375 
12376  status = nc_inq_varid(ncid_az, "az_east", &azId);//scans x velements
12377  check_err(status, __LINE__, __FILE__);
12378  status = nc_get_var_float(ncid_az, azId, &az_east[0]);
12379  check_err(status, __LINE__, __FILE__);
12380  for(size_t i=0;i<ybins;i++){
12381  sum = az_east[i];
12382  tot += sum;
12383  }
12384 //close file
12385  if ((status = nc_close(ncid_az)))
12386  check_err(status, __LINE__, __FILE__);
12387 
12388  //using swath-averaged az_east for nadir pixels rather than along-track az_east pixel-by-pixel
12389  mean_az_east = tot / (ybins);
12390 
12391  l1cfile->mean_az_east=mean_az_east; //in degrees
12392  cout<<"mean_az_east in degrees...."<<mean_az_east<<endl;
12393 
12394 
12395 
12396  //determine # of gd groups to be processede
12397  //gdlines_group=num_gridlines;//ONE BIG GROUP
12398  gdlines_group = 250;
12399 
12400  if (num_gridlines <= gdlines_group) {
12401  gdlines_group = num_gridlines;
12402  cout << "WARNING********************* number_gridlines<=gdlines_group THEN gdlines_group=num_gridlines **************" << endl;
12403  }
12404 
12405  ngroups = floor(num_gridlines / gdlines_group);
12406  cout << "TOTAL # of gd groups.(ALL LATs...." << ngroups << endl;
12407 
12408  //--NORMALIZED gridline longitude is -180 to 180 degrees before comparison with longitude extracted from image pixels---
12409  for (int i = 0; i < num_gridlines; i++) {
12410  for (int j = 0; j < nbinx; j++) {
12411  if (lon_gd[i][j] < -180.)lon_gd[i][j] += 360.;
12412  if (lon_gd[i][j] > 180.)lon_gd[i][j] -= 360.;
12413  }
12414  }
12415  //get min/max lat/lon of the swath
12416  // Assume first element as maximum and minimum
12417  maxv = lat_gd[0][0];
12418  minv = lat_gd[0][0];
12419 
12420  //Find maximum and minimum in all array elements.
12421  for (int i = 0; i < num_gridlines; i++) {
12422  for (int j = 0; j < nbinx; j++) {
12423  if (lat_gd[i][j] > maxv)
12424  maxv = lat_gd[i][j];
12425  if (lat_gd[i][j] < minv)
12426  minv = lat_gd[i][j];
12427  }
12428  }
12429 
12430 
12431  maxv = lon_gd[0][0];
12432  minv = lon_gd[0][0];
12433  //Find maximum and minimum in all array elements.
12434  for (int i = 0; i < num_gridlines; i++) {
12435  for (int j = 0; j < nbinx; j++) {
12436  if (lon_gd[i][j] > maxv)
12437  maxv = lon_gd[i][j];
12438  if (lon_gd[i][j] < minv)
12439  minv = lon_gd[i][j];
12440  }
12441  }
12442 
12443 
12444 
12445  cout << "swath #.." << swtd << endl;
12446 
12447  //check lat bound min/max of each gd group---
12448  int k = 0, i = 0;
12449 
12450  dlatb_g = allocate2d_float(ngroups + 1, 2);
12451  dlonb_g = allocate2d_float(ngroups + 1, 2);
12452 
12453  //recompute number of gridlines based on lat limits -80 to 80 degrees
12454  //asc orbit goes from negative to positive latitude....
12455  NY = num_gridlines;
12456  NX = nbinx;
12457  for (int i = 0; i < NY; i++) {
12458  for (int j = 0; j < NX; j++) {
12459  if (lat_gd[i][j] >= -80.) c1++;
12460  if (c1 == nbinx) {
12461  NY1 = i;
12462  }
12463  }
12464  if (NY1 >= 0) break;
12465  c1 = 1;
12466  }
12467 
12468 
12469  for (int i = 0;i < NY; i++) {
12470  // cout<<"i.."<<i<<"lat_gd[i][j]..."<<lat_gd[i][nadpix]<<endl;
12471  for (int j = 0; j < NX; j++) {
12472  if (lat_gd[i][j] >= 80.) {
12473  NY2 = i - 1;
12474  }
12475  }
12476 
12477  if (NY2 >= 0) break;
12478  }
12479 
12480  // cout<<"gridlines limited to -80 to 80 degrees of latitutde.."<<"gdline ini.."<<NY1<<"gdline end.."<<NY2<<endl;
12481 
12482  l1cfile->NY1 = NY1;
12483  l1cfile->NY2 = NY2;
12484 
12485  cout << "NY.." << NY << "NY1.." << NY1 << "NY2.." << NY2 << endl;
12486 
12487 
12488 
12489  num_gridlines = NY2 - NY1 + 1;//this is the # gridlines after -80 to 80 lat constraint---
12490  ngroups = floor(num_gridlines / gdlines_group);
12491  cout << "gdlines will start in gline.." << i + 1 << "ROUNDED ngroups after adjusting beginning.for constraint lat (-80 to 80)" << ngroups << endl;
12492 
12493  //for each 'grid' group scan the swath files to see if there are scanlines within--
12494  //if that is case check the across-bin number position (0 to binx-1) based on latnad and lonnad values---
12495  last_file = 0;
12496  last_sline = 0;
12497  flag_donefile = 0;
12498 
12499  if (num_gridlines > ngroups * gdlines_group) ngroups += 1;
12500 
12501 
12502  //*********** SORTING LAT/LON ASCENDING AND TRACK INDEXES ****************************
12503  //***********************************************************************************
12504 
12505  //Create index matrix for i and j of each lat and lon L1C grid (-80 to 80)
12506  //num_gridlines x nbinx
12507  index_xy = allocate2d_short(num_gridlines, nbinx);
12508  lat_asort = allocate2d_float(num_gridlines, nbinx);
12509  // lon_asort=allocate2d_float(num_gridlines,nbinx);
12510  //fill indexe
12511 
12512  //define 1-D vector to sort 1 col L1C grid at the time---
12513  vector<pair<float, int> > vp;
12514 
12515  //fill vector with lat_gd column--
12516  cout << "*********** SORTING LAT/LON GRIDPOINTS AND TRACKING INDEXES ********************" << endl;
12517 
12518  for (int col = 0;col < nbinx;col++) {
12519  for (int row = NY1;row < NY2 + 1;row++) {
12520  vp.push_back(make_pair(lat_gd[row][col] + 90., row));
12521  }
12522  //sort
12523  stable_sort(vp.begin(), vp.end());
12524  //display lat in order along with its gridpoint index--
12525  // cout << "Lat value\t"
12526  // << "index" << endl;
12527  for (unsigned int i = 0; i < vp.size(); i++) {
12528  lat_asort[i][col] = vp[i].first;
12529  index_xy[i][col] = vp[i].second;
12530  }
12531  vp.clear();
12532  }
12533 
12534  //saddleback search
12535  short gd_row, gd_col;
12536 
12537  cout << "num_gridlines...." << num_gridlines << "ngroups.." << ngroups << endl;
12538 
12539 
12540  //****************************************************************************************************
12541  //************* BIG LOOP GROUPS ***************************************
12542  cout << "Number of granules to be L1C processed........................................." << sfiles << endl;
12543 
12544 
12545  for (k = 0;k < ngroups;k++) {
12546 
12547  //total gridlines for k groups-----
12548  n_gdlines = (k + 1) * gdlines_group;
12549  cout << "screening k group.." << k + 1 << "last_file.." << last_file << "last_line.." << last_sline << endl;
12550  cout << "number of gridlines so far..." << n_gdlines << endl;
12551  //***** compute deltas for lat_gd index 256 and 257 *******************
12552 
12553  //compute delta_lat and delta_lon based on binres/2 for lower and upper corners of 'nadir' gridpoints of 256 and 257 indexes -----------------
12554  //we need nadir 256 and 257 lat/lon coordinates to compute -delta and +delta, respectively
12555  //we need azimuth and backazimuth and binres/2 to compute deltas ---
12556 
12557  //index 256
12558  geod.Direct(lat_gd[n_gdlines - gdlines_group][256], lon_gd[n_gdlines - gdlines_group][256], az_east[n_gdlines - gdlines_group], gres, dlamin, dlomin);
12559  geod.Direct(lat_gd[n_gdlines - 1][257], lon_gd[n_gdlines - 1][257], az_east[n_gdlines - 1], gres, dlamax, dlomax);
12560 
12561  cout << "dlamin.." << dlamin << "dlomin.." << dlomin << "dlamax.." << dlamax << "dlomax.." << dlomax << endl;
12562 
12563  dlatb_g[k][0] = dlamin;//in DEGREES!!
12564  dlatb_g[k][1] = dlamax;
12565  dlonb_g[k][0] = dlomin;
12566  dlonb_g[k][1] = dlomax;
12567 
12568  //********* LOOP FILES ************************************
12569  for (unsigned int findex = last_file;findex < sfiles;findex++) {
12570 
12571  cout << "Scanning lines in file.. for crossing swath..." << swtd << "selected granule #.." << l1cfile->selgran[findex] << "swt_id.." << swtd_id[findex] << "grid group.." << k + 1 << endl;
12572 
12573  fi = l1cfile->selgran[findex];
12574  str = l1cfile->ifiles[fi - 1];
12575  ptstr = str.c_str();
12576 
12577  cout << "opening filename............" << ptstr << endl;
12578 
12579  status = nc_open(ptstr, NC_NOWRITE, &ncid_L1B);
12580  if (status != NC_NOERR) {
12581  fprintf(stderr, "nc_open error.\n");
12582  exit(EXIT_FAILURE);
12583  }
12584  //Open dimensions
12585  status = nc_inq_dimid(ncid_L1B, "number_of_scans", &dimid);
12586  if (status != NC_NOERR) {
12587  fprintf(stderr, "-E- Error reading number_of_scans.\n");
12588  exit(EXIT_FAILURE);
12589  }
12590  nc_inq_dimlen(ncid_L1B, dimid, &num_scans);
12591 
12592  //read line-by-line lat/lon/Lt
12593  status = nc_inq_grp_ncid(ncid_L1B, "geolocation_data", &geoGrp);
12594  check_err(status, __LINE__, __FILE__);
12595  status = nc_inq_grp_ncid(ncid_L1B, "observation_data", &obsGrp);
12596  check_err(status, __LINE__, __FILE__);
12597  //open geo data
12598  status = nc_inq_varid(geoGrp, "latitude", &latId);//scans x velements
12599  check_err(status, __LINE__, __FILE__);
12600  status = nc_inq_varid(geoGrp, "longitude", &lonId);//scans x velements
12601  check_err(status, __LINE__, __FILE__);
12602  status = nc_inq_varid(obsGrp, "Lt_blue", &Lt_blueId);
12603  check_err(status, __LINE__, __FILE__);
12604  status = nc_inq_varid(obsGrp, "Lt_red", &Lt_redId);
12605  check_err(status, __LINE__, __FILE__);
12606  status = nc_inq_varid(obsGrp, "Lt_SWIR", &Lt_SWIRId);
12607  check_err(status, __LINE__, __FILE__);
12608 
12609 
12610  // num_blue_bands
12611  status = nc_inq_dimid(ncid_L1B, "blue_bands", &dimid);
12612  if (status != NC_NOERR) {
12613  fprintf(stderr, "-E- Error reading num_blue_bands.\n");
12614  exit(EXIT_FAILURE);
12615  }
12616  nc_inq_dimlen(ncid_L1B, dimid, &num_blue_bands);
12617 
12618  // num_red_bands
12619  status = nc_inq_dimid(ncid_L1B, "red_bands", &dimid);
12620  if (status != NC_NOERR) {
12621  fprintf(stderr, "-E- Error reading num_red_bands.\n");
12622  exit(EXIT_FAILURE);
12623  }
12624  nc_inq_dimlen(ncid_L1B, dimid, &num_red_bands);
12625 
12626  // num_SWIR_bands
12627  status = nc_inq_dimid(ncid_L1B, "SWIR_bands", &dimid);
12628  if (status != NC_NOERR) {
12629  fprintf(stderr, "-E- Error reading num_SWIR_bands.\n");
12630  exit(EXIT_FAILURE);
12631  }
12632  nc_inq_dimlen(ncid_L1B, dimid, &num_SWIR_bands);
12633 
12634 
12635  if (last_sline == 0 && binmean_Lt == nullptr && binmean_Lt2 == nullptr && binmean_Lt3 == nullptr) { // binmean_Lt==NULL | bincount==NULL | binmean_Lt2==NULL | bincount2==NULL | binmean_Lt3==NULL | bincount3==NULL){
12636 
12637  cout << "first allocation of memory for grid bins of file #..." << l1cfile->selgran[findex] << endl;
12638 
12639  // cout<<"findex.."<<findex<<"blue bands"<<num_blue_bands<<"red bands.."<<num_red_bands<<"swir bands..."<<num_SWIR_bands<<"nbinx.."<<nbinx<<endl;
12640 
12641  binmean_Lt = allocate3d_float(num_blue_bands, num_gridlines, nbinx);
12642  bincount = allocate3d_float(num_blue_bands, num_gridlines, nbinx);
12643  binmean_Lt2 = allocate3d_float(num_red_bands, num_gridlines, nbinx);
12644  bincount2 = allocate3d_float(num_red_bands, num_gridlines, nbinx);
12645  binmean_Lt3 = allocate3d_float(num_SWIR_bands, num_gridlines, nbinx);
12646  bincount3 = allocate3d_float(num_SWIR_bands, num_gridlines, nbinx);
12647 
12648  for (unsigned int k = 0;k < num_blue_bands;k++) {
12649  for (int i = 0; i < num_gridlines; i++) {
12650  for (int j = 0; j < nbinx; j++) {
12651  bincount[k][i][j] = 0.;
12652  binmean_Lt[k][i][j] = 0.;
12653  }
12654  }
12655  }
12656 
12657  for (unsigned int k = 0;k < num_red_bands;k++) {
12658  for (int i = 0; i < num_gridlines; i++) {
12659  for (int j = 0; j < nbinx; j++) {
12660  bincount2[k][i][j] = 0.;
12661  binmean_Lt2[k][i][j] = 0.;
12662  }
12663  }
12664  }
12665 
12666  for (unsigned int k = 0;k < num_SWIR_bands;k++) {
12667  for (int i = 0; i < num_gridlines; i++) {
12668  for (int j = 0; j < nbinx; j++) {
12669  bincount3[k][i][j] = 0.;
12670  binmean_Lt3[k][i][j] = 0.;
12671  }
12672  }
12673  }
12674 
12675  }//end if first time allocating mem for binning arrays
12676 
12677 
12678  //assigning mem for Lt of different bands **********************
12679  latpix = (float*)calloc(num_pixels , sizeof(float));
12680  lonpix = (float*)calloc(num_pixels , sizeof(float));
12681  Lt_pix = allocate2d_float(num_blue_bands, num_pixels);//blue bands
12682  Lt_pix2 = allocate2d_float(num_red_bands, num_pixels);//red bands
12683  Lt_pix3 = allocate2d_float(num_SWIR_bands, num_pixels);//SWIR bands
12684 
12685  cout << "#blue bands.." << num_blue_bands << endl;
12686  cout << "#red bands.." << num_red_bands << endl;
12687  cout << "#swir bands.." << num_SWIR_bands << endl;
12688 
12689 
12690 
12691  //********************************************************************************
12692  //-----reading line by line-----------------------------------
12693  for (unsigned int sline = last_sline;sline < num_scans;sline++) {
12694 
12695  //lat and lon--
12696  start[0] = sline;
12697  start[1] = 0;
12698  count[0] = 1;
12699  count[1] = num_pixels; // 1 line at a time
12700 
12701  status = nc_get_vara_float(geoGrp, latId, start, count, latpix);
12702  status = nc_get_vara_float(geoGrp, lonId, start, count, lonpix);
12703 
12704  //****************************blue bands *********************************************************************
12705  //loop blue bands------------
12706  //*************************************************************************************************************
12707  //Lt
12708 
12709  start2[0] = 0;
12710  start2[1] = sline;
12711  start2[2] = 0;
12712 
12713  count2[0] = num_blue_bands;
12714  count2[1] = 1; // 1 line at a time
12715  count2[2] = num_pixels;
12716 
12717  count3[0] = num_red_bands;
12718  count3[1] = 1; // 1 line at a time
12719  count3[2] = num_pixels;
12720 
12721  count4[0] = num_SWIR_bands;
12722  count4[1] = 1; // 1 line at a time
12723  count4[2] = num_pixels;
12724 
12725  status = nc_get_vara_float(obsGrp, Lt_blueId, start2, count2, Lt_pix[0]);
12726  status = nc_get_vara_float(obsGrp, Lt_redId, start2, count3, Lt_pix2[0]);
12727  status = nc_get_vara_float(obsGrp, Lt_SWIRId, start2, count4, Lt_pix3[0]);
12728 
12729 
12730  /* for(int bb=0;bb<num_blue_bands;bb++){
12731  cout<<"processing blue band #.........................................................................."<<bb+1<<"of total blue bands #.."<<num_blue_bands<<endl;
12732  cout<<"Lt_pix at pix =0..."<<Lt_pix[bb][0]<<"Lt_pix at pix =1..."<<Lt_pix[bb][1]<<endl;
12733  }
12734  exit(1);
12735  */
12736 
12737  for (unsigned int pix = 0;pix < num_pixels;pix++) {
12738  if (latpix[pix] < latmin_swt) latmin_swt = latpix[pix];
12739  if (latpix[pix] > latmax_swt) latmax_swt = latpix[pix];
12740  if (lonpix[pix] < lonmin_swt) lonmin_swt = lonpix[pix];
12741  if (lonpix[pix] > lonmax_swt) lonmax_swt = lonpix[pix];
12742  }
12743 
12744 
12745  //cout<<"latpix[nadpix]..."<<latpix[nadpix]<<"lonpix[nadpix]..."<<lonpix[nadpix]<<endl;
12746  // cout<<"dlatb_g[k][0]...."<<dlatb_g[k][0]<<"dlatb_g[k][1]...."<<dlatb_g[k][1]<<endl;
12747 
12748 
12749  dlamin = 0.;dlamax = 0.;
12750  //inside the 'k' box??----- ascending ----------
12751  if (latpix[nadpix] >= dlatb_g[k][0] && latpix[nadpix] <= dlatb_g[k][1]) {
12752 
12753  if (sline % 100 == 0) cout << "EVERY 100 gds..for k group.." << k + 1 << "file number #.." << l1cfile->selgran[findex] << "sline..." << sline + 1 << "# of binned pix.." << inpix << "outpix.." << outpix << endl;
12754 
12755  //*********** BIG LOOP M_PIXEL *****************************************************************
12756  for (unsigned int pix = 0;pix < num_pixels;pix++) {
12757 
12758  bb = 0, rb = 0, swb = 0;
12759  flag_inpix = 0;
12760 
12761  boolbin1 = sbs2_l1c(l1cinput, num_gridlines, nbinx, lat_asort, index_xy, latpix[pix], lonpix[pix], lon_gd, &gd_row, &gd_col);
12762 
12763  bin_ypix = gd_row + 1;
12764  bin_xpix = gd_col + 1;
12765 
12766  // cout<<"pix..."<<pix+1<<"latpix..."<<latpix[pix]<<"lonpix..."<<lonpix[pix]<<endl;
12767 
12768  if (boolbin1 == 1) flag_inpix = 1;
12769  //************ BINNING ***************************
12770  //assign identified pixel to Lt and bin stat arrays-----
12771  //BLUE---
12772  if (flag_inpix == 1 && bin_xpix >= 1 && bin_ypix >= 1 && bin_xpix <= nbinx && bin_ypix <= num_gridlines) {
12773  inpix++;
12774  while (bb < num_blue_bands) {
12775  if (Lt_pix[bb][pix] > 0.) {
12776  binmean_Lt[bb][bin_ypix - 1][bin_xpix - 1] = binmean_Lt[bb][bin_ypix - 1][bin_xpix - 1] + Lt_pix[bb][pix];
12777  bincount[bb][bin_ypix - 1][bin_xpix - 1] += 1;
12778  }
12779  bb++;
12780  }//end while blue band band
12781  //RED---
12782  while (rb < num_red_bands) {
12783  if (Lt_pix2[rb][pix] > 0.) {
12784  binmean_Lt2[rb][bin_ypix - 1][bin_xpix - 1] = binmean_Lt2[rb][bin_ypix - 1][bin_xpix - 1] + Lt_pix2[rb][pix];
12785  bincount2[rb][bin_ypix - 1][bin_xpix - 1] += 1;
12786  }
12787  rb++;
12788  }//end red bands
12789 
12790  //SWIR----
12791  while (swb < num_SWIR_bands) {
12792  if (Lt_pix3[swb][pix] > 0.) {
12793  binmean_Lt3[swb][bin_ypix - 1][bin_xpix - 1] = binmean_Lt3[swb][bin_ypix - 1][bin_xpix - 1] + Lt_pix3[swb][pix];
12794  bincount3[swb][bin_ypix - 1][bin_xpix - 1] += 1;
12795  }
12796  swb++;
12797  }//end swir bands
12798 
12799  }//end if inpix
12800 
12801  //********** pixel AREA WEIGHTING ************************
12802  if (flag_inpix == 0) outpix++;
12803 
12804  totpix++;
12805 
12806  }//end pixels loop
12807 
12808 
12809 
12810 
12811  //END OF FILE--****** reset starting sline index if last line processed and within k box
12812  //go for another granule if it is not the last one---------------
12813  if (sline == num_scans - 1) {
12814  flag_donefile = 1;
12815  cout << "end of file..." << l1cfile->selgran[findex] << endl;
12816  last_sline = 0;
12817  if (findex >= sfiles - 1) {
12818  cout << "done with last granule of the input list........................." << endl;
12819  // findex=sfiles;
12820  k = ngroups;
12821  break;
12822  }
12823 
12824  }//end of file/last file? sliine=num_scans-1
12825  else flag_donefile = 0;
12826 
12827  }//end latpix nadir of line x inside grid group?
12828 
12829  //***** skip lines and files if sline is not within k group ********
12830  //increase k and screen files and lines again starting from the last binning
12831 
12832  if (latpix[nadpix] > lat_gd[n_gdlines - 1][257] && k < ngroups - 1) { //else limits
12833  cout << "moving to the next k group...scanning again files/slines.." << endl;
12834  cout << "file index.." << findex << "last sline index.." << sline << endl;
12835  last_file = findex;
12836  last_sline = sline;
12837  findex = sfiles;
12838  sline = num_scans - 1;
12839  }//end if lat >grid lat--IF outside the box
12840 
12841  if (sline + 1 % 100 == 0) cout << "for k group.." << k + 1 << "selected granule #.." << l1cfile->selgran[findex] << "sline..." << sline + 1 << "# of binned pix.." << inpix << "totpix.." << totpix << "outpix.." << outpix << endl;
12842  }//end for scanlines
12843 
12844  cout << "closing L1B file......." << ptstr << endl;
12845  status = nc_close(ncid_L1B);
12846  check_err(status, __LINE__, __FILE__);
12847 
12848  delete[](latpix);
12849  delete[](lonpix);
12850  delete[](Lt_pix);
12851  delete[](Lt_pix2);
12852  delete[](Lt_pix3);
12853 
12854 
12855 
12856 
12857  //**********************************************************************************************************************************
12858  //**********************************************************************************************************************************
12859  //writing each granule ---------------------------------
12860  //*****************************************************************************
12861 
12862  if (flag_donefile == 1 | (flag_donefile == 0 && k == ngroups - 1)) {
12863  cout << "writing file #.............................................." << l1cfile->selgran[findex] << "based on group #.." << k + 1 << endl;
12864  //write mean Lt as nc file---
12865  //**********************************************************************
12866  //**********************************************************************8
12867  //create Lt file
12868  pathstr = "out/";
12869  senstr = "OCIS_";
12870  monstr = std::to_string(selmon);
12871  daystr = std::to_string(selday);
12872  yearstr = std::to_string(selyear);
12873  prodstr = "binLt_sbs";
12874  swtstr = "_swt";
12875  granstr = "";
12876  granstr = "_" + std::to_string(l1cfile->selgran[findex]);
12877 
12878  if (l1cfile->l1c_pflag >= 3) {
12879  swtd = l1cfile->swtnum;
12880  swtnum = std::to_string(swtd);
12881  cout << "swtnum.." << swtnum << endl;
12882  }
12883  else swtnum = std::to_string(swtd);
12884  extstr = ".nc";
12885  NDIMS = 2;
12886  fname_out = pathstr + senstr + monstr + daystr + yearstr + prodstr + swtstr + swtnum + granstr + extstr;
12887  filename_lt = fname_out.c_str();
12888 
12889  /* try
12890  {
12891  cout<<"Opening file \"firstFile.nc\" with NcFile::replace"<<endl;
12892  NcFile ncFile("firstFile.nc",NcFile::replace);
12893  NcGroup groupA(ncFile.addGroup("groupA"));
12894  }
12895 
12896  catch (NcException& e)
12897  {
12898  cout << "unknown error"<<endl;
12899  e.what();
12900  }
12901  exit(1);
12902  */
12903 
12904  if ((status = nc_create(filename_lt, NC_CLOBBER | NC_NETCDF4, &ncid_out)))
12905  check_err(status, __LINE__, __FILE__);
12906  //define dims
12907  // Define the dimensions. NetCDF will hand back an ID for each.
12908  NY = num_gridlines;
12909  NX = nbinx;
12910  NY1 = l1cfile->NY1;//these are indexes not line #!!!!!!!!!!!!!!!!!
12911  NY2 = l1cfile->NY2;
12912  cout << "rowgrid ini.." << NY1 << "rowgrid end.." << NY2 << endl;
12913  NY = NY2 - NY1 + 1;
12914  cout << "NY.." << NY << "NX.." << NX << endl;
12915  //alloc mem for data_out and assign values from lat_gdI
12916  //NX AND NY are inverted for visualization in SeaDAS
12917 
12918  // data_out=allocate2d_float(NY,NX);
12919 
12920  /* data_out2 = allocate2d_float(NY,NX);
12921  data_out3 = allocate2d_float(NY,NX);
12922  data_out4 = allocate2d_float(NY,NX);
12923  data_out5 = allocate2d_float(NY,NX);
12924  data_out6 = allocate2d_float(NY,NX);
12925  */
12926  lat_out = allocate2d_float(NY, NX);
12927  lon_out = allocate2d_float(NY, NX);
12928 
12929  int c = 0;
12930 
12931  for (int i = NY1; i < NY2 + 1; i++) {
12932  for (int j = 0; j < NX; j++) {
12933  lat_out[NY - 1 - c][NX - 1 - j] = lat_gd[i][j];
12934  lon_out[NY - 1 - c][j] = lon_gd[i][j];
12935  }
12936  c++;
12937  }
12938 
12939  //blue
12940  /* c=0;
12941  for(bb=0;bb<num_blue_bands;bb++){
12942  for(int i=NY1; i<NY2+1; i++){
12943  for(int j=0; j<NX; j++){
12944  if (bincount[bb][i][j]>0)
12945  data_out[NY-1-c][NX-1-j]=binmean_Lt[bb][i][j]/bincount[bb][i][j];
12946  else data_out[NY-1-c][NX-1-j]=NAN;
12947  }
12948  c++;
12949  }
12950  }//end bands
12951  */
12952 
12953 
12954  //red
12955  /* if (bincount2[i][j]>0)
12956  data_out3[NY-1-c][NX-1-j]=binmean_Lt2[i][j]/bincount2[i][j];
12957  else
12958  data_out3[NY-1-c][NX-1-j]=NAN;
12959  //swir
12960  if (bincount3[i][j]>0)
12961  data_out5[NY-1-c][NX-1-j]=binmean_Lt3[i][j]/bincount3[i][j];
12962  else
12963  data_out5[NY-1-c][NX-1-j]=NAN;
12964 
12965  data_out2[NY-1-c][NX-1-j]=bincount[i][j];
12966  data_out4[NY-1-c][NX-1-j]=bincount2[i][j];
12967  data_out6[NY-1-c][NX-1-j]=bincount3[i][j];
12968  */
12969 
12970  // }
12971  // c++;
12972  // }
12973  // }//end bands
12974 
12975  if ((status = nc_def_dim(ncid_out, "x", NX, &x_dimid)))
12976  check_err(status, __LINE__, __FILE__);
12977  if ((status = nc_def_dim(ncid_out, "y", NY, &y_dimid)))
12978  check_err(status, __LINE__, __FILE__);
12979  //dims for output var
12980  dimids[0] = y_dimid;
12981  dimids[1] = x_dimid;
12982 
12983  //define groups-----
12984  // status = nc_def_grp( *ncid, line.c_str(), &gid[ngrps]);
12985  if ((status = nc_def_grp(ncid_out, "data", &grp_root))) //netcdf-4
12986  check_err(status, __LINE__, __FILE__);
12987  if ((status = nc_def_grp(grp_root, "geo_coordinates", &grp_coor))) //netcdf-4
12988  check_err(status, __LINE__, __FILE__);
12989  if ((status = nc_def_grp(grp_root, "blue_bands", &grp_blue))) //netcdf-4
12990  check_err(status, __LINE__, __FILE__);
12991  if ((status = nc_def_grp(grp_root, "red_bands", &grp_red))) //netcdf-4
12992  check_err(status, __LINE__, __FILE__);
12993  if ((status = nc_def_grp(grp_root, "swir_bands", &grp_swir))) //netcdf-4
12994  check_err(status, __LINE__, __FILE__);
12995 
12996  //def var--------------------
12997 
12998  //loop blue channels-----
12999 
13000  string bb_num, rb_num, swb_num, bb_str = "binLt_blue_ch", rb_str = "binLt_red_ch", swb_str = "binLt_swir_ch";
13001 
13002  int varid_bb[num_blue_bands], varid_rb[num_red_bands], varid_swb[num_SWIR_bands];
13003 
13004  for (bb = 0;bb < num_blue_bands;bb++) {
13005  bb_num = std::to_string(bb + 1);
13006  bb_num = bb_str + bb_num;
13007  if ((status = nc_def_var(grp_blue, bb_num.c_str(), NC_FLOAT, NDIMS, dimids, &varid))) check_err(status, __LINE__, __FILE__);
13008  varid_bb[bb] = varid;
13009  }
13010 
13011  for (rb = 0;rb < num_red_bands;rb++) {
13012  rb_num = std::to_string(rb + 1);
13013  rb_num = rb_str + rb_num;
13014  if ((status = nc_def_var(grp_red, rb_num.c_str(), NC_FLOAT, NDIMS, dimids, &varid))) check_err(status, __LINE__, __FILE__);
13015  varid_rb[rb] = varid;
13016  }
13017 
13018  for (swb = 0;swb < num_SWIR_bands;swb++) {
13019  swb_num = std::to_string(swb + 1);
13020  swb_num = swb_str + swb_num;
13021  if ((status = nc_def_var(grp_swir, swb_num.c_str(), NC_FLOAT, NDIMS, dimids, &varid))) check_err(status, __LINE__, __FILE__);
13022  varid_swb[swb] = varid;
13023  }
13024 
13025  // if ((status = nc_def_var(grp_blue,"whatever", NC_FLOAT, NDIMS,
13026  // dimids, &varid)))
13027 
13028 
13029 
13030  // if ((status = nc_def_var(ncid_out, "bincount_blue", NC_FLOAT, NDIMS,
13031  // dimids, &varid4)))
13032  // check_err(status, __LINE__, __FILE__);
13033  //red
13034  /* if ((status = nc_def_var(ncid_out, "binLt_red", NC_FLOAT, NDIMS,
13035  dimids, &varid5)))
13036  check_err(status, __LINE__, __FILE__);
13037  if ((status = nc_def_var(ncid_out, "bincount_red", NC_FLOAT, NDIMS,
13038  dimids, &varid6)))
13039  check_err(status, __LINE__, __FILE__);
13040  //swir
13041  if ((status = nc_def_var(ncid_out, "binLt_swir", NC_FLOAT, NDIMS,
13042  dimids, &varid7)))
13043  check_err(status, __LINE__, __FILE__);
13044  if ((status = nc_def_var(ncid_out, "bincount_swir", NC_FLOAT, NDIMS,
13045  dimids, &varid8)))
13046  check_err(status, __LINE__, __FILE__);
13047  */
13048 
13049  //lat/lon
13050  if ((status = nc_def_var(grp_coor, "lat_gd", NC_FLOAT, NDIMS,
13051  dimids, &varid2)))
13052  check_err(status, __LINE__, __FILE__);
13053  if ((status = nc_def_var(grp_coor, "lon_gd", NC_FLOAT, NDIMS,
13054  dimids, &varid3)))
13055  check_err(status, __LINE__, __FILE__);
13056  //leave define mode-----------------------
13057  if ((status = nc_enddef(ncid_out))) //done def vars etc
13058  check_err(status, __LINE__, __FILE__);
13059 
13060  //assign variable data------------------------
13061  /* start2[0]=0;
13062  start2[1]=0;
13063  start2[2]=0;
13064 
13065  count2[0]=1;
13066  count2[1]=NY;
13067  count2[2]=NX;
13068 
13069 
13070  float lat_data[NY][NX];
13071 
13072  for (int i=0;i<NY;i++){
13073  for (int j=0;j<NX;j++){
13074  lat_data[i][j]=lat_out[i][j];
13075  }}
13076 
13077  */
13078  // if((status = nc_put_vara_float(ncid_out,varid2,start2,count2,&lat_out[0][0])))
13079  // check_err(status, __LINE__, __FILE__);
13080  // if((status = nc_put_vara(grp_coor,varid3,start,count,lon_out)));
13081  // check_err(status, __LINE__, __FILE__);
13082  // if((status = nc_put_vara(grp_blue,varid,start,count,data_out)));
13083  // check_err(status, __LINE__, __FILE__);
13084 
13085  if ((status = nc_put_var_float(grp_coor, varid2, &lat_out[0][0])))
13086  check_err(status, __LINE__, __FILE__);
13087 
13088  if ((status = nc_put_var_float(grp_coor, varid3, &lon_out[0][0])))
13089  check_err(status, __LINE__, __FILE__);
13090  //blue
13091 
13092  for (bb = 0;bb < num_blue_bands;bb++) {
13093  data_out = allocate2d_float(NY, NX);
13094  c = 0;
13095  for (int i = NY1; i < NY2 + 1; i++) {
13096  for (int j = 0; j < NX; j++) {
13097  data_out[NY - 1 - c][NX - 1 - j] = 0.;
13098  }
13099  c++;
13100  }
13101  c = 0;
13102  for (int i = NY1; i < NY2 + 1; i++) {
13103  for (int j = 0; j < NX; j++) {
13104  if (bincount[bb][i][j] > 0)
13105  data_out[NY - 1 - c][NX - 1 - j] = binmean_Lt[bb][i][j] / bincount[bb][i][j];
13106  else data_out[NY - 1 - c][NX - 1 - j] = NAN;
13107  }
13108  c++;
13109  }
13110  cout << "writing blue band#.." << bb + 1 << endl;
13111  if ((status = nc_put_var_float(grp_blue, varid_bb[bb], &data_out[0][0])))
13112  check_err(status, __LINE__, __FILE__);
13113 
13114 
13115  delete[](data_out);
13116  }//end blue bands
13117 
13118 
13119  //red
13120  for (rb = 0;rb < num_red_bands;rb++) {
13121  data_out2 = allocate2d_float(NY, NX);
13122  c = 0;
13123  for (int i = NY1; i < NY2 + 1; i++) {
13124  for (int j = 0; j < NX; j++) {
13125  data_out2[NY - 1 - c][NX - 1 - j] = 0.;
13126  }
13127  c++;
13128  }
13129  c = 0;
13130  for (int i = NY1; i < NY2 + 1; i++) {
13131  for (int j = 0; j < NX; j++) {
13132  if (bincount2[rb][i][j] > 0)
13133  data_out2[NY - 1 - c][NX - 1 - j] = binmean_Lt2[rb][i][j] / bincount2[rb][i][j];
13134  else data_out2[NY - 1 - c][NX - 1 - j] = NAN;
13135  }
13136  c++;
13137  }
13138  cout << "writing red band#.." << rb + 1 << endl;
13139  if ((status = nc_put_var_float(grp_red, varid_rb[rb], &data_out2[0][0])))
13140  check_err(status, __LINE__, __FILE__);
13141 
13142  delete[](data_out2);
13143  }//end red bands
13144 
13145 
13146  //swir
13147  for (swb = 0;swb < num_SWIR_bands;swb++) {
13148  data_out3 = allocate2d_float(NY, NX);
13149  c = 0;
13150  for (int i = NY1; i < NY2 + 1; i++) {
13151  for (int j = 0; j < NX; j++) {
13152  data_out3[NY - 1 - c][NX - 1 - j] = 0.;
13153  }
13154  c++;
13155  }
13156  c = 0;
13157  for (int i = NY1; i < NY2 + 1; i++) {
13158  for (int j = 0; j < NX; j++) {
13159  if (bincount3[swb][i][j] > 0)
13160  data_out3[NY - 1 - c][NX - 1 - j] = binmean_Lt3[swb][i][j] / bincount3[swb][i][j];
13161  else data_out3[NY - 1 - c][NX - 1 - j] = NAN;
13162  }
13163  c++;
13164  }
13165  cout << "writing SWIR band#.." << swb + 1 << endl;
13166  if ((status = nc_put_var_float(grp_swir, varid_swb[swb], &data_out3[0][0])))
13167  check_err(status, __LINE__, __FILE__);
13168 
13169  delete[](data_out3);
13170  }//end red bands
13171 
13172 
13173  /* if ((status = nc_put_var_float(ncid_out, varid4, &data_out2[0][0])))
13174  check_err(status, __LINE__, __FILE__);
13175  //red
13176  if ((status = nc_put_var_float(ncid_out, varid5, &data_out3[0][0])))
13177  check_err(status, __LINE__, __FILE__);
13178  if ((status = nc_put_var_float(ncid_out, varid6, &data_out4[0][0])))
13179  check_err(status, __LINE__, __FILE__);
13180  //swir
13181  if ((status = nc_put_var_float(ncid_out, varid7, &data_out5[0][0])))
13182  check_err(status, __LINE__, __FILE__);
13183  if ((status = nc_put_var_float(ncid_out, varid8, &data_out6[0][0])))
13184  check_err(status, __LINE__, __FILE__);
13185  */
13186 
13187  if ((status = nc_close(ncid_out)))
13188  check_err(status, __LINE__, __FILE__);
13189 
13190  delete[](lat_out);
13191  delete[](lon_out);
13192  // delete [] (data_out);
13193 
13194 
13195  /* delete [] (data_out2);
13196  delete [] (data_out3);
13197  delete [] (data_out4);
13198  delete [] (data_out5);
13199  delete [] (data_out6);
13200  */
13201  delete[](bincount);
13202  delete[](binmean_Lt);
13203  delete[](bincount2);
13204  delete[](binmean_Lt2);
13205  delete[](bincount3);
13206  delete[](binmean_Lt3);
13207 
13208 
13209  lat_out = nullptr;;
13210  lon_out = nullptr;
13211  data_out = nullptr;
13212  data_out2 = nullptr;
13213  data_out3 = nullptr;
13214 
13215 
13216 
13217 
13218  bincount = nullptr;
13219  binmean_Lt = nullptr;
13220  bincount2 = nullptr;
13221  binmean_Lt2 = nullptr;
13222  bincount3 = nullptr;
13223  binmean_Lt3 = nullptr;
13224 
13225  flag_donefile = 0;
13226  }//end writing file
13227  }//end for files
13228 
13229  cout << "group k at the end of big loop" << k + 1 << endl;
13230 
13231  }//groups
13232 
13233  cout << "number of files per swath.." << nfiles_swt[swtd - 1] << "for swath.." << swtd << endl;
13234  cout << "total inpix.." << inpix << "total pix.." << totpix << endl;
13235  // cout<<"binned pixels.."<<inpix<<"as %.."<<(inpix/(num_pixels*num_scans*n_files*nfiles_swt[swtd-1]))*100<<endl;
13236  delete[](lat_asort);
13237  // delete [] (lon_asort);
13238  delete[](index_xy);
13239  // delete [] (index_xy2);
13240  delete[](dlatb_g);
13241  delete[](dlonb_g);
13242 
13243  delete[](lat_gd);
13244  delete[](lon_gd);
13245  delete[](az_east);
13246 
13247  printf("*** SUCCESS writing bincount and binLt rasters as nc..!\n");
13248  cout << "finish processing swath eq crossing day..." << swtd << endl;
13249  cout << "done writing Lt to nc file.." << endl;
13250 
13251  return(0);
13252  }
13253 
13254 
13255 
13256 
13257 
13258  //similar to w2 version byt hyperspectral
13259  int32_t L1C::binL1C_wgranule3(int swtd, l1c_filehandle* l1cfile, L1C_input* l1cinput, int16_t* swtd_id, int16_t* odir, int16_t* file_id, int16_t* nfiles_swt) {
13260  int32_t gdlines_group, ngroups = 0, num_gridlines, nbinx, inpix = 0, outpix = 0, totpix = 0, n_gdlines;//number of gridlines to be processed
13261  float minv = 0., maxv = 0., ** dlatb_g, ** dlonb_g;
13262  int16_t fi = 0;
13263  std::string str;
13264  const char* ptstr;
13265  int dimid, status, ncid_out, x_dimid, y_dimid, varid, varid2, varid3, NDIMS;
13266  size_t start[] = { 0, 0 };
13267  size_t count[] = { 1, 1 };
13268  size_t start2[] = { 0, 0, 0 };
13269  size_t count2[] = { 1, 1, 1 }, count3[] = { 1, 1, 1 }, count4[] = { 1, 1, 1 };
13270  int32_t bin_xpix, bin_ypix;
13271  float* latpix, * lonpix, ** Lt_pix, ** Lt_pix2, ** Lt_pix3;
13272 
13273  float latmin_swt = 100, latmax_swt = 0, lonmin_swt = 0, lonmax_swt = 0;
13274  int dimids[2];
13275  const char* filename_lt;
13276  int32_t NY = -1, NX = -1, NY1 = -1, NY2 = -1, c1 = 1;
13277  float** data_out, ** data_out2, ** data_out3, ** lat_out, ** lon_out;
13278 
13279  int last_file, last_sline, flag_inpix, flag_donefile;;//first index file id, second index line #
13280  short** index_xy;
13281  float** lat_asort;
13282  bool boolbin1;
13283 
13284  int16_t selyear = -1, selmon = -1, selday = -1;
13285  float** lat_gd, ** lon_gd, * az_east;
13286  string gridname, azeast_name;
13287  float*** bincount = NULL, *** bincount2 = NULL, *** bincount3 = NULL, *** binmean_Lt = nullptr, *** binmean_Lt2 = nullptr, *** binmean_Lt3 = nullptr;
13288  double gres = (l1cinput->gres) * 1000, dlamin, dlamax, dlomin, dlomax;
13289  int grp_root, grp_blue, grp_red, grp_swir, grp_coor;
13290  unsigned int bb = 0, rb = 0, swb = 0;
13291  char tmp[256];
13292 
13293 
13294  Geodesic geod(Constants::WGS84_a(), Constants::WGS84_f());
13295 
13296 
13297 
13298  //random seed
13299  srand((unsigned int)time(NULL));
13300  //nadir pixel ofr OCI
13301  int nadpix = l1cfile->nadpix;
13302 
13303 
13304  num_gridlines = 4000;
13305  nbinx = l1cfile->nbinx;
13306  num_pixels = l1cfile->npix;
13307 
13308  size_t sfiles = 0;
13309 
13310  if (l1cfile->selgran[0] < 0)//process all granules
13311  {
13312  sfiles = nfiles_swt[swtd - 1];
13313  for (unsigned int j = 0;j < sfiles;j++) l1cfile->selgran[j] = j + 1;
13314  }
13315  else {
13316  while (l1cfile->selgran[sfiles] > 0) {
13317  cout << "selected granule #..........................." << l1cfile->selgran[sfiles] << endl;
13318  sfiles++;
13319  }
13320  }
13321 
13322  cout<<"binning Lt using sbs2 method and hyperspectral arrays..........................................................................."<<endl;
13323  //allocate mem for lat/lon/azeast pointers---
13324  selday = l1cinput->selday;
13325  selmon = l1cinput->selmon;
13326  selyear = l1cinput->selyear;
13327 
13328  std::string fname_out, pathstr, senstr, monstr, daystr, yearstr, prodstr, gdstr, swtstr, swtnum, extstr, granstr;
13329 
13330 // pathstr = "out/";
13331  senstr = "OCIS_";
13332  monstr = std::to_string(selmon);
13333  daystr = std::to_string(selday);
13334  yearstr = std::to_string(selyear);
13335  prodstr = "L1Cgrid";
13336  swtstr = "_swt";
13337  extstr = ".csv";
13338 
13339  if (l1cfile->l1c_pflag >= 3) {
13340  swtd = l1cfile->swtnum;
13341  swtnum = std::to_string(swtd);
13342  cout << "swtnum.." << swtnum << endl;
13343  }
13344  else swtnum = std::to_string(swtd);
13345 
13346  getcwd(tmp, 256);
13347  pathstr=tmp;
13348  gridname = pathstr + "/out/"+senstr + monstr + daystr + yearstr + prodstr + swtstr + swtnum + extstr;
13349 
13350  prodstr = "az_east";
13351  azeast_name = pathstr + "/out/"+senstr + monstr + daystr + yearstr + prodstr + swtstr + swtnum + extstr;
13352  cout << "gridname.." << gridname << "azeast-name.." << azeast_name << endl;
13353 
13354  //************ OPENING **************************************
13355  //*** AZ_EAST *****************
13356  //*** AZ_EAST *****************
13357  std::string line;
13358  stringstream ss;
13359  std::string temp;
13360  std::vector<std::string> parts;
13361  ifstream fin(azeast_name);
13362  int cline = 0;
13363  while (getline(fin, line))
13364  {
13365  // load line in stringstream
13366  ss << line;
13367  getline(ss, temp, ',');
13368  parts.push_back(temp);
13369  ss.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
13370  ss.clear();
13371  cline++;
13372  }
13373  //minus -1 cause the header
13374  cout << "size of azeast minus heading row..= num_gridlines." << parts.size() - 1 << "nbinx.." << nbinx << endl;
13375  num_gridlines = parts.size() - 1;
13376 
13377 
13378  //**LAT_GD *******************
13379  ifstream fin2(gridname);
13380  std::vector<std::string> tokens_lon, tokens_lat;
13381  std::string token;
13382  cline = 0;
13383  int fcol = 0;
13384  while (getline(fin2, line))
13385  {
13386  // load line in stringstream
13387  istringstream iss(line);
13388  while (getline(iss, token, ','))
13389  {
13390  cline++;
13391  if (fcol == 0 & cline > 2) {
13392  tokens_lon.push_back(token);fcol++;
13393 }
13394  else if (fcol == 1 & cline > 2)
13395  tokens_lat.push_back(token);
13396 
13397  }
13398  fcol = 0;
13399  }
13400 
13401 
13402 
13403 
13404  cout << "size of gridline minus heading row..= num_gridlines." << (tokens_lon.size() - 1) / nbinx << "nbinx.." << nbinx << endl;
13405 
13406 
13407  //************************************************************
13408  //mem allocation for geolcoation pointers---
13409  az_east = (float*)calloc(num_gridlines , sizeof(float));
13410  lat_gd = allocate2d_float(num_gridlines, nbinx);
13411  lon_gd = allocate2d_float(num_gridlines, nbinx);
13412 
13413  float sum = 0, tot = 0;
13414  for (int j = 0;j < num_gridlines;j++) {
13415  // cout<<"j.."<<j<<"az_east"<<std::stof(parts[j+1])<<endl;
13416  az_east[j] = std::stof(parts[j + 1]);//first line is the header
13417  sum = az_east[j];
13418  tot += sum;
13419  }
13420  parts.clear();
13421 
13422 
13423 
13424  //using swath-averaged az_east for nadir pixels rather than along-track az_east pixel-by-pixel
13425  float mean_az_east = tot / (num_gridlines - 1);
13426  cout << "mean_az_east..." << mean_az_east << "numgridlines.." << num_gridlines << endl;
13427  // exit(1);
13428  for (int j = 0;j < num_gridlines;j++) {
13429  az_east[j] = mean_az_east;
13430  }
13431 
13432 
13433  int ip = 0;
13434  for (int j = 0;j < num_gridlines;j++) {
13435  for (int k = 0;k < nbinx;k++) {
13436  lat_gd[j][k] = std::stof(tokens_lat[ip]);
13437  lon_gd[j][k] = std::stof(tokens_lon[ip]);
13438  // if(ip % nbinx == 0) cout<<"ip.."<<ip<<"gdline.."<<j+1<<"binx.."<<k+1<<"latgd.."<<std::stof(tokens_lat[ip])<<"longd.."<<std::stof(tokens_lon[ip])<<endl;
13439  ip++;
13440  }
13441 }
13442  tokens_lon.clear();
13443  tokens_lat.clear();
13444 
13445  //determine # of gd groups to be processede
13446  //gdlines_group=num_gridlines;//ONE BIG GROUP
13447  gdlines_group = 250;
13448 
13449  if (num_gridlines <= gdlines_group) {
13450  gdlines_group = num_gridlines;
13451  cout << "WARNING********************* number_gridlines<=gdlines_group THEN gdlines_group=num_gridlines **************" << endl;
13452  }
13453 
13454  ngroups = floor(num_gridlines / gdlines_group);
13455  cout << "TOTAL # of gd groups.(ALL LATs...." << ngroups << endl;
13456 
13457  //--NORMALIZED gridline longitude is -180 to 180 degrees before comparison with longitude extracted from image pixels---
13458  for (int i = 0; i < num_gridlines; i++) {
13459  for (int j = 0; j < nbinx; j++) {
13460  if (lon_gd[i][j] < -180.)lon_gd[i][j] += 360.;
13461  if (lon_gd[i][j] > 180.)lon_gd[i][j] -= 360.;
13462  }
13463 }
13464  //get min/max lat/lon of the swath
13465  // Assume first element as maximum and minimum
13466  maxv = lat_gd[0][0];
13467  minv = lat_gd[0][0];
13468 
13469  //Find maximum and minimum in all array elements.
13470  for (int i = 0; i < num_gridlines; i++) {
13471  for (int j = 0; j < nbinx; j++) {
13472  if (lat_gd[i][j] > maxv)
13473  maxv = lat_gd[i][j];
13474  if (lat_gd[i][j] < minv)
13475  minv = lat_gd[i][j];
13476  }
13477 }
13478 
13479 
13480  maxv = lon_gd[0][0];
13481  minv = lon_gd[0][0];
13482  //Find maximum and minimum in all array elements.
13483  for (int i = 0; i < num_gridlines; i++) {
13484  for (int j = 0; j < nbinx; j++) {
13485  if (lon_gd[i][j] > maxv)
13486  maxv = lon_gd[i][j];
13487  if (lon_gd[i][j] < minv)
13488  minv = lon_gd[i][j];
13489  }
13490  }
13491 
13492 
13493 
13494  cout << "swath #.." << swtd << endl;
13495 
13496  //check lat bound min/max of each gd group---
13497  int k = 0, i = 0;
13498 
13499  dlatb_g = allocate2d_float(ngroups + 1, 2);
13500  dlonb_g = allocate2d_float(ngroups + 1, 2);
13501 
13502  //recompute number of gridlines based on lat limits -80 to 80 degrees
13503  //asc orbit goes from negative to positive latitude....
13504  NY = num_gridlines;
13505  NX = nbinx;
13506  for (int i = 0; i < NY; i++) {
13507  for (int j = 0; j < NX; j++) {
13508  if (lat_gd[i][j] >= -80.) c1++;
13509  if (c1 == nbinx) {
13510  NY1 = i;
13511  }
13512  }
13513  if (NY1 >= 0) break;
13514  c1 = 1;
13515  }
13516 
13517 
13518  for (int i = 0;i < NY; i++) {
13519  // cout<<"i.."<<i<<"lat_gd[i][j]..."<<lat_gd[i][nadpix]<<endl;
13520  for (int j = 0; j < NX; j++) {
13521  if (lat_gd[i][j] >= 80.) {
13522  NY2 = i - 1;
13523  }
13524  }
13525 
13526  if (NY2 >= 0) break;
13527  }
13528 
13529  // cout<<"gridlines limited to -80 to 80 degrees of latitutde.."<<"gdline ini.."<<NY1<<"gdline end.."<<NY2<<endl;
13530 
13531  l1cfile->NY1 = NY1;
13532  l1cfile->NY2 = NY2;
13533 
13534  cout << "NY.." << NY << "NY1.." << NY1 << "NY2.." << NY2 << endl;
13535 
13536 
13537 
13538  num_gridlines = NY2 - NY1 + 1;//this is the # gridlines after -80 to 80 lat constraint---
13539  ngroups = floor(num_gridlines / gdlines_group);
13540  cout << "gdlines will start in gline.." << i + 1 << "ROUNDED ngroups after adjusting beginning.for constraint lat (-80 to 80)" << ngroups << endl;
13541 
13542  //for each 'grid' group scan the swath files to see if there are scanlines within--
13543  //if that is case check the across-bin number position (0 to binx-1) based on latnad and lonnad values---
13544  last_file = 0;
13545  last_sline = 0;
13546  flag_donefile = 0;
13547 
13548  num_blue_bands = 120;
13549  num_red_bands = 120;
13550  num_SWIR_bands = 9;
13551 
13552  if (num_gridlines > ngroups * gdlines_group) ngroups += 1;
13553 
13554 
13555  //*********** SORTING LAT/LON ASCENDING AND TRACK INDEXES ****************************
13556  //***********************************************************************************
13557 
13558  //Create index matrix for i and j of each lat and lon L1C grid (-80 to 80)
13559  //num_gridlines x nbinx
13560  index_xy = allocate2d_short(num_gridlines, nbinx);
13561  lat_asort = allocate2d_float(num_gridlines, nbinx);
13562  // lon_asort=allocate2d_float(num_gridlines,nbinx);
13563  //fill indexe
13564 
13565  //define 1-D vector to sort 1 col L1C grid at the time---
13566  vector<pair<float, int> > vp;
13567 
13568  //fill vector with lat_gd column--
13569  cout << "*********** SORTING LAT/LON GRIDPOINTS AND TRACKING INDEXES ********************" << endl;
13570 
13571  for (int col = 0;col < nbinx;col++) {
13572  for (int row = NY1;row < NY2 + 1;row++) {
13573  vp.push_back(make_pair(lat_gd[row][col] + 90., row));
13574  }
13575  //sort
13576  stable_sort(vp.begin(), vp.end());
13577  //display lat in order along with its gridpoint index--
13578  // cout << "Lat value\t"
13579  // << "index" << endl;
13580  for (unsigned int i = 0; i < vp.size(); i++) {
13581  lat_asort[i][col] = vp[i].first;
13582  index_xy[i][col] = vp[i].second;
13583  }
13584  vp.clear();
13585  }
13586 
13587  //saddleback search
13588  short gd_row, gd_col;
13589 
13590  cout << "num_gridlines...." << num_gridlines << "ngroups.." << ngroups << endl;
13591 
13592 
13593  //****************************************************************************************************
13594  //************* BIG LOOP GROUPS ***************************************
13595  cout << "Number of granules to be L1C processed........................................." << sfiles << endl;
13596  num_blue_bands = 120;
13597 
13598 
13599 
13600 
13601  for (k = 0;k < ngroups;k++) {
13602 
13603  //total gridlines for k groups-----
13604  n_gdlines = (k + 1) * gdlines_group;
13605  cout << "screening k group.." << k + 1 << "last_file.." << last_file << "last_line.." << last_sline << endl;
13606  cout << "number of gridlines so far..." << n_gdlines << endl;
13607  //***** compute deltas for lat_gd index 256 and 257 *******************
13608 
13609  //compute delta_lat and delta_lon based on binres/2 for lower and upper corners of 'nadir' gridpoints of 256 and 257 indexes -----------------
13610  //we need nadir 256 and 257 lat/lon coordinates to compute -delta and +delta, respectively
13611  //we need azimuth and backazimuth and binres/2 to compute deltas ---
13612 
13613  //index 256
13614  geod.Direct(lat_gd[n_gdlines - gdlines_group][256], lon_gd[n_gdlines - gdlines_group][256], az_east[n_gdlines - gdlines_group], gres, dlamin, dlomin);
13615  geod.Direct(lat_gd[n_gdlines - 1][257], lon_gd[n_gdlines - 1][257], az_east[n_gdlines - 1], gres, dlamax, dlomax);
13616 
13617  cout << "dlamin.." << dlamin << "dlomin.." << dlomin << "dlamax.." << dlamax << "dlomax.." << dlomax << endl;
13618 
13619  dlatb_g[k][0] = dlamin;//in DEGREES!!
13620  dlatb_g[k][1] = dlamax;
13621  dlonb_g[k][0] = dlomin;
13622  dlonb_g[k][1] = dlomax;
13623 
13624  //********* LOOP FILES ************************************
13625  for (unsigned int findex = last_file;findex < sfiles;findex++) {
13626 
13627  cout << "Scanning lines in file.. for crossing swath..." << swtd << "selected granule #.." << l1cfile->selgran[findex] << "swt_id.." << swtd_id[findex] << "grid group.." << k + 1 << endl;
13628 
13629 
13630  if (last_sline == 0 && binmean_Lt == nullptr && binmean_Lt2 == nullptr && binmean_Lt3 == nullptr) { // binmean_Lt==NULL | bincount==NULL | binmean_Lt2==NULL | bincount2==NULL | binmean_Lt3==NULL | bincount3==NULL){
13631 
13632  cout << "first allocation of memory for grid bins of file #..." << l1cfile->selgran[findex] << endl;
13633 
13634  // cout<<"findex.."<<findex<<"blue bands"<<num_blue_bands<<"red bands.."<<num_red_bands<<"swir bands..."<<num_SWIR_bands<<"nbinx.."<<nbinx<<endl;
13635 
13636  binmean_Lt = allocate3d_float(num_blue_bands, num_gridlines, nbinx);
13637  bincount = allocate3d_float(num_blue_bands, num_gridlines, nbinx);
13638  binmean_Lt2 = allocate3d_float(num_red_bands, num_gridlines, nbinx);
13639  bincount2 = allocate3d_float(num_red_bands, num_gridlines, nbinx);
13640  binmean_Lt3 = allocate3d_float(num_SWIR_bands, num_gridlines, nbinx);
13641  bincount3 = allocate3d_float(num_SWIR_bands, num_gridlines, nbinx);
13642 
13643  for (unsigned int k = 0;k < num_blue_bands;k++) {
13644  for (int i = 0; i < num_gridlines; i++) {
13645  for (int j = 0; j < nbinx; j++) {
13646  bincount[k][i][j] = 0.;
13647  binmean_Lt[k][i][j] = 0.;
13648  }
13649 }
13650 }
13651 
13652  for (unsigned int k = 0;k < num_red_bands;k++) {
13653  for (int i = 0; i < num_gridlines; i++) {
13654  for (int j = 0; j < nbinx; j++) {
13655  bincount2[k][i][j] = 0.;
13656  binmean_Lt2[k][i][j] = 0.;
13657  }
13658 }
13659 }
13660 
13661  for (unsigned int k = 0;k < num_SWIR_bands;k++) {
13662  for (int i = 0; i < num_gridlines; i++) {
13663  for (int j = 0; j < nbinx; j++) {
13664  bincount3[k][i][j] = 0.;
13665  binmean_Lt3[k][i][j] = 0.;
13666  }
13667 }
13668 }
13669 
13670  }//end allocating bin arrays
13671 
13672 
13673  fi = l1cfile->selgran[findex];
13674  str = l1cfile->ifiles[fi - 1];
13675  ptstr = str.c_str();
13676 
13677  cout << "opening filename............" << ptstr << endl;
13678 
13679  status = nc_open(ptstr, NC_NOWRITE, &ncid_L1B);
13680  if (status != NC_NOERR) {
13681  fprintf(stderr, "nc_open error.\n");
13682  exit(EXIT_FAILURE);
13683 }
13684  //Open dimensions
13685  status = nc_inq_dimid(ncid_L1B, "number_of_scans", &dimid);
13686  if (status != NC_NOERR) {
13687  fprintf(stderr, "-E- Error reading number_of_scans.\n");
13688  exit(EXIT_FAILURE);
13689  }
13690  nc_inq_dimlen(ncid_L1B, dimid, &num_scans);
13691 
13692  //read line-by-line lat/lon/Lt
13693  status = nc_inq_grp_ncid(ncid_L1B, "geolocation_data", &geoGrp);
13694  check_err(status, __LINE__, __FILE__);
13695  status = nc_inq_grp_ncid(ncid_L1B, "observation_data", &obsGrp);
13696  check_err(status, __LINE__, __FILE__);
13697  //open geo data
13698  status = nc_inq_varid(geoGrp, "latitude", &latId);//scans x velements
13699  check_err(status, __LINE__, __FILE__);
13700  status = nc_inq_varid(geoGrp, "longitude", &lonId);//scans x velements
13701  check_err(status, __LINE__, __FILE__);
13702  status = nc_inq_varid(obsGrp, "Lt_blue", &Lt_blueId);
13703  check_err(status, __LINE__, __FILE__);
13704  status = nc_inq_varid(obsGrp, "Lt_red", &Lt_redId);
13705  check_err(status, __LINE__, __FILE__);
13706  status = nc_inq_varid(obsGrp, "Lt_SWIR", &Lt_SWIRId);
13707  check_err(status, __LINE__, __FILE__);
13708 
13709 
13710  // num_blue_bands
13711  status = nc_inq_dimid(ncid_L1B, "blue_bands", &dimid);
13712  if (status != NC_NOERR) {
13713  fprintf(stderr, "-E- Error reading num_blue_bands.\n");
13714  exit(EXIT_FAILURE);
13715  }
13716  nc_inq_dimlen(ncid_L1B, dimid, &num_blue_bands);
13717 
13718  // num_red_bands
13719  status = nc_inq_dimid(ncid_L1B, "red_bands", &dimid);
13720  if (status != NC_NOERR) {
13721  fprintf(stderr, "-E- Error reading num_red_bands.\n");
13722  exit(EXIT_FAILURE);
13723  }
13724  nc_inq_dimlen(ncid_L1B, dimid, &num_red_bands);
13725 
13726  // num_SWIR_bands
13727  status = nc_inq_dimid(ncid_L1B, "SWIR_bands", &dimid);
13728  if (status != NC_NOERR) {
13729  fprintf(stderr, "-E- Error reading num_SWIR_bands.\n");
13730  exit(EXIT_FAILURE);
13731  }
13732  nc_inq_dimlen(ncid_L1B, dimid, &num_SWIR_bands);
13733  //assigning mem for Lt of different bands **********************
13734  latpix = (float*)calloc(num_pixels , sizeof(float));
13735  lonpix = (float*)calloc(num_pixels , sizeof(float));
13736  Lt_pix = allocate2d_float(num_blue_bands, num_pixels);//blue bands
13737  Lt_pix2 = allocate2d_float(num_red_bands, num_pixels);//red bands
13738  Lt_pix3 = allocate2d_float(num_SWIR_bands, num_pixels);//SWIR bands
13739 
13740  cout << "#blue bands.." << num_blue_bands << endl;
13741  cout << "#red bands.." << num_red_bands << endl;
13742  cout << "#swir bands.." << num_SWIR_bands << endl;
13743 
13744 
13745 
13746  //********************************************************************************
13747  //-----reading line by line-----------------------------------
13748  for (unsigned int sline = last_sline;sline < num_scans;sline++) {
13749 
13750  //lat and lon--
13751  start[0] = sline;
13752  start[1] = 0;
13753  count[0] = 1;
13754  count[1] = num_pixels; // 1 line at a time
13755 
13756  status = nc_get_vara_float(geoGrp, latId, start, count, latpix);
13757  status = nc_get_vara_float(geoGrp, lonId, start, count, lonpix);
13758 
13759  //****************************blue bands *********************************************************************
13760  //loop blue bands------------
13761  //*************************************************************************************************************
13762  //Lt
13763 
13764  start2[0] = 0;
13765  start2[1] = sline;
13766  start2[2] = 0;
13767 
13768  count2[0] = num_blue_bands;
13769  count2[1] = 1; // 1 line at a time
13770  count2[2] = num_pixels;
13771 
13772  count3[0] = num_red_bands;
13773  count3[1] = 1; // 1 line at a time
13774  count3[2] = num_pixels;
13775 
13776  count4[0] = num_SWIR_bands;
13777  count4[1] = 1; // 1 line at a time
13778  count4[2] = num_pixels;
13779 
13780  status = nc_get_vara_float(obsGrp, Lt_blueId, start2, count2, Lt_pix[0]);
13781  status = nc_get_vara_float(obsGrp, Lt_redId, start2, count3, Lt_pix2[0]);
13782  status = nc_get_vara_float(obsGrp, Lt_SWIRId, start2, count4, Lt_pix3[0]);
13783 
13784 
13785  /* for(int bb=0;bb<num_blue_bands;bb++){
13786  cout<<"processing blue band #.........................................................................."<<bb+1<<"of total blue bands #.."<<num_blue_bands<<endl;
13787  cout<<"Lt_pix at pix =0..."<<Lt_pix[bb][0]<<"Lt_pix at pix =1..."<<Lt_pix[bb][1]<<endl;
13788  }
13789  exit(1);
13790  */
13791 
13792  for (unsigned int pix = 0;pix < num_pixels;pix++) {
13793  if (latpix[pix] < latmin_swt) latmin_swt = latpix[pix];
13794  if (latpix[pix] > latmax_swt) latmax_swt = latpix[pix];
13795  if (lonpix[pix] < lonmin_swt) lonmin_swt = lonpix[pix];
13796  if (lonpix[pix] > lonmax_swt) lonmax_swt = lonpix[pix];
13797  }
13798 
13799 
13800  //cout<<"latpix[nadpix]..."<<latpix[nadpix]<<"lonpix[nadpix]..."<<lonpix[nadpix]<<endl;
13801  // cout<<"dlatb_g[k][0]...."<<dlatb_g[k][0]<<"dlatb_g[k][1]...."<<dlatb_g[k][1]<<endl;
13802 
13803  dlamin = 0.;dlamax = 0.;
13804  //inside the 'k' box??----- ascending ----------
13805  if (latpix[nadpix] >= dlatb_g[k][0] && latpix[nadpix] <= dlatb_g[k][1]) {
13806 
13807  if (sline % 100 == 0) cout << "EVERY 100 gds..for k group.." << k + 1 << "file number #.." << l1cfile->selgran[findex] << "sline..." << sline + 1 << "# of binned pix.." << inpix << "outpix.." << outpix << endl;
13808 
13809  //*********** BIG LOOP M_PIXEL *****************************************************************
13810  for (unsigned int pix = 0;pix < num_pixels;pix++) {
13811 
13812  bb = 0, rb = 0, swb = 0;
13813  flag_inpix = 0;
13814 
13815  boolbin1 = sbs2_l1c(l1cinput, num_gridlines, nbinx, lat_asort, index_xy, latpix[pix], lonpix[pix], lon_gd, &gd_row, &gd_col);
13816 
13817  bin_ypix = gd_row + 1;
13818  bin_xpix = gd_col + 1;
13819 
13820  // cout<<"pix..."<<pix+1<<"latpix..."<<latpix[pix]<<"lonpix..."<<lonpix[pix]<<endl;
13821 
13822  if (boolbin1 == 1) flag_inpix = 1;
13823  //************ BINNING ***************************
13824  //assign identified pixel to Lt and bin stat arrays-----
13825  //BLUE---
13826  if (flag_inpix == 1 && bin_xpix >= 1 && bin_ypix >= 1 && bin_xpix <= nbinx && bin_ypix <= num_gridlines) {
13827  inpix++;
13828  while (bb < num_blue_bands) {
13829  if (Lt_pix[bb][pix] > 0.) {
13830  binmean_Lt[bb][bin_ypix - 1][bin_xpix - 1] = binmean_Lt[bb][bin_ypix - 1][bin_xpix - 1] + Lt_pix[bb][pix];
13831  bincount[bb][bin_ypix - 1][bin_xpix - 1] += 1;
13832  }
13833  bb++;
13834  }//end while blue band band
13835  //RED---
13836  while (rb < num_red_bands) {
13837  if (Lt_pix2[rb][pix] > 0.) {
13838  binmean_Lt2[rb][bin_ypix - 1][bin_xpix - 1] = binmean_Lt2[rb][bin_ypix - 1][bin_xpix - 1] + Lt_pix2[rb][pix];
13839  bincount2[rb][bin_ypix - 1][bin_xpix - 1] += 1;
13840  }
13841  rb++;
13842  }//end red bands
13843 
13844  //SWIR----
13845  while (swb < num_SWIR_bands) {
13846  if (Lt_pix3[swb][pix] > 0.) {
13847  binmean_Lt3[swb][bin_ypix - 1][bin_xpix - 1] = binmean_Lt3[swb][bin_ypix - 1][bin_xpix - 1] + Lt_pix3[swb][pix];
13848  bincount3[swb][bin_ypix - 1][bin_xpix - 1] += 1;
13849  }
13850  swb++;
13851  }//end swir bands
13852 
13853  }//end if inpix
13854 
13855  //********** pixel AREA WEIGHTING ************************
13856  if (flag_inpix == 0) outpix++;
13857 
13858  totpix++;
13859 
13860  }//end pixels loop
13861 
13862 
13863 
13864 
13865  //END OF FILE--****** reset starting sline index if last line processed and within k box
13866  //go for another granule if it is not the last one---------------
13867  if (sline == num_scans - 1) {
13868  flag_donefile = 1;
13869  cout << "end of file..." << l1cfile->selgran[findex] << endl;
13870  last_sline = 0;
13871  if (findex >= sfiles - 1) {
13872  cout << "done with last granule of the input list........................." << endl;
13873  // findex=sfiles;
13874  k = ngroups;
13875  break;
13876  }
13877 
13878  }//end of file/last file? sliine=num_scans-1
13879  else flag_donefile = 0;
13880 
13881  }//end latpix nadir of line x inside grid group?
13882 
13883  //***** skip lines and files if sline is not within k group ********
13884  //increase k and screen files and lines again starting from the last binning
13885 
13886  if (latpix[nadpix] > lat_gd[n_gdlines - 1][257] && k < ngroups - 1) { //else limits
13887  cout << "moving to the next k group...scanning again files/slines.." << endl;
13888  cout << "file index.." << findex << "last sline index.." << sline << endl;
13889  last_file = findex;
13890  last_sline = sline;
13891  findex = sfiles;
13892  sline = num_scans - 1;
13893  }//end if lat >grid lat--IF outside the box
13894 
13895  if (sline + 1 % 100 == 0) cout << "for k group.." << k + 1 << "selected granule #.." << l1cfile->selgran[findex] << "sline..." << sline + 1 << "# of binned pix.." << inpix << "totpix.." << totpix << "outpix.." << outpix << endl;
13896  }//end for scanlines
13897 
13898  cout << "closing L1B file......." << ptstr << endl;
13899  status = nc_close(ncid_L1B);
13900  check_err(status, __LINE__, __FILE__);
13901 
13902  delete[](latpix);
13903  delete[](lonpix);
13904  delete[](Lt_pix);
13905  delete[](Lt_pix2);
13906  delete[](Lt_pix3);
13907 
13908 
13909 
13910 
13911  //**********************************************************************************************************************************
13912  //**********************************************************************************************************************************
13913  //writing each granule ---------------------------------
13914  //*****************************************************************************
13915 
13916  if (flag_donefile == 1 | (flag_donefile == 0 && k == ngroups - 1)) {
13917  cout << "writing file #.............................................." << l1cfile->selgran[findex] << "based on group #.." << k + 1 << endl;
13918  //write mean Lt as nc file---
13919  //**********************************************************************
13920  //**********************************************************************8
13921  //create Lt file
13922  pathstr = "out/";
13923  senstr = "OCIS_";
13924  monstr = std::to_string(selmon);
13925  daystr = std::to_string(selday);
13926  yearstr = std::to_string(selyear);
13927  prodstr = "binLt_sbs";
13928  swtstr = "_swt";
13929  granstr = "";
13930  granstr = "_" + std::to_string(l1cfile->selgran[findex]);
13931 
13932  if (l1cfile->l1c_pflag >= 3) {
13933  swtd = l1cfile->swtnum;
13934  swtnum = std::to_string(swtd);
13935  cout << "swtnum.." << swtnum << endl;
13936  }
13937  else swtnum = std::to_string(swtd);
13938  extstr = ".nc";
13939  NDIMS = 2;
13940  fname_out = pathstr + senstr + monstr + daystr + yearstr + prodstr + swtstr + swtnum + granstr + extstr;
13941  filename_lt = fname_out.c_str();
13942 
13943  /* try
13944  {
13945  cout<<"Opening file \"firstFile.nc\" with NcFile::replace"<<endl;
13946  NcFile ncFile("firstFile.nc",NcFile::replace);
13947  NcGroup groupA(ncFile.addGroup("groupA"));
13948  }
13949 
13950  catch (NcException& e)
13951  {
13952  cout << "unknown error"<<endl;
13953  e.what();
13954  }
13955  exit(1);
13956  */
13957 
13958  if ((status = nc_create(filename_lt, NC_CLOBBER | NC_NETCDF4, &ncid_out)))
13959  check_err(status, __LINE__, __FILE__);
13960  //define dims
13961  // Define the dimensions. NetCDF will hand back an ID for each.
13962  NY = num_gridlines;
13963  NX = nbinx;
13964  NY1 = l1cfile->NY1;//these are indexes not line #!!!!!!!!!!!!!!!!!
13965  NY2 = l1cfile->NY2;
13966  cout << "rowgrid ini.." << NY1 << "rowgrid end.." << NY2 << endl;
13967  NY = NY2 - NY1 + 1;
13968  cout << "NY.." << NY << "NX.." << NX << endl;
13969  //alloc mem for data_out and assign values from lat_gdI
13970  //NX AND NY are inverted for visualization in SeaDAS
13971 
13972  // data_out=allocate2d_float(NY,NX);
13973 
13974  /* data_out2 = allocate2d_float(NY,NX);
13975  data_out3 = allocate2d_float(NY,NX);
13976  data_out4 = allocate2d_float(NY,NX);
13977  data_out5 = allocate2d_float(NY,NX);
13978  data_out6 = allocate2d_float(NY,NX);
13979  */
13980  lat_out = allocate2d_float(NY, NX);
13981  lon_out = allocate2d_float(NY, NX);
13982 
13983  int c = 0;
13984 
13985  for (int i = NY1; i < NY2 + 1; i++) {
13986  for (int j = 0; j < NX; j++) {
13987  lat_out[NY - 1 - c][NX - 1 - j] = lat_gd[i][j];
13988  lon_out[NY - 1 - c][j] = lon_gd[i][j];
13989  }
13990  c++;
13991  }
13992 
13993  //blue
13994  /* c=0;
13995  for(bb=0;bb<num_blue_bands;bb++){
13996  for(int i=NY1; i<NY2+1; i++){
13997  for(int j=0; j<NX; j++){
13998  if (bincount[bb][i][j]>0)
13999  data_out[NY-1-c][NX-1-j]=binmean_Lt[bb][i][j]/bincount[bb][i][j];
14000  else data_out[NY-1-c][NX-1-j]=NAN;
14001  }
14002  c++;
14003  }
14004  }//end bands
14005  */
14006 
14007 
14008  //red
14009  /* if (bincount2[i][j]>0)
14010  data_out3[NY-1-c][NX-1-j]=binmean_Lt2[i][j]/bincount2[i][j];
14011  else
14012  data_out3[NY-1-c][NX-1-j]=NAN;
14013  //swir
14014  if (bincount3[i][j]>0)
14015  data_out5[NY-1-c][NX-1-j]=binmean_Lt3[i][j]/bincount3[i][j];
14016  else
14017  data_out5[NY-1-c][NX-1-j]=NAN;
14018 
14019  data_out2[NY-1-c][NX-1-j]=bincount[i][j];
14020  data_out4[NY-1-c][NX-1-j]=bincount2[i][j];
14021  data_out6[NY-1-c][NX-1-j]=bincount3[i][j];
14022  */
14023 
14024  // }
14025  // c++;
14026  // }
14027  // }//end bands
14028 
14029  if ((status = nc_def_dim(ncid_out, "x", NX, &x_dimid)))
14030  check_err(status, __LINE__, __FILE__);
14031  if ((status = nc_def_dim(ncid_out, "y", NY, &y_dimid)))
14032  check_err(status, __LINE__, __FILE__);
14033  //dims for output var
14034  dimids[0] = y_dimid;
14035  dimids[1] = x_dimid;
14036 
14037  //define groups-----
14038  // status = nc_def_grp( *ncid, line.c_str(), &gid[ngrps]);
14039  if ((status = nc_def_grp(ncid_out, "data", &grp_root))) //netcdf-4
14040  check_err(status, __LINE__, __FILE__);
14041  if ((status = nc_def_grp(grp_root, "geo_coordinates", &grp_coor))) //netcdf-4
14042  check_err(status, __LINE__, __FILE__);
14043  if ((status = nc_def_grp(grp_root, "blue_bands", &grp_blue))) //netcdf-4
14044  check_err(status, __LINE__, __FILE__);
14045  if ((status = nc_def_grp(grp_root, "red_bands", &grp_red))) //netcdf-4
14046  check_err(status, __LINE__, __FILE__);
14047  if ((status = nc_def_grp(grp_root, "swir_bands", &grp_swir))) //netcdf-4
14048  check_err(status, __LINE__, __FILE__);
14049 
14050  //def var--------------------
14051 
14052  //loop blue channels-----
14053 
14054  string bb_num, rb_num, swb_num, bb_str = "binLt_blue_ch", rb_str = "binLt_red_ch", swb_str = "binLt_swir_ch";
14055 
14056  int varid_bb[num_blue_bands], varid_rb[num_red_bands], varid_swb[num_SWIR_bands];
14057 
14058  for (bb = 0;bb < num_blue_bands;bb++) {
14059  bb_num = std::to_string(bb + 1);
14060  bb_num = bb_str + bb_num;
14061  if ((status = nc_def_var(grp_blue, bb_num.c_str(), NC_FLOAT, NDIMS, dimids, &varid))) check_err(status, __LINE__, __FILE__);
14062  varid_bb[bb] = varid;
14063  }
14064 
14065  for (rb = 0;rb < num_red_bands;rb++) {
14066  rb_num = std::to_string(rb + 1);
14067  rb_num = rb_str + rb_num;
14068  if ((status = nc_def_var(grp_red, rb_num.c_str(), NC_FLOAT, NDIMS, dimids, &varid))) check_err(status, __LINE__, __FILE__);
14069  varid_rb[rb] = varid;
14070  }
14071 
14072  for (swb = 0;swb < num_SWIR_bands;swb++) {
14073  swb_num = std::to_string(swb + 1);
14074  swb_num = swb_str + swb_num;
14075  if ((status = nc_def_var(grp_swir, swb_num.c_str(), NC_FLOAT, NDIMS, dimids, &varid))) check_err(status, __LINE__, __FILE__);
14076  varid_swb[swb] = varid;
14077  }
14078 
14079  // if ((status = nc_def_var(grp_blue,"whatever", NC_FLOAT, NDIMS,
14080  // dimids, &varid)))
14081 
14082 
14083 
14084  // if ((status = nc_def_var(ncid_out, "bincount_blue", NC_FLOAT, NDIMS,
14085  // dimids, &varid4)))
14086  // check_err(status, __LINE__, __FILE__);
14087  //red
14088  /* if ((status = nc_def_var(ncid_out, "binLt_red", NC_FLOAT, NDIMS,
14089  dimids, &varid5)))
14090  check_err(status, __LINE__, __FILE__);
14091  if ((status = nc_def_var(ncid_out, "bincount_red", NC_FLOAT, NDIMS,
14092  dimids, &varid6)))
14093  check_err(status, __LINE__, __FILE__);
14094  //swir
14095  if ((status = nc_def_var(ncid_out, "binLt_swir", NC_FLOAT, NDIMS,
14096  dimids, &varid7)))
14097  check_err(status, __LINE__, __FILE__);
14098  if ((status = nc_def_var(ncid_out, "bincount_swir", NC_FLOAT, NDIMS,
14099  dimids, &varid8)))
14100  check_err(status, __LINE__, __FILE__);
14101  */
14102 
14103  //lat/lon
14104  if ((status = nc_def_var(grp_coor, "lat_gd", NC_FLOAT, NDIMS,
14105  dimids, &varid2)))
14106  check_err(status, __LINE__, __FILE__);
14107  if ((status = nc_def_var(grp_coor, "lon_gd", NC_FLOAT, NDIMS,
14108  dimids, &varid3)))
14109  check_err(status, __LINE__, __FILE__);
14110  //leave define mode-----------------------
14111  if ((status = nc_enddef(ncid_out))) //done def vars etc
14112  check_err(status, __LINE__, __FILE__);
14113 
14114  //assign variable data------------------------
14115  /* start2[0]=0;
14116  start2[1]=0;
14117  start2[2]=0;
14118 
14119  count2[0]=1;
14120  count2[1]=NY;
14121  count2[2]=NX;
14122 
14123 
14124  float lat_data[NY][NX];
14125 
14126  for (int i=0;i<NY;i++){
14127  for (int j=0;j<NX;j++){
14128  lat_data[i][j]=lat_out[i][j];
14129  }}
14130 
14131  */
14132  // if((status = nc_put_vara_float(ncid_out,varid2,start2,count2,&lat_out[0][0])))
14133  // check_err(status, __LINE__, __FILE__);
14134  // if((status = nc_put_vara(grp_coor,varid3,start,count,lon_out)));
14135  // check_err(status, __LINE__, __FILE__);
14136  // if((status = nc_put_vara(grp_blue,varid,start,count,data_out)));
14137  // check_err(status, __LINE__, __FILE__);
14138 
14139  if ((status = nc_put_var_float(grp_coor, varid2, &lat_out[0][0])))
14140  check_err(status, __LINE__, __FILE__);
14141 
14142  if ((status = nc_put_var_float(grp_coor, varid3, &lon_out[0][0])))
14143  check_err(status, __LINE__, __FILE__);
14144  //blue
14145 
14146  for (bb = 0;bb < num_blue_bands;bb++) {
14147  data_out = allocate2d_float(NY, NX);
14148  c = 0;
14149  for (int i = NY1; i < NY2 + 1; i++) {
14150  for (int j = 0; j < NX; j++) {
14151  data_out[NY - 1 - c][NX - 1 - j] = 0.;
14152  }
14153  c++;
14154  }
14155  c = 0;
14156  for (int i = NY1; i < NY2 + 1; i++) {
14157  for (int j = 0; j < NX; j++) {
14158  if (bincount[bb][i][j] > 0)
14159  data_out[NY - 1 - c][NX - 1 - j] = binmean_Lt[bb][i][j] / bincount[bb][i][j];
14160  else data_out[NY - 1 - c][NX - 1 - j] = NAN;
14161  }
14162  c++;
14163  }
14164  cout << "writing blue band#.." << bb + 1 << endl;
14165  if ((status = nc_put_var_float(grp_blue, varid_bb[bb], &data_out[0][0])))
14166  check_err(status, __LINE__, __FILE__);
14167 
14168 
14169  delete[](data_out);
14170  }//end blue bands
14171 
14172 
14173  //red
14174  for (rb = 0;rb < num_red_bands;rb++) {
14175  data_out2 = allocate2d_float(NY, NX);
14176  c = 0;
14177  for (int i = NY1; i < NY2 + 1; i++) {
14178  for (int j = 0; j < NX; j++) {
14179  data_out2[NY - 1 - c][NX - 1 - j] = 0.;
14180  }
14181  c++;
14182  }
14183  c = 0;
14184  for (int i = NY1; i < NY2 + 1; i++) {
14185  for (int j = 0; j < NX; j++) {
14186  if (bincount2[rb][i][j] > 0)
14187  data_out2[NY - 1 - c][NX - 1 - j] = binmean_Lt2[rb][i][j] / bincount2[rb][i][j];
14188  else data_out2[NY - 1 - c][NX - 1 - j] = NAN;
14189  }
14190  c++;
14191  }
14192  cout << "writing red band#.." << rb + 1 << endl;
14193  if ((status = nc_put_var_float(grp_red, varid_rb[rb], &data_out2[0][0])))
14194  check_err(status, __LINE__, __FILE__);
14195 
14196  delete[](data_out2);
14197  }//end red bands
14198 
14199 
14200  //swir
14201  for (swb = 0;swb < num_SWIR_bands;swb++) {
14202  data_out3 = allocate2d_float(NY, NX);
14203  c = 0;
14204  for (int i = NY1; i < NY2 + 1; i++) {
14205  for (int j = 0; j < NX; j++) {
14206  data_out3[NY - 1 - c][NX - 1 - j] = 0.;
14207  }
14208  c++;
14209  }
14210  c = 0;
14211  for (int i = NY1; i < NY2 + 1; i++) {
14212  for (int j = 0; j < NX; j++) {
14213  if (bincount3[swb][i][j] > 0)
14214  data_out3[NY - 1 - c][NX - 1 - j] = binmean_Lt3[swb][i][j] / bincount3[swb][i][j];
14215  else data_out3[NY - 1 - c][NX - 1 - j] = NAN;
14216  }
14217  c++;
14218  }
14219  cout << "writing SWIR band#.." << swb + 1 << endl;
14220  if ((status = nc_put_var_float(grp_swir, varid_swb[swb], &data_out3[0][0])))
14221  check_err(status, __LINE__, __FILE__);
14222 
14223  delete[](data_out3);
14224  }//end red bands
14225 
14226 
14227  /* if ((status = nc_put_var_float(ncid_out, varid4, &data_out2[0][0])))
14228  check_err(status, __LINE__, __FILE__);
14229  //red
14230  if ((status = nc_put_var_float(ncid_out, varid5, &data_out3[0][0])))
14231  check_err(status, __LINE__, __FILE__);
14232  if ((status = nc_put_var_float(ncid_out, varid6, &data_out4[0][0])))
14233  check_err(status, __LINE__, __FILE__);
14234  //swir
14235  if ((status = nc_put_var_float(ncid_out, varid7, &data_out5[0][0])))
14236  check_err(status, __LINE__, __FILE__);
14237  if ((status = nc_put_var_float(ncid_out, varid8, &data_out6[0][0])))
14238  check_err(status, __LINE__, __FILE__);
14239  */
14240 
14241  if ((status = nc_close(ncid_out)))
14242  check_err(status, __LINE__, __FILE__);
14243 
14244  delete[](lat_out);
14245  delete[](lon_out);
14246  // delete [] (data_out);
14247 
14248 
14249  /* delete [] (data_out2);
14250  delete [] (data_out3);
14251  delete [] (data_out4);
14252  delete [] (data_out5);
14253  delete [] (data_out6);
14254  */
14255  delete[](bincount);
14256  delete[](binmean_Lt);
14257  delete[](bincount2);
14258  delete[](binmean_Lt2);
14259  delete[](bincount3);
14260  delete[](binmean_Lt3);
14261 
14262 
14263  lat_out = nullptr;;
14264  lon_out = nullptr;
14265  data_out = nullptr;
14266  data_out2 = nullptr;
14267  data_out3 = nullptr;
14268 
14269 
14270 
14271 
14272  bincount = nullptr;
14273  binmean_Lt = nullptr;
14274  bincount2 = nullptr;
14275  binmean_Lt2 = nullptr;
14276  bincount3 = nullptr;
14277  binmean_Lt3 = nullptr;
14278 
14279  flag_donefile = 0;
14280  }//end writing file
14281  }//end for files
14282 
14283  cout << "group k at the end of big loop" << k + 1 << endl;
14284 
14285  }//groups
14286 
14287  cout << "number of files per swath.." << nfiles_swt[swtd - 1] << "for swath.." << swtd << endl;
14288  cout << "total inpix.." << inpix << "total pix.." << totpix << endl;
14289  // cout<<"binned pixels.."<<inpix<<"as %.."<<(inpix/(num_pixels*num_scans*n_files*nfiles_swt[swtd-1]))*100<<endl;
14290  delete[](lat_asort);
14291  // delete [] (lon_asort);
14292  delete[](index_xy);
14293  // delete [] (index_xy2);
14294  delete[](dlatb_g);
14295  delete[](dlonb_g);
14296 
14297  delete[](lat_gd);
14298  delete[](lon_gd);
14299  delete[](az_east);
14300 
14301  printf("*** SUCCESS writing bincount and binLt rasters as nc..!\n");
14302  cout << "finish processing swath eq crossing day..." << swtd << endl;
14303  cout << "done writing Lt to nc file.." << endl;
14304 
14305  return(0);
14306  }
14307 
14308 
14309 
14310  //similar to v1 but saving 1 file at the time----
14311  int32_t L1C::binL1C_wgranule2(int swtd, l1c_filehandle* l1cfile, L1C_input* l1cinput, int16_t* swtd_id, int16_t* odir, int16_t* file_id, int16_t* nfiles_swt) {
14312  int32_t gdlines_group,ngroups = 0, num_gridlines, nbinx, inpix = 0, outpix = 0, totpix = 0, n_gdlines;//number of gridlines to be processed
14313  float minv = 0., maxv = 0.,** dlatb_g, ** dlonb_g;
14314  int16_t fi = 0;
14315  std::string str;
14316  const char* ptstr;
14317  int dimid, status, ncid_out, x_dimid, y_dimid, varid, varid2, varid3, varid4, varid5, varid6, varid7, varid8, NDIMS;
14318  size_t start[] = { 0, 0 };
14319  size_t count[] = { 1, 1 };
14320  size_t start2[] = { 0, 0, 0 };
14321  size_t count2[] = { 1, 1, 1 }, count3[] = { 1, 1, 1 }, count4[] = { 1, 1, 1 };
14322 
14323  int32_t bin_xpix, bin_ypix;
14324  float* latpix, * lonpix, ** Lt_pix, ** Lt_pix2, ** Lt_pix3;
14325 
14326  float latmin_swt = 100, latmax_swt = 0, lonmin_swt = 0, lonmax_swt = 0;
14327  int dimids[2];
14328  const char* filename_lt;
14329  int32_t NY = -1, NX = -1, NY1 = -1, NY2 = -1, c1 = 1;
14330  float** data_out, ** data_out2, ** data_out3, ** data_out4, ** data_out5, ** data_out6, ** lat_out, ** lon_out;
14331 
14332 
14333  int last_file, last_sline, flag_inpix,flag_donefile;;//first index file id, second index line #
14334 
14335  short** index_xy;
14336  float** lat_asort;
14337  bool boolbin1;
14338 
14339  int16_t selyear = -1, selmon = -1, selday = -1;
14340  float** lat_gd, ** lon_gd, * az_east;
14341  string gridname, azeast_name;
14342  float** bincount = NULL, ** bincount2 = NULL, ** bincount3 = NULL, ** binmean_Lt = NULL, ** binmean_Lt2 = NULL, ** binmean_Lt3 = NULL;
14343  double gres = (l1cinput->gres) * 1000, dlamin, dlamax, dlomin, dlomax;
14344 
14345  Geodesic geod(Constants::WGS84_a(), Constants::WGS84_f());
14346 
14347  //random seed
14348  srand((unsigned int)time(NULL));
14349  //nadir pixel ofr OCI
14350  int nadpix = l1cfile->nadpix;
14351  num_gridlines = 4000;
14352  nbinx = l1cfile->nbinx;
14353  num_pixels = l1cfile->npix;
14354 
14355  cout<<"computing binning of Lt using sbs2 and some wavelengths......................................................for swtd#.."<<swtd<<endl;
14356  size_t sfiles = 0;
14357 
14358  if (l1cfile->selgran[0] < 0)//process all granules
14359  {
14360  sfiles = nfiles_swt[swtd - 1];
14361  for (unsigned int j = 0;j < sfiles;j++) l1cfile->selgran[j] = j + 1;
14362  }
14363  else {
14364  while (l1cfile->selgran[sfiles] > 0) {
14365  cout << "selected granule #..........................." << l1cfile->selgran[sfiles] << endl;
14366  sfiles++;
14367  }
14368  }
14369 
14370 
14371 
14372  //allocate mem for lat/lon/azeast pointers---
14373  selday = l1cinput->selday;
14374  selmon = l1cinput->selmon;
14375  selyear = l1cinput->selyear;
14376 
14377  std::string fname_out, pathstr, senstr, monstr, daystr, yearstr, prodstr, gdstr, swtstr, swtnum, extstr, granstr;
14378 
14379  pathstr = "out/";
14380  senstr = "OCIS_";
14381  monstr = std::to_string(selmon);
14382  daystr = std::to_string(selday);
14383  yearstr = std::to_string(selyear);
14384  prodstr = "L1Cgrid";
14385  swtstr = "_swt";
14386  extstr = ".csv";
14387 
14388  if (l1cfile->l1c_pflag >= 3) {
14389  swtd = l1cfile->swtnum;
14390  swtnum = std::to_string(swtd);
14391  cout << "swtnum.." << swtnum << endl;
14392  }
14393  else swtnum = std::to_string(swtd);
14394 
14395  gridname = pathstr + senstr + monstr + daystr + yearstr + prodstr + swtstr + swtnum + extstr;
14396 
14397  prodstr = "az_east";
14398  azeast_name = pathstr + senstr + monstr + daystr + yearstr + prodstr + swtstr + swtnum + extstr;
14399  cout << "gridname.." << gridname << "azeast-name.." << azeast_name << endl;
14400 
14401  //************ OPENING **************************************
14402  //*** AZ_EAST *****************
14403  //*** AZ_EAST *****************
14404  std::string line;
14405  stringstream ss;
14406  std::string temp;
14407  std::vector<std::string> parts;
14408  ifstream fin(azeast_name);
14409  int cline = 0;
14410  while (getline(fin, line))
14411  {
14412  // load line in stringstream
14413  ss << line;
14414  getline(ss, temp, ',');
14415  parts.push_back(temp);
14416  // cout<<parts[cline]<<endl;
14417  ss.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
14418  ss.clear();
14419  cline++;
14420  }
14421  //minus -1 cause the header
14422  cout << "size of azeast minus heading row..= num_gridlines." << parts.size() - 1 << "nbinx.." << nbinx << endl;
14423  num_gridlines = parts.size() - 1;
14424 
14425 
14426  //**LAT_GD *******************
14427  ifstream fin2(gridname);
14428  std::vector<std::string> tokens_lon, tokens_lat;
14429  std::string token;
14430  cline = 0;
14431  int fcol = 0;
14432  while (getline(fin2, line))
14433  {
14434  // load line in stringstream
14435  istringstream iss(line);
14436  while (getline(iss, token, ','))
14437  {
14438  cline++;
14439  if (fcol == 0 && cline > 2) {
14440  tokens_lon.push_back(token);fcol++;
14441 }
14442  else if (fcol == 1 && cline > 2)
14443  tokens_lat.push_back(token);
14444 
14445  }
14446  fcol = 0;
14447  }
14448 
14449 
14450 
14451 
14452  cout << "size of gridline minus heading row..= num_gridlines." << (tokens_lon.size() - 1) / nbinx << "nbinx.." << nbinx << endl;
14453 
14454 
14455  //************************************************************
14456  //mem allocation for geolcoation pointers---
14457  az_east = (float*)malloc(num_gridlines * sizeof(float));
14458  lat_gd = allocate2d_float(num_gridlines, nbinx);
14459  lon_gd = allocate2d_float(num_gridlines, nbinx);
14460 
14461  float sum = 0, tot = 0;
14462  for (int j = 0;j < num_gridlines;j++) {
14463  // cout<<"j.."<<j<<"az_east"<<std::stof(parts[j+1])<<endl;
14464  az_east[j] = std::stof(parts[j + 1]);//first line is the header
14465  sum = az_east[j];
14466  tot += sum;
14467  }
14468  parts.clear();
14469 
14470 
14471 
14472  //using swath-averaged az_east for nadir pixels rather than along-track az_east pixel-by-pixel
14473  float mean_az_east = tot / (num_gridlines - 1);
14474  cout << "mean_az_east..." << mean_az_east << "numgridlines.." << num_gridlines << endl;
14475  // exit(1);
14476  for (int j = 0;j < num_gridlines;j++) {
14477  az_east[j] = mean_az_east;
14478  }
14479 
14480 
14481  int ip = 0;
14482  for (int j = 0;j < num_gridlines;j++) {
14483  for (int k = 0;k < nbinx;k++) {
14484  lat_gd[j][k] = std::stof(tokens_lat[ip]);
14485  lon_gd[j][k] = std::stof(tokens_lon[ip]);
14486  // if(ip % nbinx == 0) cout<<"ip.."<<ip<<"gdline.."<<j+1<<"binx.."<<k+1<<"latgd.."<<std::stof(tokens_lat[ip])<<"longd.."<<std::stof(tokens_lon[ip])<<endl;
14487  ip++;
14488  }
14489 }
14490  tokens_lon.clear();
14491  tokens_lat.clear();
14492 
14493  //determine # of gd groups to be processede
14494  //gdlines_group=num_gridlines;//ONE BIG GROUP
14495  gdlines_group = 250;
14496 
14497  if (num_gridlines <= gdlines_group) {
14498  gdlines_group = num_gridlines;
14499  cout << "WARNING********************* number_gridlines<=gdlines_group THEN gdlines_group=num_gridlines **************" << endl;
14500  }
14501 
14502  ngroups = floor(num_gridlines / gdlines_group);
14503  cout << "TOTAL # of gd groups.(ALL LATs...." << ngroups << endl;
14504 
14505  //--NORMALIZED gridline longitude is -180 to 180 degrees before comparison with longitude extracted from image pixels---
14506  for (int i = 0; i < num_gridlines; i++) {
14507  for (int j = 0; j < nbinx; j++) {
14508  if (lon_gd[i][j] < -180.)lon_gd[i][j] += 360.;
14509  if (lon_gd[i][j] > 180.)lon_gd[i][j] -= 360.;
14510  }
14511 }
14512  //get min/max lat/lon of the swath
14513  // Assume first element as maximum and minimum
14514  maxv = lat_gd[0][0];
14515  minv = lat_gd[0][0];
14516 
14517  //Find maximum and minimum in all array elements.
14518  for (int i = 0; i < num_gridlines; i++) {
14519  for (int j = 0; j < nbinx; j++) {
14520  if (lat_gd[i][j] > maxv)
14521  maxv = lat_gd[i][j];
14522  if (lat_gd[i][j] < minv)
14523  minv = lat_gd[i][j];
14524  }
14525 }
14526 
14527 
14528  maxv = lon_gd[0][0];
14529  minv = lon_gd[0][0];
14530  //Find maximum and minimum in all array elements.
14531  for (int i = 0; i < num_gridlines; i++) {
14532  for (int j = 0; j < nbinx; j++) {
14533  if (lon_gd[i][j] > maxv)
14534  maxv = lon_gd[i][j];
14535  if (lon_gd[i][j] < minv)
14536  minv = lon_gd[i][j];
14537  }
14538  }
14539 
14540 
14541 
14542  cout << "swath #.." << swtd << endl;
14543 
14544  //check lat bound min/max of each gd group---
14545  int k = 0, i = 0;
14546 
14547  dlatb_g = allocate2d_float(ngroups + 1, 2);
14548  dlonb_g = allocate2d_float(ngroups + 1, 2);
14549 
14550  //recompute number of gridlines based on lat limits -80 to 80 degrees
14551  //asc orbit goes from negative to positive latitude....
14552  NY = num_gridlines;
14553  NX = nbinx;
14554  for (int i = 0; i < NY; i++) {
14555  for (int j = 0; j < NX; j++) {
14556  if (lat_gd[i][j] >= -80.) c1++;
14557  if (c1 == nbinx) {
14558  NY1 = i;
14559  }
14560  }
14561  if (NY1 >= 0) break;
14562  c1 = 1;
14563  }
14564 
14565 
14566  for (int i = 0;i < NY; i++) {
14567  // cout<<"i.."<<i<<"lat_gd[i][j]..."<<lat_gd[i][nadpix]<<endl;
14568  for (int j = 0; j < NX; j++) {
14569  if (lat_gd[i][j] >= 80.) {
14570  NY2 = i - 1;
14571  }
14572  }
14573 
14574  if (NY2 >= 0) break;
14575  }
14576 
14577  // cout<<"gridlines limited to -80 to 80 degrees of latitutde.."<<"gdline ini.."<<NY1<<"gdline end.."<<NY2<<endl;
14578 
14579  l1cfile->NY1 = NY1;
14580  l1cfile->NY2 = NY2;
14581 
14582  cout << "NY.." << NY << "NY1.." << NY1 << "NY2.." << NY2 << endl;
14583 
14584 
14585 
14586  num_gridlines = NY2 - NY1 + 1;//this is the # gridlines after -80 to 80 lat constraint---
14587  ngroups = floor(num_gridlines / gdlines_group);
14588  cout << "gdlines will start in gline.." << i + 1 << "ROUNDED ngroups after adjusting beginning.for constraint lat (-80 to 80)" << ngroups << endl;
14589 
14590  //for each 'grid' group scan the swath files to see if there are scanlines within--
14591  //if that is case check the across-bin number position (0 to binx-1) based on latnad and lonnad values---
14592  last_file = 0;
14593  last_sline = 0;
14594  flag_donefile = 0;
14595 
14596  num_blue_bands = 120;
14597  num_red_bands = 120;
14598  num_SWIR_bands = 9;
14599 
14600  if (num_gridlines > ngroups * gdlines_group) ngroups += 1;
14601 
14602 
14603  //*********** SORTING LAT/LON ASCENDING AND TRACK INDEXES ****************************
14604  //***********************************************************************************
14605 
14606  //Create index matrix for i and j of each lat and lon L1C grid (-80 to 80)
14607  //num_gridlines x nbinx
14608  index_xy = allocate2d_short(num_gridlines, nbinx);
14609  lat_asort = allocate2d_float(num_gridlines, nbinx);
14610  // lon_asort=allocate2d_float(num_gridlines,nbinx);
14611  //fill indexe
14612 
14613  //define 1-D vector to sort 1 col L1C grid at the time---
14614  vector<pair<float, int> > vp;
14615 
14616  //fill vector with lat_gd column--
14617  cout << "*********** SORTING LAT/LON GRIDPOINTS AND TRACKING INDEXES ********************" << endl;
14618 
14619  for (int col = 0;col < nbinx;col++) {
14620  for (int row = NY1;row < NY2 + 1;row++) {
14621  vp.push_back(make_pair(lat_gd[row][col] + 90., row));
14622  }
14623  //sort
14624  stable_sort(vp.begin(), vp.end());
14625  //display lat in order along with its gridpoint index--
14626  // cout << "Lat value\t"
14627  // << "index" << endl;
14628  for (unsigned int i = 0; i < vp.size(); i++) {
14629  // cout << vp[i].first << "\t"
14630  // << vp[i].second << endl;
14631  lat_asort[i][col] = vp[i].first;
14632  index_xy[i][col] = vp[i].second;
14633  }
14634  vp.clear();
14635  }
14636 
14637  //saddleback search
14638  short gd_row, gd_col;
14639 
14640  cout << "num_gridlines...." << num_gridlines << "ngroups.." << ngroups << endl;
14641 
14642 
14643  //****************************************************************************************************
14644  //************* BIG LOOP GROUPS ***************************************
14645  cout << "Number of granules to be L1C processed........................................." << sfiles << endl;
14646 
14647  for (k = 0;k < ngroups;k++) {
14648 
14649  //total gridlines for k groups-----
14650  n_gdlines = (k + 1) * gdlines_group;
14651  cout << "screening k group.." << k + 1 << "last_file.." << last_file << "last_line.." << last_sline << endl;
14652  cout << "number of gridlines so far..." << n_gdlines << endl;
14653  //***** compute deltas for lat_gd index 256 and 257 *******************
14654 
14655  //compute delta_lat and delta_lon based on binres/2 for lower and upper corners of 'nadir' gridpoints of 256 and 257 indexes -----------------
14656  //we need nadir 256 and 257 lat/lon coordinates to compute -delta and +delta, respectively
14657  //we need azimuth and backazimuth and binres/2 to compute deltas ---
14658 
14659  //index 256
14660  geod.Direct(lat_gd[n_gdlines - gdlines_group][256], lon_gd[n_gdlines - gdlines_group][256], az_east[n_gdlines - gdlines_group], gres, dlamin, dlomin);
14661  geod.Direct(lat_gd[n_gdlines - 1][257], lon_gd[n_gdlines - 1][257], az_east[n_gdlines - 1], gres, dlamax, dlomax);
14662 
14663  cout << "dlamin.." << dlamin << "dlomin.." << dlomin << "dlamax.." << dlamax << "dlomax.." << dlomax << endl;
14664 
14665  dlatb_g[k][0] = dlamin;//in DEGREES!!
14666  dlatb_g[k][1] = dlamax;
14667  dlonb_g[k][0] = dlomin;
14668  dlonb_g[k][1] = dlomax;
14669 
14670  //********* LOOP FILES ************************************
14671  for (unsigned int findex = last_file;findex < sfiles;findex++) {
14672 
14673  cout << "Scanning lines in file.. for crossing swath..." << swtd << "selected granule #.." << l1cfile->selgran[findex] << "swt_id.." << swtd_id[findex] << "grid group.." << k + 1 << endl;
14674 
14675  if (last_sline == 0) { // binmean_Lt==NULL | bincount==NULL | binmean_Lt2==NULL | bincount2==NULL | binmean_Lt3==NULL | bincount3==NULL){
14676 
14677  cout << "first allocation of memory for grid bins of file #..." << l1cfile->selgran[findex] << endl;
14678 
14679  binmean_Lt = allocate2d_float(num_gridlines, nbinx);
14680  bincount = allocate2d_float(num_gridlines, nbinx);
14681  binmean_Lt2 = allocate2d_float(num_gridlines, nbinx);
14682  bincount2 = allocate2d_float(num_gridlines, nbinx);
14683  binmean_Lt3 = allocate2d_float(num_gridlines, nbinx);
14684  bincount3 = allocate2d_float(num_gridlines, nbinx);
14685 
14686  for (int i = 0; i < num_gridlines; i++) {
14687  for (int j = 0; j < nbinx; j++) {
14688  bincount[i][j] = 0.;
14689  binmean_Lt[i][j] = 0.;
14690  bincount2[i][j] = 0.;
14691  binmean_Lt2[i][j] = 0.;
14692  bincount3[i][j] = 0.;
14693  binmean_Lt3[i][j] = 0.;
14694  }
14695 }
14696  }//end allocating bin arrays
14697 
14698 
14699  fi = l1cfile->selgran[findex];
14700  str = l1cfile->ifiles[fi - 1];
14701  ptstr = str.c_str();
14702  cout << "opening filename............" << ptstr << endl;
14703  status = nc_open(ptstr, NC_NOWRITE, &ncid_L1B);
14704  if (status != NC_NOERR) {
14705  fprintf(stderr, "nc_open.\n");
14706  exit(EXIT_FAILURE);
14707 }
14708  //Open dimensions
14709  status = nc_inq_dimid(ncid_L1B, "number_of_scans", &dimid);
14710  if (status != NC_NOERR) {
14711  fprintf(stderr, "-E- Error reading number_of_scans.\n");
14712  exit(EXIT_FAILURE);
14713  }
14714  nc_inq_dimlen(ncid_L1B, dimid, &num_scans);
14715 
14716  //read line-by-line lat/lon/Lt
14717  status = nc_inq_grp_ncid(ncid_L1B, "geolocation_data", &geoGrp);
14718  check_err(status, __LINE__, __FILE__);
14719  status = nc_inq_grp_ncid(ncid_L1B, "observation_data", &obsGrp);
14720  check_err(status, __LINE__, __FILE__);
14721  //open geo data
14722  status = nc_inq_varid(geoGrp, "latitude", &latId);//scans x velements
14723  check_err(status, __LINE__, __FILE__);
14724  status = nc_inq_varid(geoGrp, "longitude", &lonId);//scans x velements
14725  check_err(status, __LINE__, __FILE__);
14726  status = nc_inq_varid(obsGrp, "Lt_blue", &Lt_blueId);
14727  check_err(status, __LINE__, __FILE__);
14728  status = nc_inq_varid(obsGrp, "Lt_red", &Lt_redId);
14729  check_err(status, __LINE__, __FILE__);
14730  status = nc_inq_varid(obsGrp, "Lt_SWIR", &Lt_SWIRId);
14731  check_err(status, __LINE__, __FILE__);
14732 
14733 
14734  // num_blue_bands
14735  status = nc_inq_dimid(ncid_L1B, "blue_bands", &dimid);
14736  if (status != NC_NOERR) {
14737  fprintf(stderr, "-E- Error reading num_blue_bands.\n");
14738  exit(EXIT_FAILURE);
14739  }
14740  nc_inq_dimlen(ncid_L1B, dimid, &num_blue_bands);
14741 
14742  // num_red_bands
14743  status = nc_inq_dimid(ncid_L1B, "red_bands", &dimid);
14744  if (status != NC_NOERR) {
14745  fprintf(stderr, "-E- Error reading num_red_bands.\n");
14746  exit(EXIT_FAILURE);
14747  }
14748  nc_inq_dimlen(ncid_L1B, dimid, &num_red_bands);
14749 
14750  // num_SWIR_bands
14751  status = nc_inq_dimid(ncid_L1B, "SWIR_bands", &dimid);
14752  if (status != NC_NOERR) {
14753  fprintf(stderr, "-E- Error reading num_SWIR_bands.\n");
14754  exit(EXIT_FAILURE);
14755  }
14756  nc_inq_dimlen(ncid_L1B, dimid, &num_SWIR_bands);
14757 
14758  //assigning mem for Lt of different bands **********************
14759  latpix = (float*)malloc(num_pixels * sizeof(float));
14760  lonpix = (float*)malloc(num_pixels * sizeof(float));
14761  Lt_pix = allocate2d_float(num_blue_bands, num_pixels);//blue bands
14762  Lt_pix2 = allocate2d_float(num_red_bands, num_pixels);//red bands
14763  Lt_pix3 = allocate2d_float(num_SWIR_bands, num_pixels);//SWIR bands
14764 
14765  cout << "#blue bands.." << num_blue_bands << endl;
14766  cout << "#red bands.." << num_red_bands << endl;
14767  cout << "#swir bands.." << num_SWIR_bands << endl;
14768 
14769  //********************************************************************************
14770  //-----reading line by line-----------------------------------
14771  for (unsigned int sline = last_sline;sline < num_scans;sline++) {
14772  //lat and lon--
14773  start[0] = sline;
14774  start[1] = 0;
14775  count[0] = 1;
14776  count[1] = num_pixels; // 1 line at a time
14777 
14778  status = nc_get_vara_float(geoGrp, latId, start, count, latpix);
14779  status = nc_get_vara_float(geoGrp, lonId, start, count, lonpix);
14780 
14781  //Lt
14782  start2[0] = 0;
14783  start2[1] = sline;
14784  start2[2] = 0;
14785 
14786  count2[0] = num_blue_bands;
14787  count2[1] = 1; // 1 line at a time
14788  count2[2] = num_pixels;
14789 
14790  count3[0] = num_red_bands;
14791  count3[1] = 1; // 1 line at a time
14792  count3[2] = num_pixels;
14793 
14794  count4[0] = num_SWIR_bands;
14795  count4[1] = 1; // 1 line at a time
14796  count4[2] = num_pixels;
14797 
14798  status = nc_get_vara_float(obsGrp, Lt_blueId, start2, count2, Lt_pix[0]);
14799  status = nc_get_vara_float(obsGrp, Lt_redId, start2, count3, Lt_pix2[0]);
14800  status = nc_get_vara_float(obsGrp, Lt_SWIRId, start2, count4, Lt_pix3[0]);
14801 
14802  for (unsigned int pix = 0;pix < num_pixels;pix++) {
14803  if (latpix[pix] < latmin_swt) latmin_swt = latpix[pix];
14804  if (latpix[pix] > latmax_swt) latmax_swt = latpix[pix];
14805  if (lonpix[pix] < lonmin_swt) lonmin_swt = lonpix[pix];
14806  if (lonpix[pix] > lonmax_swt) lonmax_swt = lonpix[pix];
14807  }
14808 
14809  dlamin = 0.;dlamax = 0.;
14810  //inside the 'k' box??----- ascending ----------
14811  if (latpix[nadpix] >= dlatb_g[k][0] && latpix[nadpix] <= dlatb_g[k][1]) {
14812 
14813  if (sline % 100 == 0) cout << "EVERY 100 gds..for k group.." << k + 1 << "file number #.." << l1cfile->selgran[findex] << "sline..." << sline + 1 << "# of binned pix.." << inpix << "outpix.." << outpix << endl;
14814 
14815  //*********** BIG LOOP M_PIXEL *****************************************************************
14816  for (unsigned int pix = 0;pix < num_pixels;pix++) {
14817 
14818  flag_inpix = 0, bin_xpix = -1, bin_ypix = -1;
14819 
14820  boolbin1 = sbs2_l1c(l1cinput, num_gridlines, nbinx, lat_asort, index_xy, latpix[pix], lonpix[pix], lon_gd, &gd_row, &gd_col);
14821  bin_ypix = gd_row + 1;
14822  bin_xpix = gd_col + 1;
14823 
14824  // cout<<"ok after sbs2_l1c"<<"boolbin1.."<<boolbin1<<"pix.."<<pix+1<<endl;
14825 
14826  if (boolbin1 == 1) flag_inpix = 1;
14827  //************ BINNING ***************************
14828  //assign identified pixel to Lt and bin stat arrays-----
14829  if (flag_inpix == 1 && bin_xpix >= 1 && bin_ypix >= 1 && bin_xpix <= nbinx && bin_ypix <= num_gridlines) {
14830  inpix++;
14831  if (Lt_pix[0][pix] > 0.) {
14832  binmean_Lt[bin_ypix - 1][bin_xpix - 1] = binmean_Lt[bin_ypix - 1][bin_xpix - 1] + Lt_pix[0][pix];
14833  bincount[bin_ypix - 1][bin_xpix - 1] += 1;
14834  }
14835 
14836  if (Lt_pix2[0][pix] > 0.) {
14837  binmean_Lt2[bin_ypix - 1][bin_xpix - 1] = binmean_Lt2[bin_ypix - 1][bin_xpix - 1] + Lt_pix2[0][pix];
14838  bincount2[bin_ypix - 1][bin_xpix - 1] += 1;
14839  }
14840 
14841  if (Lt_pix3[0][pix] > 0.) {
14842  binmean_Lt3[bin_ypix - 1][bin_xpix - 1] = binmean_Lt3[bin_ypix - 1][bin_xpix - 1] + Lt_pix3[0][pix];
14843  bincount3[bin_ypix - 1][bin_xpix - 1] += 1;
14844  }
14845  }
14846 
14847  //********** pixel AREA WEIGHTING ************************
14848  if (flag_inpix == 0) outpix++;
14849 
14850  totpix++;
14851 
14852  }//end pixels loop
14853 
14854  //END OF FILE--****** reset starting sline index if last line processed and within k box
14855  //go for another granule if it is not the last one---------------
14856  if (sline == num_scans - 1) {
14857  flag_donefile = 1;
14858  cout << "end of file..." << l1cfile->selgran[findex] << endl;
14859  last_sline = 0;
14860  if (findex >= sfiles - 1) {
14861  cout << "done with last granule of the input list........................." << endl;
14862  // findex=sfiles;
14863  k = ngroups;
14864  break;
14865  }
14866 
14867  }//end of file/last file? sliine=num_scans-1
14868  else flag_donefile = 0;
14869 
14870  }//end latpix nadir of line x inside grid group?
14871 
14872  //***** skip lines and files if sline is not within k group ********
14873  //increase k and screen files and lines again starting from the last binning
14874 
14875  if (latpix[nadpix] > lat_gd[n_gdlines - 1][257] && k < ngroups - 1) { //else limits
14876  cout << "moving to the next k group...scanning again files/slines.." << endl;
14877  cout << "file index.." << findex << "last sline index.." << sline << endl;
14878  last_file = findex;
14879  last_sline = sline;
14880  findex = sfiles;
14881  sline = num_scans - 1;
14882  }//end if lat >grid lat--IF outside the box
14883 
14884  if (sline + 1 % 100 == 0) cout << "for k group.." << k + 1 << "selected granule #.." << l1cfile->selgran[findex] << "sline..." << sline + 1 << "# of binned pix.." << inpix << "totpix.." << totpix << "outpix.." << outpix << endl;
14885  // cout<<"sline.."<<sline+1<<endl;
14886  }//end for scanlines
14887 
14888  cout << "closing L1B file......." << ptstr << endl;
14889  status = nc_close(ncid_L1B);
14890  check_err(status, __LINE__, __FILE__);
14891 
14892  delete[](latpix);
14893  delete[](lonpix);
14894  delete[](Lt_pix);
14895  delete[](Lt_pix2);
14896  delete[](Lt_pix3);
14897 
14898 
14899 
14900  //writing each granule ---------------------------------
14901  if (flag_donefile == 1 | (flag_donefile == 0 && k == ngroups - 1)) {
14902  cout << "writing file #.............................................." << l1cfile->selgran[findex] << "based on group #.." << k + 1 << endl;
14903  //write mean Lt as nc file---
14904  //**********************************************************************
14905  //**********************************************************************8
14906  //create Lt file
14907  pathstr = "out/";
14908  senstr = "OCIS_";
14909  monstr = std::to_string(selmon);
14910  daystr = std::to_string(selday);
14911  yearstr = std::to_string(selyear);
14912  prodstr = "binLt_blue1";
14913  swtstr = "_swt";
14914  granstr = "";
14915  granstr = "_" + std::to_string(l1cfile->selgran[findex]);
14916 
14917  if (l1cfile->l1c_pflag >= 3) {
14918  swtd = l1cfile->swtnum;
14919  swtnum = std::to_string(swtd);
14920  cout << "swtnum.." << swtnum << endl;
14921  }
14922  else swtnum = std::to_string(swtd);
14923  extstr = ".nc";
14924  NDIMS = 2;
14925  fname_out = pathstr + senstr + monstr + daystr + yearstr + prodstr + swtstr + swtnum + granstr + extstr;
14926  filename_lt = fname_out.c_str();
14927  if ((status = nc_create(filename_lt, NC_CLOBBER, &ncid_out)))
14928  check_err(status, __LINE__, __FILE__);
14929  //define dims
14930  // Define the dimensions. NetCDF will hand back an ID for each.
14931  NY = num_gridlines;
14932  NX = nbinx;
14933  NY1 = l1cfile->NY1;//these are indexes not line #!!!!!!!!!!!!!!!!!
14934  NY2 = l1cfile->NY2;
14935  cout << "rowgrid ini.." << NY1 << "rowgrid end.." << NY2 << endl;
14936  NY = NY2 - NY1 + 1;
14937  cout << "NY.." << NY << "NX.." << NX << endl;
14938  //alloc mem for data_out and assign values from lat_gdI
14939  //NX AND NY are inverted for visualization in SeaDAS
14940  data_out = allocate2d_float(NY, NX);
14941  data_out2 = allocate2d_float(NY, NX);
14942  data_out3 = allocate2d_float(NY, NX);
14943  data_out4 = allocate2d_float(NY, NX);
14944  data_out5 = allocate2d_float(NY, NX);
14945  data_out6 = allocate2d_float(NY, NX);
14946  lat_out = allocate2d_float(NY, NX);
14947  lon_out = allocate2d_float(NY, NX);
14948 
14949  int c = 0;
14950  for (int i = NY1; i < NY2 + 1; i++) {
14951  for (int j = 0; j < NX; j++) {
14952  lat_out[NY - 1 - c][NX - 1 - j] = lat_gd[i][j];
14953  lon_out[NY - 1 - c][j] = lon_gd[i][j];
14954  //blue
14955  if (bincount[i][j] > 0)
14956  data_out[NY - 1 - c][NX - 1 - j] = binmean_Lt[i][j] / bincount[i][j];
14957  else
14958  data_out[NY - 1 - c][NX - 1 - j] = NAN;
14959  //red
14960  if (bincount2[i][j] > 0)
14961  data_out3[NY - 1 - c][NX - 1 - j] = binmean_Lt2[i][j] / bincount2[i][j];
14962  else
14963  data_out3[NY - 1 - c][NX - 1 - j] = NAN;
14964  //swir
14965  if (bincount3[i][j] > 0)
14966  data_out5[NY - 1 - c][NX - 1 - j] = binmean_Lt3[i][j] / bincount3[i][j];
14967  else
14968  data_out5[NY - 1 - c][NX - 1 - j] = NAN;
14969  data_out2[NY - 1 - c][NX - 1 - j] = bincount[i][j];
14970  data_out4[NY - 1 - c][NX - 1 - j] = bincount2[i][j];
14971  data_out6[NY - 1 - c][NX - 1 - j] = bincount3[i][j];
14972  }
14973  c++;
14974  }
14975 
14976  if ((status = nc_def_dim(ncid_out, "x", NX, &x_dimid)))
14977  check_err(status, __LINE__, __FILE__);
14978  if ((status = nc_def_dim(ncid_out, "y", NY, &y_dimid)))
14979  check_err(status, __LINE__, __FILE__);
14980  //dims for output var
14981  dimids[0] = y_dimid;
14982  dimids[1] = x_dimid;
14983  //def var
14984  //blue
14985  if ((status = nc_def_var(ncid_out, "binLt_blue", NC_FLOAT, NDIMS,
14986  dimids, &varid)))
14987  check_err(status, __LINE__, __FILE__);
14988  if ((status = nc_def_var(ncid_out, "bincount_blue", NC_FLOAT, NDIMS,
14989  dimids, &varid4)))
14990  check_err(status, __LINE__, __FILE__);
14991  //red
14992  if ((status = nc_def_var(ncid_out, "binLt_red", NC_FLOAT, NDIMS,
14993  dimids, &varid5)))
14994  check_err(status, __LINE__, __FILE__);
14995  if ((status = nc_def_var(ncid_out, "bincount_red", NC_FLOAT, NDIMS,
14996  dimids, &varid6)))
14997  check_err(status, __LINE__, __FILE__);
14998  //swir
14999  if ((status = nc_def_var(ncid_out, "binLt_swir", NC_FLOAT, NDIMS,
15000  dimids, &varid7)))
15001  check_err(status, __LINE__, __FILE__);
15002  if ((status = nc_def_var(ncid_out, "bincount_swir", NC_FLOAT, NDIMS,
15003  dimids, &varid8)))
15004  check_err(status, __LINE__, __FILE__);
15005  //lat/lon
15006  if ((status = nc_def_var(ncid_out, "lat_gd", NC_FLOAT, NDIMS,
15007  dimids, &varid2)))
15008  check_err(status, __LINE__, __FILE__);
15009  if ((status = nc_def_var(ncid_out, "lon_gd", NC_FLOAT, NDIMS,
15010  dimids, &varid3)))
15011  check_err(status, __LINE__, __FILE__);
15012  if ((status = nc_enddef(ncid_out))) //done def vars etc
15013  check_err(status, __LINE__, __FILE__);
15014  //writing the whole thing
15015  if ((status = nc_put_var_float(ncid_out, varid2, &lat_out[0][0])))
15016  check_err(status, __LINE__, __FILE__);
15017  if ((status = nc_put_var_float(ncid_out, varid3, &lon_out[0][0])))
15018  check_err(status, __LINE__, __FILE__);
15019  //blue
15020  if ((status = nc_put_var_float(ncid_out, varid, &data_out[0][0])))
15021  check_err(status, __LINE__, __FILE__);
15022  if ((status = nc_put_var_float(ncid_out, varid4, &data_out2[0][0])))
15023  check_err(status, __LINE__, __FILE__);
15024  //red
15025  if ((status = nc_put_var_float(ncid_out, varid5, &data_out3[0][0])))
15026  check_err(status, __LINE__, __FILE__);
15027  if ((status = nc_put_var_float(ncid_out, varid6, &data_out4[0][0])))
15028  check_err(status, __LINE__, __FILE__);
15029  //swir
15030  if ((status = nc_put_var_float(ncid_out, varid7, &data_out5[0][0])))
15031  check_err(status, __LINE__, __FILE__);
15032  if ((status = nc_put_var_float(ncid_out, varid8, &data_out6[0][0])))
15033  check_err(status, __LINE__, __FILE__);
15034 
15035 
15036  if ((status = nc_close(ncid_out)))
15037  check_err(status, __LINE__, __FILE__);
15038 
15039  delete[](lat_out);
15040  delete[](lon_out);
15041  delete[](data_out);
15042  delete[](data_out2);
15043  delete[](data_out3);
15044  delete[](data_out4);
15045  delete[](data_out5);
15046  delete[](data_out6);
15047 
15048  delete[](bincount);
15049  delete[](binmean_Lt);
15050  delete[](bincount2);
15051  delete[](binmean_Lt2);
15052  delete[](bincount3);
15053  delete[](binmean_Lt3);
15054 
15055  lat_out = nullptr;;
15056  lon_out = nullptr;
15057  data_out = nullptr;
15058  data_out2 = nullptr;
15059  data_out3 = nullptr;
15060  data_out4 = nullptr;
15061  data_out5 = nullptr;
15062  data_out6 = nullptr;
15063 
15064  bincount = nullptr;
15065  binmean_Lt = nullptr;
15066  bincount2 = nullptr;
15067  binmean_Lt2 = nullptr;
15068  bincount3 = nullptr;
15069  binmean_Lt3 = nullptr;
15070 
15071  flag_donefile = 0;
15072  }//end writing file
15073  }//end for files
15074 
15075  cout << "group k at the end of big loop" << k + 1 << endl;
15076 
15077  }//groups
15078 
15079  cout << "number of files per swath.." << nfiles_swt[swtd - 1] << "for swath.." << swtd << endl;
15080  cout << "total inpix.." << inpix << "total pix.." << totpix << endl;
15081  // cout<<"binned pixels.."<<inpix<<"as %.."<<(inpix/(num_pixels*num_scans*n_files*nfiles_swt[swtd-1]))*100<<endl;
15082  delete[](lat_asort);
15083  // delete [] (lon_asort);
15084  delete[](index_xy);
15085  // delete [] (index_xy2);
15086  delete[](dlatb_g);
15087  delete[](dlonb_g);
15088 
15089  delete[](lat_gd);
15090  delete[](lon_gd);
15091  delete[](az_east);
15092 
15093  printf("*** SUCCESS writing bincount and binLt rasters as nc..!\n");
15094  cout << "finish processing swath eq crossing day..." << swtd << endl;
15095  cout << "done writing Lt to nc file.." << endl;
15096 
15097  return(0);
15098  }
15099 
15100 
15101 
15102 
15103  int32_t L1C::pix_corners4_l1c(l1c_filehandle* l1cfile, L1C_input* l1cinput, float dist_u, float dist_v, float azpix, int32_t scanline, int32_t pix, float pixlat, float pixlon, float pixLt, float** lat_asort, short** index_xy, float** lat_gd, float** lon_gd, double** lat_cgd, double** lon_cgd, double areaFracBox[3][3], float** Ltfracsum, float** areafracsum, float** nobs_perbin) { //compute pixel corners for a specific line,pixel and file
15104 
15105  double lat_cnw, lat_cne, lat_csw, lat_cse, lon_cnw, lon_cne, lon_csw, lon_cse;
15106  float azpixc;
15107  short gd_row, gd_col;
15108  int32_t num_gridlines, nbinx;
15109 
15110  double areabinBox[3][3];
15111  float theta, thetares, dist_corn, thetagrad;
15112  double res1, res2, res3, res4;//pixel resolution in meters
15113 
15114  Geodesic geod(Constants::WGS84_a(), Constants::WGS84_f());
15115 
15116  //using namespace bg;
15117  Polygon_t pixelPoly;
15118  // Box_t pixelBox;
15119  // Point_t pixelPoint;
15120 
15121  num_gridlines = l1cfile->num_gridlines;
15122  nbinx = l1cfile->nbinx;
15123 
15124 
15125 
15126 
15127 // cout<<"in pix_corners4_l1c.........NY1.."<<NY1<<"NY2..."<<NY2<<"NY..."<<NY<<"numgridlines.."<<num_gridlines<<"number of binx.."<<nbinx<<endl;
15128 
15129  //******* M_PIXEL CORNERS *****************************
15130  //***************************************************
15131 
15132  // ad=0.5*(sqrt(dist_u*dist_u+dist_v*dist_v)/Re);
15133  dist_corn = 0.5 * (sqrt(dist_u * dist_u + dist_v * dist_v)) * 1000;//distane center to corner in meters
15134 
15135 
15136  theta = atan2(dist_v, dist_u);
15137  thetagrad = 2 * theta * 180 / M_PI;
15138  thetares = (M_PI / 2 - theta) * 180 / M_PI;
15139 
15140  //nw corner
15141  azpixc = (azpix - thetares) * degrad;//pixel bearing
15142  if (azpixc<-M_PI | azpixc>M_PI) { cout << "error in nw corner..azpixc" << azpixc << endl;exit(1); }
15143  azpixc = azpixc * 180 / M_PI;
15144  // cout << "azpixc nw...." << azpixc << endl;
15145  geod.Direct(pixlat, pixlon, azpixc, dist_corn, lat_cnw, lon_cnw);
15146  geod.Inverse(pixlat, pixlon, lat_cnw, lon_cnw, res1);
15147  // lat_cne=asin(sin(pixlat*degrad)*cos(ad)+cos(pixlat*degrad)*sin(ad)*cos(azpixc*degrad))*180./M_PI;
15148  // lon_cne=pixlon+atan2(sin(azpixc*degrad)*sin(ad)*cos(pixlat*degrad),cos(ad)-sin(pixlat*degrad)*sin(lat_cne*degrad))*180./M_PI;
15149 
15150 
15151  //ne corner (sw-180)
15152  azpixc = (azpix + thetares) * degrad;//pixel bearing
15153  if (azpixc<-M_PI | azpixc>M_PI) { cout << "error in ne corner..azpixc" << azpixc << endl;exit(1); }
15154  // azpixc=(azpix+45)*degrad;//pixel bearing
15155  /* if(azpixc>M_PI | azpixc<-M_PI){
15156  }
15157  if(azpixc<0.){
15158  azpixc=360+azpixc*180/M_PI;
15159  }
15160  else azpixc=azpixc*180/M_PI;
15161  */
15162 
15163  azpixc = azpixc * 180 / M_PI;
15164  // cout << "azpixc ne...." << azpixc << endl;
15165 
15166  // cout << "azpixc nw...." << azpixc << endl;
15167  geod.Direct(pixlat, pixlon, azpixc, dist_corn, lat_cne, lon_cne);
15168  geod.Inverse(pixlat, pixlon, lat_cne, lon_cne, res2);
15169 
15170 
15171 
15172  //sw corner
15173  // azpixc=(azpix-45-90)*degrad;//pixel bearing
15174  azpixc = (azpix - thetares - thetagrad) * degrad;//pixel bearing
15175  if (azpixc<-M_PI | azpixc>M_PI) { cout << "error in sw corner..azpixc" << azpixc << endl;exit(1); }
15176  /* if(azpixc>M_PI | azpixc<-M_PI){
15177  // cout<<"problem with BEARING in across-gridline method...az<-180 or >180...."<<"SW azpixc in degrees.."<<azpixc*180/M_PI<<endl;
15178  }
15179  if(azpixc<0.){
15180  azpixc=360+azpixc*180/M_PI;
15181  }
15182  else azpixc=azpixc*180/M_PI;
15183  */
15184 
15185  azpixc = azpixc * 180 / M_PI;
15186  // cout << "azpixc sw....." << azpixc << endl;
15187  geod.Direct(pixlat, pixlon, azpixc, dist_corn, lat_csw, lon_csw);
15188  geod.Inverse(pixlat, pixlon, lat_csw, lon_csw, res3);
15189  //lat_csw=asin(sin(pixlat*degrad)*cos(ad)+cos(pixlat*degrad)*sin(ad)*cos(azpixc*degrad))*180./M_PI;
15190  // lon_csw=pixlon+atan2(sin(azpixc*degrad)*sin(ad)*cos(pixlat*degrad),cos(ad)-sin(pixlat*degrad)*sin(lat_csw*degrad))*180./M_PI;
15191 
15192  //se corner (nw-180)
15193  azpixc = (azpix + thetares + thetagrad) * degrad;//pixel bearingi
15194  if (azpixc<-M_PI | azpixc>M_PI) { cout << "error in se corner..azpixc" << azpixc << endl;exit(1); }
15195  // azpixc=(azpix+45+90)*degrad;//pixel bearing
15196  /* if(azpixc>M_PI | azpixc<-M_PI){
15197  // cout<<"problem with BEARING in across-gridline method...az<-180 or >180...."<<"SE azpixc in degrees.."<<azpixc*180/M_PI<<endl;
15198  }
15199  if(azpixc<0.){
15200  azpixc=360+azpixc*180/M_PI;
15201  }
15202  else azpixc=azpixc*180/M_PI;
15203  */
15204  azpixc = azpixc * 180 / M_PI;
15205  // cout << "azpix se...." << azpixc << endl;
15206  geod.Direct(pixlat, pixlon, azpixc, dist_corn, lat_cse, lon_cse);
15207  geod.Inverse(pixlat, pixlon, lat_cse, lon_cse, res4);
15208  // lat_cse=asin(sin(pixlat*degrad)*cos(ad)+cos(pixlat*degrad)*sin(ad)*cos(azpixc*degrad))*180./M_PI;
15209  // lon_cse=pixlon+atan2(sin(azpixc*degrad)*sin(ad)*cos(pixlat*degrad),cos(ad)-sin(pixlat*degrad)*sin(lat_cse*degrad))*180./M_PI;
15210 /*
15211  cout << "pix.." << pix + 1 << "azpix.." << azpix << "theta.." << thetagrad << "thetares.." << thetares << endl;
15212  cout << "dist_u.." << dist_u << "dist_v.." << dist_v << endl;
15213  cout << "res1." << res1 << "res2." << res2 << "res3.." << res3 << "res4.." << res4 << endl;
15214  cout << "pix sw corner..lat." << lat_csw << "sw corner lon.." << lon_csw << endl;
15215  cout << "pix nw corner..lat." << lat_cnw << "nw corner lon.." << lon_cnw << endl;
15216  cout << "pix ne corner..lat." << lat_cne << "ne corner lon.." << lon_cne << endl;
15217  cout << "pix se corner..lat." << lat_cse << "se corner lon.." << lon_cse << endl;
15218 */
15219  std::string ws_lon_str, ws_lat_str, wn_lon_str, wn_lat_str, en_lon_str, en_lat_str, es_lon_str, es_lat_str, pixstr;
15220  ws_lon_str = std::to_string(lon_csw);
15221  ws_lat_str = std::to_string(lat_csw);
15222  wn_lon_str = std::to_string(lon_cnw);
15223  wn_lat_str = std::to_string(lat_cnw);
15224  en_lon_str = std::to_string(lon_cne);
15225  en_lat_str = std::to_string(lat_cne);
15226  es_lon_str = std::to_string(lon_cse);
15227  es_lat_str = std::to_string(lat_cse);
15228 
15229 
15230  pixstr = "POLYGON((" + ws_lon_str + " " + ws_lat_str + "," + wn_lon_str + " " + wn_lat_str + "," + en_lon_str + " " + en_lat_str + "," + es_lon_str + " " + es_lat_str + "," + ws_lon_str + " " + ws_lat_str + "))";
15231  bg::read_wkt(pixstr, pixelPoly);
15232 
15233  if (lon_csw > lon_cse | lon_cnw > lon_cne | lat_csw > lat_cnw | lat_cse > lat_cne) {
15234  // cout << "lon_csw>lon_cse | lon_cnw>lon_cne | lat_csw>lat_cnw | lat_cse>lat_cne//" << lon_csw << lon_cse << lon_cnw << lon_cne << lat_csw << lat_cnw << lat_cse << lat_cne << endl;
15235  // cout << "corners are switched for pixel due to the change of longitude from +180 to -180...." << pix + 1 << endl;
15236  }
15237 
15238  // exit(1);
15239  //*** L1C grid cell *******************************************************************************
15240 
15241  bool boolbin1 = 0;
15242 
15243  boolbin1 = sbs2_l1c(l1cinput, num_gridlines, nbinx, lat_asort, index_xy, pixlat, pixlon, lon_gd, &gd_row, &gd_col);
15244 
15245 
15246 
15247  //Ini areaBinbox
15248  for (int ar = 0;ar < 3;ar++) {
15249  for (int ac = 0;ac < 3;ac++) {
15250  areabinBox[ar][ac] = 0.;
15251  areaFracBox[ar][ac] = 0.;
15252  ac++;
15253  }
15254  ar++;
15255  }
15256 
15257  if (boolbin1 == 1 && gd_row >= 1 && gd_col >= 1 && gd_row < num_gridlines - 1 && gd_col < nbinx - 1) {
15258 
15259  binIntersectsPix4corn4_l1c(l1cfile, l1cinput, gd_row, gd_col, lat_gd, lon_gd, pixelPoly, areaFracBox, areabinBox);
15260 
15261  int ar = 0, ac = 0;
15262  for (int gr = gd_row - 1;gr < gd_row + 2;gr++) {
15263  for (int gc = gd_col - 1;gc < gd_col + 2;gc++) {
15264  if (pixLt > 0.0) {
15265  Ltfracsum[gr][gc] += pixLt * areaFracBox[ar][ac];
15266  areafracsum[gr][gc] += areaFracBox[ar][ac];
15267  nobs_perbin[gr][gc] += 1;
15268 
15269  // cout<<"Ltfracsum[gr][gc].."<<Ltfracsum[gr][gc]<<"areafracsum[gr][gc].."<<areafracsum[gr][gc]<<"nobs_perbin[gr][gc].."<<nobs_perbin[gr][gc]<<endl;
15270  }
15271  else {
15272  Ltfracsum[gr][gc] += 0.0;
15273  areafracsum[gr][gc] += 0.0;
15274  nobs_perbin[gr][gc] += 0;
15275  }
15276 
15277  ac++;
15278  }
15279  ac = 0;
15280  ar++;
15281  }
15282 
15283  }
15284  else {
15285  // cout<<"pix out of the L1Cgrid.........................."<<"pix#..."<<pix+1<<"pixlat.."<<pixlat<<"pixlon..."<<pixlon<<endl;
15286  }
15287 
15288 
15289  return 0;
15290  }
15291 
15292 
15293 
15294 
15295 
15296  int32_t L1C::gwindowTopix_l1c(l1c_filehandle* l1cfile, L1C_input* l1cinput, short row, short col, float** lat_gd, float** lon_gd, double** latcornBox, double** loncornBox) {
15297  double ws_lat, wn_lat, es_lat, en_lat, ws_lon, wn_lon, es_lon, en_lon;
15298  double ws_lat2, wn_lat2, es_lat2, en_lat2, ws_lon2, wn_lon2, es_lon2, en_lon2;
15299  double ws_lat3, wn_lat3, es_lat3, en_lat3, ws_lon3, wn_lon3, es_lon3, en_lon3;
15300  double ws_lat4, wn_lat4, es_lat4, en_lat4, ws_lon4, wn_lon4, es_lon4, en_lon4;
15301  double ws_lat5, wn_lat5, es_lat5, en_lat5, ws_lon5, wn_lon5, es_lon5, en_lon5;
15302  double ws_lat6, wn_lat6, es_lat6, en_lat6, ws_lon6, wn_lon6, es_lon6, en_lon6;
15303  double ws_lat7, wn_lat7, es_lat7, en_lat7, ws_lon7, wn_lon7, es_lon7, en_lon7;
15304  double ws_lat8, wn_lat8, es_lat8, en_lat8, ws_lon8, wn_lon8, es_lon8, en_lon8;
15305  double ws_lat9, wn_lat9, es_lat9, en_lat9, ws_lon9, wn_lon9, es_lon9, en_lon9;
15306  // shape->rowcol2bounds(row, col, n, s, e, w);
15307  float binres = 0, azgc, deltaphi, deltalam, azpixc;
15308 
15309  float aterm, bterm, dist_u, dist_v, theta, thetares, thetagrad, dist_corn2, mean_az_east;
15310  float az1, az2, az3, az4;
15311 
15312 
15313  Geodesic geod(Constants::WGS84_a(), Constants::WGS84_f());
15314 
15315 
15316  mean_az_east = l1cfile->mean_az_east; //in degrees
15317 
15318  // cout<<"mean az east.for L1C grid................. in degrees..."<<mean_az_east<<endl;
15319  binres = (l1cinput->gres);//in km
15320 
15321  // cout<<"gwindowTopix_l1c...........................gd_row......"<<row<<"gd_col...."<<col<<endl;
15322 
15323  //*******************************************************************************************
15324  //center center bin
15325  //********************************************************************************************************
15326 
15327  deltaphi = (lat_gd[row][col] - lat_gd[row][col + 1]) * degrad;
15328  deltalam = (lon_gd[row][col] - lon_gd[row][col + 1]) * degrad;
15329  //across-track grid size
15330  aterm = sin(deltaphi / 2) * sin(deltaphi / 2) + cos(lat_gd[row][col] * degrad) * cos(lat_gd[row][col + 1] * degrad) * sin(deltalam / 2) * sin(deltalam / 2);
15331  bterm = 2 * atan2(sqrt(aterm), sqrt(1 - aterm));
15332  dist_u = Re * bterm; //horizontal distance Harversine in km
15333 
15334  deltaphi = (lat_gd[row][col] - lat_gd[row + 1][col]) * degrad;
15335  deltalam = (lon_gd[row][col] - lon_gd[row + 1][col]) * degrad;
15336  //along-track distance
15337  aterm = sin(deltaphi / 2) * sin(deltaphi / 2) + cos(lat_gd[row][col] * degrad) * cos(lat_gd[row + 1][col] * degrad) * sin(deltalam / 2) * sin(deltalam / 2);
15338  bterm = 2 * atan2(sqrt(aterm), sqrt(1 - aterm));
15339  dist_v = Re * bterm;
15340 
15341  // ad=0.5*(sqrt(dist_u*dist_u+dist_v*dist_v)/Re);
15342 
15343  dist_corn2 = 0.5 * sqrt(binres * binres + binres * binres) * 1000;
15344 
15345  azgc = (mean_az_east - 90) * degrad;//this is the bearing
15346 
15347  if (azgc > M_PI | azgc < -M_PI){cout << "problem with BEARING in across-gridline method...az<-180 or >180...." << "azpixc in degrees.." << azgc * 180 / M_PI << endl;exit(1);}
15348 
15349  theta = atan2(dist_v, dist_u);
15350  thetagrad = 2 * theta * 180 / M_PI;
15351  thetares = (M_PI / 2 - theta) * 180 / M_PI;
15352  azgc = azgc * 180 / M_PI;
15353 
15354  //nw corner
15355  azpixc = (azgc - thetares) * degrad;//pixel bearing
15356  if (azpixc > M_PI | azpixc < -M_PI) {
15357  cout << "problem with BEARING in across-gridline method...az<-180 or >180...." << "NW azpixc in degrees.." << azpixc * 180 / M_PI << endl;
15358  exit(1);
15359  }
15360 
15361  azpixc = azpixc * 180 / M_PI;
15362  az1 = azpixc;
15363  geod.Direct(lat_gd[row][col], lon_gd[row][col], azpixc, dist_corn2, wn_lat, wn_lon);
15364 
15365  // cout<<"azgc.Center-Center."<<azgc<<"azpixc.."<<azpixc<<"dist_corn.."<<dist_corn<<"dist_corn2.."<<dist_corn2<<endl;
15366  // cout<<"res1..nw."<<res1<<endl;
15367 
15368  //ne corner
15369  azpixc = (azgc + thetares) * degrad;//pixel bearing
15370  if (azpixc > M_PI | azpixc < -M_PI) {
15371  cout << "problem with BEARING in across-gridline method...az<-180 or >180...." << "NE azpixc in degrees.." << azpixc * 180 / M_PI << endl;
15372  exit(1);
15373  }
15374 
15375  azpixc = azpixc * 180 / M_PI;
15376  az2 = azpixc;
15377  geod.Direct(lat_gd[row][col], lon_gd[row][col], azpixc, dist_corn2, en_lat, en_lon);
15378 
15379  // cout<<"azpixc.."<<azpixc<<"res2 ne.."<<res2<<endl;
15380  //sw corner
15381  azpixc = (azgc - thetares - thetagrad) * degrad;//pixel bearing
15382  if (azpixc > M_PI | azpixc < -M_PI) {
15383  cout << "problem with BEARING in across-gridline method...az<-180 or >180...." << "SW azpixc in degrees.." << azpixc * 180 / M_PI << endl;
15384  exit(1);
15385  }
15386 
15387  azpixc = azpixc * 180 / M_PI;
15388  az3 = azpixc;
15389  geod.Direct(lat_gd[row][col], lon_gd[row][col], azpixc, dist_corn2, ws_lat, ws_lon);
15390 
15391  // cout<<"azpixc.."<<azpixc<<"res3..sw.."<<res3<<endl;
15392 
15393  //se corner
15394  azpixc = (azgc + thetares + thetagrad) * degrad;//pixel bearing
15395  if (azpixc > M_PI | azpixc < -M_PI) {
15396  cout << "problem with BEARING in across-gridline method...az<-180 or >180...." << "SE azpixc in degrees.." << azpixc * 180 / M_PI << endl;
15397  exit(1);
15398  }
15399 
15400  azpixc = azpixc * 180 / M_PI;
15401  az4 = azpixc;
15402  geod.Direct(lat_gd[row][col], lon_gd[row][col], azpixc, dist_corn2, es_lat, es_lon);
15403  // geod.Inverse(lat_gd[row][col],lon_gd[row][col],es_lat,es_lon,res4);
15404 
15405  latcornBox[0][0] = ws_lat;
15406  latcornBox[1][0] = wn_lat;
15407  latcornBox[2][0] = en_lat;
15408  latcornBox[3][0] = es_lat;
15409  loncornBox[0][0] = ws_lon;
15410  loncornBox[1][0] = wn_lon;
15411  loncornBox[2][0] = en_lon;
15412  loncornBox[3][0] = es_lon;
15413 
15414  //***********************************************************************************************************
15415  //left center bin
15416  //********************************************************************************************************
15417 
15418 
15419  deltaphi = (lat_gd[row][col - 1] - lat_gd[row][col]) * degrad;
15420  deltalam = (lon_gd[row][col - 1] - lon_gd[row][col]) * degrad;
15421  //across-track grid size
15422  aterm = sin(deltaphi / 2) * sin(deltaphi / 2) + cos(lat_gd[row][col - 1] * degrad) * cos(lat_gd[row][col] * degrad) * sin(deltalam / 2) * sin(deltalam / 2);
15423  bterm = 2 * atan2(sqrt(aterm), sqrt(1 - aterm));
15424  dist_u = Re * bterm; //horizontal distance Harversine in km
15425 
15426  deltaphi = (lat_gd[row][col - 1] - lat_gd[row + 1][col - 1]) * degrad;
15427  deltalam = (lon_gd[row][col - 1] - lon_gd[row + 1][col - 1]) * degrad;
15428  //along-track distance
15429  aterm = sin(deltaphi / 2) * sin(deltaphi / 2) + cos(lat_gd[row][col - 1] * degrad) * cos(lat_gd[row + 1][col - 1] * degrad) * sin(deltalam / 2) * sin(deltalam / 2);
15430  bterm = 2 * atan2(sqrt(aterm), sqrt(1 - aterm));
15431  dist_v = Re * bterm;
15432 
15433  theta = atan2(dist_v, dist_u);
15434  thetagrad = 2 * theta * 180 / M_PI;
15435  thetares = (M_PI / 2 - theta) * 180 / M_PI;
15436 
15437 
15438  //nw corner
15439  azpixc = az1;
15440  geod.Direct(lat_gd[row][col - 1], lon_gd[row][col - 1], azpixc, dist_corn2, wn_lat2, wn_lon2);
15441 
15442  // cout<<"azgc..CENTER-LEFT"<<azgc<<"azpixc.."<<azpixc<<"dist_corn.."<<dist_corn<<"dist_corn2.."<<dist_corn2<<endl;
15443  // cout<<"res1..nw."<<res1<<endl;
15444  //ne corner
15445  azpixc = az2;
15446  geod.Direct(lat_gd[row][col - 1], lon_gd[row][col - 1], azpixc, dist_corn2, en_lat2, en_lon2);
15447 
15448  // cout<<"azpixc.."<<azpixc<<"res2 ne.."<<res2<<endl;
15449  //sw corner
15450  azpixc = az3;
15451  geod.Direct(lat_gd[row][col - 1], lon_gd[row][col - 1], azpixc, dist_corn2, ws_lat2, ws_lon2);
15452 
15453  // cout<<"azpixc.."<<azpixc<<"res3..sw.."<<res3<<endl;
15454  //se corner
15455  azpixc = az4;
15456  geod.Direct(lat_gd[row][col - 1], lon_gd[row][col - 1], azpixc, dist_corn2, es_lat2, es_lon2);
15457 
15458  // cout<<"azpixc.."<<azpixc<<"res4...se.."<<res4<<endl;
15459 
15460 
15461  latcornBox[0][1] = ws_lat2;
15462  latcornBox[1][1] = wn_lat2;
15463  latcornBox[2][1] = wn_lat;
15464  latcornBox[3][1] = ws_lat;
15465  loncornBox[0][1] = ws_lon2;
15466  loncornBox[1][1] = wn_lon2;
15467  loncornBox[2][1] = wn_lon;
15468  loncornBox[3][1] = ws_lon;
15469 
15470 
15471  //******************************************************************************************************************************
15472  //right center bin
15473  //*******************************************************************************************************************************
15474  //***************************************************************************
15475  //right center bin
15476  //**************************************************************************8
15477 
15478 
15479  deltaphi = (lat_gd[row][col + 1] - lat_gd[row][col + 2]) * degrad;
15480  deltalam = (lon_gd[row][col + 1] - lon_gd[row][col + 2]) * degrad;
15481  //across-track grid size
15482  aterm = sin(deltaphi / 2) * sin(deltaphi / 2) + cos(lat_gd[row][col + 1] * degrad) * cos(lat_gd[row][col + 2] * degrad) * sin(deltalam / 2) * sin(deltalam / 2);
15483  bterm = 2 * atan2(sqrt(aterm), sqrt(1 - aterm));
15484  dist_u = Re * bterm; //horizontal distance Harversine in km
15485 
15486  deltaphi = (lat_gd[row][col + 1] - lat_gd[row + 1][col + 1]) * degrad;
15487  deltalam = (lon_gd[row][col + 1] - lon_gd[row + 1][col + 1]) * degrad;
15488  //along-track distance
15489  aterm = sin(deltaphi / 2) * sin(deltaphi / 2) + cos(lat_gd[row][col + 1] * degrad) * cos(lat_gd[row + 1][col + 1] * degrad) * sin(deltalam / 2) * sin(deltalam / 2);
15490  bterm = 2 * atan2(sqrt(aterm), sqrt(1 - aterm));
15491  dist_v = Re * bterm;
15492 
15493  theta = atan2(dist_v, dist_u);
15494  thetagrad = 2 * theta * 180 / M_PI;
15495  thetares = (M_PI / 2 - theta) * 180 / M_PI;
15496 
15497  //nw corner
15498  azpixc = az1;
15499  geod.Direct(lat_gd[row][col + 1], lon_gd[row][col + 1], azpixc, dist_corn2, wn_lat3, wn_lon3);
15500  // cout<<"azgc..CENTER-RIGHT..."<<azgc<<"azpixc.."<<azpixc<<"dist_corn.."<<dist_corn<<"dist_corn2.."<<dist_corn2<<endl;
15501  // cout<<"res1..nw."<<res1<<endl;
15502 
15503  //ne corner
15504  azpixc = az2;
15505  geod.Direct(lat_gd[row][col + 1], lon_gd[row][col + 1], azpixc, dist_corn2, en_lat3, en_lon3);
15506  // cout<<"azpixc.."<<azpixc<<"res2 ne.."<<res2<<endl;
15507  //sw corner
15508  azpixc = az3;
15509  geod.Direct(lat_gd[row][col + 1], lon_gd[row][col + 1], azpixc, dist_corn2, ws_lat3, ws_lon3);
15510  // cout<<"azpixc.."<<azpixc<<"res3..sw.."<<res3<<endl;
15511  //se corner
15512  azpixc = az4;
15513  geod.Direct(lat_gd[row][col + 1], lon_gd[row][col + 1], azpixc, dist_corn2, es_lat3, es_lon3);
15514  // cout<<"azpixc.."<<azpixc<<"res4...se.."<<res4<<endl;
15515 
15516  latcornBox[0][2] = es_lat;
15517  latcornBox[1][2] = en_lat;
15518  latcornBox[2][2] = en_lat3;
15519  latcornBox[3][2] = es_lat3;
15520  loncornBox[0][2] = es_lon;
15521  loncornBox[1][2] = en_lon;
15522  loncornBox[2][2] = en_lon3;
15523  loncornBox[3][2] = es_lon3;
15524 
15525  //******************************************************************************************************
15526  //upper center bin
15527  //*****************************************************************************************************
15528 
15529 
15530  deltaphi = (lat_gd[row + 1][col] - lat_gd[row + 1][col + 1]) * degrad;
15531  deltalam = (lon_gd[row + 1][col] - lon_gd[row + 1][col + 1]) * degrad;
15532  //across-track grid size
15533  aterm = sin(deltaphi / 2) * sin(deltaphi / 2) + cos(lat_gd[row + 1][col] * degrad) * cos(lat_gd[row + 1][col + 1] * degrad) * sin(deltalam / 2) * sin(deltalam / 2);
15534  bterm = 2 * atan2(sqrt(aterm), sqrt(1 - aterm));
15535  dist_u = Re * bterm; //horizontal distance Harversine in km
15536 
15537  deltaphi = (lat_gd[row + 2][col] - lat_gd[row + 1][col]) * degrad;
15538  deltalam = (lon_gd[row + 2][col] - lon_gd[row + 1][col]) * degrad;
15539  //along-track distance
15540  aterm = sin(deltaphi / 2) * sin(deltaphi / 2) + cos(lat_gd[row + 1][col] * degrad) * cos(lat_gd[row + 2][col] * degrad) * sin(deltalam / 2) * sin(deltalam / 2);
15541  bterm = 2 * atan2(sqrt(aterm), sqrt(1 - aterm));
15542  dist_v = Re * bterm;
15543 
15544  theta = atan2(dist_v, dist_u);
15545  thetagrad = 2 * theta * 180 / M_PI;
15546  thetares = (M_PI / 2 - theta) * 180 / M_PI;
15547  //nw corner
15548  azpixc = az1;
15549  geod.Direct(lat_gd[row + 1][col], lon_gd[row + 1][col], azpixc, dist_corn2, wn_lat4, wn_lon4);
15550  // cout<<"azgc..CENTER-UPPER..."<<azgc<<"azpixc.."<<azpixc<<"dist_corn.."<<dist_corn<<"dist_corn2.."<<dist_corn2<<endl;
15551  // cout<<"res1..nw."<<res1<<endl;
15552  //ne corner
15553  azpixc = az2;
15554  geod.Direct(lat_gd[row + 1][col], lon_gd[row + 1][col], azpixc, dist_corn2, en_lat4, en_lon4);
15555  // cout<<"azpixc.."<<azpixc<<"res2 ne.."<<res2<<endl;
15556  //sw corner
15557  azpixc = az3;
15558  geod.Direct(lat_gd[row + 1][col], lon_gd[row + 1][col], azpixc, dist_corn2, ws_lat4, ws_lon4);
15559  // cout<<"azpixc.."<<azpixc<<"res3..sw.."<<res3<<endl;
15560  //se corner
15561  azpixc = az4;
15562  geod.Direct(lat_gd[row + 1][col], lon_gd[row + 1][col], azpixc, dist_corn2, es_lat4, es_lon4);
15563 
15564  latcornBox[0][3] = wn_lat;
15565  latcornBox[1][3] = wn_lat4;
15566  latcornBox[2][3] = en_lat4;
15567  latcornBox[3][3] = en_lat;
15568  loncornBox[0][3] = wn_lon;
15569  loncornBox[1][3] = wn_lon4;
15570  loncornBox[2][3] = en_lon4;
15571  loncornBox[3][3] = en_lon;
15572 
15573  //********************************************************
15574  //upper left bin
15575  //*******************************************************
15576 
15577 
15578  deltaphi = (lat_gd[row + 1][col - 1] - lat_gd[row + 1][col]) * degrad;
15579  deltalam = (lon_gd[row + 1][col - 1] - lon_gd[row + 1][col]) * degrad;
15580  //across-track grid size
15581  aterm = sin(deltaphi / 2) * sin(deltaphi / 2) + cos(lat_gd[row + 1][col - 1] * degrad) * cos(lat_gd[row + 1][col] * degrad) * sin(deltalam / 2) * sin(deltalam / 2);
15582  bterm = 2 * atan2(sqrt(aterm), sqrt(1 - aterm));
15583  dist_u = Re * bterm; //horizontal distance Harversine in km
15584 
15585  deltaphi = (lat_gd[row + 2][col - 1] - lat_gd[row + 1][col - 1]) * degrad;
15586  deltalam = (lon_gd[row + 2][col - 1] - lon_gd[row + 1][col - 1]) * degrad;
15587  //along-track distance
15588  aterm = sin(deltaphi / 2) * sin(deltaphi / 2) + cos(lat_gd[row + 1][col - 1] * degrad) * cos(lat_gd[row + 2][col - 1] * degrad) * sin(deltalam / 2) * sin(deltalam / 2);
15589  bterm = 2 * atan2(sqrt(aterm), sqrt(1 - aterm));
15590  dist_v = Re * bterm;
15591 
15592  theta = atan2(dist_v, dist_u);
15593  thetagrad = 2 * theta * 180 / M_PI;
15594  thetares = (M_PI / 2 - theta) * 180 / M_PI;
15595 
15596  //nw corner
15597  azpixc = az1;
15598  geod.Direct(lat_gd[row + 1][col - 1], lon_gd[row + 1][col - 1], azpixc, dist_corn2, wn_lat5, wn_lon5);
15599  // cout<<"azgc..LEFT-UPPER..."<<azgc<<"azpixc.."<<azpixc<<"dist_corn.."<<dist_corn<<"dist_corn2.."<<dist_corn2<<endl;
15600  // cout<<"res1..nw."<<res1<<endl;
15601  //ne corner
15602  azpixc = az2;
15603  geod.Direct(lat_gd[row + 1][col - 1], lon_gd[row + 1][col - 1], azpixc, dist_corn2, en_lat5, en_lon5);
15604  // cout<<"azpixc.."<<azpixc<<"res2 ne.."<<res2<<endl;
15605  //sw corner
15606  azpixc = az3;
15607  geod.Direct(lat_gd[row + 1][col - 1], lon_gd[row + 1][col - 1], azpixc, dist_corn2, ws_lat5, ws_lon5);
15608  // cout<<"azpixc.."<<azpixc<<"res3..sw.."<<res3<<endl;
15609  //se corner
15610  azpixc = az4;
15611  geod.Direct(lat_gd[row + 1][col - 1], lon_gd[row + 1][col - 1], azpixc, dist_corn2, es_lat5, es_lon5);
15612  // cout<<"azpixc.."<<azpixc<<"res4...se.."<<res4<<endl;
15613 
15614  latcornBox[0][4] = wn_lat2;
15615  latcornBox[1][4] = wn_lat5;
15616  latcornBox[2][4] = wn_lat4;
15617  latcornBox[3][4] = wn_lat;
15618  loncornBox[0][4] = wn_lon2;
15619  loncornBox[1][4] = wn_lon5;
15620  loncornBox[2][4] = wn_lon4;
15621  loncornBox[3][4] = wn_lon;
15622 
15623  //**************************************************************************************
15624  //upper right bin
15625  //**************************************************************************************
15626 
15627  deltaphi = (lat_gd[row + 1][col + 1] - lat_gd[row + 1][col + 2]) * degrad;
15628  deltalam = (lon_gd[row + 1][col + 1] - lon_gd[row + 1][col + 2]) * degrad;
15629  //across-track grid size
15630  aterm = sin(deltaphi / 2) * sin(deltaphi / 2) + cos(lat_gd[row + 1][col + 1] * degrad) * cos(lat_gd[row + 1][col + 2] * degrad) * sin(deltalam / 2) * sin(deltalam / 2);
15631  bterm = 2 * atan2(sqrt(aterm), sqrt(1 - aterm));
15632  dist_u = Re * bterm; //horizontal distance Harversine in km
15633 
15634  deltaphi = (lat_gd[row + 2][col + 1] - lat_gd[row + 1][col + 1]) * degrad;
15635  deltalam = (lon_gd[row + 2][col + 1] - lon_gd[row + 1][col + 1]) * degrad;
15636  //along-track distance
15637  aterm = sin(deltaphi / 2) * sin(deltaphi / 2) + cos(lat_gd[row + 1][col + 1] * degrad) * cos(lat_gd[row + 2][col + 1] * degrad) * sin(deltalam / 2) * sin(deltalam / 2);
15638  bterm = 2 * atan2(sqrt(aterm), sqrt(1 - aterm));
15639  dist_v = Re * bterm;
15640 
15641  theta = atan2(dist_v, dist_u);
15642  thetagrad = 2 * theta * 180 / M_PI;
15643  thetares = (M_PI / 2 - theta) * 180 / M_PI;
15644 
15645  //nw corner
15646  azpixc = az1;
15647  geod.Direct(lat_gd[row + 1][col + 1], lon_gd[row + 1][col + 1], azpixc, dist_corn2, wn_lat6, wn_lon6);
15648 
15649  // cout<<"azgc..RIGHT-UPPER..."<<azgc<<"azpixc.."<<azpixc<<"dist_corn.."<<dist_corn<<"dist_corn2.."<<dist_corn2<<endl;
15650  // cout<<"res1..nw."<<res1<<endl;
15651  //ne corner
15652  azpixc = az2;
15653  geod.Direct(lat_gd[row + 1][col + 1], lon_gd[row + 1][col + 1], azpixc, dist_corn2, en_lat6, en_lon6);
15654 
15655  // cout<<"azpixc.."<<azpixc<<"res2 ne.."<<res2<<endl;
15656  //sw corner
15657  azpixc = az3;
15658  geod.Direct(lat_gd[row + 1][col + 1], lon_gd[row + 1][col + 1], azpixc, dist_corn2, ws_lat6, ws_lon6);
15659 
15660  // cout<<"azpixc.."<<azpixc<<"res3..sw.."<<res3<<endl;
15661  //se corner
15662  azpixc = az4;
15663  geod.Direct(lat_gd[row + 1][col + 1], lon_gd[row + 1][col + 1], azpixc, dist_corn2, es_lat6, es_lon6);
15664 
15665  // cout<<"azpixc.."<<azpixc<<"res4...se.."<<res4<<endl;
15666  latcornBox[0][5] = en_lat;
15667  latcornBox[1][5] = en_lat4;
15668  latcornBox[2][5] = en_lat6;
15669  latcornBox[3][5] = en_lat3;
15670  loncornBox[0][5] = en_lon;
15671  loncornBox[1][5] = en_lon4;
15672  loncornBox[2][5] = en_lon6;
15673  loncornBox[3][5] = en_lon3;
15674 
15675  //************************************************************
15676  //lower center bin
15677  //*************************************************************
15678 
15679 
15680 
15681  deltaphi = (lat_gd[row - 1][col] - lat_gd[row - 1][col + 1]) * degrad;
15682  deltalam = (lon_gd[row - 1][col] - lon_gd[row - 1][col + 1]) * degrad;
15683  //across-track grid size
15684  aterm = sin(deltaphi / 2) * sin(deltaphi / 2) + cos(lat_gd[row - 1][col] * degrad) * cos(lat_gd[row - 1][col + 1] * degrad) * sin(deltalam / 2) * sin(deltalam / 2);
15685  bterm = 2 * atan2(sqrt(aterm), sqrt(1 - aterm));
15686  dist_u = Re * bterm; //horizontal distance Harversine in km
15687 
15688  deltaphi = (lat_gd[row - 1][col] - lat_gd[row][col]) * degrad;
15689  deltalam = (lon_gd[row - 1][col] - lon_gd[row][col]) * degrad;
15690  //along-track distance
15691  aterm = sin(deltaphi / 2) * sin(deltaphi / 2) + cos(lat_gd[row - 1][col] * degrad) * cos(lat_gd[row][col] * degrad) * sin(deltalam / 2) * sin(deltalam / 2);
15692  bterm = 2 * atan2(sqrt(aterm), sqrt(1 - aterm));
15693  dist_v = Re * bterm;
15694 
15695  theta = atan2(dist_v, dist_u);
15696  thetagrad = 2 * theta * 180 / M_PI;
15697  thetares = (M_PI / 2 - theta) * 180 / M_PI;
15698 
15699  //nw corner
15700  azpixc = az1;
15701  geod.Direct(lat_gd[row - 1][col], lon_gd[row - 1][col], azpixc, dist_corn2, wn_lat7, wn_lon7);
15702  // cout<<"azgc..LOWER CENTER..."<<azgc<<"azpixc.."<<azpixc<<"dist_corn.."<<dist_corn<<"dist_corn2.."<<dist_corn2<<endl;
15703  // cout<<"res1..nw."<<res1<<endl;
15704  //ne corner
15705  azpixc = az2;
15706  geod.Direct(lat_gd[row - 1][col], lon_gd[row - 1][col], azpixc, dist_corn2, en_lat7, en_lon7);
15707  // cout<<"azpixc.."<<azpixc<<"res2 ne.."<<res2<<endl;
15708  //sw corner
15709  azpixc = az3;
15710  geod.Direct(lat_gd[row - 1][col], lon_gd[row - 1][col], azpixc, dist_corn2, ws_lat7, ws_lon7);
15711 
15712  // cout<<"azpixc.."<<azpixc<<"res3..sw.."<<res3<<endl;
15713  //se corner
15714  azpixc = az4;
15715  geod.Direct(lat_gd[row - 1][col], lon_gd[row - 1][col], azpixc, dist_corn2, es_lat7, es_lon7);
15716 
15717  // cout<<"azpixc.."<<azpixc<<"res4...se.."<<res4<<endl;
15718  latcornBox[0][6] = ws_lat7;
15719  latcornBox[1][6] = ws_lat;
15720  latcornBox[2][6] = es_lat;
15721  latcornBox[3][6] = es_lat7;
15722  loncornBox[0][6] = ws_lon7;
15723  loncornBox[1][6] = ws_lon;
15724  loncornBox[2][6] = es_lon;
15725  loncornBox[3][6] = es_lon7;
15726 
15727  //******************************************************************
15728  //lower left bin
15729  //****************************************************************
15730 
15731 
15732  deltaphi = (lat_gd[row - 1][col - 1] - lat_gd[row - 1][col]) * degrad;
15733  deltalam = (lon_gd[row - 1][col - 1] - lon_gd[row - 1][col]) * degrad;
15734  //across-track grid size
15735  aterm = sin(deltaphi / 2) * sin(deltaphi / 2) + cos(lat_gd[row - 1][col - 1] * degrad) * cos(lat_gd[row - 1][col] * degrad) * sin(deltalam / 2) * sin(deltalam / 2);
15736  bterm = 2 * atan2(sqrt(aterm), sqrt(1 - aterm));
15737  dist_u = Re * bterm; //horizontal distance Harversine in km
15738 
15739  deltaphi = (lat_gd[row - 1][col - 1] - lat_gd[row][col - 1]) * degrad;
15740  deltalam = (lon_gd[row - 1][col - 1] - lon_gd[row][col - 1]) * degrad;
15741  //along-track distance
15742  aterm = sin(deltaphi / 2) * sin(deltaphi / 2) + cos(lat_gd[row - 1][col - 1] * degrad) * cos(lat_gd[row][col - 1] * degrad) * sin(deltalam / 2) * sin(deltalam / 2);
15743  bterm = 2 * atan2(sqrt(aterm), sqrt(1 - aterm));
15744  dist_v = Re * bterm;
15745 
15746  theta = atan2(dist_v, dist_u);
15747  thetagrad = 2 * theta * 180 / M_PI;
15748  thetares = (M_PI / 2 - theta) * 180 / M_PI;
15749 
15750  //nw corner
15751  azpixc = az1;
15752  geod.Direct(lat_gd[row - 1][col - 1], lon_gd[row - 1][col - 1], azpixc, dist_corn2, wn_lat8, wn_lon8);
15753  // cout<<"azgc..LOWER LEFT..."<<azgc<<"azpixc.."<<azpixc<<"dist_corn.."<<dist_corn<<"dist_corn2.."<<dist_corn2<<endl;
15754  // cout<<"res1..nw."<<res1<<endl;
15755  //ne corner
15756  azpixc = az2;
15757  geod.Direct(lat_gd[row - 1][col - 1], lon_gd[row - 1][col - 1], azpixc, dist_corn2, en_lat8, en_lon8);
15758  // cout<<"azpixc.."<<azpixc<<"res2 ne.."<<res2<<endl;
15759  //sw corner
15760  azpixc = az3;
15761  geod.Direct(lat_gd[row - 1][col - 1], lon_gd[row - 1][col - 1], azpixc, dist_corn2, ws_lat8, ws_lon8);
15762  // cout<<"azpixc.."<<azpixc<<"res3..sw.."<<res3<<endl;
15763  //se corner
15764  azpixc = az4;
15765  geod.Direct(lat_gd[row - 1][col - 1], lon_gd[row - 1][col - 1], azpixc, dist_corn2, es_lat8, es_lon8);
15766 
15767  // cout<<"azpixc.."<<azpixc<<"res4...se.."<<res4<<endl;
15768  latcornBox[0][7] = ws_lat8;
15769  latcornBox[1][7] = ws_lat2;
15770  latcornBox[2][7] = ws_lat;
15771  latcornBox[3][7] = ws_lat7;
15772  loncornBox[0][7] = ws_lon8;
15773  loncornBox[1][7] = ws_lon2;
15774  loncornBox[2][7] = ws_lon;
15775  loncornBox[3][7] = ws_lon7;
15776 
15777  //******************************************************************
15778  //lower right bin
15779  //****************************************************************
15780 
15781  deltaphi = (lat_gd[row - 1][col + 1] - lat_gd[row - 1][col + 2]) * degrad;
15782  deltalam = (lon_gd[row - 1][col + 1] - lon_gd[row - 1][col + 2]) * degrad;
15783  //across-track grid size
15784  aterm = sin(deltaphi / 2) * sin(deltaphi / 2) + cos(lat_gd[row - 1][col + 1] * degrad) * cos(lat_gd[row - 1][col + 2] * degrad) * sin(deltalam / 2) * sin(deltalam / 2);
15785  bterm = 2 * atan2(sqrt(aterm), sqrt(1 - aterm));
15786  dist_u = Re * bterm; //horizontal distance Harversine in km
15787 
15788  deltaphi = (lat_gd[row - 1][col + 1] - lat_gd[row][col + 1]) * degrad;
15789  deltalam = (lon_gd[row - 1][col + 1] - lon_gd[row][col + 1]) * degrad;
15790  //along-track distance
15791  aterm = sin(deltaphi / 2) * sin(deltaphi / 2) + cos(lat_gd[row - 1][col + 1] * degrad) * cos(lat_gd[row][col + 1] * degrad) * sin(deltalam / 2) * sin(deltalam / 2);
15792  bterm = 2 * atan2(sqrt(aterm), sqrt(1 - aterm));
15793  dist_v = Re * bterm;
15794 
15795  theta = atan2(dist_v, dist_u);
15796  thetagrad = 2 * theta * 180 / M_PI;
15797  thetares = (M_PI / 2 - theta) * 180 / M_PI;
15798 
15799  //nw corner
15800  azpixc = az1;
15801  geod.Direct(lat_gd[row - 1][col + 1], lon_gd[row - 1][col + 1], azpixc, dist_corn2, wn_lat9, wn_lon9);
15802  // cout<<"azgc..LOWER RIGHT..."<<azgc<<"azpixc.."<<azpixc<<"dist_corn.."<<dist_corn<<"dist_corn2.."<<dist_corn2<<endl;
15803  // cout<<"res1..nw."<<res1<<endl;
15804  //ne corner
15805  azpixc = az2;
15806  geod.Direct(lat_gd[row - 1][col + 1], lon_gd[row - 1][col + 1], azpixc, dist_corn2, en_lat9, en_lon9);
15807  // cout<<"azpixc.."<<azpixc<<"res2 ne.."<<res2<<endl;
15808  //sw corner
15809  azpixc = az3;
15810  geod.Direct(lat_gd[row - 1][col + 1], lon_gd[row - 1][col + 1], azpixc, dist_corn2, ws_lat9, ws_lon9);
15811  // cout<<"azpixc.."<<azpixc<<"res3..sw.."<<res3<<endl;
15812  //se corner
15813  azpixc = az4;
15814  geod.Direct(lat_gd[row - 1][col + 1], lon_gd[row - 1][col + 1], azpixc, dist_corn2, es_lat9, es_lon9);
15815  // cout<<"azpixc.."<<azpixc<<"res4...se.."<<res4<<endl;
15816  latcornBox[0][8] = es_lat7;
15817  latcornBox[1][8] = es_lat;
15818  latcornBox[2][8] = es_lat3;
15819  latcornBox[3][8] = es_lat9;
15820  loncornBox[0][8] = es_lon7;
15821  loncornBox[1][8] = es_lon;
15822  loncornBox[2][8] = es_lon3;
15823  loncornBox[3][8] = es_lon9;
15824 
15825 
15826 
15827  return 0;
15828  }
15829 
15830 
15831 
15832 
15833  int32_t L1C::pixcornBox(l1c_filehandle* l1cfile, L1C_input* l1cinput, float dist_u, float dist_v, float azpix, int32_t scanline, int32_t pix, float pixlat, float pixlon, float pixLt, short gd_row, short gd_col, float** lat_gd, float** lon_gd, Polygon_t& pixelPoly) {
15834 
15835  double lat_cnw, lat_cne, lat_csw, lat_cse, lon_cnw, lon_cne, lon_csw, lon_cse;
15836  float azpixc;
15837  float theta, thetares, dist_corn, thetagrad;
15838 
15839  Geodesic geod(Constants::WGS84_a(), Constants::WGS84_f());
15840 
15841  //using namespace bg;
15842  // Polygon_t pixelPoly;
15843  // Box_t pixelBox;
15844  // Point_t pixelPoint;
15845 
15846 
15847 
15848  //******* M_PIXEL CORNERS *****************************
15849  //***************************************************
15850  dist_corn = 0.5 * (sqrt(dist_u * dist_u + dist_v * dist_v)) * 1000;//distane center to corner in meters
15851 
15852  theta = atan2(dist_v, dist_u);
15853  thetagrad = 2 * theta * 180 / M_PI;
15854  thetares = (M_PI / 2 - theta) * 180 / M_PI;
15855 
15856  //nw corner
15857  azpixc = (azpix - thetares) * degrad;//pixel bearing
15858  if (azpixc<-M_PI | azpixc>M_PI) { cout << "error in nw corner..azpixc" << azpixc << endl;exit(1); }
15859  azpixc = azpixc * 180 / M_PI;
15860  // cout<<"azpixc nw...."<<azpixc<<endl;
15861  geod.Direct(pixlat, pixlon, azpixc, dist_corn, lat_cnw, lon_cnw);
15862  // geod.Inverse(pixlat,pixlon,lat_cnw,lon_cnw,res1);
15863  //ne corner (sw-180)
15864  azpixc = (azpix + thetares) * degrad;//pixel bearing
15865  if (azpixc<-M_PI | azpixc>M_PI) { cout << "error in ne corner..azpixc" << azpixc << endl;exit(1); }
15866  azpixc = azpixc * 180 / M_PI;
15867  // cout<<"azpixc ne...."<<azpixc<<endl;
15868  geod.Direct(pixlat, pixlon, azpixc, dist_corn, lat_cne, lon_cne);
15869  // geod.Inverse(pixlat,pixlon,lat_cne,lon_cne,res2);
15870  //sw corner
15871  // azpixc=(azpix-45-90)*degrad;//pixel bearing
15872  azpixc = (azpix - thetares - thetagrad) * degrad;//pixel bearing
15873  if (azpixc<-M_PI | azpixc>M_PI) { cout << "error in sw corner..azpixc" << azpixc << endl;exit(1); }
15874  azpixc = azpixc * 180 / M_PI;
15875  // cout<<"azpixc sw....."<<azpixc<<endl;
15876  geod.Direct(pixlat, pixlon, azpixc, dist_corn, lat_csw, lon_csw);
15877  //geod.Inverse(pixlat,pixlon,lat_csw,lon_csw,res3);
15878 
15879  //se corner (nw-180)
15880  azpixc = (azpix + thetares + thetagrad) * degrad;//pixel bearingi
15881  if (azpixc<-M_PI | azpixc>M_PI) { cout << "error in se corner..azpixc" << azpixc << endl;exit(1); }
15882  // azpixc=(azpix+45+90)*degrad;//pixel bearing
15883  azpixc = azpixc * 180 / M_PI;
15884  // cout<<"azpix se...."<<azpixc<<endl;
15885  geod.Direct(pixlat, pixlon, azpixc, dist_corn, lat_cse, lon_cse);
15886 
15887  std::string ws_lon_str, ws_lat_str, wn_lon_str, wn_lat_str, en_lon_str, en_lat_str, es_lon_str, es_lat_str, pixstr;
15888 
15889  ws_lon_str = std::to_string(lon_csw);
15890  ws_lat_str = std::to_string(lat_csw);
15891  wn_lon_str = std::to_string(lon_cnw);
15892  wn_lat_str = std::to_string(lat_cnw);
15893  en_lon_str = std::to_string(lon_cne);
15894  en_lat_str = std::to_string(lat_cne);
15895  es_lon_str = std::to_string(lon_cse);
15896  es_lat_str = std::to_string(lat_cse);
15897 
15898 
15899  pixstr = "POLYGON((" + ws_lon_str + " " + ws_lat_str + "," + wn_lon_str + " " + wn_lat_str + "," + en_lon_str + " " + en_lat_str + "," + es_lon_str + " " + es_lat_str + "," + ws_lon_str + " " + ws_lat_str + "))";
15900  bg::read_wkt(pixstr, pixelPoly);
15901 
15902  if (lon_csw > lon_cse | lon_cnw > lon_cne | lat_csw > lat_cnw | lat_cse > lat_cne) {
15903  cout << "lon_csw>lon_cse | lon_cnw>lon_cne | lat_csw>lat_cnw | lat_cse>lat_cne//" << lon_csw << lon_cse << lon_cnw << lon_cne << lat_csw << lat_cnw << lat_cse << lat_cne << endl;
15904  cout << "corners are switched for pixel.." << pix + 1 << endl;
15905  }
15906 
15907 
15908 
15909  return 0;
15910  }
15911 
15912 
15913 
15914 
15915  int32_t L1C::pix_corners4_l1c3(l1c_filehandle* l1cfile, L1C_input* l1cinput, float dist_u, float dist_v, float azpix, int32_t scanline, int32_t pix, float pixlat, float pixlon, float pixLt, short gd_row, short gd_col, float** lat_gd, float** lon_gd, double areaFracBox[3][3], double areabinBox[3][3]) {
15916 
15917  double lat_cnw, lat_cne, lat_csw, lat_cse, lon_cnw, lon_cne, lon_csw, lon_cse;
15918  float azpixc;
15919  int32_t num_gridlines, nbinx;
15920  float theta, thetares, dist_corn, thetagrad;
15921 
15922 
15923  Geodesic geod(Constants::WGS84_a(), Constants::WGS84_f());
15924 
15925  //using namespace bg;
15926  Polygon_t pixelPoly;
15927 
15928  num_gridlines = l1cfile->num_gridlines;
15929  nbinx = l1cfile->nbinx;
15930 
15931  //******* M_PIXEL CORNERS *****************************
15932  //***************************************************
15933  dist_corn = 0.5 * (sqrt(dist_u * dist_u + dist_v * dist_v)) * 1000;//distane center to corner in meters
15934 
15935  theta = atan2(dist_v, dist_u);
15936  thetagrad = 2 * theta * 180 / M_PI;
15937  thetares = (M_PI / 2 - theta) * 180 / M_PI;
15938 
15939  //nw corner
15940  azpixc = (azpix - thetares) * degrad;//pixel bearing
15941  if (azpixc<-M_PI | azpixc>M_PI) { cout << "error in nw corner..azpixc" << azpixc << endl;exit(1); }
15942  azpixc = azpixc * 180 / M_PI;
15943  // cout<<"azpixc nw...."<<azpixc<<endl;
15944  geod.Direct(pixlat, pixlon, azpixc, dist_corn, lat_cnw, lon_cnw);
15945  // geod.Inverse(pixlat,pixlon,lat_cnw,lon_cnw,res1);
15946  //ne corner (sw-180)
15947  azpixc = (azpix + thetares) * degrad;//pixel bearing
15948  if (azpixc<-M_PI | azpixc>M_PI) { cout << "error in ne corner..azpixc" << azpixc << endl;exit(1); }
15949  azpixc = azpixc * 180 / M_PI;
15950  // cout<<"azpixc ne...."<<azpixc<<endl;
15951  geod.Direct(pixlat, pixlon, azpixc, dist_corn, lat_cne, lon_cne);
15952  // geod.Inverse(pixlat,pixlon,lat_cne,lon_cne,res2);
15953  //sw corner
15954  // azpixc=(azpix-45-90)*degrad;//pixel bearing
15955  azpixc = (azpix - thetares - thetagrad) * degrad;//pixel bearing
15956  if (azpixc<-M_PI | azpixc>M_PI) { cout << "error in sw corner..azpixc" << azpixc << endl;exit(1); }
15957  azpixc = azpixc * 180 / M_PI;
15958  // cout<<"azpixc sw....."<<azpixc<<endl;
15959  geod.Direct(pixlat, pixlon, azpixc, dist_corn, lat_csw, lon_csw);
15960  //geod.Inverse(pixlat,pixlon,lat_csw,lon_csw,res3);
15961 
15962  //se corner (nw-180)
15963  azpixc = (azpix + thetares + thetagrad) * degrad;//pixel bearingi
15964  if (azpixc<-M_PI | azpixc>M_PI) { cout << "error in se corner..azpixc" << azpixc << endl;exit(1); }
15965  // azpixc=(azpix+45+90)*degrad;//pixel bearing
15966  azpixc = azpixc * 180 / M_PI;
15967  // cout<<"azpix se...."<<azpixc<<endl;
15968  geod.Direct(pixlat, pixlon, azpixc, dist_corn, lat_cse, lon_cse);
15969  //geod.Inverse(pixlat,pixlon,lat_cse,lon_cse,res4);
15970 
15971  /* cout<<"pix.."<<pix+1<<"azpix.."<<azpix<<"theta.."<<thetagrad<<"thetares.."<<thetares<<endl;
15972  cout<<"res1."<<res1<<"res2."<<res2<<"res3.."<<res3<<"res4.."<<res4<<endl;
15973  cout<<"pix sw corner..lat."<<lat_csw<<"sw corner lon.."<<lon_csw<<endl;
15974  cout<<"pix nw corner..lat."<<lat_cnw<<"nw corner lon.."<<lon_cnw<<endl;
15975  cout<<"pix ne corner..lat."<<lat_cne<<"ne corner lon.."<<lon_cne<<endl;
15976  cout<<"pix se corner..lat."<<lat_cse<<"se corner lon.."<<lon_cse<<endl;
15977  */
15978 
15979 
15980  std::string ws_lon_str, ws_lat_str, wn_lon_str, wn_lat_str, en_lon_str, en_lat_str, es_lon_str, es_lat_str, pixstr;
15981 
15982  ws_lon_str = std::to_string(lon_csw);
15983  ws_lat_str = std::to_string(lat_csw);
15984  wn_lon_str = std::to_string(lon_cnw);
15985  wn_lat_str = std::to_string(lat_cnw);
15986  en_lon_str = std::to_string(lon_cne);
15987  en_lat_str = std::to_string(lat_cne);
15988  es_lon_str = std::to_string(lon_cse);
15989  es_lat_str = std::to_string(lat_cse);
15990 
15991 
15992  pixstr = "POLYGON((" + ws_lon_str + " " + ws_lat_str + "," + wn_lon_str + " " + wn_lat_str + "," + en_lon_str + " " + en_lat_str + "," + es_lon_str + " " + es_lat_str + "," + ws_lon_str + " " + ws_lat_str + "))";
15993  bg::read_wkt(pixstr, pixelPoly);
15994 
15995  if (lon_csw > lon_cse | lon_cnw > lon_cne | lat_csw > lat_cnw | lat_cse > lat_cne) {
15996  cout << "lon_csw>lon_cse | lon_cnw>lon_cne | lat_csw>lat_cnw | lat_cse>lat_cne//" << lon_csw << lon_cse << lon_cnw << lon_cne << lat_csw << lat_cnw << lat_cse << lat_cne << endl;
15997  cout << "corners are switched for pixel.." << pix + 1 << endl;
15998  }
15999 
16000 
16001  if (gd_row >= 1 && gd_col >= 1 && gd_row < num_gridlines - 1 && gd_col < nbinx - 1) {
16002  /*
16003  latcornBox=allocate2d_double(4,9);//4 corners, 9 grid cells
16004  loncornBox=allocate2d_double(4,9);
16005 
16006  for(int i=0;i<4;i++){
16007  for(int j=0;j<9;j++){
16008  latcornBox[i][j]=0.;
16009  loncornBox[i][j]=0.;
16010  }}
16011  gwindowTopix_l1c(l1cfile,l1cinput,gd_row, gd_col,lat_gd,lon_gd,latcornBox,loncornBox);
16012 
16013 
16014  for(int i=0;i<4;i++){
16015  for(int j=0;j<9;j++){
16016  cout<<"corner#..."<<i<<"gridcell#..."<<j<<"latcorn.."<<latcornBox[i][j]<<"loncorn.."<<loncornBox[i][j]<<endl;
16017  }}
16018 
16019 
16020 
16021 
16022  // binIntersectsPix4corn4_l1c(l1cfile,l1cinput,gd_row, gd_col,lat_gd,lon_gd,pixelPoly,areaFracBox,areabinBox);
16023  // exit(1);
16024 
16025 
16026  delete [] (latcornBox);
16027  delete [] (loncornBox);
16028 
16029  latcornBox=nullptr;
16030  loncornBox=nullptr;
16031  */
16032 
16033  /*
16034  int ar=0,ac=0;
16035  size_t fracells=0;
16036 
16037  for(int gr=gd_row-1;gr<gd_row+2;gr++){
16038  for(int gc=gd_col-1;gc<gd_col+2;gc++){
16039  // cout<<"ar.."<<ar<<"ac.."<<ac<<"areafracbox.."<<areaFracBox[ar][ac]<<"areabin.."<<areabinBox[ar][ac]<<endl;
16040  if(areaFracBox[ar][ac]>0) fracells++;
16041 
16042  if(pixLt>0.0){
16043  Ltfracsum[gr][gc]+=pixLt*areaFracBox[ar][ac];
16044  areafracsum[gr][gc]+=areaFracBox[ar][ac];
16045  nobs_perbin[gr][gc]+=1;
16046  }
16047  else{
16048  Ltfracsum[gr][gc]+=0.0;
16049  areafracsum[gr][gc]+=0.0;
16050  nobs_perbin[gr][gc]+=0;
16051  }
16052  ac++;
16053  }
16054  ac=0;
16055  ar++;
16056  }
16057 
16058  if(fracells>5){
16059  cout<<"Number of gridcells with pixel fractions CANNOT be greater than 5!!!...................fracells = ......."<<fracells<<endl;
16060  exit(1);
16061  }
16062  */
16063 
16064  }//if gd_row gd_col
16065 
16066 
16067  //exit(1);
16068 
16069  return 0;
16070  }
16071 
16072 
16073 
16074 
16075  int32_t L1C::pix_corners4_l1c2(l1c_filehandle* l1cfile, L1C_input* l1cinput, float dist_u, float dist_v, float azpix, int32_t scanline, int32_t pix, float pixlat, float pixlon, float pixLt, short gd_row, short gd_col, float** lat_gd, float** lon_gd, double areaFracBox[3][3], double** Ltfracsum, double** areafracsum, float** nobs_perbin) { //compute pixel corners for a specific line,pixel and file
16076 
16077  double lat_cnw, lat_cne, lat_csw, lat_cse, lon_cnw, lon_cne, lon_csw, lon_cse;
16078  float azpixc;
16079  int32_t num_gridlines, nbinx;
16080  double areabinBox[3][3];
16081  float theta, thetares, dist_corn, thetagrad;
16082  double res1, res2, res3, res4;//pixel resolution in meters
16083  Geodesic geod(Constants::WGS84_a(), Constants::WGS84_f());
16084 
16085  //using namespace bg;
16086  Polygon_t pixelPoly;
16087  num_gridlines = l1cfile->num_gridlines;
16088  nbinx = l1cfile->nbinx;
16089 
16090 
16091  //******* M_PIXEL CORNERS *****************************
16092  //***************************************************
16093 
16094  // ad=0.5*(sqrt(dist_u*dist_u+dist_v*dist_v)/Re);
16095  dist_corn = 0.5 * (sqrt(dist_u * dist_u + dist_v * dist_v)) * 1000;//distane center to corner in meters
16096 
16097 
16098  theta = atan2(dist_v, dist_u);
16099  thetagrad = 2 * theta * 180 / M_PI;
16100  thetares = (M_PI / 2 - theta) * 180 / M_PI;
16101 
16102  //nw corner
16103  azpixc = (azpix - thetares) * degrad;//pixel bearing
16104  if (azpixc<-M_PI | azpixc>M_PI) { cout << "error in nw corner..azpixc" << azpixc << endl;exit(1); }
16105  azpixc = azpixc * 180 / M_PI;
16106  // cout<<"azpixc nw...."<<azpixc<<endl;
16107  geod.Direct(pixlat, pixlon, azpixc, dist_corn, lat_cnw, lon_cnw);
16108  geod.Inverse(pixlat, pixlon, lat_cnw, lon_cnw, res1);
16109  // lat_cne=asin(sin(pixlat*degrad)*cos(ad)+cos(pixlat*degrad)*sin(ad)*cos(azpixc*degrad))*180./M_PI;
16110  // lon_cne=pixlon+atan2(sin(azpixc*degrad)*sin(ad)*cos(pixlat*degrad),cos(ad)-sin(pixlat*degrad)*sin(lat_cne*degrad))*180./M_PI;
16111 
16112 
16113  //ne corner (sw-180)
16114  azpixc = (azpix + thetares) * degrad;//pixel bearing
16115  if (azpixc<-M_PI | azpixc>M_PI) { cout << "error in ne corner..azpixc" << azpixc << endl;exit(1); }
16116  // azpixc=(azpix+45)*degrad;//pixel bearing
16117  /* if(azpixc>M_PI | azpixc<-M_PI){
16118  }
16119  if(azpixc<0.){
16120  azpixc=360+azpixc*180/M_PI;
16121  }
16122  else azpixc=azpixc*180/M_PI;
16123  */
16124 
16125  azpixc = azpixc * 180 / M_PI;
16126  // cout<<"azpixc ne...."<<azpixc<<endl;
16127  geod.Direct(pixlat, pixlon, azpixc, dist_corn, lat_cne, lon_cne);
16128  geod.Inverse(pixlat, pixlon, lat_cne, lon_cne, res2);
16129 
16130 
16131  //sw corner
16132  // azpixc=(azpix-45-90)*degrad;//pixel bearing
16133  azpixc = (azpix - thetares - thetagrad) * degrad;//pixel bearing
16134  if (azpixc<-M_PI | azpixc>M_PI) { cout << "error in sw corner..azpixc" << azpixc << endl;exit(1); }
16135  /* if(azpixc>M_PI | azpixc<-M_PI){
16136  // cout<<"problem with BEARING in across-gridline method...az<-180 or >180...."<<"SW azpixc in degrees.."<<azpixc*180/M_PI<<endl;
16137  }
16138  if(azpixc<0.){
16139  azpixc=360+azpixc*180/M_PI;
16140  }
16141  else azpixc=azpixc*180/M_PI;
16142  */
16143 
16144  azpixc = azpixc * 180 / M_PI;
16145  // cout<<"azpixc sw....."<<azpixc<<endl;
16146  geod.Direct(pixlat, pixlon, azpixc, dist_corn, lat_csw, lon_csw);
16147  geod.Inverse(pixlat, pixlon, lat_csw, lon_csw, res3);
16148  //lat_csw=asin(sin(pixlat*degrad)*cos(ad)+cos(pixlat*degrad)*sin(ad)*cos(azpixc*degrad))*180./M_PI;
16149  // lon_csw=pixlon+atan2(sin(azpixc*degrad)*sin(ad)*cos(pixlat*degrad),cos(ad)-sin(pixlat*degrad)*sin(lat_csw*degrad))*180./M_PI;
16150 
16151  //se corner (nw-180)
16152  azpixc = (azpix + thetares + thetagrad) * degrad;//pixel bearingi
16153  if (azpixc<-M_PI | azpixc>M_PI) { cout << "error in se corner..azpixc" << azpixc << endl;exit(1); }
16154  // azpixc=(azpix+45+90)*degrad;//pixel bearing
16155  /* if(azpixc>M_PI | azpixc<-M_PI){
16156  // cout<<"problem with BEARING in across-gridline method...az<-180 or >180...."<<"SE azpixc in degrees.."<<azpixc*180/M_PI<<endl;
16157  }
16158  if(azpixc<0.){
16159  azpixc=360+azpixc*180/M_PI;
16160  }
16161  else azpixc=azpixc*180/M_PI;
16162  */
16163  azpixc = azpixc * 180 / M_PI;
16164  // cout<<"azpix se...."<<azpixc<<endl;
16165  geod.Direct(pixlat, pixlon, azpixc, dist_corn, lat_cse, lon_cse);
16166  geod.Inverse(pixlat, pixlon, lat_cse, lon_cse, res4);
16167  // lat_cse=asin(sin(pixlat*degrad)*cos(ad)+cos(pixlat*degrad)*sin(ad)*cos(azpixc*degrad))*180./M_PI;
16168  // lon_cse=pixlon+atan2(sin(azpixc*degrad)*sin(ad)*cos(pixlat*degrad),cos(ad)-sin(pixlat*degrad)*sin(lat_cse*degrad))*180./M_PI;
16169 
16170  /*
16171  cout<<"pix.."<<pix+1<<"azpix.."<<azpix<<"theta.."<<thetagrad<<"thetares.."<<thetares<<endl;
16172  cout<<"res1."<<res1<<"res2."<<res2<<"res3.."<<res3<<"res4.."<<res4<<endl;
16173  cout<<"pix sw corner..lat."<<lat_csw<<"sw corner lon.."<<lon_csw<<endl;
16174  cout<<"pix nw corner..lat."<<lat_cnw<<"nw corner lon.."<<lon_cnw<<endl;
16175  cout<<"pix ne corner..lat."<<lat_cne<<"ne corner lon.."<<lon_cne<<endl;
16176  cout<<"pix se corner..lat."<<lat_cse<<"se corner lon.."<<lon_cse<<endl;
16177  */
16178 
16179 
16180 
16181  std::string ws_lon_str, ws_lat_str, wn_lon_str, wn_lat_str, en_lon_str, en_lat_str, es_lon_str, es_lat_str, pixstr;
16182  ws_lon_str = std::to_string(lon_csw);
16183  ws_lat_str = std::to_string(lat_csw);
16184  wn_lon_str = std::to_string(lon_cnw);
16185  wn_lat_str = std::to_string(lat_cnw);
16186  en_lon_str = std::to_string(lon_cne);
16187  en_lat_str = std::to_string(lat_cne);
16188  es_lon_str = std::to_string(lon_cse);
16189  es_lat_str = std::to_string(lat_cse);
16190 
16191 
16192  pixstr = "POLYGON((" + ws_lon_str + " " + ws_lat_str + "," + wn_lon_str + " " + wn_lat_str + "," + en_lon_str + " " + en_lat_str + "," + es_lon_str + " " + es_lat_str + "," + ws_lon_str + " " + ws_lat_str + "))";
16193  bg::read_wkt(pixstr, pixelPoly);
16194 
16195  if (lon_csw > lon_cse | lon_cnw > lon_cne | lat_csw > lat_cnw | lat_cse > lat_cne) {
16196  cout << "lon_csw>lon_cse | lon_cnw>lon_cne | lat_csw>lat_cnw | lat_cse>lat_cne//" << lon_csw << lon_cse << lon_cnw << lon_cne << lat_csw << lat_cnw << lat_cse << lat_cne << endl;
16197  cout << "corners are switched for pixel.." << pix + 1 << endl;
16198  }
16199 
16200  // exit(1);
16201 
16202  //*** L1C grid cell *******************************************************************************
16203  for (int ar = 0;ar < 3;ar++) {
16204  for (int ac = 0;ac < 3;ac++) {
16205  areaFracBox[ar][ac] = 0.;
16206  areabinBox[ar][ac] = 0.;
16207  ac++;
16208  }
16209  ar++;
16210  }
16211 
16212 
16213 
16214  if (gd_row >= 1 && gd_col >= 1 && gd_row < num_gridlines - 1 && gd_col < nbinx - 1) {
16215 
16216  binIntersectsPix4corn4_l1c(l1cfile, l1cinput, gd_row, gd_col, lat_gd, lon_gd, pixelPoly, areaFracBox, areabinBox);
16217  // exit(1);
16218 
16219  int ar = 0, ac = 0;
16220  size_t fracells = 0;
16221  for (int gr = gd_row - 1;gr < gd_row + 2;gr++) {
16222  for (int gc = gd_col - 1;gc < gd_col + 2;gc++) {
16223 
16224  // cout<<"ar.."<<ar<<"ac.."<<ac<<"areafracbox.."<<areaFracBox[ar][ac]<<"areabin.."<<areabinBox[ar][ac]<<endl;
16225  if (areaFracBox[ar][ac] > 0) fracells++;
16226 
16227  if (pixLt > 0.0) {
16228  Ltfracsum[gr][gc] += pixLt * areaFracBox[ar][ac];
16229  areafracsum[gr][gc] += areaFracBox[ar][ac];
16230  nobs_perbin[gr][gc] += 1;
16231  }
16232  else {
16233  Ltfracsum[gr][gc] += 0.0;
16234  areafracsum[gr][gc] += 0.0;
16235  nobs_perbin[gr][gc] += 0;
16236  }
16237  ac++;
16238  }
16239  ac = 0;
16240  ar++;
16241  }
16242 
16243  if (fracells > 5) {
16244  cout << "Number of gridcells with pixel fractions CANNOT be greater than 5!!!...................fracells = ......." << fracells << endl;
16245  exit(1);
16246  }
16247  }
16248  else {
16249  // cout<<"pix out of the L1Cgrid.........................."<<"pix#..."<<pix+1<<"pixlat.."<<pixlat<<"pixlon..."<<pixlon<<endl;
16250  }
16251 
16252 
16253  return 0;
16254  }
16255 
16256 
16257 
16258  int32_t L1C::xy_pixsize_sf3(const char* filename, l1c_filehandle* l1cfile, L1C_input* l1cinput, float** pix_size_u, float** pix_size_v, float** lat_gd, float** lon_gd, double** lat_cgd, double** lon_cgd, float** Ltfracsum, float** areabinsum, float** nobs_perbin,float **lat_asort,short **index_xy){
16259 
16260  int dimid, status;
16261  size_t start[] = { 0, 0 }, start2[] = { 0,0 };
16262  size_t count[] = { 1, 1 };
16263  size_t start3[] = { 0,0,0 }, count3[] = { 1, 1, 1 };
16264  float* latpix, * lonpix, * latpix2, * lonpix2, ** Lt_pix;
16265  float Re = 6378;
16266  float deltaphi = 0., deltalam = 0., aterm = 0., bterm, dist_u = 0., dist_v = 0., azpix = 0.;
16267  double areaFracBox[3][3];
16268 // short gd_row = 0, gd_col = 0;
16269 
16270  for (int ar = 0;ar < 3;ar++) {
16271  for (int ac = 0;ac < 3;ac++) {
16272  areaFracBox[ar][ac] = 0.;
16273  ac++;
16274  }
16275  ar++;
16276  }
16277 
16278  num_pixels = l1cfile->npix;
16279 
16280  //recompute number of gridlines based on lat limits -80 to 80 degrees
16281  //asc orbit goes from negative to positive latitude....
16282 
16283  latpix = (float*)calloc(num_pixels , sizeof(float));
16284  lonpix = (float*)calloc(num_pixels , sizeof(float));
16285  latpix2 = (float*)calloc(num_pixels , sizeof(float));
16286  lonpix2 = (float*)calloc(num_pixels , sizeof(float));
16287 
16288 
16289 
16290  /* for(int gd=0;gd<2;gd++){
16291  for(int k=0;k<nbinx;k++){
16292  cout<<"gd.."<<gd+1<<"binx.."<<k+1<<"latgd..."<<lat_gd[gd][k]<<"longd..."<<lon_gd[gd][k]<<"latgd..."<<lat_cgd[gd][k]<<"longd..."<<lon_cgd[gd][k]<<endl;
16293  }}
16294  exit(1);
16295  */
16296  cout << "inside....xy_pixsize_sf3!!.." << endl;
16297 
16298  // sbs2_sort_latgd(l1cfile, lat_gd, lat_asort, index_xy);
16299 
16300  cout << "filename..." << filename << endl;
16301  status = nc_open(filename, NC_NOWRITE, &ncid_L1B);
16302  if (status != NC_NOERR) {
16303  fprintf(stderr, "-nc_open fails.\n");
16304  exit(EXIT_FAILURE);
16305  }
16306 
16307  //Open dimensions
16308  status = nc_inq_dimid(ncid_L1B, "number_of_scans", &dimid);
16309  if (status != NC_NOERR) {
16310  fprintf(stderr, "-E- Error reading number_of_scans.\n");
16311  exit(EXIT_FAILURE);
16312  }
16313  nc_inq_dimlen(ncid_L1B, dimid, &num_scans);
16314 
16315  //read line-by-line lat/lon/Lt
16316  status = nc_inq_grp_ncid(ncid_L1B, "geolocation_data", &geoGrp);
16317  check_err(status, __LINE__, __FILE__);
16318  status = nc_inq_grp_ncid(ncid_L1B, "observation_data", &obsGrp);
16319  check_err(status, __LINE__, __FILE__);
16320  //open geo data
16321  status = nc_inq_varid(geoGrp, "latitude", &latId);//scans x velements
16322  check_err(status, __LINE__, __FILE__);
16323  status = nc_inq_varid(geoGrp, "longitude", &lonId);//scans x velements
16324  check_err(status, __LINE__, __FILE__);
16325 
16326  // num_blue_bands
16327  status = nc_inq_dimid(ncid_L1B, "blue_bands", &dimid);
16328  if (status != NC_NOERR) {
16329  fprintf(stderr, "-E- Error reading num_blue_bands.\n");
16330  exit(EXIT_FAILURE);
16331  }
16332  nc_inq_dimlen(ncid_L1B, dimid, &num_blue_bands);
16333 
16334  status = nc_inq_varid(obsGrp, "Lt_blue", &Lt_blueId);
16335  check_err(status, __LINE__, __FILE__);
16336 
16337  Lt_pix = allocate2d_float(num_blue_bands, num_pixels);
16338 
16339  //-----reading line by line-----------------------------------
16340  for (unsigned int sline = 0;sline < num_scans - 1;sline++) {
16341 
16342  //lat and lon--
16343  start[0] = sline;
16344  start[1] = 0;
16345  start2[0] = sline + 1;
16346  start2[1] = 0;
16347  count[0] = 1;
16348  count[1] = num_pixels; // 1 line at a time
16349 
16350  start3[0] = 0;
16351  start3[1] = sline;
16352  start3[2] = 0;
16353 
16354  count3[0] = num_blue_bands;
16355  count3[1] = 1; // 1 line at a time
16356  count3[2] = num_pixels;
16357 
16358  status = nc_get_vara_float(geoGrp, latId, start, count, latpix);
16359  status = nc_get_vara_float(geoGrp, lonId, start, count, lonpix);
16360  status = nc_get_vara_float(geoGrp, latId, start2, count, latpix2);
16361  status = nc_get_vara_float(geoGrp, lonId, start2, count, lonpix2);
16362  status = nc_get_vara_float(obsGrp, Lt_blueId, start3, count3, Lt_pix[0]);
16363 
16364  if (sline % 100 == 1) cout << "weight-binning sline..." << sline + 1 << endl;
16365 
16366  for (unsigned int pix = 0;pix < num_pixels - 1;pix++) {
16367 
16368  //across-track distance
16369  deltaphi = (latpix[pix] - latpix[pix + 1]) * degrad;
16370  deltalam = (lonpix[pix] - lonpix[pix + 1]) * degrad;
16371  aterm = sin(deltaphi / 2) * sin(deltaphi / 2) + cos(latpix[pix] * degrad) * cos(latpix[pix + 1] * degrad) * sin(deltalam / 2) * sin(deltalam / 2);
16372  bterm = 2 * atan2(sqrt(aterm), sqrt(1 - aterm));
16373  dist_u = Re * bterm; //horizontal distance Harversine in km
16374  //along-track distance
16375  deltaphi = (latpix[pix] - latpix2[pix]) * degrad;
16376  deltalam = (lonpix[pix] - lonpix2[pix]) * degrad;
16377  aterm = sin(deltaphi / 2) * sin(deltaphi / 2) + cos(latpix[pix] * degrad) * cos(latpix2[pix] * degrad) * sin(deltalam / 2) * sin(deltalam / 2);
16378  bterm = 2 * atan2(sqrt(aterm), sqrt(1 - aterm));
16379  dist_v = Re * bterm;
16380 
16381  pix_size_u[sline][pix] = dist_u;
16382  pix_size_v[sline][pix] = dist_v;
16383 
16384  //pixel azimuth
16385  azpix = atan2(sin(deltalam) * cos(latpix2[pix] * degrad), cos(latpix[pix] * degrad) * sin(latpix2[pix] * degrad) - sin(latpix[pix] * degrad) * cos(latpix2[pix] * degrad) * cos(deltaphi));
16386  if (azpix > M_PI | azpix < -M_PI) {
16387  cout << "problem with BEARING in across-gridline method...az<-180 or >180...." << "azpixc in degrees.." << azpix * 180 / M_PI << endl;
16388  exit(1);
16389  }
16390  // cout<<"azpix.."<<azpix*180/M_PI<<endl;
16391 
16392  /* if(azpix<0.){
16393  azpix=360+azpix*180/M_PI;
16394  }
16395  else azpix=azpix*180./M_PI;
16396  */
16397  azpix = azpix * 180. / M_PI;
16398 
16399 // cout << "line.." << sline + 1 << "pix #:.." << pix + 1 << "pix size.U in km." << pix_size_u[sline][pix] << "pixsize.V in km." << pix_size_v[sline][pix] << "azpix before corners4.." << azpix << endl;
16400  // pix_corners(dist_u,dist_v,azpix, sline,pix,latpix[pix],lonpix[pix]);
16401 // pix_corners3(l1cfile,dist_u,dist_v,azpix, sline,pix,latpix[pix],lonpix[pix],Lt_pix[0][pix],lat_asort,index_xy,lat_gd,lon_gd,lat_cgd,lon_cgd,areaFracBox,Ltfracsum,areabinsum,nobs_perbin);
16402  pix_corners4_l1c(l1cfile, l1cinput, dist_u, dist_v, azpix, sline, pix, latpix[pix], lonpix[pix], Lt_pix[0][pix], lat_asort, index_xy, lat_gd, lon_gd, lat_cgd, lon_cgd, areaFracBox, Ltfracsum, areabinsum, nobs_perbin);
16403 // pix_corners4_l1c2(l1cfile,l1cinput, dist_u, dist_v, azpix, sline, pix,latpix[pix], lonpix[pix], Lt_pix[0][pix], gd_row, gd_col,lat_gd,lon_gd,areaFracBox,Ltfracsum,areafracsum,nobs_perbin) {
16404 // cout<<"Lt_pix[pix].."<<Lt_pix[0][pix]<<endl;//first blue channel
16405 
16406 
16407  // exit(1);
16408  }//end pixels
16409  // exit(1);
16410 
16411  }//end lines
16412 
16413 // exit(1);
16414  status = nc_close(ncid_L1B);
16415  check_err(status, __LINE__, __FILE__);
16416 
16417  delete[](latpix);
16418  delete[](lonpix);
16419  delete[](latpix2);
16420  delete[](lonpix2);
16421  delete[](Lt_pix);
16422 
16423 
16424  return 0;
16425  }
16426 
16427 
16428 
16429 
16430  int32_t L1C::xy_pixsize_sf2(const char* filename, l1c_filehandle* l1cfile, L1C_input* l1cinput, float** pix_size_u, float** pix_size_v, float** lat_gd, float** lon_gd, double** lat_cgd, double** lon_cgd, float** Ltfracsum, float** areabinsum, float** nobs_perbin)
16431  { //single file pixel size
16432  int32_t nbinx, num_gridlines;//number of gridlines to be processed
16433  int dimid, status;
16434  size_t start[] = { 0, 0 }, start2[] = { 0,0 };
16435  size_t count[] = { 1, 1 };
16436  size_t start3[] = { 0,0,0 }, count3[] = { 1, 1, 1 };
16437  float* latpix, * lonpix, * latpix2, * lonpix2, ** Lt_pix;
16438  float Re = 6378;
16439  int32_t NY = -1, NX = -1, NY1 = -1, NY2 = -1, c1 = 1;
16440  float deltaphi = 0., deltalam = 0., aterm = 0., bterm, dist_u = 0., dist_v = 0., azpix = 0.;
16441  float** lat_asort;
16442  short** index_xy;
16443  double areaFracBox[3][3];
16444 
16445  for (int ar = 0;ar < 3;ar++) {
16446  for (int ac = 0;ac < 3;ac++) {
16447  areaFracBox[ar][ac] = 0.;
16448  ac++;
16449  }
16450  ar++;
16451  }
16452 
16453  num_gridlines = l1cfile->num_gridlines;
16454  nbinx = l1cfile->nbinx;
16455  num_pixels = l1cfile->npix;
16456 
16457 
16458 
16459  //recompute number of gridlines based on lat limits -80 to 80 degrees
16460  //asc orbit goes from negative to positive latitude....
16461  NY = num_gridlines;
16462  NX = nbinx;
16463 
16464  for (int i = 0; i < NY; i++) {
16465  for (int j = 0; j < NX; j++) {
16466  if (lat_gd[i][j] >= -80.) c1++;
16467  if (c1 == nbinx) {
16468  NY1 = i;
16469  }
16470  }
16471  if (NY1 >= 0) break;
16472  c1 = 1;
16473  }
16474 
16475  for (int i = 0;i < NY; i++) {
16476  for (int j = 0; j < NX; j++) {
16477  if (lat_gd[i][j] >= 80.) {
16478  NY2 = i - 1;
16479  }
16480  }
16481  if (NY2 >= 0) break;
16482  }
16483 
16484  l1cfile->NY1 = NY1;
16485  l1cfile->NY2 = NY2;
16486 
16487  NY = NY2 - NY1 + 1;
16488 
16489 
16490  latpix = (float*)calloc(num_pixels , sizeof(float));
16491  lonpix = (float*)calloc(num_pixels , sizeof(float));
16492  latpix2 = (float*)calloc(num_pixels , sizeof(float));
16493  lonpix2 = (float*)calloc(num_pixels , sizeof(float));
16494  index_xy = allocate2d_short(num_gridlines, nbinx);
16495  lat_asort = allocate2d_float(num_gridlines, nbinx);
16496 
16497  /* for(int gd=0;gd<2;gd++){
16498  for(int k=0;k<nbinx;k++){
16499  cout<<"gd.."<<gd+1<<"binx.."<<k+1<<"latgd..."<<lat_gd[gd][k]<<"longd..."<<lon_gd[gd][k]<<"latgd..."<<lat_cgd[gd][k]<<"longd..."<<lon_cgd[gd][k]<<endl;
16500  }}
16501  exit(1);
16502  */
16503  cout << "inside....xy_pixsize_sf2.." << "NY1.." << NY1 << "NY2.." << NY2 << endl;
16504 
16505  sbs2_sort_latgd(l1cfile, lat_gd, lat_asort, index_xy);
16506 
16507  cout << "filename..." << filename << endl;
16508  status = nc_open(filename, NC_NOWRITE, &ncid_L1B);
16509  if (status != NC_NOERR) {
16510  fprintf(stderr, "-fail nc_open.\n");
16511  exit(EXIT_FAILURE);
16512  }
16513 
16514  //Open dimensions
16515  status = nc_inq_dimid(ncid_L1B, "number_of_scans", &dimid);
16516  if (status != NC_NOERR) {
16517  fprintf(stderr, "-E- Error reading number_of_scans.\n");
16518  exit(EXIT_FAILURE);
16519  }
16520  nc_inq_dimlen(ncid_L1B, dimid, &num_scans);
16521 
16522  //read line-by-line lat/lon/Lt
16523  status = nc_inq_grp_ncid(ncid_L1B, "geolocation_data", &geoGrp);
16524  check_err(status, __LINE__, __FILE__);
16525  status = nc_inq_grp_ncid(ncid_L1B, "observation_data", &obsGrp);
16526  check_err(status, __LINE__, __FILE__);
16527  //open geo data
16528  status = nc_inq_varid(geoGrp, "latitude", &latId);//scans x velements
16529  check_err(status, __LINE__, __FILE__);
16530  status = nc_inq_varid(geoGrp, "longitude", &lonId);//scans x velements
16531  check_err(status, __LINE__, __FILE__);
16532 
16533  // num_blue_bands
16534  status = nc_inq_dimid(ncid_L1B, "blue_bands", &dimid);
16535  if (status != NC_NOERR) {
16536  fprintf(stderr, "-E- Error reading num_blue_bands.\n");
16537  exit(EXIT_FAILURE);
16538  }
16539  nc_inq_dimlen(ncid_L1B, dimid, &num_blue_bands);
16540 
16541  status = nc_inq_varid(obsGrp, "Lt_blue", &Lt_blueId);
16542  check_err(status, __LINE__, __FILE__);
16543 
16544  Lt_pix = allocate2d_float(num_blue_bands, num_pixels);
16545 
16546  //-----reading line by line-----------------------------------
16547  for (unsigned int sline = 0;sline < num_scans - 1;sline++) {
16548  //lat and lon--
16549  start[0] = sline;
16550  start[1] = 0;
16551  start2[0] = sline + 1;
16552  start2[1] = 0;
16553  count[0] = 1;
16554  count[1] = num_pixels; // 1 line at a time
16555 
16556  start3[0] = 0;
16557  start3[1] = sline;
16558  start3[2] = 0;
16559 
16560  count3[0] = num_blue_bands;
16561  count3[1] = 1; // 1 line at a time
16562  count3[2] = num_pixels;
16563 
16564  status = nc_get_vara_float(geoGrp, latId, start, count, latpix);
16565  status = nc_get_vara_float(geoGrp, lonId, start, count, lonpix);
16566  status = nc_get_vara_float(geoGrp, latId, start2, count, latpix2);
16567  status = nc_get_vara_float(geoGrp, lonId, start2, count, lonpix2);
16568  status = nc_get_vara_float(obsGrp, Lt_blueId, start3, count3, Lt_pix[0]);
16569 
16570  if (sline % 100 == 1) cout << "weight-binning sline..." << sline + 1 << endl;
16571 
16572  for (unsigned int pix = 0;pix < num_pixels - 1;pix++) {
16573 
16574  //across-track distance
16575  deltaphi = (latpix[pix] - latpix[pix + 1]) * degrad;
16576  deltalam = (lonpix[pix] - lonpix[pix + 1]) * degrad;
16577  aterm = sin(deltaphi / 2) * sin(deltaphi / 2) + cos(latpix[pix] * degrad) * cos(latpix[pix + 1] * degrad) * sin(deltalam / 2) * sin(deltalam / 2);
16578  bterm = 2 * atan2(sqrt(aterm), sqrt(1 - aterm));
16579  dist_u = Re * bterm; //horizontal distance Harversine in km
16580  //along-track distance
16581  deltaphi = (latpix[pix] - latpix2[pix]) * degrad;
16582  deltalam = (lonpix[pix] - lonpix2[pix]) * degrad;
16583  aterm = sin(deltaphi / 2) * sin(deltaphi / 2) + cos(latpix[pix] * degrad) * cos(latpix2[pix] * degrad) * sin(deltalam / 2) * sin(deltalam / 2);
16584  bterm = 2 * atan2(sqrt(aterm), sqrt(1 - aterm));
16585  dist_v = Re * bterm;
16586 
16587  pix_size_u[sline][pix] = dist_u;
16588  pix_size_v[sline][pix] = dist_v;
16589 
16590  //pixel azimuth
16591  azpix = atan2(sin(deltalam) * cos(latpix2[pix] * degrad), cos(latpix[pix] * degrad) * sin(latpix2[pix] * degrad) - sin(latpix[pix] * degrad) * cos(latpix2[pix] * degrad) * cos(deltaphi));
16592  if (azpix > M_PI | azpix < -M_PI) {
16593  cout << "problem with BEARING in across-gridline method...az<-180 or >180...." << "azpixc in degrees.." << azpix * 180 / M_PI << endl;
16594  exit(1);
16595  }
16596  // cout<<"azpix.."<<azpix*180/M_PI<<endl;
16597 
16598  /* if(azpix<0.){
16599  azpix=360+azpix*180/M_PI;
16600  }
16601  else azpix=azpix*180./M_PI;
16602  */
16603  azpix = azpix * 180. / M_PI;
16604 
16605 // cout << "line.." << sline + 1 << "pix #:.." << pix + 1 << "pix size.U in km." << pix_size_u[sline][pix] << "pixsize.V in km." << pix_size_v[sline][pix] << "azpix before corners4.." << azpix << endl;
16606  // pix_corners(dist_u,dist_v,azpix, sline,pix,latpix[pix],lonpix[pix]);
16607 // pix_corners3(l1cfile,dist_u,dist_v,azpix, sline,pix,latpix[pix],lonpix[pix],Lt_pix[0][pix],lat_asort,index_xy,lat_gd,lon_gd,lat_cgd,lon_cgd,areaFracBox,Ltfracsum,areabinsum,nobs_perbin);
16608  pix_corners4_l1c(l1cfile, l1cinput, dist_u, dist_v, azpix, sline, pix, latpix[pix], lonpix[pix], Lt_pix[0][pix], lat_asort, index_xy, lat_gd, lon_gd, lat_cgd, lon_cgd, areaFracBox, Ltfracsum, areabinsum, nobs_perbin);
16609 // pix_corners4_l1c2(l1cfile,l1cinput, dist_u, dist_v, azpix, sline, pix,latpix[pix], lonpix[pix], Lt_pix[0][pix], gd_row, gd_col,lat_gd,lon_gd,areaFracBox,Ltfracsum,areafracsum,nobs_perbin) {
16610 // cout<<"Lt_pix[pix].."<<Lt_pix[0][pix]<<endl;//first blue channel
16611 
16612 
16613  // exit(1);
16614  }//end pixels
16615  // exit(1);
16616 
16617  }//end lines
16618 
16619 // exit(1);
16620  status = nc_close(ncid_L1B);
16621  check_err(status, __LINE__, __FILE__);
16622 
16623  delete[](latpix);
16624  delete[](lonpix);
16625  delete[](latpix2);
16626  delete[](lonpix2);
16627  delete[](index_xy);
16628  delete[](lat_asort);
16629  delete[](Lt_pix);
16630 
16631 
16632  return 0;
16633  }
16634 
16635 
16636 
16637 
16638  int32_t L1C::xy_pixsize(int swtd, l1c_filehandle* l1cfile, int16_t* swtd_id, int16_t* odir, int16_t* file_id, int16_t* nfiles_swt, float** binx_size_u, float** binx_size_v) {
16639  int16_t fi = 0;
16640  std::string str;
16641  const char* ptstr;
16642  int dimid, status;
16643  size_t start[] = { 0, 0 }, start2[] = { 0,0 };
16644  size_t count[] = { 1, 1 };
16645  float* latpix, * lonpix, * latpix2, * lonpix2;
16646  float Re = 6378;
16647  float deltaphi = 0., deltalam = 0., aterm = 0., bterm, dist_u = 0., dist_v = 0.;
16648  int32_t n_files = l1cfile->ifiles.size();
16649  num_pixels = l1cfile->npix;
16650 
16651  latpix = (float*)malloc(num_pixels * sizeof(float));
16652  lonpix = (float*)malloc(num_pixels * sizeof(float));
16653  latpix2 = (float*)malloc(num_pixels * sizeof(float));
16654  lonpix2 = (float*)malloc(num_pixels * sizeof(float));
16655 
16656  for (int findex = 0;findex < n_files;findex++) {
16657 
16658  //opening swath files----
16659  if (swtd == swtd_id[findex]) {
16660  cout << "Scanning lines in file.. for crossing swath..." << swtd << "file_id.." << file_id[findex] << "swt_id.." << swtd_id[findex] << endl;
16661  fi = file_id[findex];
16662  str = l1cfile->ifiles[fi - 1];
16663  ptstr = str.c_str();
16664  cout << "filename..." << ptstr << endl;
16665  status = nc_open(ptstr, NC_NOWRITE, &ncid_L1B);
16666  if (status != NC_NOERR) {
16667  fprintf(stderr, "-E- failed nc_open.\n");
16668  exit(EXIT_FAILURE);
16669 }
16670  //Open dimensions
16671  status = nc_inq_dimid(ncid_L1B, "number_of_scans", &dimid);
16672  if (status != NC_NOERR) {
16673  fprintf(stderr, "-E- Error reading number_of_scans.\n");
16674  exit(EXIT_FAILURE);
16675  }
16676  nc_inq_dimlen(ncid_L1B, dimid, &num_scans);
16677 
16678  //read line-by-line lat/lon/Lt
16679  status = nc_inq_grp_ncid(ncid_L1B, "geolocation_data", &geoGrp);
16680  check_err(status, __LINE__, __FILE__);
16681  status = nc_inq_grp_ncid(ncid_L1B, "observation_data", &obsGrp);
16682  check_err(status, __LINE__, __FILE__);
16683  //open geo data
16684  status = nc_inq_varid(geoGrp, "latitude", &latId);//scans x velements
16685  check_err(status, __LINE__, __FILE__);
16686  status = nc_inq_varid(geoGrp, "longitude", &lonId);//scans x velements
16687  check_err(status, __LINE__, __FILE__);
16688 
16689  //-----reading line by line-----------------------------------
16690  for (unsigned int sline = 0;sline < num_scans - 1;sline++) {
16691  //lat and lon--
16692  start[0] = sline;
16693  start[1] = 0;
16694  start2[0] = sline + 1;
16695  start2[1] = 0;
16696  count[0] = 1;
16697  count[1] = num_pixels; // 1 line at a time
16698 
16699  status = nc_get_vara_float(geoGrp, latId, start, count, latpix);
16700  status = nc_get_vara_float(geoGrp, lonId, start, count, lonpix);
16701  status = nc_get_vara_float(geoGrp, latId, start2, count, latpix2);
16702  status = nc_get_vara_float(geoGrp, lonId, start2, count, lonpix2);
16703 
16704 
16705 
16706  for (unsigned int pix = 0;pix < num_pixels - 1;pix++) {
16707  //across-track distance
16708  deltaphi = (latpix[pix] - latpix[pix + 1]) * degrad;
16709  deltalam = (lonpix[pix] - lonpix[pix + 1]) * degrad;
16710  aterm = sin(deltaphi / 2) * sin(deltaphi / 2) + cos(latpix[pix] * degrad) * cos(latpix[pix + 1] * degrad) * sin(deltalam / 2) * sin(deltalam / 2);
16711  bterm = 2 * atan2(sqrt(aterm), sqrt(1 - aterm));
16712  dist_u = Re * bterm; //horizontal distance Harversine in km
16713  //along-track distance
16714  deltaphi = (latpix[pix] - latpix2[pix]) * degrad;
16715  deltalam = (lonpix[pix] - lonpix2[pix]) * degrad;
16716  aterm = sin(deltaphi / 2) * sin(deltaphi / 2) + cos(latpix[pix] * degrad) * cos(latpix2[pix] * degrad) * sin(deltalam / 2) * sin(deltalam / 2);
16717  bterm = 2 * atan2(sqrt(aterm), sqrt(1 - aterm));
16718  dist_v = Re * bterm;
16719 
16720  binx_size_u[sline][pix] = dist_u;
16721  binx_size_v[sline][pix] = dist_v;
16722  // cout<<"pix #:.."<<pix+1<<"binxsize.U in km."<<binx_size_u[sline][pix]<<"binxsize.V in km."<<binx_size_v[sline][pix]<<endl;
16723  // cout<<"pix #:.."<<pix+1<<"latpix1.."<<latpix[pix]<<"latpix2.."<<latpix2[pix]<<endl;
16724  }//end pixels
16725  exit(1);
16726  }//end scanlines
16727  status = nc_close(ncid_L1B);
16728  check_err(status, __LINE__, __FILE__);
16729  }//end if swtd
16730  }//end for files
16731 
16732  delete[](latpix);
16733  delete[](lonpix);
16734  delete[](latpix2);
16735  delete[](lonpix2);
16736 
16737  // exit(1);
16738 
16739  return 0;
16740  }
16741 
16742 
16743 
16744 
16745 
16746 int32_t L1C::write_L1C_granule(int swtd, l1c_filehandle* l1cfile, L1C_input* l1cinput,double *tmgv,float** lat_gd, float** lon_gd){
16747  int32_t num_gridlines, nbinx, NY1 = -1, NY2 = -1;
16748  int ncid_out,x_dimid, y_dimid, varid1, varid2, status;
16749  int NDIMS=2;
16750  int dimids[NDIMS];
16751  int32_t NX, NY;
16752  int grp_coor;
16753  const char* filename_lt;
16754  float **lat_out=nullptr,**lon_out=nullptr;
16755 // float **lt_out=nullptr;
16756  int NVIEWS, NBANDS,v_dimid,b_dimid,asc_mode=-1;
16757  string senstr;
16758  double tg_ini,tg_end;
16759  int numgran;
16760  double tgridline,tfile_ini_sec;
16761  int16_t *granid=nullptr;
16762  int32_t gransize;
16763  short **gdindex=nullptr;
16764  double **gdtime=nullptr;
16765  int16_t y_ini,mo_ini,d_ini,h_ini,mi_ini,y_end,mo_end,d_end,h_end,mi_end;
16766  double sec_ini,sec_end;
16767  string tswt_ini,tswt_end,tswt_ini_file;
16768  int logoff=-1;
16769 // int gd_per_gran=-1;
16770 
16771 
16772 
16773  if(l1cinput->sensor==1){
16774  senstr="SPEXone";
16775  l1cfile->nbinx=20;
16776  }
16777  else if (l1cinput->sensor==2){
16778  senstr="OCI";
16779  l1cfile->nbinx=514;
16780  }
16781  else if (l1cinput->sensor==3){
16782  senstr="HARP2";
16783  l1cfile->nbinx=452;
16784  }
16785  else{cout<<"sensor by default is OCI option 2....."<<endl;
16786  senstr="OCI";
16787  l1cfile->nbinx=514;
16788  }
16789 
16790 
16791  //this is swath stuff, create_socea function
16792 /*
16793  tswt_ini=l1cfile->tswt_ini;
16794  tswt_end=l1cfile->tswt_end;
16795  tswt_ini_file=l1cfile->tswt_ini_file;
16796 */
16797 
16798  cout<<"tswt_ini..."<<tswt_ini<<endl;
16799  cout<<"tswt_end..."<<tswt_end<<endl;
16800 
16801 
16802  asc_mode=l1cfile->orb_dir;
16803  gransize=l1cfile->gransize;
16804  num_gridlines = l1cfile->num_gridlines;
16805  cout<<"# gridlines...."<<num_gridlines<<"gransize.."<<gransize<<endl;
16806 
16807  granid=(int16_t*)calloc(num_gridlines,sizeof(int16_t));
16808 
16809  numgran=l1cfile->numgran;
16810  // gd_per_gran=l1cfile->gd_per_gran;
16811  nbinx = l1cfile->nbinx;
16812  tfile_ini_sec=l1cfile->tfile_ini_sec;
16813 
16814  gdtime = allocate2d_double(numgran,2);
16815  gdindex= allocate2d_short(numgran,2);
16816 
16817  //first granule----
16818  tg_ini=tfile_ini_sec;//always unix time
16819  tg_end=tg_ini+gransize*60;
16820 
16821 
16822  for(int i=0;i<num_gridlines-1;i++){
16823  granid[i]=-1;
16824  }
16825 
16826  for(int i=0;i<numgran;i++){
16827  for(size_t j=0;j<2;j++){
16828  gdtime[i][j]=-1;
16829  gdindex[i][j]=-1;
16830  }}
16831 
16832 
16833  int neg=0,gmin=-1,c=0;
16834  for(int gran=0;gran<numgran;gran++){
16835  for(int i=0;i<num_gridlines-1;i++){
16836  tgridline=tfile_ini_sec+tmgv[i];
16837  if(tgridline>=tg_ini && tgridline<=tg_end){
16838  granid[i]=gran+1;
16839  if(gmin<0){//first index
16840  gdtime[c][0]=tg_ini;
16841  gdtime[c][1]=tg_end;
16842  gdindex[c][0]=i;
16843  gmin=1;
16844 // cout<<"c.."<<c<<"i.."<<i<<endl;
16845  }
16846  gdindex[c][1]=i;
16847 
16848  // cout<<"gd#."<<i+1<<"tgridline..."<<tgridline<<"gran#.."<<gran+1<<endl;
16849  /*
16850  unix2ymdhms(tg_ini,&y_ini,&mo_ini,&d_ini, &h_ini, &mi_ini, &sec_ini);
16851  unix2ymdhms(tg_end,&y_end,&mo_end,&d_end, &h_end, &mi_end, &sec_end);
16852  cout<<"year ini"<<y_ini<<"month ini.."<<mo_ini<<"day ini"<<d_ini<<"hour ini"<<h_ini<<"min ini"<<mi_ini<<"sec ini"<<sec_ini<<endl;
16853  cout<<"year end"<<y_end<<"month end.."<<mo_end<<"day end"<<d_end<<"hour end"<<h_end<<"min end"<<mi_end<<"sec end"<<sec_end<<endl;
16854  */
16855  }
16856 
16857 
16858  if(tmgv[i]<0 && gran==0){
16859  neg++;
16860  // cout<<"neg time at gd#"<<i+1<<endl;
16861  }
16862  }
16863  tg_ini=tg_end;
16864  tg_end=tg_ini+gransize*60;
16865  gmin=-1;
16866  c++;
16867 
16868 
16869  if(tg_ini>tgridline){
16870  cout<<"gridlines with negative time..."<<neg<<endl;
16871  break;}
16872 
16873  }
16874 
16875 //-------------------------------------------------------------
16876 /*
16877  for(size_t gd=0;gd<num_gridlines-1;gd++){
16878  cout<<"gd#.."<<gd+1<<"granid..#"<<granid[gd]<<endl;
16879  }
16880 
16881  for(size_t i=0;i<numgran;i++){
16882  for(size_t j=0;j<2;j++){
16883  cout<<"gran#.."<<i+1<<"gdindex.."<<gdindex[i][j]<<endl;
16884  cout<<"time bounds..."<<j+1<<"gdtime.."<<gdtime[i][j]<<endl;
16885  }}
16886 
16887 */
16888 
16889 //exit(1);
16890 
16891 
16892 
16893 /*
16894 //--------- COUNT GDLINES PER GRANULE ----------
16895 
16896  size_t granule=1,g=0;
16897  size_t i=0,gdline=0,tot=0;
16898 
16899  while(g<numgran-1){
16900 
16901 
16902  while(i<num_gridlines-1){
16903 
16904  if (granule==granid[i]){
16905  gdline++;
16906  tot++;
16907  // cout<<"granid..#.."<<granid[i]<<"for gridline #.."<<i+1<<endl;
16908  }
16909 
16910  if(i==num_gridlines-2){
16911  cout<<"done with granule #..."<<granule<<"# gridlines = "<<gdline<<"tot.."<<tot<<endl;
16912  granule++;
16913  g++;
16914  i=num_gridlines;
16915  gdline=0;
16916  }
16917  i++;
16918  }
16919  i=0;
16920  }//end while
16921 
16922 */
16923 
16924 int16_t ngridlines,totlines=0;
16925 //write files with granid>0 ---------------------
16926  for(int gran=0;gran<numgran;gran++){
16927  if(gdtime[gran][0]>0){
16928  cout<<"gran #..."<<gran+1<<endl;
16929 
16930  tg_ini=gdtime[gran][0];
16931  tg_end=gdtime[gran][1];
16932 
16933  unix2ymdhms(tg_ini,&y_ini,&mo_ini,&d_ini, &h_ini, &mi_ini, &sec_ini);
16934  unix2ymdhms(tg_end,&y_end,&mo_end,&d_end, &h_end, &mi_end, &sec_end);
16935 
16936  //# gridlines per granule
16937  //gridline index 0-num_gridlines
16938  ngridlines=gdindex[gran][1]-gdindex[gran][0]+1;
16939  totlines+=ngridlines;
16940  cout<<"ngridlines..."<<ngridlines<<"tot gridlines..."<<totlines<<endl;
16941 
16942 
16943  std::string timestr,missionstr,fname_out, pathstr,monstr, daystr, yearstr, secstr,mistr,hstr,prodstr, gdstr, swtstr, swtnum, extstr,ofilestr,dirstr,datetimestr1,datetimestr2,fdatetimestr1;
16944 
16945  if(asc_mode==1) dirstr="Ascending";
16946  else if(asc_mode==0) dirstr="Descending";
16947 
16948 //time coverage start----
16949  pathstr = "out/";
16950  missionstr="PACE";
16951  extstr = ".nc";
16952 
16953  secstr = std::to_string(sec_ini);
16954  mistr = std::to_string(mi_ini);
16955  hstr = std::to_string(h_ini);
16956  daystr = std::to_string(d_ini);
16957  monstr = std::to_string(mo_ini);
16958  yearstr = std::to_string(y_ini);
16959 
16960  int length = (int) floor( log10 (mo_ini) ) + 1;
16961  if(length==1) monstr="0"+monstr;
16962  length = (int) floor( log10 (d_ini) ) + 1;
16963  if(length==1) daystr="0"+daystr;
16964 
16965 
16966 
16967  if(h_ini==0) logoff=1; else logoff=0;
16968  length = (int) floor( log10 (h_ini+logoff)) + 1;
16969  if(length==1) hstr="0"+hstr;
16970  if(mi_ini==0) logoff=1; else logoff=0;
16971  length = (int) floor( log10 (mi_ini+logoff)) + 1;
16972  if(length==1) mistr="0"+mistr;
16973  if(sec_ini==0) logoff=1; else logoff=0;
16974  length = (int) floor( log10 (round(sec_ini+logoff))) + 1;
16975  if(length==1) secstr="0"+secstr;
16976 
16977 
16978  fdatetimestr1=yearstr+monstr+daystr+"T"+hstr+mistr+secstr.substr(0,2)+"Z";
16979  datetimestr1=yearstr+"-"+monstr+"-"+daystr+"T"+hstr+":"+mistr+":"+secstr.substr(0,2)+"Z";
16980 //time coevrage end----
16981 //
16982  secstr = std::to_string(sec_end);
16983  mistr = std::to_string(mi_end);
16984  hstr = std::to_string(h_end);
16985  daystr = std::to_string(d_end);
16986  monstr = std::to_string(mo_end);
16987  yearstr = std::to_string(y_end);
16988 
16989  length = (int) floor( log10 (mo_end) ) + 1;
16990  if(length==1) monstr="0"+monstr;
16991  length = (int) floor( log10 (d_end) ) + 1;
16992  if(length==1) daystr="0"+daystr;
16993 
16994  if(h_end==0) logoff=1; else logoff=0;
16995  length = (int) floor( log10 (h_end+logoff)) + 1;
16996  if(length==1) hstr="0"+hstr;
16997  if(mi_end==0) logoff=1; else logoff=0;
16998  length = (int) floor( log10 (mi_end+logoff)) + 1;
16999  if(length==1) mistr="0"+mistr;
17000  if(sec_end==0) logoff=1; else logoff=0;
17001  length = (int) floor( log10 (round(sec_end+logoff))) + 1;
17002  if(length==1) secstr="0"+secstr;
17003 
17004 
17005  datetimestr2=yearstr+"-"+monstr+"-"+daystr+"T"+hstr+":"+mistr+":"+secstr.substr(0,2)+"Z";
17006 
17007  fname_out=pathstr+"PACE_"+senstr+"."+fdatetimestr1+".L1C.5.2km.nc";
17008 
17009  // tswt_ini=y_swt+"-"+mo_swt+"-"+d_swt+"T"+h_swt+":"+mi_swt+":"+s_swt2.substr(0,2)+"Z";
17010 
17011 
17012 
17013  cout<<"granule filename.."<<fname_out<<endl;
17014 
17015 
17016 
17017 
17018  /*
17019  // string datestr=date;
17020 
17021  auto t = std::time(nullptr);
17022  auto tm = *std::localtime(&t);
17023  std::ostringstream oss,oss2;
17024  oss << std::put_time(&tm, "%d-%m-%Y %H-%M-%S") << std::endl;
17025  // cout<<"current datetime.n UTC."<<datestr<<endl;
17026  auto datestr = oss.str();
17027  cout<<"date.."<<datestr.substr(0,2)<<endl;
17028 
17029  time_t rawtime;
17030  time (&rawtime);
17031  string datestr2=ctime (&rawtime);
17032 
17033 
17034 // oss2<<system("date")<<endl;
17035 // string datestr2=oss2.str();
17036  cout<<"date.."<<datestr2.substr(0,10)<<endl;
17037 // exit(1);
17038 */
17039 
17040 
17041  string ATT_NAME="Units", ATT_VAL="degrees",GATT_NAME1="Title",GATT_VAL1="PACE OCI Level-1C Data",GATT_NAME2="instrument",GATT_VAL2="OCI",GATT_NAME3="processing_version",GATT_VAL3="V1.0",GATT_NAME4="Conventions",GATT_VAL4="CF-1.6";
17042  string GATT_NAME5="institution",GATT_VAL5="NASA Goddard Space Flight Center, Ocean Biology Processing Group",GATT_NAME6="license",GATT_VAL6="http://science.nasa.gov/earth-science/earth-science-data/data-information-policy/";
17043  string GATT_NAME7="naming_authority",GATT_VAL7="gov.nasa.gsfc.sci.oceancolor",GATT_NAME8="keywords_vocabulary",GATT_VAL8="NASA Global Change Master Directory (GCMD) Science Keywords";
17044  string GATT_NAME9="stdname_vocabulary",GATT_VAL9="NetCDF Climate and Forecast (CF) Metadata Convention",GATT_NAME10="creator_name",GATT_VAL10="NASA/GSFC",GATT_NAME11="creator_email",GATT_VAL11="data@oceancolor.gsfc.nasa.gov";
17045  string GATT_NAME12="creator_url",GATT_VAL12="http://oceancolor.gsfc.nasa.gov",GATT_NAME13="project",GATT_VAL13="PACE Project",GATT_NAME14="publisher_name",GATT_VAL14="NASA/GSFC";
17046  string GATT_NAME15="publisher_email",GATT_VAL15="data@oceancolor.gsfc.nasa.gov",GATT_NAME16="publisher_url",GATT_VAL16="http://oceancolor.gsfc.nasa.gov",GATT_NAME17="processing_level",GATT_VAL17="L1C";
17047  string GATT_NAME18="cdm_data_type",GATT_VAL18="swath",GATT_NAME19="orbit_number",GATT_VAL19="xxx",GATT_NAME20="history",GATT_VAL20="",GATT_NAME21="CDL_version_date",GATT_VAL21="2021-09-10",GATT_NAME22="product_name",GATT_VAL22=fname_out;
17048  string GATT_NAME23="startDirection",GATT_VAL23=dirstr,GATT_NAME24="endDirection",GATT_VAL24=dirstr,GATT_NAME25="time_coverage_start",GATT_VAL25=datetimestr1,GATT_NAME26="time_coverage_end",GATT_VAL26=datetimestr2,GATT_NAME27="date_created",GATT_VAL27="2022-03-25T15:12:41Z",GATT_NAME28="sun_earth_distance",GATT_VAL28="0.990849042172323",GATT_NAME29="terrain_data_source",GATT_VAL29="",GATT_NAME30="spectral_response_function",GATT_VAL30="",GATT_NAME31="systematic_uncertainty_model",GATT_VAL31="",GATT_NAME32="nadir_bin",GATT_VAL32="12345",GATT_NAME33="bin_size_at_nadir",GATT_VAL33="5.2km2";
17049 
17050 
17051  l1cfile->gridname = fname_out.c_str();
17052  filename_lt = fname_out.c_str();
17053 
17054  cout<<"creating file for L1C coor..."<<filename_lt<<endl;
17055 
17056 
17057  if ((status = nc_create(filename_lt, NC_CLOBBER | NC_NETCDF4, &ncid_out)))
17058  check_err(status, __LINE__, __FILE__);
17059  //define dims
17060  // Define the dimensions,vars and attributes at the root level
17061  NY = ngridlines;
17062  NX = nbinx;
17063  //subset lat and lon arrays
17064  NY1=gdindex[gran][0];
17065  NY2=gdindex[gran][1];
17066 
17067  lat_out = allocate2d_float(NY, NX);
17068  lon_out = allocate2d_float(NY, NX);
17069 
17070  int cc=0;
17071  for (int i = NY1; i < NY2 + 1; i++) {
17072  for (int j = 0; j < NX; j++) {
17073  lat_out[cc][j] = lat_gd[i][j];
17074  lon_out[cc][j] = lon_gd[i][j];
17075  }
17076  cc++;
17077  }
17078 
17079  if(l1cinput->sensor==1){
17080  senstr="SPEXone";
17081  GATT_VAL2="SPEXone";
17082  GATT_VAL32="3567";
17083  NVIEWS=5;
17084  NBANDS=400;
17085  }
17086  else if (l1cinput->sensor==2){
17087  senstr="OCI";
17088  GATT_VAL2="OCI";
17089  GATT_VAL32="635";
17090  NVIEWS=2;
17091  NBANDS=249;
17092  }
17093  else if (l1cinput->sensor==3){
17094  senstr="HARP2";
17095  GATT_VAL2="HARP";
17096  GATT_VAL32="127";
17097  NVIEWS=90;
17098  NBANDS=1;
17099  }
17100  else{
17101  cout<<"sensor by default is OCI option 2....."<<endl;
17102  senstr="OCI";
17103  GATT_VAL2="OCI";
17104  GATT_VAL32="635";
17105  NVIEWS=2;
17106  NBANDS=249;
17107  }
17108 
17109 // lt_out = allocate2d_float(NY, NX);
17110  //DEF DIMENSIONS
17111  if ((status = nc_def_dim(ncid_out, "bins_across_track", NX, &x_dimid)))
17112  check_err(status, __LINE__, __FILE__);
17113  if ((status = nc_def_dim(ncid_out, "bins_along_track", NY, &y_dimid)))
17114  check_err(status, __LINE__, __FILE__);
17115  //dims for output var
17116  dimids[0] = y_dimid;
17117  dimids[1] = x_dimid;
17118  NDIMS=2;
17119  if ((status = nc_def_dim(ncid_out, "number_of_views", NVIEWS, &v_dimid)))
17120  check_err(status, __LINE__, __FILE__);
17121  if ((status = nc_def_dim(ncid_out, "intensity_bands_per_view", NBANDS, &b_dimid)))
17122  check_err(status, __LINE__, __FILE__);
17123  //define attributes
17124 // if (nc_put_att_text(ncid_out, varid1, ATT_NAME.c_str(), strlen(ATT_VAL.c_str()), ATT_VAL.c_str()))
17125 // check_err(status, __LINE__, __FILE__);
17126 // if (nc_put_att_text(ncid_out, varid2, ATT_NAME.c_str(), strlen(ATT_VAL.c_str()), ATT_VAL.c_str()))
17127 // check_err(status, __LINE__, __FILE__);
17128  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME1.c_str(), strlen(GATT_VAL1.c_str()),
17129  GATT_VAL1.c_str()))
17130  check_err(status, __LINE__, __FILE__);
17131  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME2.c_str(), strlen(GATT_VAL2.c_str()),
17132  GATT_VAL2.c_str()))
17133  check_err(status, __LINE__, __FILE__);
17134  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME3.c_str(), strlen(GATT_VAL3.c_str()),
17135  GATT_VAL3.c_str()))
17136  check_err(status, __LINE__, __FILE__);
17137  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME4.c_str(), strlen(GATT_VAL4.c_str()),
17138  GATT_VAL4.c_str()))
17139  check_err(status, __LINE__, __FILE__);
17140  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME5.c_str(), strlen(GATT_VAL5.c_str()),
17141  GATT_VAL5.c_str()))
17142  check_err(status, __LINE__, __FILE__);
17143  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME6.c_str(), strlen(GATT_VAL6.c_str()),
17144  GATT_VAL6.c_str()))
17145  check_err(status, __LINE__, __FILE__);
17146  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME7.c_str(), strlen(GATT_VAL7.c_str()),
17147  GATT_VAL7.c_str()))
17148  check_err(status, __LINE__, __FILE__);
17149  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME8.c_str(), strlen(GATT_VAL8.c_str()),
17150  GATT_VAL8.c_str()))
17151  check_err(status, __LINE__, __FILE__);
17152  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME9.c_str(), strlen(GATT_VAL9.c_str()),
17153  GATT_VAL9.c_str()))
17154  check_err(status, __LINE__, __FILE__);
17155  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME10.c_str(), strlen(GATT_VAL10.c_str()),
17156  GATT_VAL10.c_str()))
17157  check_err(status, __LINE__, __FILE__);
17158  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME11.c_str(), strlen(GATT_VAL11.c_str()),
17159  GATT_VAL11.c_str()))
17160  check_err(status, __LINE__, __FILE__);
17161  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME12.c_str(), strlen(GATT_VAL12.c_str()),
17162  GATT_VAL12.c_str()))
17163  check_err(status, __LINE__, __FILE__);
17164  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME13.c_str(), strlen(GATT_VAL13.c_str()),
17165  GATT_VAL13.c_str()))
17166  check_err(status, __LINE__, __FILE__);
17167  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME14.c_str(), strlen(GATT_VAL14.c_str()),
17168  GATT_VAL14.c_str()))
17169  check_err(status, __LINE__, __FILE__);
17170  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME15.c_str(), strlen(GATT_VAL15.c_str()),
17171  GATT_VAL15.c_str()))
17172  check_err(status, __LINE__, __FILE__);
17173  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME16.c_str(), strlen(GATT_VAL16.c_str()),
17174  GATT_VAL16.c_str()))
17175  check_err(status, __LINE__, __FILE__);
17176  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME17.c_str(), strlen(GATT_VAL17.c_str()),
17177  GATT_VAL17.c_str()))
17178  check_err(status, __LINE__, __FILE__);
17179  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME18.c_str(), strlen(GATT_VAL18.c_str()),
17180  GATT_VAL18.c_str()))
17181  check_err(status, __LINE__, __FILE__);
17182  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME19.c_str(), strlen(GATT_VAL19.c_str()),
17183  GATT_VAL19.c_str()))
17184  check_err(status, __LINE__, __FILE__);
17185  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME20.c_str(), strlen(GATT_VAL20.c_str()),
17186  GATT_VAL20.c_str()))
17187  check_err(status, __LINE__, __FILE__);
17188  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME21.c_str(), strlen(GATT_VAL21.c_str()),
17189  GATT_VAL21.c_str()))
17190  check_err(status, __LINE__, __FILE__);
17191  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME22.c_str(), strlen(GATT_VAL22.c_str()),
17192  GATT_VAL22.c_str()))
17193  check_err(status, __LINE__, __FILE__);
17194  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME23.c_str(), strlen(GATT_VAL23.c_str()),
17195  GATT_VAL23.c_str()))
17196  check_err(status, __LINE__, __FILE__);
17197  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME24.c_str(), strlen(GATT_VAL24.c_str()),
17198  GATT_VAL24.c_str()))
17199  check_err(status, __LINE__, __FILE__);
17200  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME25.c_str(), strlen(GATT_VAL25.c_str()),
17201  GATT_VAL25.c_str()))
17202  check_err(status, __LINE__, __FILE__);
17203  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME26.c_str(), strlen(GATT_VAL26.c_str()),
17204  GATT_VAL26.c_str()))
17205  check_err(status, __LINE__, __FILE__);
17206  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME27.c_str(), strlen(GATT_VAL27.c_str()),
17207  GATT_VAL27.c_str()))
17208  check_err(status, __LINE__, __FILE__);
17209  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME28.c_str(), strlen(GATT_VAL28.c_str()),
17210  GATT_VAL28.c_str()))
17211  check_err(status, __LINE__, __FILE__);
17212  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME29.c_str(), strlen(GATT_VAL29.c_str()),
17213  GATT_VAL29.c_str()))
17214  check_err(status, __LINE__, __FILE__);
17215  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME30.c_str(), strlen(GATT_VAL30.c_str()),
17216  GATT_VAL30.c_str()))
17217  check_err(status, __LINE__, __FILE__);
17218  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME31.c_str(), strlen(GATT_VAL31.c_str()),
17219  GATT_VAL31.c_str()))
17220  check_err(status, __LINE__, __FILE__);
17221  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME32.c_str(), strlen(GATT_VAL32.c_str()),
17222  GATT_VAL32.c_str()))
17223  check_err(status, __LINE__, __FILE__);
17224  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME33.c_str(), strlen(GATT_VAL33.c_str()),
17225  GATT_VAL33.c_str()))
17226  check_err(status, __LINE__, __FILE__);
17227 
17228  //define groups check_err(status, __LINE__, __FILE__);
17229  if ((status = nc_def_grp(ncid_out, "geolocation_data", &grp_coor))) //netcdf-4
17230  check_err(status, __LINE__, __FILE__);
17231  //def var
17232  if ((status = nc_def_var(grp_coor, "latitude", NC_FLOAT, NDIMS,
17233  dimids, &varid1)))
17234  check_err(status, __LINE__, __FILE__);
17235  if ((status = nc_def_var(grp_coor, "longitude", NC_FLOAT, NDIMS,
17236  dimids, &varid2)))
17237  check_err(status, __LINE__, __FILE__);
17238  //leave define mode-----------------------
17239  if ((status = nc_enddef(grp_coor))) //done def vars etc
17240  check_err(status, __LINE__, __FILE__);
17241 
17242 
17243  //writing the whole thing
17244  if ((status = nc_put_var_float(grp_coor, varid1, &lat_out[0][0])))
17245  check_err(status, __LINE__, __FILE__);
17246 
17247  if ((status = nc_put_var_float(grp_coor, varid2, &lon_out[0][0])))
17248  check_err(status, __LINE__, __FILE__);
17249 
17250 
17251 
17252 //define attributes of vars in groups
17253 //UNITS in degrees ----
17254  if (nc_put_att_text(grp_coor, varid1, ATT_NAME.c_str(), strlen(ATT_VAL.c_str()), ATT_VAL.c_str()))
17255  check_err(status, __LINE__, __FILE__);
17256  check_err(status, __LINE__, __FILE__);
17257  if (nc_put_att_text(grp_coor, varid2, ATT_NAME.c_str(), strlen(ATT_VAL.c_str()), ATT_VAL.c_str()))
17258  check_err(status, __LINE__, __FILE__);
17259 
17260 
17261 //close file
17262  if ((status = nc_close(ncid_out)))
17263  check_err(status, __LINE__, __FILE__);
17264 
17265 
17266 
17267  }//granule >0
17268  }//end granule loop
17269 
17270 
17271 
17272 
17273 
17274 
17275 
17276 
17277  if(gdtime!=nullptr)
17278  delete[] (gdtime);
17279  gdtime=nullptr;
17280 
17281  if(gdindex!=nullptr)
17282  delete[] (gdindex);
17283  gdindex=nullptr;
17284 
17285  if(granid!=nullptr)
17286  delete[] (granid);
17287  granid=nullptr;
17288 
17289 
17290 return 0;
17291 }
17292 
17293 
17294 
17295 //granules processing
17296 int32_t L1C::across_gridlines_l1c_vec3(int swtd, l1c_filehandle* l1cfile, L1C_input* l1cinput,float* lati2, float* loni2, float** lat_gd, float** lon_gd, float* az_east) {
17297  int32_t num_gridlines, nbinx, NY1 = -1, NY2 = -1, c1 = 1;
17298  float lat1_l, lat1_r, lon1_l, lon1_r, lat2, lon2, dlambda, az_r, az_l, h, *lati_l, *loni_l, *lati_r, *loni_r, htot = 0.,az=0.;
17299  int ncid_out,x_dimid, y_dimid, varid1, varid2, status;
17300  int NDIMS=2;
17301  int dimids[NDIMS];
17302  int32_t NX, NY;
17303  int16_t selyear = -1, selmon = -1, selday = -1;
17304  double latih, lonih, latih2, lonih2, res1, res2;
17305  float gres;
17306  int fnan1=0, fnan2=0, fnan3=0, fnan4=0;
17307  float latfirst = -999;
17308  int badline = 0;
17309  int grp_coor;
17310  const char* filename_lt;
17311  float **lat_out=nullptr,**lon_out=nullptr;
17312 // float **lt_out=nullptr;
17313  int NVIEWS, NBANDS,v_dimid,b_dimid,asc_mode=-1;
17314  string senstr,tswt_ini,tswt_end;
17315 
17316  Geodesic geod(Constants::WGS84_a(), Constants::WGS84_f());
17317 
17318 
17319  if(l1cinput->sensor==1) senstr="SPEXone";
17320  else if (l1cinput->sensor==2) senstr="OCI";
17321  else if (l1cinput->sensor==3) senstr="HARP";
17322  else{cout<<"sensor by default is OCI option 2....."<<endl;
17323  senstr="OCI"; }
17324 
17325  //compute azimuth angle for each along-track position (nadir pixel or centered swath pixel) of the swath
17326  //azimuth angle in rads
17327  //lon+540/360-180 is a normalization factor for -180 to 180 degrees
17328  num_gridlines = l1cfile->num_gridlines;
17329  num_pixels = l1cfile->npix;
17330  nbinx = l1cfile->nbinx;
17331 
17332  tswt_ini=l1cfile->tswt_ini;
17333  tswt_end=l1cfile->tswt_end;
17334 
17335 
17336  lati_l = (float*)calloc(nbinx / 2 , sizeof(float));
17337  lati_r = (float*)calloc(nbinx / 2 , sizeof(float));
17338  loni_l = (float*)calloc(nbinx / 2 , sizeof(float));
17339  loni_r = (float*)calloc(nbinx / 2 , sizeof(float));
17340 
17341  //big loop
17342 
17343  int gd = 0;
17344  asc_mode=l1cfile->orb_dir;
17345 
17346 
17347  //compute mean az_east---
17348  float sum = 0., tot = 0.;
17349  size_t azc = 0;
17350  for (int i = 0;i < num_gridlines - 2;i++) {
17351 
17352  // cout<<"gd#.."<<i+1<<"lati2[i].."<<lati2[i]<<endl;
17353 
17354  //assign central positions---
17355  lat1_l = lati2[i] * M_PI / 180.;
17356  lat1_r = lati2[i] * M_PI / 180.;
17357  lat2 = lati2[i + 1] * M_PI / 180.;
17358  lon1_l = loni2[i] * M_PI / 180.;
17359  lon1_r = loni2[i] * M_PI / 180.;
17360  lon2 = loni2[i + 1] * M_PI / 180.;
17361 
17362  dlambda = (lon2 - lon1_l);
17363  //bearing---
17364  //make sure there are not NAN values ----------
17365  az = atan2(sin(dlambda) * cos(lat2), cos(lat1_l) * sin(lat2) - sin(lat1_l) * cos(lat2) * cos(dlambda));
17366 
17367  // cout<<lat2<<"..."<<lat1_l<<".."<<dlambda<<az*180/M_PI<<endl;
17368  if (az > M_PI || az < -M_PI) {
17369  cout << "problem with BEARING in across-gridline method...az<-180 or >180...." << "az in degrees.." << az * 180 / M_PI << endl;
17370  exit(1);
17371  }
17372  if (isnan(az) < 1) {
17373  // cout<<"az.."<<az<<"azcount"<<azc<<endl;
17374  az_r = (az + M_PI / 2.);
17375  az_east[i] = az_r * 180. / M_PI;
17376  if (az_east[i] < 0.0001 && az_east[i]>0) az_east[i] = 0.0;
17377  sum = az_east[i];
17378  tot += sum;
17379  azc++;
17380  }
17381  else {
17382  az_east[i] = NAN;
17383  }
17384  }
17385  float mean_az_east = tot / (azc);
17386 
17387  cout << "recomputing mean_az_east..(based on second interp rather than first interp)" << mean_az_east << "num_gridlines.." << num_gridlines-2 << endl;
17388 
17389 
17390  for (int j = 0;j < num_gridlines - 2;j++) {
17391  az_east[j] = mean_az_east;
17392  }
17393 
17394  l1cfile->mean_az_east = mean_az_east;
17395 
17396  for (int i = 0;i < num_gridlines - 2;i++) {
17397 
17398  if (i % 1 == 0) {
17399  //assign central positions---
17400  lat1_l = lati2[i] * M_PI / 180.;
17401  lat1_r = lati2[i] * M_PI / 180.;
17402  lat2 = lati2[i + 1] * M_PI / 180.;
17403  lon1_l = loni2[i] * M_PI / 180.;
17404  lon1_r = loni2[i] * M_PI / 180.;
17405  lon2 = loni2[i + 1] * M_PI / 180.;
17406 
17407  dlambda = (lon2 - lon1_l);
17408 
17409 
17410  gres = (l1cinput->gres) * 1000; //grid resolution in meters
17411 
17412  //bearing---
17413  //this is Harverside--law f cosines is more accurate---
17414  az = atan2(sin(dlambda) * cos(lat2), cos(lat1_l) * sin(lat2) - sin(lat1_l) * cos(lat2) * cos(dlambda));
17415  if (az > M_PI || az < -M_PI) {
17416  cout << "problem with BEARING in across-gridline method...az<-180 or >180...." << "az in degrees.." << az * 180 / M_PI << endl;
17417  exit(1);
17418  }
17419 
17420  //compute RIGHT across-gridline pixels---
17421  for (int k = 0;k < (nbinx / 2);k++) {
17422  h = (l1cinput->gres);//distance between along positions in km, must be 5.2 k m for L1C
17423  if (k == 0) h /= 2;//if nadpix
17424  htot += h;
17425 
17426  //right pixels---
17427  az_r = mean_az_east * degrad;
17428 
17429  //left pixels---
17430  az_l = az_r - M_PI;
17431 
17432  //bearing should be always positive (clockwise) before pixel location calculation based on Harverside---
17433  if (az_r < 0.) {
17434  az_r = 360 + az_r * 180 / M_PI;
17435  az_r = az_r * M_PI / 180;
17436  }
17437 
17438  if (az_l < 0.) {
17439  az_l = 360 + az_l * 180 / M_PI;
17440  az_l = az_l * M_PI / 180;
17441  }
17442 
17443  geod.Direct(lat1_r * 180 / M_PI, lon1_r * 180 / M_PI, az_r * 180 / M_PI, gres, latih, lonih);
17444  geod.Inverse(lat1_r * 180 / M_PI, lon1_r * 180 / M_PI, latih, lonih, res1);
17445 
17446 
17447  fnan1 = isnan(latih);
17448  fnan2 = isnan(lonih);
17449  lati_r[k] = latih;
17450  loni_r[k] = lonih;
17451  // cout<<"righside.."<<latih<<"..."<<lonih<<"res1"<<res1<<endl;
17452 
17453  lat1_r = lati_r[k] * M_PI / 180;
17454  lon1_r = loni_r[k] * M_PI / 180;
17455 
17456  geod.Direct(lat1_l * 180 / M_PI, lon1_l * 180 / M_PI, az_l * 180 / M_PI, gres, latih2, lonih2);
17457  geod.Inverse(lat1_l * 180 / M_PI, lon1_l * 180 / M_PI, latih2, lonih2, res2);
17458 
17459  /* if(i==500){
17460  cout<<"gd#..."<<i+1<<"az_r.."<<az_r* 180 / M_PI<<"az_l.."<<az_l* 180 / M_PI<<endl;
17461  cout<<"lat1_r.."<<lat1_r<<"lon1_r.."<<lon1_r<<"latih.."<<latih<<"lonih.."<<lonih<<"res1.."<<res1<<endl;
17462  cout<<"lat1_l.."<<lat1_l<<"lon1_l.."<<lon1_l<<"latih2.."<<latih2<<"lonih2.."<<lonih2<<"res2.."<<res2<<endl;
17463  }
17464  */
17465 
17466  fnan3 = isnan(latih2);
17467  fnan4 = isnan(lonih2);
17468  lati_l[k] = latih2;
17469  loni_l[k] = lonih2;
17470  // cout<<"leftside.."<<latih2<<"..."<<lonih2<<"res2"<<res2<<endl;
17471 
17472  lat1_l = lati_l[k] * M_PI / 180;
17473  lon1_l = loni_l[k] * M_PI / 180;
17474 
17475  //right swath side------------- //we tolerate +- 6 m error
17476  if (asc_mode==1 && lati2[i]>lati2[i+1] || asc_mode==0 && lati2[i]<lati2[i+1] || fnan1 > 0 || fnan2 > 0 || res1 > (gres + 6) || res1 < (gres - 6)) { //nan values
17477  badline++;
17478  if (badline == 1) {
17479  latfirst = lati2[i];
17480  }
17481 
17482  cout << "bad interpolation - missing orbital data at near nadir grid cell..NAN right side of line.." << i + 1 << "corresponding to lat..."<<latfirst <<"lati2[i].."<<lati2[i]<<endl;
17483  cout<<"gd.."<<gd+1<<"XBIN.."<<k+1<<"lati_l[k]"<<lati_l[k]<<"loni_l[k]"<<loni_l[k]<<"lati_r[k]"<<lati_r[k]<<"loni_r[k]"<<loni_r[k]<<endl;
17484 
17485  lati2[i] = NAN;
17486  loni2[i] = NAN;
17487 
17488  for (int k = 0;k < (nbinx / 2);k++) {
17489  lat_gd[gd][k + nbinx / 2] = NAN;
17490  lon_gd[gd][k + nbinx / 2] = NAN;
17491  }
17492  // cout<<"nan value.right.."<<endl;
17493  }
17494  else {
17495  lat_gd[gd][k + nbinx / 2] = latih;
17496  lon_gd[gd][k + nbinx / 2] = lonih;
17497  }
17498 
17499  //left side
17500  if (asc_mode==1 && lati2[i]>lati2[i+1] || asc_mode==0 && lati2[i]<lati2[i+1] || fnan3 > 0 || fnan4 > 0 || res2 > (gres + 6) || res2 < (gres - 6)) {
17501  // if(fnan3>0 | fnan4>0 | res2>(gres+6) | res2<(gres-6)){
17502  cout << "bad interpolation - missing orbital data at near nadir grid cell..NAN left side of line.." << i + 1 << endl;
17503  cout<<"gd.."<<gd+1<<"XBIN.."<<k+1<<"lati_l[k]"<<lati_l[k]<<"loni_l[k]"<<loni_l[k]<<"lati_r[k]"<<lati_r[k]<<"loni_r[k]"<<loni_r[k]<<"lati2[i].."<<lati2[i]<<endl;
17504 
17505  lati2[i] = NAN;
17506  loni2[i] = NAN;
17507  for (int k = 0;k < (nbinx / 2);k++) {
17508  lat_gd[gd][nbinx / 2 - 1 - k] = NAN;//as k increases we are farther away from nadpix or along-track position---
17509  lon_gd[gd][nbinx / 2 - 1 - k] = NAN;
17510  }
17511  // cout<<"nan value.left.."<<endl;
17512  }
17513  else {
17514  lat_gd[gd][nbinx / 2 - 1 - k] = latih2;//as k increases we are farther away from nadpix or along-track position---
17515  lon_gd[gd][nbinx / 2 - 1 - k] = lonih2;
17516  }
17517  fnan1=0;
17518  fnan2=0;
17519  fnan3=0;
17520  fnan4=0;
17521 
17522  }//end pixel loop
17523 
17524 
17525  htot = 0;
17526  gd++;
17527  }//end if every 100 gd
17528  }//end gridlines loop
17529  cout << "`L1C gridding successful!......................................." << endl;
17530 
17531 
17532  // granid=1;
17533  // write_L1C_granule(swtd, granid,l1cfile,l1cinput,lat_gd, lon_gd);
17534  // exit(1);
17535 
17536 //---- writing results -------------------------------------------
17537 //--------------------------------------------------------------
17538 
17539  float lontemp = 0.;
17540  selday = l1cinput->selday;
17541  selmon = l1cinput->selmon;
17542  selyear = l1cinput->selyear;
17543 
17544  std::string timestr,missionstr,fname_out, pathstr,monstr, daystr, yearstr, prodstr, gdstr, swtstr, swtnum, extstr,ofilestr,dirstr;
17545 
17546  if(asc_mode==1) dirstr="Ascending";
17547  else if(asc_mode==0) dirstr="Descending";
17548 
17549 
17550 
17551  pathstr = "out/";
17552  missionstr="PACE";
17553  monstr = std::to_string(selmon);
17554  daystr = std::to_string(selday);
17555  yearstr = std::to_string(selyear);
17556  timestr="T00:00:00Z";
17557  prodstr = "L1Cgrid_";
17558  swtstr = "_swt";
17559  swtnum = std::to_string(swtd);
17560  extstr = ".nc";
17561  ofilestr=std::string(l1cinput->ofile);
17562 
17563  fname_out = pathstr + ofilestr+"_"+ prodstr+senstr+swtstr+swtnum+extstr;
17564 
17565 
17566 
17567  string ATT_NAME="Units", ATT_VAL="degrees",GATT_NAME1="Title",GATT_VAL1="PACE OCI Level-1C Data",GATT_NAME2="instrument",GATT_VAL2="OCI",GATT_NAME3="processing_version",GATT_VAL3="V1.0",GATT_NAME4="Conventions",GATT_VAL4="CF-1.6";
17568  string GATT_NAME5="institution",GATT_VAL5="NASA Goddard Space Flight Center, Ocean Biology Processing Group",GATT_NAME6="license",GATT_VAL6="http://science.nasa.gov/earth-science/earth-science-data/data-information-policy/";
17569  string GATT_NAME7="naming_authority",GATT_VAL7="gov.nasa.gsfc.sci.oceancolor",GATT_NAME8="keywords_vocabulary",GATT_VAL8="NASA Global Change Master Directory (GCMD) Science Keywords";
17570  string GATT_NAME9="stdname_vocabulary",GATT_VAL9="NetCDF Climate and Forecast (CF) Metadata Convention",GATT_NAME10="creator_name",GATT_VAL10="NASA/GSFC",GATT_NAME11="creator_email",GATT_VAL11="data@oceancolor.gsfc.nasa.gov";
17571  string GATT_NAME12="creator_url",GATT_VAL12="http://oceancolor.gsfc.nasa.gov",GATT_NAME13="project",GATT_VAL13="PACE Project",GATT_NAME14="publisher_name",GATT_VAL14="NASA/GSFC";
17572  string GATT_NAME15="publisher_email",GATT_VAL15="data@oceancolor.gsfc.nasa.gov",GATT_NAME16="publisher_url",GATT_VAL16="http://oceancolor.gsfc.nasa.gov",GATT_NAME17="processing_level",GATT_VAL17="L1C";
17573  string GATT_NAME18="cdm_data_type",GATT_VAL18="swath",GATT_NAME19="orbit_number",GATT_VAL19="xxx",GATT_NAME20="history",GATT_VAL20="",GATT_NAME21="CDL_version_date",GATT_VAL21="2021-09-10",GATT_NAME22="product_name",GATT_VAL22=fname_out;
17574  string GATT_NAME23="startDirection",GATT_VAL23=dirstr,GATT_NAME24="endDirection",GATT_VAL24=dirstr,GATT_NAME25="time_coverage_start",GATT_VAL25=tswt_ini,GATT_NAME26="time_coverage_end",GATT_VAL26=tswt_end,GATT_NAME27="date_created",GATT_VAL27="2022-03-25T15:12:41Z",GATT_NAME28="sun_earth_distance",GATT_VAL28="0.990849042172323",GATT_NAME29="terrain_data_source",GATT_VAL29="",GATT_NAME30="spectral_response_function",GATT_VAL30="",GATT_NAME31="systematic_uncertainty_model",GATT_VAL31="",GATT_NAME32="nadir_bin",GATT_VAL32="12345",GATT_NAME33="bin_size_at_nadir",GATT_VAL33="5.2km2";
17575 
17576 
17577  l1cfile->gridname = fname_out.c_str();
17578  filename_lt = fname_out.c_str();
17579 
17580  cout<<"creating file for L1C coor..."<<filename_lt<<endl;
17581 
17582 
17583  if ((status = nc_create(filename_lt, NC_CLOBBER | NC_NETCDF4, &ncid_out)))
17584  check_err(status, __LINE__, __FILE__);
17585  //define dims
17586  // Define the dimensions,vars and attributes at the root level
17587  NY = num_gridlines-2;
17588  NX = nbinx;
17589 
17590  if(l1cinput->sensor==1){
17591  senstr="SPEXone";
17592  GATT_VAL2="SPEXone";
17593  GATT_VAL32="3567";
17594  NVIEWS=5;
17595  NBANDS=400;
17596  }
17597  else if (l1cinput->sensor==2){
17598  senstr="OCI";
17599  GATT_VAL2="OCI";
17600  GATT_VAL32="635";
17601  NVIEWS=2;
17602  NBANDS=249;
17603  }
17604  else if (l1cinput->sensor==3){
17605  senstr="HARP2";
17606  GATT_VAL2="HARP";
17607  GATT_VAL32="127";
17608  NVIEWS=90;
17609  NBANDS=1;
17610  }
17611  else{
17612  cout<<"sensor by default is OCI option 2....."<<endl;
17613  senstr="OCI";
17614  GATT_VAL2="OCI";
17615  GATT_VAL32="635";
17616  NVIEWS=2;
17617  NBANDS=249;
17618  }
17619 
17620 // lt_out = allocate2d_float(NY, NX);
17621  //DEF DIMENSIONS
17622  if ((status = nc_def_dim(ncid_out, "bins_across_track", NX, &x_dimid)))
17623  check_err(status, __LINE__, __FILE__);
17624  if ((status = nc_def_dim(ncid_out, "bins_along_track", NY, &y_dimid)))
17625  check_err(status, __LINE__, __FILE__);
17626  //dims for output var
17627  dimids[0] = y_dimid;
17628  dimids[1] = x_dimid;
17629  NDIMS=2;
17630  if ((status = nc_def_dim(ncid_out, "number_of_views", NVIEWS, &v_dimid)))
17631  check_err(status, __LINE__, __FILE__);
17632  if ((status = nc_def_dim(ncid_out, "intensity_bands_per_view", NBANDS, &b_dimid)))
17633  check_err(status, __LINE__, __FILE__);
17634  //define attributes
17635 // if (nc_put_att_text(ncid_out, varid1, ATT_NAME.c_str(), strlen(ATT_VAL.c_str()), ATT_VAL.c_str()))
17636 // check_err(status, __LINE__, __FILE__);
17637 // if (nc_put_att_text(ncid_out, varid2, ATT_NAME.c_str(), strlen(ATT_VAL.c_str()), ATT_VAL.c_str()))
17638 // check_err(status, __LINE__, __FILE__);
17639  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME1.c_str(), strlen(GATT_VAL1.c_str()),
17640  GATT_VAL1.c_str()))
17641  check_err(status, __LINE__, __FILE__);
17642  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME2.c_str(), strlen(GATT_VAL2.c_str()),
17643  GATT_VAL2.c_str()))
17644  check_err(status, __LINE__, __FILE__);
17645  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME3.c_str(), strlen(GATT_VAL3.c_str()),
17646  GATT_VAL3.c_str()))
17647  check_err(status, __LINE__, __FILE__);
17648  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME4.c_str(), strlen(GATT_VAL4.c_str()),
17649  GATT_VAL4.c_str()))
17650  check_err(status, __LINE__, __FILE__);
17651  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME5.c_str(), strlen(GATT_VAL5.c_str()),
17652  GATT_VAL5.c_str()))
17653  check_err(status, __LINE__, __FILE__);
17654  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME6.c_str(), strlen(GATT_VAL6.c_str()),
17655  GATT_VAL6.c_str()))
17656  check_err(status, __LINE__, __FILE__);
17657  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME7.c_str(), strlen(GATT_VAL7.c_str()),
17658  GATT_VAL7.c_str()))
17659  check_err(status, __LINE__, __FILE__);
17660  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME8.c_str(), strlen(GATT_VAL8.c_str()),
17661  GATT_VAL8.c_str()))
17662  check_err(status, __LINE__, __FILE__);
17663  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME9.c_str(), strlen(GATT_VAL9.c_str()),
17664  GATT_VAL9.c_str()))
17665  check_err(status, __LINE__, __FILE__);
17666  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME10.c_str(), strlen(GATT_VAL10.c_str()),
17667  GATT_VAL10.c_str()))
17668  check_err(status, __LINE__, __FILE__);
17669  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME11.c_str(), strlen(GATT_VAL11.c_str()),
17670  GATT_VAL11.c_str()))
17671  check_err(status, __LINE__, __FILE__);
17672  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME12.c_str(), strlen(GATT_VAL12.c_str()),
17673  GATT_VAL12.c_str()))
17674  check_err(status, __LINE__, __FILE__);
17675  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME13.c_str(), strlen(GATT_VAL13.c_str()),
17676  GATT_VAL13.c_str()))
17677  check_err(status, __LINE__, __FILE__);
17678  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME14.c_str(), strlen(GATT_VAL14.c_str()),
17679  GATT_VAL14.c_str()))
17680  check_err(status, __LINE__, __FILE__);
17681  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME15.c_str(), strlen(GATT_VAL15.c_str()),
17682  GATT_VAL15.c_str()))
17683  check_err(status, __LINE__, __FILE__);
17684  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME16.c_str(), strlen(GATT_VAL16.c_str()),
17685  GATT_VAL16.c_str()))
17686  check_err(status, __LINE__, __FILE__);
17687  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME17.c_str(), strlen(GATT_VAL17.c_str()),
17688  GATT_VAL17.c_str()))
17689  check_err(status, __LINE__, __FILE__);
17690  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME18.c_str(), strlen(GATT_VAL18.c_str()),
17691  GATT_VAL18.c_str()))
17692  check_err(status, __LINE__, __FILE__);
17693  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME19.c_str(), strlen(GATT_VAL19.c_str()),
17694  GATT_VAL19.c_str()))
17695  check_err(status, __LINE__, __FILE__);
17696  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME20.c_str(), strlen(GATT_VAL20.c_str()),
17697  GATT_VAL20.c_str()))
17698  check_err(status, __LINE__, __FILE__);
17699  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME21.c_str(), strlen(GATT_VAL21.c_str()),
17700  GATT_VAL21.c_str()))
17701  check_err(status, __LINE__, __FILE__);
17702  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME22.c_str(), strlen(GATT_VAL22.c_str()),
17703  GATT_VAL22.c_str()))
17704  check_err(status, __LINE__, __FILE__);
17705  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME23.c_str(), strlen(GATT_VAL23.c_str()),
17706  GATT_VAL23.c_str()))
17707  check_err(status, __LINE__, __FILE__);
17708  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME24.c_str(), strlen(GATT_VAL24.c_str()),
17709  GATT_VAL24.c_str()))
17710  check_err(status, __LINE__, __FILE__);
17711  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME25.c_str(), strlen(GATT_VAL25.c_str()),
17712  GATT_VAL25.c_str()))
17713  check_err(status, __LINE__, __FILE__);
17714  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME26.c_str(), strlen(GATT_VAL26.c_str()),
17715  GATT_VAL26.c_str()))
17716  check_err(status, __LINE__, __FILE__);
17717  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME27.c_str(), strlen(GATT_VAL27.c_str()),
17718  GATT_VAL27.c_str()))
17719  check_err(status, __LINE__, __FILE__);
17720  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME28.c_str(), strlen(GATT_VAL28.c_str()),
17721  GATT_VAL28.c_str()))
17722  check_err(status, __LINE__, __FILE__);
17723  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME29.c_str(), strlen(GATT_VAL29.c_str()),
17724  GATT_VAL29.c_str()))
17725  check_err(status, __LINE__, __FILE__);
17726  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME30.c_str(), strlen(GATT_VAL30.c_str()),
17727  GATT_VAL30.c_str()))
17728  check_err(status, __LINE__, __FILE__);
17729  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME31.c_str(), strlen(GATT_VAL31.c_str()),
17730  GATT_VAL31.c_str()))
17731  check_err(status, __LINE__, __FILE__);
17732  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME32.c_str(), strlen(GATT_VAL32.c_str()),
17733  GATT_VAL32.c_str()))
17734  check_err(status, __LINE__, __FILE__);
17735  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME33.c_str(), strlen(GATT_VAL33.c_str()),
17736  GATT_VAL33.c_str()))
17737  check_err(status, __LINE__, __FILE__);
17738 
17739  //define groups check_err(status, __LINE__, __FILE__);
17740  if ((status = nc_def_grp(ncid_out, "geolocation_data", &grp_coor))) //netcdf-4
17741  check_err(status, __LINE__, __FILE__);
17742  //def var
17743  if ((status = nc_def_var(grp_coor, "latitude", NC_FLOAT, NDIMS,
17744  dimids, &varid1)))
17745  check_err(status, __LINE__, __FILE__);
17746  if ((status = nc_def_var(grp_coor, "longitude", NC_FLOAT, NDIMS,
17747  dimids, &varid2)))
17748  check_err(status, __LINE__, __FILE__);
17749  //leave define mode-----------------------
17750  if ((status = nc_enddef(grp_coor))) //done def vars etc
17751  check_err(status, __LINE__, __FILE__);
17752 
17753 
17754  //writing the whole thing
17755  if ((status = nc_put_var_float(grp_coor, varid1, &lat_gd[0][0])))
17756  check_err(status, __LINE__, __FILE__);
17757 
17758  if ((status = nc_put_var_float(grp_coor, varid2, &lon_gd[0][0])))
17759  check_err(status, __LINE__, __FILE__);
17760 
17761 
17762 
17763 //define attributes of vars in groups
17764 //UNITS in degrees ----
17765  if (nc_put_att_text(grp_coor, varid1, ATT_NAME.c_str(), strlen(ATT_VAL.c_str()), ATT_VAL.c_str()))
17766  check_err(status, __LINE__, __FILE__);
17767  check_err(status, __LINE__, __FILE__);
17768  if (nc_put_att_text(grp_coor, varid2, ATT_NAME.c_str(), strlen(ATT_VAL.c_str()), ATT_VAL.c_str()))
17769  check_err(status, __LINE__, __FILE__);
17770 
17771 
17772 //close file
17773  if ((status = nc_close(ncid_out)))
17774  check_err(status, __LINE__, __FILE__);
17775 
17776 // delete [] (lt_out);
17777 
17778 //CASE ONLY LON POS VALUES***************************************************************************
17779 
17780  //Only positive longitude 0-360 degrees for visualization ****************************************************************
17781  //lat lon grid for visualization--
17782  prodstr = "L1Cgrid_lonpos_";
17783  // gdstr="_gdFULL_";
17784  //recompute number of gridlines based on lat limits -80 to 80 degrees
17785  //asc orbit goes from negative to positive latitude....
17786 
17787  NY = num_gridlines-2;
17788  NX = nbinx;
17789 
17790  cout<<"NY before geographic constraint."<<NY<<"NY1.initial lat index ."<<NY1<<"NY2..final lat index."<<NY2<<"NX.."<<NX<<endl;
17791 
17792  for (int i = 0; i < NY; i++) {
17793  for (int j = 0; j < NX; j++) {
17794  if (lat_gd[i][j] >= -80.) c1++;
17795  if (c1 == nbinx) {
17796  NY1 = i;
17797  }
17798  }
17799  if (NY1 >= 0) break;
17800  c1 = 1;
17801  }
17802 
17803  for (int i = 0;i < NY; i++) {
17804  for (int j = 0; j < NX; j++) {
17805  if (lat_gd[i][j] >= 80.) {
17806  NY2 = i - 1;
17807  }
17808  }
17809  if (NY2 >= 0) break;
17810  }
17811 
17812  l1cfile->NY1 = NY1;
17813  l1cfile->NY2 = NY2;
17814 
17815  NY = NY2 - NY1 + 1;
17816  cout<<"NY.after geographic constraint."<<NY<<"NY1.initial lat index ."<<NY1<<"NY2..final lat index."<<NY2<<"NX.."<<NX<<endl;
17817 
17818  lat_out = allocate2d_float(NY, NX);
17819  lon_out = allocate2d_float(NY, NX);
17820 
17821  int c=0;
17822  for (int i = NY1; i < NY2 + 1; i++) {
17823  for (int j = 0; j < NX; j++) {
17824  if(lon_gd[i][j]<0) lon_out[c][j]=lon_gd[i][j]+360;
17825  else lon_out[c][j]=lon_gd[i][j];
17826  lat_out[c][j] = lat_gd[i][j];
17827  }
17828  // cout<<"gd#..."<<c+1<<endl;
17829  c++;
17830 
17831  }
17832 
17833  extstr = ".nc";
17834 // fname_out = pathstr + missionstr + "_" + senstr + "." + yearstr + monstr + daystr + timestr + prodstr+extstr;
17835  fname_out = pathstr + ofilestr+"_"+ prodstr+senstr+swtstr+swtnum+extstr;
17836  cout<<"path..."<<pathstr<<"ofile.."<<ofilestr<<"prod.."<<prodstr<<endl;
17837 
17838  l1cfile->gridname = fname_out.c_str();
17839  filename_lt = fname_out.c_str();
17840  cout<<"creating file for L1C coor.with only POS LONGITUDE.."<<filename_lt<<endl;
17841 // if ((status = nc_create(filename_lt, NC_CLOBBER, &ncid_out)))
17842  if ((status = nc_create(filename_lt, NC_CLOBBER | NC_NETCDF4, &ncid_out)))
17843  check_err(status, __LINE__, __FILE__);
17844  //define dims
17845  // Define the dimensions,vars and attributes at the root level
17846 
17847 
17848  //DEF DIMENSIONS
17849  if ((status = nc_def_dim(ncid_out, "bins_across_track", NX, &x_dimid)))
17850  check_err(status, __LINE__, __FILE__);
17851  if ((status = nc_def_dim(ncid_out, "bins_along_track", NY, &y_dimid)))
17852  check_err(status, __LINE__, __FILE__);
17853  //dims for output var
17854  dimids[0] = y_dimid;
17855  dimids[1] = x_dimid;
17856  NDIMS=2;
17857  if ((status = nc_def_dim(ncid_out, "number_of_views", NVIEWS, &v_dimid)))
17858  check_err(status, __LINE__, __FILE__);
17859  if ((status = nc_def_dim(ncid_out, "intensity_bands_per_view", NBANDS, &b_dimid)))
17860  check_err(status, __LINE__, __FILE__);
17861 
17862  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME1.c_str(), strlen(GATT_VAL1.c_str()),
17863  GATT_VAL1.c_str()))
17864  check_err(status, __LINE__, __FILE__);
17865  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME2.c_str(), strlen(GATT_VAL2.c_str()),
17866  GATT_VAL2.c_str()))
17867  check_err(status, __LINE__, __FILE__);
17868  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME3.c_str(), strlen(GATT_VAL3.c_str()),
17869  GATT_VAL3.c_str()))
17870  check_err(status, __LINE__, __FILE__);
17871  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME4.c_str(), strlen(GATT_VAL4.c_str()),
17872  GATT_VAL4.c_str()))
17873  check_err(status, __LINE__, __FILE__);
17874  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME5.c_str(), strlen(GATT_VAL5.c_str()),
17875  GATT_VAL5.c_str()))
17876  check_err(status, __LINE__, __FILE__);
17877  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME6.c_str(), strlen(GATT_VAL6.c_str()),
17878  GATT_VAL6.c_str()))
17879  check_err(status, __LINE__, __FILE__);
17880  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME7.c_str(), strlen(GATT_VAL7.c_str()),
17881  GATT_VAL7.c_str()))
17882  check_err(status, __LINE__, __FILE__);
17883  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME8.c_str(), strlen(GATT_VAL8.c_str()),
17884  GATT_VAL8.c_str()))
17885  check_err(status, __LINE__, __FILE__);
17886  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME9.c_str(), strlen(GATT_VAL9.c_str()),
17887  GATT_VAL9.c_str()))
17888  check_err(status, __LINE__, __FILE__);
17889  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME10.c_str(), strlen(GATT_VAL10.c_str()),
17890  GATT_VAL10.c_str()))
17891  check_err(status, __LINE__, __FILE__);
17892  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME11.c_str(), strlen(GATT_VAL11.c_str()),
17893  GATT_VAL11.c_str()))
17894  check_err(status, __LINE__, __FILE__);
17895  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME12.c_str(), strlen(GATT_VAL12.c_str()),
17896  GATT_VAL12.c_str()))
17897  check_err(status, __LINE__, __FILE__);
17898  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME13.c_str(), strlen(GATT_VAL13.c_str()),
17899  GATT_VAL13.c_str()))
17900  check_err(status, __LINE__, __FILE__);
17901  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME14.c_str(), strlen(GATT_VAL14.c_str()),
17902  GATT_VAL14.c_str()))
17903  check_err(status, __LINE__, __FILE__);
17904  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME15.c_str(), strlen(GATT_VAL15.c_str()),
17905  GATT_VAL15.c_str()))
17906  check_err(status, __LINE__, __FILE__);
17907  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME16.c_str(), strlen(GATT_VAL16.c_str()),
17908  GATT_VAL16.c_str()))
17909  check_err(status, __LINE__, __FILE__);
17910  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME17.c_str(), strlen(GATT_VAL17.c_str()),
17911  GATT_VAL17.c_str()))
17912  check_err(status, __LINE__, __FILE__);
17913  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME18.c_str(), strlen(GATT_VAL18.c_str()),
17914  GATT_VAL18.c_str()))
17915  check_err(status, __LINE__, __FILE__);
17916  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME19.c_str(), strlen(GATT_VAL19.c_str()),
17917  GATT_VAL19.c_str()))
17918  check_err(status, __LINE__, __FILE__);
17919  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME20.c_str(), strlen(GATT_VAL20.c_str()),
17920  GATT_VAL20.c_str()))
17921  check_err(status, __LINE__, __FILE__);
17922  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME21.c_str(), strlen(GATT_VAL21.c_str()),
17923  GATT_VAL21.c_str()))
17924  check_err(status, __LINE__, __FILE__);
17925  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME22.c_str(), strlen(GATT_VAL22.c_str()),
17926  GATT_VAL22.c_str()))
17927  check_err(status, __LINE__, __FILE__);
17928  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME23.c_str(), strlen(GATT_VAL23.c_str()),
17929  GATT_VAL23.c_str()))
17930  check_err(status, __LINE__, __FILE__);
17931  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME24.c_str(), strlen(GATT_VAL24.c_str()),
17932  GATT_VAL24.c_str()))
17933  check_err(status, __LINE__, __FILE__);
17934  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME25.c_str(), strlen(GATT_VAL25.c_str()),
17935  GATT_VAL25.c_str()))
17936  check_err(status, __LINE__, __FILE__);
17937  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME26.c_str(), strlen(GATT_VAL26.c_str()),
17938  GATT_VAL26.c_str()))
17939  check_err(status, __LINE__, __FILE__);
17940  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME27.c_str(), strlen(GATT_VAL27.c_str()),
17941  GATT_VAL27.c_str()))
17942  check_err(status, __LINE__, __FILE__);
17943  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME28.c_str(), strlen(GATT_VAL28.c_str()),
17944  GATT_VAL28.c_str()))
17945  check_err(status, __LINE__, __FILE__);
17946  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME29.c_str(), strlen(GATT_VAL29.c_str()),
17947  GATT_VAL29.c_str()))
17948  check_err(status, __LINE__, __FILE__);
17949  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME30.c_str(), strlen(GATT_VAL30.c_str()),
17950  GATT_VAL30.c_str()))
17951  check_err(status, __LINE__, __FILE__);
17952  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME31.c_str(), strlen(GATT_VAL31.c_str()),
17953  GATT_VAL31.c_str()))
17954  check_err(status, __LINE__, __FILE__);
17955  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME32.c_str(), strlen(GATT_VAL32.c_str()),
17956  GATT_VAL32.c_str()))
17957  check_err(status, __LINE__, __FILE__);
17958  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME33.c_str(), strlen(GATT_VAL33.c_str()),
17959  GATT_VAL33.c_str()))
17960  check_err(status, __LINE__, __FILE__);
17961 
17962  //define groups check_err(status, __LINE__, __FILE__);
17963  if ((status = nc_def_grp(ncid_out, "geolocation_data", &grp_coor))) //netcdf-4
17964  check_err(status, __LINE__, __FILE__);
17965  //def var
17966  if ((status = nc_def_var(grp_coor, "latitude", NC_FLOAT, NDIMS,
17967  dimids, &varid1)))
17968  check_err(status, __LINE__, __FILE__);
17969  if ((status = nc_def_var(grp_coor, "longitude", NC_FLOAT, NDIMS,
17970  dimids, &varid2)))
17971  check_err(status, __LINE__, __FILE__);
17972 
17973  //leave define mode-----------------------
17974  if ((status = nc_enddef(grp_coor))) //done def vars etc
17975  check_err(status, __LINE__, __FILE__);
17976 
17977  //writing the whole thing
17978  if ((status = nc_put_var_float(grp_coor, varid1, &lat_out[0][0])))
17979  check_err(status, __LINE__, __FILE__);
17980 
17981  if ((status = nc_put_var_float(grp_coor, varid2, &lon_out[0][0])))
17982  check_err(status, __LINE__, __FILE__);
17983 
17984 //define attributes of vars in groups
17985  if (nc_put_att_text(grp_coor, varid1, ATT_NAME.c_str(), strlen(ATT_VAL.c_str()), ATT_VAL.c_str()))
17986  check_err(status, __LINE__, __FILE__);
17987  if (nc_put_att_text(grp_coor, varid2, ATT_NAME.c_str(), strlen(ATT_VAL.c_str()), ATT_VAL.c_str()))
17988  check_err(status, __LINE__, __FILE__);
17989 
17990 
17991  if ((status = nc_close(ncid_out)))
17992  check_err(status, __LINE__, __FILE__);
17993 
17994 
17995  delete [] (lat_out);
17996  delete [] (lon_out);
17997  lat_out=nullptr;
17998  lon_out=nullptr;
17999 
18000 
18001 
18002 //CASE INVERTED ALONG/ACROSS INDEXES ***************************************************************************
18003  prodstr = "L1Cgrid_inverted_";
18004 
18005 
18006  lat_out = allocate2d_float(NY, NX);
18007  lon_out = allocate2d_float(NY, NX);
18008 
18009  c = 0;
18010  for (int i = NY1; i < NY2 + 1; i++) {
18011  for (int j = 0; j < NX; j++) {
18012  lat_out[NY - 1 - c][NX - 1 - j] = lat_gd[i][j];
18013  lon_out[NY - 1 - c][j] = lon_gd[i][j];
18014  }
18015  c++;
18016  }
18017 
18018  extstr = ".nc";
18019 // fname_out = pathstr + missionstr + "_" + senstr + "." + yearstr + monstr + daystr + timestr + prodstr+extstr;
18020  fname_out = pathstr + ofilestr+"_"+ prodstr+senstr+swtstr+swtnum+extstr;
18021  l1cfile->gridname = fname_out.c_str();
18022  filename_lt = fname_out.c_str();
18023  cout<<"creating file for L1C coor.with x/y inverted indexes.."<<filename_lt<<endl;
18024 // if ((status = nc_create(filename_lt, NC_CLOBBER, &ncid_out)))
18025  if ((status = nc_create(filename_lt, NC_CLOBBER | NC_NETCDF4, &ncid_out)))
18026  check_err(status, __LINE__, __FILE__);
18027  //define dims
18028  // Define the dimensions,vars and attributes at the root level
18029 
18030 
18031  //DEF DIMENSIONS
18032  if ((status = nc_def_dim(ncid_out, "bins_across_track", NX, &x_dimid)))
18033  check_err(status, __LINE__, __FILE__);
18034  if ((status = nc_def_dim(ncid_out, "bins_along_track", NY, &y_dimid)))
18035  check_err(status, __LINE__, __FILE__);
18036  //dims for output var
18037  dimids[0] = y_dimid;
18038  dimids[1] = x_dimid;
18039  NDIMS=2;
18040  if ((status = nc_def_dim(ncid_out, "number_of_views", NVIEWS, &v_dimid)))
18041  check_err(status, __LINE__, __FILE__);
18042  if ((status = nc_def_dim(ncid_out, "intensity_bands_per_view", NBANDS, &b_dimid)))
18043  check_err(status, __LINE__, __FILE__);
18044 /*
18045 //def variables at the root level!
18046  if ((status = nc_def_var(ncid_out, "latitude", NC_FLOAT, NDIMS,
18047  dimids, &varid1)))
18048  check_err(status, __LINE__, __FILE__);
18049  if ((status = nc_def_var(ncid_out, "longitude", NC_FLOAT, NDIMS,
18050  dimids, &varid2)))
18051  check_err(status, __LINE__, __FILE__);
18052 
18053  if ((status = nc_enddef(ncid_out))) //done def vars etc
18054  check_err(status, __LINE__, __FILE__);
18055  if ((status = nc_put_var_float(ncid_out, varid1, &lat_out[0][0])))
18056  check_err(status, __LINE__, __FILE__);
18057  if ((status = nc_put_var_float(ncid_out, varid2, &lon_out[0][0])))
18058  check_err(status, __LINE__, __FILE__);
18059 
18060 //define attributes
18061  if (nc_put_att_text(ncid_out, varid1, ATT_NAME.c_str(), strlen(ATT_VAL.c_str()), ATT_VAL.c_str()))
18062  check_err(status, __LINE__, __FILE__);
18063  if (nc_put_att_text(ncid_out, varid2, ATT_NAME.c_str(), strlen(ATT_VAL.c_str()), ATT_VAL.c_str()))
18064  check_err(status, __LINE__, __FILE__);
18065 */
18066 
18067  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME1.c_str(), strlen(GATT_VAL1.c_str()),
18068  GATT_VAL1.c_str()))
18069  check_err(status, __LINE__, __FILE__);
18070  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME2.c_str(), strlen(GATT_VAL2.c_str()),
18071  GATT_VAL2.c_str()))
18072  check_err(status, __LINE__, __FILE__);
18073  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME3.c_str(), strlen(GATT_VAL3.c_str()),
18074  GATT_VAL3.c_str()))
18075  check_err(status, __LINE__, __FILE__);
18076  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME4.c_str(), strlen(GATT_VAL4.c_str()),
18077  GATT_VAL4.c_str()))
18078  check_err(status, __LINE__, __FILE__);
18079  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME5.c_str(), strlen(GATT_VAL5.c_str()),
18080  GATT_VAL5.c_str()))
18081  check_err(status, __LINE__, __FILE__);
18082  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME6.c_str(), strlen(GATT_VAL6.c_str()),
18083  GATT_VAL6.c_str()))
18084  check_err(status, __LINE__, __FILE__);
18085  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME7.c_str(), strlen(GATT_VAL7.c_str()),
18086  GATT_VAL7.c_str()))
18087  check_err(status, __LINE__, __FILE__);
18088  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME8.c_str(), strlen(GATT_VAL8.c_str()),
18089  GATT_VAL8.c_str()))
18090  check_err(status, __LINE__, __FILE__);
18091  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME9.c_str(), strlen(GATT_VAL9.c_str()),
18092  GATT_VAL9.c_str()))
18093  check_err(status, __LINE__, __FILE__);
18094  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME10.c_str(), strlen(GATT_VAL10.c_str()),
18095  GATT_VAL10.c_str()))
18096  check_err(status, __LINE__, __FILE__);
18097  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME11.c_str(), strlen(GATT_VAL11.c_str()),
18098  GATT_VAL11.c_str()))
18099  check_err(status, __LINE__, __FILE__);
18100  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME12.c_str(), strlen(GATT_VAL12.c_str()),
18101  GATT_VAL12.c_str()))
18102  check_err(status, __LINE__, __FILE__);
18103  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME13.c_str(), strlen(GATT_VAL13.c_str()),
18104  GATT_VAL13.c_str()))
18105  check_err(status, __LINE__, __FILE__);
18106  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME14.c_str(), strlen(GATT_VAL14.c_str()),
18107  GATT_VAL14.c_str()))
18108  check_err(status, __LINE__, __FILE__);
18109  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME15.c_str(), strlen(GATT_VAL15.c_str()),
18110  GATT_VAL15.c_str()))
18111  check_err(status, __LINE__, __FILE__);
18112  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME16.c_str(), strlen(GATT_VAL16.c_str()),
18113  GATT_VAL16.c_str()))
18114  check_err(status, __LINE__, __FILE__);
18115  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME17.c_str(), strlen(GATT_VAL17.c_str()),
18116  GATT_VAL17.c_str()))
18117  check_err(status, __LINE__, __FILE__);
18118  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME18.c_str(), strlen(GATT_VAL18.c_str()),
18119  GATT_VAL18.c_str()))
18120  check_err(status, __LINE__, __FILE__);
18121  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME19.c_str(), strlen(GATT_VAL19.c_str()),
18122  GATT_VAL19.c_str()))
18123  check_err(status, __LINE__, __FILE__);
18124  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME20.c_str(), strlen(GATT_VAL20.c_str()),
18125  GATT_VAL20.c_str()))
18126  check_err(status, __LINE__, __FILE__);
18127  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME21.c_str(), strlen(GATT_VAL21.c_str()),
18128  GATT_VAL21.c_str()))
18129  check_err(status, __LINE__, __FILE__);
18130  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME22.c_str(), strlen(GATT_VAL22.c_str()),
18131  GATT_VAL22.c_str()))
18132  check_err(status, __LINE__, __FILE__);
18133  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME23.c_str(), strlen(GATT_VAL23.c_str()),
18134  GATT_VAL23.c_str()))
18135  check_err(status, __LINE__, __FILE__);
18136  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME24.c_str(), strlen(GATT_VAL24.c_str()),
18137  GATT_VAL24.c_str()))
18138  check_err(status, __LINE__, __FILE__);
18139  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME25.c_str(), strlen(GATT_VAL25.c_str()),
18140  GATT_VAL25.c_str()))
18141  check_err(status, __LINE__, __FILE__);
18142  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME26.c_str(), strlen(GATT_VAL26.c_str()),
18143  GATT_VAL26.c_str()))
18144  check_err(status, __LINE__, __FILE__);
18145  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME27.c_str(), strlen(GATT_VAL27.c_str()),
18146  GATT_VAL27.c_str()))
18147  check_err(status, __LINE__, __FILE__);
18148  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME28.c_str(), strlen(GATT_VAL28.c_str()),
18149  GATT_VAL28.c_str()))
18150  check_err(status, __LINE__, __FILE__);
18151  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME29.c_str(), strlen(GATT_VAL29.c_str()),
18152  GATT_VAL29.c_str()))
18153  check_err(status, __LINE__, __FILE__);
18154  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME30.c_str(), strlen(GATT_VAL30.c_str()),
18155  GATT_VAL30.c_str()))
18156  check_err(status, __LINE__, __FILE__);
18157  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME31.c_str(), strlen(GATT_VAL31.c_str()),
18158  GATT_VAL31.c_str()))
18159  check_err(status, __LINE__, __FILE__);
18160  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME32.c_str(), strlen(GATT_VAL32.c_str()),
18161  GATT_VAL32.c_str()))
18162  check_err(status, __LINE__, __FILE__);
18163  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME33.c_str(), strlen(GATT_VAL33.c_str()),
18164  GATT_VAL33.c_str()))
18165  check_err(status, __LINE__, __FILE__);
18166 
18167  //define groups check_err(status, __LINE__, __FILE__);
18168  if ((status = nc_def_grp(ncid_out, "geolocation_data", &grp_coor))) //netcdf-4
18169  check_err(status, __LINE__, __FILE__);
18170 /*
18171 //DEF DIMENSIONS
18172  if ((status = nc_def_dim(grp_coor, "x", NX, &x_dimid)))
18173  check_err(status, __LINE__, __FILE__);
18174  if ((status = nc_def_dim(grp_coor, "y", NY, &y_dimid)))
18175  check_err(status, __LINE__, __FILE__);
18176  dimids[0] = y_dimid;
18177  dimids[1] = x_dimid;
18178  NDIMS=2;
18179 */
18180  //def var
18181  if ((status = nc_def_var(grp_coor, "latitude", NC_FLOAT, NDIMS,
18182  dimids, &varid1)))
18183  check_err(status, __LINE__, __FILE__);
18184  if ((status = nc_def_var(grp_coor, "longitude", NC_FLOAT, NDIMS,
18185  dimids, &varid2)))
18186  check_err(status, __LINE__, __FILE__);
18187 
18188  //leave define mode-----------------------
18189  if ((status = nc_enddef(grp_coor))) //done def vars etc
18190  check_err(status, __LINE__, __FILE__);
18191  //writing the whole thing
18192  if ((status = nc_put_var_float(grp_coor, varid1, &lat_out[0][0])))
18193  check_err(status, __LINE__, __FILE__);
18194 
18195  if ((status = nc_put_var_float(grp_coor, varid2, &lon_out[0][0])))
18196  check_err(status, __LINE__, __FILE__);
18197 
18198 
18199 //define attributes of vars in groups
18200  if (nc_put_att_text(grp_coor, varid1, ATT_NAME.c_str(), strlen(ATT_VAL.c_str()), ATT_VAL.c_str()))
18201  check_err(status, __LINE__, __FILE__);
18202  if (nc_put_att_text(grp_coor, varid2, ATT_NAME.c_str(), strlen(ATT_VAL.c_str()), ATT_VAL.c_str()))
18203  check_err(status, __LINE__, __FILE__);
18204 
18205 
18206 
18207  if ((status = nc_close(ncid_out)))
18208  check_err(status, __LINE__, __FILE__);
18209 
18210 
18211  delete [] (lat_out);
18212  delete [] (lon_out);
18213  lat_out=nullptr;
18214  lon_out=nullptr;
18215 
18216 
18217 
18218 //******** save az_east param as nc ***************************************************************
18219 //az_east[count]
18220  prodstr="az_east_";
18221  extstr = ".nc";
18222  fname_out = pathstr + ofilestr+"_"+ prodstr+senstr+extstr;
18223  filename_lt = fname_out.c_str();
18224  cout<<"creating file for az_east values in degrees as nc format.."<<filename_lt<<endl;
18225 // if ((status = nc_create(filename_lt, NC_CLOBBER, &ncid_out)))
18226  if ((status = nc_create(filename_lt, NC_CLOBBER | NC_NETCDF4, &ncid_out)))
18227  check_err(status, __LINE__, __FILE__);
18228  //define dims
18229  // Define the dimensions,vars and attributes at the root level
18230 
18231 
18232  //DEF DIMENSIONS
18233  if ((status = nc_def_dim(ncid_out, "bins_along_track", NY, &y_dimid)))
18234  check_err(status, __LINE__, __FILE__);
18235 //DEF VARIABLE
18236  if ((status = nc_def_var(ncid_out, "az_east", NC_FLOAT, 1,
18237  &y_dimid, &varid1)))
18238  check_err(status, __LINE__, __FILE__);
18239 
18240  if ((status = nc_enddef(ncid_out))) //done def vars etc
18241  check_err(status, __LINE__, __FILE__);
18242 
18243  for (int count = 0; count < num_gridlines - 2; count++) {
18244  if (az_east[count] < 0.001) az_east[count] = 0.0;}
18245  //writing the whole thing
18246  if ((status = nc_put_var_float(ncid_out, varid1, &az_east[0])))
18247  check_err(status, __LINE__, __FILE__);
18248 //close file
18249  if ((status = nc_close(ncid_out)))
18250  check_err(status, __LINE__, __FILE__);
18251 
18252  l1cfile->azeast_name = fname_out.c_str();
18253 
18254 
18255 //***********************************************************************************************
18256  prodstr = "L1CgridV_";
18257  extstr=".csv";
18258 
18259  fname_out = pathstr + ofilestr+"_"+ prodstr+senstr+extstr;
18260  // std::ofstream myl1c("/accounts/mamontes/images/OCIS/swt1_ALLgd_L1C500_swtd13again.csv");
18261  std::ofstream myl1cV(fname_out);
18262  for (int count = 0; count < num_gridlines - 2;count++) {
18263  // for(int count = 0; count <num_gridlines/100;count ++){
18264  for (int gp = 0; gp < nbinx; gp++) {
18265  lontemp = lon_gd[count][gp];
18266  if (lon_gd[count][gp] < -180.) lontemp = lon_gd[count][gp] + 360;
18267  if (lon_gd[count][gp] > +180.) lontemp = lon_gd[count][gp] - 360;
18268  if (lontemp < 0.) lontemp += 360.;//make better visualization, all lon values positive
18269 
18270  myl1cV << lontemp << "," << lat_gd[count][gp] << endl;
18271  }
18272  }
18273 
18274 
18275  myl1cV.close();
18276 
18277 
18278  prodstr = "lat_nadpix_";
18279  fname_out = pathstr + ofilestr+"_"+ prodstr+senstr+extstr;
18280  // fname_out= "/accounts/mamontes/images/OCIS/out/"+"L1Cgrid_"+"lat_nadpix"+"_"+swtstr+".txt";
18281  // ofstream myfile1 ("/accounts/mamontes/images/OCIS/lat_nadpix_swtd13again.txt");
18282  ofstream myfile1(fname_out);
18283  if (myfile1.is_open())
18284  {
18285  myfile1 << "lat_nadpix.\n";
18286  for (int count = 0; count < num_gridlines - 2; count++) {
18287  // for(int gp = 0; gp <nbinx; gp ++){
18288  myfile1 << lati2[count] << "," << endl;
18289  }
18290  myfile1.close();
18291  }
18292  else cout << "Unable to open file";
18293  prodstr = "lon_nadpix_";
18294  fname_out = pathstr + ofilestr+"_"+ prodstr+senstr+extstr;
18295  // fname_out= "/accounts/mamontes/images/OCIS/out/"+"L1Cgrid_"+"lon_nadpix"+"_"+swtstr+".txt";
18296  // ofstream myfile2 ("/accounts/mamontes/images/OCIS/lon_nadpix_swtd13again.txt");
18297  ofstream myfile2(fname_out);
18298  if (myfile2.is_open())
18299  {
18300  myfile2 << "lon_nadpix.\n";
18301  for (int count = 0; count < num_gridlines - 2; count++) {
18302  // for(int gp = 0; gp <nbinx; gp ++){
18303  myfile2 << loni2[count] << "," << endl;
18304  }
18305  myfile2.close();
18306  }
18307  else cout << "Unable to open file";
18308 
18309 /* prodstr = "az_east";
18310  fname_out = pathstr + ofilestr+"_"+ prodstr+extstr;
18311 
18312  l1cfile->azeast_name = fname_out.c_str();
18313 
18314 
18315 
18316  // fname_out= "/accounts/mamontes/images/OCIS/out/"+"L1Cgrid_"+"lon_nadpix"+"_"+swtstr+".txt";
18317  // ofstream myfile2 ("/accounts/mamontes/images/OCIS/lon_nadpix_swtd13again.txt");
18318  ofstream myfile3(fname_out);
18319  if (myfile3.is_open())
18320  {
18321  myfile3 << "az_east.\n";
18322  for (int count = 0; count < num_gridlines - 2; count++) {
18323  if (az_east[count] < 0.001) az_east[count] = 0.0;
18324  myfile3 << az_east[count] << "," << endl;
18325  }
18326  myfile3.close();
18327  }
18328  else cout << "Unable to open file";
18329 */
18330 
18331 
18332  if(lati_l!=nullptr)
18333  delete[](lati_l);
18334  if(lati_r!=nullptr)
18335  delete[](lati_r);
18336  if(loni_l!=nullptr)
18337  delete[](loni_l);
18338  if(loni_r!=nullptr)
18339  delete[](loni_r);
18340 
18341 
18342  cout << " SUCCESS writing results full L1C grid center positions for--swath #..." << swtd << "\n";
18343 
18344 
18345 
18346 
18347  return 0;
18348  }
18349 
18350 
18351 
18352 
18353 
18354 //swath processing-----
18355 int32_t L1C::across_gridlines_l1c_vec2(int swtd, l1c_filehandle* l1cfile, L1C_input* l1cinput,float* lati2, float* loni2, float** lat_gd, float** lon_gd, float* az_east) {
18356  int32_t num_gridlines, nbinx, NY1 = -1, NY2 = -1, c1 = 1;
18357  float lat1_l, lat1_r, lon1_l, lon1_r, az_r, az_l, *lati_l, *loni_l, *lati_r, *loni_r;
18358  int ncid_out,x_dimid, y_dimid, varid1, varid2, status;
18359  int NDIMS=2;
18360  int dimids[NDIMS];
18361  int32_t NX, NY;
18362  int16_t selyear = -1, selmon = -1, selday = -1;
18363  double latih, lonih, latih2, lonih2, res1, res2;
18364  float gres;
18365  int fnan1=0, fnan2=0, fnan3=0, fnan4=0;
18366  float latfirst = -999;
18367  int badline = 0;
18368  int grp_coor;
18369  const char* filename_lt;
18370  float **lat_out=nullptr,**lon_out=nullptr;
18371 // float **lt_out=nullptr;
18372  int NVIEWS, NBANDS,v_dimid,b_dimid,asc_mode=-1;
18373  string senstr,tswt_ini,tswt_end,tswt_ini_file;
18374 
18375 
18376  Geodesic geod(Constants::WGS84_a(), Constants::WGS84_f());
18377 
18378 
18379  if(l1cinput->sensor==1) senstr="SPEXone";
18380  else if (l1cinput->sensor==2) senstr="OCI";
18381  else if (l1cinput->sensor==3) senstr="HARP";
18382  else{cout<<"sensor by default is OCI option 2....."<<endl;
18383  senstr="OCI"; }
18384 
18385  //compute azimuth angle for each along-track position (nadir pixel or centered swath pixel) of the swath
18386  //azimuth angle in rads
18387  //lon+540/360-180 is a normalization factor for -180 to 180 degrees
18388  num_gridlines = l1cfile->num_gridlines;
18389  num_pixels = l1cfile->npix;
18390  nbinx = l1cfile->nbinx;
18391 
18392  tswt_ini=l1cfile->tswt_ini;
18393  tswt_end=l1cfile->tswt_end;
18394  tswt_ini_file=l1cfile->tswt_ini_file;
18395 
18396 
18397  lati_l = (float*)calloc(nbinx / 2 , sizeof(float));
18398  lati_r = (float*)calloc(nbinx / 2 , sizeof(float));
18399  loni_l = (float*)calloc(nbinx / 2 , sizeof(float));
18400  loni_r = (float*)calloc(nbinx / 2 , sizeof(float));
18401 
18402  //big loop
18403 
18404  int gd = 0;
18405  asc_mode=l1cfile->orb_dir;
18406 
18407 
18408  //compute mean az_east---
18409 
18410  float mean_az_east=l1cfile->mean_az_east;
18411 
18412  cout << "recomputing mean_az_east..(based on second interp rather than first interp)" << mean_az_east << "num_gridlines.." << num_gridlines << endl;
18413 
18414 
18415 
18416  for (int j = 0;j < num_gridlines;j++) {
18417  az_east[j] = mean_az_east;
18418  }
18419 
18420 
18421 //i==1 cause 1 more bin for second interpolation
18422  for (int i = 0;i <num_gridlines;i++) {
18423 
18424  if (i % 1 == 0) {
18425  //assign central positions---
18426  lat1_l = lati2[i] * M_PI / 180.;
18427  lat1_r = lati2[i] * M_PI / 180.;
18428  lon1_l = loni2[i] * M_PI / 180.;
18429  lon1_r = loni2[i] * M_PI / 180.;
18430 
18431  gres = (l1cinput->gres) * 1000; //grid resolution in meters
18432 
18433  //compute RIGHT across-gridline pixels---
18434  for (int k = 0;k < (nbinx / 2);k++) {
18435 
18436  //right pixels---
18437  az_r = mean_az_east * degrad;
18438 
18439  //left pixels---
18440  az_l = az_r - M_PI;
18441 
18442  //bearing should be always positive (clockwise) before pixel location calculation based on Harverside---
18443  if (az_r < 0.) {
18444  az_r = 360 + az_r * 180 / M_PI;
18445  az_r = az_r * M_PI / 180;
18446  }
18447 
18448  if (az_l < 0.) {
18449  az_l = 360 + az_l * 180 / M_PI;
18450  az_l = az_l * M_PI / 180;
18451  }
18452 
18453  if(k==0){
18454  geod.Direct(lat1_r * 180 / M_PI, lon1_r * 180 / M_PI, az_r * 180 / M_PI, gres/2, latih, lonih);
18455  geod.Inverse(lat1_r * 180 / M_PI, lon1_r * 180 / M_PI, latih, lonih, res1);
18456  }
18457  else{
18458  geod.Direct(lat1_r * 180 / M_PI, lon1_r * 180 / M_PI, az_r * 180 / M_PI, gres, latih, lonih);
18459  geod.Inverse(lat1_r * 180 / M_PI, lon1_r * 180 / M_PI, latih, lonih, res1);
18460  }
18461 
18462 
18463  fnan1 = isnan(latih);
18464  fnan2 = isnan(lonih);
18465  lati_r[k] = latih;
18466  loni_r[k] = lonih;
18467  // cout<<"righside.."<<latih<<"..."<<lonih<<"res1"<<res1<<endl;
18468 
18469  lat1_r = lati_r[k] * M_PI / 180;
18470  lon1_r = loni_r[k] * M_PI / 180;
18471 
18472 
18473  if(k==0){
18474  geod.Direct(lat1_l * 180 / M_PI, lon1_l * 180 / M_PI, az_l * 180 / M_PI, gres/2, latih2, lonih2);
18475  geod.Inverse(lat1_l * 180 / M_PI, lon1_l * 180 / M_PI, latih2, lonih2, res2);
18476  }
18477  else{
18478  geod.Direct(lat1_l * 180 / M_PI, lon1_l * 180 / M_PI, az_l * 180 / M_PI, gres, latih2, lonih2);
18479  geod.Inverse(lat1_l * 180 / M_PI, lon1_l * 180 / M_PI, latih2, lonih2, res2);
18480 
18481  }
18482 
18483 /* if(i==2000){//before and after crossing
18484  cout<<"gd#..."<<i+1<<"binx.."<<k+1<<"az_r.."<<az_r* 180 / M_PI<<"az_l.."<<az_l* 180 / M_PI<<endl;
18485  cout<<"lat1_l.."<<lat1_l<<"lon1_l.."<<lon1_l<<"latih2.."<<latih2<<"lonih2.."<<lonih2<<"res2.."<<res2<<endl;
18486  cout<<"lat1_r.."<<lat1_r<<"lon1_r.."<<lon1_r<<"latih.."<<latih<<"lonih.."<<lonih<<"res1.."<<res1<<endl;
18487  }
18488  */
18489 
18490  fnan3 = isnan(latih2);
18491  fnan4 = isnan(lonih2);
18492  lati_l[k] = latih2;
18493  loni_l[k] = lonih2;
18494  // cout<<"leftside.."<<latih2<<"..."<<lonih2<<"res2"<<res2<<endl;
18495 
18496  lat1_l = lati_l[k] * M_PI / 180;
18497  lon1_l = loni_l[k] * M_PI / 180;
18498 
18499  //right swath side------------- //we tolerate +- 6 m error
18500 
18501 // if (asc_mode==1 && lati2[i]>lati2[i+1] || asc_mode==0 && lati2[i]<lati2[i+1] || fnan1 > 0 || fnan2 > 0 || res1 > (gres + 6) || res1 < (gres - 6)) { //nan values
18502 // if (asc_mode==1 && lati2[i]>lati2[i+1] || asc_mode==0 && lati2[i]<lati2[i+1] || fnan1 > 0 || fnan2 > 0 || res1 > (gres + 6)) { //nan val
18503  if (fnan1 > 0 || fnan2 > 0 || res1 > (gres + 6)) { //nan values
18504  badline++;
18505  if (badline == 1) {
18506  latfirst = lati2[i];
18507  }
18508 
18509  cout << "bad interpolation - missing orbital data at near nadir grid cell..NAN right side of line.." << i + 1 << "corresponding to lat..."<<latfirst <<"lati2[i].."<<lati2[i]<<endl;
18510  cout<<"gd.."<<gd+1<<"XBIN.."<<k+1<<"lati_l[k]"<<lati_l[k]<<"loni_l[k]"<<loni_l[k]<<"lati_r[k]"<<lati_r[k]<<"loni_r[k]"<<loni_r[k]<<endl;
18511 
18512  lati2[i] = NAN;
18513  loni2[i] = NAN;
18514 
18515  for (int k = 0;k < (nbinx / 2);k++) {
18516  lat_gd[gd][k + nbinx / 2] = NAN;
18517  lon_gd[gd][k + nbinx / 2] = NAN;
18518  }
18519  // cout<<"nan value.right.."<<endl;
18520  }
18521  else {
18522  lat_gd[gd][k + nbinx / 2] = latih;
18523  lon_gd[gd][k + nbinx / 2] = lonih;
18524  }
18525 
18526  //left side
18527  // if (asc_mode==1 && lati2[i]>lati2[i+1] || asc_mode==0 && lati2[i]<lati2[i+1] || fnan3 > 0 || fnan4 > 0 || res2 > (gres + 6) || res2 < (gres - 6)) {
18528  // if (asc_mode==1 && lati2[i]>lati2[i+1] || asc_mode==0 && lati2[i]<lati2[i+1] || fnan3 > 0 || fnan4 > 0 || res2 > (gres + 6)) {
18529  if (fnan3 > 0 || fnan4 > 0 || res2 > (gres + 6)) {
18530  // if(fnan3>0 | fnan4>0 | res2>(gres+6) | res2<(gres-6)){
18531  cout << "bad interpolation - missing orbital data at near nadir grid cell..NAN left side of line.." << i + 1 << endl;
18532  cout<<"gd.."<<gd+1<<"XBIN.."<<k+1<<"lati_l[k]"<<lati_l[k]<<"loni_l[k]"<<loni_l[k]<<"lati_r[k]"<<lati_r[k]<<"loni_r[k]"<<loni_r[k]<<"lati2[i].."<<lati2[i]<<endl;
18533 
18534  lati2[i] = NAN;
18535  loni2[i] = NAN;
18536  for (int k = 0;k < (nbinx / 2);k++) {
18537  lat_gd[gd][nbinx / 2 - 1 - k] = NAN;//as k increases we are farther away from nadpix or along-track position---
18538  lon_gd[gd][nbinx / 2 - 1 - k] = NAN;
18539  }
18540  // cout<<"nan value.left.."<<endl;
18541  }
18542  else {
18543  lat_gd[gd][nbinx / 2 - 1 - k] = latih2;//as k increases we are farther away from nadpix or along-track position---
18544  lon_gd[gd][nbinx / 2 - 1 - k] = lonih2;
18545  }
18546  fnan1=0;
18547  fnan2=0;
18548  fnan3=0;
18549  fnan4=0;
18550 
18551  }//end BINX k loop
18552 
18553  gd++;
18554  }//end if every 100 gd
18555  }//end gridlines loop
18556  cout << "`L1C gridding successful!......................................." << endl;
18557 
18558 
18559 //---- writing results -------------------------------------------
18560 //--------------------------------------------------------------
18561 
18562 
18563  selday = l1cinput->selday;
18564  selmon = l1cinput->selmon;
18565  selyear = l1cinput->selyear;
18566 
18567  std::string timestr,missionstr,fname_out, pathstr,monstr, daystr, yearstr, prodstr, gdstr, swtstr, swtnum, extstr,ofilestr,dirstr;
18568 
18569  if(asc_mode==1) dirstr="Ascending";
18570  else if(asc_mode==0) dirstr="Descending";
18571 
18572 
18573 
18574  pathstr = "out/";
18575  missionstr="PACE";
18576  monstr = std::to_string(selmon);
18577  daystr = std::to_string(selday);
18578  yearstr = std::to_string(selyear);
18579  timestr="T00:00:00Z";
18580  prodstr = "L1Cgrid_";
18581  swtstr = "_swt";
18582  swtnum = std::to_string(swtd);
18583  extstr = ".nc";
18584  ofilestr=std::string(l1cinput->ofile);
18585 
18586 // fname_out = pathstr + ofilestr+"_"+ prodstr+senstr+swtstr+swtnum+extstr;
18587  fname_out=pathstr+"PACE_"+senstr+"."+tswt_ini_file+".L1C.5.2km.nc";
18588  // string datestr=date;
18589 
18590  auto t = std::time(nullptr);
18591  auto tm = *std::localtime(&t);
18592  std::ostringstream oss,oss2;
18593  oss << std::put_time(&tm, "%d-%m-%Y %H-%M-%S") << std::endl;
18594  // cout<<"current datetime.n UTC."<<datestr<<endl;
18595  auto datestr = oss.str();
18596  cout<<"date.."<<datestr.substr(0,2)<<endl;
18597 
18598  time_t rawtime;
18599  time (&rawtime);
18600  string datestr2=ctime (&rawtime);
18601 
18602 
18603 // oss2<<system("date")<<endl;
18604 // string datestr2=oss2.str();
18605  cout<<"date.."<<datestr2.substr(0,10)<<endl;
18606 // exit(1);
18607 
18608 
18609 
18610 
18611  string ATT_NAME="Units", ATT_VAL="degrees",GATT_NAME1="Title",GATT_VAL1="PACE OCI Level-1C Data",GATT_NAME2="instrument",GATT_VAL2="OCI",GATT_NAME3="processing_version",GATT_VAL3="V1.0",GATT_NAME4="Conventions",GATT_VAL4="CF-1.6";
18612  string GATT_NAME5="institution",GATT_VAL5="NASA Goddard Space Flight Center, Ocean Biology Processing Group",GATT_NAME6="license",GATT_VAL6="http://science.nasa.gov/earth-science/earth-science-data/data-information-policy/";
18613  string GATT_NAME7="naming_authority",GATT_VAL7="gov.nasa.gsfc.sci.oceancolor",GATT_NAME8="keywords_vocabulary",GATT_VAL8="NASA Global Change Master Directory (GCMD) Science Keywords";
18614  string GATT_NAME9="stdname_vocabulary",GATT_VAL9="NetCDF Climate and Forecast (CF) Metadata Convention",GATT_NAME10="creator_name",GATT_VAL10="NASA/GSFC",GATT_NAME11="creator_email",GATT_VAL11="data@oceancolor.gsfc.nasa.gov";
18615  string GATT_NAME12="creator_url",GATT_VAL12="http://oceancolor.gsfc.nasa.gov",GATT_NAME13="project",GATT_VAL13="PACE Project",GATT_NAME14="publisher_name",GATT_VAL14="NASA/GSFC";
18616  string GATT_NAME15="publisher_email",GATT_VAL15="data@oceancolor.gsfc.nasa.gov",GATT_NAME16="publisher_url",GATT_VAL16="http://oceancolor.gsfc.nasa.gov",GATT_NAME17="processing_level",GATT_VAL17="L1C";
18617  string GATT_NAME18="cdm_data_type",GATT_VAL18="swath",GATT_NAME19="orbit_number",GATT_VAL19="xxx",GATT_NAME20="history",GATT_VAL20="",GATT_NAME21="CDL_version_date",GATT_VAL21="2021-09-10",GATT_NAME22="product_name",GATT_VAL22=fname_out;
18618  string GATT_NAME23="startDirection",GATT_VAL23=dirstr,GATT_NAME24="endDirection",GATT_VAL24=dirstr,GATT_NAME25="time_coverage_start",GATT_VAL25=tswt_ini,GATT_NAME26="time_coverage_end",GATT_VAL26=tswt_end,GATT_NAME27="date_created",GATT_VAL27="2022-03-25T15:12:41Z",GATT_NAME28="sun_earth_distance",GATT_VAL28="0.990849042172323",GATT_NAME29="terrain_data_source",GATT_VAL29="",GATT_NAME30="spectral_response_function",GATT_VAL30="",GATT_NAME31="systematic_uncertainty_model",GATT_VAL31="",GATT_NAME32="nadir_bin",GATT_VAL32="12345",GATT_NAME33="bin_size_at_nadir",GATT_VAL33="5.2km2";
18619 
18620 
18621  l1cfile->gridname = fname_out.c_str();
18622  filename_lt = fname_out.c_str();
18623 
18624  cout<<"creating file for L1C coor..."<<filename_lt<<endl;
18625 
18626 
18627  if ((status = nc_create(filename_lt, NC_CLOBBER | NC_NETCDF4, &ncid_out)))
18628  check_err(status, __LINE__, __FILE__);
18629  //define dims
18630  // Define the dimensions,vars and attributes at the root level
18631  NY = num_gridlines;
18632  NX = nbinx;
18633 
18634  if(l1cinput->sensor==1){
18635  senstr="SPEXone";
18636  GATT_VAL2="SPEXone";
18637  GATT_VAL32="3567";
18638  NVIEWS=5;
18639  NBANDS=400;
18640  }
18641  else if (l1cinput->sensor==2){
18642  senstr="OCI";
18643  GATT_VAL2="OCI";
18644  GATT_VAL32="635";
18645  NVIEWS=2;
18646  NBANDS=249;
18647  }
18648  else if (l1cinput->sensor==3){
18649  senstr="HARP2";
18650  GATT_VAL2="HARP";
18651  GATT_VAL32="127";
18652  NVIEWS=90;
18653  NBANDS=1;
18654  }
18655  else{
18656  cout<<"sensor by default is OCI option 2....."<<endl;
18657  senstr="OCI";
18658  GATT_VAL2="OCI";
18659  GATT_VAL32="635";
18660  NVIEWS=2;
18661  NBANDS=249;
18662  }
18663 
18664 // lt_out = allocate2d_float(NY, NX);
18665  //DEF DIMENSIONS
18666  if ((status = nc_def_dim(ncid_out, "bins_across_track", NX, &x_dimid)))
18667  check_err(status, __LINE__, __FILE__);
18668  if ((status = nc_def_dim(ncid_out, "bins_along_track", NY, &y_dimid)))
18669  check_err(status, __LINE__, __FILE__);
18670  //dims for output var
18671  dimids[0] = y_dimid;
18672  dimids[1] = x_dimid;
18673  NDIMS=2;
18674  if ((status = nc_def_dim(ncid_out, "number_of_views", NVIEWS, &v_dimid)))
18675  check_err(status, __LINE__, __FILE__);
18676  if ((status = nc_def_dim(ncid_out, "intensity_bands_per_view", NBANDS, &b_dimid)))
18677  check_err(status, __LINE__, __FILE__);
18678  //define attributes
18679 // if (nc_put_att_text(ncid_out, varid1, ATT_NAME.c_str(), strlen(ATT_VAL.c_str()), ATT_VAL.c_str()))
18680 // check_err(status, __LINE__, __FILE__);
18681 // if (nc_put_att_text(ncid_out, varid2, ATT_NAME.c_str(), strlen(ATT_VAL.c_str()), ATT_VAL.c_str()))
18682 // check_err(status, __LINE__, __FILE__);
18683  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME1.c_str(), strlen(GATT_VAL1.c_str()),
18684  GATT_VAL1.c_str()))
18685  check_err(status, __LINE__, __FILE__);
18686  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME2.c_str(), strlen(GATT_VAL2.c_str()),
18687  GATT_VAL2.c_str()))
18688  check_err(status, __LINE__, __FILE__);
18689  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME3.c_str(), strlen(GATT_VAL3.c_str()),
18690  GATT_VAL3.c_str()))
18691  check_err(status, __LINE__, __FILE__);
18692  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME4.c_str(), strlen(GATT_VAL4.c_str()),
18693  GATT_VAL4.c_str()))
18694  check_err(status, __LINE__, __FILE__);
18695  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME5.c_str(), strlen(GATT_VAL5.c_str()),
18696  GATT_VAL5.c_str()))
18697  check_err(status, __LINE__, __FILE__);
18698  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME6.c_str(), strlen(GATT_VAL6.c_str()),
18699  GATT_VAL6.c_str()))
18700  check_err(status, __LINE__, __FILE__);
18701  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME7.c_str(), strlen(GATT_VAL7.c_str()),
18702  GATT_VAL7.c_str()))
18703  check_err(status, __LINE__, __FILE__);
18704  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME8.c_str(), strlen(GATT_VAL8.c_str()),
18705  GATT_VAL8.c_str()))
18706  check_err(status, __LINE__, __FILE__);
18707  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME9.c_str(), strlen(GATT_VAL9.c_str()),
18708  GATT_VAL9.c_str()))
18709  check_err(status, __LINE__, __FILE__);
18710  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME10.c_str(), strlen(GATT_VAL10.c_str()),
18711  GATT_VAL10.c_str()))
18712  check_err(status, __LINE__, __FILE__);
18713  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME11.c_str(), strlen(GATT_VAL11.c_str()),
18714  GATT_VAL11.c_str()))
18715  check_err(status, __LINE__, __FILE__);
18716  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME12.c_str(), strlen(GATT_VAL12.c_str()),
18717  GATT_VAL12.c_str()))
18718  check_err(status, __LINE__, __FILE__);
18719  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME13.c_str(), strlen(GATT_VAL13.c_str()),
18720  GATT_VAL13.c_str()))
18721  check_err(status, __LINE__, __FILE__);
18722  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME14.c_str(), strlen(GATT_VAL14.c_str()),
18723  GATT_VAL14.c_str()))
18724  check_err(status, __LINE__, __FILE__);
18725  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME15.c_str(), strlen(GATT_VAL15.c_str()),
18726  GATT_VAL15.c_str()))
18727  check_err(status, __LINE__, __FILE__);
18728  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME16.c_str(), strlen(GATT_VAL16.c_str()),
18729  GATT_VAL16.c_str()))
18730  check_err(status, __LINE__, __FILE__);
18731  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME17.c_str(), strlen(GATT_VAL17.c_str()),
18732  GATT_VAL17.c_str()))
18733  check_err(status, __LINE__, __FILE__);
18734  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME18.c_str(), strlen(GATT_VAL18.c_str()),
18735  GATT_VAL18.c_str()))
18736  check_err(status, __LINE__, __FILE__);
18737  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME19.c_str(), strlen(GATT_VAL19.c_str()),
18738  GATT_VAL19.c_str()))
18739  check_err(status, __LINE__, __FILE__);
18740  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME20.c_str(), strlen(GATT_VAL20.c_str()),
18741  GATT_VAL20.c_str()))
18742  check_err(status, __LINE__, __FILE__);
18743  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME21.c_str(), strlen(GATT_VAL21.c_str()),
18744  GATT_VAL21.c_str()))
18745  check_err(status, __LINE__, __FILE__);
18746  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME22.c_str(), strlen(GATT_VAL22.c_str()),
18747  GATT_VAL22.c_str()))
18748  check_err(status, __LINE__, __FILE__);
18749  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME23.c_str(), strlen(GATT_VAL23.c_str()),
18750  GATT_VAL23.c_str()))
18751  check_err(status, __LINE__, __FILE__);
18752  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME24.c_str(), strlen(GATT_VAL24.c_str()),
18753  GATT_VAL24.c_str()))
18754  check_err(status, __LINE__, __FILE__);
18755  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME25.c_str(), strlen(GATT_VAL25.c_str()),
18756  GATT_VAL25.c_str()))
18757  check_err(status, __LINE__, __FILE__);
18758  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME26.c_str(), strlen(GATT_VAL26.c_str()),
18759  GATT_VAL26.c_str()))
18760  check_err(status, __LINE__, __FILE__);
18761  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME27.c_str(), strlen(GATT_VAL27.c_str()),
18762  GATT_VAL27.c_str()))
18763  check_err(status, __LINE__, __FILE__);
18764  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME28.c_str(), strlen(GATT_VAL28.c_str()),
18765  GATT_VAL28.c_str()))
18766  check_err(status, __LINE__, __FILE__);
18767  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME29.c_str(), strlen(GATT_VAL29.c_str()),
18768  GATT_VAL29.c_str()))
18769  check_err(status, __LINE__, __FILE__);
18770  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME30.c_str(), strlen(GATT_VAL30.c_str()),
18771  GATT_VAL30.c_str()))
18772  check_err(status, __LINE__, __FILE__);
18773  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME31.c_str(), strlen(GATT_VAL31.c_str()),
18774  GATT_VAL31.c_str()))
18775  check_err(status, __LINE__, __FILE__);
18776  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME32.c_str(), strlen(GATT_VAL32.c_str()),
18777  GATT_VAL32.c_str()))
18778  check_err(status, __LINE__, __FILE__);
18779  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME33.c_str(), strlen(GATT_VAL33.c_str()),
18780  GATT_VAL33.c_str()))
18781  check_err(status, __LINE__, __FILE__);
18782 
18783  //define groups check_err(status, __LINE__, __FILE__);
18784  if ((status = nc_def_grp(ncid_out, "geolocation_data", &grp_coor))) //netcdf-4
18785  check_err(status, __LINE__, __FILE__);
18786  //def var
18787  if ((status = nc_def_var(grp_coor, "latitude", NC_FLOAT, NDIMS,
18788  dimids, &varid1)))
18789  check_err(status, __LINE__, __FILE__);
18790  if ((status = nc_def_var(grp_coor, "longitude", NC_FLOAT, NDIMS,
18791  dimids, &varid2)))
18792  check_err(status, __LINE__, __FILE__);
18793  //leave define mode-----------------------
18794  if ((status = nc_enddef(grp_coor))) //done def vars etc
18795  check_err(status, __LINE__, __FILE__);
18796 
18797 
18798  //writing the whole thing
18799  if ((status = nc_put_var_float(grp_coor, varid1, &lat_gd[0][0])))
18800  check_err(status, __LINE__, __FILE__);
18801 
18802  if ((status = nc_put_var_float(grp_coor, varid2, &lon_gd[0][0])))
18803  check_err(status, __LINE__, __FILE__);
18804 
18805 
18806 
18807 //define attributes of vars in groups
18808 //UNITS in degrees ----
18809  if (nc_put_att_text(grp_coor, varid1, ATT_NAME.c_str(), strlen(ATT_VAL.c_str()), ATT_VAL.c_str()))
18810  check_err(status, __LINE__, __FILE__);
18811  check_err(status, __LINE__, __FILE__);
18812  if (nc_put_att_text(grp_coor, varid2, ATT_NAME.c_str(), strlen(ATT_VAL.c_str()), ATT_VAL.c_str()))
18813  check_err(status, __LINE__, __FILE__);
18814 
18815 
18816 //close file
18817  if ((status = nc_close(ncid_out)))
18818  check_err(status, __LINE__, __FILE__);
18819 
18820 // delete [] (lt_out);
18821 
18822 //CASE ONLY LON POS VALUES***************************************************************************
18823 
18824  //Only positive longitude 0-360 degrees for visualization ****************************************************************
18825  //lat lon grid for visualization--
18826  prodstr = "L1Cgrid_lonpos_";
18827  // gdstr="_gdFULL_";
18828  //recompute number of gridlines based on lat limits -80 to 80 degrees
18829  //asc orbit goes from negative to positive latitude....
18830 
18831  NY = num_gridlines;
18832  NX = nbinx;
18833 
18834  cout<<"NY before geographic constraint."<<NY<<"NY1.initial lat index ."<<NY1<<"NY2..final lat index."<<NY2<<"NX.."<<NX<<endl;
18835 
18836  for (int i = 0; i < NY; i++) {
18837  for (int j = 0; j < NX; j++) {
18838  if (lat_gd[i][j] >= -80.) c1++;
18839  if (c1 == nbinx) {
18840  NY1 = i;
18841  }
18842  }
18843  if (NY1 >= 0) break;
18844  c1 = 1;
18845  }
18846 
18847  for (int i = 0;i < NY; i++) {
18848  for (int j = 0; j < NX; j++) {
18849  if (lat_gd[i][j] >= 80.) {
18850  NY2 = i - 1;
18851  }
18852  }
18853  if (NY2 >= 0) break;
18854  }
18855 
18856 // l1cfile->NY1 = NY1;
18857 // l1cfile->NY2 = NY2;
18858  NY1=0;
18859  NY2=NY-1;
18860 //
18861 
18862  NY = NY2 - NY1 + 1;
18863  cout<<"NY.after geographic constraint."<<NY<<"NY1.initial lat index ."<<NY1<<"NY2..final lat index."<<NY2<<"NX.."<<NX<<endl;
18864 
18865  lat_out = allocate2d_float(NY, NX);
18866  lon_out = allocate2d_float(NY, NX);
18867 
18868  int c=0;
18869  for (int i = NY1; i < NY2 + 1; i++) {
18870  for (int j = 0; j < NX; j++) {
18871  if(lon_gd[i][j]<0) lon_out[c][j]=lon_gd[i][j]+360;
18872  else lon_out[c][j]=lon_gd[i][j];
18873  lat_out[c][j] = lat_gd[i][j];
18874  }
18875  // cout<<"gd#..."<<c+1<<endl;
18876  c++;
18877 
18878  }
18879 
18880  extstr = ".nc";
18881 // fname_out = pathstr + missionstr + "_" + senstr + "." + yearstr + monstr + daystr + timestr + prodstr+extstr;
18882  // fname_out = pathstr + ofilestr+"_"+ prodstr+senstr+swtstr+swtnum+extstr;
18883  fname_out=pathstr+"PACE_"+senstr+"."+tswt_ini_file+".L1C.5.2km"+prodstr+extstr;
18884  cout<<"path..."<<pathstr<<"ofile.."<<ofilestr<<"prod.."<<prodstr<<endl;
18885 
18886  l1cfile->gridname = fname_out.c_str();
18887  filename_lt = fname_out.c_str();
18888  cout<<"creating file for L1C coor.with only POS LONGITUDE.."<<filename_lt<<endl;
18889 // if ((status = nc_create(filename_lt, NC_CLOBBER, &ncid_out)))
18890  if ((status = nc_create(filename_lt, NC_CLOBBER | NC_NETCDF4, &ncid_out)))
18891  check_err(status, __LINE__, __FILE__);
18892  //define dims
18893  // Define the dimensions,vars and attributes at the root level
18894 
18895 
18896  //DEF DIMENSIONS
18897  if ((status = nc_def_dim(ncid_out, "bins_across_track", NX, &x_dimid)))
18898  check_err(status, __LINE__, __FILE__);
18899  if ((status = nc_def_dim(ncid_out, "bins_along_track", NY, &y_dimid)))
18900  check_err(status, __LINE__, __FILE__);
18901  //dims for output var
18902  dimids[0] = y_dimid;
18903  dimids[1] = x_dimid;
18904  NDIMS=2;
18905  if ((status = nc_def_dim(ncid_out, "number_of_views", NVIEWS, &v_dimid)))
18906  check_err(status, __LINE__, __FILE__);
18907  if ((status = nc_def_dim(ncid_out, "intensity_bands_per_view", NBANDS, &b_dimid)))
18908  check_err(status, __LINE__, __FILE__);
18909 
18910  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME1.c_str(), strlen(GATT_VAL1.c_str()),
18911  GATT_VAL1.c_str()))
18912  check_err(status, __LINE__, __FILE__);
18913  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME2.c_str(), strlen(GATT_VAL2.c_str()),
18914  GATT_VAL2.c_str()))
18915  check_err(status, __LINE__, __FILE__);
18916  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME3.c_str(), strlen(GATT_VAL3.c_str()),
18917  GATT_VAL3.c_str()))
18918  check_err(status, __LINE__, __FILE__);
18919  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME4.c_str(), strlen(GATT_VAL4.c_str()),
18920  GATT_VAL4.c_str()))
18921  check_err(status, __LINE__, __FILE__);
18922  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME5.c_str(), strlen(GATT_VAL5.c_str()),
18923  GATT_VAL5.c_str()))
18924  check_err(status, __LINE__, __FILE__);
18925  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME6.c_str(), strlen(GATT_VAL6.c_str()),
18926  GATT_VAL6.c_str()))
18927  check_err(status, __LINE__, __FILE__);
18928  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME7.c_str(), strlen(GATT_VAL7.c_str()),
18929  GATT_VAL7.c_str()))
18930  check_err(status, __LINE__, __FILE__);
18931  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME8.c_str(), strlen(GATT_VAL8.c_str()),
18932  GATT_VAL8.c_str()))
18933  check_err(status, __LINE__, __FILE__);
18934  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME9.c_str(), strlen(GATT_VAL9.c_str()),
18935  GATT_VAL9.c_str()))
18936  check_err(status, __LINE__, __FILE__);
18937  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME10.c_str(), strlen(GATT_VAL10.c_str()),
18938  GATT_VAL10.c_str()))
18939  check_err(status, __LINE__, __FILE__);
18940  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME11.c_str(), strlen(GATT_VAL11.c_str()),
18941  GATT_VAL11.c_str()))
18942  check_err(status, __LINE__, __FILE__);
18943  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME12.c_str(), strlen(GATT_VAL12.c_str()),
18944  GATT_VAL12.c_str()))
18945  check_err(status, __LINE__, __FILE__);
18946  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME13.c_str(), strlen(GATT_VAL13.c_str()),
18947  GATT_VAL13.c_str()))
18948  check_err(status, __LINE__, __FILE__);
18949  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME14.c_str(), strlen(GATT_VAL14.c_str()),
18950  GATT_VAL14.c_str()))
18951  check_err(status, __LINE__, __FILE__);
18952  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME15.c_str(), strlen(GATT_VAL15.c_str()),
18953  GATT_VAL15.c_str()))
18954  check_err(status, __LINE__, __FILE__);
18955  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME16.c_str(), strlen(GATT_VAL16.c_str()),
18956  GATT_VAL16.c_str()))
18957  check_err(status, __LINE__, __FILE__);
18958  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME17.c_str(), strlen(GATT_VAL17.c_str()),
18959  GATT_VAL17.c_str()))
18960  check_err(status, __LINE__, __FILE__);
18961  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME18.c_str(), strlen(GATT_VAL18.c_str()),
18962  GATT_VAL18.c_str()))
18963  check_err(status, __LINE__, __FILE__);
18964  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME19.c_str(), strlen(GATT_VAL19.c_str()),
18965  GATT_VAL19.c_str()))
18966  check_err(status, __LINE__, __FILE__);
18967  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME20.c_str(), strlen(GATT_VAL20.c_str()),
18968  GATT_VAL20.c_str()))
18969  check_err(status, __LINE__, __FILE__);
18970  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME21.c_str(), strlen(GATT_VAL21.c_str()),
18971  GATT_VAL21.c_str()))
18972  check_err(status, __LINE__, __FILE__);
18973  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME22.c_str(), strlen(GATT_VAL22.c_str()),
18974  GATT_VAL22.c_str()))
18975  check_err(status, __LINE__, __FILE__);
18976  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME23.c_str(), strlen(GATT_VAL23.c_str()),
18977  GATT_VAL23.c_str()))
18978  check_err(status, __LINE__, __FILE__);
18979  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME24.c_str(), strlen(GATT_VAL24.c_str()),
18980  GATT_VAL24.c_str()))
18981  check_err(status, __LINE__, __FILE__);
18982  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME25.c_str(), strlen(GATT_VAL25.c_str()),
18983  GATT_VAL25.c_str()))
18984  check_err(status, __LINE__, __FILE__);
18985  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME26.c_str(), strlen(GATT_VAL26.c_str()),
18986  GATT_VAL26.c_str()))
18987  check_err(status, __LINE__, __FILE__);
18988  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME27.c_str(), strlen(GATT_VAL27.c_str()),
18989  GATT_VAL27.c_str()))
18990  check_err(status, __LINE__, __FILE__);
18991  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME28.c_str(), strlen(GATT_VAL28.c_str()),
18992  GATT_VAL28.c_str()))
18993  check_err(status, __LINE__, __FILE__);
18994  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME29.c_str(), strlen(GATT_VAL29.c_str()),
18995  GATT_VAL29.c_str()))
18996  check_err(status, __LINE__, __FILE__);
18997  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME30.c_str(), strlen(GATT_VAL30.c_str()),
18998  GATT_VAL30.c_str()))
18999  check_err(status, __LINE__, __FILE__);
19000  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME31.c_str(), strlen(GATT_VAL31.c_str()),
19001  GATT_VAL31.c_str()))
19002  check_err(status, __LINE__, __FILE__);
19003  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME32.c_str(), strlen(GATT_VAL32.c_str()),
19004  GATT_VAL32.c_str()))
19005  check_err(status, __LINE__, __FILE__);
19006  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME33.c_str(), strlen(GATT_VAL33.c_str()),
19007  GATT_VAL33.c_str()))
19008  check_err(status, __LINE__, __FILE__);
19009 
19010  //define groups check_err(status, __LINE__, __FILE__);
19011  if ((status = nc_def_grp(ncid_out, "geolocation_data", &grp_coor))) //netcdf-4
19012  check_err(status, __LINE__, __FILE__);
19013  //def var
19014  if ((status = nc_def_var(grp_coor, "latitude", NC_FLOAT, NDIMS,
19015  dimids, &varid1)))
19016  check_err(status, __LINE__, __FILE__);
19017  if ((status = nc_def_var(grp_coor, "longitude", NC_FLOAT, NDIMS,
19018  dimids, &varid2)))
19019  check_err(status, __LINE__, __FILE__);
19020 
19021  //leave define mode-----------------------
19022  if ((status = nc_enddef(grp_coor))) //done def vars etc
19023  check_err(status, __LINE__, __FILE__);
19024 
19025  //writing the whole thing
19026  if ((status = nc_put_var_float(grp_coor, varid1, &lat_out[0][0])))
19027  check_err(status, __LINE__, __FILE__);
19028 
19029  if ((status = nc_put_var_float(grp_coor, varid2, &lon_out[0][0])))
19030  check_err(status, __LINE__, __FILE__);
19031 
19032 //define attributes of vars in groups
19033  if (nc_put_att_text(grp_coor, varid1, ATT_NAME.c_str(), strlen(ATT_VAL.c_str()), ATT_VAL.c_str()))
19034  check_err(status, __LINE__, __FILE__);
19035  if (nc_put_att_text(grp_coor, varid2, ATT_NAME.c_str(), strlen(ATT_VAL.c_str()), ATT_VAL.c_str()))
19036  check_err(status, __LINE__, __FILE__);
19037 
19038 
19039  if ((status = nc_close(ncid_out)))
19040  check_err(status, __LINE__, __FILE__);
19041 
19042 
19043  delete [] (lat_out);
19044  delete [] (lon_out);
19045  lat_out=nullptr;
19046  lon_out=nullptr;
19047 
19048 
19049 
19050 //CASE INVERTED ALONG/ACROSS INDEXES ***************************************************************************
19051  prodstr = "L1Cgrid_inverted_";
19052 
19053 
19054  lat_out = allocate2d_float(NY, NX);
19055  lon_out = allocate2d_float(NY, NX);
19056 
19057  c = 0;
19058  for (int i = NY1; i < NY2 + 1; i++) {
19059  for (int j = 0; j < NX; j++) {
19060  lat_out[NY - 1 - c][NX - 1 - j] = lat_gd[i][j];
19061  lon_out[NY - 1 - c][j] = lon_gd[i][j];
19062  }
19063  c++;
19064  }
19065 
19066  extstr = ".nc";
19067 // fname_out = pathstr + missionstr + "_" + senstr + "." + yearstr + monstr + daystr + timestr + prodstr+extstr;
19068 // fname_out = pathstr + ofilestr+"_"+ prodstr+senstr+swtstr+swtnum+extstr;
19069  fname_out=pathstr+"PACE_"+senstr+"."+tswt_ini_file+".L1C.5.2km"+prodstr+extstr;
19070  l1cfile->gridname = fname_out.c_str();
19071  filename_lt = fname_out.c_str();
19072  cout<<"creating file for L1C coor.with x/y inverted indexes.."<<filename_lt<<endl;
19073 // if ((status = nc_create(filename_lt, NC_CLOBBER, &ncid_out)))
19074  if ((status = nc_create(filename_lt, NC_CLOBBER | NC_NETCDF4, &ncid_out)))
19075  check_err(status, __LINE__, __FILE__);
19076  //define dims
19077  // Define the dimensions,vars and attributes at the root level
19078 
19079 
19080  //DEF DIMENSIONS
19081  if ((status = nc_def_dim(ncid_out, "bins_across_track", NX, &x_dimid)))
19082  check_err(status, __LINE__, __FILE__);
19083  if ((status = nc_def_dim(ncid_out, "bins_along_track", NY, &y_dimid)))
19084  check_err(status, __LINE__, __FILE__);
19085  //dims for output var
19086  dimids[0] = y_dimid;
19087  dimids[1] = x_dimid;
19088  NDIMS=2;
19089  if ((status = nc_def_dim(ncid_out, "number_of_views", NVIEWS, &v_dimid)))
19090  check_err(status, __LINE__, __FILE__);
19091  if ((status = nc_def_dim(ncid_out, "intensity_bands_per_view", NBANDS, &b_dimid)))
19092  check_err(status, __LINE__, __FILE__);
19093 
19094 
19095 
19096  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME1.c_str(), strlen(GATT_VAL1.c_str()),
19097  GATT_VAL1.c_str()))
19098  check_err(status, __LINE__, __FILE__);
19099  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME2.c_str(), strlen(GATT_VAL2.c_str()),
19100  GATT_VAL2.c_str()))
19101  check_err(status, __LINE__, __FILE__);
19102  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME3.c_str(), strlen(GATT_VAL3.c_str()),
19103  GATT_VAL3.c_str()))
19104  check_err(status, __LINE__, __FILE__);
19105  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME4.c_str(), strlen(GATT_VAL4.c_str()),
19106  GATT_VAL4.c_str()))
19107  check_err(status, __LINE__, __FILE__);
19108  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME5.c_str(), strlen(GATT_VAL5.c_str()),
19109  GATT_VAL5.c_str()))
19110  check_err(status, __LINE__, __FILE__);
19111  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME6.c_str(), strlen(GATT_VAL6.c_str()),
19112  GATT_VAL6.c_str()))
19113  check_err(status, __LINE__, __FILE__);
19114  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME7.c_str(), strlen(GATT_VAL7.c_str()),
19115  GATT_VAL7.c_str()))
19116  check_err(status, __LINE__, __FILE__);
19117  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME8.c_str(), strlen(GATT_VAL8.c_str()),
19118  GATT_VAL8.c_str()))
19119  check_err(status, __LINE__, __FILE__);
19120  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME9.c_str(), strlen(GATT_VAL9.c_str()),
19121  GATT_VAL9.c_str()))
19122  check_err(status, __LINE__, __FILE__);
19123  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME10.c_str(), strlen(GATT_VAL10.c_str()),
19124  GATT_VAL10.c_str()))
19125  check_err(status, __LINE__, __FILE__);
19126  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME11.c_str(), strlen(GATT_VAL11.c_str()),
19127  GATT_VAL11.c_str()))
19128  check_err(status, __LINE__, __FILE__);
19129  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME12.c_str(), strlen(GATT_VAL12.c_str()),
19130  GATT_VAL12.c_str()))
19131  check_err(status, __LINE__, __FILE__);
19132  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME13.c_str(), strlen(GATT_VAL13.c_str()),
19133  GATT_VAL13.c_str()))
19134  check_err(status, __LINE__, __FILE__);
19135  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME14.c_str(), strlen(GATT_VAL14.c_str()),
19136  GATT_VAL14.c_str()))
19137  check_err(status, __LINE__, __FILE__);
19138  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME15.c_str(), strlen(GATT_VAL15.c_str()),
19139  GATT_VAL15.c_str()))
19140  check_err(status, __LINE__, __FILE__);
19141  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME16.c_str(), strlen(GATT_VAL16.c_str()),
19142  GATT_VAL16.c_str()))
19143  check_err(status, __LINE__, __FILE__);
19144  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME17.c_str(), strlen(GATT_VAL17.c_str()),
19145  GATT_VAL17.c_str()))
19146  check_err(status, __LINE__, __FILE__);
19147  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME18.c_str(), strlen(GATT_VAL18.c_str()),
19148  GATT_VAL18.c_str()))
19149  check_err(status, __LINE__, __FILE__);
19150  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME19.c_str(), strlen(GATT_VAL19.c_str()),
19151  GATT_VAL19.c_str()))
19152  check_err(status, __LINE__, __FILE__);
19153  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME20.c_str(), strlen(GATT_VAL20.c_str()),
19154  GATT_VAL20.c_str()))
19155  check_err(status, __LINE__, __FILE__);
19156  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME21.c_str(), strlen(GATT_VAL21.c_str()),
19157  GATT_VAL21.c_str()))
19158  check_err(status, __LINE__, __FILE__);
19159  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME22.c_str(), strlen(GATT_VAL22.c_str()),
19160  GATT_VAL22.c_str()))
19161  check_err(status, __LINE__, __FILE__);
19162  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME23.c_str(), strlen(GATT_VAL23.c_str()),
19163  GATT_VAL23.c_str()))
19164  check_err(status, __LINE__, __FILE__);
19165  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME24.c_str(), strlen(GATT_VAL24.c_str()),
19166  GATT_VAL24.c_str()))
19167  check_err(status, __LINE__, __FILE__);
19168  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME25.c_str(), strlen(GATT_VAL25.c_str()),
19169  GATT_VAL25.c_str()))
19170  check_err(status, __LINE__, __FILE__);
19171  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME26.c_str(), strlen(GATT_VAL26.c_str()),
19172  GATT_VAL26.c_str()))
19173  check_err(status, __LINE__, __FILE__);
19174  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME27.c_str(), strlen(GATT_VAL27.c_str()),
19175  GATT_VAL27.c_str()))
19176  check_err(status, __LINE__, __FILE__);
19177  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME28.c_str(), strlen(GATT_VAL28.c_str()),
19178  GATT_VAL28.c_str()))
19179  check_err(status, __LINE__, __FILE__);
19180  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME29.c_str(), strlen(GATT_VAL29.c_str()),
19181  GATT_VAL29.c_str()))
19182  check_err(status, __LINE__, __FILE__);
19183  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME30.c_str(), strlen(GATT_VAL30.c_str()),
19184  GATT_VAL30.c_str()))
19185  check_err(status, __LINE__, __FILE__);
19186  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME31.c_str(), strlen(GATT_VAL31.c_str()),
19187  GATT_VAL31.c_str()))
19188  check_err(status, __LINE__, __FILE__);
19189  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME32.c_str(), strlen(GATT_VAL32.c_str()),
19190  GATT_VAL32.c_str()))
19191  check_err(status, __LINE__, __FILE__);
19192  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME33.c_str(), strlen(GATT_VAL33.c_str()),
19193  GATT_VAL33.c_str()))
19194  check_err(status, __LINE__, __FILE__);
19195 
19196  //define groups check_err(status, __LINE__, __FILE__);
19197  if ((status = nc_def_grp(ncid_out, "geolocation_data", &grp_coor))) //netcdf-4
19198  check_err(status, __LINE__, __FILE__);
19199 
19200 
19201  //def var
19202  if ((status = nc_def_var(grp_coor, "latitude", NC_FLOAT, NDIMS,
19203  dimids, &varid1)))
19204  check_err(status, __LINE__, __FILE__);
19205  if ((status = nc_def_var(grp_coor, "longitude", NC_FLOAT, NDIMS,
19206  dimids, &varid2)))
19207  check_err(status, __LINE__, __FILE__);
19208 
19209  //leave define mode-----------------------
19210  if ((status = nc_enddef(grp_coor))) //done def vars etc
19211  check_err(status, __LINE__, __FILE__);
19212  //writing the whole thing
19213  if ((status = nc_put_var_float(grp_coor, varid1, &lat_out[0][0])))
19214  check_err(status, __LINE__, __FILE__);
19215 
19216  if ((status = nc_put_var_float(grp_coor, varid2, &lon_out[0][0])))
19217  check_err(status, __LINE__, __FILE__);
19218 
19219 
19220 //define attributes of vars in groups
19221  if (nc_put_att_text(grp_coor, varid1, ATT_NAME.c_str(), strlen(ATT_VAL.c_str()), ATT_VAL.c_str()))
19222  check_err(status, __LINE__, __FILE__);
19223  if (nc_put_att_text(grp_coor, varid2, ATT_NAME.c_str(), strlen(ATT_VAL.c_str()), ATT_VAL.c_str()))
19224  check_err(status, __LINE__, __FILE__);
19225 
19226 
19227 
19228  if ((status = nc_close(ncid_out)))
19229  check_err(status, __LINE__, __FILE__);
19230 
19231 
19232  delete [] (lat_out);
19233  delete [] (lon_out);
19234  lat_out=nullptr;
19235  lon_out=nullptr;
19236 
19237 
19238 
19239 //******** save az_east param as nc ***************************************************************
19240 //az_east[count]
19241  prodstr="az_east_";
19242  extstr = ".nc";
19243 // fname_out = pathstr + ofilestr+"_"+ prodstr+senstr+extstr;
19244  fname_out=pathstr+"PACE_"+senstr+"."+tswt_ini_file+".L1C.5.2km"+prodstr+extstr;
19245  filename_lt = fname_out.c_str();
19246  cout<<"creating file for az_east values in degrees as nc format.."<<filename_lt<<endl;
19247 // if ((status = nc_create(filename_lt, NC_CLOBBER, &ncid_out)))
19248  if ((status = nc_create(filename_lt, NC_CLOBBER | NC_NETCDF4, &ncid_out)))
19249  check_err(status, __LINE__, __FILE__);
19250  //define dims
19251  // Define the dimensions,vars and attributes at the root level
19252 
19253 
19254  //DEF DIMENSIONS
19255  if ((status = nc_def_dim(ncid_out, "bins_along_track", NY, &y_dimid)))
19256  check_err(status, __LINE__, __FILE__);
19257 //DEF VARIABLE
19258  if ((status = nc_def_var(ncid_out, "az_east", NC_FLOAT, 1,
19259  &y_dimid, &varid1)))
19260  check_err(status, __LINE__, __FILE__);
19261 
19262  if ((status = nc_enddef(ncid_out))) //done def vars etc
19263  check_err(status, __LINE__, __FILE__);
19264 
19265  for (int count = 0; count < num_gridlines; count++) {
19266  if (az_east[count] < 0.001) az_east[count] = 0.0;}
19267  //writing the whole thing
19268  if ((status = nc_put_var_float(ncid_out, varid1, &az_east[0])))
19269  check_err(status, __LINE__, __FILE__);
19270 //close file
19271  if ((status = nc_close(ncid_out)))
19272  check_err(status, __LINE__, __FILE__);
19273 
19274  l1cfile->azeast_name = fname_out.c_str();
19275 
19276 
19277 //***********************************************************************************************
19278  prodstr = "L1CgridV_";
19279  extstr=".csv";
19280 
19281  fname_out = pathstr + ofilestr+"_"+ prodstr+senstr+extstr;
19282 
19283  std::ofstream myl1cV(fname_out);
19284  for (int count = 0; count < num_gridlines;count++) {
19285  if(count==1999 || count==2000){//equat crossing lines
19286  for (int gp = 0; gp < nbinx; gp++) {
19287  // lontemp = lon_gd[count][gp];
19288  // if (lon_gd[count][gp] < -180.) lontemp = lon_gd[count][gp] + 360;
19289  // if (lon_gd[count][gp] > +180.) lontemp = lon_gd[count][gp] - 360;
19290  // if (lontemp < 0.) lontemp += 360.;//make better visualization, all lon values positive
19291 
19292 // myl1cV << lontemp << "," << lat_gd[count][gp] << endl;
19293  myl1cV << lon_gd[count][gp] << "," << lat_gd[count][gp] << endl;
19294  }
19295 
19296 
19297  }
19298  }
19299 
19300 
19301  myl1cV.close();
19302 
19303 
19304  prodstr = "lat_nadpix_";
19305 // fname_out = pathstr + ofilestr+"_"+ prodstr+senstr+extstr;
19306  fname_out=pathstr+"PACE_"+senstr+"."+tswt_ini_file+".L1C.5.2km"+prodstr+extstr;
19307  // fname_out= "/accounts/mamontes/images/OCIS/out/"+"L1Cgrid_"+"lat_nadpix"+"_"+swtstr+".txt";
19308  // ofstream myfile1 ("/accounts/mamontes/images/OCIS/lat_nadpix_swtd13again.txt");
19309  ofstream myfile1(fname_out);
19310  if (myfile1.is_open())
19311  {
19312  myfile1 << "lat_nadpix.\n";
19313  for (int count = 0; count < num_gridlines; count++) {
19314  // for(int gp = 0; gp <nbinx; gp ++){
19315  myfile1 << lati2[count] << "," << endl;
19316  }
19317  myfile1.close();
19318  }
19319  else cout << "Unable to open file";
19320  prodstr = "lon_nadpix_";
19321 // fname_out = pathstr + ofilestr+"_"+ prodstr+senstr+extstr;
19322  fname_out=pathstr+"PACE_"+senstr+"."+tswt_ini_file+".L1C.5.2km"+prodstr+extstr;
19323  // fname_out= "/accounts/mamontes/images/OCIS/out/"+"L1Cgrid_"+"lon_nadpix"+"_"+swtstr+".txt";
19324  // ofstream myfile2 ("/accounts/mamontes/images/OCIS/lon_nadpix_swtd13again.txt");
19325  ofstream myfile2(fname_out);
19326  if (myfile2.is_open())
19327  {
19328  myfile2 << "lon_nadpix.\n";
19329  for (int count = 0; count < num_gridlines; count++) {
19330  // for(int gp = 0; gp <nbinx; gp ++){
19331  myfile2 << loni2[count] << "," << endl;
19332  }
19333  myfile2.close();
19334  }
19335  else cout << "Unable to open file";
19336 
19337 
19338  if(lati_l!=nullptr)
19339  delete[](lati_l);
19340  if(lati_r!=nullptr)
19341  delete[](lati_r);
19342  if(loni_l!=nullptr)
19343  delete[](loni_l);
19344  if(loni_r!=nullptr)
19345  delete[](loni_r);
19346 
19347 
19348  cout << " SUCCESS writing results full L1C grid center positions for--swath #..." << swtd << "\n";
19349 
19350 
19351 
19352  return 0;
19353  }
19354 
19355 
19356 
19357 int32_t L1C::across_gridlines_l1c_vec(int swtd, l1c_filehandle* l1cfile, L1C_input* l1cinput,float* lati2, float* loni2, float** lat_gd, float** lon_gd, float* az_east) {
19358  int32_t num_gridlines, nbinx, NY1 = -1, NY2 = -1, c1 = 1;
19359  float lat1_l, lat1_r, lon1_l, lon1_r, lat2, lon2, dlambda, az_r, az_l, h, *lati_l, *loni_l, *lati_r, *loni_r, htot = 0.,az=0.;
19360  int ncid_out,x_dimid, y_dimid, varid1, varid2, status;
19361  int NDIMS=2;
19362  int dimids[NDIMS];
19363  int32_t NX, NY;
19364  int16_t selyear = -1, selmon = -1, selday = -1;
19365  double latih, lonih, latih2, lonih2, res1, res2;
19366  float gres;
19367  int fnan1=0, fnan2=0, fnan3=0, fnan4=0;
19368  float latfirst = -999;
19369  int badline = 0;
19370  int grp_coor;
19371  const char* filename_lt;
19372  float **lat_out=nullptr,**lon_out=nullptr;
19373 // float **lt_out=nullptr;
19374  int NVIEWS, NBANDS,v_dimid,b_dimid;
19375 
19376  Geodesic geod(Constants::WGS84_a(), Constants::WGS84_f());
19377 
19378  //compute azimuth angle for each along-track position (nadir pixel or centered swath pixel) of the swath
19379  //azimuth angle in rads
19380  //lon+540/360-180 is a normalization factor for -180 to 180 degrees
19381  num_gridlines = l1cfile->num_gridlines;
19382  num_pixels = l1cfile->npix;
19383  nbinx = l1cfile->nbinx;
19384  lati_l = (float*)calloc(nbinx / 2 , sizeof(float));
19385  lati_r = (float*)calloc(nbinx / 2 , sizeof(float));
19386  loni_l = (float*)calloc(nbinx / 2 , sizeof(float));
19387  loni_r = (float*)calloc(nbinx / 2 , sizeof(float));
19388 
19389  //big loop
19390 
19391  int gd = 0;
19392 
19393 
19394  //compute mean az_east---
19395  float sum = 0., tot = 0.;
19396  size_t azc = 0;
19397  for (int i = 0;i < num_gridlines - 2;i++) {
19398 
19399  // cout<<"gd#.."<<i+1<<"lati2[i].."<<lati2[i]<<endl;
19400 
19401  //assign central positions---
19402  lat1_l = lati2[i] * M_PI / 180.;
19403  lat1_r = lati2[i] * M_PI / 180.;
19404  lat2 = lati2[i + 1] * M_PI / 180.;
19405  lon1_l = loni2[i] * M_PI / 180.;
19406  lon1_r = loni2[i] * M_PI / 180.;
19407  lon2 = loni2[i + 1] * M_PI / 180.;
19408 
19409  dlambda = (lon2 - lon1_l);
19410  //bearing---
19411  //make sure there are not NAN values ----------
19412  az = atan2(sin(dlambda) * cos(lat2), cos(lat1_l) * sin(lat2) - sin(lat1_l) * cos(lat2) * cos(dlambda));
19413 
19414  // cout<<lat2<<"..."<<lat1_l<<".."<<dlambda<<az*180/M_PI<<endl;
19415  if (az > M_PI || az < -M_PI) {
19416  cout << "problem with BEARING in across-gridline method...az<-180 or >180...." << "az in degrees.." << az * 180 / M_PI << endl;
19417  exit(1);
19418  }
19419  if (isnan(az) < 1) {
19420  // cout<<"az.."<<az<<"azcount"<<azc<<endl;
19421  az_r = (az + M_PI / 2.);
19422  az_east[i] = az_r * 180. / M_PI;
19423  if (az_east[i] < 0.0001 && az_east[i]>0) az_east[i] = 0.0;
19424  sum = az_east[i];
19425  tot += sum;
19426  azc++;
19427  }
19428  else {
19429  az_east[i] = NAN;
19430  }
19431  }
19432  float mean_az_east = tot / (azc);
19433 
19434  cout << "recomputed mean_az_east..(based on second interp rather than first interp)" << mean_az_east << "num_gridlines.." << num_gridlines-2 << endl;
19435 
19436 
19437  for (int j = 0;j < num_gridlines - 2;j++) {
19438  az_east[j] = mean_az_east;
19439  }
19440 
19441  l1cfile->mean_az_east = mean_az_east;
19442 
19443  for (int i = 0;i < num_gridlines - 2;i++) {
19444 
19445  if (i % 1 == 0) {
19446  //assign central positions---
19447  lat1_l = lati2[i] * M_PI / 180.;
19448  lat1_r = lati2[i] * M_PI / 180.;
19449  lat2 = lati2[i + 1] * M_PI / 180.;
19450  lon1_l = loni2[i] * M_PI / 180.;
19451  lon1_r = loni2[i] * M_PI / 180.;
19452  lon2 = loni2[i + 1] * M_PI / 180.;
19453 
19454  dlambda = (lon2 - lon1_l);
19455 
19456 
19457  gres = (l1cinput->gres) * 1000; //grid resolution in meters
19458 
19459  //bearing---
19460  //this is Harverside--law f cosines is more accurate---
19461  az = atan2(sin(dlambda) * cos(lat2), cos(lat1_l) * sin(lat2) - sin(lat1_l) * cos(lat2) * cos(dlambda));
19462  if (az > M_PI || az < -M_PI) {
19463  cout << "problem with BEARING in across-gridline method...az<-180 or >180...." << "az in degrees.." << az * 180 / M_PI << endl;
19464  exit(1);
19465  }
19466 
19467  //compute RIGHT across-gridline pixels---
19468  for (int k = 0;k < (nbinx / 2);k++) {
19469  h = (l1cinput->gres);//distance between along positions in km, must be 5.2 k m for L1C
19470  if (k == 0) h /= 2;//if nadpix
19471  htot += h;
19472 
19473  //right pixels---
19474  az_r = mean_az_east * degrad;
19475 
19476  //left pixels---
19477  az_l = az_r - M_PI;
19478 
19479  //bearing should be always positive (clockwise) before pixel location calculation based on Harverside---
19480  if (az_r < 0.) {
19481  az_r = 360 + az_r * 180 / M_PI;
19482  az_r = az_r * M_PI / 180;
19483  }
19484 
19485  if (az_l < 0.) {
19486  az_l = 360 + az_l * 180 / M_PI;
19487  az_l = az_l * M_PI / 180;
19488  }
19489 
19490  geod.Direct(lat1_r * 180 / M_PI, lon1_r * 180 / M_PI, az_r * 180 / M_PI, gres, latih, lonih);
19491  geod.Inverse(lat1_r * 180 / M_PI, lon1_r * 180 / M_PI, latih, lonih, res1);
19492 
19493  /* if(i==0){
19494  cout<<"gd#..."<<i+1<<"az_r.."<<az_r* 180 / M_PI<<"az_l.."<<az_l* 180 / M_PI<<endl;
19495  cout<<"lat1_r.."<<lat1_r<<"lon1_r.."<<lon1_r<<"latih.."<<latih<<"lonih.."<<lonih<<"res1.."<<res1<<endl;
19496  }
19497  */
19498 
19499  fnan1 = isnan(latih);
19500  fnan2 = isnan(lonih);
19501  lati_r[k] = latih;
19502  loni_r[k] = lonih;
19503  // cout<<"righside.."<<latih<<"..."<<lonih<<"res1"<<res1<<endl;
19504 
19505  lat1_r = lati_r[k] * M_PI / 180;
19506  lon1_r = loni_r[k] * M_PI / 180;
19507 
19508  geod.Direct(lat1_l * 180 / M_PI, lon1_l * 180 / M_PI, az_l * 180 / M_PI, gres, latih2, lonih2);
19509  geod.Inverse(lat1_l * 180 / M_PI, lon1_l * 180 / M_PI, latih2, lonih2, res2);
19510  fnan3 = isnan(latih2);
19511  fnan4 = isnan(lonih2);
19512  lati_l[k] = latih2;
19513  loni_l[k] = lonih2;
19514  // cout<<"leftside.."<<latih2<<"..."<<lonih2<<"res2"<<res2<<endl;
19515 
19516  lat1_l = lati_l[k] * M_PI / 180;
19517  lon1_l = loni_l[k] * M_PI / 180;
19518 
19519  //right swath side------------- //we tolerate +- 6 m error
19520  if (lati2[i]<=80 && (fnan1 > 0 || fnan2 > 0 || res1 > (gres + 6) || res1 < (gres - 6) || lati2[i + 1] < lati2[i] || lati2[i] < latfirst)) { //nan values
19521  badline++;
19522  if (badline == 1) {
19523  latfirst = lati2[i];
19524  }
19525 
19526  // cout << "bad interpolation - missing orbital data at near nadir grid cell..NAN right side of line.." << i + 1 << "corresponding to lat..."<<latfirst <<"lati2[i].."<<lati2[i]<<endl;
19527  // cout<<"gd.."<<gd+1<<"XBIN.."<<k+1<<"lati_l[k]"<<lati_l[k]<<"loni_l[k]"<<loni_l[k]<<"lati_r[k]"<<lati_r[k]<<"loni_r[k]"<<loni_r[k]<<endl;
19528 
19529  lati2[i] = NAN;
19530  loni2[i] = NAN;
19531 
19532  for (int k = 0;k < (nbinx / 2);k++) {
19533  lat_gd[gd][k + nbinx / 2] = NAN;
19534  lon_gd[gd][k + nbinx / 2] = NAN;
19535  }
19536  // cout<<"nan value.right.."<<endl;
19537  }
19538  else {
19539  lat_gd[gd][k + nbinx / 2] = latih;
19540  lon_gd[gd][k + nbinx / 2] = lonih;
19541  }
19542 
19543  //left side
19544  if (lati2[i]<=80 && (fnan3 > 0 || fnan4 > 0 || res2 > (gres + 6) || res2 < (gres - 6) || lati2[i + 1] < lati2[i] || lati2[i] < latfirst)) {
19545  // if(fnan3>0 | fnan4>0 | res2>(gres+6) | res2<(gres-6)){
19546  // cout << "bad interpolation - missing orbital data at near nadir grid cell..NAN left side of line.." << i + 1 << endl;
19547  // cout<<"gd.."<<gd+1<<"XBIN.."<<k+1<<"lati_l[k]"<<lati_l[k]<<"loni_l[k]"<<loni_l[k]<<"lati_r[k]"<<lati_r[k]<<"loni_r[k]"<<loni_r[k]<<"lati2[i].."<<lati2[i]<<endl;
19548 
19549  lati2[i] = NAN;
19550  loni2[i] = NAN;
19551  for (int k = 0;k < (nbinx / 2);k++) {
19552  lat_gd[gd][nbinx / 2 - 1 - k] = NAN;//as k increases we are farther away from nadpix or along-track position---
19553  lon_gd[gd][nbinx / 2 - 1 - k] = NAN;
19554  }
19555  // cout<<"nan value.left.."<<endl;
19556  }
19557  else {
19558  lat_gd[gd][nbinx / 2 - 1 - k] = latih2;//as k increases we are farther away from nadpix or along-track position---
19559  lon_gd[gd][nbinx / 2 - 1 - k] = lonih2;
19560  }
19561  fnan1=0;
19562  fnan2=0;
19563  fnan3=0;
19564  fnan4=0;
19565 
19566  }//end pixel loop
19567 
19568 
19569  htot = 0;
19570  gd++;
19571  }//end if every 100 gd
19572  }//end gridlines loop
19573  cout << "`L1C gridding successful!......................................." << endl;
19574 
19575 
19576 //---- writing results -------------------------------------------
19577 //--------------------------------------------------------------
19578 
19579  float lontemp = 0.;
19580  selday = l1cinput->selday;
19581  selmon = l1cinput->selmon;
19582  selyear = l1cinput->selyear;
19583 
19584  std::string timestr,missionstr,fname_out, pathstr, senstr, monstr, daystr, yearstr, prodstr, gdstr, swtstr, swtnum, extstr,ofilestr;
19585  pathstr = "out/";
19586  missionstr="PACE";
19587  senstr = "OCIS";
19588  monstr = std::to_string(selmon);
19589  daystr = std::to_string(selday);
19590  yearstr = std::to_string(selyear);
19591  timestr="T00:00:00Z";
19592  prodstr = "L1Cgrid";
19593  // gdstr="_gdFULL_";
19594  swtstr = "_swt";
19595  swtnum = std::to_string(swtd);
19596 
19597  extstr = ".nc";
19598  ofilestr=std::string(l1cinput->ofile);
19599 
19600  fname_out = pathstr + ofilestr+"_"+ prodstr+swtstr+swtnum+extstr;
19601 
19602  string ATT_NAME="Units", ATT_VAL="degrees",GATT_NAME1="Title",GATT_VAL1="PACE OCI Level-1C Data",GATT_NAME2="instrument",GATT_VAL2="OCI",GATT_NAME3="processing_version",GATT_VAL3="V1.0",GATT_NAME4="Conventions",GATT_VAL4="CF-1.6";
19603  string GATT_NAME5="institution",GATT_VAL5="NASA Goddard Space Flight Center, Ocean Biology Processing Group",GATT_NAME6="license",GATT_VAL6="http://science.nasa.gov/earth-science/earth-science-data/data-information-policy/";
19604  string GATT_NAME7="naming_authority",GATT_VAL7="gov.nasa.gsfc.sci.oceancolor",GATT_NAME8="keywords_vocabulary",GATT_VAL8="NASA Global Change Master Directory (GCMD) Science Keywords";
19605  string GATT_NAME9="stdname_vocabulary",GATT_VAL9="NetCDF Climate and Forecast (CF) Metadata Convention",GATT_NAME10="creator_name",GATT_VAL10="NASA/GSFC",GATT_NAME11="creator_email",GATT_VAL11="data@oceancolor.gsfc.nasa.gov";
19606  string GATT_NAME12="creator_url",GATT_VAL12="http://oceancolor.gsfc.nasa.gov",GATT_NAME13="project",GATT_VAL13="PACE Project",GATT_NAME14="publisher_name",GATT_VAL14="NASA/GSFC";
19607  string GATT_NAME15="publisher_email",GATT_VAL15="data@oceancolor.gsfc.nasa.gov",GATT_NAME16="publisher_url",GATT_VAL16="http://oceancolor.gsfc.nasa.gov",GATT_NAME17="processing_level",GATT_VAL17="L1C";
19608  string GATT_NAME18="cdm_data_type",GATT_VAL18="swath",GATT_NAME19="orbit_number",GATT_VAL19="12345",GATT_NAME20="history",GATT_VAL20="",GATT_NAME21="CDL_version_date",GATT_VAL21="2021-09-10",GATT_NAME22="product_name",GATT_VAL22=fname_out;
19609  string GATT_NAME23="startDirection",GATT_VAL23="Ascending",GATT_NAME24="endDirection",GATT_VAL24="Ascending",GATT_NAME25="time_coverage_start",GATT_VAL25=yearstr+"-"+monstr+"-"+daystr+"-"+timestr,GATT_NAME26="time_coverage_end",GATT_VAL26=yearstr+"-"+monstr+"-"+daystr+"-"+timestr,GATT_NAME27="date{_created",GATT_VAL27="2021-09-10T15:12:41Z",GATT_NAME28="sun_earth_distance",GATT_VAL28="0.990849042172323",GATT_NAME29="terrain_data_source",GATT_VAL29="",GATT_NAME30="spectral_response_function",GATT_VAL30="",GATT_NAME31="systematic_uncertainty_model",GATT_VAL31="",GATT_NAME32="nadir_bin",GATT_VAL32="12345",GATT_NAME33="bin_size_at_nadir",GATT_VAL33="2.6km2";
19610 
19611 
19612  l1cfile->gridname = fname_out.c_str();
19613  filename_lt = fname_out.c_str();
19614 
19615  cout<<"creating file for L1C coor..."<<filename_lt<<endl;
19616 
19617 
19618  if ((status = nc_create(filename_lt, NC_CLOBBER | NC_NETCDF4, &ncid_out)))
19619  check_err(status, __LINE__, __FILE__);
19620  //define dims
19621  // Define the dimensions,vars and attributes at the root level
19622  NY = num_gridlines-2;
19623  NX = nbinx;
19624  NVIEWS= 2;//for OCI
19625  NBANDS=249;
19626 // lt_out = allocate2d_float(NY, NX);
19627  //DEF DIMENSIONS
19628  if ((status = nc_def_dim(ncid_out, "bins_across_track", NX, &x_dimid)))
19629  check_err(status, __LINE__, __FILE__);
19630  if ((status = nc_def_dim(ncid_out, "bins_along_track", NY, &y_dimid)))
19631  check_err(status, __LINE__, __FILE__);
19632  //dims for output var
19633  dimids[0] = y_dimid;
19634  dimids[1] = x_dimid;
19635  NDIMS=2;
19636  if ((status = nc_def_dim(ncid_out, "number_of_views", NVIEWS, &v_dimid)))
19637  check_err(status, __LINE__, __FILE__);
19638  if ((status = nc_def_dim(ncid_out, "intensity_bands_per_view", NBANDS, &b_dimid)))
19639  check_err(status, __LINE__, __FILE__);
19640  //define attributes
19641 // if (nc_put_att_text(ncid_out, varid1, ATT_NAME.c_str(), strlen(ATT_VAL.c_str()), ATT_VAL.c_str()))
19642 // check_err(status, __LINE__, __FILE__);
19643 // if (nc_put_att_text(ncid_out, varid2, ATT_NAME.c_str(), strlen(ATT_VAL.c_str()), ATT_VAL.c_str()))
19644 // check_err(status, __LINE__, __FILE__);
19645  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME1.c_str(), strlen(GATT_VAL1.c_str()),
19646  GATT_VAL1.c_str()))
19647  check_err(status, __LINE__, __FILE__);
19648  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME2.c_str(), strlen(GATT_VAL2.c_str()),
19649  GATT_VAL2.c_str()))
19650  check_err(status, __LINE__, __FILE__);
19651  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME3.c_str(), strlen(GATT_VAL3.c_str()),
19652  GATT_VAL3.c_str()))
19653  check_err(status, __LINE__, __FILE__);
19654  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME4.c_str(), strlen(GATT_VAL4.c_str()),
19655  GATT_VAL4.c_str()))
19656  check_err(status, __LINE__, __FILE__);
19657  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME5.c_str(), strlen(GATT_VAL5.c_str()),
19658  GATT_VAL5.c_str()))
19659  check_err(status, __LINE__, __FILE__);
19660  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME6.c_str(), strlen(GATT_VAL6.c_str()),
19661  GATT_VAL6.c_str()))
19662  check_err(status, __LINE__, __FILE__);
19663  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME7.c_str(), strlen(GATT_VAL7.c_str()),
19664  GATT_VAL7.c_str()))
19665  check_err(status, __LINE__, __FILE__);
19666  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME8.c_str(), strlen(GATT_VAL8.c_str()),
19667  GATT_VAL8.c_str()))
19668  check_err(status, __LINE__, __FILE__);
19669  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME9.c_str(), strlen(GATT_VAL9.c_str()),
19670  GATT_VAL9.c_str()))
19671  check_err(status, __LINE__, __FILE__);
19672  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME10.c_str(), strlen(GATT_VAL10.c_str()),
19673  GATT_VAL10.c_str()))
19674  check_err(status, __LINE__, __FILE__);
19675  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME11.c_str(), strlen(GATT_VAL11.c_str()),
19676  GATT_VAL11.c_str()))
19677  check_err(status, __LINE__, __FILE__);
19678  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME12.c_str(), strlen(GATT_VAL12.c_str()),
19679  GATT_VAL12.c_str()))
19680  check_err(status, __LINE__, __FILE__);
19681  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME13.c_str(), strlen(GATT_VAL13.c_str()),
19682  GATT_VAL13.c_str()))
19683  check_err(status, __LINE__, __FILE__);
19684  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME14.c_str(), strlen(GATT_VAL14.c_str()),
19685  GATT_VAL14.c_str()))
19686  check_err(status, __LINE__, __FILE__);
19687  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME15.c_str(), strlen(GATT_VAL15.c_str()),
19688  GATT_VAL15.c_str()))
19689  check_err(status, __LINE__, __FILE__);
19690  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME16.c_str(), strlen(GATT_VAL16.c_str()),
19691  GATT_VAL16.c_str()))
19692  check_err(status, __LINE__, __FILE__);
19693  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME17.c_str(), strlen(GATT_VAL17.c_str()),
19694  GATT_VAL17.c_str()))
19695  check_err(status, __LINE__, __FILE__);
19696  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME18.c_str(), strlen(GATT_VAL18.c_str()),
19697  GATT_VAL18.c_str()))
19698  check_err(status, __LINE__, __FILE__);
19699  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME19.c_str(), strlen(GATT_VAL19.c_str()),
19700  GATT_VAL19.c_str()))
19701  check_err(status, __LINE__, __FILE__);
19702  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME20.c_str(), strlen(GATT_VAL20.c_str()),
19703  GATT_VAL20.c_str()))
19704  check_err(status, __LINE__, __FILE__);
19705  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME21.c_str(), strlen(GATT_VAL21.c_str()),
19706  GATT_VAL21.c_str()))
19707  check_err(status, __LINE__, __FILE__);
19708  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME22.c_str(), strlen(GATT_VAL22.c_str()),
19709  GATT_VAL22.c_str()))
19710  check_err(status, __LINE__, __FILE__);
19711  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME23.c_str(), strlen(GATT_VAL23.c_str()),
19712  GATT_VAL23.c_str()))
19713  check_err(status, __LINE__, __FILE__);
19714  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME24.c_str(), strlen(GATT_VAL24.c_str()),
19715  GATT_VAL24.c_str()))
19716  check_err(status, __LINE__, __FILE__);
19717  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME25.c_str(), strlen(GATT_VAL25.c_str()),
19718  GATT_VAL25.c_str()))
19719  check_err(status, __LINE__, __FILE__);
19720  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME26.c_str(), strlen(GATT_VAL26.c_str()),
19721  GATT_VAL26.c_str()))
19722  check_err(status, __LINE__, __FILE__);
19723  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME27.c_str(), strlen(GATT_VAL27.c_str()),
19724  GATT_VAL27.c_str()))
19725  check_err(status, __LINE__, __FILE__);
19726  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME28.c_str(), strlen(GATT_VAL28.c_str()),
19727  GATT_VAL28.c_str()))
19728  check_err(status, __LINE__, __FILE__);
19729  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME29.c_str(), strlen(GATT_VAL29.c_str()),
19730  GATT_VAL29.c_str()))
19731  check_err(status, __LINE__, __FILE__);
19732  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME30.c_str(), strlen(GATT_VAL30.c_str()),
19733  GATT_VAL30.c_str()))
19734  check_err(status, __LINE__, __FILE__);
19735  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME31.c_str(), strlen(GATT_VAL31.c_str()),
19736  GATT_VAL31.c_str()))
19737  check_err(status, __LINE__, __FILE__);
19738  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME32.c_str(), strlen(GATT_VAL32.c_str()),
19739  GATT_VAL32.c_str()))
19740  check_err(status, __LINE__, __FILE__);
19741  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME33.c_str(), strlen(GATT_VAL33.c_str()),
19742  GATT_VAL33.c_str()))
19743  check_err(status, __LINE__, __FILE__);
19744 
19745  //define groups check_err(status, __LINE__, __FILE__);
19746  if ((status = nc_def_grp(ncid_out, "geolocation_data", &grp_coor))) //netcdf-4
19747  check_err(status, __LINE__, __FILE__);
19748  //def var
19749  if ((status = nc_def_var(grp_coor, "latitude", NC_FLOAT, NDIMS,
19750  dimids, &varid1)))
19751  check_err(status, __LINE__, __FILE__);
19752  if ((status = nc_def_var(grp_coor, "longitude", NC_FLOAT, NDIMS,
19753  dimids, &varid2)))
19754  check_err(status, __LINE__, __FILE__);
19755  //leave define mode-----------------------
19756  if ((status = nc_enddef(grp_coor))) //done def vars etc
19757  check_err(status, __LINE__, __FILE__);
19758 
19759 
19760  //writing the whole thing
19761  if ((status = nc_put_var_float(grp_coor, varid1, &lat_gd[0][0])))
19762  check_err(status, __LINE__, __FILE__);
19763 
19764  if ((status = nc_put_var_float(grp_coor, varid2, &lon_gd[0][0])))
19765  check_err(status, __LINE__, __FILE__);
19766 
19767 
19768 
19769 //define attributes of vars in groups
19770 //UNITS in degrees ----
19771  if (nc_put_att_text(grp_coor, varid1, ATT_NAME.c_str(), strlen(ATT_VAL.c_str()), ATT_VAL.c_str()))
19772  check_err(status, __LINE__, __FILE__);
19773  check_err(status, __LINE__, __FILE__);
19774  if (nc_put_att_text(grp_coor, varid2, ATT_NAME.c_str(), strlen(ATT_VAL.c_str()), ATT_VAL.c_str()))
19775  check_err(status, __LINE__, __FILE__);
19776 
19777 
19778 //close file
19779  if ((status = nc_close(ncid_out)))
19780  check_err(status, __LINE__, __FILE__);
19781 
19782 // delete [] (lt_out);
19783 
19784 //CASE ONLY LON POS VALUES***************************************************************************
19785 
19786  //Only positive longitude 0-360 degrees for visualization ****************************************************************
19787  //lat lon grid for visualization--
19788  prodstr = "L1Cgrid_lonpos";
19789  // gdstr="_gdFULL_";
19790  //recompute number of gridlines based on lat limits -80 to 80 degrees
19791  //asc orbit goes from negative to positive latitude....
19792 
19793  NY = num_gridlines-2;
19794  NX = nbinx;
19795 
19796  cout<<"NY before geographic constraint."<<NY<<"NY1.initial lat index ."<<NY1<<"NY2..final lat index."<<NY2<<"NX.."<<NX<<endl;
19797 
19798  for (int i = 0; i < NY; i++) {
19799  for (int j = 0; j < NX; j++) {
19800  if (lat_gd[i][j] >= -80.) c1++;
19801  if (c1 == nbinx) {
19802  NY1 = i;
19803  }
19804  }
19805  if (NY1 >= 0) break;
19806  c1 = 1;
19807  }
19808 
19809  for (int i = 0;i < NY; i++) {
19810  for (int j = 0; j < NX; j++) {
19811  if (lat_gd[i][j] >= 80.) {
19812  NY2 = i - 1;
19813  }
19814  }
19815  if (NY2 >= 0) break;
19816  }
19817 
19818  l1cfile->NY1 = NY1;
19819  l1cfile->NY2 = NY2;
19820 
19821  NY = NY2 - NY1 + 1;
19822  cout<<"NY.after geographic constraint."<<NY<<"NY1.initial lat index ."<<NY1<<"NY2..final lat index."<<NY2<<"NX.."<<NX<<endl;
19823 
19824  lat_out = allocate2d_float(NY, NX);
19825  lon_out = allocate2d_float(NY, NX);
19826 
19827  int c=0;
19828  for (int i = NY1; i < NY2 + 1; i++) {
19829  for (int j = 0; j < NX; j++) {
19830  if(lon_gd[i][j]<0) lon_out[c][j]=lon_gd[i][j]+360;
19831  else lon_out[c][j]=lon_gd[i][j];
19832  lat_out[c][j] = lat_gd[i][j];
19833  }
19834  // cout<<"gd#..."<<c+1<<endl;
19835  c++;
19836 
19837  }
19838 
19839  extstr = ".nc";
19840 // fname_out = pathstr + missionstr + "_" + senstr + "." + yearstr + monstr + daystr + timestr + prodstr+extstr;
19841  fname_out = pathstr + ofilestr+"_"+ prodstr+swtstr+swtnum+extstr;
19842  cout<<"path..."<<pathstr<<"ofile.."<<ofilestr<<"prod.."<<prodstr<<endl;
19843 
19844  l1cfile->gridname = fname_out.c_str();
19845  filename_lt = fname_out.c_str();
19846  cout<<"creating file for L1C coor.with only POS LONGITUDE.."<<filename_lt<<endl;
19847 // if ((status = nc_create(filename_lt, NC_CLOBBER, &ncid_out)))
19848  if ((status = nc_create(filename_lt, NC_CLOBBER | NC_NETCDF4, &ncid_out)))
19849  check_err(status, __LINE__, __FILE__);
19850  //define dims
19851  // Define the dimensions,vars and attributes at the root level
19852 
19853 
19854  //DEF DIMENSIONS
19855  if ((status = nc_def_dim(ncid_out, "bins_across_track", NX, &x_dimid)))
19856  check_err(status, __LINE__, __FILE__);
19857  if ((status = nc_def_dim(ncid_out, "bins_along_track", NY, &y_dimid)))
19858  check_err(status, __LINE__, __FILE__);
19859  //dims for output var
19860  dimids[0] = y_dimid;
19861  dimids[1] = x_dimid;
19862  NDIMS=2;
19863  if ((status = nc_def_dim(ncid_out, "number_of_views", NVIEWS, &v_dimid)))
19864  check_err(status, __LINE__, __FILE__);
19865  if ((status = nc_def_dim(ncid_out, "intensity_bands_per_view", NBANDS, &b_dimid)))
19866  check_err(status, __LINE__, __FILE__);
19867 
19868  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME1.c_str(), strlen(GATT_VAL1.c_str()),
19869  GATT_VAL1.c_str()))
19870  check_err(status, __LINE__, __FILE__);
19871  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME2.c_str(), strlen(GATT_VAL2.c_str()),
19872  GATT_VAL2.c_str()))
19873  check_err(status, __LINE__, __FILE__);
19874  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME3.c_str(), strlen(GATT_VAL3.c_str()),
19875  GATT_VAL3.c_str()))
19876  check_err(status, __LINE__, __FILE__);
19877  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME4.c_str(), strlen(GATT_VAL4.c_str()),
19878  GATT_VAL4.c_str()))
19879  check_err(status, __LINE__, __FILE__);
19880  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME5.c_str(), strlen(GATT_VAL5.c_str()),
19881  GATT_VAL5.c_str()))
19882  check_err(status, __LINE__, __FILE__);
19883  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME6.c_str(), strlen(GATT_VAL6.c_str()),
19884  GATT_VAL6.c_str()))
19885  check_err(status, __LINE__, __FILE__);
19886  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME7.c_str(), strlen(GATT_VAL7.c_str()),
19887  GATT_VAL7.c_str()))
19888  check_err(status, __LINE__, __FILE__);
19889  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME8.c_str(), strlen(GATT_VAL8.c_str()),
19890  GATT_VAL8.c_str()))
19891  check_err(status, __LINE__, __FILE__);
19892  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME9.c_str(), strlen(GATT_VAL9.c_str()),
19893  GATT_VAL9.c_str()))
19894  check_err(status, __LINE__, __FILE__);
19895  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME10.c_str(), strlen(GATT_VAL10.c_str()),
19896  GATT_VAL10.c_str()))
19897  check_err(status, __LINE__, __FILE__);
19898  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME11.c_str(), strlen(GATT_VAL11.c_str()),
19899  GATT_VAL11.c_str()))
19900  check_err(status, __LINE__, __FILE__);
19901  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME12.c_str(), strlen(GATT_VAL12.c_str()),
19902  GATT_VAL12.c_str()))
19903  check_err(status, __LINE__, __FILE__);
19904  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME13.c_str(), strlen(GATT_VAL13.c_str()),
19905  GATT_VAL13.c_str()))
19906  check_err(status, __LINE__, __FILE__);
19907  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME14.c_str(), strlen(GATT_VAL14.c_str()),
19908  GATT_VAL14.c_str()))
19909  check_err(status, __LINE__, __FILE__);
19910  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME15.c_str(), strlen(GATT_VAL15.c_str()),
19911  GATT_VAL15.c_str()))
19912  check_err(status, __LINE__, __FILE__);
19913  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME16.c_str(), strlen(GATT_VAL16.c_str()),
19914  GATT_VAL16.c_str()))
19915  check_err(status, __LINE__, __FILE__);
19916  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME17.c_str(), strlen(GATT_VAL17.c_str()),
19917  GATT_VAL17.c_str()))
19918  check_err(status, __LINE__, __FILE__);
19919  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME18.c_str(), strlen(GATT_VAL18.c_str()),
19920  GATT_VAL18.c_str()))
19921  check_err(status, __LINE__, __FILE__);
19922  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME19.c_str(), strlen(GATT_VAL19.c_str()),
19923  GATT_VAL19.c_str()))
19924  check_err(status, __LINE__, __FILE__);
19925  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME20.c_str(), strlen(GATT_VAL20.c_str()),
19926  GATT_VAL20.c_str()))
19927  check_err(status, __LINE__, __FILE__);
19928  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME21.c_str(), strlen(GATT_VAL21.c_str()),
19929  GATT_VAL21.c_str()))
19930  check_err(status, __LINE__, __FILE__);
19931  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME22.c_str(), strlen(GATT_VAL22.c_str()),
19932  GATT_VAL22.c_str()))
19933  check_err(status, __LINE__, __FILE__);
19934  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME23.c_str(), strlen(GATT_VAL23.c_str()),
19935  GATT_VAL23.c_str()))
19936  check_err(status, __LINE__, __FILE__);
19937  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME24.c_str(), strlen(GATT_VAL24.c_str()),
19938  GATT_VAL24.c_str()))
19939  check_err(status, __LINE__, __FILE__);
19940  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME25.c_str(), strlen(GATT_VAL25.c_str()),
19941  GATT_VAL25.c_str()))
19942  check_err(status, __LINE__, __FILE__);
19943  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME26.c_str(), strlen(GATT_VAL26.c_str()),
19944  GATT_VAL26.c_str()))
19945  check_err(status, __LINE__, __FILE__);
19946  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME27.c_str(), strlen(GATT_VAL27.c_str()),
19947  GATT_VAL27.c_str()))
19948  check_err(status, __LINE__, __FILE__);
19949  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME28.c_str(), strlen(GATT_VAL28.c_str()),
19950  GATT_VAL28.c_str()))
19951  check_err(status, __LINE__, __FILE__);
19952  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME29.c_str(), strlen(GATT_VAL29.c_str()),
19953  GATT_VAL29.c_str()))
19954  check_err(status, __LINE__, __FILE__);
19955  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME30.c_str(), strlen(GATT_VAL30.c_str()),
19956  GATT_VAL30.c_str()))
19957  check_err(status, __LINE__, __FILE__);
19958  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME31.c_str(), strlen(GATT_VAL31.c_str()),
19959  GATT_VAL31.c_str()))
19960  check_err(status, __LINE__, __FILE__);
19961  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME32.c_str(), strlen(GATT_VAL32.c_str()),
19962  GATT_VAL32.c_str()))
19963  check_err(status, __LINE__, __FILE__);
19964  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME33.c_str(), strlen(GATT_VAL33.c_str()),
19965  GATT_VAL33.c_str()))
19966  check_err(status, __LINE__, __FILE__);
19967 
19968  //define groups check_err(status, __LINE__, __FILE__);
19969  if ((status = nc_def_grp(ncid_out, "geolocation_data", &grp_coor))) //netcdf-4
19970  check_err(status, __LINE__, __FILE__);
19971  //def var
19972  if ((status = nc_def_var(grp_coor, "latitude", NC_FLOAT, NDIMS,
19973  dimids, &varid1)))
19974  check_err(status, __LINE__, __FILE__);
19975  if ((status = nc_def_var(grp_coor, "longitude", NC_FLOAT, NDIMS,
19976  dimids, &varid2)))
19977  check_err(status, __LINE__, __FILE__);
19978 
19979  //leave define mode-----------------------
19980  if ((status = nc_enddef(grp_coor))) //done def vars etc
19981  check_err(status, __LINE__, __FILE__);
19982 
19983  //writing the whole thing
19984  if ((status = nc_put_var_float(grp_coor, varid1, &lat_out[0][0])))
19985  check_err(status, __LINE__, __FILE__);
19986 
19987  if ((status = nc_put_var_float(grp_coor, varid2, &lon_out[0][0])))
19988  check_err(status, __LINE__, __FILE__);
19989 
19990 //define attributes of vars in groups
19991  if (nc_put_att_text(grp_coor, varid1, ATT_NAME.c_str(), strlen(ATT_VAL.c_str()), ATT_VAL.c_str()))
19992  check_err(status, __LINE__, __FILE__);
19993  if (nc_put_att_text(grp_coor, varid2, ATT_NAME.c_str(), strlen(ATT_VAL.c_str()), ATT_VAL.c_str()))
19994  check_err(status, __LINE__, __FILE__);
19995 
19996 
19997  if ((status = nc_close(ncid_out)))
19998  check_err(status, __LINE__, __FILE__);
19999 
20000 
20001  delete [] (lat_out);
20002  delete [] (lon_out);
20003  lat_out=nullptr;
20004  lon_out=nullptr;
20005 
20006 
20007 
20008 //CASE INVERTED ALONG/ACROSS INDEXES ***************************************************************************
20009  prodstr = "L1Cgrid_inverted";
20010 
20011 
20012  lat_out = allocate2d_float(NY, NX);
20013  lon_out = allocate2d_float(NY, NX);
20014 
20015  c = 0;
20016  for (int i = NY1; i < NY2 + 1; i++) {
20017  for (int j = 0; j < NX; j++) {
20018  lat_out[NY - 1 - c][NX - 1 - j] = lat_gd[i][j];
20019  lon_out[NY - 1 - c][j] = lon_gd[i][j];
20020  }
20021  c++;
20022  }
20023 
20024  extstr = ".nc";
20025 // fname_out = pathstr + missionstr + "_" + senstr + "." + yearstr + monstr + daystr + timestr + prodstr+extstr;
20026  fname_out = pathstr + ofilestr+"_"+ prodstr+swtstr+swtnum+extstr;
20027  l1cfile->gridname = fname_out.c_str();
20028  filename_lt = fname_out.c_str();
20029  cout<<"creating file for L1C coor.with x/y inverted indexes.."<<filename_lt<<endl;
20030 // if ((status = nc_create(filename_lt, NC_CLOBBER, &ncid_out)))
20031  if ((status = nc_create(filename_lt, NC_CLOBBER | NC_NETCDF4, &ncid_out)))
20032  check_err(status, __LINE__, __FILE__);
20033  //define dims
20034  // Define the dimensions,vars and attributes at the root level
20035 
20036 
20037  //DEF DIMENSIONS
20038  if ((status = nc_def_dim(ncid_out, "bins_across_track", NX, &x_dimid)))
20039  check_err(status, __LINE__, __FILE__);
20040  if ((status = nc_def_dim(ncid_out, "bins_along_track", NY, &y_dimid)))
20041  check_err(status, __LINE__, __FILE__);
20042  //dims for output var
20043  dimids[0] = y_dimid;
20044  dimids[1] = x_dimid;
20045  NDIMS=2;
20046  if ((status = nc_def_dim(ncid_out, "number_of_views", NVIEWS, &v_dimid)))
20047  check_err(status, __LINE__, __FILE__);
20048  if ((status = nc_def_dim(ncid_out, "intensity_bands_per_view", NBANDS, &b_dimid)))
20049  check_err(status, __LINE__, __FILE__);
20050 /*
20051 //def variables at the root level!
20052  if ((status = nc_def_var(ncid_out, "latitude", NC_FLOAT, NDIMS,
20053  dimids, &varid1)))
20054  check_err(status, __LINE__, __FILE__);
20055  if ((status = nc_def_var(ncid_out, "longitude", NC_FLOAT, NDIMS,
20056  dimids, &varid2)))
20057  check_err(status, __LINE__, __FILE__);
20058 
20059  if ((status = nc_enddef(ncid_out))) //done def vars etc
20060  check_err(status, __LINE__, __FILE__);
20061  if ((status = nc_put_var_float(ncid_out, varid1, &lat_out[0][0])))
20062  check_err(status, __LINE__, __FILE__);
20063  if ((status = nc_put_var_float(ncid_out, varid2, &lon_out[0][0])))
20064  check_err(status, __LINE__, __FILE__);
20065 
20066 //define attributes
20067  if (nc_put_att_text(ncid_out, varid1, ATT_NAME.c_str(), strlen(ATT_VAL.c_str()), ATT_VAL.c_str()))
20068  check_err(status, __LINE__, __FILE__);
20069  if (nc_put_att_text(ncid_out, varid2, ATT_NAME.c_str(), strlen(ATT_VAL.c_str()), ATT_VAL.c_str()))
20070  check_err(status, __LINE__, __FILE__);
20071 */
20072 
20073  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME1.c_str(), strlen(GATT_VAL1.c_str()),
20074  GATT_VAL1.c_str()))
20075  check_err(status, __LINE__, __FILE__);
20076  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME2.c_str(), strlen(GATT_VAL2.c_str()),
20077  GATT_VAL2.c_str()))
20078  check_err(status, __LINE__, __FILE__);
20079  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME3.c_str(), strlen(GATT_VAL3.c_str()),
20080  GATT_VAL3.c_str()))
20081  check_err(status, __LINE__, __FILE__);
20082  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME4.c_str(), strlen(GATT_VAL4.c_str()),
20083  GATT_VAL4.c_str()))
20084  check_err(status, __LINE__, __FILE__);
20085  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME5.c_str(), strlen(GATT_VAL5.c_str()),
20086  GATT_VAL5.c_str()))
20087  check_err(status, __LINE__, __FILE__);
20088  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME6.c_str(), strlen(GATT_VAL6.c_str()),
20089  GATT_VAL6.c_str()))
20090  check_err(status, __LINE__, __FILE__);
20091  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME7.c_str(), strlen(GATT_VAL7.c_str()),
20092  GATT_VAL7.c_str()))
20093  check_err(status, __LINE__, __FILE__);
20094  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME8.c_str(), strlen(GATT_VAL8.c_str()),
20095  GATT_VAL8.c_str()))
20096  check_err(status, __LINE__, __FILE__);
20097  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME9.c_str(), strlen(GATT_VAL9.c_str()),
20098  GATT_VAL9.c_str()))
20099  check_err(status, __LINE__, __FILE__);
20100  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME10.c_str(), strlen(GATT_VAL10.c_str()),
20101  GATT_VAL10.c_str()))
20102  check_err(status, __LINE__, __FILE__);
20103  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME11.c_str(), strlen(GATT_VAL11.c_str()),
20104  GATT_VAL11.c_str()))
20105  check_err(status, __LINE__, __FILE__);
20106  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME12.c_str(), strlen(GATT_VAL12.c_str()),
20107  GATT_VAL12.c_str()))
20108  check_err(status, __LINE__, __FILE__);
20109  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME13.c_str(), strlen(GATT_VAL13.c_str()),
20110  GATT_VAL13.c_str()))
20111  check_err(status, __LINE__, __FILE__);
20112  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME14.c_str(), strlen(GATT_VAL14.c_str()),
20113  GATT_VAL14.c_str()))
20114  check_err(status, __LINE__, __FILE__);
20115  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME15.c_str(), strlen(GATT_VAL15.c_str()),
20116  GATT_VAL15.c_str()))
20117  check_err(status, __LINE__, __FILE__);
20118  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME16.c_str(), strlen(GATT_VAL16.c_str()),
20119  GATT_VAL16.c_str()))
20120  check_err(status, __LINE__, __FILE__);
20121  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME17.c_str(), strlen(GATT_VAL17.c_str()),
20122  GATT_VAL17.c_str()))
20123  check_err(status, __LINE__, __FILE__);
20124  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME18.c_str(), strlen(GATT_VAL18.c_str()),
20125  GATT_VAL18.c_str()))
20126  check_err(status, __LINE__, __FILE__);
20127  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME19.c_str(), strlen(GATT_VAL19.c_str()),
20128  GATT_VAL19.c_str()))
20129  check_err(status, __LINE__, __FILE__);
20130  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME20.c_str(), strlen(GATT_VAL20.c_str()),
20131  GATT_VAL20.c_str()))
20132  check_err(status, __LINE__, __FILE__);
20133  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME21.c_str(), strlen(GATT_VAL21.c_str()),
20134  GATT_VAL21.c_str()))
20135  check_err(status, __LINE__, __FILE__);
20136  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME22.c_str(), strlen(GATT_VAL22.c_str()),
20137  GATT_VAL22.c_str()))
20138  check_err(status, __LINE__, __FILE__);
20139  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME23.c_str(), strlen(GATT_VAL23.c_str()),
20140  GATT_VAL23.c_str()))
20141  check_err(status, __LINE__, __FILE__);
20142  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME24.c_str(), strlen(GATT_VAL24.c_str()),
20143  GATT_VAL24.c_str()))
20144  check_err(status, __LINE__, __FILE__);
20145  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME25.c_str(), strlen(GATT_VAL25.c_str()),
20146  GATT_VAL25.c_str()))
20147  check_err(status, __LINE__, __FILE__);
20148  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME26.c_str(), strlen(GATT_VAL26.c_str()),
20149  GATT_VAL26.c_str()))
20150  check_err(status, __LINE__, __FILE__);
20151  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME27.c_str(), strlen(GATT_VAL27.c_str()),
20152  GATT_VAL27.c_str()))
20153  check_err(status, __LINE__, __FILE__);
20154  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME28.c_str(), strlen(GATT_VAL28.c_str()),
20155  GATT_VAL28.c_str()))
20156  check_err(status, __LINE__, __FILE__);
20157  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME29.c_str(), strlen(GATT_VAL29.c_str()),
20158  GATT_VAL29.c_str()))
20159  check_err(status, __LINE__, __FILE__);
20160  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME30.c_str(), strlen(GATT_VAL30.c_str()),
20161  GATT_VAL30.c_str()))
20162  check_err(status, __LINE__, __FILE__);
20163  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME31.c_str(), strlen(GATT_VAL31.c_str()),
20164  GATT_VAL31.c_str()))
20165  check_err(status, __LINE__, __FILE__);
20166  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME32.c_str(), strlen(GATT_VAL32.c_str()),
20167  GATT_VAL32.c_str()))
20168  check_err(status, __LINE__, __FILE__);
20169  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME33.c_str(), strlen(GATT_VAL33.c_str()),
20170  GATT_VAL33.c_str()))
20171  check_err(status, __LINE__, __FILE__);
20172 
20173  //define groups check_err(status, __LINE__, __FILE__);
20174  if ((status = nc_def_grp(ncid_out, "geolocation_data", &grp_coor))) //netcdf-4
20175  check_err(status, __LINE__, __FILE__);
20176 /*
20177 //DEF DIMENSIONS
20178  if ((status = nc_def_dim(grp_coor, "x", NX, &x_dimid)))
20179  check_err(status, __LINE__, __FILE__);
20180  if ((status = nc_def_dim(grp_coor, "y", NY, &y_dimid)))
20181  check_err(status, __LINE__, __FILE__);
20182  dimids[0] = y_dimid;
20183  dimids[1] = x_dimid;
20184  NDIMS=2;
20185 */
20186  //def var
20187  if ((status = nc_def_var(grp_coor, "latitude", NC_FLOAT, NDIMS,
20188  dimids, &varid1)))
20189  check_err(status, __LINE__, __FILE__);
20190  if ((status = nc_def_var(grp_coor, "longitude", NC_FLOAT, NDIMS,
20191  dimids, &varid2)))
20192  check_err(status, __LINE__, __FILE__);
20193 
20194  //leave define mode-----------------------
20195  if ((status = nc_enddef(grp_coor))) //done def vars etc
20196  check_err(status, __LINE__, __FILE__);
20197  //writing the whole thing
20198  if ((status = nc_put_var_float(grp_coor, varid1, &lat_out[0][0])))
20199  check_err(status, __LINE__, __FILE__);
20200 
20201  if ((status = nc_put_var_float(grp_coor, varid2, &lon_out[0][0])))
20202  check_err(status, __LINE__, __FILE__);
20203 
20204 
20205 //define attributes of vars in groups
20206  if (nc_put_att_text(grp_coor, varid1, ATT_NAME.c_str(), strlen(ATT_VAL.c_str()), ATT_VAL.c_str()))
20207  check_err(status, __LINE__, __FILE__);
20208  if (nc_put_att_text(grp_coor, varid2, ATT_NAME.c_str(), strlen(ATT_VAL.c_str()), ATT_VAL.c_str()))
20209  check_err(status, __LINE__, __FILE__);
20210 
20211 
20212 
20213  if ((status = nc_close(ncid_out)))
20214  check_err(status, __LINE__, __FILE__);
20215 
20216 
20217  delete [] (lat_out);
20218  delete [] (lon_out);
20219  lat_out=nullptr;
20220  lon_out=nullptr;
20221 
20222 
20223 
20224 //******** save az_east param as nc ***************************************************************
20225 //az_east[count]
20226  prodstr="az_east";
20227  extstr = ".nc";
20228  fname_out = pathstr + ofilestr+"_"+ prodstr+extstr;
20229  filename_lt = fname_out.c_str();
20230  cout<<"creating file for az_east values in degrees as nc format.."<<filename_lt<<endl;
20231 // if ((status = nc_create(filename_lt, NC_CLOBBER, &ncid_out)))
20232  if ((status = nc_create(filename_lt, NC_CLOBBER | NC_NETCDF4, &ncid_out)))
20233  check_err(status, __LINE__, __FILE__);
20234  //define dims
20235  // Define the dimensions,vars and attributes at the root level
20236 
20237 
20238  //DEF DIMENSIONS
20239  if ((status = nc_def_dim(ncid_out, "bins_along_track", NY, &y_dimid)))
20240  check_err(status, __LINE__, __FILE__);
20241 //DEF VARIABLE
20242  if ((status = nc_def_var(ncid_out, "az_east", NC_FLOAT, 1,
20243  &y_dimid, &varid1)))
20244  check_err(status, __LINE__, __FILE__);
20245 
20246  if ((status = nc_enddef(ncid_out))) //done def vars etc
20247  check_err(status, __LINE__, __FILE__);
20248 
20249  for (int count = 0; count < num_gridlines - 2; count++) {
20250  if (az_east[count] < 0.001) az_east[count] = 0.0;}
20251  //writing the whole thing
20252  if ((status = nc_put_var_float(ncid_out, varid1, &az_east[0])))
20253  check_err(status, __LINE__, __FILE__);
20254 //close file
20255  if ((status = nc_close(ncid_out)))
20256  check_err(status, __LINE__, __FILE__);
20257 
20258 
20259 //***********************************************************************************************
20260  prodstr = "L1CgridV";
20261  extstr=".csv";
20262 
20263  fname_out = pathstr + ofilestr+"_"+ prodstr+extstr;
20264  // std::ofstream myl1c("/accounts/mamontes/images/OCIS/swt1_ALLgd_L1C500_swtd13again.csv");
20265  std::ofstream myl1cV(fname_out);
20266  for (int count = 0; count < num_gridlines - 2;count++) {
20267  // for(int count = 0; count <num_gridlines/100;count ++){
20268  for (int gp = 0; gp < nbinx; gp++) {
20269  lontemp = lon_gd[count][gp];
20270  if (lon_gd[count][gp] < -180.) lontemp = lon_gd[count][gp] + 360;
20271  if (lon_gd[count][gp] > +180.) lontemp = lon_gd[count][gp] - 360;
20272  if (lontemp < 0.) lontemp += 360.;//make better visualization, all lon values positive
20273 
20274  myl1cV << lontemp << "," << lat_gd[count][gp] << endl;
20275  }
20276  }
20277 
20278 
20279  myl1cV.close();
20280 
20281 
20282  prodstr = "lat_nadpix";
20283  fname_out = pathstr + ofilestr+"_"+ prodstr+extstr;
20284  // fname_out= "/accounts/mamontes/images/OCIS/out/"+"L1Cgrid_"+"lat_nadpix"+"_"+swtstr+".txt";
20285  // ofstream myfile1 ("/accounts/mamontes/images/OCIS/lat_nadpix_swtd13again.txt");
20286  ofstream myfile1(fname_out);
20287  if (myfile1.is_open())
20288  {
20289  myfile1 << "lat_nadpix.\n";
20290  for (int count = 0; count < num_gridlines - 2; count++) {
20291  // for(int gp = 0; gp <nbinx; gp ++){
20292  myfile1 << lati2[count] << "," << endl;
20293  }
20294  myfile1.close();
20295  }
20296  else cout << "Unable to open file";
20297  prodstr = "lon_nadpix";
20298  fname_out = pathstr + ofilestr+"_"+ prodstr+extstr;
20299  // fname_out= "/accounts/mamontes/images/OCIS/out/"+"L1Cgrid_"+"lon_nadpix"+"_"+swtstr+".txt";
20300  // ofstream myfile2 ("/accounts/mamontes/images/OCIS/lon_nadpix_swtd13again.txt");
20301  ofstream myfile2(fname_out);
20302  if (myfile2.is_open())
20303  {
20304  myfile2 << "lon_nadpix.\n";
20305  for (int count = 0; count < num_gridlines - 2; count++) {
20306  // for(int gp = 0; gp <nbinx; gp ++){
20307  myfile2 << loni2[count] << "," << endl;
20308  }
20309  myfile2.close();
20310  }
20311  else cout << "Unable to open file";
20312 
20313  prodstr = "az_east";
20314  fname_out = pathstr + ofilestr+"_"+ prodstr+extstr;
20315 
20316  l1cfile->azeast_name = fname_out.c_str();
20317 
20318 
20319 
20320  // fname_out= "/accounts/mamontes/images/OCIS/out/"+"L1Cgrid_"+"lon_nadpix"+"_"+swtstr+".txt";
20321  // ofstream myfile2 ("/accounts/mamontes/images/OCIS/lon_nadpix_swtd13again.txt");
20322  ofstream myfile3(fname_out);
20323  if (myfile3.is_open())
20324  {
20325  myfile3 << "az_east.\n";
20326  for (int count = 0; count < num_gridlines - 2; count++) {
20327  if (az_east[count] < 0.001) az_east[count] = 0.0;
20328  myfile3 << az_east[count] << "," << endl;
20329  }
20330  myfile3.close();
20331  }
20332  else cout << "Unable to open file";
20333  if(lati_l!=nullptr)
20334  delete[](lati_l);
20335  if(lati_r!=nullptr)
20336  delete[](lati_r);
20337  if(loni_l!=nullptr)
20338  delete[](loni_l);
20339  if(loni_r!=nullptr)
20340  delete[](loni_r);
20341 
20342 
20343  cout << " SUCCESS writing results full L1C grid center positions for--swath #..." << swtd << "\n";
20344 
20345  return 0;
20346  }
20347 
20348 
20349 
20350 //same as l1c but files are saved as nc
20351  int32_t L1C::across_gridlines_l1c2(int swtd, l1c_filehandle* l1cfile, L1C_input* l1cinput, int16_t* swtd_id, int16_t* file_id, int16_t* nfiles_swt, float* lati2, float* loni2, float** lat_gd, float** lon_gd, float* az_east) {
20352  int32_t num_gridlines, nbinx, NY1 = -1, NY2 = -1, c1 = 1;
20353  float lat1_l, lat1_r, lon1_l, lon1_r, lat2, lon2, dlambda, az_r, az_l, h, *lati_l, *loni_l, *lati_r, *loni_r, htot = 0.,az=0.;
20354  int ncid_out,x_dimid, y_dimid, varid1, varid2, status;
20355  int NDIMS=2;
20356  int dimids[NDIMS];
20357  int32_t NX, NY;
20358  int16_t selyear = -1, selmon = -1, selday = -1;
20359  double latih, lonih, latih2, lonih2, res1, res2;
20360  float gres;
20361  int fnan1=0, fnan2=0, fnan3=0, fnan4=0;
20362  float latfirst = -999;
20363  int badline = 0;
20364  int grp_coor;
20365  const char* filename_lt;
20366  float **lat_out=nullptr,**lon_out=nullptr;
20367 // float **lt_out=nullptr;
20368  int NVIEWS, NBANDS,v_dimid,b_dimid, asc_mode=-1;
20369 
20370  Geodesic geod(Constants::WGS84_a(), Constants::WGS84_f());
20371 
20372  //compute azimuth angle for each along-track position (nadir pixel or centered swath pixel) of the swath
20373  //azimuth angle in rads
20374  //lon+540/360-180 is a normalization factor for -180 to 180 degrees
20375  num_gridlines = l1cfile->num_gridlines;
20376  num_pixels = l1cfile->npix;
20377  nbinx = l1cfile->nbinx;
20378  lati_l = (float*)calloc(nbinx / 2 , sizeof(float));
20379  lati_r = (float*)calloc(nbinx / 2 , sizeof(float));
20380  loni_l = (float*)calloc(nbinx / 2 , sizeof(float));
20381  loni_r = (float*)calloc(nbinx / 2 , sizeof(float));
20382 
20383  //big loop
20384 
20385  int gd = 0;
20386  asc_mode=l1cfile->orb_dir;
20387 
20388 
20389  //compute mean az_east---
20390  float sum = 0., tot = 0.;
20391  size_t azc = 0;
20392 
20393 
20394 
20395  for (int i = 0;i < num_gridlines - 2;i++) {
20396 
20397  // cout<<"gd#.."<<i+1<<"lati2[i].."<<lati2[i]<<endl;
20398 
20399  //assign central positions---
20400  lat1_l = lati2[i] * M_PI / 180.;
20401  lat1_r = lati2[i] * M_PI / 180.;
20402  lat2 = lati2[i + 1] * M_PI / 180.;
20403  lon1_l = loni2[i] * M_PI / 180.;
20404  lon1_r = loni2[i] * M_PI / 180.;
20405  lon2 = loni2[i + 1] * M_PI / 180.;
20406 
20407  dlambda = (lon2 - lon1_l);
20408  //bearing---
20409  //make sure there are not NAN values ----------
20410  az = atan2(sin(dlambda) * cos(lat2), cos(lat1_l) * sin(lat2) - sin(lat1_l) * cos(lat2) * cos(dlambda));
20411 
20412  // cout<<lat2<<"..."<<lat1_l<<".."<<dlambda<<az*180/M_PI<<endl;
20413  if (az > M_PI || az < -M_PI) {
20414  cout << "problem with BEARING in across-gridline method...az<-180 or >180...." << "az in degrees.." << az * 180 / M_PI << endl;
20415  exit(1);
20416  }
20417  if (isnan(az) < 1) {
20418  // cout<<"az.."<<az<<"azcount"<<azc<<endl;
20419  az_r = (az + M_PI / 2.);
20420  az_east[i] = az_r * 180. / M_PI;
20421  if (az_east[i] < 0.0001 && az_east[i]>0) az_east[i] = 0.0;
20422  sum = az_east[i];
20423  tot += sum;
20424  azc++;
20425  }
20426  else {
20427  az_east[i] = NAN;
20428  }
20429  }
20430  float mean_az_east = tot / (azc);
20431 
20432  cout << "mean_az_east.." << mean_az_east << "numgridlines.." << num_gridlines-2 << endl;
20433  // exit(1);
20434 
20435  for (int j = 0;j < num_gridlines - 2;j++) {
20436  az_east[j] = mean_az_east;
20437  }
20438 
20439  l1cfile->mean_az_east = mean_az_east;
20440 
20441  for (int i = 0;i < num_gridlines - 2;i++) {
20442 
20443  if (i % 1 == 0) {
20444  //assign central positions---
20445  lat1_l = lati2[i] * M_PI / 180.;
20446  lat1_r = lati2[i] * M_PI / 180.;
20447  lat2 = lati2[i + 1] * M_PI / 180.;
20448  lon1_l = loni2[i] * M_PI / 180.;
20449  lon1_r = loni2[i] * M_PI / 180.;
20450  lon2 = loni2[i + 1] * M_PI / 180.;
20451 
20452  dlambda = (lon2 - lon1_l);
20453 
20454 
20455  gres = (l1cinput->gres) * 1000; //grid resolution in meters
20456 
20457  //bearing---
20458  //this is Harverside--law f cosines is more accurate---
20459  az = atan2(sin(dlambda) * cos(lat2), cos(lat1_l) * sin(lat2) - sin(lat1_l) * cos(lat2) * cos(dlambda));
20460  if (az > M_PI | az < -M_PI) {
20461  cout << "problem with BEARING in across-gridline method...az<-180 or >180...." << "az in degrees.." << az * 180 / M_PI << endl;
20462  exit(1);
20463  }
20464 
20465  //compute RIGHT across-gridline pixels---
20466 
20467  for (int k = 0;k < (nbinx / 2);k++) {
20468  h = (l1cinput->gres);//distance between along positions in km, must be 5.2 k m for L1C
20469  if (k == 0) h /= 2;//if nadpix
20470  htot += h;
20471 
20472  //right pixels---
20473  az_r = mean_az_east * degrad;
20474 
20475  //left pixels---
20476 
20477  az_l = az_r - M_PI;
20478  // az_l=(az-M_PI/2.);//this should be equal to az_r+M_PI=az_l
20479 
20480  //bearing should be always positive (clockwise) before pixel location calculation based on Harverside---
20481  if (az_r < 0.) {
20482  az_r = 360 + az_r * 180 / M_PI;
20483  az_r = az_r * M_PI / 180;
20484  }
20485 
20486  if (az_l < 0.) {
20487  az_l = 360 + az_l * 180 / M_PI;
20488  az_l = az_l * M_PI / 180;
20489  }
20490 
20491  geod.Direct(lat1_r * 180 / M_PI, lon1_r * 180 / M_PI, az_r * 180 / M_PI, gres, latih, lonih);
20492  geod.Inverse(lat1_r * 180 / M_PI, lon1_r * 180 / M_PI, latih, lonih, res1);
20493  fnan1 = isnan(latih);
20494  fnan2 = isnan(lonih);
20495  lati_r[k] = latih;
20496  loni_r[k] = lonih;
20497  // cout<<"righside.."<<latih<<"..."<<lonih<<"res1"<<res1<<endl;
20498 
20499  lat1_r = lati_r[k] * M_PI / 180;
20500  lon1_r = loni_r[k] * M_PI / 180;
20501 
20502  geod.Direct(lat1_l * 180 / M_PI, lon1_l * 180 / M_PI, az_l * 180 / M_PI, gres, latih2, lonih2);
20503  geod.Inverse(lat1_l * 180 / M_PI, lon1_l * 180 / M_PI, latih2, lonih2, res2);
20504  fnan3 = isnan(latih2);
20505  fnan4 = isnan(lonih2);
20506  lati_l[k] = latih2;
20507  loni_l[k] = lonih2;
20508  // cout<<"leftside.."<<latih2<<"..."<<lonih2<<"res2"<<res2<<endl;
20509 
20510  lat1_l = lati_l[k] * M_PI / 180;
20511  lon1_l = loni_l[k] * M_PI / 180;
20512 
20513  //right swath side-------------
20514  if (asc_mode==1 && lati2[i]>lati2[i+1] || asc_mode==0 && lati2[i]<lati2[i+1] || fnan1 > 0 || fnan2 > 0 || res1 > (gres + 6) || res1 < (gres - 6) || lati2[i + 1] < lati2[i] || lati2[i] < latfirst) { //nan values
20515  badline++;
20516  if (badline == 1) {
20517  latfirst = lati2[i];
20518  }
20519 
20520  cout << "bad interpolation - missing orbital data at near nadir grid cell..NAN right side of line.." << i + 1 << "corresponding to lat..."<<latfirst <<"lati2[i].."<<lati2[i]<<endl;
20521  cout<<"gd.."<<gd+1<<"XBIN.."<<k+1<<"lati_l[k]"<<lati_l[k]<<"loni_l[k]"<<loni_l[k]<<"lati_r[k]"<<lati_r[k]<<"loni_r[k]"<<loni_r[k]<<endl;
20522  lati2[i] = NAN;
20523  loni2[i] = NAN;
20524 
20525  for (int k = 0;k < (nbinx / 2);k++) {
20526  lat_gd[gd][k + nbinx / 2] = NAN;
20527  lon_gd[gd][k + nbinx / 2] = NAN;
20528  }
20529  // cout<<"nan value.right.."<<endl;
20530  }
20531  else {
20532  lat_gd[gd][k + nbinx / 2] = latih;
20533  lon_gd[gd][k + nbinx / 2] = lonih;
20534  }
20535 
20536  //left side
20537  if (asc_mode==1 && lati2[i]>lati2[i+1] || asc_mode==0 && lati2[i]<lati2[i+1] || fnan3 > 0 || fnan4 > 0 || res2 > (gres + 6) || res2 < (gres - 6) || lati2[i + 1] < lati2[i] || lati2[i] < latfirst) {
20538  // if(fnan3>0 | fnan4>0 | res2>(gres+6) | res2<(gres-6)){
20539  cout << "bad interpolation - missing orbital data at near nadir grid cell..NAN left side of line.." << i + 1 << endl;
20540  cout<<"gd.."<<gd+1<<"XBIN.."<<k+1<<"lati_l[k]"<<lati_l[k]<<"loni_l[k]"<<loni_l[k]<<"lati_r[k]"<<lati_r[k]<<"loni_r[k]"<<loni_r[k]<<"lati2[i].."<<lati2[i]<<endl;
20541  lati2[i] = NAN;
20542  loni2[i] = NAN;
20543  for (int k = 0;k < (nbinx / 2);k++) {
20544  lat_gd[gd][nbinx / 2 - 1 - k] = NAN;//as k increases we are farther away from nadpix or along-track position---
20545  lon_gd[gd][nbinx / 2 - 1 - k] = NAN;
20546  }
20547  // cout<<"nan value.left.."<<endl;
20548  }
20549  else {
20550  lat_gd[gd][nbinx / 2 - 1 - k] = latih2;//as k increases we are farther away from nadpix or along-track position---
20551  lon_gd[gd][nbinx / 2 - 1 - k] = lonih2;
20552  }
20553  fnan1=0;
20554  fnan2=0;
20555  fnan3=0;
20556  fnan4=0;
20557 
20558  }//end pixel loop
20559 
20560 
20561  htot = 0;
20562  gd++;
20563  }//end if every 100 gd
20564  }//end gridlines loop
20565  cout << "`L1C gridding successful!......................................." << endl;
20566 
20567 //writing results ***************************************************************************
20568  float lontemp = 0.;
20569  selday = l1cinput->selday;
20570  selmon = l1cinput->selmon;
20571  selyear = l1cinput->selyear;
20572 
20573  std::string timestr,missionstr,fname_out, pathstr, senstr, monstr, daystr, yearstr, prodstr, gdstr, swtstr, swtnum, extstr,ofilestr;
20574  pathstr = "out/";
20575  missionstr="PACE";
20576  senstr = "OCIS";
20577  monstr = std::to_string(selmon);
20578  daystr = std::to_string(selday);
20579  yearstr = std::to_string(selyear);
20580  timestr="T00:00:00Z";
20581  prodstr = "L1Cgrid";
20582  // gdstr="_gdFULL_";
20583  swtstr = "_swt";
20584 
20585  if (l1cfile->l1c_pflag >= 3) {
20586  swtd = l1cfile->swtnum;
20587  swtnum = std::to_string(swtd);
20588  cout << "swtnum.." << swtnum << endl;
20589  }
20590  else swtnum = std::to_string(swtd);
20591 
20592  extstr = ".nc";
20593  ofilestr=std::string(l1cinput->ofile);
20594 
20595  fname_out = pathstr + ofilestr+"_"+ prodstr+extstr;
20596 
20597  string ATT_NAME="Units", ATT_VAL="degrees",GATT_NAME1="Title",GATT_VAL1="PACE OCI Level-1C Data",GATT_NAME2="instrument",GATT_VAL2="OCI",GATT_NAME3="processing_version",GATT_VAL3="V1.0",GATT_NAME4="Conventions",GATT_VAL4="CF-1.6";
20598  string GATT_NAME5="institution",GATT_VAL5="NASA Goddard Space Flight Center, Ocean Biology Processing Group",GATT_NAME6="license",GATT_VAL6="http://science.nasa.gov/earth-science/earth-science-data/data-information-policy/";
20599  string GATT_NAME7="naming_authority",GATT_VAL7="gov.nasa.gsfc.sci.oceancolor",GATT_NAME8="keywords_vocabulary",GATT_VAL8="NASA Global Change Master Directory (GCMD) Science Keywords";
20600  string GATT_NAME9="stdname_vocabulary",GATT_VAL9="NetCDF Climate and Forecast (CF) Metadata Convention",GATT_NAME10="creator_name",GATT_VAL10="NASA/GSFC",GATT_NAME11="creator_email",GATT_VAL11="data@oceancolor.gsfc.nasa.gov";
20601  string GATT_NAME12="creator_url",GATT_VAL12="http://oceancolor.gsfc.nasa.gov",GATT_NAME13="project",GATT_VAL13="PACE Project",GATT_NAME14="publisher_name",GATT_VAL14="NASA/GSFC";
20602  string GATT_NAME15="publisher_email",GATT_VAL15="data@oceancolor.gsfc.nasa.gov",GATT_NAME16="publisher_url",GATT_VAL16="http://oceancolor.gsfc.nasa.gov",GATT_NAME17="processing_level",GATT_VAL17="L1C";
20603  string GATT_NAME18="cdm_data_type",GATT_VAL18="swath",GATT_NAME19="orbit_number",GATT_VAL19="12345",GATT_NAME20="history",GATT_VAL20="",GATT_NAME21="CDL_version_date",GATT_VAL21="2021-09-10",GATT_NAME22="product_name",GATT_VAL22=fname_out;
20604  string GATT_NAME23="startDirection",GATT_VAL23="Ascending",GATT_NAME24="endDirection",GATT_VAL24="Ascending",GATT_NAME25="time_coverage_start",GATT_VAL25=yearstr+"-"+monstr+"-"+daystr+"-"+timestr,GATT_NAME26="time_coverage_end",GATT_VAL26=yearstr+"-"+monstr+"-"+daystr+"-"+timestr,GATT_NAME27="date{_created",GATT_VAL27="2021-09-10T15:12:41Z",GATT_NAME28="sun_earth_distance",GATT_VAL28="0.990849042172323",GATT_NAME29="terrain_data_source",GATT_VAL29="",GATT_NAME30="spectral_response_function",GATT_VAL30="",GATT_NAME31="systematic_uncertainty_model",GATT_VAL31="",GATT_NAME32="nadir_bin",GATT_VAL32="12345",GATT_NAME33="bin_size_at_nadir",GATT_VAL33="2.6km2";
20605 
20606 
20607  l1cfile->gridname = fname_out.c_str();
20608  filename_lt = fname_out.c_str();
20609  cout<<"creating file for L1C coor..."<<filename_lt<<endl;
20610 // if ((status = nc_create(filename_lt, NC_CLOBBER, &ncid_out)))
20611  if ((status = nc_create(filename_lt, NC_CLOBBER | NC_NETCDF4, &ncid_out)))
20612  check_err(status, __LINE__, __FILE__);
20613  //define dims
20614  // Define the dimensions,vars and attributes at the root level
20615  NY = num_gridlines-2;
20616  NX = nbinx;
20617  NVIEWS= 2;//for OCI
20618  NBANDS=249;
20619 // lt_out = allocate2d_float(NY, NX);
20620  //DEF DIMENSIONS
20621  if ((status = nc_def_dim(ncid_out, "bins_across_track", NX, &x_dimid)))
20622  check_err(status, __LINE__, __FILE__);
20623  if ((status = nc_def_dim(ncid_out, "bins_along_track", NY, &y_dimid)))
20624  check_err(status, __LINE__, __FILE__);
20625  //dims for output var
20626  dimids[0] = y_dimid;
20627  dimids[1] = x_dimid;
20628  NDIMS=2;
20629  if ((status = nc_def_dim(ncid_out, "number_of_views", NVIEWS, &v_dimid)))
20630  check_err(status, __LINE__, __FILE__);
20631  if ((status = nc_def_dim(ncid_out, "intensity_bands_per_view", NBANDS, &b_dimid)))
20632  check_err(status, __LINE__, __FILE__);
20633 
20634 /*
20635 //def variables at the root level!
20636  if ((status = nc_def_var(ncid_out, "latitude", NC_FLOAT, NDIMS,
20637  dimids, &varid1)))
20638  check_err(status, __LINE__, __FILE__);
20639  if ((status = nc_def_var(ncid_out, "longitude", NC_FLOAT, NDIMS,
20640  dimids, &varid2)))
20641  check_err(status, __LINE__, __FILE__);
20642 
20643  if ((status = nc_enddef(ncid_out))) //done def vars etc
20644  check_err(status, __LINE__, __FILE__);
20645  if ((status = nc_put_var_float(ncid_out, varid1, &lat_gd[0][0])))
20646  check_err(status, __LINE__, __FILE__);
20647  if ((status = nc_put_var_float(ncid_out, varid2, &lon_gd[0][0])))
20648  check_err(status, __LINE__, __FILE__);
20649 */
20650 
20651 //define attributes
20652 // if (nc_put_att_text(ncid_out, varid1, ATT_NAME.c_str(), strlen(ATT_VAL.c_str()), ATT_VAL.c_str()))
20653 // check_err(status, __LINE__, __FILE__);
20654 // if (nc_put_att_text(ncid_out, varid2, ATT_NAME.c_str(), strlen(ATT_VAL.c_str()), ATT_VAL.c_str()))
20655 // check_err(status, __LINE__, __FILE__);
20656  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME1.c_str(), strlen(GATT_VAL1.c_str()),
20657  GATT_VAL1.c_str()))
20658  check_err(status, __LINE__, __FILE__);
20659  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME2.c_str(), strlen(GATT_VAL2.c_str()),
20660  GATT_VAL2.c_str()))
20661  check_err(status, __LINE__, __FILE__);
20662  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME3.c_str(), strlen(GATT_VAL3.c_str()),
20663  GATT_VAL3.c_str()))
20664  check_err(status, __LINE__, __FILE__);
20665  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME4.c_str(), strlen(GATT_VAL4.c_str()),
20666  GATT_VAL4.c_str()))
20667  check_err(status, __LINE__, __FILE__);
20668  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME5.c_str(), strlen(GATT_VAL5.c_str()),
20669  GATT_VAL5.c_str()))
20670  check_err(status, __LINE__, __FILE__);
20671  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME6.c_str(), strlen(GATT_VAL6.c_str()),
20672  GATT_VAL6.c_str()))
20673  check_err(status, __LINE__, __FILE__);
20674  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME7.c_str(), strlen(GATT_VAL7.c_str()),
20675  GATT_VAL7.c_str()))
20676  check_err(status, __LINE__, __FILE__);
20677  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME8.c_str(), strlen(GATT_VAL8.c_str()),
20678  GATT_VAL8.c_str()))
20679  check_err(status, __LINE__, __FILE__);
20680  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME9.c_str(), strlen(GATT_VAL9.c_str()),
20681  GATT_VAL9.c_str()))
20682  check_err(status, __LINE__, __FILE__);
20683  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME10.c_str(), strlen(GATT_VAL10.c_str()),
20684  GATT_VAL10.c_str()))
20685  check_err(status, __LINE__, __FILE__);
20686  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME11.c_str(), strlen(GATT_VAL11.c_str()),
20687  GATT_VAL11.c_str()))
20688  check_err(status, __LINE__, __FILE__);
20689  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME12.c_str(), strlen(GATT_VAL12.c_str()),
20690  GATT_VAL12.c_str()))
20691  check_err(status, __LINE__, __FILE__);
20692  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME13.c_str(), strlen(GATT_VAL13.c_str()),
20693  GATT_VAL13.c_str()))
20694  check_err(status, __LINE__, __FILE__);
20695  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME14.c_str(), strlen(GATT_VAL14.c_str()),
20696  GATT_VAL14.c_str()))
20697  check_err(status, __LINE__, __FILE__);
20698  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME15.c_str(), strlen(GATT_VAL15.c_str()),
20699  GATT_VAL15.c_str()))
20700  check_err(status, __LINE__, __FILE__);
20701  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME16.c_str(), strlen(GATT_VAL16.c_str()),
20702  GATT_VAL16.c_str()))
20703  check_err(status, __LINE__, __FILE__);
20704  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME17.c_str(), strlen(GATT_VAL17.c_str()),
20705  GATT_VAL17.c_str()))
20706  check_err(status, __LINE__, __FILE__);
20707  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME18.c_str(), strlen(GATT_VAL18.c_str()),
20708  GATT_VAL18.c_str()))
20709  check_err(status, __LINE__, __FILE__);
20710  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME19.c_str(), strlen(GATT_VAL19.c_str()),
20711  GATT_VAL19.c_str()))
20712  check_err(status, __LINE__, __FILE__);
20713  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME20.c_str(), strlen(GATT_VAL20.c_str()),
20714  GATT_VAL20.c_str()))
20715  check_err(status, __LINE__, __FILE__);
20716  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME21.c_str(), strlen(GATT_VAL21.c_str()),
20717  GATT_VAL21.c_str()))
20718  check_err(status, __LINE__, __FILE__);
20719  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME22.c_str(), strlen(GATT_VAL22.c_str()),
20720  GATT_VAL22.c_str()))
20721  check_err(status, __LINE__, __FILE__);
20722  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME23.c_str(), strlen(GATT_VAL23.c_str()),
20723  GATT_VAL23.c_str()))
20724  check_err(status, __LINE__, __FILE__);
20725  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME24.c_str(), strlen(GATT_VAL24.c_str()),
20726  GATT_VAL24.c_str()))
20727  check_err(status, __LINE__, __FILE__);
20728  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME25.c_str(), strlen(GATT_VAL25.c_str()),
20729  GATT_VAL25.c_str()))
20730  check_err(status, __LINE__, __FILE__);
20731  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME26.c_str(), strlen(GATT_VAL26.c_str()),
20732  GATT_VAL26.c_str()))
20733  check_err(status, __LINE__, __FILE__);
20734  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME27.c_str(), strlen(GATT_VAL27.c_str()),
20735  GATT_VAL27.c_str()))
20736  check_err(status, __LINE__, __FILE__);
20737  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME28.c_str(), strlen(GATT_VAL28.c_str()),
20738  GATT_VAL28.c_str()))
20739  check_err(status, __LINE__, __FILE__);
20740  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME29.c_str(), strlen(GATT_VAL29.c_str()),
20741  GATT_VAL29.c_str()))
20742  check_err(status, __LINE__, __FILE__);
20743  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME30.c_str(), strlen(GATT_VAL30.c_str()),
20744  GATT_VAL30.c_str()))
20745  check_err(status, __LINE__, __FILE__);
20746  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME31.c_str(), strlen(GATT_VAL31.c_str()),
20747  GATT_VAL31.c_str()))
20748  check_err(status, __LINE__, __FILE__);
20749  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME32.c_str(), strlen(GATT_VAL32.c_str()),
20750  GATT_VAL32.c_str()))
20751  check_err(status, __LINE__, __FILE__);
20752  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME33.c_str(), strlen(GATT_VAL33.c_str()),
20753  GATT_VAL33.c_str()))
20754  check_err(status, __LINE__, __FILE__);
20755 
20756  //define groups check_err(status, __LINE__, __FILE__);
20757  if ((status = nc_def_grp(ncid_out, "geolocation_data", &grp_coor))) //netcdf-4
20758  check_err(status, __LINE__, __FILE__);
20759 // if ((status = nc_def_grp(ncid_out, "observation_data", &grp_obs))) //netcdf-4
20760 // check_err(status, __LINE__, __FILE__);
20761 
20762 //DEF DIMENSIONS
20763  /* if ((status = nc_def_dim(grp_coor, "x", NX, &x_dimid)))
20764  check_err(status, __LINE__, __FILE__);
20765  if ((status = nc_def_dim(grp_coor, "y", NY, &y_dimid)))
20766  check_err(status, __LINE__, __FILE__);
20767  dimids[0] = y_dimid;
20768  dimids[1] = x_dimid;
20769 
20770  NDIMS=2;
20771 */
20772  //def var
20773  if ((status = nc_def_var(grp_coor, "latitude", NC_FLOAT, NDIMS,
20774  dimids, &varid1)))
20775  check_err(status, __LINE__, __FILE__);
20776  if ((status = nc_def_var(grp_coor, "longitude", NC_FLOAT, NDIMS,
20777  dimids, &varid2)))
20778  check_err(status, __LINE__, __FILE__);
20779  //leave define mode-----------------------
20780  if ((status = nc_enddef(grp_coor))) //done def vars etc
20781  check_err(status, __LINE__, __FILE__);
20782 // if ((status = nc_def_var(grp_obs, "lt", NC_FLOAT, NDIMS,
20783 // dimids, &varid3)))
20784 // check_err(status, __LINE__, __FILE__);
20785  //leave define mode-----------------------
20786 // if ((status = nc_enddef(grp_obs))) //done def vars etc
20787 // check_err(status, __LINE__, __FILE__);
20788 
20789  //writing the whole thing
20790  if ((status = nc_put_var_float(grp_coor, varid1, &lat_gd[0][0])))
20791  check_err(status, __LINE__, __FILE__);
20792 
20793  if ((status = nc_put_var_float(grp_coor, varid2, &lon_gd[0][0])))
20794  check_err(status, __LINE__, __FILE__);
20795 // if ((status = nc_put_var_float(grp_obs, varid3, &lt_out[0][0])))
20796 // check_err(status, __LINE__, __FILE__);
20797 //define attributes of vars in groups
20798 //UNITS in degrees ----
20799  if (nc_put_att_text(grp_coor, varid1, ATT_NAME.c_str(), strlen(ATT_VAL.c_str()), ATT_VAL.c_str()))
20800  check_err(status, __LINE__, __FILE__);
20801  if (nc_put_att_text(grp_coor, varid2, ATT_NAME.c_str(), strlen(ATT_VAL.c_str()), ATT_VAL.c_str()))
20802  check_err(status, __LINE__, __FILE__);
20803 
20804 
20805 //close file
20806  if ((status = nc_close(ncid_out)))
20807  check_err(status, __LINE__, __FILE__);
20808 
20809 // delete [] (lt_out);
20810 
20811 //CASE ONLY LON POS VALUES***************************************************************************
20812 
20813  //Only positive longitude 0-360 degrees for visualization ****************************************************************
20814  //lat lon grid for visualization--
20815  prodstr = "L1Cgrid_lonpos";
20816  // gdstr="_gdFULL_";
20817  //recompute number of gridlines based on lat limits -80 to 80 degrees
20818  //asc orbit goes from negative to positive latitude....
20819 
20820  NY = num_gridlines-2;
20821  NX = nbinx;
20822 
20823  for (int i = 0; i < NY; i++) {
20824  for (int j = 0; j < NX; j++) {
20825  if (lat_gd[i][j] >= -80.) c1++;
20826  if (c1 == nbinx) {
20827  NY1 = i;
20828  }
20829  }
20830  if (NY1 >= 0) break;
20831  c1 = 1;
20832  }
20833 
20834  for (int i = 0;i < NY; i++) {
20835  for (int j = 0; j < NX; j++) {
20836  if (lat_gd[i][j] >= 80.) {
20837  NY2 = i - 1;
20838  }
20839  }
20840  if (NY2 >= 0) break;
20841  }
20842 
20843  l1cfile->NY1 = NY1;
20844  l1cfile->NY2 = NY2;
20845 
20846  NY = NY2 - NY1 + 1;
20847 
20848  lat_out = allocate2d_float(NY, NX);
20849  lon_out = allocate2d_float(NY, NX);
20850 
20851  int c=0;
20852  for (int i = NY1; i < NY2 + 1; i++) {
20853  for (int j = 0; j < NX; j++) {
20854  if(lon_gd[i][j]<0) lon_out[c][j]=lon_gd[i][j]+360;
20855  else lon_out[c][j]=lon_gd[i][j];
20856  lat_out[c][j] = lat_gd[i][j];
20857  }
20858  cout<<"gd#..."<<c+1<<endl;
20859  c++;
20860 
20861  }
20862 
20863 
20864  extstr = ".nc";
20865 // fname_out = pathstr + missionstr + "_" + senstr + "." + yearstr + monstr + daystr + timestr + prodstr+extstr;
20866  fname_out = pathstr + ofilestr+"_"+ prodstr+extstr;
20867 
20868  l1cfile->gridname = fname_out.c_str();
20869  filename_lt = fname_out.c_str();
20870  cout<<"creating file for L1C coor.with only POS LONGITUDE.."<<filename_lt<<endl;
20871 // if ((status = nc_create(filename_lt, NC_CLOBBER, &ncid_out)))
20872  if ((status = nc_create(filename_lt, NC_CLOBBER | NC_NETCDF4, &ncid_out)))
20873  check_err(status, __LINE__, __FILE__);
20874  //define dims
20875  // Define the dimensions,vars and attributes at the root level
20876 
20877 
20878  //DEF DIMENSIONS
20879  if ((status = nc_def_dim(ncid_out, "bins_across_track", NX, &x_dimid)))
20880  check_err(status, __LINE__, __FILE__);
20881  if ((status = nc_def_dim(ncid_out, "bins_along_track", NY, &y_dimid)))
20882  check_err(status, __LINE__, __FILE__);
20883  //dims for output var
20884  dimids[0] = y_dimid;
20885  dimids[1] = x_dimid;
20886  NDIMS=2;
20887  if ((status = nc_def_dim(ncid_out, "number_of_views", NVIEWS, &v_dimid)))
20888  check_err(status, __LINE__, __FILE__);
20889  if ((status = nc_def_dim(ncid_out, "intensity_bands_per_view", NBANDS, &b_dimid)))
20890  check_err(status, __LINE__, __FILE__);
20891 /*
20892 //def variables at the root level!
20893  if ((status = nc_def_var(ncid_out, "latitude", NC_FLOAT, NDIMS,
20894  dimids, &varid1)))
20895  check_err(status, __LINE__, __FILE__);
20896  if ((status = nc_def_var(ncid_out, "longitude", NC_FLOAT, NDIMS,
20897  dimids, &varid2)))
20898  check_err(status, __LINE__, __FILE__);
20899 
20900  if ((status = nc_enddef(ncid_out))) //done def vars etc
20901  check_err(status, __LINE__, __FILE__);
20902  if ((status = nc_put_var_float(ncid_out, varid1, &lat_out[0][0])))
20903  check_err(status, __LINE__, __FILE__);
20904  if ((status = nc_put_var_float(ncid_out, varid2, &lon_out[0][0])))
20905  check_err(status, __LINE__, __FILE__);
20906 
20907 //define attributes
20908  if (nc_put_att_text(ncid_out, varid1, ATT_NAME.c_str(), strlen(ATT_VAL.c_str()), ATT_VAL.c_str()))
20909  check_err(status, __LINE__, __FILE__);
20910  if (nc_put_att_text(ncid_out, varid2, ATT_NAME.c_str(), strlen(ATT_VAL.c_str()), ATT_VAL.c_str()))
20911  check_err(status, __LINE__, __FILE__);
20912 */
20913  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME1.c_str(), strlen(GATT_VAL1.c_str()),
20914  GATT_VAL1.c_str()))
20915  check_err(status, __LINE__, __FILE__);
20916  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME2.c_str(), strlen(GATT_VAL2.c_str()),
20917  GATT_VAL2.c_str()))
20918  check_err(status, __LINE__, __FILE__);
20919  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME3.c_str(), strlen(GATT_VAL3.c_str()),
20920  GATT_VAL3.c_str()))
20921  check_err(status, __LINE__, __FILE__);
20922  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME4.c_str(), strlen(GATT_VAL4.c_str()),
20923  GATT_VAL4.c_str()))
20924  check_err(status, __LINE__, __FILE__);
20925  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME5.c_str(), strlen(GATT_VAL5.c_str()),
20926  GATT_VAL5.c_str()))
20927  check_err(status, __LINE__, __FILE__);
20928  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME6.c_str(), strlen(GATT_VAL6.c_str()),
20929  GATT_VAL6.c_str()))
20930  check_err(status, __LINE__, __FILE__);
20931  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME7.c_str(), strlen(GATT_VAL7.c_str()),
20932  GATT_VAL7.c_str()))
20933  check_err(status, __LINE__, __FILE__);
20934  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME8.c_str(), strlen(GATT_VAL8.c_str()),
20935  GATT_VAL8.c_str()))
20936  check_err(status, __LINE__, __FILE__);
20937  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME9.c_str(), strlen(GATT_VAL9.c_str()),
20938  GATT_VAL9.c_str()))
20939  check_err(status, __LINE__, __FILE__);
20940  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME10.c_str(), strlen(GATT_VAL10.c_str()),
20941  GATT_VAL10.c_str()))
20942  check_err(status, __LINE__, __FILE__);
20943  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME11.c_str(), strlen(GATT_VAL11.c_str()),
20944  GATT_VAL11.c_str()))
20945  check_err(status, __LINE__, __FILE__);
20946  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME12.c_str(), strlen(GATT_VAL12.c_str()),
20947  GATT_VAL12.c_str()))
20948  check_err(status, __LINE__, __FILE__);
20949  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME13.c_str(), strlen(GATT_VAL13.c_str()),
20950  GATT_VAL13.c_str()))
20951  check_err(status, __LINE__, __FILE__);
20952  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME14.c_str(), strlen(GATT_VAL14.c_str()),
20953  GATT_VAL14.c_str()))
20954  check_err(status, __LINE__, __FILE__);
20955  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME15.c_str(), strlen(GATT_VAL15.c_str()),
20956  GATT_VAL15.c_str()))
20957  check_err(status, __LINE__, __FILE__);
20958  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME16.c_str(), strlen(GATT_VAL16.c_str()),
20959  GATT_VAL16.c_str()))
20960  check_err(status, __LINE__, __FILE__);
20961  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME17.c_str(), strlen(GATT_VAL17.c_str()),
20962  GATT_VAL17.c_str()))
20963  check_err(status, __LINE__, __FILE__);
20964  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME18.c_str(), strlen(GATT_VAL18.c_str()),
20965  GATT_VAL18.c_str()))
20966  check_err(status, __LINE__, __FILE__);
20967  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME19.c_str(), strlen(GATT_VAL19.c_str()),
20968  GATT_VAL19.c_str()))
20969  check_err(status, __LINE__, __FILE__);
20970  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME20.c_str(), strlen(GATT_VAL20.c_str()),
20971  GATT_VAL20.c_str()))
20972  check_err(status, __LINE__, __FILE__);
20973  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME21.c_str(), strlen(GATT_VAL21.c_str()),
20974  GATT_VAL21.c_str()))
20975  check_err(status, __LINE__, __FILE__);
20976  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME22.c_str(), strlen(GATT_VAL22.c_str()),
20977  GATT_VAL22.c_str()))
20978  check_err(status, __LINE__, __FILE__);
20979  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME23.c_str(), strlen(GATT_VAL23.c_str()),
20980  GATT_VAL23.c_str()))
20981  check_err(status, __LINE__, __FILE__);
20982  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME24.c_str(), strlen(GATT_VAL24.c_str()),
20983  GATT_VAL24.c_str()))
20984  check_err(status, __LINE__, __FILE__);
20985  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME25.c_str(), strlen(GATT_VAL25.c_str()),
20986  GATT_VAL25.c_str()))
20987  check_err(status, __LINE__, __FILE__);
20988  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME26.c_str(), strlen(GATT_VAL26.c_str()),
20989  GATT_VAL26.c_str()))
20990  check_err(status, __LINE__, __FILE__);
20991  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME27.c_str(), strlen(GATT_VAL27.c_str()),
20992  GATT_VAL27.c_str()))
20993  check_err(status, __LINE__, __FILE__);
20994  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME28.c_str(), strlen(GATT_VAL28.c_str()),
20995  GATT_VAL28.c_str()))
20996  check_err(status, __LINE__, __FILE__);
20997  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME29.c_str(), strlen(GATT_VAL29.c_str()),
20998  GATT_VAL29.c_str()))
20999  check_err(status, __LINE__, __FILE__);
21000  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME30.c_str(), strlen(GATT_VAL30.c_str()),
21001  GATT_VAL30.c_str()))
21002  check_err(status, __LINE__, __FILE__);
21003  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME31.c_str(), strlen(GATT_VAL31.c_str()),
21004  GATT_VAL31.c_str()))
21005  check_err(status, __LINE__, __FILE__);
21006  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME32.c_str(), strlen(GATT_VAL32.c_str()),
21007  GATT_VAL32.c_str()))
21008  check_err(status, __LINE__, __FILE__);
21009  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME33.c_str(), strlen(GATT_VAL33.c_str()),
21010  GATT_VAL33.c_str()))
21011  check_err(status, __LINE__, __FILE__);
21012 
21013 
21014 
21015 
21016  //define groups check_err(status, __LINE__, __FILE__);
21017  if ((status = nc_def_grp(ncid_out, "geolocation_data", &grp_coor))) //netcdf-4
21018  check_err(status, __LINE__, __FILE__);
21019 /*
21020 //DEF DIMENSIONS
21021  if ((status = nc_def_dim(grp_coor, "x", NX, &x_dimid)))
21022  check_err(status, __LINE__, __FILE__);
21023  if ((status = nc_def_dim(grp_coor, "y", NY, &y_dimid)))
21024  check_err(status, __LINE__, __FILE__);
21025  dimids[0] = y_dimid;
21026  dimids[1] = x_dimid;
21027  NDIMS=2;
21028 */
21029  //def var
21030  if ((status = nc_def_var(grp_coor, "latitude", NC_FLOAT, NDIMS,
21031  dimids, &varid1)))
21032  check_err(status, __LINE__, __FILE__);
21033  if ((status = nc_def_var(grp_coor, "longitude", NC_FLOAT, NDIMS,
21034  dimids, &varid2)))
21035  check_err(status, __LINE__, __FILE__);
21036 
21037  //leave define mode-----------------------
21038  if ((status = nc_enddef(grp_coor))) //done def vars etc
21039  check_err(status, __LINE__, __FILE__);
21040 
21041  //writing the whole thing
21042  if ((status = nc_put_var_float(grp_coor, varid1, &lat_out[0][0])))
21043  check_err(status, __LINE__, __FILE__);
21044 
21045  if ((status = nc_put_var_float(grp_coor, varid2, &lon_out[0][0])))
21046  check_err(status, __LINE__, __FILE__);
21047 
21048 //define attributes of vars in groups
21049  if (nc_put_att_text(grp_coor, varid1, ATT_NAME.c_str(), strlen(ATT_VAL.c_str()), ATT_VAL.c_str()))
21050  check_err(status, __LINE__, __FILE__);
21051  if (nc_put_att_text(grp_coor, varid2, ATT_NAME.c_str(), strlen(ATT_VAL.c_str()), ATT_VAL.c_str()))
21052  check_err(status, __LINE__, __FILE__);
21053 
21054 
21055  if ((status = nc_close(ncid_out)))
21056  check_err(status, __LINE__, __FILE__);
21057 
21058 
21059  delete [] (lat_out);
21060  delete [] (lon_out);
21061  lat_out=nullptr;
21062  lon_out=nullptr;
21063 
21064 
21065 //CASE INVERTED ALONG/ACROSS INDEXES ***************************************************************************
21066  prodstr = "L1Cgrid_inverted";
21067 
21068 
21069  lat_out = allocate2d_float(NY, NX);
21070  lon_out = allocate2d_float(NY, NX);
21071 
21072  c = 0;
21073  for (int i = NY1; i < NY2 + 1; i++) {
21074  for (int j = 0; j < NX; j++) {
21075  lat_out[NY - 1 - c][NX - 1 - j] = lat_gd[i][j];
21076  lon_out[NY - 1 - c][j] = lon_gd[i][j];
21077  }
21078  c++;
21079  }
21080 
21081  extstr = ".nc";
21082 // fname_out = pathstr + missionstr + "_" + senstr + "." + yearstr + monstr + daystr + timestr + prodstr+extstr;
21083  fname_out = pathstr + ofilestr+"_"+ prodstr+extstr;
21084  l1cfile->gridname = fname_out.c_str();
21085  filename_lt = fname_out.c_str();
21086  cout<<"creating file for L1C coor.with x/y inverted indexes.."<<filename_lt<<endl;
21087 // if ((status = nc_create(filename_lt, NC_CLOBBER, &ncid_out)))
21088  if ((status = nc_create(filename_lt, NC_CLOBBER | NC_NETCDF4, &ncid_out)))
21089  check_err(status, __LINE__, __FILE__);
21090  //define dims
21091  // Define the dimensions,vars and attributes at the root level
21092 
21093 
21094  //DEF DIMENSIONS
21095  if ((status = nc_def_dim(ncid_out, "bins_across_track", NX, &x_dimid)))
21096  check_err(status, __LINE__, __FILE__);
21097  if ((status = nc_def_dim(ncid_out, "bins_along_track", NY, &y_dimid)))
21098  check_err(status, __LINE__, __FILE__);
21099  //dims for output var
21100  dimids[0] = y_dimid;
21101  dimids[1] = x_dimid;
21102  NDIMS=2;
21103  if ((status = nc_def_dim(ncid_out, "number_of_views", NVIEWS, &v_dimid)))
21104  check_err(status, __LINE__, __FILE__);
21105  if ((status = nc_def_dim(ncid_out, "intensity_bands_per_view", NBANDS, &b_dimid)))
21106  check_err(status, __LINE__, __FILE__);
21107 /*
21108 //def variables at the root level!
21109  if ((status = nc_def_var(ncid_out, "latitude", NC_FLOAT, NDIMS,
21110  dimids, &varid1)))
21111  check_err(status, __LINE__, __FILE__);
21112  if ((status = nc_def_var(ncid_out, "longitude", NC_FLOAT, NDIMS,
21113  dimids, &varid2)))
21114  check_err(status, __LINE__, __FILE__);
21115 
21116  if ((status = nc_enddef(ncid_out))) //done def vars etc
21117  check_err(status, __LINE__, __FILE__);
21118  if ((status = nc_put_var_float(ncid_out, varid1, &lat_out[0][0])))
21119  check_err(status, __LINE__, __FILE__);
21120  if ((status = nc_put_var_float(ncid_out, varid2, &lon_out[0][0])))
21121  check_err(status, __LINE__, __FILE__);
21122 
21123 //define attributes
21124  if (nc_put_att_text(ncid_out, varid1, ATT_NAME.c_str(), strlen(ATT_VAL.c_str()), ATT_VAL.c_str()))
21125  check_err(status, __LINE__, __FILE__);
21126  if (nc_put_att_text(ncid_out, varid2, ATT_NAME.c_str(), strlen(ATT_VAL.c_str()), ATT_VAL.c_str()))
21127  check_err(status, __LINE__, __FILE__);
21128 */
21129 
21130  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME1.c_str(), strlen(GATT_VAL1.c_str()),
21131  GATT_VAL1.c_str()))
21132  check_err(status, __LINE__, __FILE__);
21133  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME2.c_str(), strlen(GATT_VAL2.c_str()),
21134  GATT_VAL2.c_str()))
21135  check_err(status, __LINE__, __FILE__);
21136  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME3.c_str(), strlen(GATT_VAL3.c_str()),
21137  GATT_VAL3.c_str()))
21138  check_err(status, __LINE__, __FILE__);
21139  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME4.c_str(), strlen(GATT_VAL4.c_str()),
21140  GATT_VAL4.c_str()))
21141  check_err(status, __LINE__, __FILE__);
21142  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME5.c_str(), strlen(GATT_VAL5.c_str()),
21143  GATT_VAL5.c_str()))
21144  check_err(status, __LINE__, __FILE__);
21145  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME6.c_str(), strlen(GATT_VAL6.c_str()),
21146  GATT_VAL6.c_str()))
21147  check_err(status, __LINE__, __FILE__);
21148  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME7.c_str(), strlen(GATT_VAL7.c_str()),
21149  GATT_VAL7.c_str()))
21150  check_err(status, __LINE__, __FILE__);
21151  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME8.c_str(), strlen(GATT_VAL8.c_str()),
21152  GATT_VAL8.c_str()))
21153  check_err(status, __LINE__, __FILE__);
21154  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME9.c_str(), strlen(GATT_VAL9.c_str()),
21155  GATT_VAL9.c_str()))
21156  check_err(status, __LINE__, __FILE__);
21157  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME10.c_str(), strlen(GATT_VAL10.c_str()),
21158  GATT_VAL10.c_str()))
21159  check_err(status, __LINE__, __FILE__);
21160  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME11.c_str(), strlen(GATT_VAL11.c_str()),
21161  GATT_VAL11.c_str()))
21162  check_err(status, __LINE__, __FILE__);
21163  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME12.c_str(), strlen(GATT_VAL12.c_str()),
21164  GATT_VAL12.c_str()))
21165  check_err(status, __LINE__, __FILE__);
21166  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME13.c_str(), strlen(GATT_VAL13.c_str()),
21167  GATT_VAL13.c_str()))
21168  check_err(status, __LINE__, __FILE__);
21169  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME14.c_str(), strlen(GATT_VAL14.c_str()),
21170  GATT_VAL14.c_str()))
21171  check_err(status, __LINE__, __FILE__);
21172  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME15.c_str(), strlen(GATT_VAL15.c_str()),
21173  GATT_VAL15.c_str()))
21174  check_err(status, __LINE__, __FILE__);
21175  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME16.c_str(), strlen(GATT_VAL16.c_str()),
21176  GATT_VAL16.c_str()))
21177  check_err(status, __LINE__, __FILE__);
21178  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME17.c_str(), strlen(GATT_VAL17.c_str()),
21179  GATT_VAL17.c_str()))
21180  check_err(status, __LINE__, __FILE__);
21181  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME18.c_str(), strlen(GATT_VAL18.c_str()),
21182  GATT_VAL18.c_str()))
21183  check_err(status, __LINE__, __FILE__);
21184  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME19.c_str(), strlen(GATT_VAL19.c_str()),
21185  GATT_VAL19.c_str()))
21186  check_err(status, __LINE__, __FILE__);
21187  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME20.c_str(), strlen(GATT_VAL20.c_str()),
21188  GATT_VAL20.c_str()))
21189  check_err(status, __LINE__, __FILE__);
21190  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME21.c_str(), strlen(GATT_VAL21.c_str()),
21191  GATT_VAL21.c_str()))
21192  check_err(status, __LINE__, __FILE__);
21193  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME22.c_str(), strlen(GATT_VAL22.c_str()),
21194  GATT_VAL22.c_str()))
21195  check_err(status, __LINE__, __FILE__);
21196  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME23.c_str(), strlen(GATT_VAL23.c_str()),
21197  GATT_VAL23.c_str()))
21198  check_err(status, __LINE__, __FILE__);
21199  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME24.c_str(), strlen(GATT_VAL24.c_str()),
21200  GATT_VAL24.c_str()))
21201  check_err(status, __LINE__, __FILE__);
21202  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME25.c_str(), strlen(GATT_VAL25.c_str()),
21203  GATT_VAL25.c_str()))
21204  check_err(status, __LINE__, __FILE__);
21205  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME26.c_str(), strlen(GATT_VAL26.c_str()),
21206  GATT_VAL26.c_str()))
21207  check_err(status, __LINE__, __FILE__);
21208  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME27.c_str(), strlen(GATT_VAL27.c_str()),
21209  GATT_VAL27.c_str()))
21210  check_err(status, __LINE__, __FILE__);
21211  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME28.c_str(), strlen(GATT_VAL28.c_str()),
21212  GATT_VAL28.c_str()))
21213  check_err(status, __LINE__, __FILE__);
21214  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME29.c_str(), strlen(GATT_VAL29.c_str()),
21215  GATT_VAL29.c_str()))
21216  check_err(status, __LINE__, __FILE__);
21217  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME30.c_str(), strlen(GATT_VAL30.c_str()),
21218  GATT_VAL30.c_str()))
21219  check_err(status, __LINE__, __FILE__);
21220  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME31.c_str(), strlen(GATT_VAL31.c_str()),
21221  GATT_VAL31.c_str()))
21222  check_err(status, __LINE__, __FILE__);
21223  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME32.c_str(), strlen(GATT_VAL32.c_str()),
21224  GATT_VAL32.c_str()))
21225  check_err(status, __LINE__, __FILE__);
21226  if (nc_put_att_text(ncid_out, NC_GLOBAL, GATT_NAME33.c_str(), strlen(GATT_VAL33.c_str()),
21227  GATT_VAL33.c_str()))
21228  check_err(status, __LINE__, __FILE__);
21229 
21230  //define groups check_err(status, __LINE__, __FILE__);
21231  if ((status = nc_def_grp(ncid_out, "geolocation_data", &grp_coor))) //netcdf-4
21232  check_err(status, __LINE__, __FILE__);
21233 /*
21234 //DEF DIMENSIONS
21235  if ((status = nc_def_dim(grp_coor, "x", NX, &x_dimid)))
21236  check_err(status, __LINE__, __FILE__);
21237  if ((status = nc_def_dim(grp_coor, "y", NY, &y_dimid)))
21238  check_err(status, __LINE__, __FILE__);
21239  dimids[0] = y_dimid;
21240  dimids[1] = x_dimid;
21241  NDIMS=2;
21242 */
21243  //def var
21244  if ((status = nc_def_var(grp_coor, "latitude", NC_FLOAT, NDIMS,
21245  dimids, &varid1)))
21246  check_err(status, __LINE__, __FILE__);
21247  if ((status = nc_def_var(grp_coor, "longitude", NC_FLOAT, NDIMS,
21248  dimids, &varid2)))
21249  check_err(status, __LINE__, __FILE__);
21250 
21251  //leave define mode-----------------------
21252  if ((status = nc_enddef(grp_coor))) //done def vars etc
21253  check_err(status, __LINE__, __FILE__);
21254 
21255  //writing the whole thing
21256  if ((status = nc_put_var_float(grp_coor, varid1, &lat_out[0][0])))
21257  check_err(status, __LINE__, __FILE__);
21258 
21259  if ((status = nc_put_var_float(grp_coor, varid2, &lon_out[0][0])))
21260  check_err(status, __LINE__, __FILE__);
21261 
21262 
21263 //define attributes of vars in groups
21264  if (nc_put_att_text(grp_coor, varid1, ATT_NAME.c_str(), strlen(ATT_VAL.c_str()), ATT_VAL.c_str()))
21265  check_err(status, __LINE__, __FILE__);
21266  if (nc_put_att_text(grp_coor, varid2, ATT_NAME.c_str(), strlen(ATT_VAL.c_str()), ATT_VAL.c_str()))
21267  check_err(status, __LINE__, __FILE__);
21268 
21269 
21270 
21271  if ((status = nc_close(ncid_out)))
21272  check_err(status, __LINE__, __FILE__);
21273 
21274 
21275  delete [] (lat_out);
21276  delete [] (lon_out);
21277  lat_out=nullptr;
21278  lon_out=nullptr;
21279 
21280 
21281 
21282 //******** save az_east param as nc ***************************************************************
21283 //az_east[count]
21284  prodstr="az_east";
21285  extstr = ".nc";
21286  fname_out = pathstr + ofilestr+"_"+ prodstr+extstr;
21287  filename_lt = fname_out.c_str();
21288  cout<<"creating file for az_east values in degrees as nc format.."<<filename_lt<<endl;
21289 // if ((status = nc_create(filename_lt, NC_CLOBBER, &ncid_out)))
21290  if ((status = nc_create(filename_lt, NC_CLOBBER | NC_NETCDF4, &ncid_out)))
21291  check_err(status, __LINE__, __FILE__);
21292  //define dims
21293  // Define the dimensions,vars and attributes at the root level
21294 
21295 
21296  //DEF DIMENSIONS
21297  if ((status = nc_def_dim(ncid_out, "bins_along_track", NY, &y_dimid)))
21298  check_err(status, __LINE__, __FILE__);
21299 //DEF VARIABLE
21300  if ((status = nc_def_var(ncid_out, "az_east", NC_FLOAT, 1,
21301  &y_dimid, &varid1)))
21302  check_err(status, __LINE__, __FILE__);
21303 
21304  if ((status = nc_enddef(ncid_out))) //done def vars etc
21305  check_err(status, __LINE__, __FILE__);
21306 
21307  for (int count = 0; count < num_gridlines - 2; count++) {
21308  if (az_east[count] < 0.001) az_east[count] = 0.0;}
21309  //writing the whole thing
21310  if ((status = nc_put_var_float(ncid_out, varid1, &az_east[0])))
21311  check_err(status, __LINE__, __FILE__);
21312 //close file
21313  if ((status = nc_close(ncid_out)))
21314  check_err(status, __LINE__, __FILE__);
21315 
21316 
21317 //***********************************************************************************************
21318  prodstr = "L1CgridV";
21319  extstr=".csv";
21320 
21321  fname_out = pathstr + ofilestr+"_"+ prodstr+extstr;
21322  // std::ofstream myl1c("/accounts/mamontes/images/OCIS/swt1_ALLgd_L1C500_swtd13again.csv");
21323  std::ofstream myl1cV(fname_out);
21324  // for(int count = 0; count <num_gridlines; count ++){
21325  /* for(int gp = 0; gp <nbinx/2; gp ++){
21326  if (loni_l[gp]<0.) loni_l[gp]+=360;
21327  if (loni_r[gp]<0.) loni_r[gp]+=360;
21328  myl1c << loni_l[gp] << ","<<lati_l[gp]<<endl;
21329  myl1c << loni_r[gp] << ","<<lati_r[gp]<<endl;}*/
21330 
21331  for (int count = 0; count < num_gridlines - 2;count++) {
21332  // for(int count = 0; count <num_gridlines/100;count ++){
21333  for (int gp = 0; gp < nbinx; gp++) {
21334  lontemp = lon_gd[count][gp];
21335  if (lon_gd[count][gp] < -180.) lontemp = lon_gd[count][gp] + 360;
21336  if (lon_gd[count][gp] > +180.) lontemp = lon_gd[count][gp] - 360;
21337  if (lontemp < 0.) lontemp += 360.;//make better visualization, all lon values positive
21338 
21339  myl1cV << lontemp << "," << lat_gd[count][gp] << endl;
21340  }
21341  }
21342 
21343 
21344  myl1cV.close();
21345 
21346 
21347  prodstr = "lat_nadpix";
21348  fname_out = pathstr + ofilestr+"_"+ prodstr+extstr;
21349  // fname_out= "/accounts/mamontes/images/OCIS/out/"+"L1Cgrid_"+"lat_nadpix"+"_"+swtstr+".txt";
21350  // ofstream myfile1 ("/accounts/mamontes/images/OCIS/lat_nadpix_swtd13again.txt");
21351  ofstream myfile1(fname_out);
21352  if (myfile1.is_open())
21353  {
21354  myfile1 << "lat_nadpix.\n";
21355  for (int count = 0; count < num_gridlines - 2; count++) {
21356  // for(int gp = 0; gp <nbinx; gp ++){
21357  myfile1 << lati2[count] << "," << endl;
21358  }
21359  myfile1.close();
21360  }
21361  else cout << "Unable to open file";
21362  prodstr = "lon_nadpix";
21363  fname_out = pathstr + ofilestr+"_"+ prodstr+extstr;
21364  // fname_out= "/accounts/mamontes/images/OCIS/out/"+"L1Cgrid_"+"lon_nadpix"+"_"+swtstr+".txt";
21365  // ofstream myfile2 ("/accounts/mamontes/images/OCIS/lon_nadpix_swtd13again.txt");
21366  ofstream myfile2(fname_out);
21367  if (myfile2.is_open())
21368  {
21369  myfile2 << "lon_nadpix.\n";
21370  for (int count = 0; count < num_gridlines - 2; count++) {
21371  // for(int gp = 0; gp <nbinx; gp ++){
21372  myfile2 << loni2[count] << "," << endl;
21373  }
21374  myfile2.close();
21375  }
21376  else cout << "Unable to open file";
21377 
21378  prodstr = "az_east";
21379  fname_out = pathstr + ofilestr+"_"+ prodstr+extstr;
21380 
21381  l1cfile->azeast_name = fname_out.c_str();
21382 
21383 
21384 
21385  // fname_out= "/accounts/mamontes/images/OCIS/out/"+"L1Cgrid_"+"lon_nadpix"+"_"+swtstr+".txt";
21386  // ofstream myfile2 ("/accounts/mamontes/images/OCIS/lon_nadpix_swtd13again.txt");
21387  ofstream myfile3(fname_out);
21388  if (myfile3.is_open())
21389  {
21390  myfile3 << "az_east.\n";
21391  for (int count = 0; count < num_gridlines - 2; count++) {
21392  if (az_east[count] < 0.001) az_east[count] = 0.0;
21393  myfile3 << az_east[count] << "," << endl;
21394  }
21395  myfile3.close();
21396  }
21397  else cout << "Unable to open file";
21398  if(lati_l!=nullptr)
21399  delete[](lati_l);
21400  if(lati_r!=nullptr)
21401  delete[](lati_r);
21402  if(loni_l!=nullptr)
21403  delete[](loni_l);
21404  if(loni_r!=nullptr)
21405  delete[](loni_r);
21406 
21407 
21408  cout << " SUCCESS writing results full L1C grid center positions for--swath #..." << swtd << "\n";
21409 
21410  return 0;
21411  }
21412 
21413 
21414 
21415 
21416 
21417 
21418 
21419 
21420  int32_t L1C::across_gridlines_l1c(int swtd, l1c_filehandle* l1cfile, L1C_input* l1cinput, int16_t* swtd_id, int16_t* file_id, int16_t* nfiles_swt, float* lati2, float* loni2, float** lat_gd, float** lon_gd, float* az_east) {
21421  int32_t num_gridlines, nbinx, NY1 = -1, NY2 = -1, c1 = 1;
21422  float lat1_l, lat1_r, lon1_l, lon1_r, lat2, lon2, az, dlambda, az_r, az_l, h, *lati_l, *loni_l, *lati_r, *loni_r, htot = 0.;
21423  int32_t NX, NY;
21424  int16_t selyear = -1, selmon = -1, selday = -1;
21425  double latih, lonih, latih2, lonih2, res1, res2;
21426  float gres;
21427  int fnan1, fnan2, fnan3, fnan4;
21428  float latfirst = -999;
21429  int badline = 0;
21430 
21431  Geodesic geod(Constants::WGS84_a(), Constants::WGS84_f());
21432 
21433  //compute azimuth angle for each along-track position (nadir pixel or centered swath pixel) of the swath
21434  //azimuth angle in rads
21435  //lon+540/360-180 is a normalization factor for -180 to 180 degrees
21436  num_gridlines = l1cfile->num_gridlines;
21437  num_pixels = l1cfile->npix;
21438  nbinx = l1cfile->nbinx;
21439  lati_l = (float*)malloc(nbinx / 2 * sizeof(float));
21440  lati_r = (float*)malloc(nbinx / 2 * sizeof(float));
21441  loni_l = (float*)malloc(nbinx / 2 * sizeof(float));
21442  loni_r = (float*)malloc(nbinx / 2 * sizeof(float));
21443 
21444 
21445 
21446 
21447  //big loop
21448 
21449  int gd = 0;
21450 
21451 
21452  //compute mean az_east---
21453  float sum = 0., tot = 0.;
21454  size_t azc = 0;
21455  for (int i = 0;i < num_gridlines - 1;i++) {
21456 
21457  //assign central positions---
21458  lat1_l = lati2[i] * M_PI / 180.;
21459  lat1_r = lati2[i] * M_PI / 180.;
21460  lat2 = lati2[i + 1] * M_PI / 180.;
21461  lon1_l = loni2[i] * M_PI / 180.;
21462  lon1_r = loni2[i] * M_PI / 180.;
21463  lon2 = loni2[i + 1] * M_PI / 180.;
21464 
21465  dlambda = (lon2 - lon1_l);
21466  //bearing---
21467  //make sure there are not NAN values ----------
21468  az = atan2(sin(dlambda) * cos(lat2), cos(lat1_l) * sin(lat2) - sin(lat1_l) * cos(lat2) * cos(dlambda));
21469 
21470  // cout<<lat2<<"..."<<lat1_l<<".."<<dlambda<<az*180/M_PI<<endl;
21471  if (az > M_PI || az < -M_PI) {
21472  cout << "problem with BEARING in across-gridline method...az<-180 or >180...." << "az in degrees.." << az * 180 / M_PI << endl;
21473  exit(1);
21474  }
21475  if (isnan(az) < 1) {
21476  // cout<<"az.."<<az<<"azcount"<<azc<<endl;
21477  az_r = (az + M_PI / 2.);
21478  az_east[i] = az_r * 180. / M_PI;
21479  if (az_east[i] < 0.0001 && az_east[i]>0) az_east[i] = 0.0;
21480  sum = az_east[i];
21481  tot += sum;
21482  azc++;
21483  }
21484  else {
21485  az_east[i] = NAN;
21486  }
21487  }
21488  float mean_az_east = tot / (azc);
21489  // float mean_az_east=tot/(num_gridlines-1);
21490  cout << "mean_az_east.." << mean_az_east << "numgridlines.." << num_gridlines << endl;
21491  // exit(1);
21492 
21493  for (int j = 0;j < num_gridlines - 1;j++) {
21494  az_east[j] = mean_az_east;
21495  }
21496 
21497  l1cfile->mean_az_east = mean_az_east;
21498 
21499  for (int i = 0;i < num_gridlines - 1;i++) {
21500 
21501  if (i % 1 == 0) {
21502  //assign central positions---
21503  lat1_l = lati2[i] * M_PI / 180.;
21504  lat1_r = lati2[i] * M_PI / 180.;
21505  lat2 = lati2[i + 1] * M_PI / 180.;
21506  lon1_l = loni2[i] * M_PI / 180.;
21507  lon1_r = loni2[i] * M_PI / 180.;
21508  lon2 = loni2[i + 1] * M_PI / 180.;
21509 
21510  dlambda = (lon2 - lon1_l);
21511 
21512  /* deltaphi=(lati2[i]-lati2[i+1])*degrad;
21513  deltalam=(loni2[i]-loni2[i+1])*degrad;
21514  aterm=sin(deltaphi/2)*sin(deltaphi/2)+cos(lati2[i]*degrad)*cos(lati2[i+1]*degrad)*sin(deltalam/2)*sin(deltalam/2);
21515  bterm=2*atan2(sqrt(aterm),sqrt(1-aterm));
21516  dist=Re*bterm;
21517  cout<<dist<<endl;
21518  */
21519 
21520 
21521  gres = (l1cinput->gres) * 1000; //grid resolution in meters
21522 
21523  // geod.Inverse(lati2[i], loni2[i], lati2[i+1], loni2[i+1], s12);
21524  // cout << s12 << "\n";
21525 
21526  //bearing---
21527  //this is Harverside--law f cosines is more accurate---
21528  az = atan2(sin(dlambda) * cos(lat2), cos(lat1_l) * sin(lat2) - sin(lat1_l) * cos(lat2) * cos(dlambda));
21529  if (az > M_PI | az < -M_PI) {
21530  cout << "problem with BEARING in across-gridline method...az<-180 or >180...." << "az in degrees.." << az * 180 / M_PI << endl;
21531  exit(1);
21532  }
21533 
21534  //compute RIGHT across-gridline pixels---
21535 
21536  for (int k = 0;k < (nbinx / 2);k++) {
21537  h = (l1cinput->gres);//distance between along positions in km, must be 5.2 k m for L1C
21538  if (k == 0) h /= 2;//if nadpix
21539  htot += h;
21540 
21541  //right pixels---
21542  az_r = mean_az_east * degrad;
21543 
21544 
21545  // az_r=(az+M_PI/2.);
21546  // az_east[i]=az_r*180./M_PI;
21547  // if(az_east[i]<0.001) az_east[i]=0.0;//this is important later on to avoid issues when converting string to double
21548 
21549  //left pixels---
21550 
21551  az_l = az_r - M_PI;
21552  // az_l=(az-M_PI/2.);//this should be equal to az_r+M_PI=az_l
21553 
21554  //bearing should be always positive (clockwise) before pixel location calculation based on Harverside---
21555  if (az_r < 0.) {
21556  az_r = 360 + az_r * 180 / M_PI;
21557  az_r = az_r * M_PI / 180;
21558  }
21559 
21560  if (az_l < 0.) {
21561  az_l = 360 + az_l * 180 / M_PI;
21562  az_l = az_l * M_PI / 180;
21563  }
21564  // ad = (h / Re);
21565  //right side--Harversine
21566  /* lati_r[k]=asin(sin(lat1_r)*cos(ad)+cos(lat1_r)*sin(ad)*cos(az_r))*180./M_PI;
21567  loni_r[k]=lon1_r*180./M_PI+atan2(sin(az_r)*sin(ad)*cos(lat1_r),cos(ad)-sin(lat1_r)*sin(lati_r[k]*M_PI/180.))*180./M_PI;
21568  */
21569  geod.Direct(lat1_r * 180 / M_PI, lon1_r * 180 / M_PI, az_r * 180 / M_PI, gres, latih, lonih);
21570  geod.Inverse(lat1_r * 180 / M_PI, lon1_r * 180 / M_PI, latih, lonih, res1);
21571  fnan1 = isnan(latih);
21572  fnan2 = isnan(lonih);
21573  lati_r[k] = latih;
21574  loni_r[k] = lonih;
21575  // cout<<"righside.."<<latih<<"..."<<lonih<<"res1"<<res1<<endl;
21576 
21577  lat1_r = lati_r[k] * M_PI / 180;
21578  lon1_r = loni_r[k] * M_PI / 180;
21579 
21580  //left side-Harversine
21581  /* lati_l[k]=asin(sin(lat1_l)*cos(ad)+cos(lat1_l)*sin(ad)*cos(az_l))*180./M_PI;
21582  loni_l[k]=lon1_l*180./M_PI+atan2(sin(az_l)*sin(ad)*cos(lat1_l),cos(ad)-sin(lat1_l)*sin(lati_l[k]*M_PI/180.))*180./M_PI;
21583  */
21584  geod.Direct(lat1_l * 180 / M_PI, lon1_l * 180 / M_PI, az_l * 180 / M_PI, gres, latih2, lonih2);
21585  geod.Inverse(lat1_l * 180 / M_PI, lon1_l * 180 / M_PI, latih2, lonih2, res2);
21586  fnan3 = isnan(latih2);
21587  fnan4 = isnan(lonih2);
21588  lati_l[k] = latih2;
21589  loni_l[k] = lonih2;
21590  // cout<<"leftside.."<<latih2<<"..."<<lonih2<<"res2"<<res2<<endl;
21591 
21592  lat1_l = lati_l[k] * M_PI / 180;
21593  lon1_l = loni_l[k] * M_PI / 180;
21594 
21595 
21596  // cout<<"gd.."<<gd+1<<"gd.."<<gd+1<<lati_r[k].."<<lati_l[k]"<<lati_l[k]<<"loni_l[k]"<<loni_l[k]<<"lati_r[k]"<<lati_r[k]<<"loni_r[k]"<<loni_r[k]<<endl;
21597 
21598  //left side
21599  // lat_gd[gd][nbinx/2-1-k]=lati_l[k];//as k increases we are farther away from nadpix or along-track position---
21600  // lon_gd[gd][nbinx/2-1-k]=loni_l[k];
21601 
21602  //right swath side--------------
21603  // lat_gd[gd][k+nbinx/2]=lati_r[k];
21604  // lon_gd[gd][k+nbinx/2]=loni_r[k];
21605 
21606  //right swath side-------------
21607 
21608 
21609  if (fnan1 > 0 || fnan2 > 0 || res1 > (gres + 6) || res1 < (gres - 6) || lati2[i + 1] < lati2[i] || lati2[i] < latfirst) { //nan values
21610  // if(fnan1>0 | fnan2>0 | res1>(gres+6) | res1<(gres-6)){
21611  badline++;
21612  if (badline == 1) {
21613  latfirst = lati2[i];
21614  }
21615 
21616  cout << "bad interpolation - missing orbital data..deleteing right side of line.." << i + 1 << latfirst << endl;
21617  lati2[i] = NAN;
21618  loni2[i] = NAN;
21619 
21620  for (int k = 0;k < (nbinx / 2);k++) {
21621  lat_gd[gd][k + nbinx / 2] = NAN;
21622  lon_gd[gd][k + nbinx / 2] = NAN;
21623  }
21624  // cout<<"nan value.right.."<<endl;
21625  }
21626  else {
21627  lat_gd[gd][k + nbinx / 2] = latih;
21628  lon_gd[gd][k + nbinx / 2] = lonih;
21629 }
21630 
21631  //left side
21632  if (fnan3 > 0 || fnan4 > 0 || res2 > (gres + 6) || res2 < (gres - 6) || lati2[i + 1] < lati2[i] || lati2[i] < latfirst) {
21633  // if(fnan3>0 | fnan4>0 | res2>(gres+6) | res2<(gres-6)){
21634  cout << "bad interpolation - missing orbital data..deleteing left side of line.." << i + 1 << endl;
21635  lati2[i] = NAN;
21636  loni2[i] = NAN;
21637  for (int k = 0;k < (nbinx / 2);k++) {
21638  lat_gd[gd][nbinx / 2 - 1 - k] = NAN;//as k increases we are farther away from nadpix or along-track position---
21639  lon_gd[gd][nbinx / 2 - 1 - k] = NAN;
21640 }
21641  // cout<<"nan value.left.."<<endl;
21642  }
21643  else {
21644  lat_gd[gd][nbinx / 2 - 1 - k] = latih2;//as k increases we are farther away from nadpix or along-track position---
21645  lon_gd[gd][nbinx / 2 - 1 - k] = lonih2;
21646 }
21647 
21648 
21649  /* float longd,latgd,latgd2,longd2;
21650  latgd=lat_gd[gd][nbinx/2-1-k];
21651  longd=lon_gd[gd][nbinx/2-1-k];
21652  latgd2=lat_gd[gd][nbinx/2-1-k+1];
21653  longd2=lon_gd[gd][nbinx/2-1-k+1];
21654 
21655  geod.Inverse(latgd,longd,latgd2,longd2, s12);
21656  cout <<latgd<<"..."<<latgd2<<"s12..left"<< s12 << "\n";
21657  cout <<longd<<"..."<<longd2<< "\n";
21658  cout<<s12<<endl;
21659 
21660  latgd=lat_gd[gd][k+nbinx/2];
21661  longd=lon_gd[gd][k+nbinx/2];
21662  latgd2=lat_gd[gd][k+nbinx/2+1];
21663  longd2=lon_gd[gd][k+nbinx/2+1];
21664  geod.Inverse(latgd,longd,latgd2,longd2, s12);
21665  cout <<latgd<<"..."<<latgd2<<"s12..right"<< s12 << "\n";
21666  cout <<longd<<"..."<<longd2<< "\n";
21667  cout<<s12<<endl;
21668  */
21669  }//end pixel loop
21670  // exit(1);
21671 
21672  htot = 0;
21673  gd++;
21674  }//end if every 100 gd
21675  }//end gridlines loop
21676  cout << "`L1C gridding successful!......................................." << endl;
21677  //write results-----
21678 
21679  float lontemp = 0.;
21680  selday = l1cinput->selday;
21681  selmon = l1cinput->selmon;
21682  selyear = l1cinput->selyear;
21683 
21684  std::string fname_out, pathstr, senstr, monstr, daystr, yearstr, prodstr, gdstr, swtstr, swtnum, extstr;
21685  pathstr = "out/";
21686  senstr = "OCIS_";
21687  monstr = std::to_string(selmon);
21688  daystr = std::to_string(selday);
21689  yearstr = std::to_string(selyear);
21690  prodstr = "L1Cgrid";
21691  // gdstr="_gdFULL_";
21692  swtstr = "_swt";
21693 
21694  if (l1cfile->l1c_pflag >= 3) {
21695  swtd = l1cfile->swtnum;
21696  swtnum = std::to_string(swtd);
21697  cout << "swtnum.." << swtnum << endl;
21698  }
21699  else swtnum = std::to_string(swtd);
21700 
21701  extstr = ".csv";
21702  fname_out = pathstr + senstr + monstr + daystr + yearstr + prodstr + swtstr + swtnum + extstr;
21703 
21704 
21705  l1cfile->gridname = fname_out.c_str();
21706  std::ofstream myl1c(fname_out);
21707 
21708  myl1c << "lon_gd" << "," << "lat_gd" << endl;
21709  for (int count = 0; count < num_gridlines - 1;count++) {
21710  for (int gp = 0; gp < nbinx; gp++) {
21711  /* if(count<num_gridlines-2 & lat_gd[count][nadpix]>lat_gd[count+1][nadpix])
21712  {
21713  cout<<"lat is not increasing north..........."<<endl;
21714  for(int gp = 0; gp <nbinx; gp ++){
21715  lat_gd[count][gp]=NAN;
21716  lon_gd[count][gp]=NAN;
21717  myl1c << lon_gd[count][gp] << ","<<lat_gd[count][gp]<<endl;
21718  }
21719 
21720  }
21721  else
21722  */
21723  myl1c << lon_gd[count][gp] << "," << lat_gd[count][gp] << endl;
21724  // cout<<"gd"<<count+1<<"gp"<<gp+1<<"lat_gd[count][gp]"<<lat_gd[count][gp]<<"lon_gd[count][gp]"<<lon_gd[count][gp]<<endl;
21725 
21726  /* deltaphi=(lat_gd[count][gp]-lat_gd[count][gp+1])*degrad;
21727  deltalam=(lon_gd[count][gp]-lon_gd[count][gp+1])*degrad;
21728  //across-track grid size
21729  aterm=sin(deltaphi/2)*sin(deltaphi/2)+cos(lat_gd[count][gp]*degrad)*cos(lat_gd[count][gp+1]*degrad)*sin(deltalam/2)*sin(deltalam/2);
21730  bterm=2*atan2(sqrt(aterm),sqrt(1-aterm));
21731  dist_u=Re*bterm;
21732  cout<<dist_u<<endl;*/
21733  }//end pixels
21734  // exit(1);
21735  } //end lines
21736  myl1c.close();
21737 
21738 
21739  //****************************************************************
21740  //lat lon grid for visualization--
21741  prodstr = "L1CgridV";
21742 
21743  fname_out = pathstr + senstr + monstr + daystr + yearstr + prodstr + gdstr + swtstr + swtnum + extstr;
21744  // std::ofstream myl1c("/accounts/mamontes/images/OCIS/swt1_ALLgd_L1C500_swtd13again.csv");
21745  std::ofstream myl1cV(fname_out);
21746  // for(int count = 0; count <num_gridlines; count ++){
21747  /* for(int gp = 0; gp <nbinx/2; gp ++){
21748  if (loni_l[gp]<0.) loni_l[gp]+=360;
21749  if (loni_r[gp]<0.) loni_r[gp]+=360;
21750  myl1c << loni_l[gp] << ","<<lati_l[gp]<<endl;
21751  myl1c << loni_r[gp] << ","<<lati_r[gp]<<endl;}*/
21752 
21753  for (int count = 0; count < num_gridlines - 1;count++) {
21754  // for(int count = 0; count <num_gridlines/100;count ++){
21755  for (int gp = 0; gp < nbinx; gp++) {
21756  lontemp = lon_gd[count][gp];
21757  if (lon_gd[count][gp] < -180.) lontemp = lon_gd[count][gp] + 360;
21758  if (lon_gd[count][gp] > +180.) lontemp = lon_gd[count][gp] - 360;
21759  if (lontemp < 0.) lontemp += 360.;//make better visualization, all lon values positive
21760 
21761  myl1cV << lontemp << "," << lat_gd[count][gp] << endl;
21762 }
21763 }
21764 
21765 
21766  myl1cV.close();
21767 
21768 
21769  prodstr = "lat_nadpix";
21770  fname_out = pathstr + senstr + monstr + daystr + yearstr + prodstr + swtstr + swtnum + extstr;
21771  // fname_out= "/accounts/mamontes/images/OCIS/out/"+"L1Cgrid_"+"lat_nadpix"+"_"+swtstr+".txt";
21772  // ofstream myfile1 ("/accounts/mamontes/images/OCIS/lat_nadpix_swtd13again.txt");
21773  ofstream myfile1(fname_out);
21774  if (myfile1.is_open())
21775  {
21776  myfile1 << "lat_nadpix.\n";
21777  for (int count = 0; count < num_gridlines - 1; count++) {
21778  // for(int gp = 0; gp <nbinx; gp ++){
21779  myfile1 << lati2[count] << "," << endl;
21780  }
21781  myfile1.close();
21782  }
21783  else cout << "Unable to open file";
21784  prodstr = "lon_nadpix";
21785  fname_out = pathstr + senstr + monstr + daystr + yearstr + prodstr + swtstr + swtnum + extstr;
21786  // fname_out= "/accounts/mamontes/images/OCIS/out/"+"L1Cgrid_"+"lon_nadpix"+"_"+swtstr+".txt";
21787  // ofstream myfile2 ("/accounts/mamontes/images/OCIS/lon_nadpix_swtd13again.txt");
21788  ofstream myfile2(fname_out);
21789  if (myfile2.is_open())
21790  {
21791  myfile2 << "lon_nadpix.\n";
21792  for (int count = 0; count < num_gridlines - 1; count++) {
21793  // for(int gp = 0; gp <nbinx; gp ++){
21794  myfile2 << loni2[count] << "," << endl;
21795  }
21796  myfile2.close();
21797  }
21798  else cout << "Unable to open file";
21799 
21800  prodstr = "az_east";
21801  fname_out = pathstr + senstr + monstr + daystr + yearstr + prodstr + swtstr + swtnum + extstr;
21802 
21803  l1cfile->azeast_name = fname_out.c_str();
21804 
21805 
21806 
21807  // fname_out= "/accounts/mamontes/images/OCIS/out/"+"L1Cgrid_"+"lon_nadpix"+"_"+swtstr+".txt";
21808  // ofstream myfile2 ("/accounts/mamontes/images/OCIS/lon_nadpix_swtd13again.txt");
21809  ofstream myfile3(fname_out);
21810  if (myfile3.is_open())
21811  {
21812  myfile3 << "az_east.\n";
21813  for (int count = 0; count < num_gridlines - 1; count++) {
21814  if (az_east[count] < 0.001) az_east[count] = 0.0;
21815  myfile3 << az_east[count] << "," << endl;
21816  }
21817  myfile3.close();
21818  }
21819  else cout << "Unable to open file";
21820  if(lati_l!=nullptr)
21821  delete[](lati_l);
21822  if(lati_r!=nullptr)
21823  delete[](lati_r);
21824  if(loni_l!=nullptr)
21825  delete[](loni_l);
21826  if(loni_r!=nullptr)
21827  delete[](loni_r);
21828 
21829  //recompute number of gridlines based on lat limits -80 to 80 degrees
21830  //asc orbit goes from negative to positive latitude....
21831  NY = num_gridlines;
21832  NX = nbinx;
21833 
21834  for (int i = 0; i < NY; i++) {
21835  for (int j = 0; j < NX; j++) {
21836  if (lat_gd[i][j] >= -80.) c1++;
21837  if (c1 == nbinx) {
21838  NY1 = i;
21839  }
21840  }
21841  if (NY1 >= 0) break;
21842  c1 = 1;
21843  }
21844 
21845  for (int i = 0;i < NY; i++) {
21846  for (int j = 0; j < NX; j++) {
21847  if (lat_gd[i][j] >= 80.) {
21848  NY2 = i - 1;
21849  }
21850  }
21851  if (NY2 >= 0) break;
21852  }
21853 
21854  l1cfile->NY1 = NY1;
21855  l1cfile->NY2 = NY2;
21856 
21857  NY = NY2 - NY1 + 1;
21858 
21859  cout << " SUCCESS writing results full L1C grid center positions for--swath #..." << swtd << "\n";
21860 
21861  return 0;
21862  }
21863 
21864 
21865 
21866 
21867 //si plified version of interp_swt_dist2
21868 int32_t L1C::interp_swt_dist_vec(int swtd, l1c_filehandle* l1cfile, L1C_input* l1cinput, double* time_mgv, float* lati, float* loni, float* lati2, float* loni2) {
21869  std::string str,pathstr,filestr,ofilestr;
21870  int32_t num_gridlines = 0;//4000 gridlines at 5.2 km and 8000 at 2.6 km resolution
21871  float res = 0;
21872  double s12;
21873  float mean_az_east;
21874  float az_track, thre;
21875  double newlat, newlon;
21876  Geodesic geod(Constants::WGS84_a(), Constants::WGS84_f());
21877  //compute delta-t for each each swath daytime--
21878  num_gridlines = l1cfile->num_gridlines;
21879  res = (l1cinput->gres);
21880  mean_az_east = l1cfile->mean_az_east;//mean azimuth in degrees
21881 
21882  if(mean_az_east<-180){cout<<"ERROR mean_az_east should be >=-180..."<<mean_az_east<<endl; exit(1);}
21883  az_track = mean_az_east - 90;
21884  thre = 0.02;//thres error in km
21885 
21886  for (int j = 0;j < num_gridlines;j++) {
21887  lati2[j]=lati[j];
21888  loni2[j]=loni[j];
21889  }
21890 
21891 
21892 
21893  //solution inestable at gd 3839
21894  lati2[0]=lati[0];
21895  loni2[0]=loni[0];
21896 // newlat=lati2[0];
21897 // newlon=loni2[0];
21898 
21899  for (int j = 1;j < num_gridlines-1;j++) {
21900  s12=0;
21901  geod.Inverse(lati2[j], loni2[j], lati2[j + 1], loni2[j + 1], s12);//s12 in m
21902  s12 = s12 / 1000;
21903 
21904  if (s12 > (res + thre) | s12 < (res - thre)) {
21905  geod.Direct(lati[j], loni[j], az_track, res * 1000, newlat, newlon);
21906  // geod.Direct(newlat,newlon, az_track, res * 1000, newlat, newlon);
21907 
21908 // lati2[j] = newlat;
21909 // loni2[j] = newlon;
21910  lati2[j+1] = newlat;
21911  loni2[j+1] = newlon;
21912 
21913  cout<<"gd#.."<<j+1<<"corrected s12.."<<s12<<"lati2.."<<lati2[j]<<"loni2.."<<loni2[j]<<endl;
21914  }
21915 
21916  if (isnan(s12) == 1) { cout << "no convergence for s12" << endl;exit(1); }
21917 
21918  }
21919 
21920 /*
21921  for (int j = 0;j < num_gridlines - 1;j++) {
21922  s12=0;
21923  geod.Inverse(lati2[j], loni2[j], lati2[j + 1], loni2[j + 1], s12);
21924  cout<<"gd#.."<<j+1<<"corrected s12.."<<s12<<"lati2.."<<lati2[j]<<"loni2.."<<loni2[j]<<endl;
21925  }
21926 */
21927 
21928 
21929 
21930  cout << "L1C::interp_swt_dist2.. second interpolation (distance along-track gridpoints)..." << "swath #.." << swtd << "\n";
21931  //-------------------------------------------------------------------------------------------------------------
21932  //writing results---only nadir pixels---
21933  cout << " writing results second interpolation--swath #..." << swtd << "\n";
21934  ofilestr=std::string(l1cinput->ofile);
21935  filestr="lat2_dist.txt";
21936  pathstr="out/"+ofilestr+"_"+filestr;
21937 
21938  ofstream myfile1(pathstr);
21939 
21940  if (myfile1.is_open())
21941  {
21942  myfile1 << "lat2_dist.\n";
21943  for (int count = 0; count < num_gridlines-1; count++) {
21944  myfile1 << lati2[count] << "," << endl;
21945  }
21946  myfile1.close();
21947  }
21948  else cout << "Unable to open lat2_dist.txt file";
21949 
21950 //----------------------------------------------------------------------------------------
21951  filestr="lon2_dist.txt";
21952  pathstr="out/"+ofilestr+"_"+filestr;
21953  ofstream myfile2(pathstr);
21954 
21955  if (myfile2.is_open())
21956  {
21957  myfile2 << "lon2_dist.\n";
21958  for (int count = 0; count < num_gridlines-1; count++) {
21959  myfile2 << loni2[count] << "," << endl;
21960  }
21961  myfile2.close();
21962  }
21963  else cout << "Unable to open lon2_dist.txt file";
21964 
21965 
21966  exit(1);
21967 
21968  return 0;
21969  }
21970 
21971 
21972 
21973 
21974 //for the vector version -telemetry files L1A
21975 int32_t L1C::interp_swt_dist3(int swtd, l1c_filehandle* l1cfile, L1C_input* l1cinput, int16_t* swtd_id, int16_t* file_id, int16_t* nfiles_swt, double* time_mgv, float* lati, float* loni, float* lati2, float* loni2) {
21976  std::string str,pathstr,filestr,ofilestr;
21977  int32_t num_gridlines = 0;//4000 gridlines at 5.2 km and 8000 at 2.6 km resolution
21978  float res = 0;
21979  double s12;
21980  float mean_az_east;
21981  float az_track, thre;
21982  double newlat, newlon;
21983  Geodesic geod(Constants::WGS84_a(), Constants::WGS84_f());
21984  //compute delta-t for each each swath daytime--
21985  num_gridlines = l1cfile->num_gridlines;
21986  res = (l1cinput->gres);
21987 
21988 
21989  mean_az_east = l1cfile->mean_az_east;
21990  if(mean_az_east<-180){cout<<"ERROR mean_az_east should be >=-180..."<<mean_az_east<<endl; exit(1);}
21991 
21992  az_track = mean_az_east - 90;
21993  thre = 0.0;
21994 
21995  thre = 0.02;//thres error in km
21996 
21997  for (int j = 0;j < num_gridlines;j++) {
21998  lati2[j]=lati[j];
21999  loni2[j]=loni[j];
22000  }
22001 
22002 
22003  for (int j = 0;j < num_gridlines-1;j++) {
22004  s12=0;
22005  geod.Inverse(lati2[j], loni2[j], lati2[j + 1], loni2[j + 1], s12);//s12 in m
22006  s12 = s12 / 1000;
22007 
22008  if (s12 > (res + thre) | s12 < (res - thre)) {
22009  geod.Direct(lati[j], loni[j], az_track, res * 1000, newlat, newlon);
22010 
22011  lati2[j+1] = newlat;
22012  loni2[j+1] = newlon;
22013 
22014 
22015  // cout<<"gd.."<<j+1<<endl;
22016  }
22017 
22018  if (isnan(s12) == 1) { cout << "no convergence for s12" << endl;exit(1); }
22019 
22020  }
22021 
22022 
22023  cout << "L1C::interp_swt_dist2.. second interpolation (distance along-track gridpoints)..." << "swath #.." << swtd << "\n";
22024  //-------------------------------------------------------------------------------------------------------------
22025  //writing results---only nadir pixels---
22026  cout << " writing results second interpolation--swath #..." << swtd << "\n";
22027  ofilestr=std::string(l1cinput->ofile);
22028  filestr="lat2_dist.txt";
22029  pathstr="out/"+ofilestr+"_"+filestr;
22030 
22031  ofstream myfile1(pathstr);
22032 
22033  if (myfile1.is_open())
22034  {
22035  myfile1 << "lat2_dist.\n";
22036  for (int count = 0; count < num_gridlines-1; count++) {
22037  myfile1 << lati2[count] << "," << endl;
22038  }
22039  myfile1.close();
22040  }
22041  else cout << "Unable to open lat2_dist.txt file";
22042 
22043 //----------------------------------------------------------------------------------------
22044  filestr="lon2_dist.txt";
22045  pathstr="out/"+ofilestr+"_"+filestr;
22046  ofstream myfile2(pathstr);
22047 
22048  if (myfile2.is_open())
22049  {
22050  myfile2 << "lon2_dist.\n";
22051  for (int count = 0; count < num_gridlines-1; count++) {
22052  myfile2 << loni2[count] << "," << endl;
22053  }
22054  myfile2.close();
22055  }
22056  else cout << "Unable to open lon2_dist.txt file";
22057 
22058 
22059  return 0;
22060  }
22061 
22062 
22063 
22064 
22065 int32_t L1C::interp_swt_dist2(int swtd, l1c_filehandle* l1cfile, L1C_input* l1cinput, int16_t* swtd_id, int16_t* file_id, int16_t* nfiles_swt, double* time_mgv, float* lati, float* loni, float* lati2, float* loni2) {
22066  std::string str,pathstr,filestr,ofilestr;
22067  int32_t num_gridlines = 0;//4000 gridlines at 5.2 km and 8000 at 2.6 km resolution
22068  float res = 0;
22069  double* dist_a, * dist_ai, s12;
22070  float mean_az_east;
22071  float az_track, thre;
22072  double newlat, newlon;
22073 
22074  Geodesic geod(Constants::WGS84_a(), Constants::WGS84_f());
22075  //compute delta-t for each each swath daytime--
22076  num_gridlines = l1cfile->num_gridlines;
22077  res = (l1cinput->gres);
22078  dist_a = (double*)malloc(num_gridlines * sizeof(double));
22079  dist_ai = (double*)malloc(num_gridlines * sizeof(double));
22080 
22081 
22082  mean_az_east = l1cfile->mean_az_east;
22083  if(mean_az_east<-180){cout<<"ERROR mean_az_east should be >=-180..."<<mean_az_east<<endl; exit(1);}
22084  az_track = mean_az_east - 90;
22085  thre = 0.03;
22086 
22087 
22088 
22089  for (int j = 0;j < num_gridlines;j++) {
22090  dist_a[j] = 0.;
22091  dist_ai[j] = 0.;
22092  // cout<<"gd"<<j+1<<"lati..."<<lati[j]<<"loni..."<<loni[j]<<endl;
22093  }
22094 
22095  double tot1, tot2;
22096 
22097  for (int j = 0;j < num_gridlines - 2;j++) {
22098  tot1 += res;//res in km
22099  dist_a[j] = tot1;
22100  geod.Inverse(lati[j], loni[j], lati[j + 1], loni[j + 1], s12);//s12 in m
22101  s12 = s12 / 1000;
22102  tot2 += s12;
22103  if (s12 > (res + thre) | s12 < (res - thre)) {
22104  geod.Direct(lati[j], loni[j], az_track, res * 1000, newlat, newlon);
22105  lati2[j] = newlat;
22106  loni2[j] = newlon;
22107  // cout<<"gd#..."<<j+1<<"lati2...."<<lati2[j]<<"s12..."<<s12<<"res.."<<res<<endl;
22108  }
22109  else {
22110  lati2[j] = lati[j];
22111  loni2[j] = loni[j];
22112  }
22113 
22114  if (isnan(s12) == 1) { cout << "no convergence for s12" << endl;exit(1); }
22115 
22116 // cout<<"gd#..."<<j+1<<"lati2...."<<lati2[j]<<"s12..."<<s12<<"res.."<<res<<endl;
22117  }
22118 
22119 
22120  // dist_ai[j]=tot2;//increasing distance similar to time, important for interpolation
22121  // cout<<s12<<endl;
22122  // cout<<lati[j]<<endl;
22123 
22124  // cout<<"gd.."<<j+1<<"dista.."<<dist_a[j]<<"distai.."<<dist_ai[j]<<endl;
22125  // if(isnan(s12)==1){ cout<<"no convergence for s12"<<endl;exit(1);}
22126  // }
22127 
22128  // exit(1);
22129 
22130  cout << "L1C::interp_swt_dist2.. second interpolation (distance along-track gridpoints)..." << "swath #.." << swtd << "\n";
22131 
22132 
22133  /*
22134  latlon_interp_dist(num_gridlines,dist_ai,lati,loni,dist_a,lati2,loni2);
22135 
22136  cout<<"checking for badlines................"<<endl;
22137  int badline=0,fnan1,jini,jend,npoints,c;
22138  float latfirst=-999,latlast=-999,dlat,dlon,lonfirst,lonlast;
22139  std::vector<int16_t> badindex;
22140 
22141  for(int j=0;j<num_gridlines-1;j++){
22142  // cout<<"gdindex"<<j<<"lati2..."<<lati2[j]<<"loni2..."<<loni2[j]<<endl;
22143  //checking that s12 is 5200 m resolutioni????
22144  geod.Inverse(lati2[j], loni2[j], lati2[j+1], loni2[j+1], s12);
22145  fnan1=isnan(s12);
22146 
22147  // cout<<"gd.."<<j+1<<s12<<endl;
22148  // cout<<lati2[j]<<endl;
22149  // cout<<"fnan.."<<fnan1<<"j.."<<j<<endl;
22150  //time interpolation of lat/lon rather than distance interpolation
22151 
22152  if(fnan1>0 | lati2[j+1]<lati2[j]){ //assuming ascending orbit
22153  badline++;
22154  if(badline==1){
22155  latfirst=lati2[j];
22156  lonfirst=loni2[j];
22157  jini=j;
22158  }
22159  }
22160 
22161  if (fnan1>0 | latfirst>-999 & lati2[j]>latfirst){
22162  latlast=lati2[j];
22163  lonlast=loni2[j];
22164  jend=j;
22165  // cout<<"fnan.."<<fnan1<<"j.."<<j<<"lati2[j].."<<lati2[j]<<"latfirst"<<latfirst<<"latlast"<<latlast<<endl;
22166  }
22167  if(latlast>-999){
22168  j=num_gridlines-1;
22169  break;}
22170  }//endgridlines
22171 
22172  //gd points to interpolate
22173  npoints=jend-jini+1;
22174  dlat=(latlast-latfirst)/npoints;
22175  if(lonfirst<0) lonfirst+=360;
22176  if(lonlast<0) lonlast+=360;
22177  dlon=(lonfirst-lonlast)/npoints;
22178 
22179  c=1;
22180  for(int j=jini+1;j<jend;j++){
22181  lati2[j]=lati2[jini]+dlat*c;
22182  loni2[j]=loni2[jini]-dlon*c;
22183  c++;
22184  }
22185  cout<<"npoints.."<<npoints<<"dlat.."<<dlat<<"dlon"<<dlon<<"jini"<<jini<<"jend"<<jend<<endl;
22186  cout<<"latfirst"<<latfirst<<"latpast"<<latlast<<"lonfirst"<<lonfirst<<"lonpast"<<lonlast<<endl;
22187 
22188 
22189  for(int j=0;j<num_gridlines-1;j++){
22190  if(loni2[j]<0) lontemp=loni2[j]+360;else lontemp=loni2[j];
22191  if(loni2[j+1]<0) lontemp2=loni2[j+1]+360;else lontemp2=loni2[j+1];
22192 
22193  // cout<<"gdindex.."<<j<<"lati2.."<<lati2[j]<<"loni2.."<<loni2[j]<<endl;
22194  if(lati2[j+1]<lati2[j] | lontemp2>lontemp & j<num_gridlines-2){
22195  cout<<"spatial interpolation...still issues lati2[j+1]<lati2[j] "<<"j"<<j<<endl;
22196  cout<<"lati2.."<<lati2[j]<<"lati2 j+1.."<<lati2[j+1]<<"loni2..."<<loni2[j]<<"loni2 j+1.."<<loni2[j+1]<<endl;
22197 
22198  }
22199  if(lontemp2>lontemp & j<num_gridlines-2){
22200  cout<<"spatial interpolation....still issues lontemp2>lontemp"<<"j"<<j<<endl;
22201  cout<<"lati2.."<<lati2[j]<<"lati2 j+1.."<<lati2[j+1]<<"loni2..."<<loni2[j]<<"loni2 j+1.."<<loni2[j+1]<<endl;
22202  }
22203 
22204  }
22205 
22206  // exit(1);
22207  // cout<<"latfirst"<<latfirst<<"latlast"<<latlast<<endl;
22208 
22209 
22210  // cout<<"flat..."<<flat<<"flon"<<flon<<"llat"<<llat<<"llon"<<llon<<endl;
22211 
22212  */
22213 
22214 //-------------------------------------------------------------------------------------------------------------
22215  //writing results---only nadir pixels---
22216  cout << " writing results second interpolation--swath #..." << swtd << "\n";
22217  ofilestr=std::string(l1cinput->ofile);
22218  filestr="lat2_dist.txt";
22219  pathstr="out/"+ofilestr+"_"+filestr;
22220 
22221  ofstream myfile1(pathstr);
22222 
22223  if (myfile1.is_open())
22224  {
22225  myfile1 << "lat2_dist.\n";
22226  for (int count = 0; count < num_gridlines-2; count++) {
22227  myfile1 << lati2[count] << "," << endl;
22228  }
22229  myfile1.close();
22230  }
22231  else cout << "Unable to open lat2_dist.txt file";
22232 
22233 //----------------------------------------------------------------------------------------
22234  filestr="lon2_dist.txt";
22235  pathstr="out/"+ofilestr+"_"+filestr;
22236  ofstream myfile2(pathstr);
22237 
22238  if (myfile2.is_open())
22239  {
22240  myfile2 << "lon2_dist.\n";
22241  for (int count = 0; count < num_gridlines-2; count++) {
22242  myfile2 << loni2[count] << "," << endl;
22243  }
22244  myfile2.close();
22245  }
22246  else cout << "Unable to open lon2_dist.txt file";
22247 
22248  if (dist_a != NULL)
22249  delete[](dist_a);
22250  if (dist_ai != NULL)
22251  delete[](dist_ai);
22252 
22253 
22254  // exit(1);
22255 
22256  return 0;
22257  }
22258 
22259 
22260 
22261 
22262 int32_t L1C::interp_swt1(int swtd, l1c_filehandle* l1cfile, L1C_input* l1cinput,int16_t* swtd_id, int16_t* file_id, int16_t* nfiles_swt, double* time_mgv, orb_array* velig, float* lati, float* loni) {
22263  const char* ptstr;
22264  int dimid, status;
22265  std::string str,pathstr,filestr,ofilestr;
22266  int16_t fi = 0;
22267  int32_t num_scans_tot = 0, swt_orb_rec = 0, num_orb_rec;
22268  int32_t ffile = 1,num_gridlines = 0, n_files, iscan = 0;//4000 gridlines at 5.2 km and 8000 at 2.6 km resolution
22269  float hsat = 676.5;
22270  double* time_tot;
22271  float** lat_tot, ** lon_tot;
22272 
22273  num_gridlines = l1cfile->num_gridlines;
22274  nswath = l1cfile->nswath;
22275  num_pixels = l1cfile->npix;
22276  n_files = l1cfile->ifiles.size();
22277  int16_t nfiles_swath = nfiles_swt[swtd - 1];
22278  int nadpix = l1cfile->nadpix;
22279 
22280  time_tot = (double*)malloc(num_scans * nfiles_swath * sizeof(double));
22281  orb_array* posr_tot = new orb_array[num_scans * nfiles_swath]();//these are arrays #orb_rec x 3 vect components
22282  orb_array* velr_tot = new orb_array[num_scans * nfiles_swath]();
22283 
22284  lat_tot = allocate2d_float(num_scans * nfiles_swath, num_pixels);
22285  lon_tot = allocate2d_float(num_scans * nfiles_swath, num_pixels);
22286 
22287  //opening swath files----
22288  for (int i = 0;i < n_files;i++) {
22289  if (swtd == swtd_id[i]) {
22290  fi = file_id[i];
22291  str = l1cfile->ifiles[fi - 1];
22292  ptstr = str.c_str();
22293 
22294  status = nc_open(ptstr, NC_NOWRITE, &ncid_L1B);
22295  if (status != NC_NOERR) {
22296  fprintf(stderr, "-E- failed nc_open\n");
22297  exit(EXIT_FAILURE);
22298  }
22299  //Open dimensions
22300  // num_scans
22301  status = nc_inq_dimid(ncid_L1B, "number_of_scans", &dimid);
22302  if (status != NC_NOERR) {
22303  fprintf(stderr, "-E- Error reading number_of_scans.\n");
22304  exit(EXIT_FAILURE);
22305  }
22306  nc_inq_dimlen(ncid_L1B, dimid, &num_scans);
22307 
22308  status = nc_inq_dimid(ncid_L1B, "ccd_pixels", &dimid);
22309  if (status != NC_NOERR) {
22310  fprintf(stderr, "-E- Error reading number_of_scans.\n");
22311  exit(EXIT_FAILURE);
22312  }
22313  nc_inq_dimlen(ncid_L1B, dimid, &num_pixels);
22314 
22315  //define file time/geo pointers--
22316  double* orb_time = new double[num_scans]();//with Fred file num_scans = sdim
22317  orb_array* posr = new orb_array[num_scans]();//these are arrays #orb_rec x 3 vect components
22318  orb_array* velr = new orb_array[num_scans]();//num_scans=num_orb_records cause interpolated previously by Fred to scanlines
22319  lat = allocate2d_float(num_scans, num_pixels);
22320  lon = allocate2d_float(num_scans, num_pixels);
22321 
22322  //open scan_time (in Fred L1B file is orb_time interpolated)
22323  status = nc_inq_grp_ncid(ncid_L1B, "scan_line_attributes", &scGrp);
22324  check_err(status, __LINE__, __FILE__);
22325 
22326  status = nc_inq_varid(scGrp, "time", &otId);
22327  check_err(status, __LINE__, __FILE__);
22328  status = nc_get_var_double(scGrp, otId, orb_time);
22329  check_err(status, __LINE__, __FILE__);
22330 
22331  //open orb vectors
22332  status = nc_inq_grp_ncid(ncid_L1B, "navigation_data", &navGrp);
22333  check_err(status, __LINE__, __FILE__);
22334 
22335  status = nc_inq_varid(navGrp, "orb_pos", &opId);//scans x velements
22336  check_err(status, __LINE__, __FILE__);
22337  status = nc_get_var_float(navGrp, opId, &posr[0][0]);
22338  check_err(status, __LINE__, __FILE__);
22339 
22340  status = nc_inq_varid(navGrp, "orb_vel", &ovId);
22341  check_err(status, __LINE__, __FILE__);
22342  status = nc_get_var_float(navGrp, ovId, &velr[0][0]);
22343  check_err(status, __LINE__, __FILE__);
22344 
22345  //open geo data
22346  status = nc_inq_grp_ncid(ncid_L1B, "geolocation_data", &geoGrp);
22347  check_err(status, __LINE__, __FILE__);
22348  status = nc_inq_varid(geoGrp, "latitude", &latId);//scans x velements
22349  check_err(status, __LINE__, __FILE__);
22350  status = nc_get_var_float(geoGrp, latId, &lat[0][0]);
22351  check_err(status, __LINE__, __FILE__);
22352 
22353  status = nc_inq_varid(geoGrp, "longitude", &lonId);//scans x velements
22354  check_err(status, __LINE__, __FILE__);
22355  status = nc_get_var_float(geoGrp, lonId, &lon[0][0]);
22356  check_err(status, __LINE__, __FILE__);
22357 
22358  //concatenate 1-D time and 2-D geo vectors for the swath---
22359  //check orbit direction changes (ascending to descending) within the same file if the file is the lastof the swath
22360  size_t last_scans = 0;
22361  if (swtd != swtd_id[i + 1]) {
22362  for (unsigned int j = 0;j < num_scans + 1;j++) {
22363  if (lat[j + 1][nadpix] < lat[j][nadpix]) break;
22364  last_scans++;
22365  }
22366  num_scans = last_scans;
22367  cout << "last file..with #scans" << last_scans << endl;
22368  }
22369 
22370  num_scans_tot += num_scans;
22371  num_orb_rec = num_scans;
22372  swt_orb_rec += num_orb_rec;
22373 
22374  for (unsigned int j = 0;j < num_scans;j++)
22375  time_tot[j + iscan] = orb_time[j];
22376 
22377  for (unsigned int j = 0;j < num_scans;j++) {
22378  posr_tot[j + iscan][0] = posr[j][0];
22379  posr_tot[j + iscan][1] = posr[j][1];
22380  posr_tot[j + iscan][2] = posr[j][2];
22381 
22382  velr_tot[j + iscan][0] = velr[j][0];
22383  velr_tot[j + iscan][1] = velr[j][1];
22384  velr_tot[j + iscan][2] = velr[j][2];
22385  }
22386 
22387  for (unsigned int j = 0;j < num_scans;j++) {
22388  for (unsigned int k = 0;k < num_pixels;k++) {
22389  lat_tot[j + iscan][k] = lat[j][k];
22390  lon_tot[j + iscan][k] = lon[j][k];
22391  }
22392  }
22393 
22394  //close file if not the last
22395  status = nc_close(ncid_L1B);
22396  check_err(status, __LINE__, __FILE__);
22397 
22398  delete[](orb_time);
22399  delete[](posr);
22400  delete[](velr);
22401  delete[](lat);
22402  delete[](lon);
22403 
22404  iscan += num_scans;
22405  ffile++;
22406  }//end if
22407  }//end for
22408 
22409 
22410  cout << "num_scans_tot.." << num_scans_tot << "should be equal to numfiles x numscans/file.." << num_scans * nfiles_swath << "and swath records.." << swt_orb_rec << endl;
22411 
22412  //the number of orb records must be larger than the number of gridlines for the interpolation since we bracket orb records with gridlines
22413  //since orb records were interpolated to scanlines we have more orb records than gridlines and we need to decimate orb records by a factor of 10 lets say
22414  //*******************************************************************************
22415 
22416  if (swt_orb_rec <= num_gridlines) {
22417  cout << "-E- Error --number of swath records" << swt_orb_rec << " must be >= than number of gridlines for interpolation" << num_gridlines << ".\n" << endl;
22418  exit(EXIT_FAILURE);
22419  }
22420 
22421  orb_array* posi = new orb_array[num_gridlines]();
22422  orb_array* veli = new orb_array[num_gridlines]();
22423 
22424  cout << " first interpolation of orb records..." << "swath #.." << swtd << "\n";
22425 
22426  //interpolating orbital velocity and ground position to time_mean ground velocity
22427  orb_interp(swt_orb_rec, num_gridlines, time_tot, posr_tot, velr_tot, time_mgv, posi, veli);
22428  latlon_interp(swt_orb_rec, num_gridlines, num_pixels, time_tot, lat_tot, lon_tot, time_mgv, lati, loni);
22429 
22430 // for(int i=0;i<num_scans_tot-1;i++) cout<<"scan#.."<<i+1<<"latot.."<<lat_tot[i][nadpix]<<"delta time_mgv.."<<time_tot[i+1]-time_tot[i]<<endl;
22431 // exit(1);
22432 
22433 //*****************************************************************************************************************************************************************************
22434  //writing results---only nadir pixels---
22435  cout << " writing results first interpolation---swath #..." << swtd << "\n";
22436  ofilestr=std::string(l1cinput->ofile);
22437  filestr="lat_mgv.txt";
22438  pathstr="out/"+ofilestr+"_"+filestr;
22439 
22440 //-----lat -------------------------
22441  ofstream myfile5(pathstr);
22442 // ofstream myfile5("out/lat_mgv.txt");
22443 
22444  if (myfile5.is_open())
22445  {
22446  myfile5 << "lat_mgv.\n";
22447  for (int count = 0; count < num_gridlines-1; count++) {
22448  myfile5 << lati[count] << "," << endl;
22449  }
22450  myfile5.close();
22451  }
22452  else cout << "Unable to open lat_mgv.txt file";
22453 //----lon------------------------------------------------------
22454  filestr="lon_mgv.txt";
22455  pathstr="out/"+ofilestr+"_"+filestr;
22456 
22457 // ofstream myfile6("out/lon_mgv.txt");
22458  ofstream myfile6(pathstr);
22459 
22460  if (myfile6.is_open())
22461  {
22462  myfile6 << "lon_mgv.\n";
22463  for (int count = 0; count < num_gridlines-1; count++) {
22464  myfile6 << loni[count] << "," << endl;
22465  }
22466  myfile6.close();
22467  }
22468  else cout << "Unable to open lon_mgv.txt file";
22469 
22470  if (time_tot != NULL)
22471  delete[](time_tot);
22472  if (posr_tot != NULL)
22473  delete[](posr_tot);
22474  if (velr_tot != NULL)
22475  delete[](velr_tot);
22476  if (lat_tot != NULL)
22477  delete[](lat_tot);
22478  if (lon_tot != NULL)
22479  delete[](lon_tot);
22480 
22481  //compute ground velocity--
22482  for (int j = 0;j < num_gridlines;j++) {
22483  velig[j][0] = veli[j][0] * Re / (Re + hsat);
22484  velig[j][1] = veli[j][1] * Re / (Re + hsat);
22485  velig[j][2] = veli[j][2] * Re / (Re + hsat);
22486  }
22487 
22488  if (posi != NULL)
22489  delete[](posi);
22490  if (veli != NULL)
22491  delete[](veli);
22492 
22493  return 0;
22494  }
22495 
22496 
22497 int32_t L1C::time_swt3(int swtd, l1c_filehandle* l1cfile, L1C_input* l1cinput, double* ect_swtd, int16_t* swtd_id, int16_t* file_id, int16_t* nfiles_swt, float* mgv_swath, double* time_mgv) {
22498  float mot, ect = -1;//mean time
22499  const char* ptstr;
22500  int status;
22501  std::string str;
22502  int16_t fi = 0;
22503  size_t num_scans_tot = 0, swt_orb_rec = 0, num_orb_rec = 0;
22504  double tini, tend;//in seconds
22505  int32_t num_frames=-1,n_files, ffile = 1;//4000 gridlines at 5.2 km and 8000 at 2.6 km resolution
22506 
22507  cout<<"crossing time..."<<ect_swtd[0]<<endl;
22508 
22509  nswath = l1cfile->nswath;
22510  n_files = l1cfile->ifiles.size();
22511  num_scans = l1cfile->nscan;
22512  num_pixels = l1cfile->npix;
22513  num_frames=l1cfile->nframes;
22514 
22515  mot = ((l1cinput->gres) * 1000) / mgv_swath[swtd - 1];//delta-t in seconds
22516 // cout << "mean swath vel.." << mgv_swath[swtd - 1] << "[mot..." << mot << "for day swath #.." << swtd << endl;
22517 
22518  cout<<"computing mean velocity time intervals......................................................................................for swath #...."<<swtd<<endl;
22519  cout<<"swtd.."<<swtd<<"swtdid"<<swtd_id[0]<<"nfiles"<<n_files<<file_id[0]<<endl;
22520 
22521  for (int i = 0;i < n_files;i++) {
22522  if (swtd == swtd_id[i]) {
22523  //open files with the same crossing swath and compute time series based on mean time
22524  fi = file_id[i];
22525  str = l1cfile->ifiles[fi - 1];
22526  ptstr = str.c_str();
22527  cout << "Opening file.." << ptstr << " for crossing swath..." << swtd << "file_id.." << file_id[i] << "swt_id.." << swtd_id[i] << endl;
22528  status = nc_open(ptstr, NC_NOWRITE, &ncid_L1B);
22529 
22530  if (status != NC_NOERR) {
22531  fprintf(stderr, "-E- Error failed nc_open.\n");
22532  exit(EXIT_FAILURE);
22533  }
22534  //defining swath pointers
22535  double* orb_time = new double[num_frames]();//with Fred file num_scans = sdim
22536 
22537  //open scan_time (in Fred L1B file is orb_time interpolated)
22538  status = nc_inq_grp_ncid(ncid_L1B, "NAVIGATION", &scGrp);
22539  check_err(status, __LINE__, __FILE__);
22540  status = nc_inq_varid(scGrp, "msec", &otId);
22541  check_err(status, __LINE__, __FILE__);
22542  status = nc_get_var_double(scGrp, otId, orb_time);
22543  check_err(status, __LINE__, __FILE__);
22544 
22545  for (int k = 0;k <num_frames;k++){
22546  num_scans_tot += num_scans;
22547  num_orb_rec = num_scans;
22548  swt_orb_rec += num_orb_rec;
22549 
22550  // cout << "num_frames.."<<num_frames<<"num_scans_tot..." << num_scans_tot << "num of orb records for swath..." << swt_orb_rec << "so far file.." << ptstr << "swath #.." << swtd << endl;
22551  if (k == 0)
22552  tini = orb_time[0]/1000;//in seconds
22553 
22554  if (k==num_frames-1)//this is the last file of the swath
22555  tend = orb_time[num_frames - 1]/1000;//in seconds
22556  }//end frames
22557 
22558  cout<<"tini.."<<tini<<"tend.."<<tend<<"ect.."<<ect_swtd[i]<<endl;
22559 
22560 
22561  if (ect_swtd[i] > 0.0)//only 1 file is carrying the crossing time the other bunch of that swath is -999
22562  ect = ect_swtd[i];
22563  //close file if not the last
22564  status = nc_close(ncid_L1B);
22565  check_err(status, __LINE__, __FILE__);
22566 
22567  delete[](orb_time);
22568  ffile++;
22569  }//end if swath
22570  }//end for files
22571 
22572 
22573 
22574  if (ect > 0.0) {
22575  // cout << "tini..." << tini << "tend..." << tend << "for swath..#.." << swtd << "mot..." << mot << "ect..." << ect << endl;
22576  //before eq crosssing time bins
22577  // double dtime = (ect - mot / 2) - tini;
22578 
22579  double tg = ect - mot / 2;
22580  int binb = 0, bina = 0;
22581 
22582  while (tg > (tini - mot / 2)) {
22583  binb++; //bins below eq crossing bin which is eq cros time +-mot/2
22584  tg -= mot;
22585  }
22586 
22587  tg = ect + mot / 2;
22588 
22589  while (tg < (tend + mot / 2)) {
22590  bina++;//time bins above eq crossing time
22591  tg += mot;
22592  }
22593 
22594  //second way of computing gridlines---
22595 // dtime = tend - tini;
22596 
22597 
22598  l1cfile->num_gridlines = binb + bina;
22599 
22600  //before--
22601  for (int bin = 0;bin < binb;bin++) //300 seconds are 5 minutes or 1 file from Fred
22602  time_mgv[bin] = tini + bin * mot;
22603 
22604  int binc = binb-1;
22605 // time_mgv[binc] = ect;//equat crossing time bin
22606 
22607  //after
22608  // for (int bin = 1;bin < bina + 1;bin++){ //300 seconds are 5 minutes or 1 file from Fred
22609  for (int bin = 1;bin < bina;bin++){ //300 seconds are 5 minutes or 1 file from Fred
22610  time_mgv[binc + bin] = time_mgv[binc] + bin * mot;}
22611 
22612 // cout<<"bina.."<<bina<<"binb.."<<binb<<"ect.."<<ect<<endl;
22613  }//ect>0
22614 
22615 
22616  return 0;
22617  }
22618 
22619 
22620 
22621 int32_t L1C::time_swt2(int swtd, l1c_filehandle* l1cfile, L1C_input* l1cinput, double* ect_swtd, int16_t* swtd_id, int16_t* file_id, int16_t* nfiles_swt, float* mgv_swath, double* time_mgv) {
22622  float mot, ect = -1;//mean time
22623  const char* ptstr;
22624  int dimid, status;
22625  std::string str;
22626  int16_t fi = 0;
22627  size_t num_scans_tot = 0, swt_orb_rec = 0, num_orb_rec = 0;
22628  double tini, tend;//in seconds
22629  int32_t n_files, ffile = 1;//4000 gridlines at 5.2 km and 8000 at 2.6 km resolution
22630 
22631  nswath = l1cfile->nswath;
22632  num_scans = l1cfile->nscan;
22633  n_files = l1cfile->ifiles.size();
22634 
22635  mot = ((l1cinput->gres) * 1000) / mgv_swath[swtd - 1];//delta-t in seconds
22636 // cout << "mean swath vel.." << mgv_swath[swtd - 1] << "[mot..." << mot << "for day swath #.." << swtd << endl;
22637 
22638  cout<<"computing mean velocity time intervals......................................................................................for swath #...."<<swtd<<endl;
22639 
22640  for (int i = 0;i < n_files;i++) {
22641  if (swtd == swtd_id[i]) {
22642  //open files with the same crossing swath and compute time series based on mean time
22643  fi = file_id[i];
22644  str = l1cfile->ifiles[fi - 1];
22645  ptstr = str.c_str();
22646  cout << "Opening file.." << ptstr << " for crossing swath..." << swtd << "file_id.." << file_id[i] << "swt_id.." << swtd_id[i] << endl;
22647  status = nc_open(ptstr, NC_NOWRITE, &ncid_L1B);
22648 
22649  if (status != NC_NOERR) {
22650  fprintf(stderr, "-E- Error failed nc_open.\n");
22651  exit(EXIT_FAILURE);
22652  }
22653 
22654  //Open dimensions
22655  // num_scans
22656  status = nc_inq_dimid(ncid_L1B, "number_of_scans", &dimid);
22657  if (status != NC_NOERR) {
22658  fprintf(stderr, "-E- Error reading number_of_scans.\n");
22659  exit(EXIT_FAILURE);
22660  }
22661  nc_inq_dimlen(ncid_L1B, dimid, &num_scans);
22662 
22663  num_scans_tot += num_scans;
22664  num_orb_rec = num_scans;
22665  swt_orb_rec += num_orb_rec;
22666 
22667  // cout << "num_scans_tot..." << num_scans_tot << "num of orb records for swath..." << swt_orb_rec << "so far file.." << ptstr << "swath #.." << swtd << endl;
22668 
22669  //defining swath pointers
22670  double* orb_time = new double[num_scans]();//with Fred file num_scans = sdim
22671 
22672  //open scan_time (in Fred L1B file is orb_time interpolated)
22673  status = nc_inq_grp_ncid(ncid_L1B, "scan_line_attributes", &scGrp);
22674  check_err(status, __LINE__, __FILE__);
22675  status = nc_inq_varid(scGrp, "time", &otId);
22676  check_err(status, __LINE__, __FILE__);
22677  status = nc_get_var_double(scGrp, otId, orb_time);
22678  check_err(status, __LINE__, __FILE__);
22679 
22680  if (ffile == 1)
22681  tini = orb_time[0];
22682 
22683  if (ffile != 1 & swtd != swtd_id[i + 1])//this is the last file of the swath
22684  tend = orb_time[num_scans - 1];
22685 
22686  if (ect_swtd[i] > 0.0)//only 1 file is carrying the crossing time the other bunch of that swath is -999
22687  ect = ect_swtd[i];
22688  //close file if not the last
22689  status = nc_close(ncid_L1B);
22690  check_err(status, __LINE__, __FILE__);
22691 
22692  delete[](orb_time);
22693  ffile++;
22694  }//end if
22695  }//end for
22696 
22697  if (ect > 0.0) {
22698  // cout << "tini..." << tini << "tend..." << tend << "for swath..#.." << swtd << "mot..." << mot << "ect..." << ect << endl;
22699  //before eq crosssing time bins
22700  // double dtime = (ect - mot / 2) - tini;
22701 
22702  double tg = ect - mot / 2;
22703  int binb = 0, bina = 0;
22704 
22705  while (tg > (tini - mot / 2)) {
22706  binb++; //bins below eq crossing bin which is eq cros time +-mot/2
22707  tg -= mot;
22708  }
22709 
22710  tg = ect + mot / 2;
22711 
22712  while (tg < (tend + mot / 2)) {
22713  bina++;//time bins aove eq crossing time
22714  tg += mot;
22715  }
22716 
22717  //second way of computing gridlines---
22718 // dtime = tend - tini;
22719 
22720 
22721  l1cfile->num_gridlines = binb + bina;
22722 
22723  //before--
22724  for (int bin = 0;bin < binb;bin++) //300 seconds are 5 minutes or 1 file from Fred
22725  time_mgv[bin] = tini + bin * mot;
22726 
22727  int binc = binb-1;
22728  // time_mgv[binc] = ect;//equat crossing time bin
22729 
22730  //after
22731  for (int bin = 1;bin < bina;bin++) //300 seconds are 5 minutes or 1 file from Fred
22732  time_mgv[binc + bin] = time_mgv[binc] + bin * mot;
22733 
22734 // for (int bin = 0;bin <bina+binb-1;bin++) cout<<time_mgv[bin]<<endl;
22735 
22736 
22737 
22738  }//ect>0
22739  return 0;
22740  }
22741 
22742 
22743 
22744 
22745 int32_t L1C::mov_sd3(l1c_filehandle* l1cfile, L1C_input* l1cinput, double* tcross, int16_t* file_id, int16_t* swtd_id, int16_t* nfiles_swath, double* ect_swtd, int16_t* tod, int16_t* orbdir, float* mgv_swath) {
22746  int dimidv,dimidx,dimidy,dimidz,status;
22747  int32_t n_files, nadpix;
22748  std::string str;
22749  const char* ptstr;
22750  float* lat_id;
22751  int16_t* swath_id, * tod_id, * orbdir_id;
22752  std::string ifile_str;
22753  char* ifile_char;
22754  float lat_s=-80,lat_n=+80;
22755  int ovelId,latId1,latId2,latId3,lonId1,lonId2,lonId3,sen1Grp,sen2Grp,sen3Grp;
22756  float ***latframe1=nullptr,***latframe2=nullptr,***latframe3=nullptr,***lonframe1=nullptr,***lonframe2=nullptr,***lonframe3=nullptr,**ovel=nullptr;
22757  size_t vcomp;
22758  float mgv=-1;
22759 
22760 
22761  ifile_str = l1cinput->files[0];
22762  ifile_char = &ifile_str[0];
22763  file_format format=getFormat(ifile_char);
22764  format.type=FT_HARP;
22765  cout<<"sensor format type.."<<format.type<<endl;
22766 
22767  nadpix = l1cfile->nadpix;
22768  n_files = l1cfile->ifiles.size();
22769 // int16_t nswath = l1cfile->nswath;
22770 
22771  swath_id = (int16_t*)calloc(n_files,sizeof(int16_t));
22772  lat_id = (float*)calloc(n_files,sizeof(float));
22773  tod_id = (int16_t*)calloc(n_files,sizeof(int16_t));
22774  orbdir_id = (int16_t*)calloc(n_files,sizeof(int16_t));
22775 
22776 
22777  cout<<"# HARP files.to be processed.."<<n_files<<endl;
22778 
22779 
22780  //big loop
22781  size_t swtdid=1,fileid=swtdid;
22782  for (int i = 0;i < n_files;i++) {
22783 
22784  if(tcross[i]>0){
22785  ect_swtd[i]=tcross[i];
22786  swtd_id[i]=swtdid;
22787  file_id[i]=fileid;
22788  swtdid++;
22789  fileid++;
22790  }
22791  str = l1cfile->ifiles[i];
22792  ptstr = str.c_str();
22793 
22794  // Open the netcdf4 input file
22795  status = nc_open(ptstr, NC_NOWRITE, &ncid_L1B);
22796  if (status != NC_NOERR) {
22797  fprintf(stderr, "-E- Error failed nc_open.\n");
22798  exit(EXIT_FAILURE);
22799  }
22800  //dimensions
22801  status = nc_inq_dimid(ncid_L1B,"Frames", &dimidz);
22802  if (status != NC_NOERR) {
22803  fprintf(stderr, "-E- Error reading number_of frames.\n");
22804  exit(EXIT_FAILURE);
22805  }
22806  status = nc_inq_dimid(ncid_L1B,"Lines", &dimidy);
22807  if (status != NC_NOERR) {
22808  fprintf(stderr, "-E- Error reading number_of_scans.\n");
22809  exit(EXIT_FAILURE);
22810  }
22811  status = nc_inq_dimid(ncid_L1B,"Pixels", &dimidx);
22812  if (status != NC_NOERR) {
22813  fprintf(stderr, "-E- Error reading number_of_pixels per line...\n");
22814  exit(EXIT_FAILURE);
22815  }
22816  status = nc_inq_dimid(ncid_L1B,"Vector_Elements", &dimidv);
22817  if (status != NC_NOERR) {
22818  fprintf(stderr, "-E- Error reading vector components...\n");
22819  exit(EXIT_FAILURE);
22820  }
22821  nc_inq_dimlen(ncid_L1B, dimidz, &num_frames);
22822  nc_inq_dimlen(ncid_L1B, dimidy, &num_scans);
22823  nc_inq_dimlen(ncid_L1B, dimidx, &num_pixels);
22824  nc_inq_dimlen(ncid_L1B, dimidv, &vcomp);
22825 
22826  l1cfile->nscan=num_scans;
22827  l1cfile->npix=num_pixels;
22828  l1cfile->nframes=num_frames;
22829 
22830  //check daylight conditions--only checking first scan!! and central pixel!
22831  //for HARP ONLY DAYTIME OBSERVATIONS so no need to check zenith angle and day_mode
22832  //
22833 
22834  if(tcross[i]>0. && tod_id[i]>0) cout<<"HARP daytime file crossing the equator.."<<endl;
22835 
22836  //check first and end line to process based on latmin and latmax ----
22837  latframe1 = allocate3d_float(num_frames,num_scans, num_pixels);
22838  lonframe1 = allocate3d_float(num_frames,num_scans, num_pixels);
22839  latframe2 = allocate3d_float(num_frames,num_scans, num_pixels);
22840  lonframe2 = allocate3d_float(num_frames,num_scans, num_pixels);
22841  latframe3 = allocate3d_float(num_frames,num_scans, num_pixels);
22842  lonframe3 = allocate3d_float(num_frames,num_scans, num_pixels);
22843 
22844  //sensor1--0 degrees polariz
22845  status = nc_inq_grp_ncid(ncid_L1B, "Sensor1", &sen1Grp);
22846  check_err(status, __LINE__, __FILE__);
22847  status = nc_inq_varid(sen1Grp, "Latitude", &latId1);//scans x velements
22848  check_err(status, __LINE__, __FILE__);
22849  status = nc_get_var_float(sen1Grp, latId1, &latframe1[0][0][0]);
22850  check_err(status, __LINE__, __FILE__);
22851  status = nc_inq_varid(sen1Grp, "Longitude", &lonId1);
22852  check_err(status, __LINE__, __FILE__);
22853  status = nc_get_var_float(sen1Grp, lonId1, &lonframe1[0][0][0]);
22854  check_err(status, __LINE__, __FILE__);
22855 
22856 
22857  //sensor2--45 degrees poilar
22858  status = nc_inq_grp_ncid(ncid_L1B, "Sensor2", &sen2Grp);
22859  check_err(status, __LINE__, __FILE__);
22860  status = nc_inq_varid(sen2Grp, "Latitude", &latId2);//scans x velements
22861  check_err(status, __LINE__, __FILE__);
22862  status = nc_get_var_float(sen2Grp, latId2, &latframe2[0][0][0]);
22863  check_err(status, __LINE__, __FILE__);
22864  status = nc_inq_varid(sen2Grp, "Longitude", &lonId2);
22865  check_err(status, __LINE__, __FILE__);
22866  status = nc_get_var_float(sen2Grp, lonId2, &lonframe2[0][0][0]);
22867  check_err(status, __LINE__, __FILE__);
22868 
22869 
22870  //sensor3--90 degrees pola
22871  status = nc_inq_grp_ncid(ncid_L1B, "Sensor3", &sen3Grp);
22872  check_err(status, __LINE__, __FILE__);
22873  status = nc_inq_varid(sen3Grp, "Latitude", &latId3);//scans x velements
22874  check_err(status, __LINE__, __FILE__);
22875  status = nc_get_var_float(sen3Grp, latId3, &latframe3[0][0][0]);
22876  check_err(status, __LINE__, __FILE__);
22877  status = nc_inq_varid(sen3Grp, "Longitude", &lonId3);
22878  check_err(status, __LINE__, __FILE__);
22879  status = nc_get_var_float(sen3Grp, lonId3, &lonframe3[0][0][0]);
22880  check_err(status, __LINE__, __FILE__);
22881 
22882 
22883  //firsr/last line indexes for velocity calculations
22884  int frame1_s=-1,frame2_s=-1,frame3_s=-1,frame1_n=-1,frame2_n=-1,frame3_n=-1;
22885  int sline1=-1,sline2=-1,sline3=-1,eline1=-1,eline2=-1,eline3=-1;
22886 
22887  for(unsigned int j=0;j<num_frames;j++){
22888  for(unsigned int s=0;s<num_scans-1;s++){
22889  if(latframe1[j][s][nadpix]>=lat_s && frame1_s<0){ frame1_s=j,sline1=s;}
22890  if(latframe2[j][s][nadpix]>=lat_s && frame2_s<0){ frame2_s=j,sline2=s;}
22891  if(latframe3[j][s][nadpix]>=lat_s && frame3_s<0){ frame3_s=j,sline3=s;}
22892 
22893  if(latframe1[j][s][nadpix]<=lat_n && latframe1[j][s+1][nadpix]>latframe1[j][s][nadpix]){ frame1_n=j,eline1=s;}
22894  if(latframe2[j][s][nadpix]<=lat_n && latframe2[j][s+1][nadpix]>latframe2[j][s][nadpix]){ frame2_n=j,eline2=s;}
22895  if(latframe3[j][s][nadpix]<=lat_n && latframe3[j][s+1][nadpix]>latframe3[j][s][nadpix]){ frame3_n=j,eline3=s;}
22896  }
22897  // cout<<"frame #.."<<j+1<<"latframe1[j][0][nadpix]..."<<latframe1[j][0][nadpix]<<endl;
22898  }
22899 
22900  cout<<"frame1s"<<frame1_s<<"frame2s"<<frame2_s<<"frame3s"<<frame3_s<<endl;
22901  cout<<"frame1n"<<frame1_n<<"frame2n"<<frame2_n<<"frame3n"<<frame3_n<<endl;
22902  cout<<"sline1"<<sline1<<"sline2"<<sline2<<"sline3"<<sline3<<endl;
22903  cout<<"eline1"<<eline1<<"eline2"<<eline2<<"eline3"<<eline3<<endl;
22904 
22905  //get velocity for those frames/lines and compute mean ground velocity
22906 
22907 
22908  //get the orbit velocity for start/end frame
22909  ovel = allocate2d_float(num_frames,vcomp);
22910  status = nc_inq_grp_ncid(ncid_L1B, "NAVIGATION", &navGrp);
22911  check_err(status, __LINE__, __FILE__);
22912  status = nc_inq_varid(navGrp, "Orb_Velocity", &ovelId);//scans x velements
22913  check_err(status, __LINE__, __FILE__);
22914  status = nc_get_var_float(navGrp, ovelId, &ovel[0][0]);
22915 
22916  float sum=0.,vxyz=0.,mov=-1,hsat=676.5;
22917  int nframes=-1;
22918  for(int f=frame1_s=0;f<frame1_n;f++){
22919  vxyz = sqrt(ovel[f][0] * ovel[f][0] + ovel[f][1] * ovel[f][1] + ovel[f][2] * ovel[f][2]);//units m/s
22920  sum = sum + vxyz;
22921  nframes=f;
22922  }
22923 
22924  mov = (sum /nframes);//mean velocity in m/s (First Fred files OCIS in km/s!!!!!!!!!!!!!!!!!)
22925  cout<<"mean velocity in m/s.."<<mov<<endl;
22926  mgv = mov * Re / (Re + hsat);
22927  cout<<"mean ground velocity in m/s.."<<mgv<<endl;
22928 
22929 
22930  if(latframe1!=nullptr)
22931  delete [](latframe1);
22932  if(latframe2!=nullptr)
22933  delete [](latframe2);
22934  if(latframe3!=nullptr)
22935  delete [](latframe3);
22936  if(lonframe1!=nullptr)
22937  delete [](lonframe1);
22938  if(lonframe2!=nullptr)
22939  delete [](lonframe2);
22940  if(lonframe3!=nullptr)
22941  delete [](lonframe3);
22942  if(ovel!=nullptr)
22943  delete [](ovel);
22944 
22945  status = nc_close(ncid_L1B);
22946  check_err(status, __LINE__, __FILE__);
22947  }//end nfiles loop
22948 
22949 
22950 /*
22951  //make sure the date (year/month.day) is the same for the bunch of files--
22952  status = nc_inq_attlen(ncid_L1B, NC_GLOBAL, "time_coverage_start", &att_len);
22953  check_err(status, __LINE__, __FILE__);
22954  // allocate required space before retrieving values
22955  char* time_str = (char*)malloc(att_len + 1); // + 1 for trailing null
22956  // get global attribute values
22957  status = nc_get_att_text(ncid_L1B, NC_GLOBAL, "time_coverage_start", time_str);
22958  check_err(status, __LINE__, __FILE__);
22959  time_str[att_len] = '\0';
22960  double start_time = isodate2unix(time_str);
22961  unix2ymds(start_time, &syear, &smon, &sday, &secs);
22962 
22963  num_scans = l1cfile->nscan;
22964  num_pixels = l1cfile->npix;
22965  lat = allocate2d_float(num_scans, num_pixels);
22966  if(format.type == FT_SPEXONE){
22967  status = nc_inq_grp_ncid(ncid_L1B, "GEOLOCATION_DATA", &geoGrp);
22968  check_err(status, __LINE__, __FILE__);
22969  }
22970  else if(format.type == FT_HARP2){
22971  status = nc_inq_grp_ncid(ncid_L1B, "geolocation_data", &geoGrp);
22972  check_err(status, __LINE__, __FILE__);
22973  }
22974  else{ status = nc_inq_grp_ncid(ncid_L1B, "geolocation_data", &geoGrp);
22975  check_err(status, __LINE__, __FILE__);
22976  }
22977 
22978 
22979  status = nc_inq_varid(geoGrp, "latitude", &latId);//scans x velements
22980  check_err(status, __LINE__, __FILE__);
22981  status = nc_get_var_float(geoGrp, latId, &lat[0][0]);
22982  check_err(status, __LINE__, __FILE__);
22983 
22984  lat_id[i] = lat[0][nadpix];
22985 
22986  //opening solz, solza must be <= 90 for daylight
22987  solz = allocate2d_short(num_scans, num_pixels);
22988  status = nc_inq_varid(geoGrp, "solar_zenith", &solzId);//scans x velements
22989  check_err(status, __LINE__, __FILE__);
22990  status = nc_get_var_short(geoGrp, solzId, &solz[0][0]);
22991 
22992  //check daylight conditions--only checking first scan!! and central pixel!
22993  float tmp = 0.0;
22994  tmp = solz[0][nadpix] * 0.01 + 0.0;
22995  if (tmp > 90.0) {//nightime
22996  day_mode = 0;
22997  }
22998  else {
22999 
23000  day_mode = 1;
23001  }//daytime
23002  tod_id[i] = day_mode;
23003 
23004  for (unsigned int k = 0;k < num_scans;k++) {
23005  for (unsigned int j = 0;j < num_pixels;j++) {
23006  if (tmp < 0.0) {
23007  cout << "Error--negative solz[k][j]..." << tmp << endl;
23008  exit(1);
23009  }
23010  }
23011  }
23012 
23013  //check north/south boundings
23014  for (unsigned int k = 0;k < num_scans;k++) {
23015  for (unsigned int j = 0;j < num_pixels;j++) {
23016  //check north/south boundings
23017  if (lat[k][j] > l1cfile->latnorth) {
23018  lat[k][j] = l1cfile->latnorth;
23019  cout << "lat values above 90 degrees..set value to 90" << endl;
23020  }
23021  else if (lat[k][j] < l1cfile->latsouth) {
23022  lat[k][j] = l1cfile->latsouth;
23023  cout << "lat values below -90 degrees.set value to -90." << endl;
23024  }
23025  }
23026  }
23027 
23028  //loading selected day,month and year-----
23029  if (i == 0) {
23030  selday = l1cinput->selday;
23031  selmon = l1cinput->selmon;
23032  selyear = l1cinput->selyear;
23033  lat1 = lat[0][nadpix];
23034  }
23035 
23036  //MAKE sure the first file is the date WE WANT---init with the first file of the list
23037  if (i == 0 & selday < 0) {//input selected date manually-----
23038  selyear = syear;//se is for selected day,month or year
23039  selmon = smon;
23040  selday = sday;
23041  lat1 = lat[0][nadpix];
23042  }
23043 
23044  asc_mode = l1cfile->orb_dir;
23045  orbdir_id[i] = asc_mode;
23046 
23047  if (syear == selyear && smon == selmon && sday == selday) {
23048  //segment swath based on orbit direction and lat
23049  //check if lat between min and max
23050  //check solar zenith for only daylight granules >90 degrees is nighttime
23051  //assuming files are ordered by time when creating the initial list
23052  //we assume only daytime files
23053  //we compare the nadir pixel
23054 
23055  //ascending or descending orbit---------
23056  if (i >= 0 && day_mode == 0) { //nightime--
23057  swt++;
23058  nite++;
23059  swath_id[i] = swt;
23060  cout << "nightime file....swath #.." << swt << endl;
23061  if (tcross[i] > 0.0) {
23062  cout << "nightime eq crossing..for file [" << i << "]" << endl;
23063  // break;
23064  }
23065  }
23066 
23067  if (i == 0 && day_mode == 1) { //first file---
23068  // selyear=syear;
23069  // selmon=smon;
23070  // selday=sday;
23071  lat1 = lat[0][nadpix];
23072  lat2 = lat[num_scans - 1][nadpix];
23073  cout << "FIRST filename.." << ptstr << "file number..." << i + 1 << "asc_mode.." << asc_mode << "daymode.." << day_mode << "swt..." << swt << "lat1..." << lat1 << "lat2..." << lat2 << endl;
23074  swath_id[i] = swt;
23075  lat1 = lat2;
23076  }
23077 
23078  //ascending orbit
23079  if (i >= 1 && asc_mode == 1 && day_mode == 1)//at least two files to compare
23080  {
23081  lat2 = lat[0][nadpix];
23082  if (tod_id[i - 1] == 0) swt++;
23083  cout << "filename.." << ptstr << "file number..." << i + 1 << "asc_mode.." << asc_mode << "daymode.." << day_mode << "swt..." << swt << "lat1..." << lat1 << "lat2..." << lat2 << endl;
23084  swath_id[i] = swt;
23085  if (lat2 < lat1) {
23086  lat1 = lat2;
23087  }
23088  }
23089 
23090  }//if same day
23091 
23092 
23093  //close file
23094  status = nc_close(ncid_L1B);
23095  check_err(status, __LINE__, __FILE__);
23096 
23097  delete[](lat);
23098  delete[](solz);
23099  }//end big loop
23100 
23101 
23102  cout << "#nightime swaths..." << nite << "daytime swaths..." << swt - nite << endl;
23103 
23104 
23105  //obtain swath files qith equat crossing-- one swath at the time
23106  int16_t swtc = 1;
23107  float vxyz = 0.0, sum = 0.0, mov = 0.0, mgv = 0.0, hsat = 676.5;//Re earth radius in km, hsat sat height above earth surface in km
23108  size_t num_scans_tot = 0;
23109  int16_t swtc_id[nswath];
23110  int16_t swt_id = 0, cross_id = 1;
23111 
23112  cout << "nswath..or total (day/night) crossing swaths..." << nswath << endl;
23113 
23114  //find crossing swath ids
23115  int k = 0;
23116  for (int i = 0;i < n_files;i++) {
23117  if (tcross[i] > 0.0 && tod_id[i] == 1) {
23118  swtc_id[k] = swath_id[i];
23119  k++;
23120  }
23121  }
23122  ndswaths = k;
23123 
23124 
23125  //dynamic vector to store file_id
23126  std::vector<int16_t> swt_files, dswaths;
23127 
23128  //compute mgv for each swath--(day/night or asc/desc) but always crossing---
23129  int j = 0, tc = 0;
23130  int16_t nfiles_swt = 0;
23131  while (j < nswath) {
23132  swt_id = swtc_id[j];
23133  for (int i = 0;i < n_files;i++) {
23134  if (swt_id == swath_id[i] && tod_id[i] == 1) {
23135  swt_files.push_back(i + 1);
23136  ect_swtd[tc] = tcross[i];
23137  // dswaths.push_back(swt_id);
23138  dswaths.push_back(cross_id);
23139  ixfile = i;
23140  cout << "processing daytime swath with eq cross #...." << swtc << "file #..." << i + 1 << "swath_id.." << swath_id[i] << endl;
23141  nfiles_swt++;
23142 
23143  // Open the netcdf4 input file
23144  str = l1cfile->ifiles[i];
23145  ptstr = str.c_str();
23146 
23147  status = nc_open(ptstr, NC_NOWRITE, &ncid_L1B);
23148  if (status != NC_NOERR) {
23149  fprintf(stderr, "-E- Error failed nc_open.\n");
23150  exit(EXIT_FAILURE);
23151  }
23152 
23153 
23154  //allocate velr mem and update #orb records
23155  if (format.type == FT_SPEXONE){
23156  nscan_str="bins_along_track";
23157  status = nc_inq_dimid(ncid_L1B,nscan_str, &dimid);
23158  if (status != NC_NOERR) {
23159  fprintf(stderr, "-E- Error reading number_of_scans.\n");
23160  exit(EXIT_FAILURE);
23161  }
23162  }
23163  else if (format.type == FT_HARP2){
23164  nscan_str="Swath_Lines";
23165  status = nc_inq_dimid(ncid_L1B,nscan_str, &dimid);
23166  if (status != NC_NOERR) {
23167  fprintf(stderr, "-E- Error reading number_of_scans.\n");
23168  exit(EXIT_FAILURE);}
23169  }
23170  else{
23171  status = nc_inq_dimid(ncid_L1B, "number_of_scans", &dimid);
23172  if (status != NC_NOERR) {
23173  fprintf(stderr, "-E- Error reading number_of_scans.\n");
23174  exit(EXIT_FAILURE);}
23175  }
23176 
23177  nc_inq_dimlen(ncid_L1B, dimid, &num_scans);
23178  n_orb_rec = num_scans;
23179  velr = allocate2d_float(n_orb_rec, 3);
23180 
23182  status = nc_inq_grp_ncid(ncid_L1B, "navigation_data", &navGrp);
23183  check_err(status, __LINE__, __FILE__);
23184  status = nc_inq_varid(navGrp, "orb_vel", &ovId);
23185  check_err(status, __LINE__, __FILE__);
23186  status = nc_get_var_float(navGrp, ovId, &velr[0][0]);
23187  check_err(status, __LINE__, __FILE__);
23188 
23189  //compute vx velocity for each scanline or orb_vector---
23190  for (unsigned int j = 0;j < num_scans;j++) {
23191  vxyz = sqrt(velr[j][0] * velr[j][0] + velr[j][1] * velr[j][1] + velr[j][2] * velr[j][2]);//units m/s
23192  sum = sum + vxyz;
23193  }
23194 
23195  num_scans_tot += num_scans;
23196 
23197  tc++;
23198 
23199  status = nc_close(ncid_L1B);
23200  check_err(status, __LINE__, __FILE__);
23201  delete[](velr);
23202  }//end if
23203  }//end for
23204  cout << "ixfile...last file index of swath" << ixfile << endl;
23205  tod[swtc - 1] = tod_id[ixfile];//using the last file of the swath
23206  orbdir[swtc - 1] = orbdir_id[ixfile];
23207  mov = (sum / num_scans_tot) * 1000;//mean velocity in m/s x 10^3
23208  mgv = mov * Re / (Re + hsat);
23209  mgv_swath[swtc - 1] = mgv;
23210  nfiles_swath[swtc - 1] = nfiles_swt;
23211  cout << "tod.." << tod[swtc - 1] << "orbdir..." << orbdir[swtc - 1] << "mgv..." << mgv_swath[swtc - 1] << "nfiles per swath.." << nfiles_swt << endl;
23212  num_scans_tot = 0;
23213  vxyz = 0.0;
23214  sum = 0.0;
23215  j++;
23216  swtc++;
23217  nfiles_swt = 0;
23218  cross_id++;
23219  }//while end for vel processing
23220 
23221 
23222  nswtfiles = swt_files.size();
23223  cout << "nfiles day.(#swaths x files/swath).." << nswtfiles << endl;
23224  cout << "file day crossing id.size.(swaths per day).." << ndswaths << endl;
23225 
23226  l1cfile->nswt_files = nswtfiles;
23227  l1cfile->ndswaths = ndswaths;
23228 
23229  k = 0; //day swaths only!!
23230  for (std::vector<int16_t>::const_iterator c = swt_files.begin(); c != swt_files.end(); ++c) {
23231  file_id[k] = *c;
23232  k++;
23233  }
23234 
23235  k = 0;
23236  for (std::vector<int16_t>::const_iterator c = dswaths.begin(); c != dswaths.end(); ++c) {
23237  swtd_id[k] = *c;
23238  k++;
23239  }
23240 
23241  swt_files.clear();
23242  dswaths.clear();
23243 */
23244  if(tod_id!=nullptr)
23245  delete [](tod_id);
23246  if(orbdir_id!=nullptr)
23247  delete [](orbdir_id);
23248  if(swath_id!=nullptr)
23249  delete [](swath_id);
23250  if(lat_id!=nullptr)
23251  delete[](lat_id);
23252  return 0;
23253  }
23254 
23255 
23256 int32_t L1C::mov_sd4(l1c_filehandle* l1cfile, L1C_input* l1cinput, double* tcross, int16_t* file_id, int16_t* swtd_id, int16_t* nfiles_swath, double* ect_swtd, int16_t* tod, int16_t* orbdir, float* mgv_swath) {
23257  int status;
23258  int32_t n_files, nadpix;
23259  std::string str;
23260  const char* ptstr;
23261  float lat1, lat2;
23262  int16_t syear, smon, sday, selyear = -1, selmon = -1, selday = -1;
23263  double secs;
23264  size_t att_len, swt = 1, nite = 0;
23265  float* lat_id, ** velr;
23266  int16_t* swath_id, * tod_id, * orbdir_id;
23267  int asc_mode, day_mode;//per file--asceding mode: 1 ascending 0 descending, day_mode: 1 day, 0 ys night
23268  int32_t n_orb_rec;
23269  int ixfile = 0;
23270 
23271  num_scans=l1cfile->nscan;
23272  num_pixels=l1cfile->npix;
23273 
23274  nadpix = l1cfile->nadpix;
23275  n_files = l1cfile->ifiles.size();
23276  int16_t nswath = l1cfile->nswath;
23277 
23278  swath_id = (int16_t*)calloc(n_files,sizeof(int16_t));
23279  lat_id = (float*)calloc(n_files,sizeof(float));
23280  tod_id = (int16_t*)calloc(n_files,sizeof(int16_t));
23281  orbdir_id = (int16_t*)calloc(n_files,sizeof(int16_t));
23282 
23283 
23284  //big loop
23285  for (int i = 0;i < n_files;i++) {
23286  str = l1cfile->ifiles[i];
23287  ptstr = str.c_str();
23288  swath_id[i] = 0;
23289 
23290  // Open the netcdf4 input file
23291  status = nc_open(ptstr, NC_NOWRITE, &ncid_L1B);
23292  if (status != NC_NOERR) {
23293  fprintf(stderr, "-E- Error failed nc_open.\n");
23294  exit(EXIT_FAILURE);
23295  }
23296  //make sure the date (year/month.day) is the same for the bunch of files--
23297  status = nc_inq_attlen(ncid_L1B, NC_GLOBAL, "time_coverage_start", &att_len);
23298  check_err(status, __LINE__, __FILE__);
23299  // allocate required space before retrieving values
23300  char* time_str = (char*)malloc(att_len + 1); // + 1 for trailing null
23301  // get global attribute values
23302  status = nc_get_att_text(ncid_L1B, NC_GLOBAL, "time_coverage_start", time_str);
23303  check_err(status, __LINE__, __FILE__);
23304  // time_str[att_len] = '\0';
23305  // time_str = "2019-03-21T00:00:00" ;//from Fred OCIS
23306  // att_len=19;
23307  time_str[att_len] = '\0';
23308  // :time_coverage_end = "2019-03-21T00:05:00" ; from Fred OCIS
23309  double start_time = isodate2unix(time_str);
23310  unix2ymds(start_time, &syear, &smon, &sday, &secs);
23311 
23312  syear=2019;
23313  smon=3;
23314  sday=21;
23315 
23316  lat = allocate2d_float(num_scans, num_pixels);
23317  status = nc_inq_grp_ncid(ncid_L1B, "GEOLOCATION_DATA", &geoGrp);
23318  check_err(status, __LINE__, __FILE__);
23319  status = nc_inq_varid(geoGrp, "latitude", &latId);//scans x velements
23320  check_err(status, __LINE__, __FILE__);
23321  status = nc_get_var_float(geoGrp, latId, &lat[0][0]);
23322  check_err(status, __LINE__, __FILE__);
23323 
23324  lat_id[i] = lat[0][nadpix];
23325 
23326  //opening solz, solza must be <= 90 for daylight
23327  solz = allocate2d_short(num_scans, num_pixels);
23328  status = nc_inq_varid(geoGrp, "solar_zenith", &solzId);//scans x velements
23329  check_err(status, __LINE__, __FILE__);
23330  status = nc_get_var_short(geoGrp, solzId, &solz[0][0]);
23331 
23332  //check daylight conditions--only checking first scan!! and central pixel!
23333  float tmp = 0.0;
23334  tmp = solz[0][nadpix] * 0.01 + 0.0;
23335  if (tmp > 90.0) {//nightime
23336  day_mode = 0;
23337  }
23338  else {
23339 
23340  day_mode = 1;
23341  }//daytime
23342  tod_id[i] = day_mode;
23343 
23344  for (unsigned int k = 0;k < num_scans;k++) {
23345  for (unsigned int j = 0;j < num_pixels;j++) {
23346  if (tmp < 0.0) {
23347  cout << "Error--negative solz[k][j]..." << tmp << endl;
23348  exit(1);
23349  }
23350  }
23351  }
23352 
23353  //check north/south boundings
23354  for (unsigned int k = 0;k < num_scans;k++) {
23355  for (unsigned int j = 0;j < num_pixels;j++) {
23356  //check north/south boundings
23357  if (lat[k][j] > l1cfile->latnorth) {
23358  lat[k][j] = l1cfile->latnorth;
23359  cout << "lat values above 90 degrees..set value to 90" << endl;
23360  }
23361  else if (lat[k][j] < l1cfile->latsouth) {
23362  lat[k][j] = l1cfile->latsouth;
23363  cout << "lat values below 90 degrees.set value to -90." << endl;
23364  }
23365  }
23366  }
23367 
23368  //loading selected day,month and year-----
23369  if (i == 0) {
23370  selday = l1cinput->selday;
23371  selmon = l1cinput->selmon;
23372  selyear = l1cinput->selyear;
23373  lat1 = lat[0][nadpix];
23374  }
23375 
23376  //MAKE sure the first file is the date WE WANT---init with the first file of the list
23377  if (i == 0 && selday < 0) {//input selected date manually-----
23378  selyear = syear;//se is for selected day,month or year
23379  selmon = smon;
23380  selday = sday;
23381  lat1 = lat[0][nadpix];
23382  }
23383 
23384  asc_mode = l1cfile->orb_dir;
23385  orbdir_id[i] = asc_mode;
23386 
23387 
23388  if (syear == selyear && smon == selmon && sday == selday) {
23389  //segment swath based on orbit direction and lat
23390  //check if lat between min and max
23391  //check solar zenith for only daylight granules >90 degrees is nighttime
23392  //assuming files are ordered by time when creating the initial list
23393  //we assume only daytime files
23394  //we compare the nadir pixel
23395 
23396 
23397 
23398  //ascending or descending orbit---------
23399  if (i >= 0 && day_mode == 0) { //nightime--
23400  swt++;
23401  nite++;
23402  swath_id[i] = swt;
23403  cout << "nightime file....swath #.." << swt << endl;
23404  if (tcross[i] > 0.0) {
23405  cout << "nightime eq crossing..for file [" << i << "]" << endl;
23406  // break;
23407  }
23408  }
23409 
23410  if (i == 0 && day_mode == 1) { //first file---
23411  // selyear=syear;
23412  // selmon=smon;
23413  // selday=sday;
23414 
23415  lat1 = lat[0][nadpix];
23416  lat2 = lat[num_scans - 1][nadpix];
23417  cout << "FIRST filename.." << ptstr << "file number..." << i + 1 << "asc_mode.." << asc_mode << "daymode.." << day_mode << "swt..." << swt << "lat1..." << lat1 << "lat2..." << lat2 << endl;
23418  swath_id[i] = swt;
23419  lat1 = lat2;
23420  }
23421 
23422  //ascending orbit
23423  if (i >= 1 && asc_mode == 1 && day_mode == 1)//at least two files to compare
23424  {
23425  lat1=lat2;
23426  lat2 = lat[0][nadpix];
23427  if (tod_id[i - 1] == 0) swt++;
23428  cout << "filename.." << ptstr << "file number..." << i + 1 << "asc_mode.." << asc_mode << "daymode.." << day_mode << "swt..." << swt << "lat1..." << lat1 << "lat2..." << lat2 << endl;
23429  swath_id[i] = swt;
23430  // if (lat2 < lat1) {
23431  // lat1 = lat2;
23432  // }
23433  }
23434 
23435  }//if same day
23436  else{ cout<<"ERROR cli date different to image date..."<<"syear"<<syear<<"smon"<<smon<<"sday"<<sday<<"selyear"<<selyear<<"selmon"<<selmon<<"selday"<<selday<<endl;
23437  exit(1);}
23438 
23439 
23440  //close file
23441  status = nc_close(ncid_L1B);
23442  check_err(status, __LINE__, __FILE__);
23443 
23444  delete[](lat);
23445  delete[](solz);
23446  }//end big loop
23447 
23448 
23449  cout << "#nightime swaths..." << nite << "daytime swaths..." << swt - nite << endl;
23450 
23451 
23452  //obtain swath files qith equat crossing-- one swath at the time
23453  int16_t swtc = 1;
23454  float mov = 0.0, mgv = 0.0, hsat = 676.5;//Re earth radius in km, hsat sat height above earth surface in km
23455  size_t num_scans_tot = 0;
23456  int16_t swtc_id[nswath];
23457  int16_t swt_id = 0, cross_id = 1;
23458 
23459  cout << "nswath..or total (day/night) crossing swaths..." << nswath << endl;
23460 
23461  //find crossing swath ids
23462  int k = 0;
23463  for (int i = 0;i < n_files;i++) {
23464  if (tcross[i] > 0.0 && tod_id[i] == 1) {
23465  swtc_id[k] = swath_id[i];
23466  k++;
23467  }
23468  }
23469  ndswaths = k;
23470 
23471 
23472  //dynamic vector to store file_id
23473  std::vector<int16_t> swt_files, dswaths;
23474 
23475  //compute mgv for each swath--(day/night or asc/desc) but always crossing---
23476  int j = 0, tc = 0;
23477  int16_t nfiles_swt = 0;
23478  while (j < nswath) {
23479  cout<<"computing mean velocity for the swath #..........................................................................................................."<<swtc_id[j]<<endl;
23480  swt_id = swtc_id[j];
23481  for (int i = 0;i < n_files;i++) {
23482  if (swt_id == swath_id[i] && tod_id[i] == 1) {
23483  swt_files.push_back(i + 1);
23484  ect_swtd[tc] = tcross[i];
23485  // dswaths.push_back(swt_id);
23486  dswaths.push_back(cross_id);
23487  ixfile = i;
23488  cout << "processing daytime swath with eq cross #...." << swtc << "file #..." << i + 1 << "swath_id.." << swath_id[i] << endl;
23489  nfiles_swt++;
23490 
23491  // Open the netcdf4 input file
23492  str = l1cfile->ifiles[i];
23493  ptstr = str.c_str();
23494 
23495  status = nc_open(ptstr, NC_NOWRITE, &ncid_L1B);
23496  if (status != NC_NOERR) {
23497  fprintf(stderr, "-E- failed nc_open.\n");
23498  exit(EXIT_FAILURE);
23499  }
23500 
23501  //allocate velr mem and update #orb records
23502  n_orb_rec = num_scans;
23503  velr = allocate2d_float(n_orb_rec, 3);
23504 
23506  /* status = nc_inq_grp_ncid(ncid_L1B, "navigation_data", &navGrp);
23507  check_err(status, __LINE__, __FILE__);
23508  status = nc_inq_varid(navGrp, "orb_vel", &ovId);
23509  check_err(status, __LINE__, __FILE__);
23510  status = nc_get_var_float(navGrp, ovId, &velr[0][0]);
23511  check_err(status, __LINE__, __FILE__);
23512 
23513  //compute vx velocity for each scanline or orb_vector---
23514  for (unsigned int j = 0;j < num_scans;j++) {
23515  vxyz = sqrt(velr[j][0] * velr[j][0] + velr[j][1] * velr[j][1] + velr[j][2] * velr[j][2]);//units m/s
23516  // cout<<"vxyz.."<<vxyz<<endl;
23517  sum = sum + vxyz;
23518  }
23519  */
23520  num_scans_tot += num_scans;
23521 
23522  tc++;
23523 
23524  status = nc_close(ncid_L1B);
23525  check_err(status, __LINE__, __FILE__);
23526  delete[](velr);
23527  }//end if
23528  }//end for
23529  // cout << "ixfile...last file index of swath" << ixfile << endl;
23530  tod[swtc - 1] = tod_id[ixfile];//using the last file of the swath
23531  orbdir[swtc - 1] = orbdir_id[ixfile];
23532  mov=-999.;
23533  // mov = (sum / num_scans_tot) * 1000;//mean velocity in m/s x 10^3
23534  mgv = mov * Re / (Re + hsat);
23535  mgv_swath[swtc - 1] = mgv;
23536  nfiles_swath[swtc - 1] = nfiles_swt;
23537 
23538 // cout << "tod.." << tod[swtc - 1] << "orbdir..." << orbdir[swtc - 1] << "mgv..." << mgv_swath[swtc - 1] << "nfiles per swath.." << nfiles_swt << endl;
23539 
23540  num_scans_tot = 0;
23541  // float vxyz = 0.0;
23542  // float sum = 0.0;
23543  j++;
23544  swtc++;
23545  nfiles_swt = 0;
23546  cross_id++;
23547  }//while end for vel processing
23548 
23549 
23550  nswtfiles = swt_files.size();
23551  // cout << "nfiles day.(#swaths x files/swath).." << nswtfiles << endl;
23552  // cout << "file day crossing id.size.(swaths per day).." << ndswaths << endl;
23553 
23554  l1cfile->nswt_files = nswtfiles;
23555  l1cfile->ndswaths = ndswaths;
23556 
23557  k = 0; //day swaths only!!
23558  for (std::vector<int16_t>::const_iterator c = swt_files.begin(); c != swt_files.end(); ++c) {
23559  file_id[k] = *c;
23560  k++;
23561  }
23562 
23563  k = 0;
23564  for (std::vector<int16_t>::const_iterator c = dswaths.begin(); c != dswaths.end(); ++c) {
23565  swtd_id[k] = *c;
23566  k++;
23567  }
23568 
23569  swt_files.clear();
23570  dswaths.clear();
23571 
23572 
23573  delete[](tod_id);
23574  delete[](orbdir_id);
23575  delete[](swath_id);
23576  delete[](lat_id);
23577  return 0;
23578  }
23579 
23580 
23581 
23582 int32_t L1C::mov_sd2(l1c_filehandle* l1cfile, L1C_input* l1cinput, double* tcross, int16_t* file_id, int16_t* swtd_id, int16_t* nfiles_swath, double* ect_swtd, int16_t* tod, int16_t* orbdir, float* mgv_swath) {
23583  int dimid, status;
23584  int32_t n_files, nadpix;
23585  std::string str;
23586  const char* ptstr;
23587  float lat1, lat2;
23588  int16_t syear, smon, sday, selyear = -1, selmon = -1, selday = -1;
23589  double secs;
23590  size_t att_len, swt = 1, nite = 0;
23591  float* lat_id, ** velr;
23592  int16_t* swath_id, * tod_id, * orbdir_id;
23593  int asc_mode, day_mode;//per file--asceding mode: 1 ascending 0 descending, day_mode: 1 day, 0 ys night
23594  int32_t n_orb_rec;
23595  int ixfile = 0;
23596 
23597 
23598  nadpix = l1cfile->nadpix;
23599  n_files = l1cfile->ifiles.size();
23600  int16_t nswath = l1cfile->nswath;
23601 
23602  swath_id = (int16_t*)calloc(n_files,sizeof(int16_t));
23603  lat_id = (float*)calloc(n_files,sizeof(float));
23604  tod_id = (int16_t*)calloc(n_files,sizeof(int16_t));
23605  orbdir_id = (int16_t*)calloc(n_files,sizeof(int16_t));
23606 
23607 
23608  //big loop
23609  for (int i = 0;i < n_files;i++) {
23610  str = l1cfile->ifiles[i];
23611  ptstr = str.c_str();
23612  swath_id[i] = 0;
23613 
23614  // Open the netcdf4 input file
23615  status = nc_open(ptstr, NC_NOWRITE, &ncid_L1B);
23616  if (status != NC_NOERR) {
23617  fprintf(stderr, "-E- Error failed nc_open.\n");
23618  exit(EXIT_FAILURE);
23619  }
23620  //make sure the date (year/month.day) is the same for the bunch of files--
23621  status = nc_inq_attlen(ncid_L1B, NC_GLOBAL, "time_coverage_start", &att_len);
23622  check_err(status, __LINE__, __FILE__);
23623  // allocate required space before retrieving values
23624  char* time_str = (char*)malloc(att_len + 1); // + 1 for trailing null
23625  // get global attribute values
23626  status = nc_get_att_text(ncid_L1B, NC_GLOBAL, "time_coverage_start", time_str);
23627  check_err(status, __LINE__, __FILE__);
23628  time_str[att_len] = '\0';
23629  double start_time = isodate2unix(time_str);
23630  unix2ymds(start_time, &syear, &smon, &sday, &secs);
23631  delete [](time_str);
23632 
23633  num_scans = l1cfile->nscan;
23634  num_pixels = l1cfile->npix;
23635  lat = allocate2d_float(num_scans, num_pixels);
23636  status = nc_inq_grp_ncid(ncid_L1B, "geolocation_data", &geoGrp);
23637  check_err(status, __LINE__, __FILE__);
23638  status = nc_inq_varid(geoGrp, "latitude", &latId);//scans x velements
23639  check_err(status, __LINE__, __FILE__);
23640  status = nc_get_var_float(geoGrp, latId, &lat[0][0]);
23641  check_err(status, __LINE__, __FILE__);
23642 
23643  lat_id[i] = lat[0][nadpix];
23644 
23645  //opening solz, solza must be <= 90 for daylight
23646  solz = allocate2d_short(num_scans, num_pixels);
23647  status = nc_inq_varid(geoGrp, "solar_zenith", &solzId);//scans x velements
23648  check_err(status, __LINE__, __FILE__);
23649  status = nc_get_var_short(geoGrp, solzId, &solz[0][0]);
23650 
23651  //check daylight conditions--only checking first scan!! and central pixel!
23652  float tmp = 0.0;
23653  tmp = solz[0][nadpix] * 0.01 + 0.0;
23654  if (tmp > 90.0) {//nightime
23655  day_mode = 0;
23656  }
23657  else {
23658 
23659  day_mode = 1;
23660  }//daytime
23661  tod_id[i] = day_mode;
23662 
23663  for (unsigned int k = 0;k < num_scans;k++) {
23664  for (unsigned int j = 0;j < num_pixels;j++) {
23665  if (tmp < 0.0) {
23666  cout << "Error--negative solz[k][j]..." << tmp << endl;
23667  exit(1);
23668  }
23669  }
23670  }
23671 
23672  //check north/south boundings
23673  for (unsigned int k = 0;k < num_scans;k++) {
23674  for (unsigned int j = 0;j < num_pixels;j++) {
23675  //check north/south boundings
23676  if (lat[k][j] > l1cfile->latnorth) {
23677  lat[k][j] = l1cfile->latnorth;
23678  cout << "lat values above 90 degrees..set value to 90" << endl;
23679  }
23680  else if (lat[k][j] < l1cfile->latsouth) {
23681  lat[k][j] = l1cfile->latsouth;
23682  cout << "lat values below 90 degrees.set value to -90." << endl;
23683  }
23684  }
23685  }
23686 
23687  //loading selected day,month and year-----
23688  if (i == 0) {
23689  selday = l1cinput->selday;
23690  selmon = l1cinput->selmon;
23691  selyear = l1cinput->selyear;
23692  lat1 = lat[0][nadpix];
23693  }
23694 
23695 
23696 
23697 /*
23698  //MAKE sure the first file is the date WE WANT---init with the first file of the list
23699  if (i == 0 & selday < 0) {//input selected date manually-----
23700  selyear = syear;//se is for selected day,month or year
23701  selmon = smon;
23702  selday = sday;
23703  lat1 = lat[0][nadpix];
23704  }
23705 */
23706  asc_mode = l1cfile->orb_dir;
23707  orbdir_id[i] = asc_mode;
23708 
23709  if (syear == selyear && smon == selmon && sday == selday) {
23710  //segment swath based on orbit direction and lat
23711  //check if lat between min and max
23712  //check solar zenith for only daylight granules >90 degrees is nighttime
23713  //assuming files are ordered by time when creating the initial list
23714  //we assume only daytime files
23715  //we compare the nadir pixel
23716 
23717  //ascending or descending orbit---------
23718  if (i >= 0 && day_mode == 0) { //nightime--
23719  swt++;
23720  nite++;
23721  swath_id[i] = swt;
23722  cout << "nightime file....swath #.." << swt << endl;
23723  if (tcross[i] > 0.0) {
23724  cout << "nightime eq crossing..for file [" << i << "]" << endl;
23725  // break;
23726  }
23727  }
23728 
23729  if (i == 0 && day_mode == 1) { //first file---
23730  // selyear=syear;
23731  // selmon=smon;
23732  // selday=sday;
23733  lat1 = lat[0][nadpix];
23734  lat2 = lat[num_scans - 1][nadpix];
23735  cout << "FIRST filename.." << ptstr << "file number..." << i + 1 << "asc_mode.." << asc_mode << "daymode.." << day_mode << "swt..." << swt << "lat1..." << lat1 << "lat2..." << lat2 << endl;
23736  swath_id[i] = swt;
23737  lat1 = lat2;
23738  }
23739 
23740  //ascending orbit
23741  if (i >= 1 && asc_mode == 1 && day_mode == 1)//at least two files to compare
23742  { lat1=lat2;
23743  lat2 = lat[0][nadpix];
23744  if (tod_id[i - 1] == 0) swt++;
23745  cout << "filename.." << ptstr << "file number..." << i + 1 << "asc_mode.." << asc_mode << "daymode.." << day_mode << "swt..." << swt << "lat1..." << lat1 << "lat2..." << lat2 << endl;
23746  swath_id[i] = swt;
23747  // if (lat2 < lat1) {
23748  // lat1 = lat2;
23749  // }
23750  }
23751 
23752  }//if same day
23753 
23754 
23755  //close file
23756  status = nc_close(ncid_L1B);
23757  check_err(status, __LINE__, __FILE__);
23758 
23759  delete[](lat);
23760  delete[](solz);
23761  }//end big loop
23762 
23763 
23764  cout << "#nightime swaths..." << nite << "daytime swaths..." << swt - nite << endl;
23765 
23766 
23767  //obtain swath files qith equat crossing-- one swath at the time
23768  int16_t swtc = 1;
23769  float vxyz = 0.0, sum = 0.0, mov = 0.0, mgv = 0.0, hsat = 676.5;//Re earth radius in km, hsat sat height above earth surface in km
23770  size_t num_scans_tot = 0;
23771  int16_t swtc_id[nswath];
23772  int16_t swt_id = 0, cross_id = 1;
23773 
23774  cout << "nswath..or total (day/night) crossing swaths..." << nswath << endl;
23775 
23776  //find crossing swath ids
23777  int k = 0;
23778  for (int i = 0;i < n_files;i++) {
23779  if (tcross[i] > 0.0 && tod_id[i] == 1) {
23780  swtc_id[k] = swath_id[i];
23781  k++;
23782  }
23783  }
23784  ndswaths = k;
23785 
23786 
23787  //dynamic vector to store file_id
23788  std::vector<int16_t> swt_files, dswaths;
23789 
23790  //compute mgv for each swath--(day/night or asc/desc) but always crossing---
23791  int j = 0, tc = 0;
23792  int16_t nfiles_swt = 0;
23793  while (j < nswath) {
23794  cout<<"computing mean velocity for the swath #..........................................................................................................."<<swtc_id[j]<<endl;
23795  swt_id = swtc_id[j];
23796  for (int i = 0;i < n_files;i++) {
23797  if (swt_id == swath_id[i] && tod_id[i] == 1) {
23798  swt_files.push_back(i + 1);
23799  ect_swtd[tc] = tcross[i];
23800  // dswaths.push_back(swt_id);
23801  dswaths.push_back(cross_id);
23802  ixfile = i;
23803  cout << "processing daytime swath with eq cross #...." << swtc << "file #..." << i + 1 << "swath_id.." << swath_id[i] << endl;
23804  nfiles_swt++;
23805 
23806  // Open the netcdf4 input file
23807  str = l1cfile->ifiles[i];
23808  ptstr = str.c_str();
23809 
23810  status = nc_open(ptstr, NC_NOWRITE, &ncid_L1B);
23811  if (status != NC_NOERR) {
23812  fprintf(stderr, "-E- failed nc_open.\n");
23813  exit(EXIT_FAILURE);
23814  }
23815 
23816  //allocate velr mem and update #orb records
23817  status = nc_inq_dimid(ncid_L1B, "number_of_scans", &dimid);
23818  if (status != NC_NOERR) {
23819  fprintf(stderr, "-E- Error reading number_of_scans.\n");
23820  exit(EXIT_FAILURE);
23821  }
23822 
23823  nc_inq_dimlen(ncid_L1B, dimid, &num_scans);
23824  n_orb_rec = num_scans;
23825  velr = allocate2d_float(n_orb_rec, 3);
23826 
23828  status = nc_inq_grp_ncid(ncid_L1B, "navigation_data", &navGrp);
23829  check_err(status, __LINE__, __FILE__);
23830  status = nc_inq_varid(navGrp, "orb_vel", &ovId);
23831  check_err(status, __LINE__, __FILE__);
23832  status = nc_get_var_float(navGrp, ovId, &velr[0][0]);
23833  check_err(status, __LINE__, __FILE__);
23834 
23835  //compute vx velocity for each scanline or orb_vector---
23836  for (unsigned int j = 0;j < num_scans;j++) {
23837  vxyz = sqrt(velr[j][0] * velr[j][0] + velr[j][1] * velr[j][1] + velr[j][2] * velr[j][2]);//units m/s
23838  // cout<<"vxyz.."<<vxyz<<endl;
23839  sum = sum + vxyz;
23840  }
23841 
23842  num_scans_tot += num_scans;
23843 
23844  tc++;
23845 
23846  status = nc_close(ncid_L1B);
23847  check_err(status, __LINE__, __FILE__);
23848  delete[](velr);
23849  }//end if
23850  }//end for
23851  // cout << "ixfile...last file index of swath" << ixfile << endl;
23852  tod[swtc - 1] = tod_id[ixfile];//using the last file of the swath
23853  orbdir[swtc - 1] = orbdir_id[ixfile];
23854  mov = (sum / num_scans_tot) * 1000;//mean velocity in m/s x 10^3
23855  mgv = mov * Re / (Re + hsat);
23856  mgv_swath[swtc - 1] = mgv;
23857  nfiles_swath[swtc - 1] = nfiles_swt;
23858 
23859 // cout << "tod.." << tod[swtc - 1] << "orbdir..." << orbdir[swtc - 1] << "mgv..." << mgv_swath[swtc - 1] << "nfiles per swath.." << nfiles_swt << endl;
23860 
23861  num_scans_tot = 0;
23862  vxyz = 0.0;
23863  sum = 0.0;
23864  j++;
23865  swtc++;
23866  nfiles_swt = 0;
23867  cross_id++;
23868  }//while end for vel processing
23869 
23870 
23871  nswtfiles = swt_files.size();
23872  // cout << "nfiles day.(#swaths x files/swath).." << nswtfiles << endl;
23873  // cout << "file day crossing id.size.(swaths per day).." << ndswaths << endl;
23874 
23875  l1cfile->nswt_files = nswtfiles;
23876  l1cfile->ndswaths = ndswaths;
23877 
23878  k = 0; //day swaths only!!
23879  for (std::vector<int16_t>::const_iterator c = swt_files.begin(); c != swt_files.end(); ++c) {
23880  file_id[k] = *c;
23881  k++;
23882  }
23883 
23884  k = 0;
23885  for (std::vector<int16_t>::const_iterator c = dswaths.begin(); c != dswaths.end(); ++c) {
23886  swtd_id[k] = *c;
23887  k++;
23888  }
23889 
23890  swt_files.clear();
23891  dswaths.clear();
23892 
23893 
23894  delete[](tod_id);
23895  delete[](orbdir_id);
23896  delete[](swath_id);
23897  delete[](lat_id);
23898 
23899  return 0;
23900  }
23901 
23902 
23903 
23904 int32_t L1C::ect_sf2(const char* filename, L1C_input* l1cinput,l1c_filehandle* l1cfile) { //ect version for single file
23905  int dimid,dimidz,dimidx,dimidy,status,sen1Grp,blueGrp,v1Grp,dimidv;
23906  int asc_mode = 0, scan_brack[2] = { -1,-1 };
23907  float lat1, lat2, lon1, lon2;//lat,lon defined globally
23908  float ***latframe=nullptr,***lonframe=nullptr;;
23909  double t1 = -1, t2 = -1;
23910  double tcross,secs;
23911  float loncross;
23912  std::string ifile_str;
23913  char* ifile_char;
23914  const char *nscan_str,*npix_str;
23915  double *stime=nullptr;
23916  int16_t syear, smon, sday, selyear = -1, selmon = -1, selday = -1;
23917  size_t att_len;
23918 
23919  l1cfile->l1b_name = filename;
23920  selday = l1cinput->selday;
23921  selmon = l1cinput->selmon;
23922  selyear = l1cinput->selyear;
23923 
23924 
23925  l1cfile->l1b_name = filename;
23926 
23927  // Open the netcdf4 input file
23928  status = nc_open(filename, NC_NOWRITE, &ncid_L1B);
23929 
23930  if (status != NC_NOERR) {
23931  fprintf(stderr, "-E- Error failed nc_open...\n");
23932  exit(EXIT_FAILURE);
23933  }
23934 
23935  //Open dimensions
23936  // num_scans
23937  ifile_str = l1cinput->files[0];
23938  ifile_char = &ifile_str[0];
23939  file_format format = getFormat(ifile_char);
23940 
23941  format.type=l1cfile->format;
23942  cout<<"format type..in ect_sf2"<<format.type<<endl;
23943 
23944 
23945  //checking input date
23946  status = nc_inq_attlen(ncid_L1B, NC_GLOBAL, "time_coverage_start", &att_len);
23947  check_err(status, __LINE__, __FILE__);
23948  // allocate required space before retrieving values
23949  char* time_str = (char*)malloc(att_len + 1); // + 1 for trailing null
23950  // get global attribute values
23951  status = nc_get_att_text(ncid_L1B, NC_GLOBAL, "time_coverage_start", time_str);
23952  check_err(status, __LINE__, __FILE__);
23953  time_str[att_len] = '\0';
23954  double start_time = isodate2unix(time_str);
23955  unix2ymds(start_time, &syear, &smon, &sday, &secs);
23956 
23957  if (syear == selyear && smon == selmon && sday == selday) {
23958  cout<<"computing equatorial crossing time...............................................................for file."<<filename<<endl;
23959  }
23960  else{
23961  cout<<"input date does not match year.."<<syear<<"month.."<<smon<<"day.."<<sday<<" extracted from the l1b file....."<<endl;
23962  exit(1);
23963  }
23964 
23965 //*******legacy sensors including OCI **************
23966  if (format.type != FT_SPEXONE && format.type != FT_HARP2 && format.type != FT_HARP){
23967  cout<<"reading num scan for legacy sensors"<<endl;
23968  status = nc_inq_dimid(ncid_L1B, "number_of_scans", &dimid);
23969  if (status != NC_NOERR) {
23970  fprintf(stderr, "-E- Error reading number_of_scans.\n");
23971  exit(EXIT_FAILURE);
23972  }
23973  nc_inq_dimlen(ncid_L1B, dimid, &num_scans);
23974 
23975  //across-track bins
23976  status = nc_inq_dimid(ncid_L1B, "ccd_pixels", &dimid);
23977  if (status != NC_NOERR) {
23978  fprintf(stderr, "-E- Error reading number_of_pixels per line...\n");
23979  exit(EXIT_FAILURE);
23980  }
23981  nc_inq_dimlen(ncid_L1B, dimid, &num_pixels);
23982 
23983  }
23984 
23985 // *********** SPEXONE **************************
23986  if (format.type == FT_SPEXONE){
23987  cout<<"Processing SPEXone equat crossing time......"<<endl;
23988 
23989  nscan_str="bins_along_track";
23990  npix_str="spatial_samples_per_image";
23991  status = nc_inq_dimid(ncid_L1B,nscan_str, &dimidy);
23992  if (status != NC_NOERR) {
23993  fprintf(stderr, "-E- Error reading number_of_scans.\n");
23994  exit(EXIT_FAILURE);
23995  }
23996  status = nc_inq_dimid(ncid_L1B,npix_str, &dimidx);
23997  if (status != NC_NOERR) {
23998  fprintf(stderr, "-E- Error reading number_of_pixels per line...\n");
23999  exit(EXIT_FAILURE);
24000  }
24001  nc_inq_dimlen(ncid_L1B, dimidy, &num_scans);
24002  nc_inq_dimlen(ncid_L1B, dimidx, &num_pixels);
24003  }
24004 
24005  //********** HARP2 ***************************
24006  if (format.type == FT_HARP2){
24007  status = nc_inq_dimid(ncid_L1B,"Frames", &dimidz);
24008  if (status != NC_NOERR) {
24009  fprintf(stderr, "-E- Error reading number_of frames.\n");
24010  exit(EXIT_FAILURE);
24011  }
24012  status = nc_inq_dimid(ncid_L1B,"Lines", &dimidy);
24013  if (status != NC_NOERR) {
24014  fprintf(stderr, "-E- Error reading number_of_scans.\n");
24015  exit(EXIT_FAILURE);
24016  }
24017  status = nc_inq_dimid(ncid_L1B,"Pixels", &dimidx);
24018  if (status != NC_NOERR) {
24019  fprintf(stderr, "-E- Error reading number_of_pixels per line...\n");
24020  exit(EXIT_FAILURE);
24021  }
24022  nc_inq_dimlen(ncid_L1B, dimidz, &num_frames);
24023  nc_inq_dimlen(ncid_L1B, dimidy, &num_scans);
24024  nc_inq_dimlen(ncid_L1B, dimidx, &num_pixels);
24025  }
24026 
24027  //********** HARP ***************************
24028  if (format.type == FT_HARP){
24029  status = nc_inq_grp_ncid(ncid_L1B, "blue", &blueGrp);
24030  if (status != NC_NOERR) {
24031  fprintf(stderr, "-E- Error reading group blue.\n");
24032  exit(EXIT_FAILURE);
24033  }
24034  status = nc_inq_dimid(blueGrp,"Views", &dimidv);
24035  if (status != NC_NOERR) {
24036  fprintf(stderr, "-E- Error reading dimensions number_of views.\n");
24037  exit(EXIT_FAILURE);
24038  }
24039  //reading subgroup view1
24040  status = nc_inq_grp_ncid(blueGrp, "View01", &v1Grp);
24041  if (status != NC_NOERR) {
24042  fprintf(stderr, "-E- Error reading subgroup view 1 --blue.\n");
24043  exit(EXIT_FAILURE);
24044  }
24045  //lines and pixels
24046  status = nc_inq_dimid(v1Grp,"Swath_Pixels", &dimidx);
24047  if (status != NC_NOERR) {
24048  fprintf(stderr, "-E- Error reading # pixel dimensions view01.\n");
24049  exit(EXIT_FAILURE);
24050  }
24051  status = nc_inq_dimid(v1Grp,"Swath_Lines", &dimidy);
24052  if (status != NC_NOERR) {
24053  fprintf(stderr, "-E- Error reading # lines dimensions view01.\n");
24054  exit(EXIT_FAILURE);
24055  }
24056  nc_inq_dimlen(ncid_L1B, dimidv, &nviews);
24057  nc_inq_dimlen(ncid_L1B, dimidy, &num_scans);
24058  nc_inq_dimlen(ncid_L1B, dimidx, &num_pixels);
24059  }
24060 
24061 
24062 
24063  l1cfile->nscan = num_scans;
24064  l1cfile->npix = num_pixels;
24065 
24066  //time line and geolocation attributes------
24067  //************************************************************
24068  //
24069  if(format.type == FT_SPEXONE){
24070  stime = new double[num_scans]();
24071  lat = allocate2d_float(num_scans, num_pixels);
24072  lon = allocate2d_float(num_scans, num_pixels);
24073  status = nc_inq_grp_ncid(ncid_L1B, "BIN_ATTRIBUTES", &scGrp);
24074  check_err(status, __LINE__, __FILE__);
24075  status = nc_inq_varid(scGrp, "image_time", &otId);
24076  check_err(status, __LINE__, __FILE__);
24077  status = nc_get_var_double(scGrp, otId, stime);
24078  check_err(status, __LINE__, __FILE__);
24079  lat = allocate2d_float(num_scans, num_pixels);
24080  lon = allocate2d_float(num_scans, num_pixels);
24081  status = nc_inq_grp_ncid(ncid_L1B, "GEOLOCATION_DATA", &navGrp);
24082  check_err(status, __LINE__, __FILE__);
24083  status = nc_inq_varid(navGrp, "latitude", &latId);//scans x velements
24084  check_err(status, __LINE__, __FILE__);
24085  status = nc_get_var_float(navGrp, latId, &lat[0][0]);
24086  check_err(status, __LINE__, __FILE__);
24087  status = nc_inq_varid(navGrp, "longitude", &lonId);
24088  check_err(status, __LINE__, __FILE__);
24089  status = nc_get_var_float(navGrp, lonId, &lon[0][0]);
24090  check_err(status, __LINE__, __FILE__);
24091  }
24092  else if(format.type == FT_HARP2){
24093  stime = new double[num_frames]();
24094  status = nc_inq_grp_ncid(ncid_L1B, "NAVIGATION", &scGrp);
24095  check_err(status, __LINE__, __FILE__);
24096  status = nc_inq_varid(scGrp, "msec", &otId);
24097  check_err(status, __LINE__, __FILE__);
24098  status = nc_get_var_double(scGrp, otId, stime);
24099  check_err(status, __LINE__, __FILE__);
24100  latframe = allocate3d_float(num_frames,num_scans, num_pixels);
24101  lonframe = allocate3d_float(num_frames,num_scans, num_pixels);
24102  status = nc_inq_grp_ncid(ncid_L1B, "Sensor1", &sen1Grp);
24103  check_err(status, __LINE__, __FILE__);
24104  status = nc_inq_varid(sen1Grp, "Latitude", &latId);//scans x velements
24105  check_err(status, __LINE__, __FILE__);
24106  status = nc_get_var_float(sen1Grp, latId, &latframe[0][0][0]);
24107  check_err(status, __LINE__, __FILE__);
24108  status = nc_inq_varid(sen1Grp, "Longitude", &lonId);
24109  check_err(status, __LINE__, __FILE__);
24110  status = nc_get_var_float(sen1Grp, lonId, &lonframe[0][0][0]);
24111  check_err(status, __LINE__, __FILE__);
24112  }
24113  else if(format.type == FT_HARP){
24114  cout<<"checking lat/lon arrays...HARP.."<<endl;
24115  stime = new double[num_scans]();
24116  lat = allocate2d_float(num_scans, num_pixels);
24117  lon = allocate2d_float(num_scans, num_pixels);
24118  /* stime = new double[num_frames]();
24119  status = nc_inq_grp_ncid(ncid_L1B, "NAVIGATION", &scGrp);
24120  check_err(status, __LINE__, __FILE__);
24121  status = nc_inq_varid(scGrp, "msec", &otId);
24122  check_err(status, __LINE__, __FILE__);
24123  status = nc_get_var_double(scGrp, otId, stime);
24124  check_err(status, __LINE__, __FILE__);
24125  latframe = allocate3d_float(num_frames,num_scans, num_pixels);
24126  lonframe = allocate3d_float(num_frames,num_scans, num_pixels);
24127  status = nc_inq_grp_ncid(ncid_L1B, "Sensor1", &sen1Grp);
24128  check_err(status, __LINE__, __FILE__);
24129 
24130  status = nc_inq_varid(sen1Grp, "Latitude", &latId);//scans x velements
24131  check_err(status, __LINE__, __FILE__);
24132  status = nc_get_var_float(sen1Grp, latId, &latframe[0][0][0]);
24133  check_err(status, __LINE__, __FILE__);
24134  status = nc_inq_varid(sen1Grp, "Longitude", &lonId);
24135  check_err(status, __LINE__, __FILE__);
24136  status = nc_get_var_float(sen1Grp, lonId, &lonframe[0][0][0]);
24137  check_err(status, __LINE__, __FILE__);
24138  */
24139  }
24140  else{ //legacy sensors including OCI
24141  stime = new double[num_scans]();
24142  status = nc_inq_grp_ncid(ncid_L1B, "scan_line_attributes", &scGrp);
24143  check_err(status, __LINE__, __FILE__);
24144  status = nc_inq_varid(scGrp, "time", &otId);
24145  check_err(status, __LINE__, __FILE__);
24146  status = nc_get_var_double(scGrp, otId, stime);
24147  check_err(status, __LINE__, __FILE__);
24148  lat = allocate2d_float(num_scans, num_pixels);
24149  lon = allocate2d_float(num_scans, num_pixels);
24150  status = nc_inq_grp_ncid(ncid_L1B, "geolocation_data", &navGrp);
24151  check_err(status, __LINE__, __FILE__);
24152  status = nc_inq_varid(navGrp, "latitude", &latId);//scans x velements
24153  check_err(status, __LINE__, __FILE__);
24154  status = nc_get_var_float(navGrp, latId, &lat[0][0]);
24155  check_err(status, __LINE__, __FILE__);
24156  status = nc_inq_varid(navGrp, "longitude", &lonId);
24157  check_err(status, __LINE__, __FILE__);
24158  status = nc_get_var_float(navGrp, lonId, &lon[0][0]);
24159  check_err(status, __LINE__, __FILE__);
24160  }
24161 
24162  //find scans bracketing equator
24163  int nad_pix = floor(num_pixels / 2) + 1;
24164  int timeix=0;
24165  nad_pix = nad_pix - 1;
24166  l1cfile->nadpix = nad_pix;
24167 
24168  if(format.type == FT_HARP2 | format.type == FT_HARP){
24169  if (latframe[0][0][nad_pix] > latframe[0][1][nad_pix])
24170  asc_mode = 0;//descending
24171  else
24172  asc_mode = 1;//ascending
24173  }
24174  else{//OCIS/SPEXONE
24175  if (lat[0][nad_pix] > lat[1][nad_pix])
24176  asc_mode = 0;//descending
24177  else
24178  asc_mode = 1;//ascending
24179  }
24180 
24181 
24182  l1cfile->orb_dir = asc_mode;
24183 
24184 //HARP2-----------
24185  if(format.type == FT_HARP2 | format.type == FT_HARP){
24186  for (unsigned k = 0;k < num_frames;k++) {
24187  for (unsigned i = 0;i < num_scans - 1;i++) { //improve with binary search
24188  if (asc_mode == 1 && latframe[k][i][nad_pix] < 0. && latframe[k][i + 1][nad_pix]>0.) {
24189  scan_brack[0] = i + 1;
24190  scan_brack[1] = i + 2;
24191  lat1 = latframe[k][i][nad_pix];
24192  lat2 = latframe[k][i + 1][nad_pix];
24193  lon1 = lonframe[k][i][nad_pix];
24194  lon2 = lonframe[k][i + 1][nad_pix];
24195  timeix=k;
24196  i=num_scans;
24197  k=num_frames;
24198  break;
24199  }
24200 
24201  else if (asc_mode == 0 && latframe[k][i][nad_pix] > 0. && latframe[k][i + 1][nad_pix] < 0) { //descending orbit
24202  scan_brack[0] = i + 2;//negative lat first convention
24203  scan_brack[1] = i + 1;
24204  lat1 = latframe[k][i + 1][nad_pix];
24205  lat2 = latframe[k][i][nad_pix];
24206  lon1 = lonframe[k][i + 1][nad_pix];
24207  lon2 = lonframe[k][i][nad_pix];
24208  timeix=k;
24209  i=num_scans;
24210  k=num_frames;
24211  break;
24212  }
24213  } }//end for
24214  }
24215  else{
24216 
24217 //OCIS/SPEXONE--------
24218  for (unsigned i = 0;i < num_scans - 1;i++) { //improve with binary search
24219  if (asc_mode == 1 && lat[i][nad_pix] < 0. && lat[i + 1][nad_pix]>0.) {
24220  scan_brack[0] = i + 1;
24221  scan_brack[1] = i + 2;
24222  lat1 = lat[i][nad_pix];
24223  lat2 = lat[i + 1][nad_pix];
24224  lon1 = lon[i][nad_pix];
24225  lon2 = lon[i + 1][nad_pix];
24226  timeix=i;
24227  i=num_scans;
24228  break;
24229  }
24230 
24231  else if (asc_mode == 0 && lat[i][nad_pix] > 0. && lat[i + 1][nad_pix] < 0) { //descending orbit
24232  scan_brack[0] = i + 2;//negative lat first convention
24233  scan_brack[1] = i + 1;
24234  lat1 = lat[i + 1][nad_pix];
24235  lat2 = lat[i][nad_pix];
24236  lon1 = lon[i + 1][nad_pix];
24237  lon2 = lon[i][nad_pix];
24238  timeix=i;
24239  i=num_scans;
24240  break;
24241  }
24242  } //end for
24243  }
24244 
24245 
24246  if (scan_brack[0] > -1) {//if file with equat crossing
24247  t1 = stime[timeix];
24248  t2 = stime[timeix + 1];
24249  //interpolate time--linear--this can be improved using Harversine!!
24250  tcross = t1 - lat1 * (t2 - t1) / (lat2 - lat1);//equat crossing time
24251  float dtcross = (tcross - t1) / (t2 - t1);
24252  loncross = lon1 + (lon2 - lon1) * dtcross;//latcross is zero
24253  l1cfile->eqt = tcross;
24254  l1cfile->orbit_node_lon = loncross;
24255 
24256  cout<<"tcross..in ect_sf2.."<<tcross<<endl;
24257  }
24258  else {
24259  l1cfile->eqt = -999.0;
24260  l1cfile->orbit_node_lon = -999.0;
24261  }
24262 
24263  status = nc_close(ncid_L1B);
24264  check_err(status, __LINE__, __FILE__);
24265 
24266  delete [](time_str);
24267  delete [](stime);
24268  delete [](lat);
24269  delete [](lon);
24270  delete [](latframe);
24271  delete [](lonframe);
24272 
24273  return status;
24274  }
24275 
24276 
24277 
24278 
24279 int32_t L1C::ect_sf(const char* filename, l1c_filehandle* l1cfile,L1C_input* l1cinput) { //ect version for single file
24280  int dimid, status;
24281  int asc_mode = 0, scan_brack[2] = { -1,-1 };
24282  float lat1, lat2, lon1, lon2;//lat,lon defined globally
24283  double t1 = -1, t2 = -1;
24284  double tcross,secs;
24285  float loncross;
24286  int tindex;
24287  float **lat=nullptr,**lon=nullptr;
24288  int16_t syear, smon, sday, selyear = -1, selmon = -1, selday = -1;
24289  size_t att_len;
24290 
24291  l1cfile->l1b_name = filename;
24292  selday = l1cinput->selday;
24293  selmon = l1cinput->selmon;
24294  selyear = l1cinput->selyear;
24295 
24296 
24297 
24298  // Open the netcdf4 input file
24299  status = nc_open(filename, NC_NOWRITE, &ncid_L1B);
24300 
24301  if (status != NC_NOERR) {
24302  fprintf(stderr, "-E- %s line %d: nc_open(%s) failed.\n",
24303  __FILE__, __LINE__, filename);
24304  return (1);
24305  }
24306 
24307  //checking input date
24308  status = nc_inq_attlen(ncid_L1B, NC_GLOBAL, "time_coverage_start", &att_len);
24309  check_err(status, __LINE__, __FILE__);
24310  // allocate required space before retrieving values
24311  char* time_str = (char*)malloc(att_len + 1); // + 1 for trailing null
24312  // get global attribute values
24313  status = nc_get_att_text(ncid_L1B, NC_GLOBAL, "time_coverage_start", time_str);
24314  check_err(status, __LINE__, __FILE__);
24315  time_str[att_len] = '\0';
24316  double start_time = isodate2unix(time_str);
24317  unix2ymds(start_time, &syear, &smon, &sday, &secs);
24318 
24319  if (syear == selyear && smon == selmon && sday == selday) {
24320  cout<<"computing equatorial crossing time...............................................................for file."<<filename<<endl;
24321  }
24322  else{
24323  cout<<"input date does not match year.."<<syear<<"month.."<<smon<<"day.."<<sday<<" extracted from the l1b file....."<<endl;
24324  exit(1);
24325  }
24326 
24327  status = nc_inq_dimid(ncid_L1B, "number_of_scans", &dimid);
24328  if (status != NC_NOERR) {
24329  fprintf(stderr, "-E- Error reading number_of_scans.\n");
24330  exit(EXIT_FAILURE);
24331  }
24332  nc_inq_dimlen(ncid_L1B, dimid, &num_scans);
24333 
24334  //across-track bins
24335  status = nc_inq_dimid(ncid_L1B, "ccd_pixels", &dimid);
24336  if (status != NC_NOERR) {
24337  fprintf(stderr, "-E- Error reading number_of_pixels per line...\n");
24338  exit(EXIT_FAILURE);
24339  }
24340  nc_inq_dimlen(ncid_L1B, dimid, &num_pixels);
24341 
24342  l1cfile->nscan = num_scans;
24343  l1cfile->npix = num_pixels;
24344 
24345  lat = allocate2d_float(num_scans, num_pixels);
24346  lon = allocate2d_float(num_scans, num_pixels);
24347 
24348  status = nc_inq_grp_ncid(ncid_L1B, "geolocation_data", &navGrp);
24349  check_err(status, __LINE__, __FILE__);
24350 
24351  status = nc_inq_varid(navGrp, "latitude", &latId);//scans x velements
24352  check_err(status, __LINE__, __FILE__);
24353  status = nc_get_var_float(navGrp, latId, &lat[0][0]);
24354  check_err(status, __LINE__, __FILE__);
24355 
24356  status = nc_inq_varid(navGrp, "longitude", &lonId);
24357  check_err(status, __LINE__, __FILE__);
24358  status = nc_get_var_float(navGrp, lonId, &lon[0][0]);
24359  check_err(status, __LINE__, __FILE__);
24360 
24361  //find scans bracketing equator
24362  int nad_pix = floor(num_pixels / 2) + 1;
24363  nad_pix = nad_pix - 1;
24364  l1cfile->nadpix = nad_pix;
24365 
24366  if (lat[0][nad_pix] > lat[1][nad_pix])
24367  asc_mode = 0;//descending
24368  else
24369  asc_mode = 1;//ascending
24370 
24371  l1cfile->orb_dir = asc_mode;
24372 
24373  for (unsigned i = 0;i < num_scans - 1;i++) { //improve with binary search
24374  if (asc_mode == 1 && lat[i][nad_pix] < 0. && lat[i + 1][nad_pix]>0.) {
24375  scan_brack[0] = i + 1;
24376  scan_brack[1] = i + 2;
24377  lat1 = lat[i][nad_pix];
24378  lat2 = lat[i + 1][nad_pix];
24379  lon1 = lon[i][nad_pix];
24380  lon2 = lon[i + 1][nad_pix];
24381  tindex=i;
24382  i=num_scans;
24383  break;
24384  }
24385 
24386  else if (asc_mode == 0 && lat[i][nad_pix] > 0. && lat[i + 1][nad_pix] < 0) { //descending orbit
24387  scan_brack[0] = i + 2;//negative lat first convention
24388  scan_brack[1] = i + 1;
24389  lat1 = lat[i + 1][nad_pix];
24390  lat2 = lat[i][nad_pix];
24391  lon1 = lon[i + 1][nad_pix];
24392  lon2 = lon[i][nad_pix];
24393  tindex=i;
24394  i=num_scans;
24395  break;
24396  }
24397  } //end for
24398 
24399  //************************************************************************************
24400  //obtain time for lower and upper scan--
24401  //open scan_time (in Fred L1B file is orb_time interpolated)
24402  double* stime = new double[num_scans]();
24403  status = nc_inq_grp_ncid(ncid_L1B, "scan_line_attributes", &scGrp);
24404  check_err(status, __LINE__, __FILE__);
24405 
24406  status = nc_inq_varid(scGrp, "time", &otId);
24407  check_err(status, __LINE__, __FILE__);
24408  status = nc_get_var_double(scGrp, otId, stime);
24409  check_err(status, __LINE__, __FILE__);
24410 
24411  if (scan_brack[0] > -1) {//if file with equat crossing
24412  t1 = stime[tindex];
24413  t2 = stime[tindex + 1];
24414  //interpolate time--linear--this can be improved using Harversine!!
24415  tcross = t1 - lat1 * (t2 - t1) / (lat2 - lat1);//equat crossing time
24416  float dtcross = (tcross - t1) / (t2 - t1);
24417  loncross = lon1 + (lon2 - lon1) * dtcross;//latcross is zero
24418 
24419  l1cfile->eqt = tcross;
24420  l1cfile->orbit_node_lon = loncross;
24421  l1cfile->orb_dir = asc_mode;
24422  }
24423  else {
24424 
24425  l1cfile->eqt = -999.0;
24426  l1cfile->orbit_node_lon = -999.0;
24427  l1cfile->orb_dir = asc_mode;
24428  }
24429 
24430  status = nc_close(ncid_L1B);
24431  check_err(status, __LINE__, __FILE__);
24432 
24433  delete[](stime);
24434  delete[](lat);
24435  delete[](lon);
24436  delete [] (time_str);
24437 
24438 
24439  return status;
24440  }
24441 
24442 
24443 
24444 
24445 
24446 
24447 
24448 int32_t L1C::ect(l1c_filehandle* l1cfile) {
24449  int dimid, status;
24450  int32_t n_files;
24451  std::string str;
24452  const char* ptstr;
24453  int asc_mode, scan_brack[2];
24454  float lat1, lat2, lon1, lon2;
24455  double t1, t2;
24456  n_files = l1cfile->ifiles.size();
24457 
24458  //big loop
24459  for (int i = 0;i < n_files;i++) {
24460  str = l1cfile->ifiles[i];
24461  ptstr = str.c_str();
24462 
24463  // Open the netcdf4 input file
24464  cout << "Opening L1B file..." << l1cfile->ifiles[i] << endl;
24465  status = nc_open(ptstr, NC_NOWRITE, &ncid_L1B);
24466 
24467  if (status != NC_NOERR) {
24468  fprintf(stderr, "-E- Error reading the file.\n");
24469  exit(EXIT_FAILURE);
24470  }
24471 
24472  //Open dimensions
24473  // num_scans
24474  status = nc_inq_dimid(ncid_L1B, "number_of_scans", &dimid);
24475  if (status != NC_NOERR) {
24476  fprintf(stderr, "-E- Error reading number_of_scans.\n");
24477  exit(EXIT_FAILURE);
24478  }
24479  nc_inq_dimlen(ncid_L1B, dimid, &num_scans);
24480  printf("number_of_scans.....%zu\n", num_scans);
24481 
24482  //across-track bins
24483  status = nc_inq_dimid(ncid_L1B, "ccd_pixels", &dimid);
24484  if (status != NC_NOERR) {
24485  fprintf(stderr, "-E- Error reading number_of_pixels per line...\n");
24486  exit(EXIT_FAILURE);
24487  }
24488  nc_inq_dimlen(ncid_L1B, dimid, &num_pixels);
24489  printf("number_of_pixels.....%zu\n", num_pixels);
24490 
24491  lat = allocate2d_float(num_scans, num_pixels);
24492  lon = allocate2d_float(num_scans, num_pixels);
24493 
24494  status = nc_inq_grp_ncid(ncid_L1B, "geolocation_data", &navGrp);
24495  check_err(status, __LINE__, __FILE__);
24496 
24497  status = nc_inq_varid(navGrp, "latitude", &latId);//scans x velements
24498  check_err(status, __LINE__, __FILE__);
24499  status = nc_get_var_float(navGrp, latId, &lat[0][0]);
24500  check_err(status, __LINE__, __FILE__);
24501 
24502  status = nc_inq_varid(navGrp, "longitude", &lonId);
24503  check_err(status, __LINE__, __FILE__);
24504  status = nc_get_var_float(navGrp, lonId, &lon[0][0]);
24505  check_err(status, __LINE__, __FILE__);
24506 
24507  //obtain time for lower and upper scan--
24508  //open scan_time (in Fred L1B file is orb_time interpolated)
24509  double* stime = new double[num_scans]();
24510  status = nc_inq_grp_ncid(ncid_L1B, "scan_line_attributes", &scGrp);
24511  check_err(status, __LINE__, __FILE__);
24512 
24513  status = nc_inq_varid(scGrp, "time", &otId);
24514  check_err(status, __LINE__, __FILE__);
24515  status = nc_get_var_double(scGrp, otId, stime);
24516  check_err(status, __LINE__, __FILE__);
24517 
24518  //find scans bracketing equator
24519  int nad_pix = floor(num_pixels / 2) + 1;
24520 
24521  //also in global attribute startDirection endDirection
24522  if (lat[0][nad_pix] > lat[1][nad_pix])
24523  asc_mode = 0;//descending
24524  else
24525  asc_mode = 1;//ascending
24526 
24527  for (unsigned int i = 0;i < num_scans - 1;i++) { //improve with binary search
24528  if (asc_mode == 1 && lat[i][nad_pix] < 0. && lat[i + 1][nad_pix]>0.) {
24529  scan_brack[0] = i + 1;
24530  scan_brack[1] = i + 2;
24531  lat1 = lat[i][nad_pix - 1];
24532  lat2 = lat[i + 1][nad_pix - 1];
24533  lon1 = lon[i][nad_pix - 1];
24534  lon2 = lon[i + 1][nad_pix - 1];
24535  t1 = stime[i];
24536  t2 = stime[i + 1];
24537 
24538  cout << "lower_scan.." << scan_brack[0] << "upper_scan.." << scan_brack[1] << endl;
24539  cout << "lower_lat.." << lat[i][nad_pix - 1] << "upper_lat.." << lat[i + 1][nad_pix - 1] << endl;
24540  break;
24541 }
24542  else if (asc_mode == 0 && lat[i][nad_pix] > 0. && lat[i + 1][nad_pix] < 0) { //descending orbit
24543  scan_brack[0] = i + 2;
24544  scan_brack[1] = i + 1;
24545  lat1 = lat[i + 1][nad_pix - 1];
24546  lat2 = lat[i][nad_pix - 1];
24547  lon1 = lon[i + 1][nad_pix - 1];
24548  lon2 = lon[i][nad_pix - 1];
24549  t1 = stime[i];
24550  t2 = stime[i + 1];
24551  break;
24552 }
24553  }
24554 
24555  //interpolate time--linear
24556  float tcross = t1 - lat1 * (t2 - t1) / (lat2 - lat1);//equat crossing time
24557  float dtcross = (tcross - t1) / (t2 - t1);
24558  float loncross = lon1 + (lon2 - lon1) * dtcross;//latcross is zero
24559  cout << "tcross...." << tcross << "loncross..." << loncross << endl;
24560 
24561 
24562  cout << "Closing L1B file..." << l1cfile->ifiles[i] << endl;
24563  status = nc_close(ncid_L1B);
24564  check_err(status, __LINE__, __FILE__);
24565 
24566  delete[](stime);
24567  delete[](lat);
24568  delete[](lon);
24569 
24570  }//end big loop
24571 
24572 
24573  return 0;
24574  }
24575 
24576 
24577 
24578 
24579 
24580 
24581 
24582 
24583  //this version includes info coming from Don open file routines--
24584 
24585  int32_t L1C::load_l1c_filehandle4(l1c_filehandle* l1cfile, L1C_input* l1cinput) {
24586  int nfiles;
24587  string filename;
24588  // printf("Loading filehandle with L1B input sensor info\n");
24589 
24590  // openl1b_ocis(file);
24591 
24592 
24593  // file_format format = getFormat(file->name);
24594 
24595  //if (format.type == FT_INVALID) {
24596 
24597  // l1cfile->l1b_name=file->name;
24598 
24599  nfiles = l1cinput->files.size();
24600  // cout<<"number of files to be processed.."<<nfiles<<endl;
24601  for (int j = 0;j < nfiles;j++) {
24602  // cout<<l1cinput->files[j]<<endl;
24603  filename = l1cinput->files[j];
24604  l1cfile->ifiles.push_back(filename);
24605  // cout<<l1cfile->ifiles[j]<<endl;
24606  }
24607 
24608 
24609  //these are going to be default values and not coming actually from opening the files--
24610  /* l1cfile->sd_id=file->sd_id;
24611  l1cfile->format=file->format;
24612  l1cfile->mode=file->mode;
24613  l1cfile->length=file->length;
24614  l1cfile->sensorID=file->sensorID;
24615  l1cfile->subsensorID=file->subsensorID;
24616  */
24617 
24618  // cout<<"file->sd_id.."<<file->sd_id<<"file->format.."<<file->format<<"file->mode.."<<file->mode<<"file->length.."<<file->length<<"file->sensorID.."<<file->sensorID<<"file->subsensorID.."<<file->subsensorID<<endl;
24619  // exit(1);
24620 
24621 
24622  //res_spat;//nc file? or input str
24623  //res_spec=-999.0;;//nc file?
24624 
24625  //time-space limits of image
24626  //syear=0;//from nc
24627  //sday=0;//nc
24628  //minlat_img=-999.0;//from nc
24629  //maxlat_img=-999.0;
24630  //minlon_img=-999.0;
24631  //maxlon_img=-999.0;
24632 
24633  //dimensions--
24634  /* l1cfile->ndets=file->ndets;
24635  l1cfile->nscan=file->nscan;
24636  //n_views=1;//sensor views //nc
24637  //npols=1; //polarization states //nc
24638  l1cfile->nbands=file->nbands;//number of total bands //nc
24639  l1cfile->nband_blue=file->nbands_b;//nc file--this includes uv + visible bands//nc
24640  l1cfile->nband_red=file->nbands_r;//nc--this includes nir + visible bands
24641  l1cfile->nband_swir=file->nbands_swir;//nc--
24642  l1cfile->npix=file->npix;
24643  */
24644 
24645  // cout<<"file->name"<<file->name<<"file->sd_id"<<file->sd_id<<"file->format"<<file->format<<"file->mode"<<file->mode<<"file->length.."<<file->length<<"file->sensorID"<<file->sensorID<<"file->subsensorID"<<file->subsensorID<<endl;
24646  // cout<<"file->ndets"<<file->ndets<<"file->nscan"<<file->nscan<<"file->nbands.."<<file->nbands<<"file->nbands_b"<<file->nbands_b<<"file->nbands_swir"<<file->nbands_swir<<"file->npix"<<file->npix<<endl;
24647  // exit(1);
24648 
24649 
24650 
24651  //sensor characteritics
24652  //views=nullptr;//nc file !!indexes are not defined//?? no pointer in filehandle, nc
24653  //pols[0] = 0;//0: non-pol, 1: cross, 2: parall//nc file
24654  //pols[1] = 0;//0: non-pol, 1: cross, 2: parall
24655  //pols[2] = 0;//0: non-pol, 1: cross, 2: parall
24656  //bbands=nullptr;//nc file group sensor_band_parameters !! array with bands wavelengths//fwwave pointer in filehandle
24657  //rbands=nullptr;//nc file
24658  //swirbands=nullptr;//nc file
24659 
24660  //navigation attributes
24661  // l1cfile->orbit_number=file->orbit_number;
24662  //orb_dir=-1;//nc file global attributes--0 asc 1 des file//nc
24663  // l1cfile->orbit_node_lon=file->orbit_node_lon;//this is node_crossing_time
24664 
24665  //geolocation attributes
24666  // l1cfile->terrain_corrected=file->terrain_corrected;
24667 
24668  //cloud_height=nullptr;//anc file or observ data group in nc?
24669  //More iput L1C parameters-----
24670  l1cfile->l1c_pflag = l1cinput->l1c_pflag;
24671  l1cfile->swtnum = l1cinput->swtnum;
24672 
24673 
24674  for (int j = 0;j < 10;j++) {
24675  l1cfile->selgran[j] = l1cinput->selgran[j];
24676  }
24677  //projection params
24678  l1cfile->gres = l1cinput->gres;
24679  l1cfile->proj_type = l1cinput->l1c_proj;
24680  l1cfile->cloud_corrected = l1cinput->cloud_correct;
24681  //multi attributes (view, pol, bands)
24682  l1cfile->overlap_vflag = l1cinput->overlap_vflag;
24683  l1cfile->overlap_pflag = l1cinput->overlap_pflag;
24684  l1cfile->overlap_bflag = l1cinput->overlap_bflag;
24685  //uncertainty params l1c merged products
24686  l1cfile->unc_meth = l1cinput->unc_meth;
24687  l1cfile->unc_thres_v = l1cinput->unc_thres_v;
24688  l1cfile->unc_thres_p = l1cinput->unc_thres_p;
24689  l1cfile->unc_thres_b = l1cinput->unc_thres_b;
24690 
24691  //calibration attributes
24692  //l1cfile->Fobar=file->Fobar;//nc
24693 
24694  cout << "ok transfering filehandle to l1c_filehandle info.." << endl;
24695  return 0;
24696  }
24697 
24698 
24699 }//close l1c namespace
int32_t binL1C_sbs_line_l2(int swtd, L1C *l1c, l2_str *l2str, l1c_filehandle *l1cfile, L1C_input *l1cinput, int16_t *swtd_id, int16_t *file_id, int16_t *nfiles_swt, float **lat_gd, float **lon_gd, float *az_east, float **lat_asort, short **index_xy, float ****binmean_prod, int ****bincount, size_t sline, int granid)
float ** Lt_blue
Definition: l1c_str.h:50
bool binIntersectsPix2corn2(int32_t row, int32_t col, double **lat_cgd, double **lon_cgd, Box_t &pixelBox, double areaFracBox[3][3])
data_t t[NROOTS+1]
Definition: decode_rs.h:77
int32_t binL1C_wgranule5(int swtd, l1c_filehandle *l1cfile, L1C_input *l1cinput, int16_t *swtd_id, int16_t *odir, int16_t *file_id, int16_t *nfiles_swt)
float * offsetprod
Definition: l2_str.h:58
bool binIntersectsPix4corn(int32_t row, int32_t col, double **lat_cgd, double **lon_cgd, Polygon_t &pixelPoly, double &areaFrac)
Utility functions for allocating and freeing three-dimensional arrays of various types.
#define NX
Definition: main_biosmap.c:51
int32_t binL1C_wgranule7(int swtd, l1c_filehandle *l1cfile, L1C_input *l1cinput, int16_t *swtd_id, int16_t *odir, int16_t *file_id, int16_t *nfiles_swt)
int j
Definition: decode_rs.h:73
int32_t day
int status
Definition: l1_czcs_hdf.c:32
int orb_interp(size_t n_orb_rec, size_t sdim, double *torb, orb_array *p, orb_array *v, double *time, orb_array *posi, orb_array *veli)
int32_t ect_swt(int swt, l1c_filehandle *l1cfile, int32_t norbs, double *tswt, double *latswt, double *lonswt, float *tcross, float *loncross)
int32_t across_gridlines_l1c_vec2(int swtd, l1c_filehandle *l1cfile, L1C_input *l1cinput, float *lati2, float *loni2, float **lat_gd, float **lon_gd, float *az_east)
void check_err(const int stat, const int line, const char *file)
Definition: nc4utils.c:35
float **** allocate4d_float(size_t nr, size_t nz, size_t ny, size_t nx)
Allocate a four-dimensional array of type float of a given size.
Definition: allocate4d.c:56
int orb_interp2(size_t n_orb_rec, size_t sdim, double *torb, orb_array2 *p, orb_array2 *v, double *time, orb_array2 *posi, orb_array2 *veli)
float ** Lt_SWIR
Definition: l1c_str.h:52
@ FT_HARP
Definition: filetype.h:62
These are used to scale the SD before writing it to the HDF4 file The default is and which means the product is not scaled at all Since the product is usually stored as a float inside of this is a way to write the float out as a integer l2prod min
float ** l2prod
Definition: l2_str.h:55
int32_t swtime_vec(int swtd, L1C_input *l1cinput, l1c_filehandle *l1cfile, int16_t time_index[6], std::vector< double > &tvec, double tcross, double mgv1, double *tmgv1)
float orb_array[3]
char l2prod[2048]
Definition: l1c_input.h:42
std::string l1b_name
int *** allocate3d_int(size_t nz, size_t ny, size_t nx)
Allocate a three-dimensional array of type int of a given size.
Definition: allocate3d.c:45
int32_t open_l2tol1c(l1c_filehandle *l1cfile, L1C_input *l1cinput)
size_t nl2prod
Definition: l2_str.h:56
#define NULL
Definition: decode_rs.h:63
float * lonpix2
Definition: l1c_str.h:72
real, dimension(260) sb
int32_t mov_sd4(l1c_filehandle *l1cfile, L1C_input *l1cinput, double *tcross, int16_t *file_id, int16_t *swtd_id, int16_t *nfiles_swt, double *ect_swtd, int16_t *tod, int16_t *orbdir, float *mgv_swath)
int32_t write_L1C_granule(int swtd, l1c_filehandle *l1cfile, L1C_input *l1cinput, double *tmgv, float **lat_gd, float **lon_gd)
float * tilt
Definition: l2_str.h:59
int32_t ect(l1c_filehandle *l1cfile)
int16_t selgran[10]
Definition: l1c_input.h:88
bool binIntersectsPix4corn2(int32_t row, int32_t col, double **lat_cgd, double **lon_cgd, Polygon_t &pixelPoly, double areaFracBox[3][3])
int32_t time_swt3(int swtd, l1c_filehandle *l1cfile, L1C_input *l1cinput, double *ect_d, int16_t *swtdid, int16_t *fileid, int16_t *nfiles_swt, float *mgv_swt, double *time_mgv)
float binlonmax
Definition: l1c_input.h:78
float unc_thres_p
Definition: l1c_input.h:110
float binlatmax
Definition: l1c_input.h:76
int32_t fileix
Definition: l1c_input.h:82
void unix2ymds(double usec, int16_t *year, int16_t *mon, int16_t *day, double *secs)
Definition: unix2ymds.c:8
int32_t swtnum
Definition: l1c_input.h:97
float * latpix
Definition: l1c_str.h:69
float * slopeprod
Definition: l2_str.h:57
int32_t across_gridlines_l1c2(int swtd, l1c_filehandle *l1cfile, L1C_input *l1cinput, int16_t *swtd_id, int16_t *file_id, int16_t *nfiles_swt, float *lati3, float *loni3, float **lat_cgd, float **lon_cgd, float *az_east)
float h[MODELMAX]
Definition: atrem_corl1.h:131
float * senazpix
Definition: l1c_str.h:68
float * lat
float tm[MODELMAX]
int32_t binL1C_wgranule_aw2(int swtd, l1c_filehandle *l1cfile, L1C_input *l1cinput, l1c_str *l1cstr, float **lat_gd, float **lon_gd, float *az_east, float **Ltfracsum, float **areabinsum, float **nobs_perbin, size_t sline)
int32_t selday
Definition: l1c_input.h:94
int syear
Definition: l1_czcs_hdf.c:15
u5 which has been done in the LOCALGRANULEID metadata should have an extension NRT It is requested to identify the NRT production Changes from v6 which may affect scientific output
Definition: HISTORY.txt:186
int32_t binL1C_wgranule_aw(int swtd, l1c_filehandle *l1cfile, L1C_input *l1cinput, int16_t *swtd_id, int16_t *odir, int16_t *file_id, int16_t *nfiles_swt)
int32_t swtime_swt2(int swt, L1C_input *l1cinput, l1c_filehandle *l1cfile, int32_t norbs, double *tswt, double tcross, double mgv, double *tmgv)
int32_t azmean_swt(int swt, L1C_input *l1cinput, l1c_filehandle *l1cfile, float *lati, float *loni)
int32_t gransize
Definition: l1c_input.h:83
float * latpix2
Definition: l1c_str.h:71
int **** allocate4d_int(size_t nr, size_t nz, size_t ny, size_t nx)
Allocate a four-dimensional array of type int of a given size.
Definition: allocate4d.c:12
int32_t ect_sf(const char *filename, l1c_filehandle *l1cfile, L1C_input *l1cinput)
int32_t overlap_pflag
Definition: l1c_input.h:105
@ string
float * lonpix
Definition: l1c_str.h:70
int32_t pix_corners4_l1c3(l1c_filehandle *l1cfile, L1C_input *l1cinput, float dist_u, float dist_v, float azpix, int32_t scanline, int32_t pix, float pixlat, float pixlon, float pixLt, short row, short col, float **lat_gd, float **lon_gd, double areaFracBox[3][3], double areaBinbox[3][3])
int swapc_bytes(char *in, int nbyte, int ntime)
Definition: swapc_bytes.c:4
int sday
Definition: l1_czcs_hdf.c:15
int32_t l1c_proj
Definition: l1c_input.h:100
int32_t across_gridlines_l1c_vec3(int swtd, l1c_filehandle *l1cfile, L1C_input *l1cinput, float *lati2, float *loni2, float **lat_gd, float **lon_gd, float *az_east)
int time_str(short, short, int, char *)
Definition: time_str.c:3
bool binIntersectsPix2corn(int32_t row, int32_t col, double **lat_cgd, double **lon_cgd, Box_t &pixelBox, double &areaFrac)
float ** Lt
Definition: l1c_str.h:49
const char * azeast_name
int32_t openL1Cgrid(int swtd, l1c_str *l1cstr, l1c_filehandle *l1cfile, L1C_input *l1cinput, int16_t *swtd_id, int16_t *file_id, int16_t *nfiles_swt, float **lat_gd, float **lon_gd, float *az_east, float **lat_asort, short **index_xy)
float binlonmin
Definition: l1c_input.h:77
double precision function f(R1)
Definition: tmd.lp.f:1454
int32_t xy_pixsize(int swtd, l1c_filehandle *l1cfile, int16_t *swtd_id, int16_t *odir, int16_t *file_id, int16_t *nfiles_swt, float **binx_size_u, float **binx_size_v)
std::string tswt_ini
Definition: l1c.h:43
data_t tmp
Definition: decode_rs.h:74
void cross_product_double(double vector_a[], double vector_b[], double temp[])
Definition: l1c.cpp:88
double binL1C_pixelpoly(l1c_filehandle *l1cfile, L1C_input *l1cinput, l1c_str *l1cstr, short gd_row, short gd_col, int32_t pix)
Utility functions for allocating and freeing four-dimensional arrays of various types.
int32_t xy_pixsize_sf2(const char *filename, l1c_filehandle *l1cfile, L1C_input *l1cinput, float **pix_size_u, float **pix_size_v, float **lat_gd, float **lon_gd, double **lat_cgd, double **lon_cgd, float **Ltfracsum, float **areabinsum, float **nobs_perbin)
bool sbs2_l1c(L1C_input *l1cinput, int32_t ydim, int32_t xdim, float **alat, short **alat_index, float latpix, float lonpix, float **lon_gd, short *erow, short *ecol)
file_format getFormat(char *filename)
Definition: filetype.c:192
int32_t sensor
Definition: l1c_input.h:93
float * lonpix
Definition: l2_str.h:77
const char * gridname
int32_t ect_sf2(const char *filename, L1C_input *l1cinput, l1c_filehandle *l1cfile)
int32_t load_l1c_filehandle4(l1c_filehandle *l1cfile, L1C_input *l1cinput)
int32_t across_gridlines_l1c_vec(int swtd, l1c_filehandle *l1cfile, L1C_input *l1cinput, float *lati2, float *loni2, float **lat_gd, float **lon_gd, float *az_east)
float32 slope[]
Definition: l2lists.h:30
bg::model::point< double, 2, bg::cs::spherical_equatorial< bg::degree > > Point_t
Definition: get_dataday.cpp:23
int32_t binL1C_wgranule4(int swtd, l1c_filehandle *l1cfile, L1C_input *l1cinput, int16_t *swtd_id, int16_t *odir, int16_t *file_id, int16_t *nfiles_swt)
int32_t swtime_swt(int swt, L1C_input *l1cinput, l1c_filehandle *l1cfile, int32_t norbs, int16_t time_index[6], double *tswt, double tcross, double mgv, double *tmgv)
int32_t overlap_vflag
Definition: l1c_input.h:104
float *** allocate3d_float(size_t nz, size_t ny, size_t nx)
Allocate a three-dimensional array of type float of a given size.
Definition: allocate3d.c:77
#define M_PI
Definition: pml_iop.h:15
int32_t pix_corners4_l1c(l1c_filehandle *l1cfile, L1C_input *l1cinput, float dist_u, float dist_v, float azpix, int32_t scanline, int32_t pix, float pixlat, float pixlon, float pixLt, float **lat_asort, short **index_xy, float **lat_gd, float **lon_gd, double **lat_cgd, double **lon_cgd, double areaFracBox[3][3], float **Ltfracsum, float **areabinsum, float **nobs_perbin)
int32_t mov_sd3(l1c_filehandle *l1cfile, L1C_input *l1cinput, double *tcross, int16_t *file_id, int16_t *swtd_id, int16_t *nfiles_swt, double *ect_swtd, int16_t *tod, int16_t *orbdir, float *mgv_swath)
char filename[FILENAME_MAX]
Definition: atrem_corl1.h:122
unsigned char ** allocate2d_uchar(size_t h, size_t w)
Allocate a two-dimensional array of type unsigned char of a given size.
Definition: allocate2d.c:41
float * ac[MAX_BANDS]
std::string tswt_end
int32_t interp_swt_dist_vec(int swtd, l1c_filehandle *l1cfile, L1C_input *l1cinput, double *time_mgv, float *lati, float *loni, float *lati2, float *loni2)
Definition: l1c.cpp:76
int32_t nbinx
Definition: l1c_input.h:91
Utility functions for allocating and freeing two-dimensional arrays of various types.
@ FT_SPEXONE
Definition: filetype.h:60
std::vector< std::string > files
Definition: l1c_input.h:70
float gamma
Definition: color_dtdb.py:447
int32_t overlap_bflag
Definition: l1c_input.h:106
data_t b[NROOTS+1]
Definition: decode_rs.h:77
int32_t selmon
Definition: l1c_input.h:95
int32_t selyear
Definition: l1c_input.h:96
int32_t ect_vec(int swt, l1c_filehandle *l1cfile, std::vector< double > &tvect, std::vector< double > &latvec, std::vector< double > &lonvec, float *tcross, float *loncross)
#define omf2
Definition: l1_czcs_hdf.c:703
#define NY
Definition: main_biosmap.c:52
const char * str
Definition: l1c_msi.cpp:35
@ FT_HARP2
Definition: filetype.h:61
float * latpix
Definition: l2_str.h:76
bg::model::point< double, 2, bg::cs::geographic< bg::degree > > Point_t
Definition: l1c.cpp:71
subroutine geometry
std::string tswt_ini_file
an array had not been initialized Several spelling and grammar corrections were which is read from the appropriate MCF the above metadata values were hard coded A problem calculating the average background DN for SWIR bands when the moon is in the space view port was corrected The new algorithm used to calculate the average background DN for all reflective bands when the moon is in the space view port is now the same as the algorithm employed by the thermal bands For non SWIR changes in the averages are typically less than Also for non SWIR the black body DNs remain a backup in case the SV DNs are not available For SWIR the changes in computed averages were larger because the old which used the black body suffered from contamination by the micron leak As a consequence of the if SV DNs are not available for the SWIR the EV pixels will not be the granule time is used to identify the appropriate tables within the set given for one LUT the first two or last two tables respectively will be used for the interpolation If there is only one LUT in the set of it will be treated as a constant LUT The manner in which Earth View data is checked for saturation was changed Previously the raw Earth View DNs and Space View DNs were checked against the lookup table values contained in the table dn_sat The change made is to check the raw Earth and Space View DNs to be sure they are less than the maximum saturation value and to check the Space View subtracted Earth View dns against a set of values contained in the new lookup table dn_sat_ev The metadata configuration and ASSOCIATEDINSTRUMENTSHORTNAME from the MOD02HKM product The same metatdata with extensions and were removed from the MOD021KM and MOD02OBC products ASSOCIATEDSENSORSHORTNAME was set to MODIS in all products These changes are reflected in new File Specification which users may consult for exact the pow functions were eliminated in Emissive_Cal and Emissive bands replaced by more efficient code Other calculations throughout the code were also made more efficient Aside from a few round off there was no difference to the product The CPU time decreased by about for a day case and for a night case A minor bug in calculating the uncertainty index for emissive bands was corrected The frame the required RAM for each execution is MB on the DEC ALPHA and MB on the SGI Octane v2
Definition: HISTORY.txt:728
int32_t interp_swt_dist3(int swtd, l1c_filehandle *l1cfile, L1C_input *l1cinput, int16_t *swtd_id, int16_t *file_id, int16_t *nfiles_swt, double *time_mgv, float *lati, float *loni, float *lati2, float *loni2)
char ofile[FILENAME_MAX]
Definition: l1c_input.h:33
int32_t open_l1atol1c(L1C_input *l1cinput, l1c_filehandle *l1cfile)
bool binIntersectsPix4corn4_l1c(l1c_filehandle *l1cfile, L1C_input *l1cinput, short row, short col, float **lat_gd, float **lon_gd, Polygon_t &pixelPoly, double areaFracBox[3][3], double areabinBox[3][3])
int32_t cloud_correct
Definition: l1c_input.h:102
float unc_thres_v
Definition: l1c_input.h:109
int32_t nbands
double tai58_to_unix(double tai58)
Definition: yds2tai.c:29
void sbs2_sort_latgd(l1c_filehandle *l1cfile, float **lat_gd, float **lat_asort, short **index_xy)
int32_t search_SOCEA(L1C_input *l1cinput, l1c_filehandle *l1cfile, float **lat_gd, float **lon_gd, double *time_mgv, float ect, float loncross)
this program makes no use of any feature of the SDP Toolkit that could generate such a then geolocation is calculated at that and then aggregated up to Resolved feature request Bug by adding three new int8 SDSs for each high resolution offsets between the high resolution geolocation and a bi linear interpolation extrapolation of the positions This can be used to reconstruct the high resolution geolocation Resolved Bug by delaying cumulation of gflags until after validation of derived products Resolved Bug by setting Latitude and Longitude to the correct fill resolving to support Near Real Time because they may be unnecessary if use of entrained ephemeris and attitude data is turned resolving bug report Corrected to filter out Aqua attitude records with missing status helping resolve bug MOD_PR03 will still correctly write scan and pixel data that does not depend upon the start time
Definition: HISTORY.txt:248
int32_t binL1C_wgranule3(int swtd, l1c_filehandle *l1cfile, L1C_input *l1cinput, int16_t *swtd_id, int16_t *odir, int16_t *file_id, int16_t *nfiles_swt)
int32_t iscan
float unc_thres_b
Definition: l1c_input.h:111
int latlon_interp(size_t n_orb_rec, size_t num_gridlines, size_t num_pixels, double *torb, float **lat, float **lon, double *time, float *lati, float *loni)
int32_t savebinL1C_v2(int swtd, L1C_input *l1cinput, l1c_filehandle *l1cfile, float **lat_gd, float **lon_gd, float **Ltfracsum, float **areafracsum, float **nobs_perbin)
double ** allocate2d_double(size_t h, size_t w)
Allocate a two-dimensional array of type double of a given size.
Definition: allocate2d.c:153
int32_t azmean_swt2(int swt, L1C_input *l1cinput, l1c_filehandle *l1cfile, float *lati, float *loni)
float * lon
data_t s[NROOTS]
Definition: decode_rs.h:75
bg::model::polygon< Point_t > Polygon_t
Definition: l1c.cpp:72
int32_t l1c_pflag
Definition: l1c_input.h:90
int32_t across_gridlines_l1c(int swtd, l1c_filehandle *l1cfile, L1C_input *l1cinput, int16_t *swtd_id, int16_t *file_id, int16_t *nfiles_swt, float *lati3, float *loni3, float **lat_cgd, float **lon_cgd, float *az_east)
int32_t pixcornBox(l1c_filehandle *l1cfile, L1C_input *l1cinput, float dist_u, float dist_v, float azpix, int32_t scanline, int32_t pix, float pixlat, float pixlon, float pixLt, short gd_row, short gd_col, float **lat_gd, float **lon_gd, Polygon_t &pixelPoly)
void search_rc_l1c(L1C_input *l1cinput, l1c_filehandle *l1cfile, float lat_pix, float lon_pix, double otime_pix, float lon_eqc, short *rowindex, short *colindex, short Nneg)
int32_t binL1C_wgranule6(int swtd, l1c_filehandle *l1cfile, L1C_input *l1cinput, int16_t *swtd_id, int16_t *odir, int16_t *file_id, int16_t *nfiles_swt)
int32_t gwindowTopix_l1c(l1c_filehandle *l1cfile, L1C_input *l1cinput, short gd_row, short gd_col, float **lat_gd, float **lon_gd, double **latcornBox, double **loncornBox)
short ** allocate2d_short(size_t h, size_t w)
Allocate a two-dimensional array of type short of a given size.
Definition: allocate2d.c:97
float ** allocate2d_float(size_t h, size_t w)
Allocate a two-dimensional array of type float of a given size.
Definition: allocate2d.c:125
double ymds2unix(short year, short month, short day, double secs)
l2prod offset
int32_t unc_meth
Definition: l1c_input.h:108
no change in intended resolving MODur00064 Corrected handling of bad ephemeris attitude resolving resolving GSFcd00179 Corrected handling of fill values for[Sensor|Solar][Zenith|Azimuth] resolving MODxl01751 Changed to validate LUT version against a value retrieved from the resolving MODxl02056 Changed to calculate Solar Diffuser angles without adjustment for estimated post launch changes in the MODIS orientation relative to incidentally resolving defects MODxl01766 Also resolves MODxl01947 Changed to ignore fill values in SCI_ABNORM and SCI_STATE rather than treating them as resolving MODxl01780 Changed to use spacecraft ancillary data to recognise when the mirror encoder data is being set by side A or side B and to change calculations accordingly This removes the need for seperate LUTs for Side A and Side B data it makes the new LUTs incompatible with older versions of the and vice versa Also resolves MODxl01685 A more robust GRing algorithm is being which will create a non default GRing anytime there s even a single geolocated pixel in a granule Removed obsolete messages from seed as required for compatibility with version of the SDP toolkit Corrected test output file names to end in per delivery and then split off a new MYD_PR03 pcf file for Aqua Added AssociatedPlatformInstrumentSensor to the inventory metadata in MOD01 mcf and MOD03 mcf Created new versions named MYD01 mcf and MYD03 where AssociatedPlatformShortName is rather than Terra The program itself has been changed to read the Satellite Instrument validate it against the input L1A and LUT and to use it determine the correct files to retrieve the ephemeris and attitude data from Changed to produce a LocalGranuleID starting with MYD03 if run on Aqua data Added the Scan Type file attribute to the Geolocation copied from the L1A and attitude_angels to radians rather than degrees The accumulation of Cumulated gflags was moved from GEO_validate_earth_location c to GEO_locate_one_scan c
Definition: HISTORY.txt:464
int32_t pix_corners4_l1c2(l1c_filehandle *l1cfile, L1C_input *l1cinput, float dist_u, float dist_v, float azpix, int32_t scanline, int32_t pix, float pixlat, float pixlon, float pixLt, short row, short col, float **lat_gd, float **lon_gd, double areaFracBox[3][3], double **Ltfracsum, double **areabinsum, float **nobs_perbin)
int32_t mov_sd2(l1c_filehandle *l1cfile, L1C_input *l1cinput, double *tcross, int16_t *file_id, int16_t *swtd_id, int16_t *nfiles_swt, double *ect_swtd, int16_t *tod, int16_t *orbdir, float *mgv_swath)
bg::model::polygon< Point_t > Polygon_t
Definition: get_dataday.cpp:25
void unix2ymdhms(double usec, int16_t *year, int16_t *mon, int16_t *day, int16_t *hour, int16_t *min, double *sec)
Definition: unix2ymdhms.c:8
double cross_product_norm_double(double vector_a[], double vector_b[])
Definition: l1c.cpp:94
int32_t binL1C_wgranule2(int swtd, l1c_filehandle *l1cfile, L1C_input *l1cinput, int16_t *swtd_id, int16_t *odir, int16_t *file_id, int16_t *nfiles_swt)
bool binIntersectsPix4corn3(short row, short col, double **lat_cgd, double **lon_cgd, Polygon_t &pixelPoly, double areaFracBox[3][3], double areabinBox[3][3])
#define abs(a)
Definition: misc.h:90
int i
Definition: decode_rs.h:71
this program makes no use of any feature of the SDP Toolkit that could generate such a then geolocation is calculated at that and then aggregated up to Resolved feature request Bug by adding three new int8 SDSs for each high resolution offsets between the high resolution geolocation and a bi linear interpolation extrapolation of the positions This can be used to reconstruct the high resolution geolocation Resolved Bug by delaying cumulation of gflags until after validation of derived products Resolved Bug by setting Latitude and Longitude to the correct fill resolving to support Near Real Time because they may be unnecessary if use of entrained ephemeris and attitude data is turned on(as it will be in Near-Real-Time processing).
How many dimensions is the output array Default is Not sure if anything above will work correctly strcpy(l2prod->title, "no title yet")
int32_t xy_pixsize_sf3(const char *filename, l1c_filehandle *l1cfile, L1C_input *l1cinput, float **pix_size_u, float **pix_size_v, float **lat_gd, float **lon_gd, double **lat_cgd, double **lon_cgd, float **Ltfracsum, float **areabinsum, float **nobs_perbin, float **lat_asort, short **index_xy)
@ NBANDS
Definition: make_L3_v1.1.c:53
int32_t interp_swt_dist2(int swtd, l1c_filehandle *l1cfile, L1C_input *l1cinput, int16_t *swtd_id, int16_t *file_id, int16_t *nfiles_swt, double *time_mgv, float *lati, float *loni, float *lati2, float *loni2)
int k
Definition: decode_rs.h:73
std::vector< std::string > ifiles
int32_t binL1C_sbs_line(int swtd, L1C *l1c, l1c_str *l1cstr, l1c_filehandle *l1cfile, L1C_input *l1cinput, int16_t *swtd_id, int16_t *file_id, int16_t *nfiles_swt, float **lat_gd, float **lon_gd, float *az_east, float **lat_asort, short **index_xy, float ****binLt, int ****bincount, size_t recnums, int granid)
float p[MODELMAX]
Definition: atrem_corl1.h:131
int32_t create_SOCEA(int swtd, L1C_input *l1cinput, l1c_filehandle *l1cfile, float **lat_gd, float **lon_gd)
bg::model::box< Point_t > Box_t
Definition: l1c.cpp:73
l2prod max
def ctime(the_file)
Definition: ProcUtils.py:332
float binlatmin
Definition: l1c_input.h:75
int32_t time_swt2(int swtd, l1c_filehandle *l1cfile, L1C_input *l1cinput, double *ect_d, int16_t *swtdid, int16_t *fileid, int16_t *nfiles_swt, float *mgv_swt, double *time_mgv)
double isodate2unix(const char *isodate)
Definition: unix2isodate.c:61
float ** Lt_red
Definition: l1c_str.h:51
double orb_array2[3]
int count
Definition: decode_rs.h:79
int32_t interp_swt1(int swtd, l1c_filehandle *l1cfile, L1C_input *l1cinput, int16_t *swtd_id, int16_t *file_id, int16_t *nfiles_swt, double *time_mgvi, orb_array *velig, float *lati, float *loni)