/**
 **
 **  Ultima 4 Tools by Otmar Lendl (lendl@cosy.sbg.ac.at)
 **
 **	Use and redistribution of this program is free.
 **	Please send any modifications to me.
 **
 **		Share and Enjoy !
 **
 **/

#include <dos.h>
#include <math.h>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>

#include <graphics.h>


#define ESC	0x1b			/* Define the escape key	*/
#define TRUE	1			/* Define some handy constants	*/
#define FALSE	0			/* Define some handy constants	*/
#define PI	3.14159 		/* Define a value for PI	*/
#define ON	1			/* Define some handy constants	*/
#define OFF	0			/* Define some handy constants	*/

int    GraphDriver;		/* The Graphics device driver		*/
int    GraphMode;		/* The Graphics mode value		*/
double AspectRatio;		/* Aspect ratio of a pixel on the screen*/
int    MaxX, MaxY;		/* The maximum resolution of the screen */
int    MaxColors;		/* The maximum # of colors available	*/
int    ErrorCode;		/* Reports any graphics errors		*/
struct palettetype palette;		/* Used to read palette info	*/


void Initialize(void)
{
  int xasp, yasp;			/* Used to read the aspect ratio*/

  GraphDriver = DETECT; 		/* Request auto-detection	*/
  initgraph( &GraphDriver, &GraphMode, "" );
  ErrorCode = graphresult();		/* Read result of initialization*/
  if( ErrorCode != grOk ){		/* Error occured during init	*/
    printf(" Graphics System Error: %s\n", grapherrormsg( ErrorCode ) );
    exit( 1 );
  }

  getpalette( &palette );		/* Read the palette from board	*/
  MaxColors = getmaxcolor() + 1;	/* Read maximum number of colors*/

  MaxX = getmaxx();
  MaxY = getmaxy();			/* Read size of screen		*/

  getaspectratio( &xasp, &yasp );	/* read the hardware aspect	*/
  AspectRatio = (double)xasp / (double)yasp; /* Get correction factor	*/

}

#define BPROW  (256*16)    /* Bytes pro 16 Linien */


main()
{
 char filen[50]="world.map";
 int sy,x,y,i,j,blockid,xpos, ypos;
 long foffset;
 unsigned char n1,n2;
 unsigned char block[32][32];
 #define BLKSIZE (32*32)
 FILE *fh;

 fh = fopen(filen,"rb");
 if ( fh==NULL) exit(10);

 puts("\n Ultima IV Landscape-viewer (c) Otmar Lendl 1993 !\n");
 Initialize();
 for(blockid=0;blockid<64;blockid++)
	{
	if (fread(block,1,BLKSIZE,fh) != BLKSIZE )
		{
		getch();
		puts("\nFile error !!!! \n");
		exit(20);
		}
/*	xpos = (blockid / 4) % 16;
	ypos = (blockid % 4) + (blockid / 64) * 4;  */
	xpos = blockid % 8;
	ypos = blockid / 8;
		for(j=0;j<BLKSIZE;j++)
			{
			x = j % 32;
			y = j / 32;
			i = block[y][x];
			putpixel(2*(xpos*32+x)+0,2*(ypos*32+y)+0,i&15);
			putpixel(2*(xpos*32+x)+1,2*(ypos*32+y)+0,i&15);
			putpixel(2*(xpos*32+x)+0,2*(ypos*32+y)+1,i&15);
			putpixel(2*(xpos*32+x)+1,2*(ypos*32+y)+1,i&15);
			}
	}
 fclose(fh);
getch();
closegraph();
}


