#include "raine.h"

/* Extremely simplified iso image handling, can handle only files in the
 * root directory (I don't need anything else !) */

static int find_file(char *iso, char *filename, int *size, int *start) {
  FILE *f = fopen(iso,"rb");
  if (!f) {
    return 0;
  }
  fseek(f,0x809e,SEEK_SET);
  int root_dir = 0;
  fread(&root_dir,1,4,f);
  fseek(f,root_dir * 0x800, SEEK_SET);
  unsigned char buff[2048];
  fread(buff,2048,1,f);
  unsigned char *ptr = buff;
  int len_record;
  int len_dir = 0;
  int found = 0;
  do {
    len_record = *ptr;
    if (len_record == 0 && len_dir > 0) {
      fread(buff,2048,1,f);
      len_dir -= 2048;
      if (len_dir) {
	ptr = buff;
	len_record = *ptr;
      }
    }
    if (len_record) {
      // int len_ext = ptr[1];
      int location = *((int *)&ptr[2]);
      int len_file = *((int *)&ptr[10]);
      int len_name = ptr[32];
      char name[40];
      memcpy(name,&ptr[33],len_name);
      name[len_name] = 0;
      char *s = strchr(name,';'); // extension iso : ; + number
      if (s)
	*s = 0;
      // printf("%s len %d location %x\n",name,len_file,location);
      if (!name[0] && len_file && !len_dir) {
	len_dir = len_file;
	// printf("init len_dir %d\n",len_dir);
      } else if (!stricmp(name,filename)) {
	*size = len_file;
	*start = location;
	found = 1;
	break;
      }
    }
    ptr += len_record;
  } while (len_record);
  fclose(f);
  return found;
}

int iso_size(char *iso, char *name) {
  int len, location;
  if (find_file(iso,name,&len,&location))
    return len;
  return 0;
}

int load_from_iso(char *iso, char *name, unsigned char *dest, int size) {
  int len, location;
  if (find_file(iso, name, &len, &location)) {
    FILE *f = fopen(iso,"rb");
    fseek(f,location * 0x800, SEEK_SET);
    fread(dest,1,size,f);
    fclose(f);
    return 1;
  }
  return 0;
}

