/*
 *	Mac-Paint to TIFF Image File converter
 *
 *		1988/05/08 Waku Factory
 *		1991/01/25 
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define PIXWIDTH 576
#define PIXHEIGHT 720

/*
    TIFF format definition
*/

/* structure of IFD field */
typedef struct {
	short tag ;
	short type ;
	long  count ;
	long  value ;
} IFD_E ;


struct {
	long ver ;
	long ifdofs ;
	short ifds ;
	IFD_E tag[15] ;
	long ifde ;
	char dum[0x1f0-0xc2] ;
	long xa,xb,ya,yb ;
} head = { 0x2a4949, 8, 15,
	0xFE,  4, 1, 0,
	0x100, 3, 1, PIXWIDTH,
	0x101, 3, 1, PIXHEIGHT,
	0x102, 3, 1, 1,
	0x103, 3, 1, 1, 
	0x106, 3, 1, 0,
	0x10a, 3, 1, 1,
	0x111, 4, 1, 0x200,
	0x115, 3, 1, 1, 
	0x116, 4, 1, PIXWIDTH,
	0x117, 4, 1, PIXWIDTH/8*PIXHEIGHT,
	0x119, 2, 1, 1, 
	0x11a, 5, 1, 0x1f0,
	0x11b, 5, 1, 0x1f8,
	0x11c, 3, 1, 1,
	0 } ;

char lbuf[ PIXWIDTH / 8 ] ;
int headsize ;

main( ac,av )
int ac ;
char **av ;
{
	char name[256] ;
	FILE *sfp, *dfp ;
	int x,l,cnt,ch ;
	headsize = 512+128 ;
	cnt = 1 ;
	if( *av[1] == '-' && *(av[1]+1) == 'r' ) {
		headsize = 512 ;
		cnt = 2 ;
	}
	if( ac < cnt+1  ) usage() ;
	strcpy( name, av[cnt] ) ;
	strcat( name, ".MP" ) ;
	if( ( sfp = fopen( name, "rb" )) == NULL )
		error( "Source File Can't Open" ) ;
	printf( "Open source file : %s\n", name ) ;
	
	strcpy( name, av[cnt] ) ;
	strcat( name, ".TIF" ) ;
	if( ( dfp = fopen( name, "wb" )) == NULL )
		error( "Writ file Can't Open") ;
	printf( "Open  dest. file : %s\n", name ) ;

 	head.xa = head.ya = 75 ;
 	head.xb = head.yb = 1 ;

 	fwrite( &head, sizeof( head ) , 1, dfp ) ;
	fseek( sfp, headsize, SEEK_SET ) ;
	printf( "Converting...." ) ;
	
	for( l = 0 ; l < PIXHEIGHT ; l++ ) {
		x = cnt = 0 ;
		while( (ch = getc( sfp )) != EOF ) {
			ch &= 0xFF ;
			if( cnt-- == 0 )
				if( ch < 72 ) {
					cnt = ch + 1 ;
				}
				else {
					cnt = 257 - ch ;
					ch = getc( sfp ) ^ 0xFF ;
					while( cnt-- > 0 ) {
						lbuf[x++] = ch ^ 0xFF ;
						if( x == 72 ) goto exit ;
					}
					cnt = 0 ;
				}
			else {
				lbuf[x++] = ch  ;
				if( x == 72 ) goto exit ;
			}
		}
	exit:	fwrite( lbuf, sizeof(lbuf), 1, dfp ) ;
	}
	fclose( sfp ) ;
	fclose( dfp ) ;
	printf( "compreted!\n" ) ;
}

usage()
{
	printf( "MacPaint format to TIFF file converter\n" ) ;
	printf( "  USAGE : run386 mpcnv <filename>\n" ) ;
	printf( "          couvert <filename>.MP to <filename>.TIF\n" ) ;
	printf( "              Thus, <filename> must have no extension.\n" ) ;
	exit( 0 ) ;
}

error( mes )
char *mes ;
{
	printf( "******* %s Error\n", mes ) ;
	exit( 1 ) ;
}


