Example #1
0
/**
 * Basic tests of ndn_btree_io_from_directory() and its methods.
 *
 * Assumes TEST_DIRECTORY has been set.
 */
static int
test_btree_io(void)
{
    int res;
    struct ndn_btree_node nodespace = {0};
    struct ndn_btree_node *node = &nodespace;
    struct ndn_btree_io *io = NULL;

    /* Open it up. */
    io = ndn_btree_io_from_directory(getenv("TEST_DIRECTORY"), NULL);
    CHKPTR(io);
    node->buf = ndn_charbuf_create();
    CHKPTR(node->buf);
    node->nodeid = 12345;
    res = io->btopen(io, node);
    CHKSYS(res);
    FAILIF(node->iodata == NULL);
    ndn_charbuf_putf(node->buf, "smoke");
    res = io->btwrite(io, node);
    CHKSYS(res);
    node->buf->length = 0;
    ndn_charbuf_putf(node->buf, "garbage");
    res = io->btread(io, node, 500000);
    CHKSYS(res);
    FAILIF(node->buf->length != 5);
    FAILIF(node->buf->limit > 10000);
    node->clean = 5;
    ndn_charbuf_putf(node->buf, "r");
    res = io->btwrite(io, node);
    CHKSYS(res);
    node->buf->length--;
    ndn_charbuf_putf(node->buf, "d");
    res = io->btread(io, node, 1000);
    CHKSYS(res);
    FAILIF(0 != strcmp("smoker", ndn_charbuf_as_string(node->buf)));
    node->buf->length--;
    res = io->btwrite(io, node);
    CHKSYS(res);
    node->buf->length = 0;
    ndn_charbuf_putf(node->buf, "garbage");
    node->clean = 0;
    res = io->btread(io, node, 1000);
    CHKSYS(res);
    res = io->btclose(io, node);
    CHKSYS(res);
    FAILIF(node->iodata != NULL);
    FAILIF(0 != strcmp("smoke", ndn_charbuf_as_string(node->buf)));
    res = io->btdestroy(&io);
    CHKSYS(res);
    ndn_charbuf_destroy(&node->buf);
    return(res);
}
Example #2
0
/**
 * Use standard mkdtemp() to create a subdirectory of the
 * current working directory, and set the TEST_DIRECTORY environment
 * variable with its name.
 */
static int
test_directory_creation(void)
{
    int res;
    struct ndn_charbuf *dirbuf;
    char *temp;
    
    dirbuf = ndn_charbuf_create();
    CHKPTR(dirbuf);
    res = ndn_charbuf_putf(dirbuf, "./%s", "_bt_XXXXXX");
    CHKSYS(res);
    temp = mkdtemp(ndn_charbuf_as_string(dirbuf));
    CHKPTR(temp);
    res = ndn_charbuf_putf(dirbuf, "/%s", "_test");
    CHKSYS(res);
    res = mkdir(ndn_charbuf_as_string(dirbuf), 0777);
    CHKSYS(res);
    printf("Created directory %s\n", ndn_charbuf_as_string(dirbuf));
    setenv("TEST_DIRECTORY", ndn_charbuf_as_string(dirbuf), 1);
    ndn_charbuf_destroy(&dirbuf);
    return(res);
}
Example #3
0
/**
   @brief Print content of code table
   @param tbl Code table
 */
void 
print_code_tbl(const struct hf_code *const tbl)
{
  int i;

  CHKPTR(tbl);
  
  puts("=== TABLE OF ASSIGNED HUFFMAN CODES ===");

  for (i = 0; i < MAX_CODE_TBL_SIZE; ++i)
      print_code(i, tbl[i]);

  puts("=======================================");
}
Example #4
0
/**
 *  Get a handle on the content object that matches key, or if there is
 * no match, the one that would come just after it.
 *
 * The key is in flatname format.
 */
static struct content_entry *    
r_store_look(struct ccnr_handle *h, const unsigned char *key, size_t size)
{
    struct content_entry *content = NULL;
    struct ccn_btree_node *leaf = NULL;
    ccnr_accession accession;
    int ndx;
    int res;

    res = ccn_btree_lookup(h->btree, key, size, &leaf);
    if (res >= 0) {
        ndx = CCN_BT_SRCH_INDEX(res);
        if (ndx == ccn_btree_node_nent(leaf)) {
            res = ccn_btree_next_leaf(h->btree, leaf, &leaf);
            if (res <= 0)
                return(NULL);
            ndx = 0;
        }
        accession = ccnr_accession_decode(h, ccn_btree_content_cobid(leaf, ndx));
        if (accession != CCNR_NULL_ACCESSION) {
            struct content_by_accession_entry *entry;
            entry = hashtb_lookup(h->content_by_accession_tab,
                                    &accession, sizeof(accession));
            if (entry != NULL)
                content = entry->content;
            if (content == NULL) {
                /* Construct handle without actually reading the cob */
                res = ccn_btree_content_cobsz(leaf, ndx);
                content = calloc(1, sizeof(*content));
                if (res > 0 && content != NULL) {
                    content->accession = accession;
                    content->cob = NULL;
                    content->size = res;
                    content->flatname = ccn_charbuf_create();
                    CHKPTR(content->flatname);
                    res = ccn_btree_key_fetch(content->flatname, leaf, ndx);
                    CHKRES(res);
                    r_store_enroll_content(h, content);
                }
            }
        }
    }
    return(content);
}
Example #5
0
/**
 * Test that the lockfile works.
 */
int
test_btree_lockfile(void)
{
    int res;
    struct ndn_btree_io *io = NULL;
    struct ndn_btree_io *io2 = NULL;

    io = ndn_btree_io_from_directory(getenv("TEST_DIRECTORY"), NULL);
    CHKPTR(io);
    /* Make sure the locking works */
    errno = 0;
    io2 = ndn_btree_io_from_directory(getenv("TEST_DIRECTORY"), NULL);
    FAILIF(io2 != NULL || errno == 0);
    errno=EINVAL;
    res = io->btdestroy(&io);
    CHKSYS(res);
    FAILIF(io != NULL);
    return(res);
}
Example #6
0
PUBLIC struct content_entry *
r_store_content_from_accession(struct ccnr_handle *h, ccnr_accession accession)
{
    struct ccn_parsed_ContentObject obj = {0};
    struct content_entry *content = NULL;
    struct content_by_accession_entry *entry;
    const unsigned char *content_base = NULL;
    int res;
    ccnr_accession acc;
    
    if (accession == CCNR_NULL_ACCESSION)
        return(NULL);
    entry = hashtb_lookup(h->content_by_accession_tab,
                          &accession, sizeof(accession));
    if (entry != NULL) {
        h->content_from_accession_hits++;
        return(entry->content);
    }
    h->content_from_accession_misses++;
    content = calloc(1, sizeof(*content));
    CHKPTR(content);
    content->cookie = 0;
    content->accession = accession;
    content->cob = NULL;
    content->size = 0;
    content_base = r_store_content_base(h, content);
    if (content_base == NULL || content->size == 0)
        goto Bail;
    res = r_store_set_flatname(h, content, &obj);
    if (res < 0) goto Bail;
    r_store_enroll_content(h, content);
    res = r_store_content_btree_insert(h, content, &obj, &acc);
    if (res < 0) goto Bail;
    if (res == 1 || CCNSHOULDLOG(h, sdf, CCNL_FINEST))
        ccnr_debug_content(h, __LINE__, "content/accession", NULL, content);
    return(content);
Bail:
    ccnr_msg(h, "r_store_content_from_accession.%d failed 0x%jx",
             __LINE__, ccnr_accession_encode(h, accession));
    r_store_forget_content(h, &content);
    return(content);
}
Example #7
0
   void ucase_c ( SpiceChar   * in,
                  SpiceInt      lenout, 
                  SpiceChar   * out    ) 

/*

-Brief_I/O
 
    VARIABLE  I/O  DESCRIPTION 
    --------  ---  -------------------------------------------------- 
    in         I   Input string. 
    lenout     I   Maximum length of output string.
    out        O   Output string, all uppercase. 
 
-Detailed_Input
 
    in          is the input string. 
    
    lenout      is the maximum allowed length of the output string, 
                including the terminating null.
 
-Detailed_Output
 
    out         is the output string. This is the input string 
                with all lowercase letters converted to uppercase. 
                Non-letters are not affected. 
                
                If 
                  
                   lenout < strlen(in)+1
                   
                the output string will be truncated on the right.

                A terminating null will be placed in out at position
                
                   min ( strlen(in),  lenout-1 )
                   
                unless lenout is less than or equal to zero.
                
 
                out may overwrite in. 
 
-Parameters
 
   None. 
 
-Particulars
 
    Convert each lowercase character in IN to uppercase. 
 
-Examples
 
    "This is an example"   becomes   "THIS IS AN EXAMPLE" 
    "12345 +-=? > * $ &"             "12345 +-=? > * $ &" 
 
-Restrictions
 
    None. 
 
-Exceptions
 
 
    1) If the input string pointer is null, the error 
       SPICE(NULLPOINTER) will be signaled.
       
    2) If the output string pointer is null, the error 
       SPICE(NULLPOINTER) will be signaled.
       
    3) If lenout is less than or equal to zero, the error 
       SPICE(STRINGTOOSHORT) will be signaled.      
 
    4) If the output string is shorter than the input string, the
       result will be truncated on the right.
       
-Files
 
    None. 
 
-Author_and_Institution
 
    N.J. Bachman    (JPL)
    K.R. Gehringer  (JPL) 
    I.M. Underwood  (JPL) 
 
-Literature_References
 
    None. 
 
-Version
 
   -CSPICE Version 1.1.0, 26-JAN-2005 (NJB)

       Cast to SpiceInt was applied to strlen output to suppress
       compiler warnings about comparison of signed and unsigned types.

   -CSPICE Version 2.0.0, 26-AUG-1999 (NJB)
   
      Added string error checks.

   -CSPICE Version 1.0.0, 08-FEB-1998 (NJB)

      Based on SPICELIB Version 1.1.0, 13-MAR-1996 (KRG)
      
      
-Index_Entries
 
   convert to uppercase 
 
-&
*/

