#include <dos.h>
#include <process.h>
#include <stdio.h>
#include <conio.h>

union REGS in, out;
struct SREGS sr;
unsigned char buf[512], sector[30], clust_size, fat_cnt;
unsigned char  root_heads, root_sectors, root_cyls;
unsigned int i = 0, j = 1, p,res_sect, sect_size, trk_sec,  fat_adress, head_cnt, a;
unsigned long starting_sector,  fat_size, root_catalogue_adress;
struct sec_cat {
  unsigned char name[8];
  unsigned char name_e[3];
  unsigned char atr;
  unsigned char rez[10];
  unsigned int time;
  unsigned int date;
  unsigned int n_clust;
  unsigned long size;
} *cat;
struct sec_cat sec[16];

void main()
{  //Content of root sector of first partition
  in.h.ah = 2;
  in.h.dl = 0x80;
  in.h.dh = buf[0x1bf];
  in.x.cx = *((int*)&buf[0x1c0]);
  in.h.al = 1;
  sr.es = FP_SEG(sector);
  in.x.bx = FP_OFF(sector);
  int86x(0x13, &in, &out, &sr);
  if (out.x.cflag != 0 && out.h.ah != 0)
  {
    return;
  }
  sect_size = *((int*)&sector[0x0b]);
  clust_size = sector[0x0d];
  fat_size = *((unsigned long*)&sector[0x24]);
  trk_sec = *((int*)&sector[0x18]);
  head_cnt = *((int*)&sector[0x1A]);
  res_sect = *((int*)&sector[0x0e]);
  fat_cnt = sector[0x10];

  //Adress of FAT and root catalogue
  fat_adress = starting_sector + res_sect;
  root_catalogue_adress = fat_adress + fat_size * fat_cnt;
  printf("LBA root catalogue adress: %lu %u\n", root_catalogue_adress, fat_adress);
  root_cyls = root_catalogue_adress / (trk_sec * head_cnt);
  root_heads = (root_catalogue_adress % (trk_sec * head_cnt)) / trk_sec;
  root_sectors = (root_catalogue_adress % (trk_sec * head_cnt)) % trk_sec + 1;
  printf("CHS root catalogue adress: %u %u %u\n", root_cyls, root_heads, root_sectors);
  printf("Press any key to continue...\n");
  getch();
  in.h.ah = 2;
  in.h.dl = 0x80;
  in.h.dh = root_heads;
  in.h.ch = root_cyls;
  in.h.cl = root_sectors;
  in.h.al = 1;
  sr.es = FP_SEG(buf);
  in.x.bx = FP_OFF(buf);
  cat = (struct sec_cat*)&buf[0];
  int86x(0x13, &in, &out, &sr);

  if (out.x.cflag != 0 && out.h.ah != 0)
  {
    printf("OPERATION PORT READING WAS NOT SUCCESFULL! Hold down some key to quit...");
    getch();
    return;
  }


  a = 1;
  for (i = 0; i < 16; i++, a++)
  {
    if ((cat[i].atr & 0x16) == 1) {         
      printf("Name: ");
      for (j = 0; j < 8; j++)
        printf("%c", cat[i].name[j]);
      break;
    }
  }
  printf("\n\nPress any key to exit...");
  getch();
}