/*
** Qdirgzip (c) Per Johansson 2005-03-07
** Also known as a slackers guide to quick-compress emulator-roms in
** given folders. ;)
**
** v1.0 - Initial release
** v1.1 - Bugfix, showed wrong ratio, fixed algo now.
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <exec/exec.h>
#include <dos/dos.h>
#include <proto/exec.h>
#include <proto/dos.h>

int scanandzip(char *path);
long GetFileSize(char *file);

int main(int argc, char *argv[])
{
	printf("Qdirgzip (c) Per Johansson\n");
	printf("gzips all files as separate entities in given folder.\n");
	printf("very useful for emulator roms-folders. ;)\n");
	printf("Usage: qdirgzip <directory>\n\n");
	if(argc <= 1)
	{
		printf("Bad args..\n");
		return 0;
	}
	scanandzip(argv[1]);
	return 0;
}


int scanandzip(char *path)
{
	char command[1024];
	char newfile[1024];
	struct FileInfoBlock fib;
	BPTR lock,old;
	int success=FALSE;
	long orgsize,newsize;

	memset(&fib,0,sizeof(struct FileInfoBlock));

	lock=IDOS->Lock(path,SHARED_LOCK);
	old=IDOS->CurrentDir(lock);
	if(lock != 0)
	{
		success = IDOS->Examine(lock,&fib);
		while ( success != 0 )
		{
			success=IDOS->ExNext(lock,&fib);

			if( IDOS->IoErr() == ERROR_NO_MORE_ENTRIES)
				break;
			if (fib.fib_DirEntryType == ST_FILE)
			{
				orgsize=newsize=0;
				memset(command,0,sizeof(command));
				sprintf(command,"gzip -f -N -q -9 \"%s\"",fib.fib_FileName);
				orgsize=fib.fib_Size;

				if(strstr(fib.fib_FileName,".gz") == 0)
				{
					IDOS->Execute(command,NULL,NULL);
					memset(newfile,0,sizeof(newfile));
					sprintf(newfile,"%s.gz",fib.fib_FileName);
					newsize=GetFileSize(newfile);

					//Print information
					printf("File: %s , org size: %ld , new size: %ld , ratio: %2.2f%%\n",fib.fib_FileName,orgsize,newsize,(float)100-((float)newsize*100/orgsize));
				}
			}
		}
		IDOS->UnLock(lock);
		IDOS->CurrentDir(old);
	}
	return TRUE;
}

long GetFileSize(char *file)
{
	BPTR fp;
	struct FileInfoBlock fib;
	long pos,len;
	fp=IDOS->FOpen((uint8 *)file,MODE_OLDFILE,0);
	if( fp == NULL)
		return NULL;
	IDOS->ExamineFH(fp,&fib);
	IDOS->FClose(fp);
	return fib.fib_Size;
}
