#define __VERSION__ 	"39"
#define __REVISION__ 	"4"
#define __NAME__			"Gallery"
#define __AUTHOR__		"Markus Hillenbrand"

char *V = "$VER: " __NAME__ " " __VERSION__ "." __REVISION__ " (" __DATE__ ")";

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

#include <GUIC_Classes/GUIC_System.hpp>
#include <GUIC_Classes/GUIC_Date.hpp>
#include <GUIC_Classes/GUIC_Error.hpp>
#include <GUIC_Classes/GUIC_Frame.hpp>
#include <GUIC_Classes/GUIC_Application.hpp>
#include <GUIC_Classes/GUIC_Screen.hpp>
#include <GUIC_Classes/GUIC_Window.hpp>
#include <GUIC_Classes/GUIC_Error.hpp>
#include <GUIC_Classes/GUIC_Exceptions.hpp>
#include <GUIC_Classes/GUIC_DirectoryExamine.hpp>
#include <GUIC_Classes/GUIC_FileExamine.hpp>
#include <GUIC_Classes/GUIC_File.hpp>
#include <GUIC_Classes/GUIC_Key.hpp>
#include <GUIC_Classes/GUIC_List.hpp>
#include <GUIC_Classes/GUIC_Node.hpp>
#include <GUIC_Classes/GUIC_Exceptions.hpp>
#include <GUIC_Classes/GUIC_Button.hpp>
#include <GUIC_Classes/GUIC_Checkbox.hpp>
#include <GUIC_Classes/GUIC_String.hpp>
#include <GUIC_Classes/GUIC_Integer.hpp>
#include <GUIC_Classes/GUIC_Slider.hpp>
#include <GUIC_Classes/GUIC_Label.hpp>
#include <GUIC_Classes/GUIC_SlidingInteger.hpp>
#include <GUIC_Classes/GUIC_FileString.hpp>
#include <GUIC_Classes/GUIC_PathString.hpp>
#include <GUIC_Classes/GUIC_Message.hpp>
#include <GUIC_Classes/GUIC_FileRequester.hpp>
#include <GUIC_Classes/GUIC_ProgramArgs.hpp>

#define COPYRIGHT	"<SMALL> index file created with 'Gallery', (c) 1997 by <A HREF=\"http://www.student.uni-kl.de/~hillenbr\" TARGET=_top>Markus Hillenbrand</A> </SMALL>"
#define FILEFILTER 	"#?.(jpeg|jpg|gif|iff|ilbm|iff24|png|bmp|pcx|tiff)"

// Defines 
#define MINLINES							3
#define MINCOLUMNS					3	
#define MAXLINES							200
#define MAXCOLUMNS					200	
#define DEFAULTLINES					3
#define DEFAULTCOLUMNS			5
#define MENUFRAMEWIDTH			150
#define MINTHUMBNAILWIDTH 		50
#define MINTHUMBNAILHEIGHT		50
#define MAXTHUMBNAILWIDTH		200
#define MAXTHUMBNAILHEIGHT	200
#define DEFTHUMBNAILWIDTH 		100
#define DEFTHUMBNAILHEIGHT		100
#define MINTABLEBORDERSIZE		0
#define MAXTABLEBORDERSIZE	20
#define DEFTABLEBORDERSIZE		4

#include "GUIC_Register.hpp"

GUIC_ListC errorList;
int lastDay=0,lastMonth=0,lastYear=0;


class GalleryEntryC : public GUIC_ObjectC
	{
	public:
		GalleryEntryC		(STRPTR f, LONG s, int d, int m, int y) 	{ fileName=f; size=s; day=d; month=m; year=y; }
		int 		compare	(GUIC_ObjectC &o);
		void	print		(void) { cout << fileName << endl; }
		String fileName;
		int day,month,year;
		LONG size;
	protected:
		void cleanUp(void) {};
	};
	
int GalleryEntryC::compare(GUIC_ObjectC &o)
{ 
	// First we must convert the argument to what it really is:
	GalleryEntryC *g = (GalleryEntryC *)&o; 
	
	return strcmp(this->fileName, g->fileName); // Just compare the two file names	
}

