#include <stdio.h>
#include <fcntl.h>
#include <exec/memory.h>
#include <graphics/gfxbase.h>
#include <graphics/gfxmacros.h>
#include <intuition/intuition.h>
#include <intuition/screens.h>

#include "cdsconst.h"
#include "cdsprefs.h"

#define LOCAL_SIZE	PATHLEN + 1

static char   ext[LOCAL_SIZE] = "--";
static char   dir[LOCAL_SIZE] = "--";
static char   file[LOCAL_SIZE] = "--";

extern BOOL FileRequest();
 		
/* -------------------------------------------------------------- */

void SaveFile(S,P,Bild,Lv,time,sec,x,y)

struct Screen   *S;
struct CDSPrefs	*P;
UBYTE Bild[BildBreite][BildHoehe];
int   *Lv;
int   *time;
int   *sec;
int   *x;
int   *y;

{ 
  char	 buf[200];
  char	 nam[200];
  BOOL   Result;
  FILE   *f;
  int    i,j;
  
  if (strcmp((char*)dir,"--") == 0)
     sprintf(dir,"%s",P->game);
  if (strcmp((char*)file,"--") == 0)
     sprintf(file,"savedgame");
  if (strcmp((char*)ext,"--") == 0)
     sprintf(ext,"cds");

  Result = FileRequest(S,dir,file,ext);

  if (Result)
   {
    if (dir[strlen(dir)-1] == ':')
       sprintf(buf,"%s%s",dir,file);
    else
       sprintf(buf,"%s/%s",dir,file);
       
    if (strlen(buf) < strlen(ext))
       sprintf(nam,"%s.%s",buf,ext);
    else
      if (strcmp(&buf[strlen(buf)-strlen(ext)],ext) != 0)
         sprintf(nam,"%s.%s",buf,ext);
      else
         sprintf(nam,"%s",buf);
        
    if (!(f = fopen(nam,"w")))
       return();
    putw(MAGIC_WORD,f);
    putw(*Lv,f);
    putw(*time,f);
    putw(*sec,f);
    putw(*x,f);
    putw(*y,f);
    
    for (i = 0; i < BildBreite; i++)
        for (j = 0; j < BildHoehe; j++)
            putc(Bild[i][j],f);
    fclose(f);
   }
}

