#include <stdio.h>
#include <proto/datatypes.h>
#include <proto/exec.h>
#include <proto/dos.h>

char *id(char *buf,char *fname);
char *id2(char *buf, char *fname);
char *strippath(char *name);

char *id(char *buf,char *fname) {
	struct DataType *dtn;
	struct DataTypeHeader *dth;
	BPTR lock;
	
	strcpy(buf,"");
	
	if(lock=Lock(fname,ACCESS_READ)) {	
		if(dtn=ObtainDataTypeA(DTST_FILE,(APTR)lock,0)) {
			dth=dtn->dtn_Header;
			
			sprintf(buf,"%s ",dth->dth_Name);
			
			switch(dth->dth_GroupID) {
				char b2[1000];
				
				case GID_SYSTEM:
					/* This is a bit of a catch all so lets see if
					   we can id it other ways */
					   
					if(strcmp(id2(b2,fname),""))
						strcpy(buf,b2);
					else
						strcat(buf,"system file");	
				break;
				case GID_TEXT:
					strcat(buf,"text file");	
				break;
				case GID_DOCUMENT:
					strcat(buf,"document");	
				break;
				case GID_SOUND:
					strcat(buf,"Sound Sample");	
				break;
				case GID_INSTRUMENT:
					strcat(buf,"instrument");	
				break;
				case GID_MUSIC:
					strcat(buf,"music score");	
				break;
				case GID_PICTURE:
					strcat(buf,"Picture");	
				break;
				case GID_ANIMATION:
					strcat(buf,"Animation");	
				break;
				case GID_MOVIE:
					strcat(buf,"Movie");	
				break;
			}
			
			ReleaseDataType(dtn);
		} else
			buf=0;
		UnLock(lock);
	} else 
		buf=0;	
	
	return(buf);
}


char *id2(char *buf, char *fname) {
	FILE *fp=0;
	char tmp[100];
	char byte;
	char mem[1000];
	
	strcpy(mem,fname);
	
	strcpy(buf,"");
	
	if(fp=fopen(fname,"r")) {
		/* Read header */
		
		fread(tmp,99,1,fp);
		
		byte=tmp[4];
		tmp[4]=0;
		if(!(strcmp(tmp,"MMD0"))) {
			strcpy(buf,"MED Music Module");
			goto end;
		}
		if(!(strcmp(tmp,"MMD1"))) {
			strcpy(buf,"MED Music Module");
			goto end;
		}
		if(!(strcmp(tmp,"MMD2"))) {
			strcpy(buf,"OctaMED Music Module");
			goto end;
		}
		if(!(strcmp(tmp,"MThd"))) {
			strcpy(buf,"MIDI Music File");
			goto end;
		}
		tmp[4]=byte;

		strippath(fname);

		byte=fname[4];
		fname[4]=0;
		strlwr(fname);
		if(!(strcmp(fname,"mod."))) {
			strcpy(buf,"Tracker Music Module");
			goto end;
		}
		fname[4]=byte;
		
		
	}

	end:
	if(fp) fclose(fp);
	strcpy(fname,mem);
	return(buf);
}

char *strippath(char *name) {
	
	long count,i;
	char tmp[1000];
	
	count=strlen(name);

	for(i=count; i>=0; i--) {
		if(name[i]=='/' || name[i]==':') {
			strcpy(tmp,&name[i+1]);
			strcpy(name,tmp);
			return(name);
		}
		
	}
	
	printf("strip = %s\n",name);
	return(name);
}