#include <cpu_prog_model.h>
#include <stdio.h>

#define FALSE  0
#define TRUE   1

int open();

void obj_reader( code, file_name)
PM *code;
char   file_name [];
{
   int    file_pointer;

   unsigned short int address_counter;

   char   in_buffer   [0x200],
          name_buffer [256];
   short  new_line,
          bytes;

   sprintf( name_buffer, "%s>%s", APPLE_PROGS, file_name);
   file_pointer = open( name_buffer, 0);    /* 0 = read */
   if (file_pointer == -1)
   {
      printf("Couldn't open the file %s\n", file_name);
      exit (-1);
   }

   printf( "Reading from file %s :\n", file_name);
   read( file_pointer, in_buffer, 2);
   address_counter = (in_buffer [1] << 8) | in_buffer [0];
   code->St = address_counter;

/*   printf("Start at $%04x:\n", address_counter);*/
   new_line = TRUE;
   while (bytes = read( file_pointer, in_buffer, 0x100) )
   {
      short loop;

      for (loop = 0;loop < bytes;loop ++)
      {
         code->Me [address_counter++] = in_buffer [loop];

         if (!(address_counter & 0x1FF) )
         {
            printf(".");
            new_line = FALSE;
         }

         if (!(address_counter & 0x7FFF) )
         {
            printf("\n");
            new_line = TRUE;
         }
      }
   }
/*   printf("Ended to $%04x\n\n", (address_counter - 1) & 0xFFFF);*/

   if (!new_line)
      printf("\n");

   close( file_pointer);
}



short hex_reader( code, file_name)
PM   * code;
char   file_name [];
{
   FILE * file_pointer;

   short action_flag;

   unsigned short int address;

   int  length,
        type,
        byte,
        checksum;

   action_flag = FALSE;
   file_pointer = fopen( file_name, "r");
   if (file_pointer)
   {
      printf("Reading from file %s :\n", file_name);
      fscanf( file_pointer, ":%02x%04hx%02x", &length, &address, &type);
      printf("Start at $%04x\n", address);
      code->St = address;
      action_flag = TRUE;

      do  /* Until type == 0x10 */
      {
         char buffer [256];

         while (length--)
         {
            fscanf( file_pointer, "%02x", &byte);
            code->Me [address++] = byte;
         }
         fscanf( file_pointer, "%02x\n", &checksum);
         printf(".");

         fscanf( file_pointer, ":%02x%04hx%02x", &length, &address, &type);
      }  while (type != 0x01);

      printf("\n");
      fclose( file_pointer);
   }

   else
      printf("Failed to open file \"%s\"\n", file_name);

   return action_flag;
}


