#include "config.h"
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include "common.h"
#include "getuint.h"
#include "cam2jpgtab.h"

int
write_file(buf, len, outfp)
     u_char	*buf;
     int	len;
     FILE	*outfp;
{
  int i, l;

  i = 0;
  while( len > i) {
    l = ( (len - i) < BUFSIZ) ? (len -i) : BUFSIZ;
    fwrite(&buf[i], sizeof(u_char), l, outfp);
    i = i + l;
  }
  return(i);
}

int
write_jpeg(buf, outfp)
     u_char	*buf;
     FILE	*outfp;
{
  int i = 0;
  int areaNum;
  int ysize;
  int usize;
  int vsize;
  
  areaNum =  get_u_short(buf);	/* areaNum == 0x03 */
  ysize = get_u_short(buf + 2);
  usize = get_u_short(buf + 4);
  vsize = get_u_short(buf + 6);
  i = i + 8;
  
  write_file(soi, sizeof(soi), outfp);
  write_file(app0, sizeof(app0), outfp);
  write_file(dqt0, sizeof(dqt0), outfp);
  write_file(&buf[i], 64, outfp);
  i = i + 64;

  write_file(dqt1, sizeof(dqt1), outfp);
  write_file(&buf[i], 64, outfp);
  i = i + 64;

  write_file(sof, sizeof(sof), outfp);
  write_file(dht, sizeof(dht), outfp);

  write_file(sos_y, sizeof(sos_y), outfp);
  write_file(&buf[i], ysize, outfp);
  i = i + ysize;
  
  write_file(sos_u, sizeof(sos_u), outfp);
  write_file(&buf[i], usize, outfp);
  i = i + usize;

  write_file(sos_v, sizeof(sos_v), outfp);
  write_file(&buf[i], vsize, outfp);
  i = i + vsize;

  write_file(eoi, sizeof(eoi), outfp);

  return(i);
  
}
