예제 #1
0
/* Date Utility Routine: Convert ODL style date to structure.
   Input format is YYYY-DDDTHH:MM:SS.TTT */
void parse_odlTime(const char *str, ymd_date *date, hms_time *time)
{
        char tmpBuf[6];
        int  cnt=0;
        julian_date jul;

        tmpBuf[0] = str[cnt++]; tmpBuf[1] = str[cnt++];
        tmpBuf[2] = str[cnt++]; tmpBuf[3] = str[cnt++];
        tmpBuf[4] = '\0'; jul.year = atoi(tmpBuf);
        cnt++;

        tmpBuf[0] = str[cnt++]; tmpBuf[1] = str[cnt++];
        tmpBuf[2] = str[cnt++]; tmpBuf[3] = '\0'; jul.jd = atoi(tmpBuf);
        cnt++;

        date_jd2ymd(&jul,date);

        tmpBuf[0] = str[cnt++]; tmpBuf[1] = str[cnt++];
        tmpBuf[2] = '\0'; time->hour = atoi(tmpBuf);
        cnt++;

        tmpBuf[0] = str[cnt++]; tmpBuf[1] = str[cnt++];
        tmpBuf[2] = '\0'; time->min = atoi(tmpBuf);
        cnt++;

        tmpBuf[0] = str[cnt++]; tmpBuf[1] = str[cnt++];
        cnt++;
        tmpBuf[2] = str[cnt++]; tmpBuf[3] = str[cnt++];
        tmpBuf[4] = str[cnt++];
        tmpBuf[5] = '\0'; time->sec = atof(tmpBuf)/1000.0;
}
예제 #2
0
static void jd2date(julian_date *jd, char *buf)
{
  char mon[][5]= 
    {"","JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"};
  ymd_date ymd;
  date_jd2ymd(jd, &ymd);
  sprintf(buf, "%02d-%s-%4d", ymd.day, mon[ymd.month], ymd.year);
}
예제 #3
0
// Compute date corresponding to seconds since midnight, Jan 1, 1985.
void seconds2date(double seconds, ymd_date *date, hms_time *time)
{
  julian_date jd;
  int year = 1985;
  double secs = seconds;
  while (secs >= date_getDaysInYear(year)*DAY2SEC)
    secs -= date_getDaysInYear(year++)*DAY2SEC;
  jd.year = year;
  jd.jd = 1 + (int)(secs/DAY2SEC);
  secs -= (jd.jd - 1)*DAY2SEC;
  date_sec2hms(secs, time);
  date_jd2ymd(&jd, date);
}
예제 #4
0
// input is seconds since midnight Jan 1, 1900
// output is a string of the form "MM/DD HH:MM"
const char *date_str(double s)
{
  julian_date jd;
  hms_time t;
  ymd_date d;
  static char buf[64];

  sec2date(s, &jd, &t);
  date_jd2ymd(&jd, &d);

  sprintf(buf, "%02d/%02d %02d:%02d", d.month, d.day, t.hour, t.min);
  return buf;
}
예제 #5
0
static void rgps2iso_date(int year, double day, char *isoStr)
{
  julian_date jd;
  hms_time time;
  ymd_date date;
  
  jd.year = year;
  jd.jd = (int) day;
  date_jd2ymd(&jd, &date);
  double sec = 86400 * (day - jd.jd);
  date_sec2hms(sec, &time);
  sprintf(isoStr, "%4d-%02d-%02dT%02d:%02d:%09.6lfZ",
        date.year, date.month, date.day, time.hour, time.min, time.sec);
}
예제 #6
0
// input is seconds since midnight Jan 1, 1900
// output is a string of the form "DD-MON-YYYY HH:MM"
const char *date_str_long(double s)
{
  char mon[][5]= 
    {"","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
  julian_date jd;
  hms_time t;
  ymd_date d;
  static char buf[64];

  sec2date(s, &jd, &t);
  date_jd2ymd(&jd, &d);

  sprintf(buf, "%02d-%s-%4d, %02d:%02d:%02d", d.day, mon[d.month], d.year,
          t.hour, t.min, (int)(t.sec+.5));
  return buf;
}
예제 #7
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);
}
예제 #8
0
static void dateTimeStamp(meta_parameters *meta, int line, 
			  iso_dateTime *dateTime)
{
  julian_date jd;
  hms_time hms;
  ymd_date ymd;
  jd.year = meta->state_vectors->year;
  jd.jd = meta->state_vectors->julDay;
  date_sec2hms(meta->state_vectors->second, &hms);
  date_jd2ymd(&jd, &ymd);
  double imgSec = line*meta->sar->azimuth_time_per_pixel;
  add_time(imgSec, &ymd, &hms);
  dateTime->year = ymd.year;
  dateTime->month = ymd.month;
  dateTime->day = ymd.day;
  dateTime->hour = hms.hour;
  dateTime->min = hms.min;
  dateTime->second = hms.sec;
}
예제 #9
0
void testssv(double rsv[], char *datestr, int year, int *itworks_flag)
{
    int			i;
    char		cmd[255], tmpstr[255],
    			inVec[255],outVec[255],
    			llfile[255],projfile[255];
    double		gmtSec,
    			tstlat;
    julian_date jld;
    ymd_date	ymd;
    hms_time	hms;
    
    FILE	*fpi, *fpo;
    
    *itworks_flag=1;  /* assume that it will work-- change if it doesn't */
    
    /* fix string length if required */
	strcpy(tmpstr, "");
	for (i=0; i<16-strlen(datestr); i++) { strcat(tmpstr, "0"); }
        strcat(tmpstr, datestr);
	strcpy(datestr, tmpstr);
	
    jld.year = year;
    datestr_parse(datestr, &jld, &hms);
    date_jd2ymd(&jld,&ymd);
    gmtSec = hms.hour*3600+hms.min*60+hms.sec;
        
    strcpy(inVec,"propIn.1");
	strcpy(outVec,"propOut.1");
	strcpy(llfile,"latlon.1");
	strcpy(projfile,"proj.1");
	
	/* Write the rsv file for use by prop2ll */
	fpo = fopen(RSVfile,"w");
	for (i=1; i<=6; i++) { fprintf(fpo, "%lf ", rsv[i]); }
	fprintf(fpo, "\n%d %d %lf",jld.year,jld.jd,gmtSec);
	fprintf(fpo, "\n%lf\n",propahead/2);
	fclose(fpo);
	
	/* Write input file for propagate and run */
	fpo = fopen(inVec,"w");
    for (i=1; i<=6; i++) { fprintf(fpo, "%lf\n", rsv[i]); }
    fprintf(fpo,"%d\n%d\n%d\n",ymd.year,ymd.month,ymd.day);
    fprintf(fpo,"%lf\n",gmtSec);
    fprintf(fpo,"%d\n%d\n%d\n",ymd.year,ymd.month,ymd.day);
    fprintf(fpo,"%lf\n",gmtSec+propahead);
    fprintf(fpo,"%d\n",(int)(propahead/deltatime));
    fclose(fpo);
    sprintf(cmd,"propagate %s %s\n",inVec,outVec); execute(cmd);
    sprintf(cmd,"prop2ll %s %s %s\n",RSVfile,outVec,llfile); execute(cmd);
    
    /* Failure of ll2proj indicates the state vector did not work */
    sprintf(cmd,"ll2proj %s %s %s\n",DEMfile,llfile,projfile);
    printf("%s",cmd); fflush(stdin);
    if (system(cmd)!=0) *itworks_flag=0;
    	else {  /* Second test to make sure it covers the whole scene */
    		fpi = fopen(llfile,"r");
	    	for (i=1; i<=5; i++) fscanf(fpi,"%lf",&tstlat);
	    	printf("LAT extreme 1: %lf\n",tstlat);
	    	if (tstlat<hilat&&tstlat>lolat) *itworks_flag=0;
	    	for (i=1; i<=(int)(5*(propahead/deltatime-1)); i++) 
	    		{ fscanf(fpi,"%lf",&tstlat); }
	    	printf("LAT extreme 2: %lf\n",tstlat);
	    	if (tstlat<hilat&&tstlat>lolat) *itworks_flag=0;
	    	fclose(fpi);
    	}
    
    /* Clean up temporary files */
    if (*itworks_flag) {
    	sprintf(cmd,"rm %s %s %s %s\n",inVec,outVec,llfile,projfile);
    	execute(cmd); }
    else {
    	printf("State vector failed: %s\n",datestr);
    	sprintf(cmd,"rm %s %s %s\n",inVec,outVec,llfile);
    	execute(cmd);
    	sprintf(cmd,"rm %s\n",RSVfile);
    	execute(cmd); }
    
}
예제 #10
0
/***************************************************************
 * Ceos_init_stVec:
 * Reads state vectors from given CEOS file, writing them in the
 * appropriate format to SAR parameters structure.*/