String 	makeThumbnail	(GUIC_FileExamineC &file, LONG thumbnailWidth, LONG thumbnailHeight)
{
	String fileName = file.getName();

	int i = fileName.length();
	while (--i) if (fileName[i] == '.') break;

	String thumbName = fileName.left(i);
	thumbName+="_.jpg";

	try
		{
		GUIC_FileExamineC f(thumbName);
		if (f.newer(file)) return thumbName;
		}
	catch (GUIC_SystemX &e) { }

	char args[1024];
	sprintf ( args, "<>NIL: \"%s\" TO \"%s\" FORMAT JPEG QUALITY 90 BOXFIT %ld %ld", (char *)fileName, (char *)thumbName, thumbnailWidth, thumbnailHeight);

	cout << " - creating thumbnail for file '" << fileName << "' ... " << flush;
	BOOL result = GUIC_SystemC::runProgram("GfxCon_68020", 100000, args);
	if (result) cout << "done." << endl; else cout << "error occured." << endl;

	return thumbName;
}
void 		createGallery		(GUIC_ListC &fileList, STRPTR pattern, LONG linesInTable, LONG columnsInTable, BOOL picClick, BOOL showSize, BOOL showDate, LONG menuFrameWidth, LONG thumbnailWidth, LONG thumbnailHeight, LONG tableBorderSize, STRPTR baseName)
{
	GalleryEntryC *key = (GalleryEntryC *)fileList.objectAt(1);
	GUIC_FileExamineC firstFile(key->fileName);
	String currentDir = firstFile.getPathPart();
	
	ldiv_t d = ldiv ( fileList.length(), columnsInTable );
	int lines = d.quot;
	if (d.rem) lines++;
	
	d = ldiv (lines, linesInTable);
	int galleries = d.quot;
	if (d.rem) galleries++;

	cout << "Creating " << galleries << " galleries in directory '" << currentDir << "' " << endl;
	
	fileList.sort();
	
	GUIC_FileExamineC directoryName(currentDir);

	// Create the index file with the frames
	STRPTR st = (STRPTR) malloc (strlen(baseName) + 6);
	if (! st) throw GUIC_MemoryX("Can't allocate memory for a string.");
	sprintf(st, "%s.html", baseName);
	GUIC_FileC gallery(currentDir, st, GUIC_Write);
	free (st);
	
	gallery.write("<TITLE>Gallery '");
	gallery.write(directoryName.getFilePart());
	gallery.writeLn("'</TITLE>");
	gallery.write("<FRAMESET COLS=");
	gallery.write(menuFrameWidth);
	gallery.writeLn(",*>");
	gallery.write("<FRAME NAME=F1 SRC=\"");
	gallery.write(baseName);
	gallery.writeLn("0.html\" MarginHeight=0 MarginWidth=0 Scrolling=\"auto\" FrameBorder=0>");
	gallery.write("<FRAME NAME=F2 SRC=\"");
	gallery.write(baseName);
	gallery.writeLn("1.html\" MarginHeight=0 MarginWidth=0 Scrolling=\"auto\" FrameBorder=0>");
	gallery.writeLn("</FRAMESET>");
	
	// now create the overview over the galleries
	st = (STRPTR) malloc (strlen(baseName) + 7);
	if (! st) throw GUIC_MemoryX("Can't allocate memory for a string.");
	sprintf(st, "%s0.html", baseName);
	GUIC_FileC overview (currentDir, st, GUIC_Write);
	free(st);
	
	overview.writeLn("<HTML>");
	overview.write("<H2 ALIGN=Center>"); 
	overview.write(directoryName.getFilePart());
	overview.writeLn("</H2><BR><UL>");
	for (int i=1; i<=galleries; i++)
		{
		overview.write("<LI><A HREF=\"");
		overview.write(baseName);
		overview.write(i);
		overview.write(".html\" TARGET=F2>Gallery ");
		overview.write(i);
		overview.writeLn("</A> <BR>");
		}
		
	overview.write("</UL><BR> <BR> <IMG SRC=internal-gopher-menu> <A HREF=\"../");
	overview.write(baseName);
	overview.writeLn(".html\" TARGET=_top> up </A>");
	overview.writeLn("</HTML>");

	// create each gallery
	int count = 0;
	for (i=1; i<=galleries; i++)
		{
		char filename[256];
		sprintf(filename, "%s%ld.html", baseName, i);
		GUIC_FileC indexFile(currentDir, filename, GUIC_Write);

		// write head and title	
		indexFile.writeLn("<HTML>");
		indexFile.writeLn("<HEAD>");
	
		indexFile.write("<TITLE> "); indexFile.write(directoryName.getFilePart());	indexFile.writeLn(" </TITLE>");
		indexFile.writeLn("</HEAD>");
		indexFile.write("<BODY");
		if (pattern)
			{
			indexFile.write(" Background=\"");
			indexFile.write(pattern);
			indexFile.write("\"");
			}
		indexFile.writeLn(">");
		
		indexFile.write("<CENTER><H2>"); 
		indexFile.write(directoryName.getFilePart()); 
		indexFile.write("</H2> (Part ");
		indexFile.write(i);
		indexFile.write(" of ");
		indexFile.write(galleries);
		indexFile.writeLn(")<BR>");

		indexFile.writeLn("<HR>");
		indexFile.write("<TABLE Border=");
		indexFile.write(tableBorderSize);
		indexFile.writeLn(" CellSpacing=4 CellPadding=4>");
		
		int boundary = count + columnsInTable*linesInTable;
		if (boundary>fileList.length()) boundary = fileList.length();
		
		for (int j=count; j<boundary; j++)
			{
			key = (GalleryEntryC *)fileList.objectAt(j+1);
			GUIC_FileExamineC file(key->fileName);
			String thumbName = "";
			
			// Create the thumbnail now			
			try
				{
				thumbName = makeThumbnail(file, thumbnailWidth, thumbnailHeight);
				GUIC_FileExamineC thumb (thumbName);
				thumbName = thumb.getFilePart();
				}
			catch (GUIC_SystemX &e) { GalleryEntryC *s = new GalleryEntryC(key->fileName,0,0,0,0); errorList.addTail(*s); }

			// Check the date
			GUIC_DateC oldDate(lastDay,lastMonth,lastYear),*fileDate = file.getDate();;
			if (fileDate->greater(oldDate) )
				{
				lastDay   = fileDate->getDay();
				lastMonth = fileDate->getMonth();
				lastYear  = fileDate->getYear();
				}

			// Check if there are enough entries per line in the table
			if (count++ % columnsInTable == 0) indexFile.write("<TR> ");

			// write the picture data
			indexFile.write("<TD> <CENTER>");
			
			if (picClick)
				{
				indexFile.write("<A HREF=\"");
				indexFile.write(file.getFilePart());
				indexFile.write("\"> <IMG SRC=\"");
				indexFile.write(thumbName);
				indexFile.write("\" ALT=Thumbnail BORDER=0> <BR>");
				}
			else
				{
				indexFile.write("<IMG SRC=\"");
				indexFile.write(thumbName);
				indexFile.write("\" ALT=Thumbnail> <BR>");
				indexFile.write("<A HREF=\"");
				indexFile.write(file.getFilePart());
				indexFile.write("\">");
				}
				
			indexFile.write(file.getFilePart());
			indexFile.write(" </A>");
			if (showSize)
				{
				indexFile.write("<BR> Size: ");
				indexFile.write(key->size);
				}
			if (showDate)
				{
				indexFile.write("<BR> Date: ");
				indexFile.write(key->day);
				indexFile.write(".");
				indexFile.write(key->month);
				indexFile.write(".");
				indexFile.write(key->year);
				}
			indexFile.writeLn("</TD>");
			}
			
		indexFile.writeLn("</TABLE>");

		indexFile.writeLn("<HR>");
		indexFile.writeLn(COPYRIGHT);
		indexFile.writeLn("</BODY>");
		indexFile.writeLn("</HTML>");
		}
}
void 		createHTML		(GUIC_ListC &fileList, STRPTR pattern, BOOL showDate, LONG tableBorderSize, STRPTR baseName)
{
	GalleryEntryC *key = (GalleryEntryC *)fileList.objectAt(1);
	GUIC_FileExamineC firstFile(key->fileName);

	STRPTR currentDir = firstFile.getPathPart();
	STRPTR st = (STRPTR) malloc (strlen(baseName) + 6);
	if (! st) throw GUIC_MemoryX("Can't allocate memory for a string.");
	sprintf(st, "%s.html", baseName);
	GUIC_FileC indexFile(currentDir, st, GUIC_Write);
	free (st);
	
	GUIC_FileExamineC directoryName(currentDir);

	String titleString = directoryName.getFilePart();
	if (titleString == String("") ) titleString = directoryName.getName();

	cout << "Creating file '" << indexFile.getName() << "'" << endl;

	indexFile.writeLn("<HTML>");
	indexFile.writeLn("<HEAD>");
	indexFile.write("<TITLE> "); indexFile.write(titleString); indexFile.writeLn(" </TITLE>");
	indexFile.writeLn("</HEAD>");
	indexFile.write("<BODY");
	if (pattern)
		{
		indexFile.write(" Background=\"");
		indexFile.write(pattern);
		indexFile.write("\"");
		}
	indexFile.writeLn(">");
	indexFile.write("<CENTER><H1>"); indexFile.write(titleString); indexFile.writeLn("</H1>");
	indexFile.writeLn("<HR><BR><BR>");
	
	// Create the table of galleries
	
	indexFile.write("<TABLE Border=");
	indexFile.write(tableBorderSize);
	indexFile.writeLn(" CellSpacing=4 CellPadding=4>");
	indexFile.write("<TR> <TH> <CENTER> <H3> Gallery Name </H3> </TH> <TH> <CENTER> <H3> Entries </H3> </TH>");
	if (showDate) indexFile.write("<TH> <CENTER> <H3> Last Update </H3> </TH>");
	indexFile.writeLn("");
	
	fileList.sort();
	
	for (int i=1; i<=fileList.length(); i++)
		{
		key = (GalleryEntryC *)fileList.objectAt(i);
		GUIC_FileExamineC file (key->fileName);

		indexFile.write("<TR> <TD> <CENTER> <A HREF=\"");
		indexFile.write(file.getFilePart());
		indexFile.write("/");
		indexFile.write(baseName);
		indexFile.write(".html\"");
		indexFile.write("> ");
		indexFile.write(file.getFilePart());
		indexFile.write(" </A> </TD> <TD> <CENTER> ");
		indexFile.write(key->size);
		
		if (showDate)
			{			
			indexFile.write(" </TD> <TD> <CENTER> ");

			if (key->day)
				{
				indexFile.write(key->day);
				indexFile.write(".");
				indexFile.write(key->month);
				indexFile.write(".");
				indexFile.write(key->year);
				}
			else indexFile.write("(Directory)");
			}
			
		indexFile.writeLn(" </TD>");
		}

	indexFile.writeLn("</TABLE>");

	indexFile.write("<BR> <IMG SRC=internal-gopher-menu> <A HREF=\"../");
	indexFile.write(baseName);
	indexFile.writeLn(".html\" TARGET=_top> up </A> <BR>");

	indexFile.writeLn("<HR>");
	indexFile.writeLn(COPYRIGHT);
	indexFile.writeLn("</BODY>");
	indexFile.writeLn("</HTML>");
}
int 			scanDir				(STRPTR startDir, STRPTR pattern, LONG linesInTable, LONG columnsInTable, BOOL picClick, BOOL showSize, BOOL showDate, LONG menuFrameWidth, LONG thumbnailWidth, LONG thumbnailHeight, LONG tableBorderSize, STRPTR baseName)
{
	GUIC_ListC fileList,dirList;
	GalleryEntryC *key = 0;
	GUIC_FileExamineC *filex = 0;
	int entries = 0;

	GUIC_FileExamineC *examine = new GUIC_FileExamineC(startDir);
	if (!examine->isDirectory()) throw GUIC_SystemX("Error in function ScanDir (directory name expected).");
	String dirName = examine->getName();
	delete examine; examine=0;

	GUIC_DirectoryExamineC *direx= new GUIC_DirectoryExamineC(dirName);
	BOOL hasSubDirs = direx->hasSubdirectory();
	if (!hasSubDirs) direx->setFilter(FILEFILTER);

	try
		{
		while ( (filex = direx->examineNext()) )
			{
			String fileName  = filex->getName();
			GUIC_DateC *date = filex->getDate();

			if (filex->isDirectory())
				{
				String newPattern = String("../") + String(pattern);
				int entriesInDir  = scanDir(fileName, pattern ? (STRPTR) newPattern : 0, linesInTable, columnsInTable, picClick, showSize, showDate, menuFrameWidth, thumbnailWidth, thumbnailHeight, tableBorderSize, baseName);
				if (entriesInDir)
					{
					key = new GalleryEntryC(fileName, entriesInDir, lastDay, lastMonth, lastYear);
					if (!key) throw GUIC_MemoryX("Can't allocate memory for key.");
					dirList.addTail(*key);
					entries+=entriesInDir;
					}
				lastDay=0; lastMonth=0; lastYear=0;
				}
			else if (! hasSubDirs && (fileName.right(5) != String("_.jpg") ) )
				{
				key = new GalleryEntryC(fileName, filex->getSize(), date->getDay(), date->getMonth(), date->getYear() );
				if (!key) throw GUIC_MemoryX("Can't allocate memory for key.");
				fileList.addTail(*key);
				entries++;
				}
			}
		}
	catch (GUIC_SystemX &e) { cerr << "Exception caught while processing directory '" << direx->getName() << "': " << e.getMessage() << endl; }
	delete direx;direx=0; /* Damit der lock auf das Verzeichnis freigegeben wird ! */

	if (dirList.length()) 	createHTML		(dirList,pattern, showDate, tableBorderSize, baseName);
	if (fileList.length())	createGallery		(fileList,pattern, linesInTable, columnsInTable, picClick, showSize, showDate, menuFrameWidth, thumbnailWidth, thumbnailHeight, tableBorderSize, baseName);

	while (fileList.length()) delete (GalleryEntryC *)fileList.remove(1);
	while ( dirList.length()) delete (GalleryEntryC *) dirList.remove(1);

	return entries;
}


