/*
	Xmillennium T_TUNE
	旧式テープファイルへのコンバート
*/
#include <stdio.h>
#include <string.h>
#include "new_tap.h"

void main(int argc,unsigned char **argv)
{
	FILE *fp;
	int ret;
	unsigned long freq;
	X1TAPE_HEADER header;
	char *fname;

	if( argc < 2)
	{
		printf("new TAP file to old TAP file converter\n\n");
		printf("use : old_tap filename.tap\n");
		return;
	}
	/* get filename from parameter */
	fname = argv[1];

	/* open file */
	if( (fp = fopen(fname,"rb")) == NULL)
	{
		printf("'%s' can't open\n",fname);
		return;
	}

	/* read header */
	ret = fread(&header,1,sizeof(header),fp);
	fclose(fp);
	if( ret != sizeof(header) )
	{
		printf("file can't read\n",fname);
		return;
	}

	/* check header INDEX */
	if(header.index != TAPE_INDEX)
	{
		printf("'%s' is not new TAP file\n",fname);
		return;
	}

	/* show header info */
	printf("filename :%s\n\n",fname);
	printf("name     :%s\n",header.name);
	printf("protect  :%s\n",header.protect ? "on" : "off");
	printf("format   :%02x\n",header.format);
	printf("frequency:%ld Hz\n",(long)header.frequency);
	printf("data size:%08lx bits\n",(long)header.datasize);
	printf("position :%ld bits\n",(long)header.position);

	/* convert to old header */
	freq = header.frequency;
	memset(&header,0,sizeof(header));
	header.index = freq;

	/* reopen */
	if( (fp = fopen(fname,"r+b")) == NULL)
	{
		printf("file can't write\n");
		return;
	}

	/* write */
	ret = fwrite(&header,1,sizeof(header),fp);
	fclose(fp);
	if( ret != sizeof(header) )
	{
		printf("write error\n");
		return;
	}
	printf("done !");
}