{ /* Begin ucase_c */


   /*
   Local macros
   */
   #define  LOWA     (  (SpiceInt) ('a')          )
   #define  LOWZ     (  (SpiceInt) ('z')          )
   #define  SHIFT    (  (SpiceInt) ('A')  - LOWA  )


   /*
   Local variables
   */
   SpiceInt                i;
   SpiceInt                ich;
   SpiceInt                nmove;



   
   /*
   Check the input string pointer to make sure it's non-null.
   */
   CHKPTR( CHK_DISCOVER, "ucase_c", in );
   

   /*
   Make sure the output string has at least enough room for one output
   character and a null terminator.  Also check for a null pointer.
   */
   CHKOSTR ( CHK_DISCOVER, "ucase_c", out, lenout );
   
   
   /*
   Move the string from in to out. Step through in one character
   at a time, translating letters between 'a' and 'z' to uppercase.
   
   First, determine how many characters to move.
   */
   
   nmove = MinVal ( (SpiceInt)strlen(in), lenout-1 );
   
   
   for ( i = 0;  i < nmove;  i++ )
   {
      ich = (SpiceInt) in[i];

      if ( ( ich >= LOWA ) && ( ich <= LOWZ ) ) 
      {
         out[i] = (char) ( ich + SHIFT );
      }
      else
      {
         out[i] = in[i];
      }
   }
 
 
   /*
   Terminate the output string with a null. We know it has room for at 
   least one character.
   */
   out[nmove] = NULLCHAR;


} /* End ucase_c */
Example #8
0
void main( int argc, char* argv[] )
{
	u_int32_t	i, i2, arrcount;
	int	x, y, xs, ys, xh, yh;
	char	dumpheaders = 0;
	char*	tganame;
	char*   arrname;
	char*	palname;
	char*	arrident;
	char*	arrnext;
	char*	arrmode;

	int	reducemode;

	int		mm;
	int		ts, td;
	int		pixels;
	int		rsum, gsum, bsum;
	int		x2, y2;

	int		blur;

	FILE*	tgahandle;
	FILE*	arrhandle;
	FILE*	palhandle;
	pal_t*	pal = NULL;	
	tga_t*	tga[2];
	arr_t*	arr;
	rgb_t	rgb;
	
	dumpheaders = CheckCmdSwitch( "-d", argc, argv );

	palname = GetCmdOpt( "-p", argc, argv );

	tganame = GetCmdOpt( "-t", argc, argv );
	if( tganame == NULL )
	{
		printf( "no tga given.\n" );
		PrintUsage();
		exit( 0 );
	}


	if ( CheckCmdSwitch( "--rgb565", argc, argv ) )
	{
		reducemode = ARR_F_RGB565;
	}
	else
	{
		reducemode = ARR_F_P8;
	}

	arrident = GetCmdOpt( "-i", argc, argv );
	if( arrident == NULL )
		__warning( "no arr ident given.\n" );
	else if( strlen( arrident ) >= 32 )
		arrident[31] = '\0';

	printf( "tga: %s\n", tganame );
	tgahandle = fopen( tganame, "rb" );
	CHKPTR( tgahandle );
	tga[0] = TGA_Read( tgahandle );
       	CHKPTR( tga[0] );
//	TGA_Dump( tga[0] );

	fclose( tgahandle );
	if( dumpheaders )
		TGA_Dump( tga[0] );

	tga[1] = TGA_Create( tga[0]->image_width/*/2*/, tga[0]->image_height/*/2*/, TGA_TYPE_TRUECOLOR );
	__chkptr( tga[1] );
	
	arrname = GetCmdOpt( "-a", argc, argv );
	if( arrname == NULL )
	{
		printf( "no arr given.\n" );
		PrintUsage();
		exit( 0 );
	}
	printf( "arr: %s\n", arrname );
	
	switch( tga[0]->image_type )
	{
	case TGA_TYPE_TRUECOLOR:
		
		printf( "tga is 24bit.\n" );
		if( palname == NULL )
		{
			CDB_StartUp( 0 );
			palname = CDB_GetString( "misc/default_pal" );
			if( palname == NULL )
			{
				PrintUsage();
				__error( "no pal found.\n" );
			}
		}
		printf( "pal: %s\n", palname );
		palhandle = fopen( palname, "rb" );
		CHKPTR( palhandle );
		pal = PAL_Read( palhandle );
		CHKPTR( pal );
		fclose( palhandle );

		arr = ARR_Create( tga[0]->image_width, tga[0]->image_height, 4, 1, arrident, reducemode );

		CHKPTR( arr );
		printf( "reducing color. " );

		xs = tga[0]->image_width;
		ys = tga[0]->image_height;
		arrcount = 0;

		for ( mm = 0; mm < 4; mm++ ) {
			ts = mm & 1;
			td = (mm+1) & 1;
//			printf("%d->%d\n",ts,td);
			// reduce
//			printf(" i: %d, x: %d, y: %d\n", mm, xs, ys );
			pixels = xs * ys;
			for( i = 0; i < pixels; i++ )
			{
				rgb.red = tga[ts]->image.red[i];
				rgb.green = tga[ts]->image.green[i];
				rgb.blue = tga[ts]->image.blue[i];
				
				if ( reducemode == ARR_F_P8 )
					arr->data[arrcount++] = PAL_ReduceColor( pal, &rgb );
				else
				{
					*((unsigned short*)(&arr->data[arrcount])) = RGB888ToRGB565( &rgb );
					arrcount+=2;
				}

				if( (i & 0xff) == 0 )
				{
					printf( "." );
					fflush( stdout );
				}
			}			

			if ( mm == 3 )
				break;
			
			// mipmap 
			xh = xs / 2;
			yh = ys / 2;

			if ( xh < 4 || yh < 4 )
				blur = 0;
			else
				blur = 1;

			for ( y = 0; y < yh; y++ ) {
				for ( x = 0; x < xh; x++ ) {
					x2 = x*2;
					y2 = y*2;

					if ( blur )
					{
						rsum = tga[ts]->image.red[ y2*xs + x2 ];
						gsum = tga[ts]->image.green[ y2*xs + x2 ];
						bsum = tga[ts]->image.blue[ y2*xs + x2 ];
						
						rsum += tga[ts]->image.red[ y2*xs + (x2+1) ];
						gsum += tga[ts]->image.green[ y2*xs + (x2+1) ];
						bsum += tga[ts]->image.blue[ y2*xs + (x2+1) ];
						
						rsum += tga[ts]->image.red[ (y2+1)*xs + x2 ];
						gsum += tga[ts]->image.green[ (y2+1)*xs + x2 ];
						bsum += tga[ts]->image.blue[ (y2+1)*xs + x2 ];
						
						rsum += tga[ts]->image.red[ (y2+1)*xs + (x2+1) ];
						gsum += tga[ts]->image.green[ (y2+1)*xs + (x2+1) ];
						bsum += tga[ts]->image.blue[ (y2+1)*xs + (x2+1) ];
						
						tga[td]->image.red[ y*xh + x ] = rsum / 4;
						tga[td]->image.green[ y*xh + x ] = gsum / 4;
						tga[td]->image.blue[ y*xh + x ] = bsum / 4;
					}
					else
					{

						rsum = tga[ts]->image.red[ y2*xs + x2 ];
						gsum = tga[ts]->image.green[ y2*xs + x2 ];
						bsum = tga[ts]->image.blue[ y2*xs + x2 ];				
						tga[td]->image.red[ y*xh + x ] = 255; //rsum;
						tga[td]->image.green[ y*xh + x ] = 0;//gsum;
						tga[td]->image.blue[ y*xh + x ] = 0; //bsum;		
					}
				}
			}
			xs = xh;
			ys = yh;
		}
		

		printf( "\n" );
		
		break;
		/*
	case TGA_TYPE_INDEXED:
		printf( "tga is indexed./n" );
		arr = ARR_Create( tga->image_width, tga->image_height, 1, arr_ident, NULL );
		CHKPTR( arr );
		printf( "copying ...\n" );
		memcpy( arr->data, tga->image_indexed.data, tga->image_indexed.bytes );
		break;
		*/
	default:
		__error( "we need an uncompressed 24(/8)bit tga.\n" );
		ARR_Free( arr );
		break;
	}
	arrhandle = fopen( arrname, "wb" );
	CHKPTR( arrhandle );
	ARR_Write( arrhandle, arr );
	fclose( arrhandle );
}
Example #9
0
   void lxqstr_c ( ConstSpiceChar    * string,
                   SpiceChar           qchar,
                   SpiceInt            first,
                   SpiceInt          * last,
                   SpiceInt          * nchar  ) 
/*

-Brief_I/O
 
   Variable  I/O  Description 
   --------  ---  -------------------------------------------------- 
   string     I   String to be scanned. 
   qchar      I   Quote delimiter character. 
   first      I   Character position at which to start scanning. 
   last       O   Character position of end of token. 
   nchar      O   Number of characters in token. 
 
-Detailed_Input
 
   string         is a character string that may contain a "string 
                  token" starting at the character position 
                  indicated by the input argument first (see below). 
                  String tokens are sequences of characters that 
                  represent literal strings.  Syntactically, a string 
                  token is a sequence of characters that begins and 
                  ends with a designated "quote character".  Within 
                  the token, any occurrence of the quote character 
                  is indicated by an adjacent pair of quote 
                  characters:  for example, if the quote character is 
 
                     " 
 
                  then the token representing one instance of this 
                  character is 
 
                     """" 
 
                  Here the first quote indicates the beginning of the 
                  token, the next two quotes together indicate a 
                  single quote character that constitutes the 
                  "contents" of the token, and the final quote 
                  indicates the end of the token. 
 
   qchar          is the quote character.  This is always a single 
                  character.  The characters 
 
                     "  and ' 
 
                  are common choices, but any non-blank character is 
                  accepted.  Case *is* significant in qchar. 
 
 
   first          is the character position at which the routine 
                  is to start scanning a quoted string token.  Note 
                  that the character string[first] must equal 
                  qchar if a string token is to be found; this 
                  routine does *not* attempt to locate the first 
                  quoted string following the position first. 
 
-Detailed_Output
 
   last           is the last character position such that the subtring
                  ranging from string[first] to string[last] is a
                  quoted string token, if such a substring exists.
                  Otherwise, the returned value of last is first-1.
 
   nchar          is the length of the string token found by this 
                  routine, if such a token exists.  This length 
                  includes the starting and ending bracketing quotes. 
                  If a string token is not found, the returned value 
                  of nchar is zero. 
 
-Parameters
 
   None. 
 
-Exceptions

   1) If the input argument first is less than 1 or greater than 
      len(string)-1, the returned value of last is first-1, and the 
      returned value of nchar is zero. 
 
   2) It is not an error for a quoted string token to consist of 
      two consecutive quote characters with no intervening 
      characters.  Calling routines that require special treatment 
      of null tokens must handle this case. 
 
   3) If the input argument qchar is blank, the returned value of 
      last is first-1, and the returned value of nchar is zero. 

   4) If the input string pointer is null, the error SPICE(NULLPOINTER)
      will be signaled.

   5) If the input string has length zero, last will be set to first-1
      and nchar will be set to zero.  This case is not considered an
      error.

-Files
 
   None. 
 
-Particulars
 
   Quote characters may be ANY non-blank character.  For example, the 
   ampersand 
 
      & 
 
   is a perfectly valid quote character.  If we were using the 
   ampersand as the quote character, then the term "doubled quote" 
   in the following discussion would refer to the sequence 
 
      && 
 
   not the character 
 
      " 
 
   The string tokens identified by this routine are Fortran-style 
   quoted strings:  they start and end with quote characters.  In the 
   interior of any such token, any quote characters are represented 
   by doubled quote characters.  These rules imply that the number of 
   quote characters in a quoted string token is always even.  The end 
   of a quoted string token is located at the first even-numbered 
   quote character, counting from the initial quote character, that 
   is  not the first member of a pair of quotes indicating an 
   embedded quote character. 
 
   To map the token to the string of characters it represents, use 
   the CSPICE subroutine parsqs_c (String parse, quoted).  parsqs_c 
   removes the bracketing quotes from a quoted string token and 
   converts each doubled quote between the bracketing quotes to a 
   single quote.  For example, the token 
 
      """" 
 
   identified by this routine would be mapped by parsqs_c to a string 
   variable containing the single character 
 
      " 
 
-Examples
 
   1)  The table below illustrates the action of this routine. 
 
 
       STRING CONTENTS               qchar   first   last   nchar 
       ========================================================== 
       The "SPICE" system            "       4       10      7 
       The "SPICE" system            "       0       -1      0 
       The "SPICE" system            '       4        3      0 
       The """SPICE"" system"        "       4       12      9 
       The """SPICE"""" system       "       4       14     11 
       The &&&SPICE system           &       4        5      2 
       ' '                           '       0        2      3 
       ''                            '       0        1      2 
       ==========================================================      
       01234567890123456789012
 
-Restrictions
 
   None. 
 
-Literature_References
 
   None. 
 
-Author_and_Institution
 
   N.J. Bachman       (JPL) 
 
-Version
 
   -CSPICE Version 1.0.0, 19-AUG-2002 (NJB)

-Index_Entries
 
   scan quoted string token 
   lex quoted string token 
   recognize quoted string token 
 
-&
*/

{ /* Begin lxqstr_c */

   /*
   Local variables 
   */
   SpiceInt                locFirst;
   SpiceInt                len;


   /*
   Use discovery check-in.

   Check the input string argument for a null pointer.
   */
   CHKPTR ( CHK_DISCOVER, "lxqstr_c", string );


   /*
   We're done if the input string has zero length. 
   */
   len = strlen(string);

   if ( len == 0 )
   {
      *last  = first - 1;
      *nchar = 0;

      return;
   }


   /*
   Map first to a Fortran-style index. 
   */
   locFirst = first + 1;


   /*
   Call the f2c'd routine. 
   */
   lxqstr_ ( ( char    * ) string,
             ( char    * ) &qchar,
             ( integer * ) &locFirst,
             ( integer * ) last,
             ( integer * ) nchar,
             ( ftnlen    ) len,
             ( ftnlen    ) 1         );

   /*
   Map last to a C-style index. 
   */

   (*last)--;


} /* End lxqstr_c */
Example #10
0
   void insrtc_c ( ConstSpiceChar  * item,
                   SpiceCell       * set   )

