
#include <limits.h>

#include "timecon.h"
#include "tar.h"


static unsigned char TimeShift[5] = { 96, 106, 153, 110, 51 };


void unix_to_fs_time(unsigned char *fstime, unsigned long unixtime) {
  int Cnt;
  signed long Carry,tmp;

  fstime[4] = 0;
  fstime[3] = (unsigned char)(unixtime >> 24);
  fstime[2] = (unsigned char)(unixtime >> 16) & 255;
  fstime[1] = (unsigned char)(unixtime >>  8) & 255;
  fstime[0] = (unsigned char)(unixtime & 255);
  Carry = 0;
  Cnt = 0;
  while (Cnt <= 4) {
    tmp = (long)fstime[Cnt] * 100L + Carry;
    Carry = 0;
    while (tmp >= 256) {
      Carry++;
      tmp -= 256;
    }
    fstime[Cnt] = (unsigned char)tmp;
    Cnt++;
  }
  Carry = 0;
  Cnt = 0;
  while (Cnt <= 4) {
    tmp = (long)fstime[Cnt] + (long)TimeShift[Cnt] + Carry;
    Carry = 0;
    if (tmp >= 256) {
      Carry = 1;
      tmp -= 256;
    }
    fstime[Cnt] = (unsigned char)tmp;
    Cnt++;
  }
} /* unix_to_fs_time */


unsigned long fs_to_unix_time(unsigned char *FStime) {
  signed int Cnt;
  signed long tmp,Carry,divident;
  unsigned char fstime[5];

  Cnt = 0;
  Carry = 0;
  while (Cnt <= 4) {
    tmp = (long)FStime[Cnt] - (long)TimeShift[Cnt] - Carry;
    Carry = 0;
    if (tmp < 0) {
      tmp += 256;
      Carry = 1;
    }
    fstime[Cnt] = (unsigned char)tmp;
    Cnt++;
  }
  if (Carry > 0) {
    fprintf(stderr,"tar: warning: UNIX time underflow\n");
    return 0;
  }
  Cnt = 4;
  Carry = 0;
  while (Cnt >= 0) {
    divident = (Carry * 256 + fstime[Cnt]); 
    tmp =  divident / 100;
    Carry = divident - tmp * 100;
    fstime[Cnt] = (unsigned char)tmp;
    Cnt--;
  }
  if (Carry * 256 / 100 >= 128)
    fstime[0]++;
  if (fstime[4] > 0) {
    fprintf(stderr,"tar: warning: UNIX time overflow");
    return ULONG_MAX;
  } else
    return (long)fstime[0] +
           (long)fstime[1] * 256L +
           (long)fstime[2] * 256L * 256L +
           (long)fstime[3] * 256L * 256L * 256L;
} /* fs_to_unix_time */
