Ejemplo n.º 1
0
static void getsgiheader(struct sgiheader *head, FILE *fp) {
    head->magic = getshort(fp);
    head->format = getc(fp);
    head->bpc = getc(fp);
    head->dim = getshort(fp);
    head->width = getshort(fp);
    head->height = getshort(fp);
    head->chans = getshort(fp);
    head->pixmin = getlong(fp);
    head->pixmax = getlong(fp);
    fread(head->dummy,sizeof(head->dummy),1,fp);
    fread(head->imagename,sizeof(head->imagename),1,fp);
    head->colormap = getlong(fp);
    fread(head->pad,sizeof(head->pad),1,fp);
}
Ejemplo n.º 2
0
void
three_coord_out(FILE *fp, fastf_t *m)
{
    point_t	p1;
    short	p2[3];

    p1[0] = getshort(fp);	/* get X */
    p1[1] = getshort(fp);	/* and Y */
    p1[2] = getshort(fp);	/* and Z */

    MAT4X3PNT( p2, m, p1 );

    putsi(p2[0]);		/* put X */
    putsi(p2[1]);		/* and Y */
    putsi(p2[2]);		/* and Z */
}
Ejemplo n.º 3
0
/** 
 * 
 * 
 * @param input 
 * @param filename 
 */
void do_ppt(FILE *input,char *filename) {
	int itemsread=1;
	int rectype;
	long reclen;
	unsigned char recbuf[8];

	while(itemsread) {
		itemsread = catdoc_read(recbuf, 1, 8, input);
/* 		fprintf(stderr,"itemsread=%d: ",itemsread); */
/* 		for(i=0; i<8; i++) */
/* 			fprintf(stderr,"%02x ",recbuf[i]); */
/* 		fprintf(stderr,"\n"); */
		
		if (catdoc_eof(input)) {
			process_item(DOCUMENT_END,0,input);
			return;
		}
		if(itemsread < 8)
			break;
		rectype=getshort(recbuf,2);
		reclen=getulong(recbuf,4);
		if (reclen < 0) {
			return;
		}	
		process_item(rectype,reclen,input);
	}
}
Ejemplo n.º 4
0
long getvalue()
{
    unsigned char ch;
    char c;
    short s;

    ch = getbyte();
    if (ch < 128) {
        return (ch);
    }
    switch (ch & 0xff) {
        case OLF_STRING:
            s = getbyte();
            dump_hex(s, true);
            return (0);

        case OLF_1_SIGNED:
                // Fix for vax compiler bug, doesn't cast procedure return
                // values correctly

            c = getbyte();
            return (c);

        case OLF_2_SIGNED:
            s = getshort();
            return (s);

        case OLF_2_UNSIGNED:
            return (getshort() & 0xffff);

        case OLF_4_UNSIGNED:
        case OLF_4_SIGNED:
            return (getlong());

        case OLF_8_UNSIGNED:
        case OLF_8_SIGNED:
            StdOutPuts(L"??? 8 byte values not handled presently\n");
            dump_hex(8, true);
            return(0);

        default:
            ty_error(ch, L"Expecting numeric leaf");
            return (0);
    }
}
Ejemplo n.º 5
0
void DumpCobL0 (BYTE level)
{
    WORD  NameAlg = getshort();

    StdOutPrintf(L"\tLevel = %02d ", level);
    StdOutPrintf(L"root = \"%S\"", getstring());
    dump_hex((Leaf_bytes - Leaf_pos), true);
    StdOutPuts(L"\n");
}
Ejemplo n.º 6
0
void
outshort(int n)
{
    int i;

    for (i = 0; i < n; i++) {
	(void)getshort();
    }
}
Ejemplo n.º 7
0
void
NetDifficulty::Unpacketize(uint16 id, uint8* buf, uint16 size)
{
	Assert(buf[0] == 'G' && buf[1] == 'D');
	PLAYER_INDEX pidx = (PLAYER_INDEX)getshort(&buf[2]);
	
	Assert(pidx < k_MAX_PLAYERS);
	Assert(g_player[pidx] != NULL);

	*g_player[pidx]->m_difficulty = *(Difficulty*)&buf[4];
}
Ejemplo n.º 8
0
Archivo: sgilib.c Proyecto: Minoos/gimp
int
sgiGetRow(sgi_t          *sgip,	/* I - SGI image */
          unsigned short *row,	/* O - Row to read */
          int            y,	/* I - Line to read */
          int            z)	/* I - Channel to read */
{
  int	x;		/* X coordinate */
  long	offset;		/* File offset */


  if (sgip == NULL ||
      row == NULL ||
      y < 0 || y >= sgip->ysize ||
      z < 0 || z >= sgip->zsize)
    return (-1);

  switch (sgip->comp)
  {
    case SGI_COMP_NONE :
       /*
        * Seek to the image row - optimize buffering by only seeking if
        * necessary...
        */

        offset = 512 + (y + z * sgip->ysize) * sgip->xsize * sgip->bpp;
        if (offset != ftell(sgip->file))
          fseek(sgip->file, offset, SEEK_SET);

        if (sgip->bpp == 1)
        {
          for (x = sgip->xsize; x > 0; x --, row ++)
            *row = getc(sgip->file);
        }
        else
        {
          for (x = sgip->xsize; x > 0; x --, row ++)
            *row = getshort(sgip);
        };
        break;

    case SGI_COMP_RLE :
        offset = sgip->table[z][y];
        if (offset != ftell(sgip->file))
          fseek(sgip->file, offset, SEEK_SET);

        if (sgip->bpp == 1)
          return (read_rle8(sgip, row, sgip->xsize));
        else
          return (read_rle16(sgip, row, sgip->xsize));
        break;
  };

  return (0);
}
Ejemplo n.º 9
0
unsigned short getindex()
{
    unsigned char ch;

    ch = getbyte();

    if (ch != OLF_INDEX) {
        ty_error(ch, L"Expecting index leaf");
    }

    return(getshort());
}
Ejemplo n.º 10
0
Archivo: zip.c Proyecto: ccxvii/mio
static unsigned char *read_zip_file(FILE *file, int offset, int *sizep)
{
	int sig, method, csize, usize;
	int namelength, extralength;
	char *cdata, *udata;

	fseek(file, offset, 0);

	sig = getlong(file);
	if (sig != ZIP_LOCAL_FILE_SIG) {
		warn("zip: wrong signature for local file");
		return NULL;
	}

	(void) getshort(file); /* version */
	(void) getshort(file); /* general */
	method = getshort(file);
	(void) getshort(file); /* file time */
	(void) getshort(file); /* file date */
	(void) getlong(file); /* crc-32 */
	csize = getlong(file); /* csize */
	usize = getlong(file); /* usize */
	namelength = getshort(file);
	extralength = getshort(file);

	fseek(file, namelength + extralength, 1);

	if (method == 0 && csize == usize) {
		cdata = malloc(csize);
		fread(cdata, 1, csize, file);
		*sizep = csize;
		return (unsigned char*) cdata;
	}

	if (method == 8) {
		cdata = malloc(csize);
		fread(cdata, 1, csize, file);
		udata = malloc(usize);
		usize = stbi_zlib_decode_noheader_buffer(udata, usize, cdata, csize);
		free(cdata);
		if (usize < 0) {
			warn("zip: %s", stbi_failure_reason());
			return NULL;
		}
		*sizep = usize;
		return (unsigned char*) udata;
	}

	warn("zip: unknown compression method");
	return NULL;
}
Ejemplo n.º 11
0
void
MBR_parse(struct disk *disk, struct dos_mbr *dos_mbr, off_t offset,
    off_t reloff, struct mbr *mbr)
{
	int i;

	memcpy(mbr->code, dos_mbr->dmbr_boot, sizeof(mbr->code));
	mbr->offset = offset;
	mbr->reloffset = reloff;
	mbr->signature = getshort(&dos_mbr->dmbr_sign);

	for (i = 0; i < NDOSPART; i++)
		PRT_parse(disk, &dos_mbr->dmbr_parts[i], offset, reloff,
		    &mbr->part[i]);
}
Ejemplo n.º 12
0
static void
rt_uplot_get_args(FILE *fp, const struct uplot *up, char *carg, fastf_t *arg)
{
    size_t ret;
    int i, j;
    int cc = 0;
    char inbuf[SIZEOF_NETWORK_DOUBLE] = {'\0', '\0', '\0', '\0', '\0', '\0', '\0', '\0'};

    for (i = 0; i < up->narg; i++) {
	switch (up->targ) {
	    case TSHORT:
		arg[i] = getshort(fp);
		break;
	    case TIEEE:
	    {
		double scan;
		ret = fread(inbuf, SIZEOF_NETWORK_DOUBLE, 1, fp);
		if (ret != 1)
		    bu_log("WARNING: uplot read failure\n");
		ntohd((unsigned char *)&scan, (unsigned char *)inbuf, 1);
		arg[i] = scan; /* convert double to fastf_t */
		break;
	    }
	    case TSTRING:
		j = 0;
		while (!feof(fp) &&
		       (cc = getc(fp)) != '\n')
		    carg[j++] = cc;
		carg[j] = '\0';
		break;
	    case TCHAR:
		cc = getc(fp);
		if (cc == EOF)
		    return;

		carg[i] = cc;
		arg[i] = 0;
		break;
	    case TNONE:
	    default:
		arg[i] = 0;	/* ? */
		break;
	}
    }
}
Ejemplo n.º 13
0
static int readheaderttf(FILE *pcl,struct ttf_header *hdr) {
    int i;
    int seg_id, seg_size;

    hdr->scale_factor = getshort(pcl);
    hdr->mupos = (short) getshort(pcl);
    hdr->muthick = getshort(pcl);
    hdr->fontscaletech = getc(pcl);
    hdr->variety = getc(pcl);

    if ( hdr->fd_size<72 || hdr->header_format!=15 ) {
	fprintf( stderr, "%s is not a PCL truetype font\n", hdr->fontname );
return( false );
    }
    /* Manual says there font descriptor size is at least 72, but no indication */
    /*  given about what these variable data might contain. The examples I've */
    /*  been given have the fd_size==72 */
    for ( i=0 ; i<hdr->fd_size-72; ++i )
	getc(pcl);

    for (;;) {
	seg_id = getshort(pcl);
	seg_size = getshort(pcl);
	if ( seg_id == (('C'<<8)|'P') ) {
	    hdr->copyright = malloc(seg_size+1);
	    fread(hdr->copyright,1,seg_size,pcl);
	    hdr->copyright[seg_size] = '\0';
	} else if ( seg_id == (('C'<<8)|'C') ) {
	    if ( seg_size==8 )
		fread(hdr->charcompl,1,8,pcl);
	    else
		fseek(pcl,seg_size,SEEK_CUR);
	} else if ( seg_id == (('P'<<8)|'A') ) {
	    if ( seg_size==10 )
		fread(hdr->panose,1,10,pcl);
	    else
		fseek(pcl,seg_size,SEEK_CUR);
	} else if ( seg_id == (('G'<<8)|'T') ) {
	    readttftables(pcl,hdr,seg_size);
	} else if ( seg_id == 0xffff || seg_id==EOF ) {
	    getshort(pcl);
    break;
	} else
	    fseek(pcl,seg_size,SEEK_CUR);
    }
    if ( !hasRequiredTables(hdr)) {
	fprintf( stderr, "%s is missing a required ttf table\n", hdr->fontname );
return( false );
    }

return( slurpglyphs(pcl,hdr));
}
Ejemplo n.º 14
0
void Archive::Open(IO::Stream* stream)
{
	m_p->m_stream = stream;

	TRY
	{
		uint32 signature;
		while ((signature = getint32()) == 0x04034b50)
		{
			File* file = new File(this);

			file->m_bytepos = m_p->m_stream->GetPosition();

			uint16 version_needed_to_extract = getshort();//       2 bytes
			uint16 general_purpose_bit_flag = getshort();//        2 bytes
			file->m_compression_method = getshort();//              2 bytes
			uint16 last_mod_file_time = getshort();//              2 bytes
			uint16 last_mod_file_date = getshort();//              2 bytes
			file->m_crc_32 = getint32();//                          4 bytes
			file->m_compressed_size = getint32();//                 4 bytes
			file->m_uncompressed_size = getint32();//               4 bytes
			uint16 file_name_length = getshort();//                2 bytes
			uint16 extra_field_length = getshort();//              2 bytes

			file->m_name = String(string_alloc<char>(file_name_length));
			m_p->m_stream->Read(file->m_name.GetData8(), file_name_length);

			m_p->m_stream->Seek(extra_field_length, IO::STREAM_SEEK_CUR);

			file->m_dataoffset = m_p->m_stream->GetPosition() - file->m_bytepos;
			m_p->m_stream->Seek(file->m_compressed_size, IO::STREAM_SEEK_CUR);

			m_p->m_filesByName[file->m_name] = file;
			m_p->m_files.push_back(file);
		}

		while (signature == 0x02014b50)
		{
			signature = getint32();
		}
	}
	CATCH (Exception* e)
	{
	}
}
Ejemplo n.º 15
0
void
getmaze(TCPsocket sock)
{
   Uint16 n;
   int recv;

   switch (n = getshort(sock))
   {
      case MAZE_MAGIC:
         break;
      case SRV_BUSY:
         fprintf(stderr, "Game is already going on :(\n");
         exit(EXIT_FAILURE);
      default:
         fprintf(stderr, "Bad magic number from server: %x\n", n);
         exit(EXIT_FAILURE);
   }

   MAZE.w = getint(sock);
   MAZE.size = getint(sock);
   MAZE.h = MAZE.size / MAZE.w;

#ifdef _DEBUG
   printf("[DEBUG] maze w size h = %ld %ld %ld\n", MAZE.w, MAZE.size, MAZE.h);
#endif

   MAZE.data = malloc(MAZE.size);

   // uh no
   if ((recv = recvall(sock, MAZE.data, MAZE.size)) != MAZE.size)
   {
      fprintf(stderr, "Failed to get maze. Got %d bytes, expected %ld. %s\n",
            recv, MAZE.size, SDLNet_GetError());
      exit(EXIT_FAILURE);
   }

   sendshort(sock, MAZE_MAGIC);     /* Confirmation reply */

}
Ejemplo n.º 16
0
/** \brief Read pixel data from an SGI .rgb image.
 *
 *  Reads an .rgb file, allocates memory for the pixels
 *  and sets *w and *h to image width and height.
 *
 *  \param name file name
 *  \param w will be set to image width
 *  \param h will be set to image height
 *  \return pointer to the pixel data or NULL on error
 */