/*

-Brief_I/O
 
   VARIABLE  I/O  DESCRIPTION 
   --------  ---  -------------------------------------------------- 
   item       I   Item to be inserted. 
   set       I/O  Insertion set. 
 
-Detailed_Input
 
   item        is an item which is to be inserted into the specified
               set. item may or may not already be an element of the
               set.  Trailing blanks in item are not significant.


   set         is a CSPICE set.  set must be declared as a character
               SpiceCell. 

               On input, set  may or may not contain the input item 
               as an element. 
 
-Detailed_Output

   set         on output contains the union of the input set and 
               the singleton set containing the input item.
 
-Parameters
 
   None. 
 
-Exceptions
 
   1) If the input set argument is a SpiceCell of type other than
      character, the error SPICE(TYPEMISMATCH) is signaled.

   2) If the insertion of the element into the set causes an excess 
      of elements, the error SPICE(SETEXCESS) is signaled. 
 
   3) If the input set argument does not qualify as a CSPICE set, 
      the error SPICE(NOTASET) will be signaled.  CSPICE sets have
      their data elements sorted in increasing order and contain
      no duplicate data elements.

   4) If the input string pointer is null, the error SPICE(NULLPOINTER)
      is signaled.

-Files
 
   None. 
 
-Particulars
 
   None. 
 
-Examples
 
   1) In the following example, the element "PLUTO" is removed from 
      the character set planets and inserted into the character set 
      asteroids. 

         #include "SpiceUsr.h"
                .
                .
                .
         /.
         Declare the sets with string length NAMLEN and with maximum
         number of elements MAXSIZ.
         ./
         SPICECHAR_CELL ( planets,   MAXSIZ, NAMLEN );
         SPICECHAR_CELL ( asteroids, MAXSIZ, NAMLEN );
                .
                .
                .
         removc_c ( "PLUTO", &planets   );
         insrtc_c ( "PLUTO", &asteroids ); 


      If "PLUTO" is not an element of planets, then the contents of 
      planets are not changed. Similarly, if "PLUTO" is already an 
      element of asteroids, the contents of asteroids remain unchanged. 

      Because inserting an element into a set can increase the 
      cardinality of the set, an error may occur in the insertion 
      routines. 
 
-Restrictions
 
   1)  String comparisons performed by this routine are Fortran-style:
       trailing blanks in the input set or key value are ignored.
       This gives consistent behavior with CSPICE code generated by
       the f2c translator, as well as with the Fortran SPICE Toolkit.
      
       Note that this behavior is not identical to that of the ANSI
       C library functions strcmp and strncmp.

-Literature_References
 
   None. 
 
-Author_and_Institution
 
   N.J. Bachman    (JPL) 
   C.A. Curzon     (JPL) 
   W.L. Taber      (JPL) 
   I.M. Underwood  (JPL) 
 
-Version
 
   -CSPICE Version 2.1.0, 07-MAR-2009 (NJB)

       This file now includes the header file f2cMang.h.
       This header supports name mangling of f2c library
       functions.

   -CSPICE Version 2.0.0, 01-NOV-2005 (NJB)
         
       Bug fix:  when the item to be inserted would, after
       truncation to the set's string length, match an item
       already in the set, no insertion is performed.  Previously
       the truncated string was inserted, corrupting the set.

       Long error message was updated to include size of
       set into which insertion was attempted.
         
   -CSPICE Version 1.0.0, 21-AUG-2002 (NJB) (CAC) (WLT) (IMU)

-Index_Entries
 
   insert an item into a character set 
 
-&
*/
{
   /*
   f2c library utility prototypes 
   */
   extern integer   s_cmp  (char *a, char *b, ftnlen la, ftnlen lb ); 


   /*
   Local macros 
   */
   #define ARRAY( i )    (  (SpiceChar *)(set->data) + (i)*(set->length)  )


   /*
   local variables
   */
   SpiceBoolean            inSet;

   SpiceChar             * cdata;

   SpiceInt                i;
   SpiceInt                loc;
   SpiceInt                slen;



   /*
   Use discovery check-in. 

   Check the input string pointer to make sure it's not null.
   */
   CHKPTR ( CHK_DISCOVER, "insrtc_c", item );


   /*
   Make sure we're working with a character cell. 
   */
   CELLTYPECHK ( CHK_DISCOVER, "insrtc_c", SPICE_CHR, set );


   /*
   Make sure the input cell is a set.
   */
   CELLISSETCHK ( CHK_DISCOVER, "insrtc_c", set );


   /*
   Initialize the set if it's not already initialized.
   */
   CELLINIT ( set );


   /*
   Let slen be the effective string length of the input item.
   Characters beyond the string length of the set are ignored.
   */
   slen = mini_c ( 2, set->length, strlen(item) );


   /*
   Is the item already in the set? If not, it needs to be inserted.
   */
   cdata =  (SpiceChar *) (set->data);

   /*
   The following call will give the location of the last element
   less than or equal to the item to be inserted.  If the item
   differs from an element of the set only in characters that would
   be truncated, no insertion will occur.  Even in this case, the
   insertion point `loc' returned by lstlec_c will be correct.
   */
   loc   =  lstlec_c ( item,  set->card,  set->length,  cdata );

   inSet =     (  loc  >  -1  ) 

            && (  s_cmp( (SpiceChar *)item,  ARRAY(loc), 
                          slen,              strlen(ARRAY(loc)) ) == 0  );
 
   if ( inSet )
   {
      return;
   }

   
   /*
   It's an error if the set has no room left. 
   */
   if ( set->card == set->size )
   {
      chkin_c  ( "insrtc_c"                                       );
      setmsg_c ( "An element could not be inserted into the set "
                 "due to lack of space; set size is #."           );
      errint_c ( "#", set->size                                   );
      sigerr_c ( "SPICE(SETEXCESS)"                               );
      chkout_c ( "insrtc_c"                                       );
      return;
   }


   /*
   Make room by moving the items that come after index loc in the set. 
   Insert the item after index loc.
   */
   for (  i = (set->card);   i > (loc+1);   i--  )
   {
      SPICE_CELL_SET_C( ARRAY(i-1), i, set );
   }

   /*
   This insertion macro will truncate the item to be inserted, if 
   necessary.  The input item will be null-terminated.
   */
   SPICE_CELL_SET_C( item, loc+1, set );


   /*
   Increment the set's cardinality.
   */
   (set->card) ++;

}
Example #11
0
   void gfoclt_c ( ConstSpiceChar   * occtyp,
                   ConstSpiceChar   * front,
                   ConstSpiceChar   * fshape,
                   ConstSpiceChar   * fframe,
                   ConstSpiceChar   * back,
                   ConstSpiceChar   * bshape,
                   ConstSpiceChar   * bframe,
                   ConstSpiceChar   * abcorr,
                   ConstSpiceChar   * obsrvr,
                   SpiceDouble        step,
                   SpiceCell        * cnfine,
                   SpiceCell        * result )
