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

#include <sha.h>

#define MAXMSG 16000

int main(int argc, char *argv[])
{
  FILE *fp, *ofp;
  unsigned char ibuf[MAXMSG + 1024], bbuf[4];
  unsigned int count = 0;
  int len, len2;
  char outf[16];
  SHA_CTX hash, hashall;

  fp = fopen(argv[1], "r");

  SHA1_Init(&hashall);

  len2 = MAXMSG;
  while (len2) {

    memset(ibuf, 0, MAXMSG + 1024);

    len2 = fread(&ibuf[28], 1, MAXMSG, fp);

    len = len2;

    ibuf[0] = count >> 8;
    ibuf[1] = count;
    ibuf[2] = len >> 8;
    ibuf[3] = len;

    if (!len)
      len = 20,
        SHA1_Final(&ibuf[28], &hashall);
    else
      SHA1_Update(&hashall, &ibuf[28], len);

    SHA1_Init(&hash);
    SHA1_Update(&hash, &ibuf[28], len);
    SHA1_Final(&ibuf[8], &hash);

    if (!count)
      memcpy(bbuf, &ibuf[8], 4);

    memcpy(&ibuf[4], bbuf, 4);

    sprintf(outf, "%08X.%03d", *((unsigned int *) (bbuf)), count++);

    ofp = fopen(outf, "w");
    fwrite(ibuf, 1, len + 28, ofp);
    fclose(ofp);

  }
  fclose(fp);
  return 0;
}