unsigned char * read_rgbimage(const char *name, int *w, int *h)
{
  unsigned char *image, *temp;
  FILE *image_in;
  unsigned char input_char;
  unsigned short int input_short;
  unsigned char header[512];
  unsigned long int loop;

  if ( (image_in = fopen(name, "rb")) == NULL)
  {
    printf("%s\n", name);
    std::string s = "read_rgbimage: Unable to open ";
    s += name;
    perror(s.c_str());
    return NULL;
  }
  input_short=getshort(image_in);
  if (input_short == 0x01da)
  {
    input_char=getrgbchar(image_in);
    if (input_char == 0)
    {
      input_char=getrgbchar(image_in);
      input_short=getshort(image_in);
      if (input_short == 3)
      {
        input_short=getshort(image_in);
        *w=input_short;
        input_short=getshort(image_in);
        *h=input_short;
        image=(unsigned char*)malloc(*w * *h *4 *sizeof(unsigned char));
        temp=(unsigned char*)malloc(*w * *h *sizeof(unsigned char));
        if ((image == NULL) || (temp == NULL))
        {
          fprintf(stderr, "Error allocating memory for %s\n", name);
          // just in case one of the two was malloc'ed correctly:
          free(image);
          free(temp);
          return NULL;
        }
        input_short=getshort(image_in);
        if (input_short == 4)
        {
          (void)fread(header,sizeof(unsigned char),500,image_in);
          (void)fread(temp, sizeof image[0], *w * *h, image_in);
          for (loop=0;loop<(unsigned long int)(*w * *h);loop++)
          {
            image[loop*4+0]=temp[loop];
          }
          (void)fread(temp, sizeof image[0], *w * *h, image_in);
          for (loop=0;loop<(unsigned long int)(*w * *h);loop++)
          {
            image[loop*4+1]=temp[loop];
          }
          (void)fread(temp, sizeof image[0], *w * *h, image_in);
          for (loop=0;loop<(unsigned long int)(*w * *h);loop++)
          {
            image[loop*4+2]=temp[loop];
          }
          (void)fread(temp, sizeof image[0], *w * *h, image_in);
          for (loop=0;loop<(unsigned long int)(*w * *h);loop++)
          {
            image[loop*4+3]=temp[loop];
          }
          free(temp);
          return image;
        }
        else
        {
          std::string s = "Error loading texture ";
          s += name;
          s += ":\nThis file isn't a 4 channel RGBA file.";
          fprintf(stderr, "%s\n", s.c_str());
          return NULL;
        }
      }
      else
      {
        std::string s = "Error loading texture ";
        s += name;
        s += ":\nNot a useable RGB file.";
        fprintf(stderr, "%s\n", s.c_str());
        return NULL;
      }
    }
    else
    {
      std::string s = "Error loading texture ";
      s += name;
      s += ":\nRLE encoded SGI files are not supported.";
      fprintf(stderr, "%s\n", s.c_str());
      return NULL;
    }
  }
  else
  {
    std::string s = "Error loading texture ";
    s += name;
    s += ":\nFile doesn't appear to be an SGI rgb file!";
    fprintf(stderr, "%s\n", s.c_str());
    return NULL;
  }
  return NULL;
}
Ejemplo n.º 17
0
static int readheaderformat(FILE *pcl,struct ttf_header *hdr) {
    int ch, i;

    memset(hdr,0,sizeof(*hdr));

    fscanf(pcl,"%d", &hdr->header_size );
    ch = getc(pcl);
    if ( ch!='W' ) {
	fprintf( stderr, "Bad font, font header command doesn't end in \"W\"\n" );
return( false );
    }
    hdr->fd_size = getshort(pcl);
    hdr->header_format = getc(pcl);
    hdr->fonttype = getc(pcl);
    hdr->style = getc(pcl)<<8;
    (void) getc(pcl);
    hdr->baseline_pos = getshort(pcl);
    hdr->cell_width = getshort(pcl);
    hdr->cell_height = getshort(pcl);
    hdr->orientation = getc(pcl);
    hdr->spacing = getc(pcl);
    hdr->symbol_set = getshort(pcl);
    hdr->pitch = getshort(pcl);
    hdr->height = getshort(pcl);
    hdr->xheight = getshort(pcl);
    hdr->widthtype = getc(pcl);
    hdr->style |= getc(pcl);
    hdr->strokeweight = getc(pcl);
    hdr->typeface = getc(pcl);
    hdr->typeface |= getc(pcl)<<8;
    hdr->serifstyle = getc(pcl);
    hdr->quality = getc(pcl);
    hdr->placement = getc(pcl);
    hdr->upos = getc(pcl);
    hdr->uthick = getc(pcl);
    hdr->textheight = getshort(pcl);
    hdr->textwidth = getshort(pcl);
    hdr->firstcode = getshort(pcl);
    hdr->num_chars = getshort(pcl);
    hdr->pitchx = getc(pcl);
    hdr->heightx = getc(pcl);
    hdr->capheight = getshort(pcl);
    hdr->fontnumber = getlong(pcl);
    for ( i=0; i<16; ++i )
	hdr->fontname[i] = getc(pcl);
    while ( i>1 && hdr->fontname[i-1]==' ' ) --i;
    hdr->fontname[i] = '\0';
return( false );
}
Ejemplo n.º 18
0
static int slurpglyph(FILE *pcl,struct ttf_header *hdr, int slot) {
    int unicode, size, ch;
    int desc_size, i;
    int cd_size;
    int glyph_start;
    int restart = ftell(pcl);

    if ( !skip2charcode(pcl)) {
	fprintf( stderr, "Fewer glyphs in font than expected\n" );
	fseek(pcl,restart,SEEK_SET);
return( false );
    }
    fscanf(pcl,"%d", &unicode );
    ch = getc(pcl);
    if ( ch!='E' ) {
	fprintf( stderr, "Fewer glyphs in font than expected\n" );
	fseek(pcl,restart,SEEK_SET);
return( false );
    }

    if ( !skip2glyph(pcl))
return( false );
    fscanf(pcl,"%d", &size );
    ch = getc(pcl);
    if ( ch!='W' ) {
	fprintf( stderr, "Bad font, glyph size does not end in \"W\"\n" );
return( false );
    }
    glyph_start = ftell(pcl);

    if ( getc(pcl)!=15 ) {
	fprintf( stderr, "Bad font, glyph format must be 15\n" );
return( false );
    }
    if ( getc(pcl)!=0 ) {
	fprintf( stderr, "Bad font, continuation may not be specified here\n" );
return( false );
    }
    desc_size = getc(pcl);
    if ( getc(pcl)!=15 ) {
	fprintf( stderr, "Bad font, glyph class must be 15\n" );
return( false );
    }
    for ( i=2; i<desc_size; ++i )
	getc(pcl);
    cd_size = getshort(pcl);
    hdr->glyphs[slot].glyph = getshort(pcl);
    hdr->glyphs[slot].unicode = unicode;
    hdr->glyphs[slot].len = cd_size-4;
    hdr->glyphs[slot].offset = ftell(pcl);
    hdr->glyphs[slot].continuation = NULL;

    fseek(pcl,glyph_start+size,SEEK_SET);
    if ( size<cd_size+4+desc_size ) {
	/* The docs only allow for one continuation glyph */
	if ( !skip2glyph(pcl))
return( false );
	fscanf(pcl,"%d", &size );
	ch = getc(pcl);
	if ( ch!='W' ) {
	    fprintf( stderr, "Bad font, glyph size does not end in \"W\"\n" );
return( false );
	}
	if ( getc(pcl)!=15 ) {
	    fprintf( stderr, "Bad font, glyph format must be 15\n" );
return( false );
	}
	if ( getc(pcl)!=1 ) {
	    fprintf( stderr, "Bad font, continuation must be specified here\n" );
return( false );
	}
	hdr->glyphs[slot].continuation = calloc(1,sizeof(struct glyph));
	hdr->glyphs[slot].continuation->offset = ftell(pcl);
	hdr->glyphs[slot].continuation->len = size-4;
	fseek(pcl,size-2,SEEK_CUR);
    }
return( true );
}
Ejemplo n.º 19
0
float raster_contagion ()
{
	int	*adj,*carea;
	int	edgeval;
	int	size;
	float	sum,contagion,prop1,prop2;
	short	i,j,n;
	short	value,neighbor;
	short	xptr,yptr;
	

/*
 *  Get a clean copy of the image.
 */
	read_image(0);

/*
 *  Allocate space for needed variables.
 */
	size = max_class - min_class + 1;

	adj = (int *) calloc ((unsigned)size,sizeof(int));
	if (adj == NULL) {
	   printf ("\nERROR! rascont: Can not allocate space for adj!");
	   exit(-1);
	}
	carea = (int *) calloc ((unsigned)size,sizeof(int));
	if (carea == NULL) {
	   printf ("\nERROR! rascont: Can not allocate space for carea!");
	   exit(-1);
	}

/*
 *  Initialize
 */
	for (i=0; i < size; i++) {
	   carea[i] = 0;
	   adj[i] = 0;
	   for(j=0; j < size; j++) 
	      setint(edge,num_wt,i,j,0);
	}


/*
 *  Step through all cells in the image 
 */

	for (i=0; i < num_rows; i++) {
	   for (j=0; j < num_cols; j++) {
	      value = getshort(image,num_cols,i,j);
	      if (value < 0) continue;

/*
 *  Get the area of each class.
 */
	      carea[value-min_class] ++;

/*
 *  Look at this values 4 neighbors ....
 */
	      for (n=0; n < 4; n++) {
                 xptr = j + xpos[n];
                 if (xptr < 0 || xptr >= num_cols) continue;
                 yptr = i + ypos[n];
                 if (yptr < 0 || yptr >= num_rows) continue;
 
		 neighbor = getshort(image,num_cols,yptr,xptr);

/*
 *  If the neighbor is within the landscape (value >=0), 
 *  increment the count of its patchtype, and increment the
 *  count of the number of this edge type combo.
 */
		 if (neighbor >= 0) {
		    adj[value-min_class] ++;
		    edgeval = getint(edge,num_wt,value-min_class,
			neighbor-min_class);
		    edgeval ++;
		    setint(edge,num_wt,value-min_class,neighbor-min_class,
			edgeval);
		 }
	      }
	   }
	}

/*
 *  Loop over all classes
 */
	sum = 0.0;
	for (i=0; i < size; i++) {
	   if (carea[i] == 0.0) continue;

/* 
 *  Get the proportion of the landscape in this class.
 */
	   prop1 = (float)carea[i] / (float)total_size;

/*
 *  Look for adjacencies with other classes.
 */
	   for (j=0; j < size; j++) {
	      edgeval = getint(edge,num_wt,i,j);
	      if (edgeval > 0) {
	         prop2 = (float)edgeval / (float)adj[i];
		 sum += (prop1 * prop2) * log(prop1 * prop2);
	      }
	   }
	}

/*
 *  Calculate contagion.
 */
	contagion = (sum / (2.0 * log((double)total_num_classes))) + 1.0;

	free (adj);
	free (carea);

	return (contagion);
}
Ejemplo n.º 20
0
/** 
 * Initializes ole structure
 * 
 * @param f (FILE *) compound document file, positioned at bufSize
 *           byte. Might be pipe or socket 
 * @param buffer (void *) bytes already read from f
 * @param bufSize number of bytes already read from f should be less
 *                than 512 
 * 
 * @return 
 */
