#include "/MPFiles.h"
#include <math.h>

/* Vars in ModePro.c */
extern struct MPSem   *MPSem;
extern UWORD   defaultpens[];
extern WORD    NumDriPens;
extern struct  FileRequester *FileReq;
extern struct  Window *Win;
extern UBYTE   filename[513];
extern struct  TextAttr *TAttr;

LONG WCB(LONG Error, struct IFFHandle *iff,APTR a,LONG l);
LONG WriteString(LONG Error, struct IFFHandle *IFF,STRPTR Str);

#define FLAG(x,y) (x?y:0)

BOOL SaveFile(struct List *List, UBYTE *fname)
{
  struct Promo pm;
  struct IFFHandle *iff;   
  ULONG len,l;
  LONG error;
  UWORD font;
  ULONG flags;
  struct DefaultNode *n;
//  APTR oldwin;
  
  SetIoErr(0);
  
  error=1;
  if(iff=AllocIFF())
  { 
    if(iff->iff_Stream = Open (fname,MODE_NEWFILE))
    {
      InitIFFasDOS(iff);
      if( !(error=OpenIFF(iff,IFFF_WRITE)) )
      {
        if(!(error=PushChunk(iff,ID_PREF,ID_FORM, IFFSIZE_UNKNOWN)))
        {
          for(l=0;l<NUM_LISTS && error==0 ;l++)
          {
            n=(struct DefaultNode *)List[l].lh_Head;
            while(n->Def_Node.ln_Succ && !error)
            {
              if(!(error=PushChunk(iff,ID_PREF,ID_PRMO, IFFSIZE_UNKNOWN)))
              {
                len=(strlen(n->Def_Node.ln_Name)+2)&0xfffffffe;
                pm.Version      =9;  //  <---- Muy importante
                pm.Type         =l;
                pm.ModeSelect   =n->ModeSelect;
                pm.ModeID       =n->ModeID;
                pm.Width        =n->Width;
                pm.Height       =n->Height;
                pm.OverscanType =n->OverscanType;
                pm.AutoScroll   =n->AutoScroll;
                pm.Look3D       =n->Look3D;
                pm.NameLen      =len;
                error=WCB(error,iff,&pm,sizeof(struct Promo));
                error=WriteString(error,iff,n->Def_Node.ln_Name);
                if(n->Look3D)
                {
                  len=DRIPENS;
                  error=WCB(error,iff,&len,4);
                  error=WCB(error,iff,n->Pens,len*sizeof(n->Pens[0]));
                }
                else
                {
                  len=0;
                  error=WCB(error,iff,&len,4);
                }
                
                /** Additions in Format 2 **/
                flags=n->Flags;
                error=WCB(error,iff,&flags,sizeof(flags));
 
                font=n->FontType;
                error=WCB(error,iff,&font,sizeof(font));
                if(n->FontType==SFONT_MP)
                {
                  error=WriteString(error,iff,n->Font.tta_Name);
                  error=WCB(error,iff,&n->Font.tta_YSize,4);
                }
                /*** Version 3 ***/
                error=WCB(error,iff,&n->PubOptions,4);
                error=WriteString(error,iff,FLAG(n->PubOptions,n->PubName));
                /*** Version 4 ***/  
                error=WCB(error,iff,(APTR)&n->Depth,2);
                error=WriteString(error,iff,FLAG(n->Flags & SHAREPENS,n->LockedPens));
                /*** Version 5 ***/
                error=WriteString(error,iff,FLAG(n->Flags & SCRHOTKEY,n->HotKey));  

                /*** Version 6 ***/
                error=WCB(error,iff,&n->OrigDisplayID,sizeof(ULONG));
                //printf("%8x\n",n->OrigDisplayID);
                /*** Version 7 ***/
                error=WCB(error,iff,&n->ODFlags,sizeof(UBYTE)*2);
                if((n->Flags & DNF_PALETTE) && n->Colors && n->Palette)
                {
                  error=WCB(error, iff,&n->Colors,sizeof(ULONG));
                  error=WCB(error, iff,n->Palette,sizeof(struct RGB)*n->Colors);
                }
                else
                {
                  ULONG colors=0;
                  
                  error=WCB(error, iff,&colors,sizeof(ULONG));
                }
                /*** Version 8 ***/
                {
                  error=WCB(error, iff, &n->BackdropType,sizeof(UWORD)); // also writes BackdropFlags
                  error=WriteString(error,iff,(n->BackdropFlags?n->BackdropFile:0));  
                }
                /*** Version 9 ***/
                {
                  LONG bdsize;
                  switch(n->BackdropType)
                  {
                    case 2:
                      bdsize=(sizeof(n->BackdropRGB));
                      error=WCB(error, iff, &bdsize, sizeof(bdsize)); 
                      error=WCB(error, iff, &n->BackdropRGB,sizeof(struct RGB)); // also writes BackdropFlags
                      break;
                    default:
                      bdsize=0;
                      error=WCB(error, iff, &bdsize, sizeof(bdsize)); 
                      break;
                  }
                }
                
                /**** End of Data ***/
                n=(struct DefaultNode *)(n->Def_Node.ln_Succ);
                error|=PopChunk(iff);
              }
            }/* wend */           
            
          }/* end l */
          if(!(error=PushChunk(iff,ID_PREF,ID_MPPR, IFFSIZE_UNKNOWN)))
          {
            struct MPPR_Chunk c;
              
            c.Version         =1;
            c.EnablePromotion =MPSem->Enabled;
            c.EnableNLM       =MPSem->EnabledNLM;
            c.AskUnknown      =MPSem->CatchScreens;
            c.AskUnknownPub   =MPSem->CatchPubScreens;
            c.CenterUnknown   =MPSem->CenterAll;

            error=WCB(error,iff,&c,sizeof(c));
            error|=PopChunk(iff);
          }
          error|=PopChunk(iff);
        }
        CloseIFF(iff);
      }
      Close(iff->iff_Stream);
    }
    FreeIFF(iff);
  }
  if(error<0)
    return(FALSE);
  else
    return(TRUE);
}


