예제 #1
0
/***************************************************************
 * Get_timeDelta:
 * Return the time difference, in seconds, between the start
 * of the state vectors (in the PPDR) and the start of the image
 * (as described in the DSSR).  Write this time to the given
 * meta_parameters->state_vectors structure.*/
double get_timeDelta(ceos_description *ceos,struct pos_data_rec *ppdr,meta_parameters *meta)
{
    ymd_date imgDate;
    julian_date imgJD,stJD;
    hms_time imgTime,stTime;
    double imgSec,stSec;/*Seconds since 1900 for start of image and start of state vectors*/

/*Read time of *start* of state vectors*/
    stJD.year = (int) ppdr->year;
    stJD.jd = (int) ppdr->gmt_day;
    date_sec2hms(ppdr->gmt_sec,&stTime);
    stSec=date2sec(&stJD,&stTime);

/*Compute the *scene* start time from the CEOS DSSR: */
    /* begin with scene center time */
    if (ceos->facility == BEIJING)
      date_dssr2time(ceos->dssr.inp_sctim,&imgDate,&imgTime);
    else
      date_dssr2date(ceos->dssr.inp_sctim,&imgDate,&imgTime);
    date_ymd2jd(&imgDate,&imgJD);
    imgSec=date2sec(&imgJD,&imgTime);

    if (ceos->processor==FOCUS && ceos->product==CCSD) {
        /* do nothing-- dssr "inp_sctim" already gives scene start time */
    }
    else if (0!=strcmp(ceos->dssr.az_time_first,""))
    { /* e.g., ESA data.  "az_time_first" field gives start of image */
        date_dssr2time(ceos->dssr.az_time_first,&imgDate,&imgTime);
        imgSec=date2sec(&imgJD,&imgTime);
    }
    else if (ceos->facility==EOC)
    {
        imgSec-=ceos->dssr.sc_lin*fabs(meta->sar->azimuth_time_per_pixel);
    }
    else {/*Convert scene center time to scene *start* time, by
       subtracting off the center line # * the time/line */
        imgSec-=ceos->dssr.sc_lin*fabs(meta->sar->azimuth_time_per_pixel);
    }
    /*
    // Complex ALOS data have an additional 1 sec shift
    // Still under investigation: Need word from DQ on this
    if (ceos->facility==EOC && ceos->product==SLC)
      imgSec -= 1.0;
    */

    /*Convert scene center # of seconds back to date/time*/
    sec2date(imgSec,&imgJD,&imgTime);

/*Write image time to meta->state_vectors structure*/
    meta->state_vectors->year   = (int) imgJD.year;
    meta->state_vectors->julDay = (int) imgJD.jd;
    meta->state_vectors->second = date_hms2sec(&imgTime);

/*Return the time between state vector start and image start*/
    return stSec-imgSec;
}
예제 #2
0
void ceos_init_alos_stVec(const char *fName, ceos_description *ceos, 
			  meta_parameters *meta)
{
  struct pos_data_rec ppdr;

  // Read platform position record
  get_ppdr(fName,&ppdr);

  // Initialize state vector
  int vector_count=3;
  double data_int = meta->sar->original_line_count / 2
    * fabs(meta->sar->azimuth_time_per_pixel);
  while (fabs(data_int) > 15.0) {
    data_int /= 2;
    vector_count = vector_count*2-1;
  }
  meta->state_vectors = meta_state_vectors_init(vector_count);
  meta->state_vectors->vector_count = vector_count;

  // Determine image start time
  ymd_date imgDate;
  julian_date imgJD;
  hms_time imgTime;
  date_dssr2date(ceos->dssr.inp_sctim, &imgDate, &imgTime);
  date_ymd2jd(&imgDate, &imgJD);
  double imgSec = date2sec(&imgJD, &imgTime);
  imgSec -= ceos->dssr.sc_lin*fabs(meta->sar->azimuth_time_per_pixel);
  
  sec2date(imgSec, &imgJD, &imgTime);
  meta->state_vectors->year   = (int) imgJD.year;
  meta->state_vectors->julDay = (int) imgJD.jd;
  meta->state_vectors->second = date_hms2sec(&imgTime);

  // Assign position and velocity for center of image
  int n = (vector_count - 1)/2;
  double timeStart = get_timeDelta(ceos, &ppdr, meta);
  double time = timeStart + n*data_int;
  stateVector st;
  st.pos.x = ppdr.orbit_ele[0];
  st.pos.y = ppdr.orbit_ele[1];
  st.pos.z = ppdr.orbit_ele[2];
  st.vel.x = ppdr.orbit_ele[3];
  st.vel.y = ppdr.orbit_ele[4];
  st.vel.z = ppdr.orbit_ele[5];
  meta->state_vectors->vecs[n].vec = st;
  meta->state_vectors->vecs[n].time = time - timeStart;

  int ii;
  double newTime;
  for (ii=0; ii<n; ii++) {
    newTime = time - (n - ii)*data_int;
    meta->state_vectors->vecs[ii].time = newTime - timeStart;
    meta->state_vectors->vecs[ii].vec = propagate(st, time, newTime);
  }
  for (ii=n+1; ii<vector_count; ii++) {
    newTime = time + (vector_count - n - 1)*data_int;
    meta->state_vectors->vecs[ii].time = newTime - timeStart;
    meta->state_vectors->vecs[ii].vec = propagate(st, time, newTime);
  }
}
예제 #3
0
/*
   Compute the average ymd_date date and hms_time time
  -----------------------------------------------------*/
void average_ymdTimes(ymd_date *date1, ymd_date *date2,
                      hms_time *time1, hms_time *time2,
                      ymd_date *ave_date, hms_time *ave_time)
{
    double secs1, secs2, ave_secs;
    julian_date jd_1, jd_2, ave_jd;

    date_ymd2jd(date1, &jd_1); // Julian date contains year and day number within that year
    date_ymd2jd(date2, &jd_2);

    secs1 = date2sec(&jd_1, time1); // Seconds from midnight, Jan 1, 1900 to julian date plus seconds into that day
    secs2 = date2sec(&jd_2, time2);
    ave_secs = (secs1 + secs2) / 2.0;

    sec2date(ave_secs, &ave_jd, ave_time);
    date_jd2ymd(&ave_jd, ave_date);
}
예제 #4
0
// input is string in the format "DD-MMM-YYYY, hh:mm:ss" (as in parse_date())
// output is seconds since midnight, Jan 1, 1900 (as from date2sec())
double seconds_from_str(const char *date_str)
{
  ymd_date d;
  hms_time t;
  parse_date(date_str, &d, &t);
  t.sec = 0;

  julian_date jd;
  date_ymd2jd(&d, &jd);

  return date2sec(&jd, &t);
}
예제 #5
0
main()
{
 long sec;
 date d;

 puts("请输入日期(格式为2008-08-08 08:08:08):");
 scanf("%d-%d-%d %d:%d:%d",&d.year,&d.month,&d.day,&d.hour,&d.min,&d.sec);
 sec=date2sec(d);
 printf("到格林时间%d秒!\n",sec);
 puts("请到格林时间的秒数:");
 scanf("%d",&sec);
 d=sec2date(sec);
 printf("日期为:%d-%d-%d %d:%d:%d\n",d.year,d.month,d.day,d.hour,d.min,d.sec);
}
예제 #6
0
파일: apoint.c 프로젝트: dunecn/calcurse
/* Updates the Appointment panel */
void
apoint_update_panel (int which_pan)
{
  int title_xpos;
  int bordr = 1;
  int title_lines = 3;
  int app_width = win[APP].w - bordr;
  int app_length = win[APP].h - bordr - title_lines;
  long date;
  struct date slctd_date;

  /* variable inits */
  slctd_date = *calendar_get_slctd_day ();
  title_xpos = win[APP].w - (strlen (_(monthnames[slctd_date.mm - 1])) + 16);
  if (slctd_date.dd < 10)
    title_xpos++;
  date = date2sec (slctd_date, 0, 0);
  day_write_pad (date, app_width, app_length, hilt);

  /* Print current date in the top right window corner. */
  erase_window_part (win[APP].p, 1, title_lines, win[APP].w - 2,
                     win[APP].h - 2);
  custom_apply_attr (win[APP].p, ATTR_HIGHEST);
  mvwprintw (win[APP].p, title_lines, title_xpos, "%s  %s %d, %d",
             calendar_get_pom (date), _(monthnames[slctd_date.mm - 1]),
             slctd_date.dd, slctd_date.yyyy);
  custom_remove_attr (win[APP].p, ATTR_HIGHEST);

  /* Draw the scrollbar if necessary. */
  if ((apad.length >= app_length) || (apad.first_onscreen > 0))
    {
      float ratio = ((float) app_length) / ((float) apad.length);
      int sbar_length = (int) (ratio * app_length);
      int highend = (int) (ratio * apad.first_onscreen);
      unsigned hilt_bar = (which_pan == APP) ? 1 : 0;
      int sbar_top = highend + title_lines + 1;

      if ((sbar_top + sbar_length) > win[APP].h - 1)
        sbar_length = win[APP].h - 1 - sbar_top;
      draw_scrollbar (win[APP].p, sbar_top, win[APP].w - 2, sbar_length,
                      title_lines + 1, win[APP].h - 1, hilt_bar);
    }

  wnoutrefresh (win[APP].p);
  pnoutrefresh (apad.ptrwin, apad.first_onscreen, 0,
                win[APP].y + title_lines + 1, win[APP].x + bordr,
                win[APP].y + win[APP].h - 2 * bordr,
                win[APP].x + win[APP].w - 3 * bordr);
}
예제 #7
0
/*******************************************************
 * meta_get_dop:
 * Converts a line, sample pair to the doppler value at
 * that location. Returns Hz. Only works for SR & GR. */