void ceos_init_stVec(const char *fName, ceos_description *ceos,
             meta_parameters *meta)
{
  struct pos_data_rec ppdr;

  /*Fetch platform position data record.*/
  get_ppdr(fName,&ppdr);

  // Read the state vectors from the leader data file, adjust coordinate system, etc.
  // and write them to the SAR parameters structures
  ceos_read_stVecs(fName, ceos, meta);

  // For ALOS Palsar orbits only
  // Don't propagate but select nine state vectors around the center for the
  // higher order interpolation scheme
  if (ceos->processor == ALOS_PROC) {

    // Determine closest state vector
    int ii, min;
    double diff = 99999999;
    for (ii=0; ii<meta->state_vectors->vector_count; ii++) {
      if (fabs(meta->state_vectors->vecs[ii].time) < diff) {
        diff = fabs(meta->state_vectors->vecs[ii].time);
        min = ii;
      }
    }

    // Populate a new state vector 
    ymd_date img_ymd;
    julian_date img_jd;
    hms_time img_time;
    img_jd.year = meta->state_vectors->year;
    img_jd.jd   = meta->state_vectors->julDay;
    date_sec2hms(meta->state_vectors->second,&img_time);
    date_jd2ymd(&img_jd, &img_ymd);
    add_time((min-4)*60, &img_ymd, &img_time);
    date_ymd2jd(&img_ymd, &img_jd);
    meta_state_vectors *new_st = meta_state_vectors_init(9);
    new_st->year   = img_jd.year;
    new_st->julDay = img_jd.jd;
    new_st->second = date_hms2sec(&img_time);
    for (ii=0; ii<9; ii++)
      new_st->vecs[ii] = meta->state_vectors->vecs[ii+min-4];
    FREE(meta->state_vectors);
    meta->state_vectors = new_st;
    // Time shift should definitely set in the code that is calling this function
    // meta->sar->time_shift = 0.0;
  }
  // Propagate three state vectors for regular frames
  else if (ceos->processor != PREC && ceos->processor != unknownProcessor) {
      int vector_count=3;
      double data_int = meta->sar->original_line_count / 2
                  * fabs(meta->sar->azimuth_time_per_pixel);
      meta->state_vectors->vecs[0].time = get_timeDelta(ceos, &ppdr, meta);
      if (ceos->processor != PREC && data_int < 360.0) {
          while (fabs(data_int) > 15.0) {
              data_int /= 2;
              vector_count = vector_count*2-1;
          }
      // propagate three state vectors: start, center, end
          propagate_state(meta, vector_count, data_int);
      }
  }
}
예제 #11
0
// Convert baselines to kml
void baseline2kml(int ii, struct base_pair *pairs, FILE *fp)
{
    int kk, vertices=4;
    double *lat, *lon;
    julian_date jd;
    ymd_date ymd;
    char *mon[13]= {"", "Jan", "Feb", "Mar", "Apr", "May", "Jun",
                    "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
                   };

    lat = (double *) MALLOC(sizeof(double)*(vertices+1));
    lon = (double *) MALLOC(sizeof(double)*(vertices+1));
    lat[0] = pairs->ns_lat;
    lon[0] = pairs->ns_lon;
    lat[1] = pairs->fs_lat;
    lon[1] = pairs->fs_lon;
    lat[2] = pairs->fe_lat;
    lon[2] = pairs->fe_lon;
    lat[3] = pairs->ne_lat;
    lon[3] = pairs->ne_lon;
    lat[vertices] = lat[0];
    lon[vertices] = lon[0];

    // Write information in kml file
    fprintf(fp, "<Placemark>\n");
    fprintf(fp, "<description><![CDATA[<table><tr><td width=400>\n");
    if (strcmp(pairs->m_sensor, pairs->s_sensor) == 0)
        fprintf(fp, "<strong>Sensor</strong>: %s<br>\n", pairs->m_sensor);
    else {
        fprintf(fp, "<strong>Master sensor</strong>: %s<br>\n", pairs->m_sensor);
        fprintf(fp, "<strong>Slave sensor</strong>: %s<br>\n", pairs->s_sensor);
    }
    fprintf(fp, "<strong>Mode</strong>: %s<br>\n", pairs->mode);
    fprintf(fp, "<strong>Frame</strong>: %d<br>\n", pairs->frame);
    if (strcmp_case(pairs->m_sensor, "PSR") == 0)
        fprintf(fp, "<strong>Off-nadir angle</strong>: %.4f\n", pairs->off_nadir);
    fprintf(fp, "<strong>Orbit direction</strong>: %s<br>\n",
            pairs->orbit_dir);
    fprintf(fp, "<strong>Master</strong>: %d<br>\n", pairs->master);
    sscanf(pairs->m_time, "%4d-%3dT", &jd.year, &jd.jd);
    date_jd2ymd(&jd, &ymd);
    fprintf(fp, "<strong>Master acquisition</strong>: %d-%s-%d<br>\n",
            ymd.day, mon[ymd.month], ymd.year);
    fprintf(fp, "<strong>Slave</strong>: %d<br>\n", pairs->slave);
    sscanf(pairs->s_time, "%4d-%3dT", &jd.year, &jd.jd);
    date_jd2ymd(&jd, &ymd);
    fprintf(fp, "<strong>Slave acquisition</strong>: %d-%s-%d<br>\n",
            ymd.day, mon[ymd.month], ymd.year);
    fprintf(fp, "<strong>Parallel baseline</strong>: %i<br>\n",
            pairs->b_par);
    fprintf(fp, "<strong>Perpendicular baseline</strong>: %i<br>\n",
            pairs->b_perp);
    fprintf(fp, "<strong>Temporal baseline</strong>: %i<br>\n",
            pairs->b_temp);
    for (kk=0; kk<vertices; kk++) {
        fprintf(fp, "<strong>%d</strong> - ", kk+1);
        fprintf(fp, "<strong>Lat</strong>: %9.4f, ", lat[kk]);
        fprintf(fp, "<strong>Lon</strong>: %9.4f<br>\n", lon[kk]);
    }
    fprintf(fp, "</td></tr></table>]]></description>\n");
    fprintf(fp, "<name>Master orbit: %d - Slave orbit: %d - "
            "Frame: %d</name>\n",
            pairs->master, pairs->slave, pairs->frame);
    fprintf(fp, "<LookAt>\n");
    fprintf(fp, "<longitude>%.4f</longitude>\n", pairs->c_lon);
    fprintf(fp, "<latitude>%.4f</latitude>\n", pairs->c_lat);
    fprintf(fp, "<range>500000</range>\n");
    fprintf(fp, "<heading>0</heading>\n");
    fprintf(fp, "</LookAt>\n");
    write_kml_style_keys(fp);
    fprintf(fp, "<Polygon>\n");
    fprintf(fp, "<outerBoundaryIs>\n");
    fprintf(fp, "<LinearRing>\n");
    fprintf(fp, "<extrude>1</extrude>\n");
    fprintf(fp, "<tessellate>1</tessellate>\n");
    fprintf(fp, "<altitudeMode>absolute</altitudeMode>\n");
    fprintf(fp, "<coordinates>\n");
    for (kk=0; kk<=vertices; kk++)
        fprintf(fp, "%.12f,%.12f,20000\n", lon[kk], lat[kk]);
    fprintf(fp, "</coordinates>\n");
    fprintf(fp, "</LinearRing>\n");
    fprintf(fp, "</outerBoundaryIs>\n");
    fprintf(fp, "</Polygon>\n");
    fprintf(fp, "</Placemark>\n");
    fflush(fp);

    return;
}
예제 #12
0
// Convert baseline to shape file
void baseline2shape(int ii, struct base_pair *pairs,
                    DBFHandle dbase, SHPHandle shape)
{
    int vertices=4, off;
    char date[15];
    double *lat, *lon;
    julian_date jd;
    ymd_date ymd;
    char *mon[13]= {"", "Jan", "Feb", "Mar", "Apr", "May", "Jun",
                    "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
                   };

    // Read coordinates of the vertices
    lat = (double *) MALLOC(sizeof(double)*(vertices+1));
    lon = (double *) MALLOC(sizeof(double)*(vertices+1));
    lat[0] = pairs->ns_lat;
    lon[0] = pairs->ns_lon;
    lat[1] = pairs->fs_lat;
    lon[1] = pairs->fs_lon;
    lat[2] = pairs->fe_lat;
    lon[2] = pairs->fe_lon;
    lat[3] = pairs->ne_lat;
    lon[3] = pairs->ne_lon;
    lat[vertices] = lat[0];
    lon[vertices] = lon[0];

    // Write information into database file
    if (strcmp_case(pairs->m_sensor, pairs->s_sensor) == 0) {
        DBFWriteStringAttribute(dbase, ii, 0, pairs->m_sensor);
        off = 0;
    }
    else {
        DBFWriteStringAttribute(dbase, ii, 0, pairs->m_sensor);
        DBFWriteStringAttribute(dbase, ii, 1, pairs->s_sensor);
        off = 1;
    }
    DBFWriteStringAttribute(dbase, ii, off+1, pairs->mode);
    DBFWriteIntegerAttribute(dbase, ii, off+2, pairs->frame);
    DBFWriteStringAttribute(dbase, ii, off+3, pairs->orbit_dir);
    DBFWriteIntegerAttribute(dbase, ii, off+4, pairs->master);
    sscanf(pairs->m_time, "%4d-%3dT", &jd.year, &jd.jd);
    date_jd2ymd(&jd, &ymd);
    sprintf(date, "%d-%s-%d", ymd.day, mon[ymd.month], ymd.year);
    DBFWriteStringAttribute(dbase, ii, off+5, date);
    DBFWriteIntegerAttribute(dbase, ii, off+6, pairs->slave);
    sscanf(pairs->s_time, "%4d-%3dT", &jd.year, &jd.jd);
    date_jd2ymd(&jd, &ymd);
    sprintf(date, "%d-%s-%d", ymd.day, mon[ymd.month], ymd.year);
    DBFWriteStringAttribute(dbase, ii, off+7, date);
    DBFWriteIntegerAttribute(dbase, ii, off+8, pairs->b_par);
    DBFWriteIntegerAttribute(dbase, ii, off+9, pairs->b_perp);
    DBFWriteIntegerAttribute(dbase, ii, off+10, pairs->b_temp);
    DBFWriteDoubleAttribute(dbase, ii, off+11, pairs->c_lat);
    DBFWriteDoubleAttribute(dbase, ii, off+12, pairs->c_lon);
    DBFWriteDoubleAttribute(dbase, ii, off+13, pairs->ns_lat);
    DBFWriteDoubleAttribute(dbase, ii, off+14, pairs->ns_lon);
    DBFWriteDoubleAttribute(dbase, ii, off+15, pairs->fs_lat);
    DBFWriteDoubleAttribute(dbase, ii, off+16, pairs->fs_lon);
    DBFWriteDoubleAttribute(dbase, ii, off+17, pairs->ne_lat);
    DBFWriteDoubleAttribute(dbase, ii, off+18, pairs->ne_lon);
    DBFWriteDoubleAttribute(dbase, ii, off+19, pairs->fe_lat);
    DBFWriteDoubleAttribute(dbase, ii, off+20, pairs->fe_lon);

    // Write shape object
    SHPObject *shapeObject=NULL;
    shapeObject = SHPCreateSimpleObject(SHPT_POLYGON, vertices+1,
                                        lon, lat, NULL);
    if (shapeObject == NULL)
        asfPrintError("Could not create shape object (%d)\n", ii);
    SHPWriteObject(shape, -1, shapeObject);
    SHPDestroyObject(shapeObject);

    FREE(lat);
    FREE(lon);
}
예제 #13
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);
}