#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include <dlg/resman.h>
#include <dlg/file.h>
#include <dlg/log.h>
#include <dlg/msg.h>

#include <Link/File.h>
#include <Link/io.h>

#include <proto/dos.h>
#include <proto/dlg.h>

#include <pragmas/dlg.h>

extern struct Library *DLGBase;

BOOL KillFile(long area,char *name,long number,char *psswd,char rcredit,struct Msg_Area *msgarea,char realdelete,struct USER_DATA *user,char *ext)
{char   descpath [64];
 char   altpath  [64];
 char   filename [256];
 char   dest     [256];
 char   desc     [128];
 char   qfilename[64];
 char   valname  [64];

 struct File_Header Header;
 struct QuickFile   QF;


 /* Get path of directory with the .fd file */
 if (area!=PVTAREA)
    {ASPrintf(NULL, descpath,  "FILE:%ld/",area);
     ASPrintf(NULL, qfilename, "FILE:%ld/File.dat",area);
     ASPrintf(NULL, valname,   "FILE:%ld/%ld.val",area,number);
     BorrowArea(area,psswd,"",64,FILELOCK|WRITELOCK);
    }
  else
    {ASPrintf(NULL, descpath,  "USER:%s/",name);
     UnderScore(descpath);
    }

 ASPrintf(NULL, desc, "%s%ld.fd", descpath,number);

 /* Read the .fd file */
 if (GetFirstStruct(desc,(char *)&Header,sizeof(Header))==-1)
    {FreeArea(area,psswd,FILELOCK|WRITELOCK);
     return(FALSE);
    }

 FreeArea(area,psswd,FILELOCK|WRITELOCK);

 /* Get the alternate path for the actual file */
 if (area!=PVTAREA && msgarea && realdelete!=2)
     GetPath(altpath,area,msgarea,Header.Filename);

 /* Calculate the name of the file to delete */
 if (realdelete!=2)
    {if (area!=PVTAREA)
         ASPrintf(NULL, filename,"%s%s",altpath,Header.Filename);
       else
         ASPrintf(NULL, filename,"%s%s",descpath,Header.Filename);
    }

 /* Delete or move the actual file */
 if (realdelete!=2 && Exists(filename))
    {if (realdelete)
         DeleteFile(filename);
       else
        {if (!Exists("File:KilledFiles"))  return(FALSE);
         ASPrintf(NULL, dest,"FILE:KilledFiles/%s",Header.Filename);
         while(SmartRename(filename,dest)==-1)
               DeleteFile(dest);
        }
    }

 /* Delete entry from quick list */
 if (area!=PVTAREA)
    {strcpy(QF.filename,Header.Filename);
     DeleteStruct(qfilename,(char *)&QF,sizeof(QF),36);
    }  

 DeleteFile(desc);
 if (area!=PVTAREA)  DeleteFile(valname);

 WriteLog(KILLED_FILE,name,ext,Header.Filename);

 if (rcredit)
     RemoveCredit(Header.From,Header.Size,user,name);

 return(TRUE);
}
