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

#define BUFSIZE 2048

unsigned char buf[BUFSIZE];

void usage(const char *name)
{
  printf("Usage: %s inpfile\n",name);
  printf("       inpfile: file which has the output\n");
  printf("    This then prints the name of the next image\n");
  printf("    and modifies the header of input file for next invocation\n"); 
  exit(1);
}

int main(int argc, char** argv)
{
  int fd;
  unsigned char buf[BUFSIZE];
  unsigned int ctr,ptr;

  if (argc <= 1) usage(argv[0]);

  fd = open(argv[1],O_RDONLY); 
  read(fd,(void *)buf,BUFSIZE); 
  close(fd);
  
  ptr=(buf[0]<<8)+(buf[1]); // offset to read from
  if (ptr > BUFSIZE) {
    // In real case, will exec default image
    printf("Error occurred. offset = %d\n",ptr);
    exit(1);
  }
  if (ptr == 0) {
    printf("No more images\n");
    exit(1);
  }
  buf[0]=buf[ptr];
  buf[1]=buf[ptr+1]; // Setup the next pointer

  fd = open(argv[1],O_WRONLY|O_TRUNC);
  write(fd,(void *)buf,BUFSIZE);
  close(fd);

  printf("%s\n",buf+ptr+2);
  exit(0);
}
