Esempio n. 1
0
int main(int argc, char* argv[]){
	
	if ( 1 && argc > 1) { 
		int n = atoi(argv[1]);
	
		int small = nearest_small(n);
		printf( "%.4i(%.4i)  ", small, count_ones(small) );	
		print_bits(small);
		
		int small2 = nearest_small2(n);
		printf( "%.4i(%.4i)  ", small2, count_ones(small) );	
		print_bits(small2);
		
		printf( "%.4i(%.4i)  ", n, count_ones(n) );			  
		print_bits(n);
		
		int large = nearest_large(n);
		printf( "%.4i(%.4i)  ", large, count_ones(large) );	
		print_bits(large);
		
		
		int large2 = nearest_large2(n);
		printf( "%.4i(%.4i)  ", large2, count_ones(large2) );	
		print_bits(large2);
	}	
  	
  exit(0);
}
Esempio n. 2
0
static int correct_and_copy_fraction(buffer_struct *buff, __u8 * destination,
				     int start, int size)
{
	struct memory_segment mseg;
	int result;
	SectorMap read_bad;
	TRACE_FUN(ft_t_any);

	mseg.read_bad = convert_sector_map(buff);
	mseg.marked_bad = 0;	/* not used... */
	mseg.blocks = buff->bytes / FT_SECTOR_SIZE;
	mseg.data = buff->address;
	/*    If there are no data sectors we can skip this segment.
	 */
	if (mseg.blocks <= 3) {
		TRACE_ABORT(0, ft_t_noise, "empty segment");
	}
	read_bad = mseg.read_bad;
	ft_history.crc_errors += count_ones(read_bad);
	result = ftape_ecc_correct_data(&mseg);
	if (read_bad != 0 || mseg.corrected != 0) {
		TRACE(ft_t_noise, "crc error map: 0x%08lx", (unsigned long)read_bad);
		TRACE(ft_t_noise, "corrected map: 0x%08lx", (unsigned long)mseg.corrected);
		ft_history.corrected += count_ones(mseg.corrected);
	}
	if (result == ECC_CORRECTED || result == ECC_OK) {
		if (result == ECC_CORRECTED) {
			TRACE(ft_t_info, "ecc corrected segment: %d", buff->segment_id);
		}
		if(start < 0) {
			start= 0;
		}
		if((start+size) > ((mseg.blocks - 3) * FT_SECTOR_SIZE)) {
			size = (mseg.blocks - 3) * FT_SECTOR_SIZE  - start;
		} 
		if (size < 0) {
			size= 0;
		}
		if(size > 0) {
			memcpy(destination + start, mseg.data + start, size);
		}
		if ((read_bad ^ mseg.corrected) & mseg.corrected) {
			/* sectors corrected without crc errors set */
			ft_history.crc_failures++;
		}
		TRACE_EXIT size; /* (mseg.blocks - 3) * FT_SECTOR_SIZE; */
	} else {
		ft_history.ecc_failures++;
		TRACE_ABORT(-EAGAIN,
			    ft_t_err, "ecc failure on segment %d",
			    buff->segment_id);
	}
	TRACE_EXIT 0;
}
Esempio n. 3
0
// brute force
int nearest_large(int n) {
	int count = count_ones(n);
	if( (count==32) || (count==0) )
		return n;
	n++;
	while( 1 ){
		if( count_ones(n) == count)
			return n;
		n++;
	}
	return 0;
}
Esempio n. 4
0
int compar(void *a, void *b)
{
	int p, q, pn, qn;

	p = *((int *)a);
	q = *((int *)b);

	pn = count_ones(p);
	qn = count_ones(q);

	return (pn - qn);
}
Esempio n. 5
0
// START FUNC DECL
int
and_not_excl(
    char *list
    )
