#include <acpi.h>
#include <stdint.h>
#include <printf.h>

static int RSDP_verify(void *rsdp_pointer) {
  printf("Verifying potential RSDP at address 0x%p... ", rsdp_pointer);  
  union rsdp_t *rsdp = rsdp_pointer;
  uint8_t checksum = 0;
  char *rsdp_csm_ptr = rsdp_pointer; 
  int i;
  if(checksum) return 0;
  if(rsdp->v1.version) {
    printf("APCI revision > 2.\n");
    checksum = 0;
    printf("len : %i\n", rsdp->v2.len);
    for(i = 0; i < rsdp->v2.len; i++) {
      checksum += rsdp_csm_ptr[i];
    }
  }
  else {
    printf("APCI revision 1.\n");
    for(i = 0; i <= 20; i++) {
      checksum += rsdp_csm_ptr[i];
    }
  }
  if(checksum) {
    return 0;
    printf("Invalid, searching on.\n");
  }
  printf("RSDP Verified!\n");
  return 1;
}

// TODO: move these when you gain your sanity
rsdp_t *find_RSDP() { // finds root descriptor
  const char sig[9] = "RSD PTR ";
  uintptr_t *p = (void *)0x040e;
  uintptr_t *ebda_unshifted = (void *)p;

  // TODO you REALLY need to verify this.
  void *ebda = (void *)((uintptr_t)ebda_unshifted << (uintptr_t)4 & (uintptr_t)0xfffff); 


  for(void *i = ebda; i <= ebda + 64000; i += 16) {
    if(!(memcmp(sig, i, 8))) {
      if(RSDP_verify(i)) {
        return(i);
      }
    }
  }

  for(void *i = (void *)0xe0000; i <= (void *)0xfffff; i += 16) {
    if(!(memcmp(sig, i, 8))) {
      if(RSDP_verify(i)) {
        return(i);
      }
    }
  }
}


