params

fidr=fopen([DATAPATH 'data35000_full.txt'],'r');
fidw=fopen([DATAPATH 'data35000_backgrounds.txt'],'w');

for i=1:NUM_IMAGES
   imgnum=fscanf(fidr,'%i',1);
   if floor((i-1)/100)==(i-1)/100, disp([i-1 imgnum]), end
   fprintf(fidw,'%i\t',imgnum);
   num_bins=fscanf(fidr,'%i',1);
   wich=zeros(1,218);
   for j=1:num_bins
      bin=fscanf(fidr,'%i',1);
      score=fscanf(fidr,'%f',1);
      wich(bin)=score;
   end
   if sum(wich)<0.97 | sum(wich)>1.03
      fprintf(1,'imgnum=%i, sum(wich)=%.3f\n',imgnum,sum(wich));
      keyboard
   end
   junk=fscanf(fidr,'%f',50); % skip 50-dim hist.
   
   num_blobs=fscanf(fidr,'%i',1);
   fprintf(fidw,'%i\n\n',num_blobs);
   for j=1:num_blobs
      background=wich;
      area=fscanf(fidr,'%f',1);
      junk=fscanf(fidr,'%f',4); % skip texture and location values
      
      num_bins=fscanf(fidr,'%i',1);
      fprintf(fidw,'%i',num_bins);      
      for k=1:num_bins
	 bin=fscanf(fidr,'%i',1);
	 score=fscanf(fidr,'%f',1);
	 fprintf(fidw,'\t%i %.3f', bin, score);
	 if bin<10, fprintf(fidw,'\t'); end
	 if k/3==floor(k/3) | k==num_bins
	    fprintf(fidw,'\n');
	 end
	 background(bin)=background(bin)-score*area;
      end
      background=background/sum(background);
      
      num_bins=sum(background > 0.001);
      fprintf(fidw,'%i',num_bins);
      used=0;
      for k=1:218
	 if background(k) > 0.001
	    used=used+1;
	    fprintf(fidw,'\t%i %.3f', k, background(k));
	    if k<10, fprintf(fidw,'\t'); end
	    if used/3==floor(used/3) & used<num_bins
	       fprintf(fidw,'\n');
	    end
	 end
      end
      fprintf(fidw,'\n');

      fscanf(fidr,'%f',4*10); % skip shape #'s
      bins=fscanf(fidr,'%i',4);
      fprintf(fidw,'%i ', bins);
      junk=fscanf(fidr,'%f',50); % skip 50-dim hist.
      fprintf(fidw,'\n\n');
   end      
   fprintf(fidw,'\n');
end

fclose(fidr);
fclose(fidw);
