/***********************************************************
	list.c -- list files in archive
***********************************************************/
#include <stdio.h>
#include <string.h>
#include <time.h>
#include "lh.h"

static int filecount;
static long originalsize, packedsize;

void initlist(void)
{
	filecount = originalsize = packedsize = 0;
	if (flg_n == 0) {
		printf("  Name          Original    Packed  Ratio"
			   "   Date     Time   Attr Type  CRC\n");
		printf("--------------  --------  -------- ------"
			   " -------- -------- ---- ----- ----\n");
	}
}

static void expanddate(char *buf, time_t t, ulong org, ulong pac)
{
	struct tm *tm;
	int rt;

	tm = localtime(&t);
	rt = ratio(pac, org, 3);
	sprintf(buf + 14, "%10lu%10lu %3d.%1d%% "
		"%02d-%02d-%02d %02d:%02d:%02d",
	    org, pac, rt / 10, rt % 10,
	    tm -> tm_year % 100,
	    tm -> tm_mon + 1,
	    tm -> tm_mday,
	    tm -> tm_hour,
	    tm -> tm_min,
	    tm -> tm_sec);
}

void list(void)
{
	char buf[79], *p, *q;
	static char attr[7] = "ohs--a";
	int i, j, k;

	p = hpb.filename;
	q = hpb.pathname;
	if (flg_n == 0) {
		memset(buf, ' ', 14);
		expanddate(buf, hpb.utc, hpb.original, hpb.packed);
		sprintf(buf + 59, " ---w       %04X", hpb.filecrc);
		memcpy(&buf[65], hpb.method, 5);
		for (i = 0, j = 1; i < 6; i++, j <<= 1) {	/* attributes */
			if (hpb.attr & j) {
				k = attr[i];
				if (i <= 2) {
					buf[63 - i] = k;
				} else {
					buf[60] = k;
				}
			}
		}
		if (hpb.level < 0) {
			memset(&buf[71], '*', 4);	/* if no CRC suppoted */
		}
		if (flg_x) {
			puts(q);	/* display in 2 lines */
		} else {
			if (p != q) {		/* display in one line */
				*buf = '+';
			}
			memcpy(&buf[2], p, strlen(p));
		}
		puts(buf);
		filecount ++;
		originalsize += hpb.original;
		packedsize += hpb.packed;
	} else {
		if (flg_x) {
			puts(q);
		} else {
			puts(p);
		}
	}
}

void endlist(time_t arctime)
{
	char buf[79];

	if (flg_n == 0) {
		if (filecount) {
			printf("--------------  --------  -------- ------"
				   " -------- --------\n");
			sprintf(buf, "   %3d files  ", filecount);
			expanddate(buf, arctime, originalsize, packedsize);
			puts(buf);
		} else {
			printf("  no file\n");
		}
	}
}