class GalleryWindowC : public GUIC_WindowC
	{
	public:
		GalleryWindowC		(GUIC_ApplicationC *app, GUIC_ScreenC *screen);
		~GalleryWindowC 	(void);
		BOOL action			(GUIC_EventC &);
	private:
		GUIC_ButtonC				*start, *quit;
		GUIC_RegisterC			*reg;
		GUIC_FileStringC			*pattern;
		GUIC_PathStringC		*directory;
		GUIC_SlidingIntegerC 	*lines, *columns, *width, *height, *tableBorder;
		GUIC_CheckboxC		*click, *size, *date;
		GUIC_IntegerC				*frame;
		GUIC_LabelC				*dirLabel, *pattLabel, *linesLabel, *columnsLabel, *clickLabel, *sizeLabel, *dateLabel, *frameLabel, *widthLabel, *heightLabel, *tableBorderLabel, *baseNameLabel;
		GUIC_StringC				*baseName;
	};
	
GalleryWindowC::GalleryWindowC	(GUIC_ApplicationC *app, GUIC_ScreenC *screen) : GUIC_WindowC (-1,-1,48,24)
{
	// Register erstellen
	reg = new GUIC_RegisterC			(1,1,46,19,4);
	
	reg -> setName(1, "Global");
	reg -> setName(2, "Tables");
	reg -> setName(3, "HTML");
	reg -> setName(4, "Thumbnail");

	reg -> setShortcut ('r');
		
	app -> addPrefs("Register", reg);

	add ( reg );


	// Erstes Register
	dirLabel				= new GUIC_LabelC			( 0, 4,10,2,"_Directory:");
	pattLabel			= new GUIC_LabelC			( 0, 6,10,2,"_Pattern:");
	baseNameLabel	= new GUIC_LabelC			( 0, 9,30,2,"_Base name for HTML files:");
	directory				= new GUIC_PathStringC	(11, 4,33,2,"");
	pattern				= new GUIC_FileStringC		(11, 6,33,2,"");
	baseName			= new GUIC_StringC			(31, 9,13,2,"index");

	directory		->setHelp("Directory for the first index file.");
	pattern		->setHelp("Background pattern in HTML pages.");
	baseName	->setHelp("Enter base file name without a suffix."),

	directory		->setShortcut('d');
	pattern		->setShortcut('p');
	baseName	->setShortcut('b');

	app->addPrefs("StartDirectory"		, directory);
	app->addPrefs("BackgroundPattern" , pattern);
	app->addPrefs("BaseName"				, baseName);
	
	reg->add(1, dirLabel);
	reg->add(1, pattLabel);
	reg->add(1, directory);
	reg->add(1, pattern);
	reg->add(1, baseNameLabel);
	reg->add(1, baseName);


	// Zweites Register
	linesLabel				= new GUIC_LabelC				( 0, 0,10,2,"_Lines:");
	columnsLabel			= new GUIC_LabelC				( 0, 2,10,2,"_Columns:");
	sizeLabel				= new GUIC_LabelC				( 0, 5,30,2,"Sh_ow size of picture:");
	dateLabel				= new GUIC_LabelC				( 0, 7,31,2,"Sho_w date of picture:");
	clickLabel				= new GUIC_LabelC				( 0,10,31,2,"_Use thumbnail picture as link:");
	tableBorderLabel	= new GUIC_LabelC				( 0,13,31,2,"Size of table's _border:");
	lines						= new GUIC_SlidingIntegerC	(11, 0,33,2,MINLINES,MAXLINES,DEFAULTLINES);
	columns					= new GUIC_SlidingIntegerC	(11, 2,33,2,MINCOLUMNS,MAXCOLUMNS,DEFAULTCOLUMNS);	
	size						= new GUIC_CheckboxC			(41, 5, 3,2,TRUE);
	date						= new GUIC_CheckboxC			(41, 7, 3,2,TRUE);
	click						= new GUIC_CheckboxC			(41,10, 3,2,FALSE);
	tableBorder				= new GUIC_SlidingIntegerC	(30,13,14,2,MINTABLEBORDERSIZE, MAXTABLEBORDERSIZE, DEFTABLEBORDERSIZE);
	
	lines			->setHelp("The number of lines per HTML table.");
	columns		->setHelp("The number of columns per HTML table.");
	size			->setHelp("Show picture's size in gallery?");
	date			->setHelp("Show picture's date in gallery?");
	click			->setHelp("Click on thumbnails to view picture?");
	tableBorder	->setHelp("Size of the border around the tables.");
	
	lines			->setShortcut('l');
	columns		->setShortcut('c');
	size			->setShortcut('o');
	date			->setShortcut('w');
	click			->setShortcut('u');
	tableBorder	->setShortcut('b');

	reg->add (2, linesLabel );
	reg->add (2, lines );
	reg->add (2, columnsLabel );
	reg->add (2, columns );
	reg->add (2, sizeLabel );
	reg->add (2, size );
	reg->add (2, dateLabel );
	reg->add (2, date );
	reg->add (2, clickLabel );
	reg->add (2, click );
	reg->add (2, tableBorderLabel);
	reg->add (2, tableBorder);
	

	// Drittes Register
	frameLabel		= new GUIC_LabelC	( 0, 7,35,2,"Width of menu _frame (left frame):");
	frame				= new GUIC_IntegerC	(36, 7,8,2,MENUFRAMEWIDTH);

	frame		->setJustification(GUIC_Right);

	frame		->setHelp("No. of pixels for the left hand frame.");

	frame		->setShortcut('f');

	reg->add (3, frameLabel );
	reg->add (3, frame );
	

	// Viertes Register
	widthLabel		= new GUIC_LabelC				( 0, 5,26, 2,"Max. _width of thumbnails:");
	heightLabel		= new GUIC_LabelC				( 0, 7,26, 2,"Max. _height of thumbnails:");
	width				= new GUIC_SlidingIntegerC	(27, 5,17, 2,MINTHUMBNAILWIDTH,MAXTHUMBNAILWIDTH,DEFTHUMBNAILWIDTH);
	height				= new GUIC_SlidingIntegerC	(27, 7,17, 2,MINTHUMBNAILHEIGHT,MAXTHUMBNAILHEIGHT,DEFTHUMBNAILHEIGHT);

	width		->setHelp("Maximum width for each thumbnail.");
	height		->setHelp("Maximum height for each thumbnail.");
	
	width		->setShortcut('w');
	height		->setShortcut('h');
	
	reg->add (4, widthLabel );
	reg->add (4, width );
	reg->add (4, heightLabel );
	reg->add (4, height );


	// Start und Quit Buttons
	start				= new GUIC_ButtonC				( 1,21,15,2,"_Start");
	quit					= new GUIC_ButtonC				(32,21,15,2,"_Quit");
	
	start		->setHelp("Start the creation of the gallery.");
	quit			->setHelp("Quit the program.");
	
	start		->setShortcut('s');
	quit			->setShortcut('q');

	add ( start );
	add ( quit );


	// Prefs für das Fenster 
	app->addPrefs("GalleryWindow"			, this);
	app->addPrefs("NumberOfLines"			, lines);
	app->addPrefs("NumberOfColumns"		, columns);
	app->addPrefs("PictureAsLink"				, click);
	app->addPrefs("TableFrameSize"			, tableBorder);
	app->addPrefs("ShowSize"					, size);
	app->addPrefs("ShowDate"					, date);
	app->addPrefs("MenuFrameWidth"		, frame);
	app->addPrefs("ThumbnailWidth"			, width);
	app->addPrefs("ThumbnailHeight"			, height);
		

	setTitle("Gallery - (c) by Markus Hillenbrand");
	setHelp(TRUE);
	
	activate();
}
GalleryWindowC::~GalleryWindowC	(void)
{
	delete reg;
	delete dirLabel;
	delete directory;
	delete pattLabel;
	delete pattern;
	delete linesLabel;
	delete lines;
	delete columnsLabel;
	delete columns;
	delete clickLabel;
	delete click;
	delete sizeLabel;
	delete size;
	delete dateLabel;
	delete date;
	delete frameLabel;
	delete frame;
	delete widthLabel;
	delete width;
	delete heightLabel;
	delete height;
	delete tableBorderLabel;
	delete tableBorder;
	delete start;
	delete quit;
}

