/*

Name
	SplitIt.c

Project
	SplitIt

Version

	1.00

Synopsis		
	An ANSI-C file splitter. Used to split long files so that they
	may be copied to MSDOS-disks, taking care of the MSDOS file-system.
	It's a shame that even Amiga users have to use this fucking
	MICROSOFT - SHIT ! Winners don't use PCs !

*/

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

#include <stat.h>		/* DeComment when compiling under Amiga OS */

#include <stdlib.h>
#include <fcntl.h>


int	main (int argc, char ** argv)
{
struct stat file;
long	disksize=atoi(argv[2]);
void	*memory;
char	joinname[20];
char	outname[20];
char	croutname[20];
char	tempname[20];
FILE	*joinfile;
int	readfile=0;
int	outfile=0;
int	namecount=0;
int 	readsize=0;

if ((argc == 4) || (argc == 3))
	{
	puts ("ANSI - C File splitter\nCopyright (c) 1995 Laserdance Productions\n");
	puts ("Scanning file...");
	if (!stat (argv [1],&file))
		{
		printf ("Found file : %s - Filesize is : %ld bytes.\n",argv[1],file.st_size);
		printf ("This file requires %d disk(s) of size %ld.\n",file.st_size/disksize+1,disksize);
		}
	else
		{
		printf ("**Error : Could not open file : %s",argv[1]);
		return (10);
		}
	puts ("Allocating buffers ...");
	if (memory = malloc (disksize))
		{
		if (argc ==3)
			strncpy (outname,argv[1],8);
		else
			strncpy (outname,argv[3],8);

		outname[8]=0;
		strcpy (joinname,outname);
		strcat (joinname,".JOI");

		printf ("Opening logfile : %s \n",joinname);

		if (joinfile = fopen (joinname,"w"))
			{
			if (readfile = open (argv[1],O_RDONLY,NULL))
				{
				fprintf (joinfile,"; Joinfile for Amiga-OS join command\n; Created by SplitIt!\n; (c) Laserdance Production 1995\n\njoin ");
				do
					{
					if ((readsize = read (readfile,memory,disksize))!=-1)
						{
						strcpy (croutname,outname);
						sprintf (tempname,".%d",namecount);
						strcat (croutname,tempname);
						namecount++;
						printf ("Opening output file : %s\n",croutname);
						if (outfile = open (croutname,O_CREAT|O_WRONLY,NULL))
							{
							write (outfile,memory,readsize);
							fprintf (joinfile,"%s ",croutname);
							close (outfile);
							chmod (croutname,S_IWRITE|S_IREAD|S_IDELETE);
							}
						else
							{
							puts ("**Error : Cannot open file to write to!");
							free (memory);
							close (readfile);
							fclose (joinfile);
							return (10);
							}
						}

					}
				while (readsize==disksize);
				fprintf (joinfile,"AS %s\n",argv[1]);
				}
			else
				{
				puts ("**Error : Cannot open file to read from");
				free (memory);
				fclose (joinfile);
				return (10);
				}
			fclose (joinfile);
			}
		else
			{
			puts ("**Error : Cannot open join file");
			free (memory);
			return (10);
			}
		}
	else
		{
		printf ("**Error : Insufficient resources. Failed to allocate memory block of %ld bytes",disksize);
		return (10);
		}
	}
else
	{
	printf ("Usage : %s FILENAME DISKSIZE [OUTPUTNAME]\n",argv[0]);
	}
}
