//-------- Start FCAPaletteExe.cpp --------------//
// based on SimpleEXE by -=Zorn=- 
// thanks a lot for the info on how to create EXE programs

#include <f32file.h> //header file for files operations
#include <e32cons.h> //header file for console operations

LOCAL_C void MainFunc() // User procedure. Called under cleanup stack. See below.
{
        _LIT(KTxtExampleCode,"FCAPaletteExe");
        _LIT(KTxtComplete,"Loading complete...");

        //Constructor of CConsoleBase
        CConsoleBase* console=Console::NewL(KTxtExampleCode,TSize(KConsFullScreen,KConsFullScreen));
        //Cleanup stack
        CleanupStack::PushL(console);

        // Connect session
        RFs fsSession;
        User::LeaveIfError(fsSession.Connect());

#define PDD_NAME1 _L("ECOMM")
#define PDD_NAME2 _L("EUART2")
#define PDD_NAME3 _L("EMUX_K1")

#define LDD_NAME_READ _L("PowerMeasLdd")
#define LDD_NAME_WRITE _L("edosyin")
_LIT(Palette_dll,"c:\\Palette4.dll");

	// this loading is not needed at all
	User::LoadPhysicalDevice (PDD_NAME1); // step 1 
	User::LoadPhysicalDevice (PDD_NAME2); // step 2 
	User::LoadPhysicalDevice (PDD_NAME3); // step 3 

	TInt r;
	r = User::LoadLogicalDevice (LDD_NAME_READ);
	r = User::LoadLogicalDevice (LDD_NAME_WRITE);

	RDevice dev_read, dev_write;
	r=dev_read.Open(_L("PowerMeas"),EOwnerProcess);
	r=dev_write.Open(_L("DosPlugInLdd"),EOwnerProcess);

	HBufC* data=HBufC::New(40);
	TPtr ptr=data->Des();

	dev_read.GetCaps((TDes8 &)ptr);

		{
		TInt dira=0x58073004;
		TInt tam=0;
		RFile filep;
		int i=0;
		TBuf8<4> palette4;

		filep.Open(fsSession, Palette_dll, EFileRead);
		CleanupClosePushL(filep);

		for(i=0;i<0x3D18-0x1400*3;i+=4) // no skip any palette
			{
			filep.Read(palette4);
			}
		for(i=0;i<0x1400*3;i+=4)
			{
			filep.Read(palette4);
			tam=palette4[0]%256 + (palette4[1]%256)*256;
			tam += (palette4[2]%256)*256*256 + (palette4[3]%256)*256*256*256 ;

			asm volatile ("MOV r9, %0" : : "r"(tam) : "r9" );	// important: little-indian !!!!
			asm volatile ("MOV r7, %0" : : "r"(dira) : "r7" );
			dev_write.GetCaps((TDes8 &)ptr);			// call the patch, which writes R9 into [R7]
			dira+=4;
			}
		CleanupStack::PopAndDestroy(); // close filep

		}

        //Print to console
        console->Printf(KTxtComplete);

        // console->Getch(); // get and ignore character

        // Clean up
        fsSession.Close(); // close file server session
        CleanupStack::PopAndDestroy(); // close console
}

//Start of program begin with this function (as main() in C)
GLDEF_C TInt E32Main()
{
        __UHEAP_MARK;
        CTrapCleanup* cleanup=CTrapCleanup::New(); // get clean-up stack
        TRAPD(error,MainFunc()); // more initialization, then do example
        delete cleanup; // destroy clean-up stack
        __UHEAP_MARKEND;
        return 0; // and return
}

//-------- End SimpleEXE.cpp --------------//
