/*
    This file is part of TIFFlib Format, a File Format plugin for Adobe Photoshop
    Copyright (C) 2005-7 Toby Thain, toby@telegraphics.com.au

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by  
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License  
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

#include "tifflibplugin.h"

FormatRecordPtr gpb;

MACPASCAL void PluginMain(short selector,FormatRecordPtr pb,long *data,short *result);

DLLEXPORT 
MACPASCAL void PluginMain(short selector,FormatRecordPtr pb,long *data,short *result){
	OSErr e = noErr;
	TIFF *tif;
	enum{ MAX_MEM = 1L<<20 }; // don't ask Photoshop for more than 1MB
	
	EnterCodeResource();
	
	gpb = pb;

	switch (selector){
	case formatSelectorAbout: DoAbout((AboutRecordPtr)pb); break;

	case formatSelectorReadPrepare:
	case formatSelectorWritePrepare: 
		pb->maxData /= 2;
		if(pb->maxData > MAX_MEM) pb->maxData = MAX_MEM;
		break;
	case formatSelectorReadStart:    e = read_start(pb);    break;
	case formatSelectorReadContinue: e = read_continue(pb); break;
	case formatSelectorReadFinish:   e = read_finish(pb);   break;

	/* write sequence: options, estimate, write */

	case formatSelectorOptionsPrepare:
	case formatSelectorEstimatePrepare:
		pb->maxData = 0; // nothing allocated in options or estimate phases
		break;

	case formatSelectorEstimateStart:
		// wild guess for now
		pb->minDataBytes = pb->maxDataBytes = 
			2048 + (long)pb->imageSize.v*((long)pb->imageSize.h*pb->planes*pb->depth+7)/8;
		break;

	case formatSelectorOptionsStart: 
		e = options_start(pb,data); 
		break;
	case formatSelectorOptionsContinue:
	case formatSelectorEstimateContinue:
		pb->data = NULL;
	case formatSelectorOptionsFinish:
	case formatSelectorEstimateFinish:
		break;

	case formatSelectorWriteStart:    e = write_start(pb, data);    break;
	case formatSelectorWriteContinue: e = write_continue(pb); break;
	case formatSelectorWriteFinish:   e = write_finish(pb);   break;

	case formatSelectorFilterFile:
		// is it a real TIFF? try to open the file with libtiff
		if( (tif = TIFFFdOpen(pb->dataFork, "", "r")) ){
			TIFFClose(tif); // free resources (does not close the file handle)
			e = noErr;
		}else
			e = formatCannotRead;
		break;

	default: 
		e = formatBadParameters;
	}

	*result = e;
	
	ExitCodeResource();
}
