Exemplo n.º 1
0
meta_parameters* gamma_isp2meta(gamma_isp *gamma)
{
  meta_parameters *meta;
  char *mon[13]={"","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep",
     "Oct","Nov","Dec"};

  // Initialize the meta structure
  meta = raw_init();

  // Fill general block
  strcpy(meta->general->basename, gamma->title);
  strcpy(meta->general->sensor, gamma->sensor);
  strcpy(meta->general->sensor_name, MAGIC_UNSET_STRING); // Sensor name not available in ISP metadata
  strcpy(meta->general->mode, MAGIC_UNSET_STRING); // Mode not available in ISP metadata
  strcpy(meta->general->processor, "GAMMA ISP");
  if (strncmp_case(gamma->image_format, "FCOMPLEX", 8) == 0)
    meta->general->data_type = COMPLEX_REAL32;
  else if (strncmp_case(gamma->image_format, "SCOMPLEX", 8) == 0)
    meta->general->data_type = COMPLEX_INTEGER16;
  else if (strncmp_case(gamma->image_format, "FLOAT", 8) == 0)
    meta->general->data_type = REAL32;
  else if (strncmp_case(gamma->image_format, "SHORT", 8) == 0)
    meta->general->data_type = INTEGER16;
  else if (strncmp_case(gamma->image_format, "BYTE", 8) == 0)
    meta->general->data_type = ASF_BYTE;
  if (strcmp(gamma->image_data_type, "UNKNOWN") == 0) {
    switch(meta->general->data_type) 
      {
      case COMPLEX_REAL32:
      case COMPLEX_INTEGER16:
	meta->general->image_data_type = COMPLEX_IMAGE;
	break;
      default:
	meta->general->image_data_type = IMAGE;
	break;
      }
  }
  else {
    if (strncmp_case(gamma->image_data_type, "RAW_IMAGE", 9) == 0)
      meta->general->image_data_type = RAW_IMAGE;
    if (strncmp_case(gamma->image_data_type, "COMPLEX_IMAGE", 13) == 0)
      meta->general->image_data_type = COMPLEX_IMAGE;
    if (strncmp_case(gamma->image_data_type, "AMPLITUDE_IMAGE", 15) == 0)
      meta->general->image_data_type = AMPLITUDE_IMAGE;
    if (strncmp_case(gamma->image_data_type, "PHASE_IMAGE", 11) == 0)
      meta->general->image_data_type = PHASE_IMAGE;
    if (strncmp_case(gamma->image_data_type, "COHERENCE_IMAGE", 15) == 0)
      meta->general->image_data_type = COHERENCE_IMAGE;
    if (strncmp_case(gamma->image_data_type, "POLARIMETRIC_IMAGE", 18) == 0)
      meta->general->image_data_type = POLARIMETRIC_IMAGE;
    if (strncmp_case(gamma->image_data_type, "POLARIMETRIC_SEGMENTATION", 25) == 0)
      meta->general->image_data_type = POLARIMETRIC_SEGMENTATION;
    if (strncmp_case(gamma->image_data_type, "POLARIMETRIC_DECOMPOSITION", 26) == 0)
      meta->general->image_data_type = POLARIMETRIC_DECOMPOSITION;
    if (strncmp_case(gamma->image_data_type, "POLARIMETRIC_PARAMETER", 22) == 0)
      meta->general->image_data_type = POLARIMETRIC_PARAMETER;
    if (strncmp_case(gamma->image_data_type, "POLARIMETRIC_C2_MATRIX", 22) == 0)
      meta->general->image_data_type = POLARIMETRIC_C2_MATRIX;
    if (strncmp_case(gamma->image_data_type, "POLARIMETRIC_C3_MATRIX", 22) == 0)
      meta->general->image_data_type = POLARIMETRIC_C3_MATRIX;
    if (strncmp_case(gamma->image_data_type, "POLARIMETRIC_C4_MATRIX", 22) == 0)
      meta->general->image_data_type = POLARIMETRIC_C4_MATRIX;
    if (strncmp_case(gamma->image_data_type, "POLARIMETRIC_T3_MATRIX", 22) == 0)
      meta->general->image_data_type = POLARIMETRIC_T3_MATRIX;
    if (strncmp_case(gamma->image_data_type, "POLARIMETRIC_T4_MATRIX", 22) == 0)
      meta->general->image_data_type = POLARIMETRIC_T4_MATRIX;
    if (strncmp_case(gamma->image_data_type, 
		     "POLARIMETRIC_STOKES_MATRIX", 26) == 0)
      meta->general->image_data_type = POLARIMETRIC_STOKES_MATRIX;
    if (strncmp_case(gamma->image_data_type, "LUT_IMAGE", 9) == 0)
      meta->general->image_data_type = LUT_IMAGE;
    if (strncmp_case(gamma->image_data_type, "ELEVATION", 9) == 0)
      meta->general->image_data_type = ELEVATION;
    if (strncmp_case(gamma->image_data_type, "DEM", 3) == 0)
      meta->general->image_data_type = DEM;
    if (strncmp_case(gamma->image_data_type, "IMAGE", 5) == 0)
      meta->general->image_data_type = IMAGE;
    if (strncmp_case(gamma->image_data_type, "MASK", 4) == 0)
      meta->general->image_data_type = MASK;
    if (strncmp_case(gamma->image_data_type, "IMAGE_LAYER_STACK", 17) == 0)
      meta->general->image_data_type = IMAGE_LAYER_STACK;
    if (strncmp_case(gamma->image_data_type, "INSAR_STACK", 11) == 0)
      meta->general->image_data_type = INSAR_STACK;
  }
  sprintf(meta->general->acquisition_date, "%2d-%s-%4d",
    gamma->acquisition.day, mon[gamma->acquisition.month],
    gamma->acquisition.year);
  meta->general->orbit = gamma->orbit;
  if (gamma->heading > 90.0 && gamma->heading < 270.0)
    meta->general->orbit_direction = 'D';
  else
    meta->general->orbit_direction = 'A';
  meta->general->frame = MAGIC_UNSET_INT;
  meta->general->band_count = 1;
  strcpy(meta->general->bands, MAGIC_UNSET_STRING);
  meta->general->line_count = gamma->azimuth_lines;
  meta->general->sample_count = gamma->range_samples;
  meta->general->start_line = 0;
  meta->general->start_sample = 0;
  meta->general->x_pixel_size = gamma->range_pixel_spacing;
  meta->general->y_pixel_size = gamma->azimuth_pixel_spacing;
  meta->general->center_latitude = gamma->center_latitude;
  meta->general->center_longitude = gamma->center_longitude;
  meta->general->re_major = gamma->earth_semi_major_axis;
  meta->general->re_minor = gamma->earth_semi_minor_axis;
  meta->general->bit_error_rate = MAGIC_UNSET_DOUBLE;
  meta->general->missing_lines = 0;
  meta->general->no_data = MAGIC_UNSET_DOUBLE;

  // Fill SAR block
  meta->sar = meta_sar_init();
  if (strncmp(uc(gamma->image_geometry), "SLANT_RANGE", 11) == 0)
    meta->sar->image_type = 'S';
  else if (strncmp(uc(gamma->image_geometry), "GROUND_RANGE", 11) == 0)
    meta->sar->image_type = 'G';
  else
    meta->sar->image_type = MAGIC_UNSET_CHAR;
  if (gamma->azimuth_angle >= 0.0)
    meta->sar->look_direction = 'R';
  else
    meta->sar->look_direction = 'L';
  meta->sar->azimuth_look_count = gamma->azimuth_looks;
  meta->sar->range_look_count = gamma->range_looks;
  if (gamma->azimuth_looks > 1 || gamma->range_looks > 1)
    meta->sar->multilook = 1;
  else
    meta->sar->multilook = 0;
  meta->sar->deskewed = gamma->azimuth_deskew;
  meta->sar->original_line_count = meta->general->line_count;
  meta->sar->original_sample_count = meta->general->sample_count;
  meta->sar->line_increment = 1;
  meta->sar->sample_increment = 1;
  meta->sar->range_time_per_pixel = fabs((2.0 * gamma->range_pixel_spacing) / 
					 gamma->range_looks /
					 SPD_LIGHT);
  meta->sar->azimuth_time_per_pixel = gamma->azimuth_line_time;
  meta->sar->slant_range_first_pixel = gamma->near_range_slc;
  meta->sar->slant_shift = 0.0;
  meta->sar->time_shift = 0.0;
  /* Under testing - does not seem to apply to the test data set.
  if (meta->general->orbit_direction == 'D')
    meta->sar->time_shift = 0.0;
  else if (meta->general->orbit_direction == 'A')
    meta->sar->time_shift = fabs(meta->sar->original_line_count * meta->sar->azimuth_time_per_pixel);
  else
    meta->sar->time_shift = MAGIC_UNSET_DOUBLE;
  */
  meta->sar->wavelength = SPD_LIGHT / gamma->radar_frequency;
  meta->sar->prf = gamma->prf;
  meta->sar->earth_radius = gamma->earth_radius_below_sensor;
  meta->sar->earth_radius_pp = meta->sar->earth_radius; // KLUDGE: This value is actually unknown in ISP metadata
  meta->sar->satellite_height = gamma->sar_to_earth_center;
  strcpy(meta->sar->satellite_binary_time, MAGIC_UNSET_STRING);
  strcpy(meta->sar->satellite_clock_time, MAGIC_UNSET_STRING);
  int i;
  if (gamma->doppler_polynomial[3] > 0.0001) {
    // FIXME: If this error ever fires, then we should insert a function that does a
    // quadratic fit to the cubic function.  Then we can derive close 'nuf quadratic
    // values from a set of points generated by the cubic and use those.
    asfPrintError("GAMMA doppler polynomial has a large cubic term\n"
        "(%f versus limit of 0.0001) and is not well modeled by a\nquadratic.",
        gamma->doppler_polynomial[3]);
  }
  for (i=0; i<3; i++) {
    meta->sar->range_doppler_coefficients[i] = gamma->doppler_polynomial[i]; 
    meta->sar->azimuth_doppler_coefficients[i] = 0.0;
  }
  // Adjust for difference in units [Hz/m] -> [Hz/pixel]
  meta->sar->range_doppler_coefficients[1] /= gamma->range_pixel_spacing;
  meta->sar->range_doppler_coefficients[2] /= 
    gamma->range_pixel_spacing * gamma->range_pixel_spacing;

  meta->sar->azimuth_doppler_coefficients[0] = gamma->doppler_polynomial[0];
  meta->sar->azimuth_processing_bandwidth = gamma->azimuth_proc_bandwidth;
  meta->sar->chirp_rate = gamma->chirp_bandwidth;
  meta->sar->pulse_duration = MAGIC_UNSET_DOUBLE;
  meta->sar->range_sampling_rate = gamma->adc_sampling_rate;
  strcpy(meta->sar->polarization, MAGIC_UNSET_STRING);

  // Fill state vector structure
  meta->state_vectors = meta_state_vectors_init(3);
  meta->state_vectors = gamma->stVec;

  // Propagate the state vectors to start, center, end
  int vector_count = 3;
  double data_int = gamma->center_time - gamma->start_time;
  while (fabs(data_int) > 15.0) {
    data_int /= 2;
    vector_count = vector_count*2-1;
  }
  propagate_state(meta, vector_count, data_int);
  
  // Generate location block
  meta_get_corner_coords(meta);

  return meta;
}
Exemplo n.º 2
0
meta_parameters *iso2meta(iso_meta *iso)
{
  int ii;
  meta_parameters *meta = raw_init();
  char str[30];

  // Convenience pointers
  iso_generalHeader *header = iso->generalHeader;
  iso_productComponents *comps = iso->productComponents;
  iso_productInfo *info = iso->productInfo;
  iso_productSpecific *spec = iso->productSpecific;
  iso_setup *setup = iso->setup;
  iso_processing *proc = iso->processing;
  iso_instrument *inst = iso->instrument;
  iso_platform *platform = iso->platform;
  iso_productQuality *quality = iso->productQuality;

  meta->meta_version = 3.5;

  // General block
  for (ii=0; ii<comps->numAnnotations; ii++)
    if (comps->annotation[ii].type == MAIN_TYPE)
      strncpy(meta->general->basename, comps->annotation[ii].file.name, 256);
  strcpy(meta->general->sensor, header->mission);
  strcpy(meta->general->sensor_name, info->sensor);
  strcpy(meta->general->mode, info->elevationBeamConfiguration);
  strcpy(meta->general->receiving_station, info->receivingStation);
  strcpy(meta->general->processor, header->generationSystem);
  if (info->imageDataType == DETECTED_DATA_TYPE &&
      info->imageDataDepth == 8)
    meta->general->data_type = ASF_BYTE;
  else if (info->imageDataType == DETECTED_DATA_TYPE &&
	   info->imageDataDepth == 16)
    meta->general->data_type = INTEGER16;
  else if (info->imageDataType == DETECTED_DATA_TYPE &&
	   info->imageDataDepth == 32)
    // assumption here is that we are not dealing with INTERGER32
    meta->general->data_type = REAL32;
  else if (info->imageDataType == DETECTED_DATA_TYPE &&
	   info->imageDataDepth == 64)
    meta->general->data_type = REAL64;
  else if (info->imageDataType == COMPLEX_DATA_TYPE &&
	   info->imageDataDepth == 8)
    meta->general->data_type = COMPLEX_BYTE;
  else if (info->imageDataType == COMPLEX_DATA_TYPE &&
	   info->imageDataDepth == 16)
    meta->general->data_type = COMPLEX_INTEGER16;
  else if (info->imageDataType == COMPLEX_DATA_TYPE &&
	   info->imageDataDepth == 32)
    // assumption here is that we are not dealing with COMPLEX_INTEGER32
    meta->general->data_type = COMPLEX_REAL32;
  else if (info->imageDataType == COMPLEX_DATA_TYPE &&
	   info->imageDataDepth == 64)
    meta->general->data_type = COMPLEX_REAL64;
  if (info->imageDataType == RAW_DATA_TYPE)
    meta->general->image_data_type = RAW_IMAGE;
  else if (info->imageDataType == COMPLEX_DATA_TYPE)
    meta->general->image_data_type = COMPLEX_IMAGE;
  else if (info->imageDataType == DETECTED_DATA_TYPE)
    meta->general->image_data_type = AMPLITUDE_IMAGE;
  // more detailed mapping of imageDataType will probably need pixelValueID 
  // context
  if (strcmp_case(info->pixelValueID, "RADAR BRIGHTNESS") == 0)
    meta->general->radiometry = r_AMP;
  // dealing with any form of calibration not implemented yet
  dateTime2str(info->sceneCenterCoord.azimuthTimeUTC,
	       meta->general->acquisition_date);
  meta->general->orbit = info->absOrbit;
  if (info->orbitDirection == ASCENDING)  
    meta->general->orbit_direction = 'A';
  else if (info->orbitDirection == DESCENDING)
    meta->general->orbit_direction = 'D';
  meta->general->frame = setup->frameID;
  meta->general->band_count = comps->numLayers;
  strcpy(meta->general->bands, polLayer2str(comps->imageData[0].polLayer));
  for (ii=1; ii<comps->numLayers; ii++) {
    sprintf(str, ", %s", polLayer2str(comps->imageData[ii].polLayer));
    strcat(meta->general->bands, str);
  }
  meta->general->line_count = info->numberOfRows;
  meta->general->sample_count = info->numberOfColumns;
  meta->general->start_line = info->startRow;
  meta->general->start_sample = info->startColumn;
  meta->general->x_pixel_size = info->groundRangeResolution;
  meta->general->y_pixel_size = info->azimuthResolution;
  meta->general->center_latitude = info->sceneCenterCoord.lat;
  meta->general->center_longitude = info->sceneCenterCoord.lon;
  spheroid_type_t spheroid = WGS84_SPHEROID; // FIXME: needs to know reference
  spheroid_axes_lengths(spheroid,
			&meta->general->re_major, &meta->general->re_minor);
  meta->general->bit_error_rate = quality->imageDataQuality[0].bitErrorRate;
  meta->general->missing_lines = quality->imageDataQuality[0].missingLines;
  meta->general->no_data = (float) quality->imageDataQuality[0].noData;

  // SAR block
  meta->sar = meta_sar_init();
  if (info->projection == SLANTRANGE_PROJ)
    meta->sar->image_type = 'S';
  else if (info->projection == GROUNDRANGE_PROJ)
    meta->sar->image_type = 'G';
  else if (info->projection == MAP_PROJ)
    meta->sar->image_type = 'P';
  if (setup->lookDirection == RIGHT_LOOK)
    meta->sar->look_direction = 'R';
  else if (setup->lookDirection == LEFT_LOOK)
    meta->sar->look_direction = 'L';
  meta->sar->azimuth_look_count = info->azimuthLooks;
  meta->sar->range_look_count = info->rangeLooks;
  if (spec->imageCoordinateType == RAW_COORD)
    meta->sar->deskewed = FALSE;
  else if (spec->imageCoordinateType == ZERODOPPLER)
    meta->sar->deskewed = TRUE;
  meta->general->line_scaling = info->rowScaling;  
  meta->general->sample_scaling = info->columnScaling;
  meta->sar->range_time_per_pixel = info->columnSpacing;
  meta->sar->azimuth_time_per_pixel = info->rowSpacing;
  meta->sar->slant_shift = spec->slantRangeShift;
  //meta->sar->slant_range_first_pixel = info->rangeTimeFirstPixel * SPD_LIGHT;
  meta->sar->slant_range_first_pixel = spec->projectedSpacingSlantRange;
  meta->sar->wavelength = SPD_LIGHT / inst->centerFrequency;
  meta->sar->prf = spec->commonPRF;
  meta->sar->earth_radius = info->earthRadius;
  meta->sar->satellite_height = info->satelliteHeight;
  // meta->sar->satellite_binary_time;
  // meta->sar->satellite_clock_time;
  for (ii=0; ii<=proc->doppler[0].polynomialDegree; ii++)
    meta->sar->range_doppler_coefficients[ii] = 
      proc->doppler[0].coefficient[ii];
  meta->sar->azimuth_doppler_coefficients[0] = proc->doppler[0].coefficient[0];
  // meta->sar->chirp_rate
  // meta->sar->pulse_duration
  meta->sar->range_sampling_rate = spec->commonRSF;
  if (info->polarizationMode == SINGLE_POL)
    strcpy(meta->sar->polarization, "SINGLE");
  else if (info->polarizationMode == DUAL_POL)
    strcpy(meta->sar->polarization, "DUAL");
  else if (info->polarizationMode == QUAD_POL)
    strcpy(meta->sar->polarization, "QUAD");
  meta->sar->multilook = proc->multiLookedFlag;
  meta->sar->pitch = info->pitch;
  meta->sar->roll = info->roll;
  meta->sar->yaw = info->yaw;
  meta->sar->incid_a[0] = info->sceneCenterCoord.incidenceAngle;
  meta->sar->heading_angle = info->headingAngle;
  meta->sar->chirp_rate = proc->processingParameter[0].chirpRate;
  meta->sar->pulse_duration = proc->processingParameter[0].pulseDuration;

  // meta->projection
  // meta->transform
  // meta->airsar
  // meta->uavsar
  // meta->statistics

  int numVectors = platform->numStateVectors;
  meta->state_vectors = meta_state_vectors_init(numVectors);
  meta->state_vectors->vector_count = numVectors;
  ymd_date ymdStart, ymdSV;
  julian_date jd;
  hms_time hmsStart, hmsSV;
  ymdStart.year = info->startTimeUTC.year;
  ymdStart.month = info->startTimeUTC.month;
  ymdStart.day = info->startTimeUTC.day;
  hmsStart.hour = info->startTimeUTC.hour;
  hmsStart.min = info->startTimeUTC.min;
  hmsStart.sec = info->startTimeUTC.second;
  meta->state_vectors->year = info->startTimeUTC.year;
  date_ymd2jd(&ymdStart, &jd);
  meta->state_vectors->julDay = jd.jd;
  meta->state_vectors->second = date_hms2sec(&hmsStart);
  for (ii=0; ii<numVectors; ii++) {
    ymdSV.year = platform->stateVec[ii].timeUTC.year;
    ymdSV.month = platform->stateVec[ii].timeUTC.month;
    ymdSV.day = platform->stateVec[ii].timeUTC.day;
    hmsSV.hour = platform->stateVec[ii].timeUTC.hour;
    hmsSV.min = platform->stateVec[ii].timeUTC.min;
    hmsSV.sec = platform->stateVec[ii].timeUTC.second;
    meta->state_vectors->vecs[ii].time = 
      time_difference(&ymdSV, &hmsSV, &ymdStart, &hmsStart);
    meta->state_vectors->vecs[ii].vec.pos.x = platform->stateVec[ii].posX;
    meta->state_vectors->vecs[ii].vec.pos.y = platform->stateVec[ii].posY;
    meta->state_vectors->vecs[ii].vec.pos.z = platform->stateVec[ii].posZ;
    meta->state_vectors->vecs[ii].vec.vel.x = platform->stateVec[ii].velX;
    meta->state_vectors->vecs[ii].vec.vel.y = platform->stateVec[ii].velY;
    meta->state_vectors->vecs[ii].vec.vel.z = platform->stateVec[ii].velZ;
  }
  if (meta->sar->azimuth_time_per_pixel > 0)
    meta->sar->time_shift = 0.0;
  else
    meta->sar->time_shift = meta->state_vectors->vecs[numVectors-1].time;

  if (meta->sar->yaw == 0 ||
      !meta_is_valid_double(meta->sar->yaw))
  {
    meta->sar->yaw = meta_yaw(meta, meta->general->line_count/2.0,
                                    meta->general->sample_count/2.0);
  }
  /*
  // few calculations need state vectors
  meta->sar->earth_radius = 
    meta_get_earth_radius(meta, line_count/2, sample_count/2);
  // meta->sar->earth_radius_pp
  meta->sar->satellite_height =
    meta_get_sat_height(meta, meta->general->line_count/2,
			meta->general->sample_count/2);
  meta->sar->incid_a[0] = meta_incid(meta, line_count/2, sample_count/2)*R2D;
  */

  // Location block
  meta_get_corner_coords(meta);
/*
  meta->location = meta_location_init();
  for (ii=0; ii<4; ii++) {
    if (info->sceneCornerCoord[ii].refRow == 0 &&
	info->sceneCornerCoord[ii].refColumn == 0) {
      meta->location->lat_start_near_range = info->sceneCornerCoord[ii].lat;
      meta->location->lon_start_near_range = info->sceneCornerCoord[ii].lon;
    }
    else if (info->sceneCornerCoord[ii].refRow == 0 &&
	     info->sceneCornerCoord[ii].refColumn == sample_count) {
      meta->location->lat_start_far_range = info->sceneCornerCoord[ii].lat;
      meta->location->lon_start_far_range = info->sceneCornerCoord[ii].lon;
    }
    else if (info->sceneCornerCoord[ii].refRow == line_count &&
	     info->sceneCornerCoord[ii].refColumn == 0) {
      meta->location->lat_end_near_range = info->sceneCornerCoord[ii].lat;
      meta->location->lon_end_near_range = info->sceneCornerCoord[ii].lon;
    }
    else if (info->sceneCornerCoord[ii].refRow == line_count &&
	     info->sceneCornerCoord[ii].refColumn == sample_count) {
      meta->location->lat_end_far_range = info->sceneCornerCoord[ii].lat;
      meta->location->lon_end_far_range = info->sceneCornerCoord[ii].lon;
    }
  }
*/
  return meta;
}
Exemplo n.º 3
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);
}