// STOP FUNC DECL
{
  int status = 0;
  char xcl_fld[MAX_LEN_FLD_NAME+1];
  char *new_fld = NULL, *cum_xcl_fld = NULL;
  int num_in_list;
  int tbl_id, list_id, xlist_id, cum_xcl_fld_id;
  TBL_REC_TYPE tbl_rec;

  status = get_list_id(list, &list_id, &tbl_id, &xlist_id); cBYE(status);
  if ( xlist_id <= 0 ) { go_BYE(-1); }
  status = get_num_in_list(list_id, &num_in_list); cBYE(status);
  status = get_tbl_meta(tbl_id, &tbl_rec); cBYE(status);
  char *tbl = tbl_rec.name;
  if ( num_in_list == 0 ) { return(status); } // Nothing to do 
  status = get_xlist_info(xlist_id, &cum_xcl_fld, &cum_xcl_fld_id);
  cBYE(status);

  for ( int pos = 1; pos <= num_in_list; pos++ ) { 
    int xcl_fld_id = -1; long long xcl_fld_cnt = -1 ;
    int new_fld_id = -1; long long new_fld_cnt = -1 ;
    status = get_fld_name(list_id, pos, "new_", &new_fld); cBYE(status);
    status = fld_meta(tbl, new_fld, "", &new_fld_id, false); cBYE(status);
    status = del_aux_fld_if_exists(tbl_id, list_id, pos, "xcl_"); cBYE(status);
    status = mk_name_new_fld(list, tbl, new_fld, "xcl_", xcl_fld); cBYE(status);
    status = f1f2opf3(tbl, new_fld, cum_xcl_fld, "&&!", xcl_fld); cBYE(status);
    status = count_ones(tbl, xcl_fld, &xcl_fld_cnt); cBYE(status);
    status = fld_meta(tbl, xcl_fld, "", &xcl_fld_id, false); cBYE(status);
    status = count_ones(tbl, new_fld, &new_fld_cnt); cBYE(status);
    // update meta data 
    if ( new_fld_cnt == xcl_fld_cnt ) { 
      status = set_fld_id_cnt(list_id, pos, "xcl_", new_fld_id, new_fld, new_fld_cnt); 
      cBYE(status);
      status = set_fld_id_cnt(list_id, pos, "lmt_", new_fld_id, new_fld, new_fld_cnt); 
      cBYE(status);
      status = del_fld(NULL, tbl_id, NULL, xcl_fld_id, true); cBYE(status);
    }
    else {
    status = set_fld_id_cnt(list_id, pos, "xcl_", xcl_fld_id, xcl_fld, xcl_fld_cnt); 
    cBYE(status);
    status = set_fld_id_cnt(list_id, pos, "lmt_", xcl_fld_id, xcl_fld, xcl_fld_cnt); 
    cBYE(status);
    }
    free_if_non_null(new_fld); 
  }
BYE:
  free_if_non_null(new_fld); 
  return(status);
}
Esempio n. 6
0
// brute force
int nearest_small(int n) {
	int count = count_ones(n);
	if( (count==32) || (count==0) )
		return n;
	if( ~(-1<<count) == n )
		return n;
	n--;
	while( n > 0 ) {
		if( count_ones(n) == count)
			return n;
		n--;
	}
	return 0;
}
Esempio n. 7
0
unsigned int hamming84_dec_symbol(unsigned int _r)
{
    // compute syndromes
    unsigned int z0 = count_ones(_r & HAMMING84_H0) % 2;
    unsigned int z1 = count_ones(_r & HAMMING84_H1) % 2;
    unsigned int z2 = count_ones(_r & HAMMING84_H2) % 2;
    unsigned int z = (z0 << 0) | (z1 << 1) | (z2 << 2);

    unsigned int r_hat = _r;
    if (z) {
        // error detected: flip appropriate bit of
        // received symbol
        r_hat ^= 1 << (8-z);
    }

#if 0
    // check extra parity bit
    unsigned int z3 = count_ones(r_hat & HAMMING84_H3) % 2;
    if (z3) printf("decoding error!\n");
#endif

    // decode
    unsigned int p0 = count_ones(r_hat & HAMMING84_R0) % 2;
    unsigned int p1 = count_ones(r_hat & HAMMING84_R1) % 2;
    unsigned int p2 = count_ones(r_hat & HAMMING84_R2) % 2;
    unsigned int p3 = count_ones(r_hat & HAMMING84_R3) % 2;

    unsigned int p = (p0 << 3) | (p1 << 2) | (p2 << 1) | (p3 << 0);

    return p;
}
Esempio n. 8
0
// find first 0; then first first one after 0 <- int first
// count numbers of 1 until this first one, not included <- int ones
// swap the first 10 to 01
// fill out the lower bits with as many ones, starting from the left
int nearest_small2(int n) {
	int count = count_ones(n);
	if( (count==32) || (count==0) )
		return n;
	if( ~(-1<<count) == n )
		return n;
	
	int ones  = 0;	
	int first = 1;
	int mask  = 1;
	while( 0 != (n & first) ){
		first = first << 1;
		mask = 1 + ( mask << 1);
		ones++;
	}
	while( 0 == (n & first) ) {
		first = first << 1;		
		mask = 1 + ( mask << 1);
	}
	
	first = first >> 1;
	int tail = first;
	while(ones) {
		first = first >> 1;
		tail = tail | first;
	  ones--;
	}
		
	return ( n & ~mask ) | tail; 
}
Esempio n. 9
0
void hadamard_decode(unsigned char codeword[], int num_blocks, unsigned char destination[]){
	unsigned char best_index, best_ones, row, col, current_ones, temp;
	int block, base_index;

	for(block=0; block<num_blocks; ++block){
		base_index = COLUMNS * block;
		best_index = -1;
		best_ones = HAD_SIZE;
		for(row=0; row<ROWS; ++row){
			current_ones = 0;
			for(col=0; col<COLUMNS; ++col){
				temp = codeword[base_index + col] ^ had_code[row][col];
				current_ones += count_ones(temp);
			}
			if (current_ones < best_ones){
				best_index = row;
				best_ones = current_ones;
				if (best_ones < 16) {
					break;
				}
			}
		}
		destination[block] = best_index;
	}
}
static int copy_and_gen_ecc(void *destination, 
			    const void *source,
			    const SectorMap bad_sector_map)
{
	int result;
	struct memory_segment mseg;
	int bads = count_ones(bad_sector_map);
	TRACE_FUN(ft_t_any);

	if (bads > 0) {
		TRACE(ft_t_noise, "bad sectors in map: %d", bads);
	}
	if (bads + 3 >= FT_SECTORS_PER_SEGMENT) {
		TRACE(ft_t_noise, "empty segment");
		mseg.blocks = 0; /* skip entire segment */
		result = 0;      /* nothing written */
	} else {
		mseg.blocks = FT_SECTORS_PER_SEGMENT - bads;
		mseg.data = destination;
		memcpy(mseg.data, source, (mseg.blocks - 3) * FT_SECTOR_SIZE);
		result = ftape_ecc_set_segment_parity(&mseg);
		if (result < 0) {
			TRACE(ft_t_err, "ecc_set_segment_parity failed");
		} else {
			result = (mseg.blocks - 3) * FT_SECTOR_SIZE;
		}
	}
	TRACE_EXIT result;
}
Esempio n. 11
0
int copy_and_gen_ecc(char *destination, byte * source,
                     unsigned int bad_sector_map)
{
    TRACE_FUN(8, "copy_and_gen_ecc");
    int result;
    struct memory_segment mseg;
    int bads = count_ones(bad_sector_map);

    if (bads > 0) {
        TRACEi(4, "bad sectors in map:", bads);
    }
    if (bads + 3 >= SECTORS_PER_SEGMENT) {
        TRACE(4, "empty segment");
        mseg.blocks = 0;	/* skip entire segment */
        result = 0;	/* nothing written */
    } else {
        mseg.blocks = SECTORS_PER_SEGMENT - bads;
        mseg.data = destination;
        memcpy(mseg.data, source, (mseg.blocks - 3) * SECTOR_SIZE);
        result = ecc_set_segment_parity(&mseg);
        if (result < 0) {
            TRACE(1, "ecc_set_segment_parity failed");
        } else {
            result = (mseg.blocks - 3) * SECTOR_SIZE;
        }
    }
    TRACE_EXIT;
    return result;
}
Esempio n. 12
0
inline unsigned int count_leading_zeros_impl(N n, std::size_t w) {
	// Algorithm adapted from:
	// <http://aggregate.org/MAGIC/#Leading%20Zero%20Count>
	for (unsigned int shift = 1; shift < w; shift *= 2) {
		n |= (n >> shift);
	}
	return static_cast<unsigned int>(w) - count_ones(n);
}
Esempio n. 13
0
unsigned int hamming74_dec_symbol(unsigned int _r)
{
    // compute syndromes
    unsigned int z0 = count_ones(_r & HAMMING74_H0) % 2;
    unsigned int z1 = count_ones(_r & HAMMING74_H1) % 2;
    unsigned int z2 = count_ones(_r & HAMMING74_H2) % 2;
    unsigned int z = (z0 << 0) | (z1 << 1) | (z2 << 2);

    unsigned int r_hat = _r;
    if (z) {
        // error detected: flip appropriate bit of
        // received symbol
        r_hat ^= 1 << (7-z);
    }

    // decode
    unsigned int p0 = count_ones(r_hat & HAMMING74_R0) % 2;
    unsigned int p1 = count_ones(r_hat & HAMMING74_R1) % 2;
    unsigned int p2 = count_ones(r_hat & HAMMING74_R2) % 2;
    unsigned int p3 = count_ones(r_hat & HAMMING74_R3) % 2;

    unsigned int p = (p0 << 3) | (p1 << 2) | (p2 << 1) | (p3 << 0);

    return p;
}
Esempio n. 14
0
File: set.c Progetto: spl/ivy
/* set_dist -- distance between two sets (# elements in common) */
int set_dist(register pset a, register pset b)
{
    register int i, sum = 0;
    register unsigned int val;
    for(i = LOOP(a); i > 0; i--)
	if ((val = a[i] & b[i]) != 0)
	    sum += count_ones(val);
    return sum;
}
unsigned int zft_get_seg_sz(unsigned int segment)
{
	int size;
	TRACE_FUN(ft_t_any);
	
	size = FT_SEGMENT_SIZE - 
		count_ones(ftape_get_bad_sector_entry(segment))*FT_SECTOR_SIZE;
	if (size > 0) {
		TRACE_EXIT (unsigned)size; 
	} else {
		TRACE_EXIT 0;
	}
}
Esempio n. 16
0
short calc_parity(char *filename) {
    char parity=0;
    long long size;
    char character;
    FILE *fp;
    fp = fopen(filename, "r");
    fseek(fp, 0L, SEEK_END);
    size = ftell(fp);
    fseek(fp, 0L, SEEK_SET);
    for(long long i=0; i<size; ++i) {
        character=fgetc(fp);
        parity ^= character;
    }
    return count_ones(parity)%2;
}
Esempio n. 17
0
unsigned int hamming84_enc_symbol(unsigned int _p)
{
    unsigned int x0 = count_ones(_p & HAMMING84_G0) % 2;
    unsigned int x1 = count_ones(_p & HAMMING84_G1) % 2;
    unsigned int x2 = count_ones(_p & HAMMING84_G2) % 2;
    unsigned int x3 = count_ones(_p & HAMMING84_G3) % 2;
    unsigned int x4 = count_ones(_p & HAMMING84_G4) % 2;
    unsigned int x5 = count_ones(_p & HAMMING84_G5) % 2;
    unsigned int x6 = count_ones(_p & HAMMING84_G6) % 2;
    unsigned int x7 = count_ones(_p & HAMMING84_G7) % 2;

    unsigned int x = (x0 << 7) | (x1 << 6) | (x2 << 5) |
                     (x3 << 4) | (x4 << 3) | (x5 << 2) |
                     (x6 << 1) | (x7     );

    return x;
}
Esempio n. 18
0
void put_bad_sector_entry(int segment_id, unsigned long new_map)
{
	byte *ptr = bad_sector_map;
	int count;
	int new_count;
	unsigned long map;

	if (format_code == 3 || format_code == 4) {
		count = forward_seek_entry(segment_id, &ptr, &map);
		new_count = count_ones(new_map);
		/*  If format code == 4 put empty segment instead of 32 bad sectors.
		 */
		if (new_count == 32 && format_code == 4) {
			new_count = 1;
		}
		if (count != new_count) {
			/*  insert (or delete if < 0) new_count - count entries.
			 *  Move trailing part of list including terminating 0.
			 */
			byte *hi_ptr = ptr;

			do {
			} while (get_sector(&hi_ptr, forward) != 0);
			memmove(ptr + new_count, ptr + count, hi_ptr - (ptr + count));
		}
		if (new_count == 1 && new_map == EMPTY_SEGMENT) {
			put_sector(&ptr, 0x800001 + segment_id * SECTORS_PER_SEGMENT);
		} else {
			int i = 0;

			while (new_map) {
				if (new_map & 1) {
					put_sector(&ptr, 1 + segment_id * SECTORS_PER_SEGMENT + i);
				}
				++i;
				new_map >>= 1;
			}
		}
	} else {
Esempio n. 19
0
int main() {

    unsigned char c_ones_mod2[256];

    unsigned int b;
    for (b=0; b<256; b++)
        c_ones_mod2[b] = count_ones((unsigned char)b) % 2;
    
    // print results
    printf("unsigned char c_ones_mod2[] = {\n    ");
    for (b=0; b<256; b++) {
        printf("%1u", c_ones_mod2[b]);
        if (b==255)
            printf("\n");
        else if (((b+1)%16)==0)
            printf(",\n    ");
        else
            printf(", ");
    }
    printf("};\n");
    return 0;
}
Esempio n. 20
0
int fitness_compute(const struct chromo_t *c, fitness_t *value)
{
	assert(CGP_INPUTS >= CGP_OUTPUTS);
	static const size_t max_count = CGP_WIDTH * CGP_HEIGHT;

	struct bitgen_t bitgen;
	if(bitgen_init(&bitgen, CGP_INPUTS))
		return 1;

	struct cell_t *cells = chromo_alap(c);
	uint64_t inputs[CGP_INPUTS];
	uint64_t sorted[CGP_INPUTS];
	uint64_t outputs[CGP_OUTPUTS];
	size_t incorrect = 0;
	uint64_t mask = 0xFFFFFFFFFFFFFFFF;

	while(bitgen_next(&bitgen, inputs)) {
		eval_fenotype(cells, c->outputs, inputs, outputs);
		bitgen_sort(inputs, sorted, CGP_INPUTS);

		if(!bitgen_has_next(&bitgen))
			mask = CGP_OUTPUTS >= 6? 0xFFFFFFFFFFFFFFFF
			     : (((uint64_t) 1) << (1 << CGP_OUTPUTS)) - 1;

		for(size_t i = 0; i < CGP_OUTPUTS; ++i) {
			const uint64_t tmp = outputs[i] ^ sorted[i];
			incorrect += count_ones(tmp & mask);
		}
	}

	if(incorrect == 0)
		*value = count_cell_list(cells);
	else
		*value = incorrect + max_count;

	bitgen_fini(&bitgen);
	assert(*value > 0);
	return 0;
}
Esempio n. 21
0
void mem_subtrie(struct mb_node_v6 *n, struct mem_stats_v6 *ms)
{
    int stride;
    int pos;
    struct mb_node_v6 *next;
    int child_num = count_children(n->external);
    int rule_num = count_children(n->internal);
    

    ms->mem += (UP_RULE(rule_num) + UP_CHILD(child_num)) * NODE_SIZE;
    ms->node += (UP_RULE(rule_num) + UP_CHILD(child_num));

    
    for (stride = 0; stride < (1<<STRIDE); stride ++ ){
        pos = count_enl_bitmap(stride);
        if (test_bitmap(n->external, pos)) {
            next = (struct mb_node_v6 *)n->child_ptr + count_ones(n->external, pos);
            mem_subtrie(next, ms);
        }
    }


}
Esempio n. 22
0
int main(int    argc,
         char **argv)
{
l_int32  w, h, n, i, sum, sumi, empty;
BOX     *box1, *box2, *box3, *box4;
BOXA    *boxa, *boxat;
NUMA    *na1, *na2, *na3, *na4, *na5;
NUMA    *na2i, *na3i, *na4i, *nat, *naw, *nah;
PIX     *pixs, *pixc, *pixt, *pixt2, *pixd, *pixcount;
PIXA    *pixas, *pixad, *pixac;

    pixDisplayWrite(NULL, -1);

        /* Draw 4 filled boxes of different sizes */
    pixs = pixCreate(200, 200, 1);
    box1 = boxCreate(10, 10, 20, 30);
    box2 = boxCreate(50, 10, 40, 20);
    box3 = boxCreate(110, 10, 35, 5);
    box4 = boxCreate(160, 10, 5, 15);
    boxa = boxaCreate(4);
    boxaAddBox(boxa, box1, L_INSERT);
    boxaAddBox(boxa, box2, L_INSERT);
    boxaAddBox(boxa, box3, L_INSERT);
    boxaAddBox(boxa, box4, L_INSERT);
    pixRenderBox(pixs, box1, 1, L_SET_PIXELS);
    pixRenderBox(pixs, box2, 1, L_SET_PIXELS);
    pixRenderBox(pixs, box3, 1, L_SET_PIXELS);
    pixRenderBox(pixs, box4, 1, L_SET_PIXELS);
    pixt = pixFillClosedBorders(pixs, 4);
    pixDisplayWrite(pixt, 1);
    pixt2 = pixCreateTemplate(pixs);
    pixRenderHashBox(pixt2, box1, 6, 4, L_POS_SLOPE_LINE, 1, L_SET_PIXELS);
    pixRenderHashBox(pixt2, box2, 7, 2, L_POS_SLOPE_LINE, 1, L_SET_PIXELS);
    pixRenderHashBox(pixt2, box3, 4, 2, L_VERTICAL_LINE, 1, L_SET_PIXELS);
    pixRenderHashBox(pixt2, box4, 3, 1, L_HORIZONTAL_LINE, 1, L_SET_PIXELS);
    pixDisplayWrite(pixt2, 1);

        /* Exercise the parameters */
    pixd = pixSelectBySize(pixt, 0, 22, 8, L_SELECT_HEIGHT,
                           L_SELECT_IF_GT, NULL);
    count_pieces(pixd, 1);
    pixd = pixSelectBySize(pixt, 0, 30, 8, L_SELECT_HEIGHT,
                           L_SELECT_IF_LT, NULL);
    count_pieces(pixd, 3);
    pixd = pixSelectBySize(pixt, 0, 5, 8, L_SELECT_HEIGHT,
                           L_SELECT_IF_GT, NULL);
    count_pieces(pixd, 3);
    pixd = pixSelectBySize(pixt, 0, 6, 8, L_SELECT_HEIGHT,
                           L_SELECT_IF_LT, NULL);
    count_pieces(pixd, 1);
    pixd = pixSelectBySize(pixt, 20, 0, 8, L_SELECT_WIDTH,
                           L_SELECT_IF_GT, NULL);
    count_pieces(pixd, 2);
    pixd = pixSelectBySize(pixt, 31, 0, 8, L_SELECT_WIDTH,
                           L_SELECT_IF_LT, NULL);
    count_pieces(pixd, 2);
    pixd = pixSelectBySize(pixt, 21, 10, 8, L_SELECT_IF_EITHER,
                           L_SELECT_IF_LT, NULL);
    count_pieces(pixd, 3);
    pixd = pixSelectBySize(pixt, 20, 30, 8, L_SELECT_IF_EITHER,
                           L_SELECT_IF_GT, NULL);
    count_pieces(pixd, 2);
    pixd = pixSelectBySize(pixt, 22, 32, 8, L_SELECT_IF_BOTH,
                           L_SELECT_IF_LT, NULL);
    count_pieces(pixd, 2);
    pixd = pixSelectBySize(pixt, 6, 32, 8, L_SELECT_IF_BOTH,
                           L_SELECT_IF_LT, NULL);
    count_pieces(pixd, 1);
    pixd = pixSelectBySize(pixt, 5, 25, 8, L_SELECT_IF_BOTH,
                           L_SELECT_IF_GT, NULL);
    count_pieces(pixd, 1);
    pixd = pixSelectBySize(pixt, 25, 5, 8, L_SELECT_IF_BOTH,
                           L_SELECT_IF_GT, NULL);
    count_pieces(pixd, 1);

    pixd = pixSelectByPerimToAreaRatio(pixt, 0.3, 8, L_SELECT_IF_GT, NULL);
    count_pieces(pixd, 2);
    pixd = pixSelectByPerimToAreaRatio(pixt, 0.15, 8, L_SELECT_IF_GT, NULL);
    count_pieces(pixd, 3);
    pixd = pixSelectByPerimToAreaRatio(pixt, 0.4, 8, L_SELECT_IF_LTE, NULL);
    count_pieces(pixd, 2);
    pixd = pixSelectByPerimToAreaRatio(pixt, 0.45, 8, L_SELECT_IF_LT, NULL);
    count_pieces(pixd, 3);

    pixd = pixSelectByPerimSizeRatio(pixt2, 2.3, 8, L_SELECT_IF_GT, NULL);
    count_pieces(pixd, 2);
    pixd = pixSelectByPerimSizeRatio(pixt2, 1.2, 8, L_SELECT_IF_GT, NULL);
    count_pieces(pixd, 3);
    pixd = pixSelectByPerimSizeRatio(pixt2, 1.7, 8, L_SELECT_IF_LTE, NULL);
    count_pieces(pixd, 1);
    pixd = pixSelectByPerimSizeRatio(pixt2, 2.9, 8, L_SELECT_IF_LT, NULL);
    count_pieces(pixd, 3);

    pixd = pixSelectByAreaFraction(pixt2, 0.3, 8, L_SELECT_IF_LT, NULL);
    count_pieces(pixd, 0);
    pixd = pixSelectByAreaFraction(pixt2, 0.9, 8, L_SELECT_IF_LT, NULL);
    count_pieces(pixd, 4);
    pixd = pixSelectByAreaFraction(pixt2, 0.5, 8, L_SELECT_IF_GTE, NULL);
    count_pieces(pixd, 3);
    pixd = pixSelectByAreaFraction(pixt2, 0.7, 8, L_SELECT_IF_GT, NULL);
    count_pieces(pixd, 2);

    boxat = boxaSelectBySize(boxa, 21, 10, L_SELECT_IF_EITHER,
                             L_SELECT_IF_LT, NULL);
    count_pieces2(boxat, 3);
    boxat = boxaSelectBySize(boxa, 22, 32, L_SELECT_IF_BOTH,
                             L_SELECT_IF_LT, NULL);
    count_pieces2(boxat, 2);

    boxaDestroy(&boxa);
    pixDestroy(&pixt);
    pixDestroy(&pixt2);
    pixDestroy(&pixs);

        /* Here's the most general method for selecting components.
         * We do it for area fraction, but any combination of
         * size, area/perimeter ratio and area fraction can be used. */
    pixs = pixRead("feyn.tif");
/*    pixs = pixRead("rabi.png"); */
    pixc = pixCopy(NULL, pixs);  /* subtract bands from this */
    pixt = pixCreateTemplate(pixs);  /* add bands to this */
    pixGetDimensions(pixs, &w, &h, NULL);
    boxa = pixConnComp(pixs, &pixas, 8);
    n = boxaGetCount(boxa);
    fprintf(stderr, "total: %d\n", n);
    na1 = pixaFindAreaFraction(pixas);
    nat = numaCreate(0);
    numaSetCount(nat, n);  /* initialize to all 0 */
    sum = sumi = 0;
    pixac = pixaCreate(0);
    for (i = 0; i < 12; i++) {
            /* Compute within the intervals using an intersection. */
        na2 = numaMakeThresholdIndicator(na1, edges[i], L_SELECT_IF_GTE);
        if (i != 11)
            na3 = numaMakeThresholdIndicator(na1, edges[i + 1], L_SELECT_IF_LT);
        else
            na3 = numaMakeThresholdIndicator(na1, edges[i + 1],
                                             L_SELECT_IF_LTE);
        na4 = numaLogicalOp(NULL, na2, na3, L_INTERSECTION);
        sum += count_ones(na4, 0, 0, NULL);

            /* Compute outside the intervals using a union, and invert */
        na2i = numaMakeThresholdIndicator(na1, edges[i], L_SELECT_IF_LT);
        if (i != 11)
            na3i = numaMakeThresholdIndicator(na1, edges[i + 1],
                                              L_SELECT_IF_GTE);
        else
            na3i = numaMakeThresholdIndicator(na1, edges[i + 1],
                                              L_SELECT_IF_GT);
        na4i = numaLogicalOp(NULL, na3i, na2i, L_UNION);
        numaInvert(na4i, na4i);
        sumi += count_ones(na4i, 0, 0, NULL);

            /* Compare the two methods */
        if (sum == sumi)
            fprintf(stderr, "\nCorrect: sum = sumi = %d\n", sum);
        else
            fprintf(stderr, "\nWRONG: sum = %d, sumi = %d\n", sum, sumi);

            /* Reconstruct the image, band by band. */
        numaLogicalOp(nat, nat, na4, L_UNION);
        pixad = pixaSelectWithIndicator(pixas, na4, NULL);
        pixd = pixaDisplay(pixad, w, h);
        pixOr(pixt, pixt, pixd);  /* add them in */
        pixcount = pixCopy(NULL, pixt);  /* destroyed by count_pieces */
        count_ones(na4, band[i], i, "band");
        count_pieces(pixd, band[i]);
        count_ones(nat, total[i], i, "total");
        count_pieces(pixcount, total[i]);
        pixaDestroy(&pixad);

            /* Remove band successively from full image */
        pixRemoveWithIndicator(pixc, pixas, na4);
        pixSaveTiled(pixc, pixac, 0.25, 1 - i % 2, 25, 8);

        numaDestroy(&na2);
        numaDestroy(&na3);
        numaDestroy(&na4);
        numaDestroy(&na2i);
        numaDestroy(&na3i);
        numaDestroy(&na4i);
    }

        /* Did we remove all components from pixc? */
    pixZero(pixc, &empty);
    if (!empty)
        fprintf(stderr, "\nWRONG: not all pixels removed from pixc\n");

    pixDestroy(&pixs);
    pixDestroy(&pixc);
    pixDestroy(&pixt);
    boxaDestroy(&boxa);
    pixaDestroy(&pixas);
    numaDestroy(&na1);
    numaDestroy(&nat);

        /* One last extraction.  Get all components that have either
         * a height of at least 50 or a width of between 30 and 35,
         * and also have a relatively large perimeter/area ratio. */
    pixs = pixRead("feyn.tif");
    boxa = pixConnComp(pixs, &pixas, 8);
    n = boxaGetCount(boxa);
    pixaFindDimensions(pixas, &naw, &nah);
    na1 = pixaFindPerimToAreaRatio(pixas);
    na2 = numaMakeThresholdIndicator(nah, 50, L_SELECT_IF_GTE);
    na3 = numaMakeThresholdIndicator(naw, 30, L_SELECT_IF_GTE);
    na4 = numaMakeThresholdIndicator(naw, 35, L_SELECT_IF_LTE);
    na5 = numaMakeThresholdIndicator(na1, 0.4, L_SELECT_IF_GTE);
    numaLogicalOp(na3, na3, na4, L_INTERSECTION);
    numaLogicalOp(na2, na2, na3, L_UNION);
    numaLogicalOp(na2, na2, na5, L_INTERSECTION);
    numaInvert(na2, na2);  /* get components to be removed */
    pixRemoveWithIndicator(pixs, pixas, na2);
    pixSaveTiled(pixs, pixac, 0.25, 1, 25, 8);
    pixDestroy(&pixs);
    boxaDestroy(&boxa);
    pixaDestroy(&pixas);
    numaDestroy(&naw);
    numaDestroy(&nah);
    numaDestroy(&na1);
    numaDestroy(&na2);
    numaDestroy(&na3);
    numaDestroy(&na4);
    numaDestroy(&na5);

    pixDisplayMultiple("/tmp/display/file*");
    pixd = pixaDisplay(pixac, 0, 0);
    pixDisplay(pixd, 100, 100);
    pixWrite("/tmp/comp.jpg", pixd, IFF_JFIF_JPEG);
    pixDestroy(&pixd);
    pixaDestroy(&pixac);
    return 0;
}
Esempio n. 23
0
  bool ReadPalette(File* file, Header& h) {

    // initialize bit masks/shifts...  just in case
    h.bf_red_mask   = h.bf_red_shift   = h.bf_red_rshift   = 0;
    h.bf_green_mask = h.bf_green_shift = h.bf_green_rshift = 0;
    h.bf_blue_mask  = h.bf_blue_shift  = h.bf_blue_rshift  = 0;

    // if we're not a palettized image, don't even read a palette
    if (h.bpp > 8) {
      h.palette_size = 0;

      // do we have bitfields?
      if (h.compression == 3) {

        auto_array<byte> bitfields(new byte[12]);
        if (file->read(bitfields, 12) != 12) {
          return false;
        }

        h.bf_red_mask   = read32_le((byte*)bitfields);
        h.bf_green_mask = read32_le((byte*)bitfields + 4);
        h.bf_blue_mask  = read32_le((byte*)bitfields + 8);

        // calculate shifts
        h.bf_red_shift    = count_right_zeroes(h.bf_red_mask);
        h.bf_green_shift  = count_right_zeroes(h.bf_green_mask);
        h.bf_blue_shift   = count_right_zeroes(h.bf_blue_mask);
        h.bf_red_rshift   = 8 - count_ones(h.bf_red_mask);
        h.bf_green_rshift = 8 - count_ones(h.bf_green_mask);
        h.bf_blue_rshift  = 8 - count_ones(h.bf_blue_mask);

      // otherwise, set default bitfield entries
      } else {

        if (h.bpp == 16) {

          h.bf_red_mask     = 0x7C00;
          h.bf_red_shift    = 10;
          h.bf_red_rshift   = 3;

          h.bf_green_mask   = 0x03E0;
          h.bf_green_shift  = 5;
          h.bf_green_rshift = 3;

          h.bf_blue_mask    = 0x001F;
          h.bf_blue_shift   = 0;
          h.bf_blue_rshift  = 3;

        } else if (h.bpp == 32) {

          // these don't need any rshift
          h.bf_red_mask   = 0x00FF0000; h.bf_red_shift   = 16;
          h.bf_green_mask = 0x0000FF00; h.bf_green_shift = 8;
          h.bf_blue_mask  = 0x000000FF; h.bf_blue_shift  = 0;

        }
      }

      return true;
    }

    if (h.bpp <= 8) {
      h.palette_size = 1 << h.bpp;
    } else {
      h.palette_size = 0;
      return true;
    }
    h.palette = new BGR[h.palette_size];

    // read the BMP color table
    const int buffer_size = h.palette_size * (h.os2 ? 3 : 4);
    auto_array<byte> buffer(new byte[buffer_size]);
    if (file->read(buffer, buffer_size) != buffer_size) {
      return false;
    }

    byte* in = buffer;
    BGR* out = h.palette;
    for (int i = 0; i < h.palette_size; ++i) {
      out->blue  = *in++;
      out->green = *in++;
      out->red   = *in++;
      if (!h.os2) {
        ++in;  // skip alpha
      }
      ++out;
    }

    return true;
  }
Esempio n. 24
0
	buff->segment_id = segment_id;
	buff->sector_offset = sector_offset;
	buff->remaining = sector_count;
	buff->head = segment_id / ftape_segments_per_head;
	buff->cyl = (segment_id % ftape_segments_per_head) / ftape_segments_per_cylinder;
	buff->sect = (segment_id % ftape_segments_per_cylinder) * FT_SECTORS_PER_SEGMENT + 1;
	buff->deleted = 0;
	offset_mask = (1 << buff->sector_offset) - 1;
	mask = ftape_get_bad_sector_entry(segment_id) & offset_mask;
	while (mask) {
		if (mask & 1) {
			offset_mask >>= 1;	/* don't count bad sector */
		}
		mask >>= 1;
	}
	buff->data_offset = count_ones(offset_mask);	/* good sectors to skip */
	buff->ptr = buff->address + buff->data_offset * FT_SECTOR_SIZE;
	TRACE(ft_t_flow, "data offset = %d sectors", buff->data_offset);
	if (retry) {
		buff->soft_error_map &= offset_mask;	/* keep skipped part */
	} else {
		buff->hard_error_map = buff->soft_error_map = 0;
	}
	buff->bad_sector_map = ftape_get_bad_sector_entry(buff->segment_id);
	if (buff->bad_sector_map != 0) {
		TRACE(ft_t_noise, "segment: %d, bad sector map: %08lx",
			buff->segment_id, (long)buff->bad_sector_map);
	} else {
		TRACE(ft_t_flow, "segment: %d", buff->segment_id);
	}
	if (buff->sector_offset > 0) {
Esempio n. 25
0
// Constructs a DFA for the inequation coeffs*variables+constant<0
// in two's complement arithmetic
DFA *build_DFA_ineq_2sc(int vars, int *coeffs, int constant, int *indices) {
	int min, max, states, next_index, next_label, result, target, count;
	long i;
	unsigned long j, transitions;
	struct map_ent *map;
	char *statuces;
	DFA *inequality, *temp;
	//int write1, overbits, label1, label2, co;
	int write1, label1, label2, co;



	preprocess(vars, coeffs, &constant, 1);

	//initialization

	min = 0;
	max = 0;
	for (i = 0; i < vars; i++)
		if (coeffs[i] > 0)
			max += coeffs[i];
		else
			min += coeffs[i];

	if (constant > max)
		max = constant;
	else if (constant < min)
		min = constant;
	states = max - min + 1;
	//overbits= ceil(log(states)/log(2));
	states *= 2;

	//This array maps state labels (carries) to state indices
	map = (struct map_ent *) malloc(states * sizeof(struct map_ent)) - min;
	for (i = min; i < max + 1; i++) {
		map[i].s = 0;
		map[i].sr = 0;
		map[i].i = -1;
		map[i].ir = -1;
	}
	map[constant].sr = 1; //the first state to be expanded
	next_index = 0; //the next available state index
	next_label = constant; //the next available state label
	map[constant].i = -1;
	map[constant].ir = 0;
	count = 0;

	transitions = 1 << vars; //number of transitions from each state

	//Begin building
	dfaSetup(states, vars, indices);

	while (next_label < max + 1) { //there is a state to expand (excuding sink)
		if (map[next_label].i == count)
			map[next_label].s = 2;
		else
			map[next_label].sr = 2;
		dfaAllocExceptions(transitions);
		for (j = 0; j < transitions; j++) {
			co = count_ones(j, vars, coeffs);
			result = next_label + co;
			if (result >= 0)
				target = result / 2;
			else
				target = (result - 1) / 2;
			write1 = result & 1;
			label1 = next_label;
			label2 = target;

			while (label1 != label2) {
				label1 = label2;
				result = label1 + co;
				if (result >= 0)
					label2 = result / 2;
				else
					label2 = (result - 1) / 2;
				write1 = result & 1;
			}

			if (write1) {
				if (map[target].s == 0) {
					map[target].s = 1;
					next_index++;
					map[target].i = next_index;
				}
				dfaStoreException(map[target].i, bintostr(j, vars));
			} else {
				if (map[target].sr == 0) {
					map[target].sr = 1;
					next_index++;
					map[target].ir = next_index;
				}
				dfaStoreException(map[target].ir, bintostr(j, vars));
			}
		}
		dfaStoreState(count);
		count++;
		for (next_label = min; (next_label <= max) && (map[next_label].i
				!= count) && (map[next_label].ir != count); next_label++)
			;
		//find next state to expand
	}
	for (i = count; i < states; i++) {
		dfaAllocExceptions(0);
		dfaStoreState(i);
	}

	//define accepting and rejecting states
	statuces = (char *) malloc(states + 1);
	for (i = 0; i < states; i++)
		statuces[i] = '-';
	for (next_label = min; next_label <= max; next_label++)
		if (map[next_label].s == 2)
			statuces[map[next_label].i] = '+';
	statuces[states] = '\0';
	temp = dfaBuild(statuces);
	temp->ns -= states - count;
	inequality = dfaMinimize(temp);
	return inequality;
}
Esempio n. 26
0
//Constructs a DFA for the inequation coeffs*variables+constant<0
DFA *build_DFA_ineq_new(int vars, int *coeffs, int constant, int *indices) {
	int min, max, states, next_index, next_label, result, target, count;
	long i, transitions;
	unsigned long j;
	struct map_ent *map;
	char *statuces;
	DFA *inequality, *temp;

	preprocess(vars, coeffs, &constant, 1);

	//initialization

	min = 0;
	max = 0;
	for (i = 0; i < vars; i++)
		if (coeffs[i] > 0)
			max += coeffs[i];
		else
			min += coeffs[i];

	if (constant > max)
		max = constant;
	else if (constant < min)
		min = constant;
	states = max - min + 1;

	//This array maps state labels (carries) to state indices
	map = (struct map_ent *) malloc(states * sizeof(struct map_ent)) - min;
	for (i = min; i < max + 1; i++) {
		map[i].s = 0;
		map[i].i = -1;
	}
	map[constant].s = 1; //the first state to be expanded
	next_index = 0; //the next available state index
	next_label = constant; //the next available state label
	map[constant].i = 0;
	count = 0;

	transitions = 1 << vars; //number of transitions from each state

	//Begin building
	dfaSetup(states + 1, vars, indices);

	dfaAllocExceptions(0);
	dfaStoreState(1);
	//count++;

	while (next_label < max + 1) { //there is a state to expand
		map[next_label].s = 2;
		dfaAllocExceptions(transitions);
		for (j = 0; j < transitions; j++) {
			result = next_label + count_ones(j, vars, coeffs);
			if (result >= 0)
				target = result / 2;
			else
				target = (result - 1) / 2;
			if (map[target].s == 0) {
				map[target].s = 1;
				next_index++;
				map[target].i = next_index;
			}
			dfaStoreException(map[target].i + 1, bintostr(j, vars));
		}
		dfaStoreState(count);
		count++;
		for (next_label = min; (next_label <= max) && (map[next_label].i
				!= count); next_label++)
			;
		//find next state to expand
	}
	for (i = count; i <= states; i++) {
		dfaAllocExceptions(0);
		dfaStoreState(i);
	}

	//define accepting and rejecting states
	statuces = (char *) malloc(states + 2);
	for (i = 0; i <= count; i++)
		statuces[i] = '-';
	for (; i <= states; i++)
		statuces[i] = '0';
	for (i = min; i < 0; i++)
		if (map[i].s == 2)
			statuces[map[i].i + 1] = '+';
	statuces[states + 1] = '\0';
	temp = dfaBuild(statuces);
	temp->ns -= states - count;
	inequality = dfaMinimize(temp);
	return inequality;
}
Esempio n. 27
0
// Constructs a DFA for the equation coeffs*variables+constant=0
// in two's complement arithmetic
DFA *build_DFA_eq_2sc(int vars, int *coeffs, int constant, int *indices) {
	int min, max, states, next_index, next_label, result, target, count;
	long i;
	unsigned long j, transitions;
	struct map_ent *map;
	char *statuces;
	DFA *equality, *temp;

	if (preprocess(vars, coeffs, &constant, 0))
		return dfaFalse();

	//initialization

	min = 0;
	max = 0;
	for (i = 0; i < vars; i++)
		if (coeffs[i] > 0)
			max += coeffs[i];
		else
			min += coeffs[i];

	if (constant > max)
		max = constant;
	else if (constant < min)
		min = constant;
	states = 2 * max - 2 * min + 3;

	//This array maps state labels (carries) to state indices
	map = (struct map_ent *) malloc(states * sizeof(struct map_ent)) - min;
	for (i = min; i < max + 1; i++) {
		map[i].s = 0;
		map[i].sr = 0;
		map[i].i = -1;
		map[i].ir = -1;
	}
	map[constant].sr = 1; //the first state to be expanded
	next_index = 0; //the next available state index
	next_label = constant; //the next available state label
	map[constant].i = -1;
	map[constant].ir = 0;
	count = 0;

	transitions = 1 << vars; //number of transitions from each state

	//Begin building
	dfaSetup(states, vars, indices);

	while (next_label < max + 1) { //there is a state to expand (excuding sink)
		if (map[next_label].i == count)
			map[next_label].s = 2;
		else
			map[next_label].sr = 2;
		dfaAllocExceptions(transitions / 2);
		for (j = 0; j < transitions; j++) {
			result = next_label + count_ones(j, vars, coeffs);
			if (!(result & 1)) {
				target = result / 2;
				if (target == next_label) {
					if (map[target].s == 0) {
						map[target].s = 1;
						next_index++;
						map[target].i = next_index;
					}
					dfaStoreException(map[target].i, bintostr(j, vars));
				} else {
					if (map[target].sr == 0) {
						map[target].sr = 1;
						next_index++;
						map[target].ir = next_index;
					}
					dfaStoreException(map[target].ir, bintostr(j, vars));
				}
			}
		}
		dfaStoreState(states - 1);
		count++;
		for (next_label = min; (next_label <= max) && (map[next_label].i
				!= count) && (map[next_label].ir != count); next_label++)
			;
		//find next state to expand
	}
	for (; count < states; count++) {
		dfaAllocExceptions(0);
		dfaStoreState(states - 1);
	}

	//define accepting and rejecting states
	statuces = (char *) malloc(states + 1);
	for (i = 0; i < states; i++)
		statuces[i] = '-';
	for (next_label = min; next_label <= max; next_label++)
		if (map[next_label].s == 2)
			statuces[map[next_label].i] = '+';
	statuces[states] = '\0';
	temp = dfaBuild(statuces);
	equality = dfaMinimize(temp);
	dfaFree(temp);
	return equality;
}
Esempio n. 28
0
static void site_write_pointer(file_handle_t* handle)
{
        //Now, let's identify where the write pointer goes.
    //Each page has a byte at the beginning indicating the write sequence;
    //  the number of '1's indicates the write order. Writes start from 0xFE
    //  and continue down to 0x00; The last page written is the one with the
    //  largest value! A value of 0xFF indicates an unused page
    //  Notice that this scheme is bound to fail when files can be larger than
    //  seven blocks. In this case, a two-byte scheme or more is called for.
    //  The modificiations to make that happen shouldn't be hard to make.

    uint8_t first_write_page = 0;
    uint8_t pages_written = 0;
    uint8_t smallest = 0xFF;
    uint8_t i;
    uint8_t counter = 0;
    for (i = 0; i < (FILE_SIZE / FLASH_PAGE_SIZE); ++i) //iterate over pages
    {
        //read first byte
        flash_read(handle->start + (FLASH_PAGE_SIZE * i), &counter, 1);
        if (counter != 0xFF)
        {
            ++pages_written;
            if (counter < smallest)
            {
                smallest = counter;
                first_write_page = i;
            }
        }
    }
    handle->write_offset = first_write_page * FLASH_PAGE_SIZE;
    if (smallest < 0xFF)
    {
        handle->write_count = 8 - count_ones(smallest) + 1;
        if (handle->write_count == 9) handle->write_count = 1;
    }
    if (pages_written)
        handle->free_space = FILE_SIZE - ((pages_written - 1)*(FLASH_PAGE_SIZE - PAGE_COUNTER_SIZE)) - (FILE_SIZE / FLASH_PAGE_SIZE * PAGE_COUNTER_SIZE); //number of bytes written - number of counter bytes

    //now that we have the /page/ let's identify the /chunk/!
    //possibility that this page is entirely free, which we need to consider. Will recognize it because first byte is 0xFF
    //the strategy is to skip chunks until we find one whose size is 0xFF.
    //we do have to worry about flipping pages here, because we need to manage the page counter bytes, of course!
    uint8_t size = 0;
    flash_read(handle->start + handle->write_offset + 1, &size, 1);
    //a free chunk is one in which the size is 0xFF
    if (size == 0xFF) //starting on a fresh page
    {
        //read in the page counter to see if it is free or not.
        uint8_t check = 0;
        flash_read(handle->start + handle->write_offset, &check, PAGE_COUNTER_SIZE);
        if (check == 0xFF) //FREE SPACE! move in.
        {
            uint8_t counter = (0xFF << handle->write_count);
            ++handle->write_count;
            if (handle->write_count == 9) handle->write_count = 1;
            flash_write(handle->start + handle->write_offset, &counter, PAGE_COUNTER_SIZE);
        }
        handle->write_offset += PAGE_COUNTER_SIZE;
    }
    else //need to find our place in this page.
    {
        //skip past page counter
        handle->write_offset += PAGE_COUNTER_SIZE;
        flash_read(handle->start + handle->write_offset, &size, 1);
        while (size != 0xFF)
        {
            //advance a chunk
            handle->write_offset += size + 2;
            handle->free_space -= size + 2;
            //now, we may have crossed a page boundary. If we did, it is because the last page written was /completely/ full.
            // We need to stop advancing at this point, because either a) we have found free space or b) we have bumped up against a not-yet-consumed chunk
            // check which case that is, and if the space is free, then we need to set the page counter
            if (!(handle->write_offset % FLASH_PAGE_SIZE)) //yep, hit the start of a new page!
            {
                //read in the page counter to see if it is free or not.
                uint8_t check = 0;
                flash_read(handle->start + handle->write_offset, &check, PAGE_COUNTER_SIZE);
                if (check == 0xFF) //FREE SPACE! move in.
                {
                    uint8_t counter = (0xFF << handle->write_count);
                    ++handle->write_count;
                    if (handle->write_count == 9) handle->write_count = 1;
                    flash_write(handle->start + handle->write_offset, &counter, PAGE_COUNTER_SIZE);
                    handle->write_offset += PAGE_COUNTER_SIZE;
                }
                //else, do nothing, do not move into the page; it is not ready for writing. Need to linger where we are and wait.
                break; //exit the loop
            }
            flash_read(handle->start + handle->write_offset, &size, 1);
        }
    }
}
Esempio n. 29
0
void extract_bad_sector_map(byte * buffer)
{
	TRACE_FUN(8, "extract_bad_sector_map");

	/*  Fill the bad sector map with the contents of buffer.
	 */
	if (format_code == 4) {
		/* QIC-3010/3020 and wide QIC-80 tapes no longer have a failed
		 * sector log but use this area to extend the bad sector map.
		 */
		memcpy(bad_sector_map, buffer + 256, sizeof(bad_sector_map));
	} else {
		/* non-wide QIC-80 tapes have a failed sector log area that
		 * mustn't be included in the bad sector map.
		 */
		memcpy(bad_sector_map, buffer + 256 + FAILED_SECTOR_LOG_SIZE,
		       sizeof(bad_sector_map) - FAILED_SECTOR_LOG_SIZE);
	}
#if 0
	/* for testing of bad sector handling at end of tape
	 */
	((unsigned long *) bad_sector_map)[segments_per_track * tracks_per_tape - 3] = 0x000003e0;
	((unsigned long *) bad_sector_map)[segments_per_track * tracks_per_tape - 2] = 0xff3fffff;
	((unsigned long *) bad_sector_map)[segments_per_track * tracks_per_tape - 1] = 0xffffe000;
#endif
#if 0
	/*  Enable to test bad sector handling
	 */
	((unsigned long *) bad_sector_map)[30] = 0xfffffffe;
	((unsigned long *) bad_sector_map)[32] = 0x7fffffff;
	((unsigned long *) bad_sector_map)[34] = 0xfffeffff;
	((unsigned long *) bad_sector_map)[36] = 0x55555555;
	((unsigned long *) bad_sector_map)[38] = 0xffffffff;
	((unsigned long *) bad_sector_map)[50] = 0xffff0000;
	((unsigned long *) bad_sector_map)[51] = 0xffffffff;
	((unsigned long *) bad_sector_map)[52] = 0xffffffff;
	((unsigned long *) bad_sector_map)[53] = 0x0000ffff;
#endif
#if 0
	/*  Enable when testing multiple volume tar dumps.
	 */
	for (i = first_data_segment; i <= ftape_last_segment.id - 7; ++i) {
		((unsigned long *) bad_sector_map)[i] = EMPTY_SEGMENT;
	}
#endif
#if 0
	/*  Enable when testing bit positions in *_error_map
	 */
	for (i = first_data_segment; i <= ftape_last_segment.id; ++i) {
		((unsigned long *) bad_sector_map)[i] |= 0x00ff00ff;
	}
#endif
	if (tracing > 2) {
		unsigned int map;
		int good_sectors = 0;
		int bad_sectors;
		unsigned int total_bad = 0;
		int i;

		if (format_code == 4 || format_code == 3) {
			byte *ptr = bad_sector_map;
			unsigned sector;

			do {
				sector = get_sector(&ptr, forward);
				if (sector != 0) {
					if (format_code == 4 && sector & 0x800000) {
						total_bad += SECTORS_PER_SEGMENT - 3;
						TRACEx1(6, "bad segment at sector: %6d", sector & 0x7fffff);
					} else {
						++total_bad;
						TRACEx1(6, "bad sector: %6d", sector);
					}
				}
			} while (sector != 0);
			/*  Display end-of-file marks
			 */
			do {
				sector = *((unsigned short *) ptr)++;
				if (sector) {
					TRACEx2(4, "eof mark: %4d/%2d", sector,
					    *((unsigned short *) ptr)++);
				}
			} while (sector);
		} else {
			for (i = first_data_segment;
			 i < segments_per_track * tracks_per_tape; ++i) {
				map = ((unsigned long *) bad_sector_map)[i];
				bad_sectors = count_ones(map);
				if (bad_sectors > 0) {
					TRACEx2(6, "bsm for segment %4d: 0x%08x", i, map);
					if (bad_sectors > SECTORS_PER_SEGMENT - 3) {
						bad_sectors = SECTORS_PER_SEGMENT - 3;
					}
					total_bad += bad_sectors;
				}
			}
		}
		good_sectors = ((segments_per_track * tracks_per_tape - first_data_segment)
				* (SECTORS_PER_SEGMENT - 3)) - total_bad;
		TRACEx1(3, "%d Kb usable on this tape",
			good_sectors - ftape_last_segment.free);
		if (total_bad == 0) {
			TRACE(1, "WARNING: this tape has no bad blocks registered !");
		} else {
			TRACEx1(2, "%d bad sectors", total_bad);
		}
	}
	TRACE_EXIT;
}
int main(){
	printf("%d\n", count_ones(0xFF75));
	printf("%d\n", count_ones(0x0085));
}