/**
 * Copyright (c) 2021 Dominic Masters
 * 
 * This software is released under the MIT License.
 * https://opensource.org/licenses/MIT
 */

#include "file.h"

void fileNormalizeSlashes(char *string) {
  char c;
  int i = 0;

  while(c = string[i++]) {
    if(c != '\\' && c != '/') continue;
    string[i-1] = FILE_PATH_SEP;
  }
}

void fileMkdirp(char *path) {
  char buffer[FILENAME_MAX];
  char c;
  int i = 0;
  bool inFile;
  bool hasMore;

  inFile = false;
  hasMore = false;
  while(c = path[i]) {
    if((c == '\\' || c == '/') && i > 0) {
      buffer[i] = '\0';
      _mkdir(buffer);
      inFile = false;
      hasMore = false;
      buffer[i] = FILE_PATH_SEP;
      i++;
      continue;
    }

    if(c == '.') inFile = true;
    hasMore = true;
    buffer[i] = c;
    i++;
  }

  if(!inFile && hasMore) {
    buffer[i] = '\0';
    _mkdir(buffer);
  }
}

void assetReadString(FILE *file, char *buffer) {
  size_t length;
  fseek(file, 0, SEEK_END);// Seek to the end
  length = ftell(file);// Get our current position (the end)
  fseek(file, 0, SEEK_SET);// Reset the seek 
  fread(buffer, 1, length, file);// Read all the bytes
}