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

#include <clib/utility_protos.h>

#include <GUIC_Classes/GUIC_Error.hpp>
#include <GUIC_Classes/GUIC_Message.hpp>
#include <GUIC_Classes/GUIC_System.hpp>
#include <GUIC_Classes/GUIC_DirectoryExamine.hpp>

#include "GalleryWindow.hpp"
#include "StatusWindow.hpp"

/*********************************************************************************************************/

static class GalleryEntryC : public GUIC_ObjectC
	{
	public:
		GalleryEntryC			(STRPTR f, LONG s, LONG d, LONG m, LONG y, BOOL i, STRPTR p);
		LONG		compare	(GUIC_ObjectC &o);
		VOID		print		(VOID);
		STRING 	fileName, pattern;
		LONG 	day, month, year;
		LONG 	size;
		BOOL 	isDirectory;
	protected:
		VOID		cleanUp	(VOID);
	};

GalleryEntryC::GalleryEntryC		(STRPTR f, LONG s, LONG d, LONG m, LONG y, BOOL i, STRPTR p)
{ 
	fileName=f; 
	size=s; 
	day=d; 
	month=m; 
	year=y; 
	isDirectory = i;
	pattern = p;
}
LONG	GalleryEntryC::compare	(GUIC_ObjectC &o)
{
	// First we must convert the argument to what it really is:
	GalleryEntryC *g = (GalleryEntryC *)&o; 
	return Stricmp(this->fileName, g->fileName); // Just compare the two file names	
}
VOID	GalleryEntryC::print			(VOID)
{ 
	cout << fileName << " -> " << size << endl; 
}
VOID	GalleryEntryC::cleanUp	(VOID)
{
}

	
/*********************************************************************************************************/
	
GalleryWindowC::GalleryWindowC					(GUIC_ApplicationC *app, GUIC_ScreenC *screen, StatusWindowC *sWindow) : GUIC_WindowC (-1,-1,48,24)
{
	totalFiles			= 0;
	actualFiles			= 0;
	this->screen		= screen;
	this->app			= app;
	this->sWindow	= sWindow;
	
	// 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 ('g');
		
	app -> addPrefs("Register", reg);

	add ( reg );


	// Erstes Register (GLOBAL)
	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");
	
	pattern		->setFilter(GUIC_PictureFile);

	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 (TABLES)
	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');

	app->addPrefs("NumberOfLines"			, lines);
	app->addPrefs("NumberOfColumns"		, columns);
	app->addPrefs("ShowSize"					, size);
	app->addPrefs("ShowDate"					, date);
	app->addPrefs("PictureAsLink"				, click);
	app->addPrefs("TableFrameSize"			, tableBorder);

	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 (HTML)
	noFramesLabel	= new GUIC_LabelC		( 0, 6,35,2,"Don't _create frames:");
	noFrames			= new GUIC_CheckboxC	(41, 6, 3,2,FALSE);
	frameLabel			= new GUIC_LabelC		( 0, 8,35,2,"Width of menu _frame (left frame):");
	frame					= new GUIC_IntegerC		(36, 8,8,2,MENUFRAMEWIDTH);

	noFrames	->setHelp("Check if you don't want to have frames.");
	noFrames	->setShortcut('c');
	
	frame		->setJustification(GUIC_Right);
	frame		->setHelp("No. of pixels for the left hand frame.");
	frame		->setShortcut('f');

	app->addPrefs("NoFrames"					, noFrames);
	app->addPrefs("MenuFrameWidth"		, frame);

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

	// Viertes Register (THUMBNAIL)
	programLabel		= new GUIC_LabelC				( 0, 1,44, 2,"System _call to create the thumbnails");
	widthLabel			= new GUIC_LabelC				( 0, 6,26, 2,"Max. _width of thumbnails:");
	heightLabel			= new GUIC_LabelC				( 0, 8,26, 2,"Max. _height of thumbnails:");
	createAllLabel	= new GUIC_LabelC				( 0,11,40, 2,"Create _thumbnail for all pictures found:");
	program				= new GUIC_StringC				( 0, 3,44, 2,COMMAND);
	width					= new GUIC_SlidingIntegerC	(27, 6,17, 2,MINTHUMBNAILWIDTH,MAXTHUMBNAILWIDTH,DEFTHUMBNAILWIDTH);
	height					= new GUIC_SlidingIntegerC	(27, 8,17, 2,MINTHUMBNAILHEIGHT,MAXTHUMBNAILHEIGHT,DEFTHUMBNAILHEIGHT);
	createAll				= new GUIC_CheckboxC			(41,11, 3, 2,FALSE);

	width		->setHelp("Maximum width for each thumbnail.");
	height		->setHelp("Maximum height for each thumbnail.");
	createAll	->setHelp("Do it even in directories with subdirs.");
	
	program	->setMaxChars(128);
	
	program	->setShortcut('c');
	width		->setShortcut('w');
	height		->setShortcut('h');
	createAll ->setShortcut('t');
	
	app->addPrefs("ThumbnailWidth"			, width);
	app->addPrefs("ThumbnailHeight"			, height);
	app->addPrefs("SystemCall"					, program);
	app->addPrefs("CreateAllThumbnails"	, createAll);

	reg->add (4, programLabel );
	reg->add (4, program );
	reg->add (4, widthLabel );
	reg->add (4, width );
	reg->add (4, heightLabel );
	reg->add (4, height );
	reg->add (4, createAllLabel );
	reg->add (4, createAll );


	// 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);

	STRING t = app->getName();
	t += " - (c) by ";
	t += app->getAuthor();
	setTitle(t);
	
	setHelp(TRUE);
	
	activate();
}
GalleryWindowC::~GalleryWindowC					(VOID)
{
	cleanUp();
}

