#include <stdio.h>
#include <stdlib.h>
#include <string.h>

FILE *fi;
unsigned char *m,*n,*o;
int i,j,k,l,ntrk,ltrk[1<<8],ptrk[1<<8];

int main(int argc,char *argv[])
{
	if (argc<2)
	{
		puts("Usage: DSK2MINI disc_file");
		return 1;
	}
	for (int z=1;z<argc;++z)
	if (fi=fopen(argv[z],"rb"))
	{
		fseek(fi,0L,SEEK_END);
		l=ftell(fi);
		fseek(fi,0L,SEEK_SET);
		m=malloc(l);
		if (m)
		{
			fread(m,1,l,fi);
			ntrk=m[0x30];
			if (!(m[0x31]&1))
				ntrk*=2;
			j=(m[0x33]<<8)+m[0x32];
			k=1<<8;
			if (!memcmp(m,"EXTENDED",8))
			{
				for (i=0;i<ntrk;i++)
				{
					ptrk[i]=k;
					k+=(ltrk[i]=m[0x34+i]<<8);
				}
			}
			else
			{
				for (i=0;i<ntrk;i++)
				{
					ptrk[i]=k;
					k+=(ltrk[i]=j);
				}
			}
			fclose(fi);
			// CHECK WHETHER WE CAN CLIP EMPTY TRACKS!
			if (l>=k)
			{
				if (k<l)
					l=k;
				i=ntrk-1;
				while (i>0)
				{
					if (ltrk[i]>256)
					{
						n=m+ptrk[i]+256;
						o=m+l;
						while ((n<o)&&(0xE5==*n))
							n++;
						if (n!=o)
							break;
					}
					l=ptrk[i--];
				}
				i++;
				for (j=i;j<ntrk;j++)
					m[0x34+j]=0;
				if (!(m[0x31]&1))
					i/=2;
				m[0x30]=i;
			}
			else
			{
				puts("Error: incomplete target!");
				return 1;
			}
			if (fi=fopen(argv[z],"wb"))
			{
				fwrite(m,1,l,fi);
				free(m);
			}
			else
			{
				puts("Error: cannot create target!");
				return 1;
			}
		}
		else
		{
			puts("Error: cannot allocate memory!");
			return 1;
		}
		fclose(fi);
	}
	else
	{
		puts("Error: cannot open source!");
		return 1;
	}
	return 0;
}
