#define NAME	 "FindFileType"
#define REVISION "1"

/* NOTE: This program depends on certain things, which may change. It is
only valid as long as the XpkMasterPrefs internal structures do not change.
It is only for tests and no standard use tool!!! Never distribute a binary
version of it or use it's routines in other programs! */

/* Programmheader

	Name:		FindFileType
	Author:		SDI
	Distribution:	PD
	Description:	shows filetype scanned with XpkMasterPrefs
	Compileropts:	-
	Linkeropts:	-l amiga

 1.0   05.04.97 : first Version
 1.1   18.06.97 : now passes file size
*/

#include <pragma/dos_lib.h>
#include <pragma/exec_lib.h>
#include <exec/memory.h>
#include <xpk/xpkprefs.h>
#include "SDI_defines.h"

struct XpkTypeNode {
  struct Node		xtn_Node;	/* standard node structure */
  ULONG			xtn_Size;	/* hold complete size to free */
  struct XpkTypePrefs	xtn_TypePrefs;  /* real data */
};

#define PARAM "FILE/M/A"

#ifdef __MAXON__
  #define __asm
#endif

typedef struct XpkTypeData * __asm (*RecogFunc) (register __a0 STRPTR,
  register __a1 STRPTR, register __a2 STRPTR, register __d0 ULONG,
  register __d1 ULONG);

void main()
{
  STRPTR *files;
  struct XpkPrefsSemaphore *semaphore;
  ULONG fh, bufsize;
  LONG size;
  STRPTR buf;
  struct XpkTypeData *td;

  struct RDArgs *rda;

  if((rda = ReadArgs(PARAM, (LONG *) &files, 0)))
  {
    Forbid();
    if((semaphore = (struct XpkPrefsSemaphore *) FindSemaphore(XPKPREFSSEMNAME)))
      ObtainSemaphoreShared((struct SignalSemaphore *) semaphore);
    Permit();
    if(semaphore)
    {
      if(semaphore->xps_PrefsType == XPREFSTYPE_STANDARD)
      {
	if((buf = (STRPTR) AllocMem((bufsize = semaphore->xps_RecogSize), MEMF_ANY)))
	{
          while(*files)
          {
	    if((fh = Open(*files, MODE_OLDFILE)))
	    {
	      size = Read(fh, buf, bufsize);
	      if(size != -1)
	      {
	      	Seek(fh, 0, OFFSET_END);
                td = ((RecogFunc)semaphore->xps_RecogFunc)
		(buf, *files, *files, size, Seek(fh, 0, OFFSET_END));
		if(semaphore->xps_PrefsData)
		{
		  struct Node *n;
		  for(n = ((struct List *)semaphore->xps_PrefsData)->lh_Head;
		  n->ln_Succ; n = n->ln_Succ)
		  {
		    if(((struct XpkTypeNode *) n)->xtn_TypePrefs.
		    xtp_PackerData == td)
		    {
		      Printf("%s is '%s'\n", *files, ((struct XpkTypeNode *)
		      n)->xtn_TypePrefs.xtp_TypeName);
		      break;
		    }
		  }
		  if(!n->ln_Succ)
		    Printf("%s is default type\n", *files);
		}
	      }
	      else
	        Printf("%s cannot be read\n", *files);
	      Close(fh);
	    }
	    else
	      Printf("%s does not exist\n", *files);
  	    ++files;
          }
	}
	FreeMem(buf, bufsize);
      }
      ReleaseSemaphore((struct SignalSemaphore *) semaphore);
    }
    FreeArgs(rda);
  }
}

