/*
    JPC: A x86 PC Hardware Emulator for a pure Java Virtual Machine
    Release Version 2.0

    A project from the Physics Dept, The University of Oxford

    Copyright (C) 2007 Isis Innovation Limited

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License version 2 as published by
    the Free Software Foundation.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License along
    with this program; if not, write to the Free Software Foundation, Inc.,
    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 
    Details (including contact information) can be found at: 

    www.physics.ox.ac.uk/jpc
*/

package org.jpc.sourcecompiler;

import java.util.*;
import java.nio.*;
import java.io.*;

import org.jpc.emulator.memory.codeblock.optimised.*;
import org.jpc.emulator.memory.codeblock.*;
import org.jpc.emulator.memory.*;

public class DebugCompilerFactory extends JavaSourceCompiler implements CodeBlockFactory
{
    File sourceOutputDir;
    CodeBlockFactory backup;
    RealModeUDecoder decoder;

    public DebugCompilerFactory(CodeBlockFactory backup)
    {
        sourceOutputDir = new File(System.getProperty("user.dir")+"/org/jpc/emulator/memory/codeblock/compiler");
        this.backup = backup;
        decoder = new RealModeUDecoder();
    }
    
    public RealModeCodeBlock getRealModeCodeBlock(ByteSource source)
    {
        ByteSourceWrappedMemory bs = (ByteSourceWrappedMemory) source;
        Memory m = bs.getMemory();
        int offset = bs.getOffset();
        
        RealModeCodeBlock result = getRealModeCodeBlock(decoder.decodeReal(source));

        int length = bs.getOffset() - offset;
        bs.set(m, offset);
        try
        {
            byte[] rawX86 = new byte[length];
            for (int i=0; i<length; i++)
                rawX86[i] = bs.getByte();
            
            FileOutputStream binary = new FileOutputStream(new File(sourceOutputDir, getLastClassTitle()+".asm"));
            binary.write(rawX86);
            binary.close();

            FileOutputStream javaSource = new FileOutputStream(new File(sourceOutputDir, getLastClassTitle()+".java")); 
            byte[] raw = getLastSourceCode().getBytes();
            javaSource.write(raw);
            javaSource.close();
        }
        catch (ArrayIndexOutOfBoundsException e) {}
        catch (Exception e)
        {
            e.printStackTrace();
        }
                           
        return result;
    }

    public ProtectedModeCodeBlock getProtectedModeCodeBlock(ByteSource source, boolean operandSize)
    {
        return backup.getProtectedModeCodeBlock(source, operandSize);
    }
}