/*

-Brief_I/O
 
   VARIABLE        I/O  DESCRIPTION 
   --------------- ---  -------------------------------------------------
   SPICE_GF_CNVTOL  P   Convergence tolerance. 
   occtyp           I   Type of occultation. 
   front            I   Name of body occulting the other. 
   fshape           I   Type of shape model used for front body. 
   fframe           I   Body-fixed, body-centered frame for front body. 
   back             I   Name of body occulted by the other. 
   bshape           I   Type of shape model used for back body. 
   bframe           I   Body-fixed, body-centered frame for back body. 
   abcorr           I   Aberration correction flag. 
   obsrvr           I   Name of the observing body. 
   step             I   Step size in seconds for finding occultation  
                        events. 
   cnfine          I-O  SPICE window to which the search is restricted. 
   result           O   SPICE window containing results. 
    
-Detailed_Input
 
 
   occtyp     indicates the type of occultation that is to be found. 
              Note that transits are considered to be a type of
              occultation.

              Supported values and corresponding definitions are: 
 
                 "FULL"               denotes the full occultation 
                                      of the body designated by  
                                      `back' by the body designated 
                                      by `front', as seen from 
                                      the location of the observer. 
                                      In other words, the occulted 
                                      body is completely invisible 
                                      as seen from the observer's 
                                      location. 
 
                 "ANNULAR"            denotes an annular 
                                      occultation: the body 
                                      designated by `front' blocks 
                                      part of, but not the limb of, 
                                      the body designated by `back', 
                                      as seen from the location of 
                                      the observer. 
 
                 "PARTIAL"            denotes a partial, non-annular
                                      occultation: the body designated
                                      by `front' blocks part, but not
                                      all, of the limb of the body
                                      designated by `back', as seen
                                      from the location of the
                                      observer.
 
                 "ANY"                denotes any of the above three 
                                      types of occultations: 
                                      "PARTIAL", "ANNULAR", or 
                                      "FULL". 
 
                                      "ANY" should be used to search 
                                      for times when the body  
                                      designated by `front' blocks 
                                      any part of the body designated 
                                      by `back'. 
 
                                      The option "ANY" must be used 
                                      if either the front or back 
                                      target body is modeled as 
                                      a point. 
 
              Case and leading or trailing blanks are not 
              significant in the string `occtyp'. 
 
 
   front      is the name of the target body that occults---that is, 
              passes in front of---the other. Optionally, you may 
              supply the integer NAIF ID code for the body as a 
              string. For example both "MOON" and "301" are 
              legitimate strings that designate the Moon. 
 
              Case and leading or trailing blanks are not 
              significant in the string `front'. 
 
 
   fshape     is a string indicating the geometric model used to
              represent the shape of the front target body. The
              supported options are:
 
                 "ELLIPSOID"     Use a triaxial ellipsoid model
                                 with radius values provided via the 
                                 kernel pool. A kernel variable  
                                 having a name of the form 
 
                                    "BODYnnn_RADII"  
 
                                 where nnn represents the NAIF 
                                 integer code associated with the 
                                 body, must be present in the kernel 
                                 pool. This variable must be 
                                 associated with three numeric 
                                 values giving the lengths of the 
                                 ellipsoid's X, Y, and Z semi-axes. 
 
                 "POINT"         Treat the body as a single point. 
                                 When a point target is specified, 
                                 the occultation type must be 
                                 set to "ANY". 
                                  
              At least one of the target bodies `front' and `back' must 
              be modeled as an ellipsoid. 
 
              Case and leading or trailing blanks are not 
              significant in the string `fshape'. 
 
 
   fframe     is the name of the body-fixed, body-centered reference 
              frame associated with the front target body. Examples 
              of such names are "IAU_SATURN" (for Saturn) and 
              "ITRF93" (for the Earth). 
 
              If the front target body is modeled as a point, `fframe' 
              should be left empty or blank. 
 
              Case and leading or trailing blanks bracketing a
              non-blank frame name are not significant in the string
              `fframe'.

 
   back       is the name of the target body that is occulted 
              by---that is, passes in back of---the other. 
              Optionally, you may supply the integer NAIF ID code 
              for the body as a string. For example both "MOON" and 
              "301" are legitimate strings that designate the Moon. 
 
              Case and leading or trailing blanks are not 
              significant in the string `back'. 
 
 
   bshape     is the shape specification for the body designated by
              `back'. The supported options are those for `fshape'. See
              the description of `fshape' above for details.
               
 
   bframe     is the name of the body-fixed, body-centered reference 
              frame associated with the ``back'' target body. 
              Examples of such names are "IAU_SATURN" (for Saturn) 
              and "ITRF93" (for the Earth). 
 
              If the back target body is modeled as a point, `bframe' 
              should be left empty or blank. 
 
              Case and leading or trailing blanks bracketing a 
              non-blank frame name are not significant in the string 
              `bframe'. 
 
 
   abcorr     indicates the aberration corrections to be applied to 
              the state of each target body to account for one-way 
              light time.  Stellar aberration corrections are 
              ignored if specified, since these corrections don't 
              improve the accuracy of the occultation determination. 
 
              See the header of the SPICE routine spkezr_c for a 
              detailed description of the aberration correction 
              options. For convenience, the options supported by 
              this routine are listed below: 
 
                 "NONE"     Apply no correction.    
 
                 "LT"       "Reception" case:  correct for 
                            one-way light time using a Newtonian 
                            formulation. 
 
                 "CN"       "Reception" case:  converged 
                            Newtonian light time correction. 
 
                 "XLT"      "Transmission" case:  correct for 
                            one-way light time using a Newtonian 
                            formulation. 
 
                 "XCN"      "Transmission" case:  converged 
                            Newtonian light time correction. 
 
              Case and blanks are not significant in the string 
              `abcorr'. 
 
 
   obsrvr     is the name of the body from which the occultation is 
              observed. Optionally, you may supply the integer NAIF 
              ID code for the body as a string. 
 
              Case and leading or trailing blanks are not 
              significant in the string `obsrvr'. 


   step       is the step size to be used in the search. `step' must 
              be shorter than any interval, within the confinement 
              window, over which the specified condition is met. In
              other words, `step' must be shorter than the shortest
              occultation event that the user wishes to detect; `step'
              must also be shorter than the shortest time interval
              between two occultation events that occur within the
              confinement window (see below). However, `step' must not
              be *too* short, or the search will take an unreasonable
              amount of time.
 
              The choice of `step' affects the completeness but not the
              precision of solutions found by this routine; the
              precision is controlled by the convergence tolerance. See
              the discussion of the parameter SPICE_GF_CNVTOL for
              details.
 
              `step' has units of TDB seconds.  
 
  
   cnfine     is a SPICE window that confines the time period over 
              which the specified search is conducted. `cnfine' may 
              consist of a single interval or a collection of  
              intervals.  
 
              The endpoints of the time intervals comprising `cnfine'
              are interpreted as seconds past J2000 TDB.
                
              See the Examples section below for a code example  
              that shows how to create a confinement window. 
 
 
-Detailed_Output
 
   cnfine     is the input confinement window, updated if necessary
              so the control area of its data array indicates the
              window's size and cardinality. The window data are
              unchanged.


   result     is a SPICE window representing the set of time 
              intervals, within the confinement period, when the 
              specified occultation occurs. 
 
              The endpoints of the time intervals comprising `result'
              are interpreted as seconds past J2000 TDB.

              If `result' is non-empty on input, its contents 
              will be discarded before gfoclt_c conducts its 
              search. 
 
-Parameters
  
   SPICE_GF_CNVTOL     

              is the convergence tolerance used for finding endpoints
              of the intervals comprising the result window.
              SPICE_GF_CNVTOL is used to determine when binary searches
              for roots should terminate: when a root is bracketed
              within an interval of length SPICE_GF_CNVTOL, the root is
              considered to have been found.
 
              The accuracy, as opposed to precision, of roots found 
              by this routine depends on the accuracy of the input 
              data. In most cases, the accuracy of solutions will be 
              inferior to their precision. 
 
              SPICE_GF_CNVTOL is declared in the header file
             
                 SpiceGF.h
 
-Exceptions
 
   1)  In order for this routine to produce correct results, 
       the step size must be appropriate for the problem at hand. 
       Step sizes that are too large may cause this routine to miss 
       roots; step sizes that are too small may cause this routine 
       to run unacceptably slowly and in some cases, find spurious 
       roots. 
 
       This routine does not diagnose invalid step sizes, except 
       that if the step size is non-positive, the error  
       SPICE(INVALIDSTEPSIZE) will be signaled. 
 
   2)  Due to numerical errors, in particular, 
 
          - Truncation error in time values 
          - Finite tolerance value 
          - Errors in computed geometric quantities 
 
       it is *normal* for the condition of interest to not always be 
       satisfied near the endpoints of the intervals comprising the 
       result window. 
 
       The result window may need to be contracted slightly by the 
       caller to achieve desired results. The SPICE window routine 
       wncond_c can be used to contract the result window. 
 
   3)  If name of either target or the observer cannot be translated 
       to a NAIF ID code, the error will be diagnosed by a routine 
       in the call tree of this routine. 
        
   4)  If the radii of a target body modeled as an ellipsoid cannot 
       be determined by searching the kernel pool for a kernel 
       variable having a name of the form 
 
          "BODYnnn_RADII"  
 
       where nnn represents the NAIF integer code associated with 
       the body, the error will be diagnosed by a routine in the 
       call tree of this routine. 
 
   5)  If either of the target bodies `front' or `back' coincides with 
       the observer body `obsrvr', the error will be diagnosed by a 
       routine in the call tree of this routine. 
 
   6)  If the body designated by `front' coincides with that 
       designated by `back', the error will be diagnosed by a routine 
       in the call tree of this routine. 
        
   7)  If either of the body model specifiers `fshape' or `bshape' 
       is not recognized, the error will be diagnosed by a routine 
       in the call tree of this routine. 
 
   8)  If both of the body model specifiers `fshape' and `bshape' 
       specify point targets, the error will be diagnosed by a 
       routine in the call tree of this routine. 
 
   9)  If a target body-fixed reference frame associated with a  
       non-point target is not recognized, the error will be 
       diagnosed by a routine in the call tree of this routine. 
 
   10) If a target body-fixed reference frame is not centered at 
       the corresponding target body,  the error will be 
       diagnosed by a routine in the call tree of this routine. 
 
   11) If the loaded kernels provide insufficient data to  
       compute any required state vector, the deficiency will 
       be diagnosed by a routine in the call tree of this routine. 
 
   12) If an error occurs while reading an SPK or other kernel file, 
       the error will be diagnosed by a routine in the call tree  
       of this routine. 
 
   13) If the output SPICE window `result' has insufficient capacity 
       to contain the number of intervals on which the specified 
       occultation condition is met, the error will be diagnosed 
       by a routine in the call tree of this routine. 
 
   14) If a point target is specified and the occultation 
       type is set to a valid value other than "ANY", the 
       error will be diagnosed by a routine in the call tree  
       of this routine. 
 
   15) Invalid occultation types will be diagnosed by a routine in
       the call tree of this routine.

   16) Invalid aberration correction specifications will be
       diagnosed by a routine in the call tree of this routine.

   17) If any input string argument pointer is null, the error
       SPICE(NULLPOINTER) will be signaled.

   18) If any input string argument, other than `fframe' or `bframe',
       is empty, the error SPICE(EMPTYSTRING) will be signaled.

-Files
 
   Appropriate SPICE kernels must be loaded by the calling program
   before this routine is called.
 
   The following data are required: 
 
      - SPK data: the calling application must load ephemeris data 
        for the target, source and observer that cover the time 
        period specified by the window `cnfine'. If aberration 
        corrections are used, the states of target and observer 
        relative to the solar system barycenter must be calculable 
        from the available ephemeris data. Typically ephemeris data 
        are made available by loading one or more SPK files via 
        furnsh_c. 
 
      - PCK data: bodies modeled as triaxial ellipsoids must have 
        semi-axis lengths provided by variables in the kernel pool. 
        Typically these data are made available by loading a text 
        PCK file via furnsh_c. 
 
      - FK data: if either of the reference frames designated by
        `bframe' or `fframe' are not built in to the SPICE system,
        one or more FKs specifying these frames must be loaded. 

   Kernel data are normally loaded once per program run, NOT every time
   this routine is called.
 
-Particulars
 
   This routine provides a simpler, but less flexible, interface 
   than does the CSPICE routine gfocce_c for conducting searches for 
   occultation events. Applications that require support for 
   progress reporting, interrupt handling, non-default step or 
   refinement functions, or non-default convergence tolerance should 
   call gfocce_c rather than this routine. 
 
   This routine determines a set of one or more time intervals 
   within the confinement window when a specified type of 
   occultation occurs. The resulting set of intervals is returned as 
   a SPICE window. 
 
   Below we discuss in greater detail aspects of this routine's 
   solution process that are relevant to correct and efficient 
   use of this routine in user applications. 
    
 
   The Search Process 
   ================== 
 
   The search for occultations is treated as a search for state 
   transitions: times are sought when the state of the `back' body 
   changes from "not occulted" to "occulted" or vice versa. 
 
   Step Size 
   ========= 
 
   Each interval of the confinement window is searched as follows:
   first, the input step size is used to determine the time separation
   at which the occultation state will be sampled. Starting at the left
   endpoint of the interval, samples of the occultation state will be
   taken at each step. If a state change is detected, a root has been
   bracketed; at that point, the "root"--the time at which the state
   change occurs---is found by a refinement process, for example, via
   binary search.
 
   Note that the optimal choice of step size depends on the lengths 
   of the intervals over which the occultation state is constant: 
   the step size should be shorter than the shortest occultation 
   duration and the shortest period between occultations, within 
   the confinement window. 
 
   Having some knowledge of the relative geometry of the targets and 
   observer can be a valuable aid in picking a reasonable step size. 
   In general, the user can compensate for lack of such knowledge by 
   picking a very short step size; the cost is increased computation 
   time. 
 
   Note that the step size is not related to the precision with which 
   the endpoints of the intervals of the result window are computed. 
   That precision level is controlled by the convergence tolerance. 
 
 
   Convergence Tolerance 
   ===================== 
 
   Once a root has been bracketed, a refinement process is used to
   narrow down the time interval within which the root must lie. This
   refinement process terminates when the location of the root has been
   determined to within an error margin called the "convergence
   tolerance." The convergence tolerance used by this routine is set
   via the parameter SPICE_GF_CNVTOL.
 
   The value of SPICE_GF_CNVTOL is set to a "tight" value so that the
   tolerance doesn't limit the accuracy of solutions found by this
   routine. In general the accuracy of input data will be the limiting
   factor.
 
   To use a different tolerance value, a lower-level GF routine such as
   gfocce_c must be called. Making the tolerance tighter than
   SPICE_GF_CNVTOL is unlikely to be useful, since the results are
   unlikely to be more accurate. Making the tolerance looser will speed
   up searches somewhat, since a few convergence steps will be omitted.
   However, in most cases, the step size is likely to have a much
   greater effect on processing time than would the convergence
   tolerance.
 
 
   The Confinement Window 
   ====================== 
 
   The simplest use of the confinement window is to specify a time 
   interval within which a solution is sought. 

   The confinement window also can be used to restrict a search to
   a time window over which required data (typically ephemeris
   data, in the case of occultation searches) are known to be
   available.

   In some cases, the confinement window be used to make searches
   more efficient. Sometimes it's possible to do an efficient search
   to reduce the size of the time period over which a relatively
   slow search of interest must be performed. See the "CASCADE"
   example program in gf.req for a demonstration.
 
-Examples
 
 
   The numerical results shown for these examples may differ across
   platforms. The results depend on the SPICE kernels used as
   input, the compiler and supporting libraries, and the machine
   specific arithmetic implementation.


   1) Find occultations of the Sun by the Moon (that is, solar
      eclipses) as seen from the center of the Earth over the month
      December, 2001.
 
      Use light time corrections to model apparent positions of Sun 
      and Moon. Stellar aberration corrections are not specified 
      because they don't affect occultation computations. 
 
      We select a step size of 3 minutes, which means we 
      ignore occultation events lasting less than 3 minutes, 
      if any exist. 
 
      Use the meta-kernel shown below to load the required SPICE
      kernels.

         KPL/MK

         File name: standard.tm

         This meta-kernel is intended to support operation of SPICE
         example programs. The kernels shown here should not be
         assumed to contain adequate or correct versions of data
         required by SPICE-based user applications.

         In order for an application to use this meta-kernel, the
         kernels referenced here must be present in the user's
         current working directory.


         \begindata

            KERNELS_TO_LOAD = ( 'de421.bsp',
                                'pck00008.tpc',
                                'naif0009.tls'  )

         \begintext
 
 

      Example code begins here.


         #include <stdio.h>
         #include "SpiceUsr.h"

         int main()
         {
            /.
            Local constants 
            ./

            #define TIMFMT          "YYYY MON DD HR:MN:SC.###### (TDB)::TDB"
            #define MAXWIN          200
            #define TIMLEN          41

            /.
            Local variables 
            ./
            SPICEDOUBLE_CELL      ( cnfine, MAXWIN );
            SPICEDOUBLE_CELL      ( result, MAXWIN );

            SpiceChar             * win0;
            SpiceChar             * win1;
            SpiceChar               begstr [ TIMLEN ];
            SpiceChar               endstr [ TIMLEN ];

            SpiceDouble             et0;
            SpiceDouble             et1;
            SpiceDouble             left;
            SpiceDouble             right;
            SpiceDouble             step;

            SpiceInt                i;

            /.
            Load kernels. 
            ./
            furnsh_c ( "standard.tm" );

            /.
            Obtain the TDB time bounds of the confinement
            window, which is a single interval in this case.
            ./
            win0 = "2001 DEC 01 00:00:00 TDB";
            win1 = "2002 JAN 01 00:00:00 TDB";

            str2et_c ( win0, &et0 );
            str2et_c ( win1, &et1 );

            /.
            Insert the time bounds into the confinement
            window.
            ./
            wninsd_c ( et0, et1, &cnfine );

            /.
            Select a 3-minute step. We'll ignore any occultations
            lasting less than 3 minutes.  Units are TDB seconds.
            ./
            step = 180.0;

            /.
            Perform the search.
            ./
            gfoclt_c ( "any",                            
                       "moon",    "ellipsoid",  "iau_moon", 
                       "sun",     "ellipsoid",  "iau_sun", 
                       "lt",      "earth",      step, 
                       &cnfine,   &result                 );

            if ( wncard_c(&result) == 0 )
            {
               printf ( "No occultation was found.\n" ); 
            }
            else
            {
               for ( i = 0;  i < wncard_c(&result); i++ )
               { 
                  /.
                  Fetch and display each occultation interval.
                  ./
                  wnfetd_c ( &result, i, &left, &right );

                  timout_c ( left,  TIMFMT, TIMLEN, begstr );
                  timout_c ( right, TIMFMT, TIMLEN, endstr );

                  printf ( "Interval %ld\n"
                           "   Start time: %s\n" 
                           "   Stop time:  %s\n",
                           i, begstr, endstr      );
               }
            }

            return ( 0 );
         }

 
      When this program was executed on a PC/Linux/gcc platform, the
      output was:
 
         Interval 0
            Start time: 2001 DEC 14 20:10:14.195952 (TDB)
            Stop time:  2001 DEC 14 21:35:50.317994 (TDB)

 
   2) Find occultations of Titan by Saturn or of Saturn by
      Titan as seen from the center of the Earth over the
      last four months of 2008. Model both target bodies as
      ellipsoids. Search for every type of occultation.

      Use light time corrections to model apparent positions of
      Saturn and Titan. Stellar aberration corrections are not
      specified because they don't affect occultation computations.

      We select a step size of 15 minutes, which means we
      ignore occultation events lasting less than 15 minutes,
      if any exist.

      Use the meta-kernel shown below to load the required SPICE
      kernels.


         KPL/MK

         File name: gfoclt_ex2.tm

         This meta-kernel is intended to support operation of SPICE
         example programs. The kernels shown here should not be
         assumed to contain adequate or correct versions of data
         required by SPICE-based user applications.

         In order for an application to use this meta-kernel, the
         kernels referenced here must be present in the user's
         current working directory.

         The names and contents of the kernels referenced
         by this meta-kernel are as follows:

            File name                     Contents
            ---------                     --------
            de421.bsp                     Planetary ephemeris
            sat288.bsp                    Satellite ephemeris for
                                          Saturn
            pck00008.tpc                  Planet orientation and
                                          radii
            naif0009.tls                  Leapseconds

         \begindata

            KERNELS_TO_LOAD = ( 'de421.bsp',
                                'sat288.bsp',
                                'pck00008.tpc',
                                'naif0009.tls'  )

         \begintext

         End of meta-kernel


     Example code begins here.
      
        #include <stdio.h>
        #include <string.h>
        #include "SpiceUsr.h"

        int main()
        {
           /.
           Local constants 
           ./
           #define TIMFMT          "YYYY MON DD HR:MN:SC.###### (TDB)::TDB"
           #define MAXWIN          200
           #define TIMLEN          41
           #define LNSIZE          81
           #define NTYPES          4

           /.
           Local variables 
           ./
           SPICEDOUBLE_CELL      ( cnfine, MAXWIN );
           SPICEDOUBLE_CELL      ( result, MAXWIN );

           SpiceChar             * back;
           SpiceChar             * bframe;
           SpiceChar             * front;
           SpiceChar             * fframe;
           SpiceChar               line   [ LNSIZE ];
           SpiceChar             * obsrvr;   

           SpiceChar             * occtyp [ NTYPES ] =
                                   {
                                      "FULL",
                                      "ANNULAR",
                                      "PARTIAL",
                                      "ANY"
                                   };

           SpiceChar             * templt [ NTYPES ] =
                                   {
                                      "Condition: # occultation of # by #",
                                      "Condition: # occultation of # by #",
                                      "Condition: # occultation of # by #",
                                      "Condition: # occultation of # by #"
                                   };

           SpiceChar               timstr [ TIMLEN ];
           SpiceChar               title  [ LNSIZE ];
           SpiceChar             * win0;
           SpiceChar             * win1;

           SpiceDouble             et0;
           SpiceDouble             et1;
           SpiceDouble             finish;
           SpiceDouble             start;
           SpiceDouble             step;

           SpiceInt                i;
           SpiceInt                j;
           SpiceInt                k;

           /.
           Load kernels. 
           ./
           furnsh_c ( "gfoclt_ex2.tm" );

           /.
           Obtain the TDB time bounds of the confinement
           window, which is a single interval in this case.
           ./
           win0 = "2008 SEP 01 00:00:00 TDB";
           win1 = "2009 JAN 01 00:00:00 TDB";

           str2et_c ( win0, &et0 );
           str2et_c ( win1, &et1 );

           /.
           Insert the time bounds into the confinement
           window.
           ./
           wninsd_c ( et0, et1, &cnfine );

           /.
           Select a 15-minute step. We'll ignore any occultations
           lasting less than 15 minutes. Units are TDB seconds.
           ./
           step = 900.0;

           /.
           The observation location is the Earth.
           ./
           obsrvr = "Earth";

           /.
           Loop over the occultation types.
           ./
           for ( i = 0;  i < NTYPES;  i++ )
           {
              /.
              For each type, do a search for both transits of
              Titan across Saturn and occultations of Titan by
              Saturn.
              ./
              for ( j = 0;  j < 2;  j++ )
              {
                 if ( j == 0 )
                 {
                    front  = "TITAN";
                    fframe = "IAU_TITAN";
                    back   = "SATURN";
                    bframe = "IAU_SATURN";
                 }
                 else
                 {
                    front  = "SATURN";
                    fframe = "IAU_SATURN";
                    back   = "TITAN";
                    bframe = "IAU_TITAN";
                 }

                 /.
                 Perform the search. The target body shapes
                 are modeled as ellipsoids.
                 ./
                 gfoclt_c ( occtyp[i],                            
                            front,    "ellipsoid",  fframe, 
                            back,     "ellipsoid",  bframe,  
                            "lt",     obsrvr,       step,   
                            &cnfine,  &result               );

                 /.
                 Display the results. 
                 ./
                 printf ( "\n" );

                 /.
                 Substitute the occultation type and target
                 body names into the title string:
                 ./
                 repmc_c ( templt[i], "#", occtyp[i], LNSIZE, title );
                 repmc_c ( title,     "#", back,      LNSIZE, title );
                 repmc_c ( title,     "#", front,     LNSIZE, title );

                 printf ( "%s\n", title );

                 if ( wncard_c(&result) == 0 )
                 {
                    printf ( " Result window is empty: "
                             "no occultation was found.\n" );
                 }
                 else
                 {
                    printf ( " Result window start, stop times:\n" );

                    for ( k = 0;  k < wncard_c(&result);  k++ )
                    { 
                       /.
                       Fetch the endpoints of the kth interval
                       of the result window.
                       ./
                       wnfetd_c ( &result, k, &start, &finish );

                       /.
                       Call strncpy with a length of 7 to include
                       a terminating null. 
                       ./
                       strncpy ( line, "  #  #", 7 );

                       timout_c ( start,  TIMFMT, TIMLEN, timstr );

                       repmc_c  ( line, "#", timstr, LNSIZE, line );

                       timout_c ( finish, TIMFMT, TIMLEN, timstr );

                       repmc_c  ( line, "#", timstr, LNSIZE, line );

                       printf ( "%s\n", line );
                    }
                 }
                 /.
                 We've finished displaying the results of the
                 current search.
                 ./
              }
              /.
              We've finished displaying the results of the
              searches using the current occultation type.
              ./
           }
           printf ( "\n" );

           return ( 0 );
        }

 
      When this program was executed on a PC/Linux/gcc platform, the
      output was:


         Condition: FULL occultation of SATURN by TITAN
          Result window is empty: no occultation was found.

         Condition: FULL occultation of TITAN by SATURN
          Result window start, stop times:
           2008 OCT 27 22:08:01.627053 (TDB)  2008 OCT 28 01:05:03.375236 (TDB)
           2008 NOV 12 21:21:59.252262 (TDB)  2008 NOV 13 02:06:05.053051 (TDB)
           2008 NOV 28 20:49:02.402832 (TDB)  2008 NOV 29 02:13:58.986344 (TDB)
           2008 DEC 14 20:05:09.246177 (TDB)  2008 DEC 15 01:44:53.523002 (TDB)
           2008 DEC 30 19:00:56.577073 (TDB)  2008 DEC 31 00:42:43.222909 (TDB)

         Condition: ANNULAR occultation of SATURN by TITAN
          Result window start, stop times:
           2008 OCT 19 21:29:20.599087 (TDB)  2008 OCT 19 22:53:34.518737 (TDB)
           2008 NOV 04 20:15:38.620368 (TDB)  2008 NOV 05 00:18:59.139978 (TDB)
           2008 NOV 20 19:38:59.647712 (TDB)  2008 NOV 21 00:35:26.725908 (TDB)
           2008 DEC 06 18:58:34.073268 (TDB)  2008 DEC 07 00:16:17.647040 (TDB)
           2008 DEC 22 18:02:46.288289 (TDB)  2008 DEC 22 23:26:52.712459 (TDB)

         Condition: ANNULAR occultation of TITAN by SATURN
          Result window is empty: no occultation was found.

         Condition: PARTIAL occultation of SATURN by TITAN
          Result window start, stop times:
           2008 OCT 19 20:44:30.326771 (TDB)  2008 OCT 19 21:29:20.599087 (TDB)
           2008 OCT 19 22:53:34.518737 (TDB)  2008 OCT 19 23:38:26.250580 (TDB)
           2008 NOV 04 19:54:40.339331 (TDB)  2008 NOV 04 20:15:38.620368 (TDB)
           2008 NOV 05 00:18:59.139978 (TDB)  2008 NOV 05 00:39:58.612935 (TDB)
           2008 NOV 20 19:21:46.689523 (TDB)  2008 NOV 20 19:38:59.647712 (TDB)
           2008 NOV 21 00:35:26.725908 (TDB)  2008 NOV 21 00:52:40.604703 (TDB)
           2008 DEC 06 18:42:36.100544 (TDB)  2008 DEC 06 18:58:34.073268 (TDB)
           2008 DEC 07 00:16:17.647040 (TDB)  2008 DEC 07 00:32:16.324244 (TDB)
           2008 DEC 22 17:47:10.776722 (TDB)  2008 DEC 22 18:02:46.288289 (TDB)
           2008 DEC 22 23:26:52.712459 (TDB)  2008 DEC 22 23:42:28.850542 (TDB)

         Condition: PARTIAL occultation of TITAN by SATURN
          Result window start, stop times:
           2008 OCT 27 21:37:16.970175 (TDB)  2008 OCT 27 22:08:01.627053 (TDB)
           2008 OCT 28 01:05:03.375236 (TDB)  2008 OCT 28 01:35:49.266506 (TDB)
           2008 NOV 12 21:01:47.105498 (TDB)  2008 NOV 12 21:21:59.252262 (TDB)
           2008 NOV 13 02:06:05.053051 (TDB)  2008 NOV 13 02:26:18.227357 (TDB)
           2008 NOV 28 20:31:28.522707 (TDB)  2008 NOV 28 20:49:02.402832 (TDB)
           2008 NOV 29 02:13:58.986344 (TDB)  2008 NOV 29 02:31:33.691598 (TDB)
           2008 DEC 14 19:48:27.094229 (TDB)  2008 DEC 14 20:05:09.246177 (TDB)
           2008 DEC 15 01:44:53.523002 (TDB)  2008 DEC 15 02:01:36.360243 (TDB)
           2008 DEC 30 18:44:23.485898 (TDB)  2008 DEC 30 19:00:56.577073 (TDB)
           2008 DEC 31 00:42:43.222909 (TDB)  2008 DEC 31 00:59:17.030568 (TDB)

         Condition: ANY occultation of SATURN by TITAN
          Result window start, stop times:
           2008 OCT 19 20:44:30.326771 (TDB)  2008 OCT 19 23:38:26.250580 (TDB)
           2008 NOV 04 19:54:40.339331 (TDB)  2008 NOV 05 00:39:58.612935 (TDB)
           2008 NOV 20 19:21:46.689523 (TDB)  2008 NOV 21 00:52:40.604703 (TDB)
           2008 DEC 06 18:42:36.100544 (TDB)  2008 DEC 07 00:32:16.324244 (TDB)
           2008 DEC 22 17:47:10.776722 (TDB)  2008 DEC 22 23:42:28.850542 (TDB)

         Condition: ANY occultation of TITAN by SATURN
          Result window start, stop times:
           2008 OCT 27 21:37:16.970175 (TDB)  2008 OCT 28 01:35:49.266506 (TDB)
           2008 NOV 12 21:01:47.105498 (TDB)  2008 NOV 13 02:26:18.227357 (TDB)
           2008 NOV 28 20:31:28.522707 (TDB)  2008 NOV 29 02:31:33.691598 (TDB)
           2008 DEC 14 19:48:27.094229 (TDB)  2008 DEC 15 02:01:36.360243 (TDB)
           2008 DEC 30 18:44:23.485898 (TDB)  2008 DEC 31 00:59:17.030568 (TDB)


-Restrictions
 
   The kernel files to be used by gfoclt_c must be loaded (normally via 
   the CSPICE routine furnsh_c) before gfoclt_c is called. 
 
-Literature_References
 
  None. 
 
-Author_and_Institution
 
  N. J. Bachman  (JPL) 
  L. S. Elson    (JPL) 
  E. D. Wright   (JPL) 
 
-Version
 
   -CSPICE Version 1.0.0, 07-APR-2009 (NJB) (LSE) (EDW)

-Index_Entries
 
   GF occultation search

-&
*/

