#include<stdio.h>
#include<unistd.h>
#include<sys/param.h>


#define word(p)	((unsigned)(p)[0] | (unsigned)(p)[1] << 8 | \
			(unsigned)(p)[2] << 16 | (unsigned)(p)[3] << 24)


int main( int argc, char **argv )
{
	FILE *fp;
	FILE *out;
	int i,num_entry;
	int offset,len;
	unsigned char buf[16];
	unsigned char path[MAXPATHLEN];
	unsigned char *fmt;

	if( argc < 2 || argc > 3 ){
		fprintf(stderr,"usage: %s DAT_file [filename_format]\n",argv[0]);
		return 1;
	}

	fp = fopen(argv[1],"r");
	if( fp == NULL ){
		perror("fopen");
		return 1;
	}

	if( fread(buf,14,1,fp) < 1 ){
		perror("fread");
		return 1;
	}
	num_entry = word(buf+10);

	if( argv[1][0] != '/' ){
		getcwd(path,MAXPATHLEN);
		strncat(path,"/",MAXPATHLEN);
		strncat(path,argv[1],MAXPATHLEN);
	}else{
		strncpy(path,argv[1],MAXPATHLEN);
	}

	if( argc == 2 )
		fmt = "ys%04d.ys";
	else
		fmt = argv[2];

	for( i = 0 ; i < num_entry ; i++ ){
		fprintf(stderr,"%04d/%04d\10\10\10\10\10\10\10\10\10",i+1,num_entry);
		fflush(stderr);
		if( fread(buf,8,1,fp) < 1 ){
			perror("fread");
			return 1;
		}
		offset = word(buf);
		len = word(buf+4);
		sprintf(buf,fmt,i);
		out = fopen(buf,"w");
		if( out == NULL ){
			perror("fopen");
			return 1;
		}
		fprintf(out,"YS_DATA %s %d\n",path,i);
		if( fclose(out) < 0 ){
			perror("fclose");
			return 1;
		}
	}
	fprintf(stderr,"\n");
	return 0;
}
