#include <inttypes.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <sys/stat.h>
 

uint8_t jexif_magic[]={0xFF,0xD8,0xFF,0xE1,0x3D,
		0x6A,0x45,0x78,0x69,0x66,0x00};

#define EXTR_SIZE (1024*1024)
uint8_t buff[EXTR_SIZE];

char jpg_name[256];

int main(int argc, char *argv[])
{
  long start_pos=143*512;
  long act_pos;
  long clust_size=16384;
  int fd_part;
  int fd_jpg;
  int jpg_cnt=1;
  int res;
  int fl_seek;
  
  fd_part=open("martin.img",O_RDONLY);
  
  act_pos=start_pos;
  fl_seek=1;
  do{
    if(fl_seek){
      fl_seek=0;
      lseek (fd_part,act_pos,SEEK_SET);
    }
    res=read(fd_part,buff,clust_size);
    if(res!=clust_size)  break;
    act_pos+=clust_size;
    if(!memcmp(buff,jexif_magic,sizeof(jexif_magic))){
      res=read(fd_part,buff+clust_size,EXTR_SIZE-clust_size);
      if(res<0) break;
      res+=clust_size;
      sprintf(jpg_name,"out%03d.jpg",jpg_cnt);
      fd_jpg=open(jpg_name,O_WRONLY|O_CREAT|O_TRUNC,S_IWRITE|S_IREAD);
      write(fd_jpg,buff,EXTR_SIZE);
      close(fd_jpg);
      jpg_cnt++;
      fl_seek=1;
    }
  }while(1);
  close(fd_part);
  return 0;
}