{ /* Begin gfoclt_c */


   /*
   Local variables 
   */
   static const SpiceChar  * blankStr = " ";

   SpiceChar               * bFrameStr;
   SpiceChar               * fFrameStr;


   /*
   Participate in error tracing.
   */
   if ( return_c() )
   {
      return;
   }
   chkin_c ( "gfoclt_c" );


   /*
   Make sure cell data types are d.p. 
   */
   CELLTYPECHK2 ( CHK_STANDARD, "gfoclt_c", SPICE_DP, cnfine, result );

   /*
   Initialize the input cells if necessary. 
   */
   CELLINIT2 ( cnfine, result );

   /*
   The input frame names are special cases because we allow the caller
   to pass in empty strings. If either of these strings are empty,
   we pass a null-terminated string containing one blank character to
   the underlying f2c'd routine. 

   First make sure the frame name pointers are non-null.
   */
   CHKPTR ( CHK_STANDARD, "gfoclt_c", bframe );
   CHKPTR ( CHK_STANDARD, "gfoclt_c", fframe );

   /*
   Use the input frame strings if they're non-empty; otherwise
   use blank strings for the frame names.
   */
  
   if ( bframe[0] )
   {
      bFrameStr = (SpiceChar *) bframe;
   }
   else
   {
      bFrameStr = (SpiceChar *) blankStr;
   }

   if ( fframe[0] )
   {
      fFrameStr = (SpiceChar *) fframe;
   }
   else
   {
      fFrameStr = (SpiceChar *) blankStr;
   }


   /*
   Check the other input strings to make sure each pointer is non-null 
   and each string length is non-zero.
   */
   CHKFSTR ( CHK_STANDARD, "gfoclt_c", occtyp );
   CHKFSTR ( CHK_STANDARD, "gfoclt_c", front  );
   CHKFSTR ( CHK_STANDARD, "gfoclt_c", fshape );
   CHKFSTR ( CHK_STANDARD, "gfoclt_c", back   );
   CHKFSTR ( CHK_STANDARD, "gfoclt_c", bshape );
   CHKFSTR ( CHK_STANDARD, "gfoclt_c", abcorr );
   CHKFSTR ( CHK_STANDARD, "gfoclt_c", obsrvr );


   /*
   Let the f2c'd routine do the work. 
   */
   gfoclt_ ( (char         *) occtyp,
             (char         *) front,
             (char         *) fshape,
             (char         *) fFrameStr,
             (char         *) back,
             (char         *) bshape,
             (char         *) bFrameStr,
             (char         *) abcorr,
             (char         *) obsrvr,
             (doublereal   *) &step,
             (doublereal   *) cnfine->base,
             (doublereal   *) result->base,
             (ftnlen        ) strlen(occtyp),
             (ftnlen        ) strlen(front),
             (ftnlen        ) strlen(fshape),
             (ftnlen        ) strlen(fframe),
             (ftnlen        ) strlen(back),
             (ftnlen        ) strlen(bshape),
             (ftnlen        ) strlen(bframe),
             (ftnlen        ) strlen(abcorr),
             (ftnlen        ) strlen(obsrvr)  );

   /*
   Sync the output result cell. 
   */
   if ( !failed_c() )
   {
      zzsynccl_c ( F2C, result );
   }


   chkout_c ( "gfoclt_c" );

} /* End gfoclt_c */
Example #12
0
PUBLIC void
r_store_init(struct ccnr_handle *h)
{
    struct ccn_btree *btree = NULL;
    struct ccn_btree_node *node = NULL;
    struct hashtb_param param = {0};
    int i;
    int j;
    int res;
    struct ccn_charbuf *path = NULL;
    struct ccn_charbuf *msgs = NULL;
    off_t offset;
    
    path = ccn_charbuf_create();
    param.finalize_data = h;
    param.finalize = 0;
    
    h->cob_limit = r_init_confval(h, "CCNR_CONTENT_CACHE", 16, 2000000, 4201);
    h->cookie_limit = choose_limit(h->cob_limit, (ccnr_cookie)(~0U));
    h->content_by_cookie = calloc(h->cookie_limit, sizeof(h->content_by_cookie[0]));
    CHKPTR(h->content_by_cookie);
    h->content_by_accession_tab = hashtb_create(sizeof(struct content_by_accession_entry), NULL);
    CHKPTR(h->content_by_accession_tab);
    h->btree = btree = ccn_btree_create();
    CHKPTR(btree);
    FAILIF(btree->nextnodeid != 1);
    ccn_charbuf_putf(path, "%s/index", h->directory);
    res = mkdir(ccn_charbuf_as_string(path), 0700);
    if (res != 0 && errno != EEXIST)
        r_init_fail(h, __LINE__, ccn_charbuf_as_string(path), errno);
    else {
        msgs = ccn_charbuf_create();
        btree->io = ccn_btree_io_from_directory(ccn_charbuf_as_string(path), msgs);
        if (btree->io == NULL)
            res = errno;
        if (msgs->length != 0 && CCNSHOULDLOG(h, sffdsdf, CCNL_WARNING)) {
            ccnr_msg(h, "while initializing %s - %s",
                     ccn_charbuf_as_string(path),
                     ccn_charbuf_as_string(msgs));
        }
        ccn_charbuf_destroy(&msgs);
        if (btree->io == NULL)
            r_init_fail(h, __LINE__, ccn_charbuf_as_string(path), res);
    }
    node = ccn_btree_getnode(btree, 1, 0);
    if (btree->io != NULL)
        btree->nextnodeid = btree->io->maxnodeid + 1;
    CHKPTR(node);
    if (node->buf->length == 0) {
        res = ccn_btree_init_node(node, 0, 'R', 0);
        CHKSYS(res);
    }
    ccn_charbuf_destroy(&path);
    if (h->running == -1)
        return;
    r_store_read_stable_point(h);
    h->active_in_fd = -1;
    h->active_out_fd = r_io_open_repo_data_file(h, "repoFile1", 1); /* output */
    offset = lseek(h->active_out_fd, 0, SEEK_END);
    h->startupbytes = offset;
    if (offset != h->stable || node->corrupt != 0) {
        ccnr_msg(h, "Index not current - resetting");
        ccn_btree_init_node(node, 0, 'R', 0);
        node = NULL;
        ccn_btree_destroy(&h->btree);
        path = ccn_charbuf_create();
        /* Remove old index files to avoid confusion */
        for (i = 1, j = 0; i > 0 && j < 3; i++) {
            path->length = 0;
            res = ccn_charbuf_putf(path, "%s/index/%d", h->directory, i);
            if (res >= 0)
                res = unlink(ccn_charbuf_as_string(path));
            if (res < 0)
                j++;
        }
        h->btree = btree = ccn_btree_create();
        path->length = 0;
        ccn_charbuf_putf(path, "%s/index", h->directory);
        btree->io = ccn_btree_io_from_directory(ccn_charbuf_as_string(path), msgs);
        CHKPTR(btree->io);
        btree->io->maxnodeid = 0;
        btree->nextnodeid = 1;
        node = ccn_btree_getnode(btree, 1, 0);
        btree->nextnodeid = btree->io->maxnodeid + 1;
        ccn_btree_init_node(node, 0, 'R', 0);
        h->stable = 0;
        h->active_in_fd = r_io_open_repo_data_file(h, "repoFile1", 0); /* input */
        ccn_charbuf_destroy(&path);
        if (CCNSHOULDLOG(h, dfds, CCNL_INFO))
            ccn_schedule_event(h->sched, 50000, r_store_reindexing, NULL, 0);
    }
    if (CCNSHOULDLOG(h, weuyg, CCNL_FINEST)) {
        FILE *dumpfile = NULL;
        
        path = ccn_charbuf_create();
        ccn_charbuf_putf(path, "%s/index/btree_check.out", h->directory);
        dumpfile = fopen(ccn_charbuf_as_string(path), "w");
        res = ccn_btree_check(btree, dumpfile);
        if (dumpfile != NULL) {
            fclose(dumpfile);
            dumpfile = NULL;
        }
        else
            path->length = 0;
        ccnr_msg(h, "ccn_btree_check returned %d (%s)",
                    res, ccn_charbuf_as_string(path));
        ccn_charbuf_destroy(&path);
        if (res < 0)
            r_init_fail(h, __LINE__, "index is corrupt", res);
    }
    btree->full = r_init_confval(h, "CCNR_BTREE_MAX_FANOUT", 4, 9999, 1999);
    btree->full0 = r_init_confval(h, "CCNR_BTREE_MAX_LEAF_ENTRIES", 4, 9999, 1999);
    btree->nodebytes = r_init_confval(h, "CCNR_BTREE_MAX_NODE_BYTES", 1024, 8388608, 2097152);
    btree->nodepool = r_init_confval(h, "CCNR_BTREE_NODE_POOL", 16, 2000000, 512);
    if (h->running != -1)
        r_store_index_needs_cleaning(h);
}
Example #13
0
   void lx4dec_c ( ConstSpiceChar   * string,
                   SpiceInt           first,
                   SpiceInt         * last,
                   SpiceInt         * nchar  ) 