/*********************************************************************************************************/

VOID 		GalleryWindowC::createHTML			(GUIC_ListC &fileList, STRPTR pattern, BOOL showDate, LONG tableBorderSize, STRPTR baseName, BOOL noFrames)
{
	GalleryEntryC *key = (GalleryEntryC *)fileList.objectAt(1);
	GUIC_FileExamineC firstFile(key->fileName);

	STRPTR currentDir = firstFile.getPathPart(), st = 0;
	GUIC_SystemC::reallocString(&st, baseName, ".html");
	GUIC_FileC indexFile(currentDir, st, GUIC_Write);
	
	GUIC_FileExamineC directoryName(currentDir);

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

	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.writeLn("<TR> <TH> <CENTER> <H3> Gallery Name </H3> </TH> <TH> <CENTER> <H3> Entries </H3> </TH>");
	
	fileList.sort();
	
	for (LONG 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);
		
		if (noFrames) indexFile.write("1");
		
		indexFile.write(".html\"");
		indexFile.write("> ");
		indexFile.write(file.getFilePart());
		indexFile.write(" </A> </TD> <TD> <CENTER> ");
		indexFile.write(key->size);
		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>");
}
VOID 		GalleryWindowC::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, BOOL noFrames)
{
	ULONG pictureFiles = fileList.length();
	
	GalleryEntryC *key = (GalleryEntryC *)fileList.objectAt(1);
	GUIC_FileExamineC firstFile(key->fileName);
	STRING currentDir = firstFile.getPathPart();
	
	ldiv_t d = ldiv ( pictureFiles, columnsInTable );
	LONG lines = d.quot;
	if (d.rem) lines++;
	
	d = ldiv (lines, linesInTable);
	LONG galleries = d.quot;
	if (d.rem) galleries++;

	fileList.sort();
	
	GUIC_FileExamineC directoryName(currentDir);

	if (! noFrames) // Create frames and overview
		{
		// Create the index file with the frames
		STRPTR st = 0;
		GUIC_SystemC::reallocString(&st, baseName, ".html");
		GUIC_FileC gallery(currentDir, st, GUIC_Write);
		
		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
		GUIC_SystemC::reallocString(&st, baseName, "0.html");
		GUIC_FileC overview (currentDir, st, GUIC_Write);
	
		overview.writeLn("<HTML>");
		overview.write("<BODY");
		if (pattern)
			{
			overview.write(" Background=\"");
			overview.write(pattern);
			overview.write("\"");
			}
		overview.writeLn(">");
		overview.write("<H2 ALIGN=Center>"); 
		overview.write(directoryName.getFilePart());
		overview.writeLn("</H2><BR><UL>");
		for (LONG 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("</BODY>\n</HTML>");
		}

	// create each gallery
	LONG count = 0;
	for (LONG 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>");
		
		LONG boundary = count + columnsInTable*linesInTable;
		if (boundary>pictureFiles) boundary = pictureFiles;
		
		for (LONG 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, FALSE, ""); errorList.addTail(*s); }

			// Check if there are enough entries per line in the table
			if (count++ % columnsInTable == 0) indexFile.write("<TR> ");
			
			// Now that count ist increased, update the status window
			sWindow->setPercent ( (++actualFiles * 100) / totalFiles );

			// 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>");
		
		if (noFrames && galleries>1) // then create jump points
			{
			indexFile.writeLn("<BR>");
			
			if (i > 1) 
				{
				indexFile.write("<A HREF=\"");
				indexFile.write(baseName);
				indexFile.write(i-1);
				indexFile.writeLn(".html\">[prev] </A>");
				}
			else indexFile.writeLn("[prev] ");
			
			for (LONG gal=1; gal<=galleries; gal++)
				{
				if (i != gal)
					{
					indexFile.write(" <A HREF=\"");
					indexFile.write(baseName);
					indexFile.write(gal);
					indexFile.write(".html\">");
					indexFile.write(gal);
					indexFile.writeLn("</A> ");
					}
				else 
					{
					indexFile.write(" ");
					indexFile.write(gal);
					indexFile.writeLn(" ");
					}
				}
			
			if (i < galleries) 
				{
				indexFile.write("<A HREF=\"");
				indexFile.write(baseName);
				indexFile.write(i+1);
				indexFile.writeLn(".html\"> [next]</A>");
				}
			else indexFile.writeLn("[next]");
			
			indexFile.write("<BR> <IMG SRC=internal-gopher-menu> <A HREF=\"../");
			indexFile.write(baseName);
			indexFile.writeLn(".html\"> up </A>");

			}

		indexFile.writeLn("<HR>");
		indexFile.writeLn(COPYRIGHT);
		indexFile.writeLn("</BODY>");
		indexFile.writeLn("</HTML>");
		}
}
BOOL		GalleryWindowC::action					(GUIC_EventC &e)
{
	switch (e.id)
		{
		case GUIC_GadgetEvent:
			if (e.gadget == (GUIC_GadgetC *)start)
				{
				if (! strcmp(directory->get(), "") )
					{
					GUIC_ErrorC err("You must at least enter a directory name!");
					err.request(this);
					}
				else 
					{
					sleep();

					screen->add(sWindow);
					sWindow->sleep();
					
					try 
						{
						sWindow->setMessage ( "Scanning for picture files." );
						totalFiles 	= scanDirectory ( directory->get(), pattern->get(), createAll->get() );
						actualFiles	= 0;
						
						sWindow->setMessage ( "Sorting file list." );
						fileList.sort();
						
						char st [64];
						sprintf(st, "Processing %ld files.", totalFiles);
						sWindow->setMessage ( st );
						generateGallery();
						
						// Nachsehen, ob es Fehlermeldungen gab:
						if (errorList.length())
							{
							GUIC_MessageC err ("Some errors have occured while scanning/creating thumbnails:", "Print|Forget");
							if (1 == err.request(this))
								{
								GUIC_SystemC::openConsole();
								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;
								}
							else 
								{
								while (errorList.length()) delete (GalleryEntryC*) errorList.remove(1);
								}
							}
						}
					catch (GUIC_Exception &x) { GUIC_ErrorC e("Exception caught:", x.getMessage() ); e.request(this); }
					
					// File Liste wieder löschen
					while ( fileList.length() ) delete (GalleryEntryC *)fileList.remove(1);
					
					sWindow->waken();
					screen->remove(sWindow);
					
					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;
}
ULONG	GalleryWindowC::scanDirectory		(STRPTR startDir, STRPTR pattern, BOOL allFiles)
{
	GUIC_ListC subdirList;
	
	GalleryEntryC *key = 0;
	GUIC_FileExamineC *filex = 0;
	LONG entries = 0;

	GUIC_FileExamineC *examine = new GUIC_FileExamineC(startDir);
	if (!examine->isDirectory()) throw GUIC_SystemX("Error in method scanDirectory (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 = "../"; newPattern += pattern;
				ULONG entriesInDir = scanDirectory ((STRPTR)fileName, (STRPTR)newPattern, allFiles);
				if (entriesInDir)
					{
					entries+=entriesInDir;
					GUIC_DirectoryExamineC d(fileName);
					key = new GalleryEntryC(fileName, entriesInDir, 0, 0, 0, TRUE, newPattern );
					if (! d.hasSubdirectory() )
						{
						fileList.addTail(key);
						subdirList.addTail( new GalleryEntryC(fileName, entriesInDir, 0, 0, 0, TRUE, newPattern ) );
						}
					else 
						{
						subdirList.addTail(key);
						}
					}
				}
			else if (! hasSubDirs && (fileName.right(5) != STRING("_.jpg") ) )
				{
				key = new GalleryEntryC(fileName, filex->getSize(), date->getDay(), date->getMonth(), date->getYear(), FALSE, "");
				fileList.addTail(*key);
				entries++;
				}
			else if (allFiles && hasSubDirs && (fileName.right(5) != STRING("_.jpg") ) )
				{
				if (filex->getFileType() == GUIC_PictureFile)
					{
					STRING t = sWindow->getMessage();
					char st[64];
					sprintf(st, "Generating thumbnail for '%s'", filex->getFilePart() );
					sWindow->setMessage(st);
					makeThumbnail(*filex, width->get(), height->get() );
					sWindow->setMessage(t);
					}
				}
			}
		}
	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 (subdirList.length() ) // Generiere die Indexfiles für die Gallerien
		{
		if (subdirList.length()) createHTML (subdirList, pattern, date->get(), tableBorder->get(), baseName->get(), noFrames->get() );
		while (subdirList.length()) delete (GalleryEntryC *) subdirList.remove(1);
		}

	// Dem Benutzer melden, wie viele Bilder gesammelt worden sind
	char st[64];
	sprintf(st, "Scanning for picture files: %ld", entries);
	sWindow->setMessage ( st );
	
	return entries;
}
VOID		GalleryWindowC::generateGallery	(VOID)
{
	GalleryEntryC *entry = (GalleryEntryC*) fileList.objectAt(1);
	if (! entry->isDirectory) // dann wurde nur ein einzelnes Verzeichnis eingescannt
		{
		createGallery ( fileList, pattern->get(), lines->get(), columns->get(), click->get(), size->get(), date->get(), frame->get(), width->get(), height->get(), tableBorder->get(), baseName->get(), noFrames->get() );
		return;
		}
		
	while ( fileList.length() )
		{
		entry = (GalleryEntryC*) fileList.remove(1);
		if (entry->isDirectory)
			{
			GUIC_ListC list;
			for (LONG i=1; i<=entry->size; i++) list.addTail ( fileList.remove(1) );
			createGallery ( list, (STRPTR)entry->pattern, lines->get(), columns->get(), click->get(), size->get(), date->get(), frame->get(), width->get(), height->get(), tableBorder->get(), baseName->get(), noFrames->get() );
			}
		else throw GUIC_Exception ( "Error in method generateGallery():\nExpected a directory name, not a file '", entry->fileName, "'");
		}
}
STRING 	GalleryWindowC::makeThumbnail	(GUIC_FileExamineC &file, LONG thumbnailWidth, LONG thumbnailHeight)
{
	STRING fileName = file.getName();

	LONG 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;
*/

	char p[1024];
	sprintf ( p, program->get(), (char *)fileName, (char *)thumbName, thumbnailWidth, thumbnailHeight);
	BOOL result = GUIC_SystemC::runProgram(p, 100000);
	
	return thumbName;
}

/*********************************************************************************************************/

VOID		GalleryWindowC::cleanUp				(VOID)
{
	while ( fileList.length() ) delete (GalleryEntryC *)fileList.remove(1);

	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;
	delete createAllLabel;
	delete createAll;
	delete programLabel;
	delete program;
	delete baseNameLabel;
	delete baseName;
}

