/*

  Example how to use FDI2RAW.C. This creates extended ADFs from FDI images.
  Copyright (c) 2001 by Toni Wilen <twilen@arabuusimiehet.com>

  FDI format created by Vincent "ApH" Joguin


  This program is free software; you can redistribute it and/or modify it
  under the terms of the GNU General Public License as published by the Free
  Software Foundation; either version 2 of the License, or (at your option)
  any later version.

  This program is distributed in the hope that it will be useful, but WITHOUT
  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
  more details.

  You should have received a copy of the GNU General Public License along
  with this program; if not, write to the Free Software Foundation, Inc.,
  59 Temple Place - Suite 330, Boston, MA  02111-1307, USA

*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "types.h"
#include "fdi2raw.h"

static char adf2extid[]={"UAE-1ADF\0\0"};

int main(int argc,char *argv[])
{
	FILE *f, *df;
	uae_u8 *dst;
	int len, i, last_track;
	uae_u8 tmp[12];
	int track_lengths[200];
	FDI *fd;

	if (argc < 2) return 0;

	f = fopen(argv[1],"rb");
	if (!f) return 0;

	if(!(fd = fdi2raw_header(f))) return 0;
	last_track = fdi2raw_get_last_track(fd);

	df = fopen("out.adf","wb");
	if (!df) return 0;
	fwrite (adf2extid, 10, 1, df);
	tmp[0] = 0;
	tmp[1] = last_track;
	fwrite (tmp, 2, 1, df);
	memset (tmp, 0, 12);
	for (i = 0; i < last_track; i++) {
		fwrite (tmp, 12, 1, df);
		track_lengths[i] = 0;
	}

	for (i = 0; i < last_track; i++) {
		dst = fdi2raw_read_track (fd, i, &len);
		if (len < 0) break;
		track_lengths[i] = len;
		len += 16;
		len &= ~15;
		len >>= 3;
		fwrite (dst, len, 1, df);
	}

	fseek (df, 12, SEEK_SET);
	for (i = 0; i < last_track; i++) {
		len = track_lengths[i];
		tmp[8] = (uae_u8) (len >> 24);
		tmp[9] = (uae_u8) (len >> 16);
		tmp[10] = (uae_u8) (len >> 8);
		tmp[11] = (uae_u8) (len >> 0);
		len += 16;
		len &= ~15;
		len >>= 3;
		tmp[0] = 0;
		tmp[1] = 0;
		tmp[2] = 0;
		tmp[3] = 1;
		tmp[4] = (uae_u8) (len >> 24);
		tmp[5] = (uae_u8) (len >> 16);
		tmp[6] = (uae_u8) (len >> 8);
		tmp[7] = (uae_u8) (len >> 0);
		fwrite (tmp, 12, 1, df);
	}

	fdi2raw_header_free(fd);
	fclose(df);
	fclose(f);
	return 0;
}