/*

-Brief_I/O
 
   VARIABLE  I/O  DESCRIPTION 
   --------  ---  -------------------------------------------------- 
   string     I   Any character string.
   first      I   First character to scan from in string.
   last       O   Last character that is part of a decimal number.
   nchar      O   Number of characters in the decimal number. 
 
-Detailed_Input
 
   string      is any character string. 
 
   first       is the location in the string to beginning scanning 
               for a decimal number.  It is assumed that the 
               decimal number begins at first.  

               The normal range of first is 0 : strlen(string)-1.
 
-Detailed_Output
 
   last        is the last character at or after first such that the
               substring ranging from string[first] through
               string[last] is a decimal number.  If there is no such
               substring, last will be returned with the value first-1.

               If a decimal number is found, last will be in the
               range is 0 : strlen(string)-1.


   nchar       is the number of characters in the decimal number that
               begins at index first and ends at last.  If there is no
               such string nchar will be given the value 0.
 
-Parameters
 
   None. 
 
-Exceptions
  
   1) If first is beyond either end of the string, then 
      last will be returned with the value first-1 and nchar 
      will be returned with the value 0. 
 
   2) If string[first] is not part of a decimal number then last 
      will be returned with the value first-1 and nchar will be 
      returned with the value 0. 

   3) If the input string pointer is null, the error SPICE(NULLPOINTER)
      will be signaled.

   4) If the input string has length zero, last will be set to first-1
      and nchar will be set to zero.  This case is not considered an
      error.
 
-Files
 
   None. 
 
-Particulars
 
   This routine allows you to scan forward in a string to locate 
   a decimal number that begins on the input character first.  Note 
   that all signed integers are included in the list of decimal 
   numbers.  See lx4sgn_c for a description of signed integers. 
 
   We let S stand for a signed integer and U stand for 
   an unsigned integer.  With this notation, the strings 
   recognized as decimal numbers are: 
 
      U 
      S 
      S. 
      S.U 
       .U 
      -.U 
      +.U 
 
 
-Examples
 
   1) Suppose you believe that a string has the form 
 
         X%Y%Z 
 
      where X, Y, and Z are decimal numbers of some unknown length and
      % stands for any character that cannot occur in a decimal number.
      You could use this routine to locate the decimal numbers in the
      string as shown below.  We'll keep track of the beginning and
      ending of the decimal numbers in the integer arrays b and e.
 

         #include <string.h>
         #include "SpiceUsr.h"

               .
               .
               .

         first = 0;
         i     = 0;
         len   = strlen(string);

         while ( first < len-1 )
         {
            lx4dec_c ( string, first, &last, &nchar );

            if ( nchar > 0 )
            {
               i++;

               b[i]  = first;
               e[i]  = last;
               first = last  +  2;
            }
            else
            {
               first++;  
            }
         }
          

-Restrictions
 
   None. 
 
-Author_and_Institution
 
   N.J. Bachman    (JPL)
   W.L. Taber      (JPL) 
 
-Literature_References
 
   None. 
 
-Version
 
   -CSPICE Version 1.0.0, 18-AUG-2002 (NJB) (WLT)

-Index_Entries
 
   Scan a string for a decimal number. 
 
-&
*/