double meta_get_dop(meta_parameters *meta,double yLine, double xSample)
{
  assert (meta->sar); // && (meta->sar->image_type == 'S'
         //   || meta->sar->image_type == 'G'));

  yLine += meta->general->start_line;
  xSample += meta->general->start_sample;
  
  if (meta->doppler && meta->doppler->tsx) {
    int ii;
    julian_date imgStartDate, imgDopplerDate;
    hms_time imgStartTime, imgDopplerTime;
    double time, refTime, *coeff;
    imgStartDate.year = meta->state_vectors->year;
    imgStartDate.jd = meta->state_vectors->julDay;
    date_sec2hms(meta->state_vectors->second, &imgStartTime);
    imgDopplerDate.year = meta->doppler->tsx->year;
    imgDopplerDate.jd = meta->doppler->tsx->julDay;
    date_sec2hms(meta->doppler->tsx->second, &imgDopplerTime);
    double imgAzimuthTime = date2sec(&imgStartDate, &imgStartTime) +
      yLine * meta->sar->range_time_per_pixel;
    double dopAzimuthStart = date2sec(&imgDopplerDate, &imgDopplerTime);
    for (ii=0; ii<meta->doppler->tsx->doppler_count; ii++) {
      time = dopAzimuthStart + meta->doppler->tsx->dop[ii].time;
      if (time > imgAzimuthTime)
	break;
    }
    int max = ii;
    int min = ii - 1;
    double dopAzimuthMin = dopAzimuthStart + meta->doppler->tsx->dop[min].time;
    double dopRangeTimeMin = meta->doppler->tsx->dop[min].first_range_time + 
      xSample * meta->sar->azimuth_time_per_pixel;
    refTime = meta->doppler->tsx->dop[min].reference_time;
    coeff = (double *) MALLOC(sizeof(double)*
			      meta->doppler->tsx->dop[min].poly_degree);
    double dopplerMin = 0.0;
    for (ii=0; ii<=meta->doppler->tsx->dop[min].poly_degree; ii++) {
      coeff[ii] = meta->doppler->tsx->dop[min].coefficient[ii];
      dopplerMin += coeff[ii] * pow(dopRangeTimeMin - refTime, ii);
    }
    FREE(coeff);
    double dopAzimuthMax = dopAzimuthStart + meta->doppler->tsx->dop[max].time;
    refTime = meta->doppler->tsx->dop[min].reference_time;
    coeff = (double *) MALLOC(sizeof(double)*
			      meta->doppler->tsx->dop[max].poly_degree);
    double dopplerMax = 0.0;
    for (ii=0; ii<=meta->doppler->tsx->dop[max].poly_degree; ii++) {
      coeff[ii] = meta->doppler->tsx->dop[max].coefficient[ii];
      dopplerMax += coeff[ii] * pow(dopRangeTimeMin - refTime, ii);
    }
    FREE(coeff);
    return dopplerMin + (dopplerMax - dopplerMin) / 
      (dopAzimuthMax - dopAzimuthMin) * (imgAzimuthTime - dopAzimuthMin);
  }
  else if (meta->doppler && meta->doppler->r2) {
    int ii;
    double doppler = 0.0;
    radarsat2_doppler_params *r2 = meta->doppler->r2;
    double slant_time = 
      r2->time_first_sample + xSample * meta->sar->range_time_per_pixel;
    for (ii=0; ii<r2->doppler_count; ++ii)
      doppler += 
	r2->centroid[ii] * pow((slant_time - r2->ref_time_centroid), ii);

    return doppler;
  }
  else
    return meta->sar->range_doppler_coefficients[0]+
      meta->sar->range_doppler_coefficients[1]*xSample+
      meta->sar->range_doppler_coefficients[2]*xSample*xSample+
      meta->sar->azimuth_doppler_coefficients[1]*yLine+
      meta->sar->azimuth_doppler_coefficients[2]*yLine*yLine;
}
예제 #8
0
main(int argc, char **argv) {

  signal(SIGINT,ctrl_c);

  double positions[3], J[3], max_err, std_err;
  int i, j, jj;

  double depth   = 2.;
  double I       = 65.6;
  double D       = -12.27;
  double Az      = 90.;
  int n_channels = 2;
  double zmin    = 100;
  double zmax    = 100;
  int background = 1;
  double dm      = 1.e-3;
  int is_shift   = 0;
  double mag_ampl = 0.;
  int is_induced = 0;
  int is_fixed_z = 0;
  int max_samples = 10000;
  int n_samples   = 0;
  int n1, n2;
  int skip_tsynt = 0;

  double ** X, ** Y, ** Z, ** Alt, ** T, **Tsynt, *dTime;

  double rms_fit, max_fit, synt_max,  synt_min;
  int      max_iterations    = 2000;
  char  inv_message[1024];

	int dnls_size =  sizeof(DNLS1_STORAGE);
	int col_size   = sizeof(CMagDataCollection);

	check_size();
	check_size2();

  n1 = n2 = -1;

   X = Y = Z = Alt = T = Tsynt = NULL;
   dTime = NULL;

  if(argc == 1) {
    fprintf(stderr,"\nUsage: %s -I val -D val -Ch val -Bg val -Z val -dm val < input > output\n",argv[0]);
    fprintf(stderr,"-I    number  -  Inclination, degrees\n");
    fprintf(stderr,"-D    number  -  Declination, degrees\n");
    fprintf(stderr,"-Ch   number  - number of channels [2] \n");
    fprintf(stderr,"-Z    number  - initial depth below sea bottom, m [2 m]\n");
    fprintf(stderr,"-Bg   number  - background order (0, 1 or 2) [1]\n");
    fprintf(stderr,"-Zfix         - all data has fixed Z\n");
    fprintf(stderr,"-dm   number  - smooth depth order [1.e-3]\n");
    fprintf(stderr,"-S          - shift all profiles except first\n");
    fprintf(stderr,"-Az   number  - Local X axis azimuth [90]\n");
    fprintf(stderr,"-MaxSamples number  - Samples to reserve for the data[10000]\n");
    fprintf(stderr,"-Ind        - Induced only\n");
    fprintf(stderr,"-N1 number  - window start\n");
	fprintf(stderr,"-N2 number  - window end\n");
    fprintf(stderr,"-SkipTsynt  - work on file with X Y Z, ALT, T Tsynt\n"); 
    exit(0);
  }


  for(i=1; i<argc; i++) {
	  if(argv[i][0]=='-') {
		  if(strcmp(argv[i],"-I")==0) {
			  I = atof(argv[i+1]); i++; continue;
		  }
		  if(strcmp(argv[i],"-D")==0) {
			  D = atof(argv[i+1]); i++;  continue;
		  }
		  if(strcmp(argv[i],"-Ch")==0) {
			  n_channels = atol(argv[i+1]); i++; continue;
		  }
		  if(strcmp(argv[i],"-Z")==0) {
			  depth = atof(argv[i+1]); i++; continue;
		  }
		  if(strcmp(argv[i],"-Bg")==0) {
			  background = atoi(argv[i+1]); i++; continue;
		  }
		  if(strcmp(argv[i],"-dm")==0) {
			  dm = atof(argv[i+1]); i++; continue;
		  }
		  if(strcmp(argv[i],"-S")==0) {
			  is_shift = 1; continue;
		  }
		  if(strcmp(argv[i],"-Zfix")==0) {
			  is_fixed_z = 1; continue;
		  }
		  if(strcmp(argv[i],"-Az")==0) {
			  Az = atof(argv[i+1]); i++; continue;
		  }
		  if(strcmp(argv[i],"-MaxSamples")==0) {
			  max_samples = atoi(argv[i+1]); i++; continue;
		  }
		  if(strcmp(argv[i],"-N1")==0) {
			  n1 = atoi(argv[i+1])-1; i++; continue;
		  }
		  if(strcmp(argv[i],"-N2")==0) {
			  n2 = atoi(argv[i+1])-1; i++; continue;
		  }
		  if(strcmp(argv[i],"-Ind")==0) {
			  is_induced = 1; continue;
		  }
		  if(strcmp(argv[i],"-SkipTsynt")==0) {
			skip_tsynt = 1; continue;	  
		 } 
      }
  }

	// allocate memory

  X     = new double *[n_channels];
  Y     = new double *[n_channels];
  Z     = new double *[n_channels];
  T     = new double *[n_channels];
  Tsynt = new double *[n_channels];
  Alt   = new double *[n_channels];
  dTime = new double[max_samples];

  if(!X || !Y || !Z || !T || !Tsynt || !Alt) {
	  fprintf(stderr,"Cannot allocate memory for pointers. Stop\n");
	  exit(0);
  }

  for(i=0; i<n_channels; i++) {
	  X[i]       = new double[max_samples];
	  Y[i]       = new double[max_samples];
	  Z[i]       = new double[max_samples];
	  T[i]       = new double[max_samples];
	  Tsynt[i]   = new double[max_samples];
	  Alt[i]     = new double[max_samples];

	  if(!X[i] || !Y[i] || !Z[i] || !T[i]  || !Tsynt[i] || !Alt[i]) {
		  fprintf(stderr,"Cannot allocate memory for pointers. Stop\n");
		  exit(0);
	  }
  }


  // FILE * dat = fopen("field.dat", "rt");
  //#define stdin dat

  // read the data
  char buffer[1024], date_txt[20], time_txt[20], name[20];
  const char *IFS = " \t\n";

  int z_first = 1;
  double z_const;
  int is_z_const=1;

  j=0;

  while(!feof(stdin)) {
      if(!fgets(buffer, 1024, stdin)) break;

      char * p  = strtok (buffer, IFS);
      if(!p) continue;

	  if(buffer[0] == '#' || !isdigit(buffer[0])) continue;


      for(int i=0; i<n_channels; i++) {
          X[i][j]   =  atof(p); p = strtok(NULL, IFS);
          Y[i][j]   =  atof(p); p = strtok(NULL, IFS);
          Z[i][j]   =  atof(p); p = strtok(NULL, IFS);
          Alt[i][j] =  atof(p); p = strtok(NULL, IFS);
          T[i][j]   =  atof(p); p = strtok(NULL, IFS);

		  if(skip_tsynt) p = strtok(NULL, IFS); 

		  if(z_first) {
			  z_const = Z[i][j];
			  z_first = 0;
		  }
		  else {
			  if(z_const!=Z[i][j]) is_z_const = 0;
		  }

      }

      double dtime = 0.;
      strcpy(name,p);     p = strtok(NULL, IFS);
      if(p) {
            strcpy(date_txt,p); p = strtok(NULL, IFS);
            strcpy(time_txt,p);
            dTime[j] = date2sec(date_txt, time_txt, 1);
      }

      j++;
	  if(j>=max_samples) break;
   }

	//fclose(dat);

	n_samples = j;
	if(n1<0) n1 = 0;
	if(n2<0) n2 = n_samples-1;

	// invesion

	std::vector<double **> vX;
    std::vector<double **> vY;
	std::vector<double **> vZ;
	std::vector<double **> vA;
	std::vector<double **> vT;
	std::vector<double **> vTsynt;
	std::vector<double *> vTime;
	std::vector<int> vCh;
	std::vector<int> vN;
	std::vector<int> vN1;
	std::vector<int> vN2;

    std::vector<double> vX0;
    std::vector<double> vY0;
    std::vector<double> vZ0;
    std::vector<double> vJ;

	vX.push_back(X);
	vY.push_back(Y);
	vZ.push_back(Z);
	vT.push_back(T);
	vTsynt.push_back(Tsynt);
	vTime.push_back(dTime);

	vA.push_back(Alt);
	vCh.push_back(n_channels);
	vN.push_back(n_samples);
	vN1.push_back(n1);
	vN2.push_back(n2);

	vX0.push_back(NO_DATA);
	vY0.push_back(NO_DATA);
	vZ0.push_back(depth);
	vJ.push_back(NO_DATA);

	CMagCollection ObjectCollection;

	int ret = ArrayInversion<double>(ObjectCollection, vX, vY, vZ, vA, vT, vTsynt, vTime,
						  		     vCh, vN, vN1, vN2, vX0, vY0, vZ0, vJ,
							         &rms_fit, &max_fit, &synt_max, &synt_min,
									 I,D,Az, 0,
							         max_iterations,
							         progress_func,
							         inv_message);



	fprintf(stderr,"RMS fit %lf Max fit %lf\n", rms_fit, max_fit);
	fprintf(stderr,"Synt. max %lf Synt min %lf\n", synt_max, synt_min);

	fprintf(stderr,"X=%lf +/- %lf\n", vX0[0], vX0[1]);
	fprintf(stderr,"Y=%lf +/- %lf\n", vY0[0], vY0[1]);
	fprintf(stderr,"Z=%lf +/- %lf\n", vZ0[0], vZ0[1]);

	fprintf(stderr,"Jx=%lf +/- %lf\n", vJ[0], vJ[3]);
	fprintf(stderr,"Jy=%lf +/- %lf\n", vJ[1], vJ[4]);
	fprintf(stderr,"Jz=%lf +/- %lf\n", vJ[2], vJ[5]);



  // free memory

	 for(i=0; i<n_channels; i++) {
		 delete [] X[i];     X[i]   = NULL;
		 delete [] Y[i];     Y[i]   = NULL;
		 delete [] Z[i];     Z[i]   = NULL;
		 delete [] T[i];     T[i]   = NULL;
		 delete [] Alt[i];   Alt[i] = NULL;
		 delete [] Tsynt[i]; Tsynt[i] = NULL;
	 }

	 delete [] X;
	 delete [] Y;
	 delete [] Z;
	 delete [] T;
	 delete [] Tsynt;
	 delete [] Alt;
	 delete [] dTime;


}
예제 #9
0
int main(int argc, char **argv)
{
  FILE *fpIn, *fpOut, *fpInList, *fpOutList, *fpXml;
  meta_parameters *meta;
  extern int currArg; /* from cla.h in asf.h... initialized to 1 */
  logflag = 0;
  
  // Parse command line args
  while (currArg < (argc-2)) {
    char *key=argv[currArg++];
    if (strmatch(key,"-log")) {
      sprintf(logFile, "%s", argv[currArg]);
      logflag = 1;
    }
    else {
      printf("\n   ***Invalid option:  %s\n\n",
	     argv[currArg-1]);
      usage(argv[0]);
    }
  }
  if ((argc-currArg) < 2) {
    printf("Insufficient arguments.\n");
    usage(argv[0]);
  }
  
  asfSplashScreen(argc, argv);
  
  char *listInFile = (char *) MALLOC(sizeof(char)*(strlen(argv[1])+1));
  strcpy(listInFile, argv[1]);
  char *outFile = (char *) MALLOC(sizeof(char)*(strlen(argv[2])+1));
  strcpy(outFile, argv[2]);
  
  // Setup file names
  char outDirName[512], outFileName[512];
  split_dir_and_file(outFile, outDirName, outFileName);
  char *tmpDir = (char *) MALLOC(sizeof(char)*512);
  sprintf(tmpDir, "%smeasures-", outDirName);
  char *tsdir = time_stamp_dir();
  strcat(tmpDir, tsdir);
  FREE(tsdir);
  create_clean_dir(tmpDir);
  char *isoStr = iso_date();

  // Read header information
  char inFile[512], imgFile[768], metaFile[768];
  char listOutFile[768], citation[50], start[30], end[30], first[30];
  char header[120], baseName[512], dirName[512], ext[5];
  float x_pix, y_pix, x_map_ll, y_map_ll, x_map_ur, y_map_ur, inc, cat;
  double lat, lon, height, x, y, z;
  int ii, kk, nFiles=0, num = 1, sample_count, line_count;
  image_data_type_t image_data_type;
  sprintf(listOutFile, "%s%crgps.xml", tmpDir, DIR_SEPARATOR);

  // Preparing map projection information
  project_parameters_t pps;
  projection_type_t proj_type;
  datum_type_t datum;
  spheroid_type_t spheroid;
  read_proj_file("polar_stereographic_north_ssmi.proj", 
     &pps, &proj_type, &datum, &spheroid);
  pps.ps.false_easting = 0.0;
  pps.ps.false_northing = 0.0;
  meta_projection *proj = meta_projection_init();
  proj->type = proj_type;
  proj->datum = HUGHES_DATUM;
  proj->spheroid = HUGHES_SPHEROID;
  proj->param = pps;
  strcpy(proj->units, "meters");
  proj->hem = 'N';
  spheroid_axes_lengths(spheroid, &proj->re_major, &proj->re_minor);
  FREE(proj);

  // Set up supplemental file names: water mask, lat/lon, x/y grids
  char maskFile[768], latFile[768], lonFile[768], xFile[768], yFile[768]; 
  sprintf(maskFile, "%s%cwater_mask.img", tmpDir, DIR_SEPARATOR);
  sprintf(latFile, "%s%clatitude.img", tmpDir, DIR_SEPARATOR);
  sprintf(lonFile, "%s%clongitude.img", tmpDir, DIR_SEPARATOR);
  sprintf(xFile, "%s%cxgrid.img", tmpDir, DIR_SEPARATOR);
  sprintf(yFile, "%s%cygrid.img", tmpDir, DIR_SEPARATOR);

  // Generating output XML file
  fpInList = FOPEN(listInFile, "r");
  fpOutList = FOPEN(listOutFile, "w");
  fprintf(fpOutList, "<netcdf>\n");
  fprintf(fpOutList, "  <data>\n");
  fprintf(fpOutList, "    <latitude>%s</latitude>\n", latFile);
  fprintf(fpOutList, "    <longitude>%s</longitude>\n", lonFile);
  fprintf(fpOutList, "    <xgrid>%s</xgrid>\n", xFile);
  fprintf(fpOutList, "    <ygrid>%s</ygrid>\n", yFile);
  fprintf(fpOutList, "    <mask>%s</mask>\n", maskFile);
  
  julian_date jdStart, jdEnd, jdRef;
  hms_time hms;
  hms.hour = 0;
  hms.min = 0;
  hms.sec = 0.0;

  asfPrintStatus("Working through the file list:\n");
  int myrFlag=FALSE, divFlag=FALSE, vrtFlag=FALSE, shrFlag=FALSE;
  int firstYear, firstDay, startYear, startDay, endYear, endDay;
  double westBoundLon, eastBoundLon, northBoundLat, southBoundLat;
  double minLat=90.0, maxLat=-90.0, minLon=180.0, maxLon=-180.0;

  while (fgets(inFile, 512, fpInList)) {

    chomp(inFile);
    char inDirName[512], inFileName[512];
    split_dir_and_file(inFile, inDirName, inFileName);

    // Preparing map projection information
    project_parameters_t pps;
    projection_type_t proj_type;
    datum_type_t datum;
    spheroid_type_t spheroid;
    read_proj_file("polar_stereographic_north_ssmi.proj", 
       &pps, &proj_type, &datum, &spheroid);
    pps.ps.false_easting = 0.0;
    pps.ps.false_northing = 0.0;
    meta_projection *proj = meta_projection_init();
    proj->type = proj_type;
    proj->datum = HUGHES_DATUM;
    proj->spheroid = HUGHES_SPHEROID;
    proj->param = pps;
    strcpy(proj->units, "meters");
    proj->hem = 'N';
    spheroid_axes_lengths(spheroid, &proj->re_major, &proj->re_minor);

    // Sort out dates
    startYear = subInt(inFileName, 0, 4);
    startDay = subInt(inFileName, 4, 3);
    endYear = subInt(inFileName, 8, 4);
    endDay = subInt(inFileName, 12, 3);
    if (nFiles == 0) {
      firstYear = startYear;
      firstDay = startDay;
    }
    sprintf(citation, "%d%03d to %d%03d", startYear, startDay, endYear, endDay);
    rgps2iso_date(startYear, (double) startDay, start);
    rgps2iso_date(endYear, (double) endDay, end);
    rgps2iso_date(firstYear, (double) firstDay, first);
    
    // Read header information
    FILE *fpIn = FOPEN(inFile, "r");
    fgets(header, 100, fpIn);
    sscanf(header, "%f %f %f %f %f %f", &x_pix, &y_pix, &x_map_ll, &y_map_ll, 
      &x_map_ur, &y_map_ur);
    fgets(header, 100, fpIn);
    int params = sscanf(header, "%f %f %d %d", 
      &inc, &cat, &sample_count, &line_count);
    if (params == 3) {
      sscanf(header, "%f %d %d", &cat, &sample_count, &line_count);
      inc = 0;
    }
    else if (params == 2) {
      sscanf(header, "%d %d", &sample_count, &line_count);
      inc = 0;
      cat = 1;
    }
    num = (int) cat;
    if (num > 1)
      asfPrintError("Multiband imagery (%s) not supported for netCDF "
        "generation!\n", inFile);

    /*  
    printf("x_pix: %f, y_pix: %f\n", x_pix, y_pix);
    printf("x_map_ll: %f, y_map_ll: %f\n", x_map_ll, y_map_ll);
    printf("x_map_ur: %f, y_map_ur: %f\n", x_map_ur, y_map_ur);
    printf("sample_count: %d, line_count: %d\n\n", sample_count, line_count);
    */
      
    // Check extension
    split_base_and_ext(inFileName, 1, '.', baseName, ext);
    asfPrintStatus("Processing %s ...\n", inFileName);
    sprintf(imgFile, "%s%c%s_%s.img", tmpDir, DIR_SEPARATOR, baseName, &ext[1]);
    sprintf(metaFile, "%s%c%s_%s.meta", tmpDir, DIR_SEPARATOR, baseName, 
      &ext[1]);
    
    jdRef.year = firstYear;
    jdRef.jd = 1;
    jdStart.year = startYear;
    jdStart.jd = startDay;
    jdEnd.year = endYear;
    jdEnd.jd = endDay;
    double startSec = date2sec(&jdStart, &hms) - date2sec(&jdRef, &hms);
    double endSec = date2sec(&jdEnd, &hms) - date2sec(&jdRef, &hms);
    if (strcmp_case(ext, ".MYR") == 0) {
      fprintf(fpOutList, "    <multiyear_ice_fraction start=\"%.0f\" end=\"%.0f"
        "\">%s</multiyear_ice_fraction>\n", startSec, endSec, imgFile);
      image_data_type = MULTIYEAR_ICE_FRACTION;
      myrFlag = TRUE;
    }
    else if (strcmp_case(ext, ".DIV") == 0) {
      fprintf(fpOutList, "    <divergence start=\"%.0f\" end=\"%.0f\">%s"
        "</divergence>\n", startSec, endSec, imgFile);
      image_data_type = DIVERGENCE;
      divFlag = TRUE;
    }
    else if (strcmp_case(ext, ".VRT") == 0) {
      fprintf(fpOutList, "    <vorticity start=\"%.0f\" end=\"%.0f\">%s"
        "</vorticity>\n", startSec, endSec, imgFile);
      image_data_type = VORTICITY;
      vrtFlag = TRUE;
    }
    else if (strcmp_case(ext, ".SHR") == 0) {
      fprintf(fpOutList, "    <shear start=\"%.0f\" end=\"%.0f\">%s</shear>", 
        startSec, endSec, imgFile);
      image_data_type = SHEAR;
      shrFlag = TRUE;
    }

    // Generate basic metadata
    meta = raw_init();
    meta->general->line_count = line_count;
    meta->general->sample_count = sample_count;
    meta->general->band_count = 1;
    meta->general->data_type = REAL32;
    meta->general->image_data_type = image_data_type;
    strcpy(meta->general->basename, inFile);
    meta->general->x_pixel_size = x_pix*1000.0;
    meta->general->y_pixel_size = y_pix*1000.0;
    meta->general->start_line = 0;
    meta->general->start_sample = 0;
    meta->general->no_data = MAGIC_UNSET_DOUBLE;
    strcpy(meta->general->sensor, "RGPS MEaSUREs");
    char *tmp = image_data_type2str(meta->general->image_data_type);
    sprintf(meta->general->bands, "%s", lc(tmp));
    FREE(tmp);
    sprintf(meta->general->acquisition_date, "%s", baseName);
    
    // Sort out map projection
    proj->startX = x_map_ll*1000.0;
    proj->startY = y_map_ur*1000.0;
    proj->perX = x_pix*1000.0;
    proj->perY = -y_pix*1000.0;
    meta->projection = proj;
    meta_write(meta, metaFile);
    strcpy(meta->general->bands, "water mask");
    sprintf(metaFile, "%s%cwater_mask.meta", tmpDir, DIR_SEPARATOR);
    meta_write(meta, metaFile);  
    sprintf(metaFile, "%s%c%s_%s.meta", tmpDir, DIR_SEPARATOR, baseName, 
      &ext[1]);
    
    float *floatBuf = (float *) MALLOC(sizeof(float)*sample_count);

    // Write gridded data to ASF internal format
    fpOut = FOPEN(imgFile, "wb");
    for (ii=0; ii<line_count; ii++) {
      for (kk=0; kk<sample_count; kk++) {
	      ASF_FREAD(&floatBuf[kk], sizeof(float), 1, fpIn);
	      ieee_big32(floatBuf[kk]);
        if (floatBuf[kk] > 10000000000.0 || 
          FLOAT_EQUIVALENT(floatBuf[kk], 10000000000.0))
          floatBuf[kk] = MAGIC_UNSET_DOUBLE;
      }
      put_float_line(fpOut, meta, line_count-ii-1, floatBuf);
    }
    FCLOSE(fpOut);
    FREE(floatBuf);
    
    double lat1, lon1, lat2, lon2, lat3, lon3, lat4, lon4;
    proj_to_latlon(proj, x_map_ll*1000.0, y_map_ll*1000.0, 0.0, 
      &lat1, &lon1, &height);
    proj_to_latlon(proj, x_map_ll*1000.0, y_map_ur*1000.0, 0.0, 
      &lat2, &lon2, &height);
    proj_to_latlon(proj, x_map_ur*1000.0, y_map_ur*1000.0, 0.0, 
      &lat3, &lon3, &height);
    proj_to_latlon(proj, x_map_ur*1000.0, y_map_ll*1000.0, 0.0, 
      &lat4, &lon4, &height);
    westBoundLon = minValue(lon1*R2D, lon2*R2D, lon3*R2D, lon4*R2D);
    eastBoundLon = maxValue(lon1*R2D, lon2*R2D, lon3*R2D, lon4*R2D);
    northBoundLat = maxValue(lat1*R2D, lat2*R2D, lat3*R2D, lat4*R2D);
    southBoundLat = minValue(lat1*R2D, lat2*R2D, lat3*R2D, lat4*R2D);
    if (westBoundLon < minLon)
      minLon = westBoundLon;
    if (eastBoundLon > maxLon)
      maxLon = eastBoundLon;
    if (southBoundLat < minLat)
      minLat = southBoundLat;
    if (northBoundLat > maxLat)
      maxLat = northBoundLat;

    meta_free(meta);
    nFiles++;
  }
  FCLOSE(fpInList);
  
  fprintf(fpOutList, "  </data>\n");
  fprintf(fpOutList, "  <metadata>\n");
  fprintf(fpOutList, "    <time>\n");
  fprintf(fpOutList, "      <axis type=\"string\" definition=\"name of axis\">T"
    "</axis>\n");
  fprintf(fpOutList, "      <long_name type=\"string\" definition=\"long "
    "descriptive name\">serial date</long_name>\n");
  fprintf(fpOutList, "      <references type=\"string\" definition=\"reference "
    "of the value\">start time of 3-day average</references>\n");
  fprintf(fpOutList, "      <standard_name type=\"string\" definition=\"name "
    "used to identify the physical quantity\">time</standard_name>\n");
  fprintf(fpOutList, "      <units type=\"string\" definition=\"unit of "
    "dimensional quantity\">seconds since %d-01-01T00:00:00Z</units>\n",
    firstYear);
  fprintf(fpOutList, "      <bounds type=\"string\" definition=\"variable "
    "containing data range\">time_bounds</bounds>\n");
  fprintf(fpOutList, "      <FillValue type=\"double\" definition=\"default "
    "value\">0</FillValue>\n");
  fprintf(fpOutList, "    </time>\n");
  fprintf(fpOutList, "    <time_bounds>\n");
  fprintf(fpOutList, "      <long_name type=\"string\" definition=\"long "
    "descriptive name\">serial date</long_name>\n");
  fprintf(fpOutList, "      <references type=\"string\" definition=\"reference "
    "of the value\">start and end time of 3-day average</references>\n");
  fprintf(fpOutList, "      <standard_name type=\"string\" definition=\"name "
    "used to identify the physical quantity\">time</standard_name>\n");
  fprintf(fpOutList, "      <units type=\"string\" definition=\"unit of "
    "dimensional quantity\">seconds since %d-01-01T00:00:00Z</units>\n",
    firstYear);
  fprintf(fpOutList, "      <FillValue type=\"double\" definition=\"default "
    "value\">0</FillValue>\n");
  fprintf(fpOutList, "    </time_bounds>\n");
  fprintf(fpOutList, "    <latitude>\n");
  fprintf(fpOutList, "      <long_name type=\"string\" definition=\"long "
    "descriptive name\">latitude</long_name>\n");
  fprintf(fpOutList, "      <standard_name type=\"string\" definition=\"name "
    "used to identify the physical quantity\">latitude</standard_name>\n");
  fprintf(fpOutList, "      <units type=\"string\" definition=\"unit of "
    "dimensional quantity\">degrees_north</units>\n");
  fprintf(fpOutList, "      <FillValue type=\"float\" definition=\"default "
    "value\">-999</FillValue>\n");
  fprintf(fpOutList, "      <valid_min type=\"float\" definition=\"minimum "
    "valid value\">-90.0</valid_min>\n");
  fprintf(fpOutList, "      <valid_max type=\"float\" definition=\"minimum "
    "valid value\">90.0</valid_max>\n");
  fprintf(fpOutList, "    </latitude>\n");
  fprintf(fpOutList, "    <longitude>\n");
  fprintf(fpOutList, "      <long_name type=\"string\" definition=\"long "
    "descriptive name\">longitude</long_name>\n");
  fprintf(fpOutList, "      <standard_name type=\"string\" definition=\"name "
    "used to identify the physical quantity\">longitude</standard_name>\n");
  fprintf(fpOutList, "      <units type=\"string\" definition=\"unit of "
    "dimensional quantity\">degrees_east</units>\n");
  fprintf(fpOutList, "      <FillValue type=\"float\" definition=\"default "
    "value\">-999</FillValue>\n");
  fprintf(fpOutList, "      <valid_min type=\"float\" definition=\"minimum "
    "valid value\">-180.0</valid_min>\n");
  fprintf(fpOutList, "      <valid_max type=\"float\" definition=\"minimum "
    "valid value\">180.0</valid_max>\n");
  fprintf(fpOutList, "    </longitude>\n");
  fprintf(fpOutList, "    <xgrid>\n");
  fprintf(fpOutList, "      <axis type=\"string\" definition=\"name of axis\">X"
    "</axis>\n");
  fprintf(fpOutList, "      <long_name type=\"string\" definition=\"long "
    "descriptive name\">projection_grid_x_center</long_name>\n");
  fprintf(fpOutList, "      <standard_name type=\"string\" definition=\"name "
    "used to identify the physical quantity\">projection_x_coordinate"
    "</standard_name>\n");
  fprintf(fpOutList, "      <units type=\"string\" definition=\"unit of "
    "dimensional quantity\">meters</units>\n");
  fprintf(fpOutList, "      <FillValue type=\"float\" definition=\"default "
    "value\">NaN</FillValue>\n");
  fprintf(fpOutList, "    </xgrid>\n");
  fprintf(fpOutList, "    <ygrid>\n");
  fprintf(fpOutList, "      <axis type=\"string\" definition=\"name of axis\">Y"
    "</axis>\n");
  fprintf(fpOutList, "      <long_name type=\"string\" definition=\"long "
    "descriptive name\">projection_grid_y_center</long_name>\n");
  fprintf(fpOutList, "      <standard_name type=\"string\" definition=\"name "
    "used to identify the physical quantity\">projection_y_coordinate"
    "</standard_name>\n");
  fprintf(fpOutList, "      <units type=\"string\" definition=\"unit of "
    "dimensional quantity\">meters</units>\n");
  fprintf(fpOutList, "      <FillValue type=\"float\" definition=\"default "
    "value\">NaN</FillValue>\n");
  fprintf(fpOutList, "    </ygrid>\n");
  fprintf(fpOutList, "    <Polar_Stereographic>\n");
  fprintf(fpOutList, "      <grid_mapping_name>polar_stereographic"
    "</grid_mapping_name>\n");
  fprintf(fpOutList, "      <straight_vertical_longitude_from_pole>%.1f"
    "</straight_vertical_longitude_from_pole>\n", pps.ps.slon);
  fprintf(fpOutList, "      <longitude_of_central_meridian>90.0"
    "</longitude_of_central_meridian>\n");
  fprintf(fpOutList, "      <standard_parallel>%.1f</standard_parallel>\n", 
    pps.ps.slat);
  fprintf(fpOutList, "      <false_easting>%.1f</false_easting>\n", 
    pps.ps.false_easting);
  fprintf(fpOutList, "      <false_northing>%.1f</false_northing>\n",
    pps.ps.false_northing);
  fprintf(fpOutList, "      <projection_x_coordinate>xgrid"
    "</projection_x_coordinate>\n");
  fprintf(fpOutList, "      <projection_y_coordinate>ygrid"
    "</projection_y_coordinate>\n");
  fprintf(fpOutList, "      <units>meters</units>\n");
  fprintf(fpOutList, "    </Polar_Stereographic>\n");
  fprintf(fpOutList, "    <mask>\n");
  fprintf(fpOutList, "      <coordinates type=\"string\" definition=\""
    "coordinate reference\">ygrid xgrid</coordinates>\n");
  fprintf(fpOutList, "      <grid_mapping type=\"string\" definition=\"\">"
    "Polar_Stereographic</grid_mapping>\n");
  fprintf(fpOutList, "      <long_name type=\"string\" definition=\"long "
    "descriptive name\">projection_grid_y_center</long_name>\n");
  fprintf(fpOutList, "      <units type=\"string\" definition=\"unit of "
    "dimensional quantity\">1</units>\n");
  fprintf(fpOutList, "      <units_description type=\"string\" definition=\""
    "descriptive information about dimensionless quantity\">unitless"
    "</units_description>\n");
  fprintf(fpOutList, "      <FillValue type=\"int\" definition=\"default "
    "value\">0</FillValue>\n");
  fprintf(fpOutList, "    </mask>\n");
  if (myrFlag) {
    fprintf(fpOutList, "    <multiyear_ice_fraction>\n");
    fprintf(fpOutList, "      <cell_methods type=\"string\" definition=\""
      "characteristic of a field that is represented by cell values\">area: "
      "multiyear ice fraction value</cell_methods>\n");
    fprintf(fpOutList, "      <coordinates type=\"string\" definition=\""
      "coordinate reference\">ygrid xgrid</coordinates>\n");
    fprintf(fpOutList, "      <grid_mapping type=\"string\" definition=\"\">"
      "Polar_Stereographic</grid_mapping>\n");
    fprintf(fpOutList, "      <long_name type=\"string\" definition=\"long "
      "descriptive name\">RGPS MEaSUREs multiyear ice fraction</long_name>\n");
    fprintf(fpOutList, "      <units type=\"string\" definition=\"unit of "
      "dimensional quantity\">1</units>\n");
    fprintf(fpOutList, "      <units_description type=\"string\" definition=\""
      "descriptive information about dimensionless quantity\">unitless"
      "</units_description>\n");
    fprintf(fpOutList, "      <FillValue type=\"float\" definition=\"default "
      "value\">NaN</FillValue>\n");
    fprintf(fpOutList, "    </multiyear_ice_fraction>\n");
  }
  if (divFlag) {
    fprintf(fpOutList, "    <divergence>\n");
    fprintf(fpOutList, "      <cell_methods type=\"string\" definition=\""
      "characteristic of a field that is represented by cell values\">area: "
      "divergence value</cell_methods>\n");
    fprintf(fpOutList, "      <coordinates type=\"string\" definition=\""
      "coordinate reference\">ygrid xgrid</coordinates>\n");
    fprintf(fpOutList, "      <grid_mapping type=\"string\" definition=\"\">"
      "Polar_Stereographic</grid_mapping>\n");
    fprintf(fpOutList, "      <long_name type=\"string\" definition=\"long "
      "descriptive name\">RGPS MEaSUREs divergence</long_name>\n");
    fprintf(fpOutList, "      <units type=\"string\" definition=\"unit of "
      "dimensional quantity\">1</units>\n");
    fprintf(fpOutList, "      <units_description type=\"string\" definition=\""
      "descriptive information about dimensionless quantity\">unitless"
      "</units_description>\n");
    fprintf(fpOutList, "      <FillValue type=\"float\" definition=\"default "
      "value\">NaN</FillValue>\n");
    fprintf(fpOutList, "    </divergence>\n");
  }
  if (vrtFlag) {
    fprintf(fpOutList, "    <vorticity>\n");
    fprintf(fpOutList, "      <cell_methods type=\"string\" definition=\""
      "characteristic of a field that is represented by cell values\">area: "
      "vorticity value</cell_methods>\n");
    fprintf(fpOutList, "      <coordinates type=\"string\" definition=\""
      "coordinate reference\">ygrid xgrid</coordinates>\n");
    fprintf(fpOutList, "      <grid_mapping type=\"string\" definition=\"\">"
      "Polar_Stereographic</grid_mapping>\n");
    fprintf(fpOutList, "      <long_name type=\"string\" definition=\"long "
      "descriptive name\">RGPS MEaSUREs vorticity</long_name>\n");
    fprintf(fpOutList, "      <units type=\"string\" definition=\"unit of "
      "dimensional quantity\">1</units>\n");
    fprintf(fpOutList, "      <units_description type=\"string\" definition=\""
      "descriptive information about dimensionless quantity\">unitless"
      "</units_description>\n");
    fprintf(fpOutList, "      <FillValue type=\"float\" definition=\"default "
      "value\">NaN</FillValue>\n");
    fprintf(fpOutList, "    </vorticity>\n");
  }
  if (shrFlag) {
    fprintf(fpOutList, "    <shear>\n");
    fprintf(fpOutList, "      <cell_methods type=\"string\" definition=\""
      "characteristic of a field that is represented by cell values\">area: "
      "shear value</cell_methods>\n");
    fprintf(fpOutList, "      <coordinates type=\"string\" definition=\""
      "coordinate reference\">ygrid xgrid</coordinates>\n");
    fprintf(fpOutList, "      <grid_mapping type=\"string\" definition=\"\">"
      "Polar_Stereographic</grid_mapping>\n");
    fprintf(fpOutList, "      <long_name type=\"string\" definition=\"long "
      "descriptive name\">RGPS MEaSUREs shear</long_name>\n");
    fprintf(fpOutList, "      <units type=\"string\" definition=\"unit of "
      "dimensional quantity\">1</units>\n");
    fprintf(fpOutList, "      <units_description type=\"string\" definition=\""
      "descriptive information about dimensionless quantity\">unitless"
      "</units_description>\n");
    fprintf(fpOutList, "      <FillValue type=\"float\" definition=\"default "
      "value\">NaN</FillValue>\n");
    fprintf(fpOutList, "    </shear>\n");
  }
  fprintf(fpOutList, "  </metadata>\n");
  fprintf(fpOutList, "  <parameter>\n");
  if (myrFlag)
    fprintf(fpOutList, "    <multiyear_ice_fraction type=\"float\"/>\n");
  if (divFlag)
    fprintf(fpOutList, "    <divergence type=\"float\"/>\n");
  if (vrtFlag)
    fprintf(fpOutList, "    <vorticity type=\"float\"/>\n");
  if (shrFlag)
    fprintf(fpOutList, "    <shear type=\"float\"/>\n");
  fprintf(fpOutList, "  </parameter>\n");
  
  char startStr[15], endStr[15];
  jdStart.year = firstYear;
  jdStart.jd = firstDay;
  jdEnd.year = endYear;
  jdEnd.jd = endDay;
  jd2date(&jdStart, startStr);
  jd2date(&jdEnd, endStr);
  if (firstYear != endYear || firstDay != endDay)
    sprintf(citation, "%s to %s", startStr, endStr);
  else
    sprintf(citation, "%s", startStr);
  fprintf(fpOutList, "  <root>\n");
  fprintf(fpOutList, "    <Conventions>CF-1.6</Conventions>\n");
  fprintf(fpOutList, "    <institution>Alaska Satellite Facility</institution>\n");
  fprintf(fpOutList, "    <title>Kwok, Ron. 2008. MEaSUREs Small-Scale Kinematics"
    " of Arctic Ocean Sea Ice, Version 01, %s. Jet Propulsion Laboratory "
    "Pasadena, CA USA and Alaska Satellite Facility Fairbanks, AK USA. "
    "Digital media.</title>\n", citation);
  fprintf(fpOutList, "    <source>Products derived from RADARSAT-1 SWB imagery at "
    "100 m resolution</source>\n");
  fprintf(fpOutList, "    <comment>Imagery the products are derived from: Copyright "
    "Canadian Space Agency (1996 to 2008)</comment>\n");
  fprintf(fpOutList, "    <reference>Documentation available at: www.asf.alaska.edu"
    "</reference>\n");
  fprintf(fpOutList, "    <history>%s: netCDF file created.</history>\n", isoStr);
  fprintf(fpOutList, "  </root>\n");
  fprintf(fpOutList, "</netcdf>\n");
  FCLOSE(fpOutList);

  // Generate supplemental files: water mask, lat/lon, x/y grids
  asfPrintStatus("Generating supplemental files ...\n");
  float *floatBuf = (float *) MALLOC(sizeof(float)*sample_count);
  float *maskBuf = (float *) MALLOC(sizeof(float)*sample_count);
  float *latBuf = (float *) MALLOC(sizeof(float)*sample_count);
  float *lonBuf = (float *) MALLOC(sizeof(float)*sample_count);
  float *xBuf = (float *) MALLOC(sizeof(float)*sample_count);
  float *yBuf = (float *) MALLOC(sizeof(float)*sample_count);
  meta = meta_read(metaFile);
  
  fpIn = FOPEN(inFile, "r");
  fgets(header, 100, fpIn);
  sscanf(header, "%f %f %f %f %f %f", &x_pix, &y_pix, &x_map_ll, &y_map_ll, 
    &x_map_ur, &y_map_ur);
  fgets(header, 100, fpIn);
  sscanf(header, "%d %d", &sample_count, &line_count);
  
  FILE *fpMask = FOPEN(maskFile, "wb");
  FILE *fpLat = FOPEN(latFile, "wb");
  FILE *fpLon = FOPEN(lonFile, "wb");
  FILE *fpXgrid = FOPEN(xFile, "wb");
  FILE *fpYgrid = FOPEN(yFile, "wb");
  for (ii=0; ii<line_count; ii++) {
    for (kk=0; kk<sample_count; kk++) {
      ASF_FREAD(&floatBuf[kk], sizeof(float), 1, fpIn);
      ieee_big32(floatBuf[kk]);
    }
    for (kk=0; kk<sample_count; kk++) {
      meta_get_latLon(meta, line_count-ii-1, kk, 0.0, &lat, &lon);
      latlon_to_proj(meta->projection, 'R', lat*D2R, lon*D2R, 0.0, &x, &y, &z);
      latBuf[kk] = lat;
      lonBuf[kk] = lon;
      xBuf[kk] = x;
      yBuf[kk] = y;
      if (floatBuf[kk] < 10000000000.0) {
        maskBuf[kk] = 1.0;
      }
      else if (floatBuf[kk] > 10000000000.0) {
        maskBuf[kk] = 1.0;
      }
      else {
        maskBuf[kk] = 0.0;
      }
    }
    put_float_line(fpMask, meta, line_count-ii-1, maskBuf);
    put_float_line(fpLat, meta, line_count-ii-1, latBuf);
    put_float_line(fpLon, meta, line_count-ii-1, lonBuf);
    put_float_line(fpXgrid, meta, line_count-ii-1, xBuf);
    put_float_line(fpYgrid, meta, line_count-ii-1, yBuf);
  }
  FCLOSE(fpIn);
  FCLOSE(fpMask);
  FCLOSE(fpLat);
  FCLOSE(fpLon);
  FREE(floatBuf);
  FREE(maskBuf);
  FREE(latBuf);
  FREE(lonBuf);
  FREE(xBuf);
  FREE(yBuf);
  meta_write(meta, latFile);
  meta_write(meta, lonFile);
  meta_write(meta, xFile);
  meta_write(meta, yFile);

  // Write ISO meatadata for netCDF
  asfPrintStatus("Generating metadata for netCDF file ...\n");

  char *ncXmlBase = get_basename(outFile);
  char *ncXmlFile = appendExt(outFile, ".xml");
  fpXml = FOPEN(ncXmlFile, "w");
  fprintf(fpXml, "<rgps>\n");
  fprintf(fpXml, "  <granule>%s</granule>\n", ncXmlBase);
  fprintf(fpXml, "  <metadata_creation>%s</metadata_creation>\n", isoStr);
  fprintf(fpXml, "  <metadata>\n");
  fprintf(fpXml, "    <product>\n");
  fprintf(fpXml, "      <file type=\"string\" definition=\"name of product "
    "file\">%s.nc</file>\n", ncXmlBase);
  if (divFlag && vrtFlag && shrFlag)
    fprintf(fpXml, "      <type type=\"string\" definition=\"product type\">"
    "divergence, vorticity, shear</type>\n");
  else if (myrFlag)
    fprintf(fpXml, "      <type type=\"string\" definition=\"product type\">"
    "multiyear ice fraction</type>\n");
  fprintf(fpXml, "      <format type=\"string\" definition=\"name of the data "
    "format\">netCDF</format>\n");

  fpInList = FOPEN(listInFile, "r");
  while (fgets(inFile, 512, fpInList)) {
    chomp(inFile);
    split_dir_and_file(inFile, dirName, baseName);
    fprintf(fpXml, "      <source type=\"string\" definition=\"name of the data"
    " source\">%s</source>\n", baseName);
  }
  FCLOSE(fpInList);

  fprintf(fpXml, "      <cell_size_x type=\"double\" definition=\"cell size "
    "in x direction\" units=\"m\">%.2f</cell_size_x>\n", x_pix*1000.0);
  fprintf(fpXml, "      <cell_size_y type=\"double\" definition=\"cell size "
    "in y direction\" units=\"m\">%.2f</cell_size_y>\n", y_pix*1000.0);
  fprintf(fpXml, "      <map_x_lower_left type=\"double\" definition=\"x "
    "coordinate of lower left corner\" units=\"m\">%.6f</map_x_lower_left>\n",
    x_map_ll*1000.0);
  fprintf(fpXml, "      <map_y_lower_left type=\"double\" definition=\"y "
    "coordinate of lower left corner\" units=\"m\">%.6f</map_y_lower_left>\n",
    y_map_ll*1000.0);
  fprintf(fpXml, "      <map_x_upper_right type=\"double\" definition=\"x "
    "coordinate of upper right corner\" units=\"m\">%.6f</map_x_upper_right>"
    "\n", x_map_ur*1000.0);
  fprintf(fpXml, "      <map_y_upper_right type=\"double\" definition=\"y "
    "coordinate of upper right corner\" units=\"m\">%.6f</map_y_upper_right>"
    "\n", y_map_ur*1000.0);
  fprintf(fpXml, "      <cell_dimension_x type=\"int\" definition=\"cell "
    "dimension in x direction\">%d</cell_dimension_x>\n", 
    sample_count);
  fprintf(fpXml, "      <cell_dimension_y type=\"int\" definition=\"cell "
    "dimension in y direction\">%d</cell_dimension_y>\n",
      line_count);
  fprintf(fpXml, "      <projection_string type=\"string\" definition=\"map "
    "projection information as well known text\">%s</projection_string>\n", 
  meta2esri_proj(meta, NULL));
  fprintf(fpXml, "    </product>\n");
  fprintf(fpXml, "  </metadata>\n");
  fprintf(fpXml, "  <extent>\n");
  fprintf(fpXml, "    <product>\n");
  fprintf(fpXml, "      <westBoundLongitude>%.5f</westBoundLongitude>\n",
    minLon);
  fprintf(fpXml, "      <eastBoundLongitude>%.5f</eastBoundLongitude>\n",
    maxLon);
  fprintf(fpXml, "      <northBoundLatitude>%.5f</northBoundLatitude>\n",
    maxLat);
  fprintf(fpXml, "      <southBoundLatitude>%.5f</southBoundLatitude>\n",
    minLat);
  fprintf(fpXml, "      <start_datetime>%s</start_datetime>\n", first);
  fprintf(fpXml, "      <end_datetime>%s</end_datetime>\n", end);
  fprintf(fpXml, "    </product>\n");
  fprintf(fpXml, "  </extent>\n");
  fprintf(fpXml, "</rgps>\n");
  FCLOSE(fpXml);
  FREE(ncXmlBase);
  FREE(ncXmlFile);
  meta_free(meta);

  // Export to netCDF
  asfPrintStatus("Exporting to netCDF file ...\n");
  export_netcdf_xml(listOutFile, outFile);

  // Clean up
  remove_dir(tmpDir);
  FREE(tmpDir);
  FREE(outFile);
  FREE(listInFile);
  FREE(isoStr);

  return 0;
}
예제 #10
0
파일: apoint.c 프로젝트: dunecn/calcurse
/*
 * Add an item in either the appointment or the event list,
 * depending if the start time is entered or not.
 */
