/*  :ts=8 bk=0
 *
 * main.c:	Driver for the cheesy IFF ILBM reader.
 *
 * Leo L. Schwab			8705.11
 */

#include <exec/types.h>
#include <graphics/gfxbase.h>
#include <graphics/view.h>
#include <stdio.h>
#include <fcntl.h>
#include "myiff.h"


extern FILE	*fopen();


struct ViewPort		*vp;
struct View		v, *oldview;
struct GfxBase		*GfxBase;
FILE			*fd;

main (ac, av)
char **av;
{
	struct ChunkHeader ch;

	openstuff ();		/*  It helps to plug it in...  */

	/*
	 * Scan all arguments and treat them as files.
	 */
	while (++av, --ac) {
		puts (*av);
		if (!(fd = fopen (*av, "r"))) {
			fail ("File open failed.");
			continue;
		}

		if (!getchunkheader (fd, &ch)) {
			fail ("Can't discover file type.");
			continue;
		}
		if (ch.TYPE != FORM) {
			fail ("Not an IFF file.");
			continue;
		}

		if (!(vp = readform (fd, ch.chunksize))) {
			fail ("readform() failed.");
			continue;
		}
		fclose (fd);  fd = NULL;

		puts ("Waiting for you to press RETURN...");
		getchar ();

		/*
		 * And now we make the views.
		 */
		oldview = GfxBase -> ActiView;

		InitView (&v);
		v.DxOffset = oldview -> DxOffset;  /* Track	 */
		v.DyOffset = oldview -> DyOffset;  /* Preferences */

		v.ViewPort = vp;

		if (vp -> Modes & LACE)
			v.Modes |= LACE;

		centerpict (vp);

		MakeVPort (&v, vp);
		MrgCop (&v);
		LoadView (&v);

		getchar ();	/*  Wait for next press of RETURN  */
		cleanup ();
	}

	closestuff ();
}

/*
 * A sleazy hack for overscan images.  If the guy is using 'morerows',
 * then this doesn't quite work.
 */
centerpict (vp)
register struct ViewPort *vp;
{
	if (vp -> Modes & HIRES)
		vp -> DxOffset += (640 - vp->DWidth) / 2;
	else
		vp -> DxOffset += (320 - vp->DWidth) / 2;

	if (vp -> Modes & LACE)
		vp -> DyOffset += (400 - vp->DHeight) / 2;
	else
		vp -> DyOffset += (200 - vp->DHeight) / 2;
}

openstuff ()
{
	if (!(GfxBase = OpenLibrary ("graphics.library", 0L)))
		die ("Dale is out for the moment.");
}

cleanup ()
{
	if (oldview) {
		LoadView (oldview);
		WaitTOF ();
		if (v.LOFCprList) {
			FreeCprList (v.LOFCprList);
			v.LOFCprList = NULL;
		}
		if (v.SHFCprList) {
			FreeCprList (v.SHFCprList);
			v.SHFCprList = NULL;
		}
		oldview = NULL;
	}

	if (vp) {
		closeviewport (vp);
		vp = NULL;
	}
	if (fd) {
		fclose (fd);
		fd = NULL;
	}
}

closestuff ()
{
	cleanup ();

	if (GfxBase)	CloseLibrary (GfxBase);
}

fail (str)
char *str;
{
	puts (str);
	cleanup ();
}

die (str)
char *str;
{
	puts (str);
	closestuff ();
	exit (20);
}
