#include "stdafx.h"
#include "nopepad.h"

void ReadText( HWND hWnd, int EditControl )
{
		char *Data;
		DWORD FileSize;
		HANDLE FileIn;
		FileIn = CreateFile( CurFile, GENERIC_READ, 0, NULL, OPEN_EXISTING, 
			FILE_ATTRIBUTE_NORMAL|FILE_FLAG_RANDOM_ACCESS, 0 );
		if( !FileIn )
		{
			MessageBox( hWnd, "Unable to open file", "NopePad", MB_OK );
			return;
		}
		DWORD HiDWord;
		FileSize = GetFileSize( FileIn, &HiDWord );
		Data = new char[FileSize+1];
		if( !Data )
		{
			MessageBox( hWnd, "Insufficient memory", "Error", MB_OK );
			CloseHandle( FileIn );
			return;
		}
		DWORD ReadIn;
		if( ReadFile( FileIn, Data, FileSize, &ReadIn, 0 ) == 0 )
		{
			MessageBox( hWnd, "Error reading file", NULL, MB_OK );
			CloseHandle( FileIn );
			return;
		}
		CloseHandle( FileIn );
		Data[ReadIn]='\0';
		SetDlgItemText( hWnd, EditControl, Data );
		delete [] Data;
}

void WriteText(HWND hWnd, int EditControl)
{
	char *Data;
	DWORD FileSize, Written;
	HANDLE FileOut;
	FileOut = CreateFile( CurFile, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 
		FILE_ATTRIBUTE_NORMAL|FILE_FLAG_RANDOM_ACCESS, 0 );
	if( !FileOut )
	{
		MessageBox( hWnd, "Unable to open file", "NopePad", MB_OK );
		return;
	}
	FileSize = GetWindowTextLength( GetDlgItem( hWnd, EditControl ) );
	Data = new char[FileSize+1];
	if( !Data )
	{
		MessageBox( hWnd, "Insufficient memory", "Error", MB_OK );
		CloseHandle( FileOut );
		return;
	}
	GetDlgItemText( hWnd, EditControl, Data, FileSize+1 );
	if( WriteFile( FileOut, Data, FileSize, &Written, 0 ) == 0 )
	{
		MessageBox( hWnd, "Error writing file", NULL, MB_OK );
		CloseHandle( FileOut );
		return;
	}
	CloseHandle( FileOut );
	delete [] Data;
}

BOOL MyFileExists( const char* Path )
{
	HANDLE File;

	File = CreateFile( CurFile, GENERIC_READ, 0, NULL, OPEN_EXISTING, 
			FILE_ATTRIBUTE_NORMAL|FILE_FLAG_RANDOM_ACCESS, 0 );
	BOOL Ret = File ? TRUE : FALSE;
	if( File )
		CloseHandle( File );
	return( Ret );
}

BOOL OkToReplace( HWND hWnd, const char * Path )
{
	if( MyFileExists( Path ) )
	{
		char Msg[MAX_PATH*2];
		wsprintf( Msg, "%s\nAlready exists, do you want to replace it?", Path );
		if( MessageBox( hWnd, Msg, "Save as", MB_ICONEXCLAMATION|MB_YESNO ) != IDYES )
			return( FALSE );
	}
	return( TRUE );
}