void
apoint_add (void)
{
#define LTIME 6
  char *mesg_1 =
    _("Enter start time ([hh:mm] or [h:mm]), "
      "leave blank for an all-day event : ");
  char *mesg_2 =
    _("Enter end time ([hh:mm] or [h:mm]) or duration (in minutes) : ");
  char *mesg_3 = _("Enter description :");
  char *format_message_1 =
    _("You entered an invalid start time, should be [h:mm] or [hh:mm]");
  char *format_message_2 =
    _("You entered an invalid end time, should be [h:mm] or [hh:mm] or [mm]");
  char *enter_str = _("Press [Enter] to continue");
  int Id = 1;
  char item_time[LTIME] = "";
  char item_mesg[BUFSIZ] = "";
  long apoint_duration = 0, apoint_start;
  unsigned heures, minutes;
  unsigned end_h, end_m;
  int is_appointment = 1;

  /* Get the starting time */
  do
    {
      status_mesg (mesg_1, "");
      if (getstring (win[STA].p, item_time, LTIME, 0, 1) != GETSTRING_ESC)
        {
          if (strlen (item_time) == 0)
            {
              is_appointment = 0;
              break;
            }
          else if (check_time (item_time) != 1)
            {
              status_mesg (format_message_1, enter_str);
              (void)wgetch (win[STA].p);
            }
          else
            (void)sscanf (item_time, "%u:%u", &heures, &minutes);
        }
      else
        return;
    }
  while (check_time (item_time) != 1);

  /*
   * Check if an event or appointment is entered,
   * depending on the starting time, and record the
   * corresponding item.
   */
  if (is_appointment)
    {				/* Get the appointment duration */
      item_time[0] = '\0';
      do
        {
          status_mesg (mesg_2, "");
          if (getstring (win[STA].p, item_time, LTIME, 0, 1) != GETSTRING_VALID)
            return;		//nothing entered, cancel adding of event
          else if (check_time (item_time) == 0)
            {
              status_mesg (format_message_2, enter_str);
              (void)wgetch (win[STA].p);
            }
          else
            {
              if (check_time (item_time) == 2)
                apoint_duration = atoi (item_time);
              else if (check_time (item_time) == 1)
                {
                  (void)sscanf (item_time, "%u:%u", &end_h, &end_m);
                  if (end_h < heures || ((end_h == heures) && (end_m < minutes)))
                    {
                      apoint_duration = MININSEC - minutes + end_m
                        + (24 + end_h - (heures + 1)) * MININSEC;
                    }
                  else
                    {
                      apoint_duration = MININSEC - minutes
                        + end_m + (end_h - (heures + 1)) * MININSEC;
                    }
                }
            }
        }
      while (check_time (item_time) == 0);
    }
  else				/* Insert the event Id */
    Id = 1;

  status_mesg (mesg_3, "");
  if (getstring (win[STA].p, item_mesg, BUFSIZ, 0, 1) == GETSTRING_VALID)
    {
      if (is_appointment)
        {
          apoint_start = date2sec (*calendar_get_slctd_day (), heures, minutes);
          (void)apoint_new (item_mesg, 0L, apoint_start,
                            min2sec (apoint_duration), 0L);
          if (notify_bar ())
            notify_check_added (item_mesg, apoint_start, 0L);
        }
      else
        (void)event_new (item_mesg, 0L,
                         date2sec (*calendar_get_slctd_day (), 12, 0), Id);

      if (hilt == 0)
        hilt++;
    }
  wins_erase_status_bar ();
}
예제 #11
0
파일: combine.c 프로젝트: glshort/MapReady
static void sort_input_preference(char **infiles, int n_inputs, 
				  char *preference)
{
  int ii, kk;
  double lat[n_inputs], lon[n_inputs], sec[n_inputs], sorter[n_inputs];
  ymd_date date;
  hms_time time;
  julian_date jd;
  char **tmpfiles = (char **) MALLOC(sizeof(char *)*n_inputs);

  asfPrintStatus("Sort input images for preference: %s\n\n", preference);

  // Read in metadata
  for (ii=0; ii<n_inputs; ii++) {
    tmpfiles[ii] = (char *) MALLOC(sizeof(char)*50);
    meta_parameters *meta = meta_read(infiles[ii]);
    lat[ii] = meta->general->center_latitude;
    lon[ii] = meta->general->center_longitude;
    parse_DMYdate(meta->general->acquisition_date, &date, &time);
    date_ymd2jd(&date, &jd);
    sec[ii] = date2sec(&jd, &time);
    if (strcmp_case(preference, "north") == 0 ||
	strcmp_case(preference, "south") == 0)
      sorter[ii] = lat[ii];
    else if (strcmp_case(preference, "west") == 0 ||
	     strcmp_case(preference, "east") == 0)
      sorter[ii] = lon[ii];
    else if (strcmp_case(preference, "old") == 0 ||
	     strcmp_case(preference, "new") == 0)
      sorter[ii] = sec[ii];
    meta_free(meta);
  }
  
  // Get on with the sorting business
  if (strcmp_case(preference, "south") == 0 ||
      strcmp_case(preference, "west") == 0 ||
      strcmp_case(preference, "old") == 0)
    qsort(sorter, n_inputs, sizeof(double), compare_big_doubles);
  else
    qsort(sorter, n_inputs, sizeof(double), compare_small_doubles);

  // Apply the order to input file list
  for (ii=0; ii<n_inputs; ii++) {
    for (kk=0; kk<n_inputs; kk++) {
      if ((strcmp_case(preference, "north") == 0 ||
	   strcmp_case(preference, "south") == 0) &&
	  sorter[ii] == lat[kk])
	sprintf(tmpfiles[ii], "%s", infiles[kk]);
      else if ((strcmp_case(preference, "east") == 0 ||
		strcmp_case(preference, "west") == 0) &&
	       sorter[ii] == lon[kk])
	sprintf(tmpfiles[ii], "%s", infiles[kk]);
      else if ((strcmp_case(preference, "old") == 0 ||
		strcmp_case(preference, "new") == 0) &&
	       sorter[ii] == sec[kk])
	sprintf(tmpfiles[ii], "%s", infiles[kk]);
    }
  }
  for (ii=0; ii<n_inputs; ii++) {
    sprintf(infiles[ii], "%s", tmpfiles[ii]);
    //printf("Sorted file[%d]: %s\n", ii+1, infiles[ii]);
  }

  // Clean up
  for (ii=0; ii<n_inputs; ii++)
    FREE(tmpfiles[ii]);
  FREE(tmpfiles);
}
예제 #12
0
main(int argc, char *argv[]) 
{
  FILE *fpin, *fpout;
  
  float ibuff[CPX_PIX*2*LD];
  float **obuff;
  float b[CPX_PIX];
  float c[CPX_PIX/LA];

  int cla,nl;
  int i,j,k,line;
  int olines, osamps;
  int oline, osamp;
  double t;
  char basefile[256], infile[256], outbasefile[256], outfile[256], roifile[256];
  char *hdrfile;
  
  ymd_date date;
  hms_time time;
  meta_parameters *meta;

  char *mon[13]={"","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep",
     "Oct","Nov","Dec"};
  
  char	 dir;			// orbit direction - A or D
  double x, y, z;		// state vector positions at start of segment
  double xdot, ydot, zdot;	// state vector veloctiy at start of segment
  int    META_ONLY = 0;		// only create meta file, no img file
  int	 SEPARATE_ROI_FILE = 0; // CLA roi file given?
  int    USE_TLES = 1;		// TLE/state vector switch
  int    ESA_FRAME = 0;		// switch to control output file names
  int    node = 0;
   
  asfSplashScreen(argc, argv); 

  if (argc<2 || argc>9) { give_usage(argc,argv); exit(1); }

  while ((cla=getopt(argc,argv,"mvcE:r:")) != -1)
    switch(cla) {
      case 'm':
        META_ONLY = 1;
	printf("Using meta only option\n");
	break;
      case 'r':
	strcpy(roifile,optarg);
	SEPARATE_ROI_FILE = 1;
	break;
      case 'E':
        ESA_FRAME = 1;
	node = atoi(optarg);
	break;
      case 'v':
        USE_TLES = 0;
	break;
      case 'c':
        USE_CLOCK_DRIFT = 1;
	break;
      case '?':
        give_usage(argc,argv);
        printf("Unknown option %s\n",optarg);
	exit(1);
      default:
        give_usage(argc,argv);
	exit(1);
    } 

  strcpy(basefile,argv[optind]);
  strcpy(infile,basefile);
  strcat(infile,".slc");

  /* if no separate roi.in file is specified, use the main name */
  if (SEPARATE_ROI_FILE == 0) {
    strcpy(roifile,basefile);
    strcat(roifile,".roi.in");
  }

  /* Read parameters from the ROI.in file */
  read_roi_infile(roifile);
  nl = npatches * patch_size;
  hdrfile = get_basename(datfilename);
  strcat(hdrfile,".hdr");
  
  /* Read the start time for this image from the hdr file */
  read_hdrfile(hdrfile);
  
  if (USE_TLES == 0) 
   {
    int cnt;
    int year, month, day, hour, min;
    double sec, thisSec;
    FILE *fpvec, *fpo;
    char tmp[256];
  
    sprintf(tmp,"/home/talogan/Seasat_State_Vectors/%3i.ebf",start_date);
    fpvec = fopen(tmp,"r");
    if (fpvec == NULL) {
      printf("Unable to open state vector file for day %i\n",start_date); 
      printf("Defaulting to using TLEs instead\n");
      USE_TLES = 1;
    } else {
      cnt = fscanf(fpvec,"%i %i %i %i %i %lf %lf %lf %lf %lf %lf %lf",&year,&month,&day,&hour,&min,&sec,&x,&y,&z,&xdot,&ydot,&zdot);
      thisSec = (double) ((hour*60+min)*60)+sec;

      /* seek to the correct second of the day for the START of this file 
      -----------------------------------------------------------------*/
      while (cnt == 12 && start_sec > (thisSec+1.0)) {
        cnt = fscanf(fpvec,"%i %i %i %i %i %lf %lf %lf %lf %lf %lf %lf",&year,&month,&day,&hour,&min,&sec,&x,&y,&z,&xdot,&ydot,&zdot);
        thisSec = (double) ((hour*60+min)*60)+sec;
      }
      printf("Found closest second %lf\n",thisSec);
  
      /* need to create a state vector file the start of this image
      ------------------------------------------------------------*/
      stateVector vec, last_vec;
      last_vec.pos.x = x; last_vec.pos.y = y; last_vec.pos.z = z;
      last_vec.vel.x = xdot; last_vec.vel.y = ydot; last_vec.vel.z = zdot;
      vec = propagate(last_vec,thisSec,start_sec);
      x = vec.pos.x; y = vec.pos.y; z = vec.pos.z;
      xdot = vec.vel.x; ydot = vec.vel.y; zdot = vec.vel.z;
    }
   }
  
  if (USE_TLES == 1) {
    /* get the correct state vector */
    printf("Propagating state vectors to requested time...\n");
    create_input_tle_file(s_date,s_time,"tle1.txt");
    propagate_state_vector("tle1.txt"); 
    printf("\n\nConverting state vectors from ECI to ECEF\n");
    fix_state_vectors(s_date.year,s_date.jd,s_time.hour,s_time.min,s_time.sec);
    remove("tle1.txt");
    remove("propagated_state_vector.txt");

    printf("Reading first state vector\n");
    FILE *fpvec = fopen("fixed_state_vector.txt","r");
    if (fscanf(fpvec,"%lf %lf %lf %lf %lf %lf %lf\n",&t,&x,&y,&z,&xdot,&ydot,&zdot)!=7) 
      { printf("ERROR: Unable to find state vector in fixed_state_vector.txt file\n"); exit(1); }
    fclose(fpvec);
    remove("fixed_state_vector.txt");
  }
  if (zdot > 0.0) dir = 'A'; else dir = 'D';

  /* set up output image parameters */
  olines = nl / LD;
  osamps = ns / LA;

  /* Create the meta file */
  printf("Initializing the meta structure\n");
  meta = raw_init();

  /* Propagate the state vectors */  
  printf("Creating state vectors\n");
  stateVector stVec;/*Source state vector*/

  stVec.pos.x = x;
  stVec.pos.y = y;
  stVec.pos.z = z;
  stVec.vel.x = xdot;
  stVec.vel.y = ydot;
  stVec.vel.z = zdot;

  date_jd2ymd(&s_date,&date);

  meta->state_vectors = meta_state_vectors_init(1);
  meta->state_vectors->vecs[0].vec = stVec;
  meta->state_vectors->year = date.year;
  meta->state_vectors->julDay = s_date.jd;
  meta->state_vectors->second = date_hms2sec(&s_time);
  meta->state_vectors->vecs[0].time = 0;
  int num_vecs = 2 + (int)(nl*PRI)/30.0;
  propagate_state(meta, num_vecs+1, (nl*PRI)/num_vecs);

  printf("Calculating scene geometry parameters\n");

  double RE = r_awgs84;
  double RP = r_awgs84 * sqrt(1-r_e2wgs84);
  
  double imgSec=date2sec(&s_date,&s_time);					// time at start of image
  int num = meta->state_vectors->num / 2;					// closest state vector to center of image
  double sourceSec = imgSec+meta->state_vectors->vecs[num].time;		// time at closest state vector
  double destSec = imgSec+meta->state_vectors->vecs[meta->state_vectors->num-1].time/2;	// time at center of image

  printf("Finding center state vector\n");
  stateVector midVec = propagate(meta->state_vectors->vecs[num].vec,sourceSec,destSec);	// state vector at middle time of image
      
  x = midVec.pos.x;
  y = midVec.pos.y;
  z = midVec.pos.z;
  xdot = midVec.vel.x;
  ydot = midVec.vel.y;
  zdot = midVec.vel.z;
  
  double geocentric_lat_nadir = asin(z / sqrt (x*x+y*y+z*z));
  double lon_nadir = atan2(x,y)*180/M_PI;
  double RE_nadir = (RE * RP) / sqrt((RP*cos(geocentric_lat_nadir)*RP*cos(geocentric_lat_nadir)) +
  				     (RE*sin(geocentric_lat_nadir)*RE*sin(geocentric_lat_nadir)));
  double Rsc = sqrt(x*x+y*y+z*z);
  double geodetic_lat_nadir = atan(tan(geocentric_lat_nadir)/(1-r_e2wgs84));
  double lat_nadir = geodetic_lat_nadir*180/M_PI;
  double gamma = geodetic_lat_nadir - geocentric_lat_nadir;
    
  printf("Filling in meta->general parameters\n");
  
  strcpy(meta->general->sensor,"SEASAT");
  strcpy(meta->general->sensor_name,"SAR");
  strcpy(meta->general->mode,"STD");
  strcpy(meta->general->processor,"ASPS-v" ASPS_VERSION_STRING);
  meta->general->data_type = REAL32;
  meta->general->image_data_type = AMPLITUDE_IMAGE;
  meta->general->radiometry = r_AMP;
  sprintf(meta->general->acquisition_date, "%02d-%s-%4d %02d:%02d:%02.0f",
          date.day, mon[date.month], date.year, s_time.hour, s_time.min, s_time.sec);
  meta->general->orbit = time2rev(s_date,s_time);
  meta->general->orbit_direction = dir;
  if (ESA_FRAME == 1) meta->general->frame = node;
  meta->general->band_count = 1;
  strcpy(meta->general->bands,"HH");
  meta->general->line_count = nl/LD;
  meta->general->sample_count = ns/LA;
  meta->general->start_line = 0; 
  meta->general->start_sample = 0;
  meta->general->line_scaling = 1;
  meta->general->sample_scaling = 1;
  meta->general->x_pixel_size = (C / (2.0 * fs)) * LA;
 
  switch (station_code) {
    case 5:
      strcpy(meta->general->receiving_station, "ULA");
      break;
    case 6:
      strcpy(meta->general->receiving_station, "GDS");
      break;
    case 7:
      strcpy(meta->general->receiving_station, "MIL");
      break;
    case 9:
      strcpy(meta->general->receiving_station, "UKO");
      break;
    case 10:
      strcpy(meta->general->receiving_station, "SNF");
      break;
  }
 
  double orbit_vel = sqrt(9.81*RE_nadir*RE_nadir / Rsc);
  double swath_vel = orbit_vel * RE_nadir / Rsc;
  
  meta->general->y_pixel_size = (swath_vel * PRI) * LD;    // TAL - Check the sc_vel...
  meta->general->re_major = r_awgs84;
  meta->general->re_minor = r_awgs84 * sqrt(1-r_e2wgs84);
  
//  meta->general->bit_error_rate = ???
//  meta->general->missing_lines = ???  
//  meta->general->no_data = ???

      
  /*Create the SAR metadata block*/
  
  printf("Creating the meta->sar block\n");
  if (!meta->sar) meta->sar = meta_sar_init();

  meta->sar->image_type = 'S';
  meta->sar->look_direction = 'R';
  meta->sar->azimuth_look_count = LD;
  meta->sar->range_look_count = LA;
  meta->sar->deskewed = 0;
  meta->sar->original_line_count = nl;
  meta->sar->original_sample_count = ns;
  meta->sar->line_increment = 1;
  meta->sar->sample_increment = 1;
  meta->sar->range_time_per_pixel = 1/(2*fs);
  
  // Should be this, right???    meta->sar->azimuth_time_per_pixel = PRI;
  // Second try is this one	 meta->sar->azimuth_time_per_pixel = (destSec - imgSec) / (meta->sar->original_line_count/2);
  
  meta->sar->azimuth_time_per_pixel = meta->general->y_pixel_size / swath_vel;
  meta->sar->azimuth_time_per_pixel *= -1;
  meta->sar->time_shift = fabs(meta->general->line_count*meta->sar->azimuth_time_per_pixel);
  
//  meta->sar->slant_shift = -1080;			// emperical value from a single delta scene
//  meta->sar->time_shift = 0.18;			// emperical value from a single delta scene

  if (USE_CLOCK_DRIFT ==1) meta->sar->slant_shift = SEASAT_SLANT_SHIFT; // -1000.0;
  else meta->sar->slant_shift = 0.0;

  meta->sar->slant_range_first_pixel = srf;
  meta->sar->wavelength = wavelength;
  meta->sar->prf = prf;
  meta->sar->earth_radius = meta_get_earth_radius(meta,	meta->general->line_count/2.0, meta->general->sample_count/2.0);
  meta->sar->satellite_height = Rsc;
  meta->sar->range_doppler_coefficients[0] = dop1*prf;
  meta->sar->range_doppler_coefficients[1] = dop2*prf;
  meta->sar->range_doppler_coefficients[2] = dop3*prf;
  meta->sar->azimuth_doppler_coefficients[0] = dop1*prf;
  meta->sar->azimuth_doppler_coefficients[1] = 0;
  meta->sar->azimuth_doppler_coefficients[2] = 0;
  
///  meta->sar->azimuth_processing_bandwidth = ????
  
  meta->sar->chirp_rate = chirp_slope;
  meta->sar->pulse_duration = pulse_duration;
  meta->sar->range_sampling_rate = fs;
  strcpy(meta->sar->polarization,"HH");
  meta->sar->multilook = 1;
  meta->sar->pitch = 0;
  meta->sar->roll = 0;
  meta->sar->yaw = 0;
///  meta->sar->incid_a[0-5] = ???

  printf("Creating the meta->location block\n");
  if (!meta->location) meta->location = meta_location_init();
  meta_get_corner_coords(meta);
  meta_get_latLon(meta,meta->general->line_count/2,meta->general->sample_count/2,0,
  		  &meta->general->center_latitude, &meta->general->center_longitude);

  if (ESA_FRAME==0) {
    strcpy(outbasefile,basefile);
  } else {
    sprintf(outbasefile,"SS_%.5i_SLANT_F%.4i",meta->general->orbit,meta->general->frame);
  }

  strcpy(outfile,outbasefile);
  strcat(outfile,".img");
  strcpy(meta->general->basename,outbasefile);

  if (META_ONLY==0) { 
    obuff = (float **) malloc (sizeof(float *)*olines);
    for (i=0; i<olines; i++) obuff[i] = (float *) malloc (sizeof(float)*osamps);
  
    /* Open the input slc file and output img file*/
    fpin = fopen(infile,"rb");
    if (fpin==NULL) {printf("ERROR: Unable to open input file %s\n",infile); exit(1);}
    fpout = fopen(outfile,"wb");

    /* Take the complex looks from the slc file to create the img file */
    printf("Taking complex looks from file %s to create %s\n",infile,outfile);
    oline = 0;
    for (line=0; line < nl; line+=LD) {
      if (line%2560==0) printf("\t%i\n",line);
      fread(ibuff,sizeof(float),ns*2*LD,fpin);

      /* take looks down */
      for (j=0; j<ns; j++) {
        b[j] = 0;
        for (i=0; i<LD; i++)
          b[j] = b[j] + (ibuff[(2*j)+(i*ns*2)]*ibuff[2*j+(i*ns*2)]) 
  		      + (ibuff[(2*j+1)+(i*ns*2)]*ibuff[(2*j+1)+(i*ns*2)]);    
      }
    
      /* take looks across */
      for (j=0; j<ns/LA; j++) {
        c[j] = 0;
        for (k=0;k<LA;k++)
          c[j] = c[j] + b[j*LA+k];
        c[j] = sqrt(c[j]);
      }
      byteswap(c,ns/LA);
      for (j=0; j<osamps; j++) obuff[oline][j] = c[j];
      oline++;
    }

    /* write out image in reverse order */
    for (j=0; j<olines; j++) fwrite(obuff[olines-j-1],sizeof(float),osamps,fpout); 
 
    fclose(fpout);
    fclose(fpin);
    free(obuff);
    
  }  /* END IF META_ONLY */   

  printf("Writing out the meta file\n");
  meta_write(meta, outbasefile);

  if (META_ONLY == 0) {
    char grfilename[256];
    float grPixSiz = 12.5;
    int err = 0;
    if (ESA_FRAME == 1) {
      char tmpstr[256];
      char cropfile[256];
      char tmpfile[256];
      
      /* create the ground range image */
      sprintf(grfilename,"temp_%.5i_STD_F%.4i",meta->general->orbit,meta->general->frame);
      sr2gr_pixsiz(outbasefile, grfilename, grPixSiz);
      
      /* crop the image to exact size */
      sprintf(cropfile,"SS_%.5i_STD_F%.4i",meta->general->orbit,meta->general->frame);
      trim(grfilename,cropfile,(long long)0,(long long)0,(long long)8000,(long long)8000);
      
      /* remove the non-cropped ground range image */
      strcat(strcpy(tmpstr,grfilename),".img");
      remove(tmpstr);
      strcat(strcpy(tmpstr,grfilename),".meta");
      remove(tmpstr);

      /* geocode and export to geotiff */
      sprintf(tmpstr,"asf_geocode -p utm %s %s_utm\n",cropfile,cropfile);
      err = system(tmpstr);
      if (err) {printf("Error returned from asf_geocode\n"); exit(1);}

      sprintf(tmpstr,"asf_export -format geotiff %s_utm %s\n",cropfile,cropfile);
      err = system(tmpstr);
      if (err) {printf("Error returned from asf_export to geotiff\n"); exit(1);}
 
      /* remove the utm projected internal format image */
      strcat(strcpy(tmpstr,cropfile),"_utm.img");
      remove(tmpstr);
      strcat(strcpy(tmpstr,cropfile),"_utm.meta");
      remove(tmpstr);
 
      /* this changes the basename in the metadata from blah_SLANT to blah_STD  */
      meta_parameters *crop_meta = meta_read(cropfile);
      strcpy(crop_meta->general->basename, cropfile);
      meta_write(crop_meta, cropfile);
      meta_free(crop_meta);
 
      /* create the dowsized QC image */
      sprintf(tmpstr,"resample -scale 0.125 %s %s_small\n",cropfile,cropfile);
      err = system(tmpstr);
      if (err) {printf("Error returned from resample\n"); exit(1);}
      
      sprintf(tmpfile,"%s_QCFULL",cropfile);
      sprintf(tmpstr,"asf_export -format jpeg %s_small %s\n",cropfile,tmpfile);
      err = system(tmpstr);
      if (err) {printf("Error returned from asf_export to jpeg\n"); exit(1);}
      
      /* remove the small .img file */
      strcat(strcpy(tmpstr,cropfile),"_small.img");
      remove(tmpstr);
      strcat(strcpy(tmpstr,cropfile),"_small.meta");
      remove(tmpstr);

      /* create the subsampled QC image */
      sprintf(tmpfile,"%s_QCSUB",cropfile);
      trim(cropfile,tmpfile,(long long)3500,(long long)3500,(long long)1000,(long long)1000);

      sprintf(tmpstr,"asf_export -format jpeg %s %s\n",tmpfile,tmpfile);
      err = system(tmpstr);
      if (err) {printf("Error returned from asf_export\n"); exit(1);}

      /* run make_seasat_h5 */
      sprintf(tmpstr,"make_seasat_h5 -gap %s.dis %s %s",basefile,cropfile,cropfile);
      err = system(tmpstr);
      if (err) {printf("Error returned from make_seasat_h5\n"); exit(1);}

      /* remove the subsampled QC .img file */
      strcat(strcpy(tmpstr,tmpfile),".img");
      remove(tmpstr);
      strcat(strcpy(tmpstr,tmpfile),".meta");
      remove(tmpstr);

      /* rename the ROI.in file to match the new file name */
      sprintf(tmpfile,"%s.roi.in",cropfile);
      rename(roifile,tmpfile);

    } else {
      strcpy(grfilename,basefile);
      strcat(grfilename,"G12");
      sr2gr_pixsiz(basefile, grfilename, grPixSiz);
    } 
  }

  exit(0);
}