#include <stdio.h>
#include "defines.h"
#include "nasm.h"
#include OSBIND
#include "debug.h"
#include NMALLOC_H
#include "labels.h"
#include "object.h"
#include "code.h"
#include "lib.h"

#if VERSION == 2 || VERSION == 0
# define V1_SIGNIFICANT 8
# define V1_SIGNDIFF    (SIGNIFICANT - V1_SIGNIFICANT)
# define V1_L_DIFF      V1_SIGNDIFF
# define V1_GSIZE       (sizeof( g_table) - V1_L_DIFF)

typedef struct
{
   char     name[ FSIGNIFICANT];  /* 32 Should be plenty for non-paths */
   lword    seek;
   word     bytes;
   word     time,
            date;
} old_f_table;

#define V1_F_DIFF ( sizeof( f_table) - sizeof( old_f_table))
#define V1_FSIZE  ( sizeof( old_f_table))
#endif


static char sorry[] = "Sorry, but that's a library version I can't handle";

void fix_lsizes( version, gsize, fsize)
lword    *gsize, *fsize;
{
   switch( version)
   {
#if VERSION == 2 || VERSION == 0
      case 1 :
         *gsize = *gsize / V1_GSIZE * sizeof( g_table);
         *fsize = *fsize / V1_FSIZE * sizeof( f_table);
         break;
#endif
      default :
         nferror( sorry);
   }
}


void fix_lversion( version, gbytes, globals, fbytes, files)
lword          *gbytes, *fbytes;
g_table huge   *globals;
f_table huge   *files;
{
   switch( version)
   {
#if VERSION == 2 || VERSION == 0
      case 1 :
      {
         register char huge   *p;
         g_table huge         *q;
         register word        i, j;
         register char huge   *dst;

         i = *gbytes /= V1_GSIZE;            /* calc # symbols */
         q = &globals[ i];                   /* move to end of */
         p = (char huge *) q - i * V1_L_DIFF; 

         while( p -= sizeof( word), --q, i--)
         {
            q->index = *(word *) p;
            for( dst = &q->name[ j = SIGNIFICANT]; j-- > V1_SIGNIFICANT;)
               *--dst = 0; 
            do
               *--dst = *--p;
            while( j--);
         }
         *gbytes *= sizeof( g_table);
      }

      {
         old_f_table huge     *p;
         f_table huge         *q;
         register word        i, j;
         register char huge   *src, *dst;

         i = *fbytes /= sizeof( old_f_table);   /* calc # symbols */
         q = &files[ i];                        /* move to end of */
         p = (old_f_table huge *) ((char huge *) q - i * V1_F_DIFF); 

         while( --p, --q, i--)
         {
            q->date  = p->date;
            q->time  = p->time;
            q->bytes = p->bytes;
            q->seek  = p->seek;
            dst = &q->name[ FSIGNIFICANT];
            src = &p->name[ FSIGNIFICANT];
            for( j = FSIGNIFICANT; j--; *--dst = *--src);
         }
         *fbytes *= sizeof( f_table);
      }
#endif   
      default :
         nferror( sorry);

   }
}

/* #1# the V1_SIZE + sizeof( word) is added, so that in the loop we need 
       not sub with sizeof( word)!! 
 */       
