/*
 * bin.c - converts an AmigaDOS executable single-hunk file to a binary image
 *
 * Bruno Costa - 9 Dec 89 - 9 Dec 89
 *
 */

#include <exec/types.h>
#include <proto/dos.h>

void print (char *msg);
void copyright (void);
void help (void);
void notify (char *msg);

#define abort(x) {errnum = x; goto cleanup;}

void main (int argc, char *argv[])
{
 int errnum = 0;
 BPTR f = NULL;
 BPTR seglist = NULL;

 if (argc != 3)
 {
   copyright ();
   help ();
   abort (5);
 }
 else
 {
   seglist = LoadSeg (argv[1]);
   if (!seglist)
   {
     notify ("Could not read executable file");
     abort (20);
   }
   else
   {
     unsigned long *bin = NULL, *ptr = BADDR (seglist);

     do
     {
       if (ptr[-1])
         if (bin)
         {
           notify ("Multiple-hunk load files not allowed");
           abort (30);
         }
         else
           bin = ptr;
     } while (ptr = BADDR (ptr[0]));

     if (!bin)
     {
       notify ("All hunks are empty !");
       abort (30);
     }

     f = Open (argv[2], MODE_NEWFILE);
     if (f)
       Write (f, &bin[1], bin[-1] - 2 * sizeof (bin[0]));
     else
     {
       notify ("Could not write binary file");
       abort (20);
     }
   }
 }

 copyright ();

cleanup:

 if (seglist)
   UnLoadSeg (seglist);
 if (f)
   Close (f);
}


/*
 * prints any message
 */
void print (char *msg)
{
 Write (Output(), msg, strlen (msg));
}

/*
 * prints a copyright message
 */
void copyright (void)
{
 print ("\x1b[33mbin v1.0\x1b[31m - \xa9 1989 by Bruno Costa\n");
}

/*
 * prints a help message
 */
void help (void)
{
 print ("Converts a relocatable code (or data) load file into a binary image file\n");
 print ("usage: bin <executable> <binary>\n");
 print ("\t <executable> = Single hunk AmigaDOS executable file\n");
 print ("\t <binary> = Binary image output filename\n");
}

/*
 * notifies an error
 */
void notify (char *msg)
{
 print ("bin: ");
 print (msg);
 print ("\n");
}
