/*
 *  Super-Kung-Foo-File-Splitting-Program (split) v 1.2,
 *  Copyright © 2001 Kalle Räisänen.
 *
 *  Uncommented for your satisfaction
 */

#include <exec/types.h>
#include <exec/memory.h>

#include <libraries/dos.h>

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

#define TRUE  1
#define FALSE 0

static UBYTE *VersTag = "\0 $VER: Super-Kung-Foo-File-Splitting-Program 1.2";

int getsize(char *filename)
{
   int size = 0;
   struct FileLock *lock;
   struct FileInfoBlock *fib_ptr;

   if(!(fib_ptr = (struct FileInfoBlock *) AllocMem(sizeof(struct FileInfoBlock),
        MEMF_PUBLIC | MEMF_CLEAR)))
      return 0;

   if(!(lock = (struct FileLock *) Lock(filename, SHARED_LOCK)))
      {
      FreeMem( fib_ptr, sizeof( struct FileInfoBlock ) );
      return 0;
      }

   if(!(Examine(lock, fib_ptr)))
      {
      FreeMem(fib_ptr, sizeof(struct FileInfoBlock));
      UnLock(lock);
      return 0;
      }

   size = fib_ptr->fib_Size;
   UnLock(lock);
   FreeMem(fib_ptr, sizeof(struct FileInfoBlock));

   return size;
}

int main(int argc, char **argv)
{
   int size, i = 0, parts, x = 2;
   char buf[300];
   BPTR infile, out;

   if(argc > 3)
      {
      parts = argc-2;
      if(!(size = getsize(argv[1])))
         {
         printf("%s: filerror on %s\n",argv[0],argv[1]);
         return RETURN_ERROR;
         }
      if(infile = Open(argv[1], MODE_OLDFILE))
         {
         printf("%s: splitting %s into:",argv[0],argv[1]);
         for(; x < argc; x++)
            {
            i = 0;
            if(out = Open(argv[x], MODE_NEWFILE))
               {
               printf(" %s", argv[x]);
               while(FGets(infile, buf, sizeof(buf)) && (i < size/parts))
                  {
                  FPuts(out, buf);
                  i += strlen(buf);
                  }
               Close(out);
               }
            else
               {
               printf("\n%s: couldn´t create %s\n",argv[0],argv[x]);
               return RETURN_ERROR;
               }
            }
         Close(infile);
         }
      else
         {
         printf("%s: couldn´t open %s\n",argv[0],argv[1]);
         return RETURN_ERROR;
         }
      }
   else
      {
      printf("Usage: %s infile outfile1 outfile2 [outfile3] [outfile4] [...]\n",argv[0]);
      return RETURN_ERROR;
      }
   printf(", done!\n");
   return RETURN_OK;
}