{ /* Begin lx4dec_c */

   /*
   Local variables 
   */
   SpiceInt                locFirst;
   SpiceInt                len;


   /*
   Use discovery check-in.

   Check the input string argument for a null pointer.
   */
   CHKPTR ( CHK_DISCOVER, "lx4dec_c", string );


   /*
   We're done if the input string has zero length. 
   */
   len = strlen(string);

   if ( len == 0 )
   {
      *last  = -1;
      *nchar =  0;

      return;
   }


   /*
   Map first to a Fortran-style index. 
   */
   locFirst = first + 1;

   /*
   Call the f2c'd routine. 
   */
   lx4dec_ ( ( char    * ) string,
             ( integer * ) &locFirst,
             ( integer * ) last,
             ( integer * ) nchar,
             ( ftnlen    ) len      );

   /*
   Map last to a C-style index. 
   */

   (*last)--;

} /* End lx4dec_c */
Example #14
0
   void repmi_c ( ConstSpiceChar     * in,
                  ConstSpiceChar     * marker,
                  SpiceInt             value,
                  SpiceInt             lenout,
                  SpiceChar          * out     ) 

/*

-Brief_I/O
 
   VARIABLE  I/O  DESCRIPTION 
   --------  ---  -------------------------------------------------- 
   in         I   Input string. 
   marker     I   Marker to be replaced. 
   value      I   Replacement value.
   lenout     I   Available space in output string.
   out        O   Output string. 
   MAXLI      P   Maximum length of an integer. 
 
-Detailed_Input
 
   in             is an arbitrary character string. 
 
   marker         is an arbitrary character string. The first occurrence 
                  of marker in the input string is to be replaced by value. 
 
                  Leading and trailing blanks in marker are NOT significant. 
                  In particular, no substitution is performed if marker 
                  is blank. 
 
   value          is an arbitrary integer. 

 
   lenout         is the allowed length of the output string.  This length
                  must large enough to hold the output string plus the
                  terminator.  If the output string is expected to have x
                  characters, lenout should be at least x + 1.

-Detailed_Output
 
   out            is the string obtained by substituting the text 
                  representation of value for the first occurrence 
                  of marker in the input string. 
 
                  out and in must be identical or disjoint. 
 
-Parameters
 
   MAXLI          is the maximum expected length of the text 
                  representation of an integer. 11 characters are 
                  sufficient to hold any integer whose absolute 
                  value is less than 10 billion. 
 
                  This routine assumes that the input integer
                  is such that its string representation contains
                  no more than MAXLI characters.
 
-Files
 
   None. 
 
-Exceptions
 
   1) The error SPICE(NULLPOINTER) is signaled if any of 
      the input or output string pointers is null.

   2) If the marker string is blank or empty, this routine leaves 
      the input string unchanged, except that trailing blanks
      will be trimmed.  This case is not considered an error.

   3) If the output string is too short to accommodate a terminating
      null character, the error SPICE(STRINGTOOSHORT) is signaled.

   4) If out does not have sufficient length to accommodate the 
      result of the substitution, the result will be truncated on 
      the right. 
  
-Particulars
 
   This is one of a family of related routines for inserting values 
   into strings. They are typically to construct messages that 
   are partly fixed, and partly determined at run time. For example, 
   a message like 
 
      "Fifty-one pictures were found in directory [USER.DATA]." 
 
   might be constructed from the fixed string 
 
      "#1 pictures were found in directory #2." 
 
   by the calls 
 
      #include "SpiceUsr.h"
           .
           .
           .
      #define   LENOUT                  81
           .
           .
           .
      repmct_c ( string, "#1",  51,  'c',      LENOUT, string );
      repmc_c  ( string, "#2", "[USER.DATA]",  LENOUT, string );
 

   which substitute the cardinal text "Fifty-one" and the character 
   string "[USER.DATA]" for the markers "#1" and "#2" respectively. 
 
   The complete list of routines is shown below. 
 
      repmc_c  ( Replace marker with character string value ) 
      repmd_c  ( Replace marker with double precision value ) 
      repmf_c  ( Replace marker with formatted d.p. value   ) 
      repmi_c  ( Replace marker with integer value          ) 
      repmct_c ( Replace marker with cardinal text          ) 
      repmot_c ( Replace marker with ordinal text           ) 

 
-Examples
 
   1. Let 
 
         in == "Invalid operation value.  The value was <opcode>." 
 
      Then following the call, 
 
         #include "SpiceUsr.h"
              .
              .
              .
         #define   LENOUT                  201
              .
              .
              .
         repmi_c ( in, "<opcode>", 5, LENOUT, outstr );
 

      outstr contains the string: 
 
         "Invalid operation value.  The value was 5." 
 
 

   2. Let 
 
         in ==  "Left endpoint exceeded right endpoint.  "
                "The left endpoint was:  XX.  The right "
                "endpoint was:  XX." 
 
      Then following the call, 
 
 
         #include "SpiceUsr.h"
              .
              .
              .
         #define   LENOUT                  201
              .
              .
              .
         repmi_c ( in, "  XX  ", 5, LENOUT, out );
 
      out is 
 
         "Left endpoint exceeded right endpoint.  The left "
         "endpoint was:  5.  The right endpoint was:  XX."
 
 
   3. Let 
 
         num    == 23 
         chance == "fair" 
         score  == 4.665 
 
      Then following the sequence of calls, 
 
         #include "SpiceUsr.h"
              .
              .
              .
         #define   LENOUT                  201
              .
              .
              .
         repmi_c ( "There are & routines that have a "  
                   "& chance of meeting your needs."    
                   "The maximum score was &.", 
                   "&",
                    num, 
                    LENOUT,
                    msg                              ); 
 
         repmc_c ( msg, marker, chance, LENOUT, msg );
 
         repmf_c ( msg, marker, score,  4, 'f', LENOUT, msg ); 
 

      msg is 
 
         "There are 23 routines that have a fair chance of "
         "meeting your needs.  The maximum score was 4.665." 
 
-Restrictions
 
   None. 
 
-Literature_References
 
   None. 
 
-Author_and_Institution
 
   N.J. Bachman   (JPL) 
   I.M. Underwood (JPL) 
 
-Version
 
   -CSPICE Version 1.0.0, 14-AUG-2002 (NJB) (IMU)

-Index_Entries
 
   replace marker with integer 
 
-&
*/

{ /* Begin repmi_c */


   /*
   Local variables 
   */
   ConstSpiceChar        * markPtr;


   /*
   Use discovery check-in. 

   Make sure no string argument pointers are null.
   */
   CHKPTR( CHK_DISCOVER, "repmi_c", in     );
   CHKPTR( CHK_DISCOVER, "repmi_c", marker );
   CHKPTR( CHK_DISCOVER, "repmi_c", out    );


   /*
   If the output string can't hold a terminating null character,
   we can't proceed. 
   */
   if ( lenout < 1 )
   {
      chkin_c  ( "repmi_c"                                    );
      setmsg_c ( "String length lenout must be >= 1; actual "
                 "value = #."                                 );
      errint_c ( "#", lenout                                  );
      sigerr_c ( "SPICE(STRINGTOOSHORT)"                      );
      chkout_c ( "repmi_c"                                    );
      return;
   }


   /*
   If the output string has no room for data characters, we simply
   terminate the string.
   */
   if ( lenout == 1 )
   {
      out[0] = NULLCHAR;
      return;
   }


   /*
   If the input string has zero length, the output is empty as well. 
   */
   if ( in[0] == NULLCHAR )
   {
      out[0] = NULLCHAR;

      return;
   }


   /*
   If the marker is empty, pass a blank marker to the f2c'd routine.
   Otherwise, pass in the marker.
   */
   if ( marker[0] == NULLCHAR )
   {
      markPtr = " ";
   }
   else
   {
      markPtr = marker;
   }
   
   /*
   Simply call the f2c'd routine. 
   */
   repmi_ ( ( char     * ) in,
            ( char     * ) markPtr,
            ( integer  * ) &value,
            ( char     * ) out,
            ( ftnlen     ) strlen(in),
            ( ftnlen     ) strlen(markPtr),
            ( ftnlen     ) lenout-1         );

   /*
   Convert the output string from Fortran to C style. 
   */
   F2C_ConvertStr ( lenout, out );
   

} /* End repmi_c */
Example #15
0
   void fovray_c ( ConstSpiceChar   * inst,
                   ConstSpiceDouble   raydir [3],
                   ConstSpiceChar   * rframe,
                   ConstSpiceChar   * abcorr,
                   ConstSpiceChar   * observer,
                   SpiceDouble      * et,
                   SpiceBoolean     * visible  )
                   
