/**************************************************************************

			 Open, close & test files

       Copyright (C) 1994 by Alexandros Loghis,  All Rights Reserved

**************************************************************************/

#include <stdio.h>	/* gets, fopen, fclose */
#include <stdlib.h>	/* exit */
#include <ctype.h>	/* toupper */
#include <string.h>	/* strcpy, strcat, strrchr, strcmp */

#include "gfx2grob.h"
#include "PrintMsg.h"
#include "FileStuf.h"
#ifdef AMIGA
#include "IffStuff.h"
#endif


static void MakeOutputFileName(OptionsType *Options);
static void TestFileExists(char *FName);
static void CloseFile(FILE **File, char **FName);

/*************************************************************************/

static void MakeOutputFileName(OptionsType *Options)
{
  char	*pChar;


  strcpy(Options->NewOutputfileName, Options->InputfileName);
  if (pChar = strrchr(Options->NewOutputfileName, '.')) *pChar = '\0';
  switch (Options->Option) {

    case OT_TOASCII :
      pChar = ".src";
    break;

    case OT_TOBIN :
      pChar = ".raw";
    break;

#ifdef AMIGA
    case OT_TOIFF :
      pChar = ".pic";
    break;
#endif
  }
  strcat(Options->NewOutputfileName, pChar);
  Options->OutputfileName = Options->NewOutputfileName;
  PrintMsg(MSG_OUTFNAM_S, Options->NewOutputfileName);
}

/*************************************************************************/

extern void OpenFiles(gvType *gv, char *OpenMode, char *WriteMode)
{
  if (!(gv->Inputfile = fopen(gv->Options.InputfileName, OpenMode)))
    PrintMsg(ERR_OPEN_S, gv->Options.InputfileName);
  if (!*gv->Options.OutputfileName)
    MakeOutputFileName(&gv->Options);
  TestFileExists(gv->Options.OutputfileName);
  if (!(gv->Outputfile = fopen(gv->Options.OutputfileName, WriteMode)))
    PrintMsg(ERR_OPEN_S, gv->Options.OutputfileName);
}

/*************************************************************************/

static void TestFileExists(char *FName)
{
  FILE *FilePtr;

  char Answer[4];


  if (FilePtr = fopen(FName, "rb")) {
    fclose(FilePtr);
    PrintMsg(MSG_OUTFEX_S, FName);
    gets(Answer);
    if (toupper(Answer[0]) != 'Y') exit(0);
  }
}

/*************************************************************************/

static void CloseFile(FILE **File, char **FName)
{
  if (*File) {
    if (EOF == fclose(*File)) {
      PrintMsg(ERR_CLOSE_S, *FName);
    }
    *File = NULL;
#ifdef AMIGA
    if (!strcmp(*FName, TEMPFILENAME))
      if (remove(*FName)) PrintMsg(ERR_IFFREM_S, *FName);
#endif
    *FName = NULLSTR;
  }
}

/*************************************************************************/

extern void CloseFiles(gvType *gv)
{
  CloseFile(&gv->Inputfile, &gv->Options.InputfileName);
  CloseFile(&gv->Outputfile, &gv->Options.OutputfileName);
}
