/* Stuff for the filerequester of reqtools.library */

#include <libraries/reqtools.h>
#include <intuition/intuition.h>
#include <functions.h>

struct ReqToolsBase *ReqToolsBase;

void * rtAllocRequestA();

static struct rtFileRequester *filereq=NULL;
static char *returnstring=NULL;
static char filename[128]="";

static char *modestr[]={"Load picture","Save picture","Delete file"};
static char *gadtxt[]={"Load","Save","Delete"};

#define RED(s) ((s)>>8)
#define GREEN(s) (((s)>>4)&0xf)
#define BLUE(s) ((s)&0xf)

InitRequest()
{
   if (filereq = rtAllocRequestA ((ULONG)RT_FILEREQ, NULL))
      return(0); /* all OK */
   else return(1); /* No Memory */
}

FreeRequest()
{
   if(filereq) rtFreeRequest(filereq);
   filereq=NULL;
   if(returnstring) free(returnstring);
   returnstring=NULL;
}

static char *catstring(s1,s2)
char *s1,*s2;
{
   char *calloc();
   int len1,len2;
   len1=strlen(s1);
   len2=strlen(s2);
   if(returnstring) free(returnstring);
   returnstring=NULL;
   if(s1[len1-1]==':') {
      returnstring=calloc(len1+len2+1);
      if(!returnstring) return(0L);
      strcpy(returnstring,s1);
      strcat(returnstring,s2);
      return(returnstring);
   } else {
      returnstring=calloc(len1+len2+2);
      if(!returnstring) return(0L);
      strcpy(returnstring,s1);
      strcat(returnstring,"/");
      strcat(returnstring,s2);
      return(returnstring);
   }
}

char *FileRequest(win,mode)
struct Window *win;
short mode;
{
   long col0,col1;
   char *ret;

   col0=GetRGB4(win->WScreen->ViewPort.ColorMap,0L);
   col1=GetRGB4(win->WScreen->ViewPort.ColorMap,1L);

   SetRGB4(&win->WScreen->ViewPort,0L,0L,0L,0L);
   SetRGB4(&win->WScreen->ViewPort,1L,15L,15L,15L);

   if(mode) {
      if(rtFileRequest(filereq,filename,modestr[mode],
         (ULONG)RT_Window,win,
         (ULONG)RTFI_OkText,gadtxt[mode],
         (ULONG)RTFI_Flags,(ULONG)FREQF_SAVE,(ULONG)TAG_END)) {
         ret=catstring(filereq->Dir,filename);
         rtFreeReqBuffer(filereq);
         SetRGB4(&win->WScreen->ViewPort,0L,RED(col0),GREEN(col0),BLUE(col0));
         SetRGB4(&win->WScreen->ViewPort,1L,RED(col1),GREEN(col1),BLUE(col1));
         return(ret);
      } else {
         SetRGB4(&win->WScreen->ViewPort,0L,RED(col0),GREEN(col0),BLUE(col0));
         SetRGB4(&win->WScreen->ViewPort,1L,RED(col1),GREEN(col1),BLUE(col1));
         return(NULL);
      }
   } else {
      if(rtFileRequest(filereq,filename,modestr[mode],
         (ULONG)RTFI_OkText,gadtxt[mode],
         (ULONG)RT_Window,win,(ULONG)TAG_END)) {
         SetRGB4(&win->WScreen->ViewPort,0L,RED(col0),GREEN(col0),BLUE(col0));
         SetRGB4(&win->WScreen->ViewPort,1L,RED(col1),GREEN(col1),BLUE(col1));
         return(catstring(filereq->Dir,filename));
      } else {
         SetRGB4(&win->WScreen->ViewPort,0L,RED(col0),GREEN(col0),BLUE(col0));
         SetRGB4(&win->WScreen->ViewPort,1L,RED(col1),GREEN(col1),BLUE(col1));
         return(NULL);
      }
   }
}