FILE* ole_init(FILE *f, void *buffer, size_t bufSize)  {
	unsigned char oleBuf[BBD_BLOCK_SIZE];
	unsigned char *tmpBuf;
	FILE *newfile;
	int ret=0, i;
	long int sbdMaxLen, sbdCurrent, propMaxLen, propCurrent, mblock, msat_size;
	oleEntry *tEntry;

	/* deleting old data (if it was allocated) */
	ole_finish();
	
	if (fseek(f,0,SEEK_SET) == -1) {
		if ( errno == ESPIPE ) {
			/* We got non-seekable file, create temp file */
			if((newfile=tmpfile()) == NULL) {
				perror("Can't create tmp file");
				return NULL;
			}
			if (bufSize > 0) {
				ret=fwrite(buffer, 1, bufSize, newfile);
				if(ret != bufSize) {
					perror("Can't write to tmp file");
					return NULL;
				}
			}
			
			while(!feof(f)){
				ret=fread(oleBuf,1,BBD_BLOCK_SIZE,f);
				fwrite(oleBuf, 1, ret, newfile);
			}
			fseek(newfile,0,SEEK_SET);
		} else {
			perror("Can't seek in file");
			return NULL;
		}
	} else {
		newfile=f;
	}	
	fseek(newfile,0,SEEK_END);
	fileLength=ftell(newfile);
/* 	fprintf(stderr, "fileLength=%ld\n", fileLength); */
	fseek(newfile,0,SEEK_SET);
	ret=fread(oleBuf,1,BBD_BLOCK_SIZE,newfile);
	if ( ret != BBD_BLOCK_SIZE ) {
		return NULL;
	}
	if (strncmp(oleBuf,ole_sign,8) != 0) {
		return NULL;
	}
 	sectorSize = 1<<getshort(oleBuf,0x1e);
	shortSectorSize=1<<getshort(oleBuf,0x20);
	
/* Read BBD into memory */
	bbdNumBlocks = getulong(oleBuf,0x2c);
	if((BBD=malloc(bbdNumBlocks*sectorSize)) == NULL ) {
		return NULL;
	}
	
	if((tmpBuf=malloc(MSAT_ORIG_SIZE)) == NULL ) {
		return NULL;
	}
	memcpy(tmpBuf,oleBuf+0x4c,MSAT_ORIG_SIZE);
	mblock=getlong(oleBuf,0x44);
	msat_size=getlong(oleBuf,0x48);

/* 	fprintf(stderr, "msat_size=%ld\n", msat_size); */

	i=0;
	while((mblock >= 0) && (i < msat_size)) {
		unsigned char *newbuf;
/* 		fprintf(stderr, "i=%d mblock=%ld\n", i, mblock); */
		if ((newbuf=realloc(tmpBuf, sectorSize*(i+1)+MSAT_ORIG_SIZE)) != NULL) {
			tmpBuf=newbuf;
		} else {
			perror("MSAT realloc error");
			free(tmpBuf);
			ole_finish();
			return NULL;
		}
		
		fseek(newfile, 512+mblock*sectorSize, SEEK_SET);
		if(fread(tmpBuf+MSAT_ORIG_SIZE+(sectorSize-4)*i,
						 1, sectorSize, newfile) != sectorSize) {
			fprintf(stderr, "Error read MSAT!\n");
			ole_finish();
			return NULL;
		}

		i++;
		mblock=getlong(tmpBuf, MSAT_ORIG_SIZE+(sectorSize-4)*i);
	}
	
/* 	fprintf(stderr, "bbdNumBlocks=%ld\n", bbdNumBlocks); */
	for(i=0; i< bbdNumBlocks; i++) {
		long int bbdSector=getlong(tmpBuf,4*i);
		
		if (bbdSector >= fileLength/sectorSize || bbdSector < 0) {
			fprintf(stderr, "Bad BBD entry!\n");
			ole_finish();
			return NULL;
		}
		fseek(newfile, 512+bbdSector*sectorSize, SEEK_SET);
		if ( fread(BBD+i*sectorSize, 1, sectorSize, newfile) != sectorSize ) {
			fprintf(stderr, "Can't read BBD!\n");
			free(tmpBuf);
			ole_finish();
			return NULL;
		}
	}
	free(tmpBuf);
	
/* Read SBD into memory */
	sbdLen=0;
	sbdMaxLen=10;
	sbdCurrent = sbdStart = getlong(oleBuf,0x3c);
	if (sbdStart > 0) {
		if((SBD=malloc(sectorSize*sbdMaxLen)) == NULL ) {
			ole_finish();
			return NULL;
		}
		while(1) {
			fseek(newfile, 512+sbdCurrent*sectorSize, SEEK_SET);
			fread(SBD+sbdLen*sectorSize, 1, sectorSize, newfile);
			sbdLen++;
			if (sbdLen >= sbdMaxLen) {
				unsigned char *newSBD;
				
				sbdMaxLen+=5;
				if ((newSBD=realloc(SBD, sectorSize*sbdMaxLen)) != NULL) {
					SBD=newSBD;
				} else {
					perror("SBD realloc error");
					ole_finish();
					return NULL;
				}
			}
			sbdCurrent = getlong(BBD, sbdCurrent*4);
			if(sbdCurrent < 0 ||
				sbdCurrent >= fileLength/sectorSize)
				break;
		}
		sbdNumber = (sbdLen*sectorSize)/shortSectorSize;
/*   		fprintf(stderr, "sbdLen=%ld sbdNumber=%ld\n",sbdLen, sbdNumber); */
	} else {
		SBD=NULL;
	}
/* Read property catalog into memory */
	propLen = 0;
	propMaxLen = 5;
	propCurrent = propStart = getlong(oleBuf,0x30);
	if (propStart >= 0) {
		if((properties=malloc(propMaxLen*sectorSize)) == NULL ) {
			ole_finish();
			return NULL;
		}
		while(1) {
/*  			fprintf(stderr, "propCurrent=%ld\n",propCurrent); */
			fseek(newfile, 512+propCurrent*sectorSize, SEEK_SET);
			fread(properties+propLen*sectorSize,
				  1, sectorSize, newfile);
			propLen++;
			if (propLen >= propMaxLen) {
				unsigned char *newProp;
				
				propMaxLen+=5;
				if ((newProp=realloc(properties, propMaxLen*sectorSize)) != NULL)
					properties=newProp;
				else {
					perror("Properties realloc error");
					ole_finish();
					return NULL;
				}
			}
			
			propCurrent = getlong(BBD, propCurrent*4);
			if(propCurrent < 0 ||
			   propCurrent >= fileLength/sectorSize ) {
				break;
			}
		}
/*  		fprintf(stderr, "propLen=%ld\n",propLen); */
		propNumber = (propLen*sectorSize)/PROP_BLOCK_SIZE;
		propCurNumber = 0;
	} else {
		ole_finish();
		properties = NULL;
		return NULL;
	}
	
	
/* Find Root Entry */
	while((tEntry=(oleEntry*)ole_readdir(newfile)) != NULL) {
		if (tEntry->type == oleRootDir ) {
			rootEntry=tEntry;
			break;
		}
		ole_close((FILE*)tEntry);
	}
	propCurNumber = 0;
	fseek(newfile, 0, SEEK_SET);
	if (!rootEntry) {
		fprintf(stderr,"Broken OLE structure. Cannot find root entry in this file!\n");		ole_finish();
		return NULL;
	}	
	return newfile;
}
Ejemplo n.º 21
0
/** 
 * Reads next directory entry from file
 * 
 * @param name buffer for name converted to us-ascii should be at least 33 chars long
 * @param size size of file 
 * 
 * @return 0 if everything is ok -1 on error
 */
