#include <stdlib.h>
#include <stdio.h>
#include "ntfile.h"
#include "xbox.h"
#include "sys/xboxkrnl.h"
#include "stdlib.h"
#include "string.h"

PUCHAR LoadFile(char *filename, ULONGLONG lFileSize) {
	FILE *fp;
	ULONGLONG FileSize;
	PUCHAR Buffer;

	fp = fopen(filename,"r");
	if (!fp) {
		printk("Error open file %s\n",filename);
		return NULL;
	}

	fseek(fp,0L,SEEK_END);
	FileSize = ftell(fp);
	fseek(fp,0L,SEEK_SET);

	if(lFileSize != 0) {
		if(FileSize != lFileSize) {
			printk("Invalid file Size %s\n",filename);
			return NULL;
		}
	}

	lFileSize = FileSize;
	Buffer = (PUCHAR)MmAllocateContiguousMemoryEx(lFileSize, MIN_KERNEL, 
			MAX_KERNEL, 0, PAGE_READWRITE);

	fread(Buffer, 1 , FileSize, fp);
	fclose(fp);
	
	return Buffer;
}


int SaveFile(char *szFileName,PBYTE Buffer,ULONG Size) {

	FILE *fp;

	fp = fopen(szFileName,"w");

	if(!fp) {
		printk("Error saving File\n");
		return 0;
	}
	
	fwrite(Buffer, 1, Size, fp);
	fclose(fp);

	return 1;
}

// Dismount all file systems
void DismountFileSystems(void) {

        ANSI_STRING String;

        RtlInitAnsiString(&String, "\\Device\\Harddisk0\\Partition1");
        IoDismountVolumeByName(&String);
        RtlInitAnsiString(&String, "\\Device\\Harddisk0\\Partition2");
        IoDismountVolumeByName(&String);
        RtlInitAnsiString(&String, "\\Device\\Harddisk0\\Partition3");
        IoDismountVolumeByName(&String);
        RtlInitAnsiString(&String, "\\Device\\Harddisk0\\Partition4");
        IoDismountVolumeByName(&String);
        RtlInitAnsiString(&String, "\\Device\\Harddisk0\\Partition5");
        IoDismountVolumeByName(&String);
        RtlInitAnsiString(&String, "\\Device\\Harddisk0\\Partition6");
        IoDismountVolumeByName(&String);
}

// Remap the drive to the XBE directory, even if the drive already mapped
int RemapDrive(char *szDrive, char *szDevice)
{
	ANSI_STRING LinkName, TargetName;
	char *DDrivePath = 0;
	char *temp = 0;

	// Allocate room for the drive path
	DDrivePath = (char *)MmAllocateContiguousMemoryEx(
				XeImageFileName->Length + 1,MIN_KERNEL,
	                        MAX_KERNEL, 0, PAGE_READWRITE);
	if (!DDrivePath)
		return 0;

	if(szDevice == NULL) {
		// Copy the XBE filename for now
		memcpy(DDrivePath, XeImageFileName->Buffer, XeImageFileName->Length);
		DDrivePath[XeImageFileName->Length] = 0;

		// Delete the trailing backslash, chopping off the XBE name, and make it
		// into an ANSI_STRING
		for(temp = &DDrivePath[XeImageFileName->Length]; temp != DDrivePath; temp--) {
			if(*temp == '\\') {
				*temp = 0;
				break;
			}
		}
	} else {
		strcpy(DDrivePath,szDevice);
	}

	RtlInitAnsiString(&TargetName, DDrivePath);

	// Set up the link
	RtlInitAnsiString(&LinkName, szDrive);
	IoDeleteSymbolicLink(&LinkName);

	if(!NT_SUCCESS(IoCreateSymbolicLink(&LinkName, &TargetName))) {
		return 0;
	}

	// Delete the filename memory
	MmFreeContiguousMemory(DDrivePath);

	return 1;
}