LONG WCB(LONG Error, struct IFFHandle *iff,APTR a,LONG l)
{
  LONG error=0;
  
  if(Error>=0)
  {
    error=WriteChunkBytes(iff,a,l);
    if(error==l) error=0;
  }
  return(error);
}

LONG WriteString(LONG Error, struct IFFHandle *IFF,STRPTR Str)
{
  LONG error=0,len;
  WORD Null=0;

  if(Error>=0)
  {
    if(Str)
    {
      len=strlen(Str)+1;
      error=WCB(error,IFF,Str,len);
      if(!error && (len & 1))
      {
        error=WCB(error,IFF,&Null,1); /* WORD align */
      } 
    }
    else
      error=WCB(error,IFF,&Null,2);
  }
   
  return(error);
}



BOOL SelectFile(UBYTE *title,UBYTE save)
{ 
  WORD width;
  
  if(!FileReq)
  {
    width=Win->Width/2;
    FileReq=(struct FileRequester *)AllocAslRequestTags(ASL_FileRequest, 
                    ASLFR_TextAttr,        TAttr,
                    ASLFR_InitialTopEdge,  Win->TopEdge+8,
                    ASLFR_InitialLeftEdge, Win->LeftEdge+width/2,
                    ASLFR_InitialWidth,    width,
                    ASLFR_InitialHeight,   Win->Height-16,
                    ASLFR_DoPatterns  ,    TRUE,
                    ASLFR_InitialPattern,  "#?",
                    ASLFR_RejectIcons,     TRUE,
                    TAG_DONE); 
  }
  if(FileReq)
  {
    if(AslRequestTags(FileReq, 
                  ASLFR_Window   ,       Win,
                  ASLFR_SleepWindow ,    TRUE,
                  ASLFR_TitleText,       title,
                  ASLFR_DoSaveMode,      save,
                  TAG_DONE))
    {
      strncpy(filename,FileReq->fr_Drawer,512);
      if(AddPart(filename,FileReq->fr_File,512))
        return(TRUE);
    }   
  }
  return(FALSE);
}