FILE *ole_readdir(FILE *f) {
	int i, nLen;
	unsigned char *oleBuf;
	oleEntry *e=NULL;
	long int chainMaxLen, chainCurrent;
	
	if ( properties == NULL || propCurNumber >= propNumber || f == NULL )
		return NULL;
	oleBuf=properties + propCurNumber*PROP_BLOCK_SIZE;
	if( !rightOleType(oleBuf))
		return NULL;
	if ((e = (oleEntry*)malloc(sizeof(oleEntry))) == NULL) {
		perror("Can\'t allocate memory");
		return NULL;
	}
	e->dirPos=oleBuf;
	e->type=getOleType(oleBuf);
	e->file=f;
	e->startBlock=getlong(oleBuf,0x74);
	e->blocks=NULL;
	
	nLen=getshort(oleBuf,0x40);
	for (i=0 ; i < nLen /2; i++)
		e->name[i]=(char)oleBuf[i*2];
	e->name[i]='\0';
	propCurNumber++;
	e->length=getulong(oleBuf,0x78);
/* Read sector chain for object */
	chainMaxLen = 25;
	e->numOfBlocks = 0;
	chainCurrent = e->startBlock;
	e->isBigBlock = (e->length >= 0x1000) || !strcmp(e->name, "Root Entry");
/* 	fprintf(stderr, "e->name=%s e->length=%ld\n", e->name, e->length); */
/* 	fprintf(stderr, "e->startBlock=%ld BBD=%p\n", e->startBlock, BBD); */
	if (e->startBlock >= 0 &&
		e->length >= 0 &&
		(e->startBlock <=
		 fileLength/(e->isBigBlock ? sectorSize : shortSectorSize))) {
		if((e->blocks=malloc(chainMaxLen*sizeof(long int))) == NULL ) {
			return NULL;
		}
		while(1) {
/* 			fprintf(stderr, "chainCurrent=%ld\n", chainCurrent); */
			e->blocks[e->numOfBlocks++] = chainCurrent;
			if (e->numOfBlocks >= chainMaxLen) {
				long int *newChain;
				chainMaxLen+=25;
				if ((newChain=realloc(e->blocks,
									  chainMaxLen*sizeof(long int))) != NULL)
					e->blocks=newChain;
				else {
					perror("Properties realloc error");
					free(e->blocks);
					e->blocks=NULL;
					return NULL;
				}
			}
			if ( e->isBigBlock ) {
				chainCurrent = getlong(BBD, chainCurrent*4);
			} else if ( SBD != NULL ) {
				chainCurrent = getlong(SBD, chainCurrent*4);
			} else {
				chainCurrent=-1;
			}
			if(chainCurrent <= 0 ||
			   chainCurrent >= ( e->isBigBlock ?
								 ((bbdNumBlocks*sectorSize)/4)
								 : ((sbdNumber*shortSectorSize)/4) ) ||
			   (e->numOfBlocks >
				e->length/(e->isBigBlock ? sectorSize : shortSectorSize))) {
/*   				fprintf(stderr, "chain End=%ld\n", chainCurrent);   */
				break;
			}
		}
	}
	
	if(e->length > (e->isBigBlock ? sectorSize : shortSectorSize)*e->numOfBlocks)
		e->length = (e->isBigBlock ? sectorSize : shortSectorSize)*e->numOfBlocks;
/* 	fprintf(stderr, "READDIR: e->name=%s e->numOfBlocks=%ld length=%ld\n", */
/* 					e->name, e->numOfBlocks, e->length); */
	
	return (FILE*)e;
}
Ejemplo n.º 22
0
Archivo: mucbz.c Proyecto: UIKit0/mupdf
static unsigned char *
cbz_read_zip_entry(cbz_document *doc, int offset, int *sizep)
{
	fz_context *ctx = doc->ctx;
	fz_stream *file = doc->file;
	int sig, method, namelength, extralength;
	unsigned long csize, usize;
	unsigned char *cdata;
	int code;

	fz_seek(file, offset, 0);

	sig = getlong(doc->file);
	if (sig != ZIP_LOCAL_FILE_SIG)
		fz_throw(ctx, "wrong zip local file signature (0x%x)", sig);

	(void) getshort(doc->file); /* version */
	(void) getshort(doc->file); /* general */
	method = getshort(doc->file);
	(void) getshort(doc->file); /* file time */
	(void) getshort(doc->file); /* file date */
	(void) getlong(doc->file); /* crc-32 */
	csize = getlong(doc->file); /* csize */
	usize = getlong(doc->file); /* usize */
	namelength = getshort(doc->file);
	extralength = getshort(doc->file);

	fz_seek(file, namelength + extralength, 1);

	cdata = fz_malloc(ctx, csize);
	fz_try(ctx)
	{
		fz_read(file, cdata, csize);
	}
	fz_catch(ctx)
	{
		fz_free(ctx, cdata);
		fz_rethrow(ctx);
	}

	if (method == 0)
	{
		*sizep = usize;
		return cdata;
	}

	if (method == 8)
	{
		unsigned char *udata = fz_malloc(ctx, usize);
		z_stream stream;

		memset(&stream, 0, sizeof stream);
		stream.zalloc = cbz_zip_alloc_items;
		stream.zfree = cbz_zip_free;
		stream.opaque = ctx;
		stream.next_in = cdata;
		stream.avail_in = csize;
		stream.next_out = udata;
		stream.avail_out = usize;

		fz_try(ctx)
		{
			code = inflateInit2(&stream, -15);
			if (code != Z_OK)
				fz_throw(ctx, "zlib inflateInit2 error: %s", stream.msg);
			code = inflate(&stream, Z_FINISH);
			if (code != Z_STREAM_END) {
				inflateEnd(&stream);
				fz_throw(ctx, "zlib inflate error: %s", stream.msg);
			}
			code = inflateEnd(&stream);
			if (code != Z_OK)
				fz_throw(ctx, "zlib inflateEnd error: %s", stream.msg);
		}
		fz_always(ctx)
		{
			fz_free(ctx, cdata);
		}
		fz_catch(ctx)
		{
			fz_free(ctx, udata);
			fz_rethrow(ctx);
		}

		*sizep = usize;
		return udata;
	}
Ejemplo n.º 23
0
int SpriteCache::initFile(const char *filnam)
{
  short vers;
  char buff[20];
  short numspri = 0;
  int vv, wdd, htt;
  long spr_initial_offs = 0;
  int spriteFileID = 0;

  for (vv = 0; vv < elements; vv++) {
    images[vv] = NULL;
    offsets[vv] = 0;
  }

  ff = clibfopen((char *)filnam, "rb");
  if (ff == NULL)
    return -1;

  spr_initial_offs = ftell(ff);

  fread(&vers, 2, 1, ff);
  // read the "Sprite File" signature
  fread(&buff[0], 13, 1, ff);

  if ((vers < 4) || (vers > 6)) {
    fclose(ff);
    ff = NULL;
    return -1;
  }

  // unknown version
  buff[13] = 0;
  if (strcmp(buff, spriteFileSig)) {
    fclose(ff);
    ff = NULL;
    return -1;
  }

  if (vers == 4)
    this->spritesAreCompressed = false;
  else if (vers == 5)
    this->spritesAreCompressed = true;
  else if (vers >= 6)
  {
    this->spritesAreCompressed = (fgetc(ff) == 1);
    spriteFileID = getw(ff);
  }

  if (vers < 5) {
    // skip the palette
    fseek(ff, 256 * 3, SEEK_CUR);
  }

  fread(&numspri, 2, 1, ff);

  if (vers < 4)
    numspri = 200;

#ifdef THIS_IS_THE_ENGINE
  // adjust the buffers to the sprite file size
  changeMaxSize(numspri + 1);
#endif

  // if there is a sprite index file, use it
  if (loadSpriteIndexFile(spriteFileID, spr_initial_offs, numspri))
  {
    // Succeeded
    return 0;
  }

  // failed, delete the index file because it's invalid
  unlink(spindexfilename);

  // no sprite index file, manually index it

  for (vv = 0; vv <= numspri; vv++) {

    offsets[vv] = ftell(ff);
    flags[vv] = 0;

    int coldep = getshort(ff);

    if (coldep == 0) {
      offsets[vv] = 0;
      images[vv] = NULL;

#ifdef THIS_IS_THE_ENGINE
      // make it a blue cup, to avoid crashes
      spritewidth[vv] = spritewidth[0];
      spriteheight[vv] = spriteheight[0];
      offsets[vv] = offsets[0];
      flags[vv] = SPRCACHEFLAG_DOESNOTEXIST;
#else
      // no sprite ... blank it out
      spritewidth[vv] = 0;
      spriteheight[vv] = 0;
      offsets[vv] = 0;
#endif

      if (feof(ff))
        break;

      continue;
    }

    if (feof(ff))
      break;

    if (vv >= elements)
      break;

    images[vv] = NULL;

    wdd = getshort(ff);
    htt = getshort(ff);

    spritewidth[vv] = wdd;
    spriteheight[vv] = htt;
    get_new_size_for_sprite(vv, wdd, htt, spritewidth[vv], spriteheight[vv]);

    long spriteDataSize;
    if (vers == 5) {
      spriteDataSize = getw(ff);
    }
    else {
      spriteDataSize = wdd * coldep * htt;
    }

    fseek(ff, spriteDataSize, SEEK_CUR);
  }

  sprite0InitialOffset = offsets[0];
  return 0;
}
Ejemplo n.º 24
0
int SpriteCache::saveToFile(const char *filnam, int lastElement, bool compressOutput)
{
  FILE *output = fopen(filnam, "wb");
  if (output == NULL)
    return -1;

  if (compressOutput) {
    // re-open the file so that it can be seeked
    fclose(output);
    output = fopen(filnam, "r+b");
    if (output == NULL)
      return -1;
  }

  int spriteFileIDCheck = (int)time(NULL);

  // version 6
  putshort(6, output);

  fwrite(spriteFileSig, strlen(spriteFileSig), 1, output);

  fputc(compressOutput ? 1 : 0, output);
  putw(spriteFileIDCheck, output);

  int i, lastslot = 0;
  if (elements < lastElement)
    lastElement = elements;

  for (i = 1; i < lastElement; i++) {
    // slot empty
    if ((images[i] != NULL) || ((offsets[i] != 0) && (offsets[i] != sprite0InitialOffset)))
      lastslot = i;
  }

  putshort(lastslot, output);

  // allocate buffers to store the indexing info
  int numsprits = lastslot + 1;
  short *spritewidths = (short*)malloc(numsprits * sizeof(short));
  short *spriteheights = (short*)malloc(numsprits * sizeof(short));
  long *spriteoffs = (long*)malloc(numsprits * sizeof(long));

  const int memBufferSize = 100000;
  char *memBuffer = (char*)malloc(memBufferSize);

  for (i = 0; i <= lastslot; i++) {

    spriteoffs[i] = ftell(output);

    // if compressing uncompressed sprites, load the sprite into memory
    if ((images[i] == NULL) && (this->spritesAreCompressed != compressOutput))
      (*this)[i];

    if (images[i] != NULL) {
      // image in memory -- write it out
      pre_save_sprite(i);
      int bpss = bitmap_color_depth(images[i]) / 8;
      spritewidths[i] = images[i]->w;
      spriteheights[i] = images[i]->h;
      putshort(bpss, output);
      putshort(spritewidths[i], output);
      putshort(spriteheights[i], output);

      if (compressOutput) {
        long lenloc = ftell(output);
        // write some space for the length data
        putw(0, output);

        compressSprite(images[i], output);

        long fileSizeSoFar = ftell(output);
        // write the length of the compressed data
        fseek(output, lenloc, SEEK_SET);
        putw((fileSizeSoFar - lenloc) - 4, output);
        fseek(output, 0, SEEK_END);
      }
      else
        fwrite(&images[i]->line[0][0], spritewidths[i] * bpss, spriteheights[i], output);

      continue;
    }

    if ((offsets[i] == 0) || ((offsets[i] == sprite0InitialOffset) && (i > 0))) {
      // sprite doesn't exist
      putshort(0, output);
      spritewidths[i] = 0;
      spriteheights[i] = 0;
      spriteoffs[i] = 0;
      continue;
    }

    // not in memory -- seek to it in the source file
    seekToSprite(i);
    lastLoad = i;

    short colDepth = getshort(ff);
    putshort(colDepth, output);

    if (colDepth == 0) {
      continue;
    }

    if (this->spritesAreCompressed != compressOutput) {
      // shouldn't be able to get here
      free(memBuffer);
      fclose(output);
      return -2;
    }

    // and copy the data across
    int width = getshort(ff);
    int height = getshort(ff);

    spritewidths[i] = width;
    spriteheights[i] = height;

    putshort(width, output);
    putshort(height, output);

    int sizeToCopy;
    if (this->spritesAreCompressed) {
      sizeToCopy = getw(ff);
      putw(sizeToCopy, output);
    }
    else {
      sizeToCopy = width * height * (int)colDepth;
    }

    while (sizeToCopy > memBufferSize) {
      fread(memBuffer, memBufferSize, 1, ff);
      fwrite(memBuffer, memBufferSize, 1, output);
      sizeToCopy -= memBufferSize;
    }

    fread(memBuffer, sizeToCopy, 1, ff);
    fwrite(memBuffer, sizeToCopy, 1, output);
  }

  free(memBuffer);

  fclose(output);

  // write the sprite index file
  FILE *ooo = fopen(spindexfilename, "wb");
  // write "SPRINDEX" id
  fwrite(&spindexid[0], strlen(spindexid), 1, ooo);
  // write version (1)
  putw(2, ooo);
  putw(spriteFileIDCheck, ooo);
  // write last sprite number and num sprites, to verify that
  // it matches the spr file
  putw(lastslot, ooo);
  putw(numsprits, ooo);
  fwrite(&spritewidths[0], sizeof(short), numsprits, ooo);
  fwrite(&spriteheights[0], sizeof(short), numsprits, ooo);
  fwrite(&spriteoffs[0], sizeof(long), numsprits, ooo);
  fclose(ooo);

  free(spritewidths);
  free(spriteheights);
  free(spriteoffs);

  return 0;
}
Ejemplo n.º 25
0
int SpriteCache::loadSprite(int index)
{

  int hh = 0;

  while (cachesize > maxCacheSize) {
    removeOldest();
    hh++;
    if (hh > 1000) {
      write_log("!!!! RUNTIME CACHE ERROR: STUCK IN FREE_UP_MEM; RESETTING CACHE");
      removeAll();
    }

  }

  if ((index < 0) || (index >= elements))
    quit("sprite cache array index out of bounds");

  // If we didn't just load the previous sprite, seek to it
  seekToSprite(index);

  int coldep = getshort(ff);

  if (coldep == 0) {
    lastLoad = index;
    return 0;
  }

  int wdd = getshort(ff);
  int htt = getshort(ff);
  // update the stored width/height
  spritewidth[index] = wdd;
  spriteheight[index] = htt;

  images[index] = create_bitmap_ex(coldep * 8, wdd, htt);
  if (images[index] == NULL) {
    offsets[index] = 0;
    return 0;
  }

  if (this->spritesAreCompressed) 
  {
    getw(ff); // skip data size
    if (coldep == 1) {
      for (hh = 0; hh < htt; hh++)
        cunpackbitl(&images[index]->line[hh][0], wdd, ff);
    }
    else if (coldep == 2) {
      for (hh = 0; hh < htt; hh++)
        cunpackbitl16((unsigned short*)&images[index]->line[hh][0], wdd, ff);
    }
    else {
      for (hh = 0; hh < htt; hh++)
        cunpackbitl32((unsigned long*)&images[index]->line[hh][0], wdd, ff);
    }
  }
  else {
    for (hh = 0; hh < htt; hh++)
      // MACPORT FIX: size and nmemb split
      fread(&images[index]->line[hh][0], coldep, wdd, ff);
  }

  lastLoad = index;

  // Stop it adding the sprite to the used list just because it's loaded
  long offs = offsets[index];
  offsets[index] = SPRITE_LOCKED;

  initialize_sprite(index);

  if (index != 0)  // leave sprite 0 locked
    offsets[index] = offs;

  // we need to store this because the main program might
  // alter spritewidth/height if it resizes stuff
  sizes[index] = spritewidth[index] * spriteheight[index] * coldep;
  cachesize += sizes[index];

#ifdef DEBUG_SPRITECACHE
  char msgg[100];
  sprintf(msgg, "Loaded %d, size now %d KB", index, cachesize / 1024);
  write_log(msgg);
#endif

  return sizes[index];
}
Ejemplo n.º 26
0
void get_sizes()
{

	short	i,j;
	short	value;
	short   min_landscape_class;
	short   max_landscape_class;
	char	*class_exists;
	char	*all_classes;
	int	*npts;
 	int	numpts;
	int	*npatches;
	int	MAX_BCKGRND_SIZE;


/*
 *  Get space for 3 arrays needed to determine NUM_CLASSES, the classes
 *  that exist, and the maximum number of patches per class.
 *  (MAX_CLASSES is set in the routines that read in the input image.)
 */

	class_exists = (char *) calloc ((unsigned)MAX_CLASSES,sizeof(char));
	if (class_exists == NULL) {
	   Rprintf ("\nERROR! Can not allocate space for class_exists!");
	   return;
	}

	all_classes = (char *) calloc ((unsigned)MAX_CLASSES,sizeof(char));
	if (all_classes == NULL) {
	   Rprintf ("\nERROR! Can not allocate space for all_classes");
	   return;
	}
	
	npatches = (int *) calloc ((unsigned)MAX_CLASSES,sizeof(int));
	if (npatches == NULL) {
	   Rprintf ("\nERROR! Can not allocate space for npatches");
	   return;
	}
	
	npts = (int *) calloc ((unsigned)MAX_CLASSES,sizeof(int));
	if (npts == NULL) {
	   Rprintf ("\nERROR! Can not allocate space for npts");
	   return;
	}


/*
 *  Initialize 
 */
	for (i=0; i < MAX_CLASSES; i++) {
	   class_exists[i] = FALSE;
	   all_classes[i] = FALSE;
	   npatches[i] = 0;
	}

	MAX_PATCH_SIZE = 0;
	MAX_BCKGRND_SIZE = 0;

/*
 *  Step through all cells in the image.
 */
	
        for (i=0; i < num_rows; i++) {
           for (j=0; j < num_cols; j++) {
	      value = getshort(image,num_cols,i,j);

/*
 *  Flag all classes that exist (must have values >= 0).
 */
	      if (value >= 0) {
	         class_exists[value] = TRUE;
		 all_classes[value] = TRUE;
	      }
/*
 *  Flag any classes in the landscape border that exist (values < 0
 *  but not background).  This is needed to compute total_num_classes
 *  used in contagion.
 */
	      if (value < 0 && value > -990 && value != -777)
		 all_classes[-value] = TRUE;

/*
 *  Find every patch in the landscape.  Keep track of the largest
 *  patch (# cells) and the number of patches per class.
 */
	      if (value >= 0) {
	         numpts = patch_size(j,i,value);
		 npts[value] += numpts;
	         if (numpts > MAX_PATCH_SIZE) MAX_PATCH_SIZE = numpts;
	         npatches[value] ++;
	      }

/*
 *  9-15-94 BJM  Changing so that it checks patch size for patches
 *  in the landscape border as well as background patches.
 */
	      else if (value < 0 && value != -777 ) {
		 numpts = patch_size (j,i,value);
		 if (numpts > MAX_BCKGRND_SIZE) MAX_BCKGRND_SIZE = numpts;
	      }

   	   }
	}


/*
 *  Now find the class that has the greatest number of patches and 
 *  save the number of patches.  This is needed to dimension arrays
 *  that hold patch level indices.  Also find the total number of 
 *  patches in the landscape, the number of classes that exist, and
 *  the total number of classes that exist (including any classes
 *  in the landscape border).
 */
	Rprintf ("\n");
	for(i=0; i < MAX_CLASSES; i++) 
	   if (class_exists[i]) Rprintf ("\nClass %5d: %9d cells, %8d patches",
		i,npts[i],npatches[i]);
	Rprintf ("\n");


	MAX_PATCHES = 0;
	NUM_CLASSES = total_num_classes = total_num_patches = 0;	
	min_landscape_class = 999;
	max_landscape_class = -999;

	for (i=0; i < MAX_CLASSES; i++) {
	   if (npatches[i] > MAX_PATCHES) MAX_PATCHES = npatches[i];
	   total_num_patches += npatches[i];
	   if (class_exists[i]) NUM_CLASSES ++;
	   if (all_classes[i]) {
	      total_num_classes ++;
	      if (i < min_landscape_class) min_landscape_class = i;
	      if (i > max_landscape_class) max_landscape_class = i;
	   }
	}

/*
 *  Allocate space for an array that will hold the values of the
 *  patch types (classes) that exist in the landscape. 
 */
	patchtype = (short *) calloc ((unsigned)NUM_CLASSES,sizeof(short));
	if (patchtype == NULL) {
	   Rprintf ("\nERROR! Can not allocate space for patchtype!");
	   return;
	}

	j = 0;
	for (i=0; i < MAX_CLASSES; i++) {
	   if (class_exists[i]) {
		patchtype[j] = i;
		j++;
	   }
	}


	Rprintf ("\nnumber of classes: %d",NUM_CLASSES);
	Rprintf ("\nmax patches/class: %d",MAX_PATCHES);

	if (MAX_BCKGRND_SIZE > MAX_PATCH_SIZE) {
	   Rprintf ("\nmax_patch_size: %d (background/border patch)",MAX_BCKGRND_SIZE);
	   MAX_PATCH_SIZE = MAX_BCKGRND_SIZE;
	}
	else
	   Rprintf ("\nmax patch size: %d\n",MAX_PATCH_SIZE);
	

/*
 *  If a user did not specify a weight file for contrast indices,
 *  set the min and max weight value to the min and max class 
 *  value in the landscape (includes patchtypes in the landscape border).
 *  These are needed to index the "edge" array.
 */
	if (!contrast_indices) {
	   min_wt = min_landscape_class;
	   max_wt = max_landscape_class;
	   num_wt = max_landscape_class - min_landscape_class + 1;
	}


	free (npatches);
	free (all_classes);
	free (class_exists);
	free (npts);

	return;
}
Ejemplo n.º 27
0
/*
 * cvt_trimtsip
 *
 * convert TSIP type format
 */
static unsigned long
cvt_trimtsip(
	     unsigned char *buffer,
	     int            size,
	     struct format *format,
	     clocktime_t   *clock_time,
	     void          *local
	     )
{
        register struct trimble *t = (struct trimble *)local; /* get local data space */
#define mb(_X_) (buffer[2+(_X_)]) /* shortcut for buffer access */
	register u_char cmd;

	clock_time->flags = 0;

	if (!t) {
		return CVT_NONE;		/* local data not allocated - sigh! */
	}

	if ((size < 4) ||
	    (buffer[0]      != DLE) ||
	    (buffer[size-1] != ETX) ||
	    (buffer[size-2] != DLE))
	{
		printf("TRIMBLE BAD packet, size %d:\n", size);
		return CVT_NONE;
	}
	else
	{
		unsigned char *bp;
		cmd = buffer[1];

		    switch(cmd)
		    {
		    case CMD_RCURTIME:
			    {			/* GPS time */
				    l_fp secs;
				    int   week = getshort((unsigned char *)&mb(4));
				    l_fp utcoffset;
				    l_fp gpstime;

				    bp = &mb(0);
				    if (fetch_ieee754(&bp, IEEE_SINGLE, &secs, trim_offsets) != IEEE_OK)
					    return CVT_FAIL|CVT_BADFMT;

				    if ((secs.l_i <= 0) ||
					(t->t_utcknown == 0))
				    {
					    clock_time->flags = PARSEB_POWERUP;
					    return CVT_OK;
				    }
				    if (week < GPSWRAP) {
					    week += GPSWEEKS;
				    }

				    /* time OK */

				    /* fetch UTC offset */
				    bp = &mb(6);
				    if (fetch_ieee754(&bp, IEEE_SINGLE, &utcoffset, trim_offsets) != IEEE_OK)
					    return CVT_FAIL|CVT_BADFMT;

				    L_SUB(&secs, &utcoffset); /* adjust GPS time to UTC time */

				    gpstolfp((unsigned short)week, (unsigned short)0,
					     secs.l_ui, &gpstime);

				    gpstime.l_uf = secs.l_uf;

				    clock_time->utctime = gpstime.l_ui - JAN_1970;

				    TSFTOTVU(gpstime.l_uf, clock_time->usecond);

				    if (t->t_leap == ADDSECOND)
					clock_time->flags |= PARSEB_LEAPADD;

				    if (t->t_leap == DELSECOND)
					clock_time->flags |= PARSEB_LEAPDEL;

				    switch (t->t_operable)
				      {
				      case STATUS_SYNC:
					clock_time->flags &= ~(PARSEB_POWERUP|PARSEB_NOSYNC);
					break;

				      case STATUS_UNSAFE:
					clock_time->flags |= PARSEB_NOSYNC;
					break;

				      case STATUS_BAD:
					clock_time->flags |= PARSEB_NOSYNC|PARSEB_POWERUP;
					break;
				      }

				    if (t->t_mode == 0)
					    clock_time->flags |= PARSEB_POSITION;

				    clock_time->flags |= PARSEB_S_LEAP|PARSEB_S_POSITION;

				    return CVT_OK;

			    } /* case 0x41 */

		    case CMD_RRECVHEALTH:
			    {
				    /* TRIMBLE health */
				    u_char status = mb(0);

				    switch (status)
				    {
				      case 0x00: /* position fixes */
					t->t_operable = STATUS_SYNC;
					break;

				      case 0x09: /* 1 satellite */
				      case 0x0A: /* 2 satellites */
				      case 0x0B: /* 3 satellites */
					t->t_operable = STATUS_UNSAFE;
					break;

				      default:
					t->t_operable = STATUS_BAD;
					break;
				    }
				    t->t_mode = status;
			    }
			    break;

		    case CMD_RUTCPARAM:
			    {
			            l_fp t0t;
				    unsigned char *lbp;

				    /* UTC correction data - derive a leap warning */
				    int tls   = t->t_gpsutc     = (u_short) getshort((unsigned char *)&mb(12)); /* current leap correction (GPS-UTC) */
				    int tlsf  = t->t_gpsutcleap = (u_short) getshort((unsigned char *)&mb(24)); /* new leap correction */

				    t->t_weekleap   = (u_short) getshort((unsigned char *)&mb(20)); /* week no of leap correction */
				    if (t->t_weekleap < GPSWRAP)
				      t->t_weekleap = (u_short)(t->t_weekleap + GPSWEEKS);

				    t->t_dayleap    = (u_short) getshort((unsigned char *)&mb(22)); /* day in week of leap correction */
				    t->t_week = (u_short) getshort((unsigned char *)&mb(18)); /* current week no */
				    if (t->t_week < GPSWRAP)
				      t->t_week = (u_short)(t->t_weekleap + GPSWEEKS);

				    lbp = (unsigned char *)&mb(14); /* last update time */
				    if (fetch_ieee754(&lbp, IEEE_SINGLE, &t0t, trim_offsets) != IEEE_OK)
					    return CVT_FAIL|CVT_BADFMT;

				    t->t_utcknown = t0t.l_ui != 0;

				    if ((t->t_utcknown) && /* got UTC information */
					(tlsf != tls)   && /* something will change */
					((t->t_weekleap - t->t_week) < 5)) /* and close in the future */
				    {
					    /* generate a leap warning */
					    if (tlsf > tls)
						t->t_leap = ADDSECOND;
					    else
						t->t_leap = DELSECOND;
				    }
				    else
				    {
					    t->t_leap = 0;
				    }
			    }
			    break;

		    default:
			    /* it's validly formed, but we don't care about it! */
			    break;
		}
	}
	return CVT_SKIP;
}
Ejemplo n.º 28
0
static int
xps_read_zip_entry(xps_context *ctx, xps_entry *ent, unsigned char *outbuf)
{
	z_stream stream;
	unsigned char *inbuf;
	int sig;
	int version, general, method;
	int namelength, extralength;
	int code;

	fz_seek(ctx->file, ent->offset, 0);

	sig = getlong(ctx->file);
	if (sig != ZIP_LOCAL_FILE_SIG)
		return fz_error_make(ctx->ctx, "wrong zip local file signature (0x%x)", sig);

	version = getshort(ctx->file);
	general = getshort(ctx->file);
	method = getshort(ctx->file);
	(void) getshort(ctx->file); /* file time */
	(void) getshort(ctx->file); /* file date */
	(void) getlong(ctx->file); /* crc-32 */
	(void) getlong(ctx->file); /* csize */
	(void) getlong(ctx->file); /* usize */
	namelength = getshort(ctx->file);
	extralength = getshort(ctx->file);

	fz_seek(ctx->file, namelength + extralength, 1);

	if (method == 0)
	{
		fz_read(ctx->file, outbuf, ent->usize);
	}
	else if (method == 8)
	{
		inbuf = fz_malloc(ctx->ctx, ent->csize);

		fz_read(ctx->file, inbuf, ent->csize);

		memset(&stream, 0, sizeof(z_stream));
		stream.zalloc = (alloc_func) xps_zip_alloc_items;
		stream.zfree = (free_func) xps_zip_free;
		stream.opaque = ctx;
		stream.next_in = inbuf;
		stream.avail_in = ent->csize;
		stream.next_out = outbuf;
		stream.avail_out = ent->usize;

		code = inflateInit2(&stream, -15);
		if (code != Z_OK)
			return fz_error_make(ctx->ctx, "zlib inflateInit2 error: %s", stream.msg);
		code = inflate(&stream, Z_FINISH);
		if (code != Z_STREAM_END)
		{
			inflateEnd(&stream);
			return fz_error_make(ctx->ctx, "zlib inflate error: %s", stream.msg);
		}
		code = inflateEnd(&stream);
		if (code != Z_OK)
			return fz_error_make(ctx->ctx, "zlib inflateEnd error: %s", stream.msg);

		fz_free(ctx->ctx, inbuf);
	}
	else
	{
		return fz_error_make(ctx->ctx, "unknown compression method (%d)", method);
	}

	return fz_okay;
}
Ejemplo n.º 29
0
GImage *
GImageReadRgb (char *filename)
{
  FILE *fp = fopen (filename, "rb");
  struct sgiheader header;
  int j, i;
  unsigned char *pt, *end;
  unsigned long *ipt, *iend;
  GImage *ret;
  struct _GImage *base;

  if (fp == NULL)
    return (NULL);
  getsgiheader (&header, fp);
  if (header.magic != SGI_MAGIC ||
      (header.format != VERBATIM && header.format != RLE) ||
      (header.bpc != 1 && header.bpc != 2) ||
      header.dim < 1 || header.dim > 3 ||
      header.pixmax > 65535 || (header.pixmax > 255 && header.bpc == 1) ||
      (header.chans != 1 && header.chans != 3 && header.chans != 4) ||
      header.pixmax < 0 || header.pixmin < 0 || header.pixmin > header.pixmax ||
      header.colormap != 0)
    {
      fclose (fp);
      return (NULL);
    }

  ret =
    GImageCreate (header.dim == 3 ? it_true : it_index, header.width,
                  header.height);
  base = ret->u.image;

  if (header.format == RLE)
    {
      unsigned long *starttab /*, *lengthtab */ ;
      unsigned char **ptrtab;
      long tablen;

      tablen = header.height * header.chans;
      starttab = (unsigned long *) xmalloc (szmax (1, tablen * sizeof (long)));
      /*lengthtab = (unsigned long *)xmalloc(szmax(1, tablen*sizeof(long))); */
      ptrtab =
        (unsigned char **)
        xmalloc (szmax (1, tablen * sizeof (unsigned char *)));
      readlongtab (fp, starttab, tablen);
      /*readlongtab(fp,lengthtab,tablen); */
      for (i = 0; i < tablen; ++i)
        find_scanline (fp, &header, i, starttab, ptrtab);
      if (header.chans == 1)
        {
          for (i = 0; i < header.height; ++i)
            memcpy (base->data + (header.height - 1 - i) * base->bytes_per_line,
                    ptrtab[i], header.width);
        }
      else
        {
          unsigned long *ipt;
          for (i = 0; i < header.height; ++i)
            {
              ipt =
                (unsigned long *) (base->data +
                                   (header.height - 1 -
                                    i) * base->bytes_per_line);
              for (j = 0; j < header.width; ++j)
                *ipt++ = COLOR_CREATE (ptrtab[i][j],
                                       ptrtab[i + header.height][j],
                                       ptrtab[i + 2 * header.height][j]);
            }
        }
      freeptrtab (ptrtab, tablen);
      free (ptrtab);
      free (starttab);          /*free(lengthtab); */
    }
  else
    {
      if (header.chans == 1 && header.bpc == 1)
        {
          for (i = 0; i < header.height; ++i)
            {
              fread (base->data +
                     (header.height - 1 - i) * base->bytes_per_line,
                     header.width, 1, fp);
              if (header.pixmax != 255)
                {
                  pt =
                    (unsigned char *) (base->data +
                                       (header.height - 1 -
                                        i) * base->bytes_per_line);
                  for (end = pt + header.width; pt < end; ++pt)
                    *pt = (*pt * 255) / header.pixmax;
                }
            }
        }
      else if (header.chans == 1)
        {
          for (i = 0; i < header.height; ++i)
            {
              pt =
                (unsigned char *) (base->data +
                                   (header.height - 1 -
                                    i) * base->bytes_per_line);
              for (end = pt + header.width; pt < end;)
                *pt++ = (getshort (fp) * 255L) / header.pixmax;
            }
        }
      else if (header.bpc == 1)
        {
          unsigned char *r, *g, *b, *a = NULL;
          unsigned char *rpt, *gpt, *bpt;
          r = (unsigned char *) xmalloc (header.width);
          g = (unsigned char *) xmalloc (header.width);
          b = (unsigned char *) xmalloc (header.width);
          if (header.chans == 4)
            a = (unsigned char *) xmalloc (header.width);
          for (i = 0; i < header.height; ++i)
            {
              fread (r, header.width, 1, fp);
              fread (g, header.width, 1, fp);
              fread (b, header.width, 1, fp);
              if (header.chans == 4)
                fread (a, header.width, 1, fp);
              ipt =
                (unsigned long *) (base->data +
                                   (header.height - 1 -
                                    i) * base->bytes_per_line);
              rpt = r;
              gpt = g;
              bpt = b;
              for (iend = ipt + header.width; ipt < iend;)
                *ipt++ = COLOR_CREATE (*rpt++ * 255L / header.pixmax,
                                       *gpt++ * 255L / header.pixmax,
                                       *bpt++ * 255L / header.pixmax);
            }
          free (r);
          free (g);
          free (b);
          free (a);
        }
      else
        {
          unsigned char *r, *g, *b, *a = NULL;
          unsigned char *rpt, *gpt, *bpt;
          r = (unsigned char *) xmalloc (header.width);
          g = (unsigned char *) xmalloc (header.width);
          b = (unsigned char *) xmalloc (header.width);
          if (header.chans == 4)
            a = (unsigned char *) xmalloc (header.width);
          for (i = 0; i < header.height; ++i)
            {
              for (j = 0; j < header.width; ++j)
                r[j] = getshort (fp) * 255L / header.pixmax;
              for (j = 0; j < header.width; ++j)
                g[j] = getshort (fp) * 255L / header.pixmax;
              for (j = 0; j < header.width; ++j)
                b[j] = getshort (fp) * 255L / header.pixmax;
              if (header.chans == 4)
                {
                  fread (a, header.width, 1, fp);
                  fread (a, header.width, 1, fp);
                }
              ipt =
                (unsigned long *) (base->data +
                                   (header.height - 1 -
                                    i) * base->bytes_per_line);
              rpt = r;
              gpt = g;
              bpt = b;
              for (iend = ipt + header.width; ipt < iend;)
                *ipt++ = COLOR_CREATE (*rpt++, *gpt++, *bpt++);
            }
          free (r);
          free (g);
          free (b);
          free (a);
        }
    }

  return (ret);
}
Ejemplo n.º 30
0
/* we always return a null-terminated string which has been malloc'ed.  The string
 * is always in the tag=value form.  If a temporary or permanent error occurs,
 * the string will be exactly "e=perm;" or "e=temp;".
 * Note that it never returns NULL.
 */
char *dns_text(char *dn)
{
// added by nhatier for compilation under MSVC
#ifdef _MSC_VER
   DNS_RECORD * l_Records = NULL;
   DNS_STATUS l_Result = DnsQuery(dn, DNS_TYPE_TEXT, DNS_QUERY_STANDARD, NULL, &l_Records, NULL);
   if (l_Result == ERROR_SUCCESS)
   {
      if (l_Records->wType == DNS_TYPE_TEXT)
      {
         unsigned int i;
         char buf[4096];
         buf[0] = 0;
         for (i = 0; i < l_Records->Data.TXT.dwStringCount; i++)
         {
            strcat(buf, l_Records->Data.TXT.pStringArray[i]);
         }
         DnsRecordListFree(l_Records, DnsFreeRecordList);
         return dk_strdup(buf);
      }
      else
      {
         DnsRecordListFree(l_Records, DnsFreeRecordList);
         return dk_strdup("e=perm;");
      }
   }
   else if (l_Result == DNS_ERROR_RECORD_TIMED_OUT)
   {
      DnsRecordListFree(l_Records, DnsFreeRecordList);
      return dk_strdup("e=temp;");
   }
   else
   {
      DnsRecordListFree(l_Records, DnsFreeRecordList);
      return dk_strdup("e=perm;");
   }
#else //end added by nhatier
    u_char response[PACKETSZ+1]; /* response */
    int responselen;		/* buffer length */

    int i, rc;			/* misc variables */
    int ancount, qdcount;	/* answer count and query count */
    u_short type, rdlength;		/* fields of records returned */
    u_char *eom, *cp;

    u_char buf[PACKETSZ+1];	/* we're storing a TXT record here, not just a DNAME */
    u_char *bufptr;

    responselen = res_query(dn, C_IN, T_TXT, response, sizeof(response));
    if (responselen  < 0){
      if (h_errno == TRY_AGAIN) return dk_strdup("e=temp;");
      else return dk_strdup("e=perm;");
    }

    qdcount = getshort( response + 4); /* http://crynwr.com/rfc1035/rfc1035.html#4.1.1. */
    ancount = getshort( response + 6);

    eom = response + responselen;
    cp  = response + HFIXEDSZ;

    while( qdcount-- > 0 && cp < eom ) {
      rc = dn_expand( response, eom, cp, (char *)buf, MAXDNAME );
      if( rc < 0 ) {
	return dk_strdup("e=perm;");
      }
      cp += rc + QFIXEDSZ;
    }

    while( ancount-- > 0 && cp < eom ) {
      rc = dn_expand( response, eom, cp, (char *)buf, MAXDNAME );
      if( rc < 0 ) {
	return dk_strdup("e=perm;");
      }

      cp += rc;

      if (cp + RRFIXEDSZ >= eom) return dk_strdup("e=perm;");

      type = getshort(cp + 0); /* http://crynwr.com/rfc1035/rfc1035.html#4.1.3. */
      rdlength = getshort(cp + 8);
      cp += RRFIXEDSZ;

      if( type != T_TXT ) {
	cp += rdlength;
	continue;
      }

      bufptr = buf;
      while (rdlength && cp < eom) {
	int cnt;

	cnt = *cp++;		 /* http://crynwr.com/rfc1035/rfc1035.html#3.3.14. */
	if( bufptr-buf + cnt + 1 >= PACKETSZ )
	  return dk_strdup("e=perm;");
	if (cp + cnt > eom)
	  return dk_strdup("e=perm;");
	memcpy( bufptr, cp, cnt);
	rdlength -= cnt + 1;
	bufptr += cnt;
	cp += cnt;
	*bufptr = '\0';
      }

      return (char *) dk_strdup( buf );
    }
    return dk_strdup("e=perm;");
#endif
}