/*

-Brief_I/O
 
   VARIABLE         I/O  DESCRIPTION 
   ---------------  ---  ------------------------------------------------  
   inst              I   Name or ID code string of the instrument.
   raydir            I   Ray's direction vector.
   rframe            I   Body-fixed, body-centered frame for target body.
   abcorr            I   Aberration correction flag. 
   observer          I   Name or ID code string of the observer.
   et                I   Time of the observation (seconds past J2000).
   visible           O   Visibility flag (SPICETRUE/SPICEFALSE).

-Detailed_Input

   inst       indicates the name of an instrument, such as a
              spacecraft-mounted framing camera. The field of view
              (FOV) of the instrument will be used to determine if
              the direction from the observer to a target,
              represented as a ray, is visible with respect to the
              instrument.

              The position of the instrument `inst' is considered to
              coincide with that of the ephemeris object `observer' (see
              description below).

              The size of the instrument's FOV is constrained by the
              following: There must be a vector A such that all of
              the instrument's FOV boundary vectors have an angular
              separation from A of less than (pi/2)-MARGIN radians
              (see description below). For FOVs that are circular or
              elliptical, the vector A is the boresight. For FOVs
              that are rectangular or polygonal, the vector A is
              calculated.

              See the header of the CSPICE routine getfov_c for a
              description of the required parameters associated with
              an instrument.

              Both object names and NAIF IDs are accepted. For
              example, both "CASSINI_ISS_NAC" and "-82360" are
              accepted. Case and leading or trailing blanks are not
              significant in the string.

   raydir     is the direction vector associated with a ray
              representing a target. The ray emanates from the
              location of the ephemeris object designated by the
              input argument `observer' and is expressed relative to the
              reference frame designated by `rframe' (see descriptions
              below).

   rframe     is the name of the reference frame associated with
              the input ray's direction vector `raydir'. Note: `rframe'
              does not need to be the instrument's reference frame.

              Since light time corrections are not supported for
              rays, the orientation of the frame is always evaluated
              at the epoch associated with the observer, as opposed
              to the epoch associated with the light-time corrected
              position of the frame center.

              Case, leading and trailing blanks are not significant
              in the string.

   abcorr     indicates the aberration corrections to be applied
              when computing the ray's direction.

              The supported aberration correction options are:

                 "NONE"          No correction.
                 "S"             Stellar aberration correction,
                                 reception case.
                 "XS"            Stellar aberration correction,
                                 transmission case.

              For detailed information, see the geometry finder
              required reading, gf.req.

              Case, leading and trailing blanks are not significant
              in the string.

   observer   is the name of the body from which the target
              represented by `raydir' is observed. The instrument
              designated by `inst' is treated as if it were co-located
              with the observer.

              Both object names and NAIF IDs are accepted. For
              example, both "CASSINI" and "-82" are accepted. Case and
              leading or trailing blanks are not significant in the
              string.

   et         is the observation time in seconds past the J2000
              epoch.

-Detailed_Output

   visible    is SPICETRUE if the ray is "visible", or in the
              field-of-view, of `inst' at the time `et'. Otherwise,
              `visible' is SPICEFALSE.

-Parameters

   SPICE_GF_MAXVRT     is the maximum number of vertices that may be used
                       to define the boundary of the specified instrument's
                       field of view. See SpiceGF.h for more details.

   MARGIN              is a small positive number used to constrain the
                       orientation of the boundary vectors of polygonal
                       FOVs. Such FOVs must satisfy the following constraints:

                       1)  The boundary vectors must be contained within
                           a right circular cone of angular radius less
                           than than (pi/2) - MARGIN radians; in
                           other words, there must be a vector A such that all
                           boundary vectors have angular separation from
                           A of less than (pi/2)-MARGIN radians.
      
                       2)  There must be a pair of boundary vectors U, V
                           such that all other boundary vectors lie in
                           the same half space bounded by the plane
                           containing U and V. Furthermore, all other
                           boundary vectors must have orthogonal
                           projections onto a specific plane normal to
                           this plane (the normal plane contains the angle
                           bisector defined by U and V) such that the
                           projections have angular separation of at least
                           2*MARGIN radians from the plane spanned
                           by U and V.
      
                       MARGIN is currently set to 1.D-6.

-Exceptions

   1)  If the observer's name cannot be mapped to a NAIF ID code, the
       error SPICE(IDCODENOTFOUND) is signaled.

   2)  If the aberration correction flag calls for light time
       correction, the error SPICE(INVALIDOPTION) is signaled.

   3)  If the ray's direction vector is zero, the error
       SPICE(ZEROVECTOR) is signaled.

   4)  If the instrument name `inst' does not have corresponding NAIF
       ID code, the error will be diagnosed by a routine in the call
       tree of this routine.

   5)  If the FOV parameters of the instrument are not present in
       the kernel pool, the error will be diagnosed by routines
       in the call tree of this routine.

   6)  If the FOV boundary has more than SPICE_GF_MAXVRT vertices, the error
       will be diagnosed by routines in the call tree of this
       routine.

   7)  If the instrument FOV shape is a polygon or rectangle, and
       this routine cannot find a ray R emanating from the FOV
       vertex such that maximum angular separation of R and any FOV
       boundary vector is within the limit (pi/2)-MARGIN radians,
       the error will be diagnosed by a routine in the call tree of
       this routine. If the FOV is any other shape, the same error
       check will be applied with the instrument boresight vector
       serving the role of R.

   8)  If the loaded kernels provide insufficient data to compute a
       requested state vector, the error will be diagnosed by a
       routine in the call tree of this routine.

   9)  If an error occurs while reading an SPK or other kernel file,
       the error will be diagnosed by a routine in the call tree
       of this routine.

   10) If any input string argument pointer is null, the error
       SPICE(NULLPOINTER) will be signaled.
 
   11) If any input string argument other than `rframe' is empty, the
       error SPICE(EMPTYSTRING) will be signaled.

-Files

   Appropriate SPICE kernels must be loaded by the calling program
   before this routine is called.

   The following data are required:

      - SPK data: ephemeris data for the observer at the time
        `et'. If aberration corrections are used, the state of the
        observer relative to the solar system barycenter
        must be calculable from the available ephemeris data.

      - Data defining the reference frame in which the instrument's
        FOV is defined must be available in the kernel pool.
        Additionally the name `inst' must be associated with an ID
        code.

      - IK data: the kernel pool must contain data such that
        the CSPICE routine getfov_c may be called to obtain
        parameters for `inst'.

   The following data may be required:

      - CK data: if the frame in which the instrument's FOV is
        defined is fixed to a spacecraft, at least one CK file will
        be needed to permit transformation of vectors between that
        frame and the J2000 frame.

      - SCLK data: if a CK file is needed, an associated SCLK
        kernel is required to enable conversion between encoded SCLK
        (used to time-tag CK data) and barycentric dynamical time
        (TDB).

      - Since the input ray direction may be expressed in any
        frame, additional FKs, CKs, SCLK kernels, PCKs, and SPKs
        may be required to map the direction to the J2000 frame.

   Kernel data are normally loaded via furnsh_c once per program run,
   NOT every time this routine is called.

-Particulars

   To treat the target as an ephemeris object rather than a ray, use
   the higher-level CSPICE routine fovtrg_c. fovtrg_c may be used to
   determine if ephemeris objects such as Saturn are visible in an
   instrument's FOV at a given time.

-Examples

   1) The Cassini Ultraviolet Imaging Spectrograph (UVIS)
      has been used to measure variations in starlight as
      rings and moons occult Cassini's view of the stars.
      One of these events happened at 2008-054T21:31:55.158 UTC.
      Let's verify that Epsilon CMa (Adhara) was in the
      Cassini UVIS field-of-view at the observation time.

         KPL/MK

         File name: fovray_ex.tm

         This meta-kernel is intended to support operation of SPICE
         example programs. The kernels shown here should not be
         assumed to contain adequate or correct versions of data
         required by SPICE-based user applications.

         In order for an application to use this meta-kernel, the
         kernels referenced here must be present in the user's
         current working directory.

         The names and contents of the kernels referenced
         by this meta-kernel are as follows:

           File name                      Contents
           ---------                      --------
           naif0010.tls                   Leapseconds
           cpck26Jan2007.tpc              Satellite orientation and
                                          radii
           cas00145.tsc                   Cassini SCLK
           cas_v40.tf                     Cassini frames
           cas_uvis_v06.ti                Cassini UVIS instrument
           080428R_SCPSE_08045_08067.bsp  Merged spacecraft,
                                          planetary, and satellite
                                          ephemeris
           08052_08057ra.bc               Orientation for Cassini

         \begindata

           KERNELS_TO_LOAD = ( 'cpck26Jan2007.tpc'
                               'naif0010.tls'
                               'cas00145.tsc'
                               'cas_v40.tf'
                               'cas_uvis_v06.ti'
                               '080428R_SCPSE_08045_08067.bsp'
                               '08052_08057ra.bc')

         \begintext

      Example code begins here.
      
         #include <stdio.h>
         #include "SpiceUsr.h"
         #include "SpiceZmc.h"
         
         int main()
         {
            
            /.
            Local constants 
            ./ 
            #define META  "fovray_ex.tm"
            #define BODLEN 32
            #define TIMLEN 32
            #define FRMLEN 32
            
            /.
            Local variables 
            
            The variable `time' is the observation time.
            ./
            
            SpiceChar             * time = "2008-054T21:31:55.158";
            SpiceChar               time_output[TIMLEN];
            ConstSpiceChar        * time_format = 
                                    "YYYY-MON-DD HR:MN:SC.###::TDB (TDB)";
         
            /.
            The variables `right_asc' and `dec' are the right ascension
            and declination of Epsilon CMa in degrees.
            ./
            SpiceDouble             dec       = -28.972;
            SpiceDouble             et;
            SpiceDouble             raydir [3];
            SpiceDouble             right_asc = 104.656;
            
            SpiceBoolean            visible;
            
            /.
            Load kernels.
            ./
            furnsh_c ( META );
            
            /.
            Convert the observation time to `et'.
            ./
            str2et_c ( time, &et );
            
            /.
            Create a unit direction vector pointing from Cassini
            to the specified star. For details on corrections such
            as parallax, please see the example in gfrfov_c.
            ./
            radrec_c ( 1.0, right_asc*rpd_c(), dec*rpd_c(), raydir );
         
            /.
            Is the star in the field-of-view of Cassini's UVIS?
            ./
            fovray_c ( "CASSINI_UVIS_FUV_OCC", raydir, "J2000",
                       "S", "Cassini", &et, &visible );
                       
            /.
            Put the time in a specified format for output and
            report the result.
            ./
            timout_c ( et, time_format, TIMLEN, time_output );
            
            if ( visible ) {
               printf ( "Epsilon CMa was visible from the Cassini\n" );
               printf ( "UVIS instrument at %s\n", time_output );
            }
            
            return (0);
         }
      
      When this program was executed on a PC/Linux/gcc platform, the 
      output was: 

         Epsilon CMa was visible from the Cassini
         UVIS instrument at 2008-FEB-23 21:33:00.343 (TDB)

-Restrictions

   None.

-Literature_References
 
   None. 
 
-Author_and_Institution
 
   S.C. Krening  (JPL)
   N.J. Bachman  (JPL) 
 
-Version
 
   -CSPICE Version 1.0.0, 15-FEB-2012 (SCK) (NJB)

-Index_Entries
 
   Ray in instrument FOV at specified time
   Ray in instrument field_of_view at specified time

-&
*/

{ /* Begin fovray_c */

   /*
   Local variables 
   */
   SpiceChar               * rFrameStr;

   /*
   Static variables
   */
   static const SpiceChar  * blankStr = " ";
   
   /*
   Participate in error tracing.
   */
   if ( return_c() )
   {
      return;
   }
   chkin_c ( "fovray_c" );

   /*
   Check the input strings to make sure the pointers are non-null
   and the string lengths are non-zero.
   */
   CHKFSTR ( CHK_STANDARD, "fovray_c", inst   );
   CHKFSTR ( CHK_STANDARD, "fovray_c", abcorr );
   CHKFSTR ( CHK_STANDARD, "fovray_c", observer );

   /*
   The input frame name is a special case because we allow the caller
   to pass in an empty string. If this string is empty,
   we pass a null-terminated string containing one blank character to
   the underlying f2c'd routine. 

   First make sure the frame name pointer is non-null.
   */
   CHKPTR ( CHK_STANDARD, "fovray_c", rframe );
   
   /*
   Use the input frame string if it's non-empty; otherwise
   use a blank string for the frame name.
   */
  
   if ( rframe[0] )
   {
      rFrameStr = (SpiceChar *) rframe;
   }
   else
   {
      rFrameStr = (SpiceChar *) blankStr;
   }
   
   /*
   Call the f2c'd Fortran routine. Use explicit type casts for every
   type defined by f2c.
   */
   fovray_ ( (char         *) inst,
             (doublereal   *) raydir,
             (char         *) rFrameStr,
             (char         *) abcorr,
             (char         *) observer,
             (doublereal   *) et,
             (logical      *) visible,
             (ftnlen        ) strlen(inst),
             (ftnlen        ) strlen(rframe),
             (ftnlen        ) strlen(abcorr),
             (ftnlen        ) strlen(observer)  );

   chkout_c ( "fovray_c" );
 

} /* End fovray_c */