//tarblocks
//Take output from tar and format with block location info
//according to file sizes. Useful if data is being put to tape.

//v2 output bytes progress to stderr.

//19980902 - only count size for regular files '-'

//Public Domain

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define BLKSIZE 512
#define BLKPK (1024 / BLKSIZE)
#define BLKPM (BLKPK * 1000)
#define MB100 (BLKPM * 100)

void main ()
{

unsigned long int tarblocks = 0;
unsigned long int tb = 0;
unsigned long int size = 0;
char line[1024];
char *sizep;

fprintf(stderr, "Written:           ");

	while (fgets(line, 1023, stdin)) {
		
		fprintf(stdout, "rec %10lu: %s", tarblocks, line);
		
		fprintf(stderr, "\b\b\b\b\b\b\b\b\b\b\b");
		if ( tarblocks > MB100 ) { 
			fprintf(stderr, "%10luM", tarblocks / BLKPM );
		} else {
			fprintf(stderr, "%10luK", tarblocks / BLKPK );
		}	

		sizep = line;
		sizep = strtok(line, " ");
		 
		if (sizep[0] == '-') {	//skip non-regular files
			sizep = strtok(NULL, " ");
			sizep = strtok(NULL, " ");
			size = strtol(sizep, NULL, 0);
		} else {
			size = 0;
		}
			
		if (size > 0) {
			tb = size / BLKSIZE;
				
			if ( (size % BLKSIZE) > 0 ) {
				tb++;	//padded block
			}
			tarblocks += tb; 
		}
	
		tarblocks++;	//always a header
	}

	fprintf(stderr, "\b\b\b\b\b\b\b\b\b\b\b");
	if ( tarblocks > MB100 ) { 
		fprintf(stderr, "%10luM, %20lu bytes\n", tarblocks / BLKPM, tarblocks * BLKSIZE );
	} else {
		fprintf(stderr, "%10luK, %20lu bytes\n", tarblocks / BLKPK, tarblocks * BLKSIZE );
	}	
}
