// jpsjps.c : Makes JPS files work with VRex DepthCharge.
// Copyright 2001 by TIm Kemp, tim@ephehm.com
// Freely distributable.  Use this in whole or part anywhere for any legal
// purpose.  All I ask is that you please send me an e-mail and let me know
// what you used it for and where. TRK 2-July-2001

#include <io.h>
#include <stdio.h>
#include <malloc.h>

#define DQT 0xdb
#define JPS 0xe3

#define NUMSEGS 44

unsigned char jpsjps[] =
{
  0xff, 0xe3,        // JPS section
  0x00, 0x1f,        // length of section
  '_', 'J', 'P', 'S',
  'J', 'P', 'S', '_',
  0x00, 0x04,        // who knows what the rest of this is? (not me)
  0x00, 0x00,
  0x02, 0x01,
  0x00, 0x0d,
  'V', 'R', 'e', 'x',
  ' ', 'J', 'P', 'S',
  ' ', 'v', '2', '.',
  '0'
};

int main(int argc, char* argv[])
{
  unsigned char *image;
  FILE *jpg;
  long fl;            // file length
  long dqtloc;        // where the dqt section starts
  long jpsloc;        // where the jps section starts
  int  f;             // file number
  long i;             // loop counter

  // step through all the command line arguments
  for (f=1; f<argc; f++)
  {
    // clear out the segment indexes
    dqtloc = -1;
    jpsloc = -1;

    // try to open the file
    if (NULL != (jpg = fopen(argv[f], "r+b")))
    {
      // allocate enough memory to load the whole file then read the file
      fl = _filelength(_fileno(jpg));
      if (NULL != (image = malloc(fl)))
      {
        fread(image, fl, 1, jpg);

        // scan the file looking for segments
        for (i=0; i<fl; i++)
        {
          if (image[i] == 0xff)
          {
            if (image[i+1] == DQT)
            {
              dqtloc = i;
            }
            else if (image[i+1] == JPS)
            {
              jpsloc = i;
            }
          }
        }

        // if we found a DQT segment and not a JPS segment insert a JPS
        if (jpsloc == -1 && dqtloc != -1)
        {
          fseek(jpg, 0, SEEK_SET);
          fwrite(image, dqtloc, 1, jpg);
          fwrite(jpsjps, sizeof(jpsjps), 1, jpg);
          fwrite(&image[dqtloc], fl - dqtloc, 1, jpg);
        }

        free(image);
      }
      fclose(jpg);
    }

  }
  return 0;
}
