#include <intuition/intuitionbase.h>
#include <intuition/intuition.h>
#include <libraries/dos.h>
#include <exec/memory.h>
#include <stdio.h>

struct IntuitionBase *IntuitionBase;
struct GfxBase *GfxBase;

#define SECSPERDAY (60*60*24)
#define SECSPERMIN 60
#define TICKSPERSEC TICKS_PER_SECOND

#define MAXNAME 128

char *stdfile();
extern char *Copyright;

main()
{
	char name[MAXNAME];

	if(!(IntuitionBase = OpenLibrary("intuition.library", 1))) {
		printf("Couldn't open intuition.library.\n");
		exit(20);
	}
	if(!(GfxBase = OpenLibrary("graphics.library", 1))) {
		printf("Couldn't open graphics.library.\n");
		CloseLibrary(IntuitionBase);
		exit(20);
	}

	printf("Testing STDFILE standard file requestor.\n%s\n", Copyright);

	name[0] = 0;
	while(stdfile("Display file", name, 0, name)) {
		BPTR stdlock;
		struct FileInfoBlock *stdfib;
		FILE *fp;
		long datestamp;
		int c;

		stdfib = AllocMem(sizeof(struct FileInfoBlock), MEMF_PUBLIC);
		if(!stdfib) {
			printf("Out of memory!\n");
			break;
		}

		if(!(stdlock = Lock(name, ACCESS_READ))) {
			printf("Can't obtain lock for %s\n", name);
			FreeMem(stdfib, sizeof(struct FileInfoBlock));
			continue;
		}
		if(!(Examine(stdlock, stdfib))) {
			printf("Can't examine %s\n", name);
			UnLock(stdlock);
			FreeMem(stdfib, sizeof(struct FileInfoBlock));
			continue;
		}
		UnLock(stdlock);

		if(stdfib->fib_DirEntryType >= 0) {
			printf("%s is a directory.\n", name);
			FreeMem(stdfib, sizeof(struct FileInfoBlock));
			continue;
		}
		if(!(fp = fopen(name, "r"))) {
			perror(name);
			FreeMem(stdfib, sizeof(struct FileInfoBlock));
			continue;
		}

		datestamp = stdfib->fib_Date.ds_Days*SECSPERDAY +
			      stdfib->fib_Date.ds_Minute*SECSPERMIN +
				  stdfib->fib_Date.ds_Tick/TICKSPERSEC;
		printf("\n%s, %s\n", stdfib->fib_FileName,
			ctime(&datestamp));
		while((c = getc(fp)) != EOF)
			putchar(c);
		fclose(fp);
		FreeMem(stdfib, sizeof(struct FileInfoBlock));
	}

	CloseLibrary(IntuitionBase);
	CloseLibrary(GfxBase);
}