BOOL GalleryWindowC::action(GUIC_EventC &e)
{
	switch (e.id)
		{
		case GUIC_GadgetEvent:
			if (e.gadget == (GUIC_GadgetC *)start)
				{
				if (! strcmp(directory->get(), "") )
					{
					GUIC_ErrorC e("You must at least enter a directory name!");
					e.request(this);
					}
				else 
					{
					GUIC_SystemC::openConsole();
					sleep();
					activate();
					try 
						{
						scanDir (directory->get(), pattern->get(), lines->get(), columns->get(), click->get(), size->get(), date->get(), frame->get(), width->get(), height->get(), tableBorder->get() , baseName->get() );
						}
					catch (GUIC_Exception &x) { GUIC_ErrorC e("Exception caught:", x.getMessage() ); e.request(this); }
					waken();
					}
				}
			else if (e.gadget == (GUIC_GadgetC *)quit) 
				{
				dispose();
				}
			return TRUE;
			break;
		case GUIC_OpenWindow:
			return TRUE;
			break;
		case GUIC_CloseWindow: 
			return FALSE;
			break;
		default:
			cerr << "Got an event: " << e.id << endl;
		}
	
	return FALSE;
}



void 		shell					(void)
{
	LONG result[] = { 0,0,0,0,0,0,0,0,0,0,0,0 };
	STRPTR templ = "STARTDIR/A,LINES/N,COLUMNS/N,BGPATTERN,PICCLICK/S,NOSIZE/S,NODATE/S,MENUFRAMEWIDTH/N,MAXTHUMBNAILWIDTH/N,MAXTHUMBNAILHEIGHT/N,TABLEBORDERSIZE/N,BASENAME";
	GUIC_ProgramArgsC args;
	if (! args.fit(templ, result))
		{
		cerr << "Usage: " << templ << endl;
		GUIC_SystemC::exit(GUIC_ExitError);
		}
	
	LONG lines = result[1] ? *(LONG *)result[1] : DEFAULTLINES;
	if (lines < MINLINES) 		lines=MINLINES;
	if (lines > MAXLINES)	lines=MAXLINES;
	
	LONG columns = result[2] ? *(LONG *)result[2] : DEFAULTCOLUMNS;
	if (columns < MINCOLUMNS) 	columns=MINCOLUMNS;
	if (columns > MAXCOLUMNS)	columns=MAXCOLUMNS;
	
	BOOL picclick		= result[4];
	BOOL showSize	= ! result[5];
	BOOL showDate	= ! result[6];
	
	LONG menuFrameWidth = result[7] ? *(LONG *)result[7] : MENUFRAMEWIDTH;
	
	LONG thumbnailWidth = result[8] ? *(LONG *)result[8] : DEFTHUMBNAILWIDTH;
	if (thumbnailWidth < MINTHUMBNAILWIDTH) 	thumbnailWidth=MINTHUMBNAILWIDTH;
	if (thumbnailWidth > MAXTHUMBNAILWIDTH)	thumbnailWidth=MAXTHUMBNAILWIDTH;

	LONG thumbnailHeight = result[9] ? *(LONG *)result[9] : DEFTHUMBNAILHEIGHT;
	if (thumbnailHeight < MINTHUMBNAILHEIGHT) 	thumbnailHeight=MINTHUMBNAILHEIGHT;
	if (thumbnailHeight > MAXTHUMBNAILHEIGHT)	thumbnailHeight=MAXTHUMBNAILHEIGHT;
	
	LONG tableBorderSize = result[10] ? *(LONG *)result[10] : DEFTABLEBORDERSIZE;
	if (tableBorderSize < MINTABLEBORDERSIZE) 	tableBorderSize=MINTABLEBORDERSIZE;
	if (tableBorderSize > MAXTABLEBORDERSIZE)	tableBorderSize=MAXTABLEBORDERSIZE;
	
	STRPTR baseName = result[11] ? (STRPTR) result[11] : "index";
	
	scanDir((STRPTR)result[0], (STRPTR)result[3], lines, columns, picclick, showSize, showDate, menuFrameWidth, thumbnailWidth, thumbnailHeight, tableBorderSize, baseName); 

	if (errorList.length())
		{
		cerr << "The following files could not be converted to a thumbnail:" << endl;
		while (errorList.length())
			{
			GalleryEntryC *s = (GalleryEntryC *)errorList.remove(1);
			cerr << "- " << s->fileName << endl;
			delete s;
			}
		cerr << "Please check them and run 'Gallery' again." << endl;
		}
}
void		workbench			(void)
{
	GUIC_ApplicationC	app("Gallery");

	app.setAuthor		(__AUTHOR__);
	app.setVersion	(__VERSION__);
	app.setRevision	(__REVISION__);
	app.setDate		(__DATE__);
	app.setTime		(__TIME__);
	app.setInitializer	(TRUE);

	GUIC_ScreenC			screen;
	GalleryWindowC 	window(&app, &screen);
	
	screen.add(window);
	app.add(screen);

	app.start();

	BOOL running = TRUE;
	GUIC_EventC *event = 0;

	int count = 0;
	
	while (running && (event = app.wait()) )
		{
		// As we have only one window, it is not neccessary to check for the window id
		if (event->id == GUIC_CloseWindow) 
			{
			GUIC_MessageC	message	("Do you really want to quit ?", "Yes|No");
			if (1 == message.request(*event->window)) running = FALSE;
			}
		}

	app.stop();
}

void 		main					(int argc, char **argv)
{
	GUIC_SystemC::checkStackSize(50000);
	if (GUIC_SystemC::runFromShell() ) shell(); else workbench();
}

