/* ======================================================
     read file
     input:  filename (you can omit extentions)
             pointer to timestamp variable
             supplement extentions(in/out)
     output: pointer to readed file
   ====================================================== */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "MThdINFO.h"
#include "etc.h"
#include "config.h"
UBYTE *readFile(FILEINFO *finfo,char *inext,char *outext);
UBYTE *readFile2(BYTE *filename);
#ifndef UNIXY_OS
int iskanji(int a);
int iskanji(int a)			/* only SJIS is supported. */
{
	return ((0x81 <= a && a <= 0x9F) || (0xE0 <= a && a <= 0xFC))? 1 : 0;
}
#endif
#ifndef UNIXY_OS					/* for setmode() */
	#include <fcntl.h>
	#include <io.h>
	#ifdef X68000
		#include <unistd.h>
	#endif
#endif
#ifndef	SEEK_SET
	#define	SEEK_SET	(0)
	#define	SEEK_CUR	(1)
	#define	SEEK_END	(2)
#endif
/* ====================================================
     read file
     input:  filename (you can omit extentions)
             pointer to timestamp variable
             supplement extentions(in/out)
     output: pointer to readed file
     effect: set source/destination files
   ==================================================== */
UBYTE *readFile(FILEINFO *finfo,char *inext,char *outext)
{
	UBYTE *zbuf;
	UBYTE *filename_ext;
	int i,flg = 1,len;
	len = (strlen(finfo->inpfile) > strlen(finfo->outfile))? strlen(finfo->inpfile) : strlen(finfo->outfile);
	filename_ext = (BYTE*)emalloc(sizeof(BYTE) * (len + 16), "filename_ext");
	strcpy(filename_ext,finfo->inpfile);			/* read source filename */
	if (finfo->inpfile[0] == '-' && finfo->outfile[0] != '-' && !(finfo->outfile[0])) {
		fatal(ILLEGALSWITCH,"Error: destination file is not specified.\n");
	}
	zbuf = readFile2(filename_ext);
	if (!zbuf) {
		strcat(filename_ext,inext);
		zbuf = readFile2(filename_ext);
		if (!zbuf) {
			fatal(FILENOTFOUND,"%s\tError: file not found.\n",finfo->inpfile);
			return (UBYTE*)NULL;
		}
	}
	/* setInFile(filename_ext); */
	strcpy(finfo->inpfile,filename_ext);
												/* set destination filename */
	if (finfo->outfile[0]) {
		strcpy(filename_ext,finfo->outfile);
	}
	for (i = strlen(filename_ext); i > 0; i--) {
		if (filename_ext[i] == '.') {
			flg = 0;
			break;
		}
	}
	if (flg) {
		i = strlen(filename_ext);
	}
	strcpy(&filename_ext[i],outext);
	if (!finfo->outfile[0]) {
#ifdef UNIXY_OS
		BYTE pathdelimita = '/';
#else
		BYTE pathdelimita = '\\';
#endif
		int i,p = -1;
		for (i = 0; i < (int)strlen(filename_ext);) {
			if (filename_ext[i] == pathdelimita) {
				p = i;
			}
#ifdef UNIXY_OS
			i++;
#else						/* when not UNIX, only SJIS is supported (in iskanji). */
			i += (iskanji(filename_ext[i]))? 2 : 1;
#endif
		}
		if (p >= 0) {							/* cut directory name */
			memmove(filename_ext, &filename_ext[p + 1], strlen(filename_ext) - p + 1);
		}
	}
	strcpy(finfo->outfile,filename_ext);
	efree(filename_ext, "filename_ext");
	return zbuf;
}
/* =======================
     read file (main)
   ======================= */
UBYTE *readFile2(BYTE *filename)
{
	FILE *fp;
	UBYTE *zbuf;
	DWORD fl = 0,fl2;
	if (!strcmp(filename,"-")) {				/* use standard input */
		int c;
		fl2 = 16 * 1024;
#ifndef UNIXY_OS
//	#if defined (X68000) || defined (BCB) ↓に修正 by Kobarin 		/* set stdin to binary mode (MS-DOS only) */
	#if defined (X68000) || defined (BCB) || defined(_MSC_VER)      /* set stdin to binary mode (MS-DOS only) */
		#ifndef XCLIB
			setmode(fileno(stdin),O_BINARY);	/* for Win32/16, DOS, OS/2, X680x0(libc) */
		#else
			fmode(stdin, _IOBINARY);
		#endif
	#endif
#endif	/* UNIXY_OS */
        {/*add by Kobarin(1バイトずつ読むよりこっちの方が速い?)
           VS2015 以外で動作するかどうかは不明*/
            fseek(stdin, 0, SEEK_END);
            fl2 = ftell(stdin);
            fseek(stdin, 0, SEEK_SET);
		    zbuf = (UBYTE*)emalloc(sizeof(UBYTE) * fl2, "zbuf");
            fl2 = fread(zbuf, 1, fl2, stdin);
            fl = fl2;
        }
        /*del by Kobarin
		zbuf = (UBYTE*)emalloc(sizeof(UBYTE) * fl2, "zbuf");// del by Kobarin
        while ((c = fgetc(stdin)) != EOF) {
			zbuf[fl++] = c;
			if (fl >= fl2) {
				fl2 *= 2;
				zbuf = (UBYTE*)erealloc(zbuf, sizeof(UBYTE) * fl2, "zbuf");
			}
		}
		fl--;*/	/* delete EOF */
		zbuf = (UBYTE*)erealloc(zbuf, sizeof(UBYTE) * (fl2 + 4), "zbuf");
	} else {
		fp = fopen(filename,"rb");
		if (fp==(FILE *)NULL) {
			return (UBYTE*)NULL;
		}
		/*fl = filelength(fileno(fp));*/
		fseek(fp,0,SEEK_END);
		fl = ftell(fp);
		rewind(fp);
		zbuf = (UBYTE*)emalloc(fl + 4, "zbuf");
		fl2 = fread(zbuf,sizeof(UBYTE),fl,fp);
		if (fl2 < fl) {
			fatal(READERR,"%s\tError: read error.\n",filename);
		}
		fclose(fp);
	}
	zbuf[fl] = zbuf[fl+1] = zbuf[fl + 2] = zbuf[fl + 3] = 0xFF;	/* gurdian */
	return zbuf;
}