using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System;
using System.Threading;
using System.IO;
using System.Text;
using Random = UnityEngine.Random;
using System.Text.RegularExpressions;
using System.Net;
using System.Globalization;
using System.Diagnostics;
using UnityEngine.SceneManagement;
using System.Runtime.InteropServices;
using System.Net.NetworkInformation;
using MyNes;
using Debug = UnityEngine.Debug;
using MyNes.Mappers;
using DynamicCSharp;
using System.Linq;
using UnityEngine.Networking;
using UnityEngine.UI;
using TMPro;
using CielaSpike;
public class RxEnhance : MonoBehaviour
{
    public static Color[] merge;
    public static Color[] mergeAlpha;
    public static Texture2D myTexture2D;
    public static Color[] toCrop;
    public static Color[] tempcolor;
    public static Color[] newPixels;
    public static Color[] originalPixels;
    public static Texture2D newTexture;
    public static bool hasntCollectedGC = false;
    public static byte[] output3;
    public static string md = "";
    public static List<String> stNames = new List<string>();
    public static string fallBack = "";
    public static string imghash = "";
    public static Color[] tempcspr;
    public bool frameAdvance = false;
    public string[] dirSplit = new string[5];
    public string up;
    public string down;
    public string left;
    public string right;
    public string upleft;
    public string downleft;
    public string upright;
    public string downright;
    //public static ActionCam actionCam;
    public static Transform actionTransform;
    public List<Vector3> smoothAction = new List<Vector3>();
    public static List<Vector3> actionPosition = new List<Vector3>();
    public bool clickedFrame = false;
    public int dotCount = 0;
    public DumpButton DumpButton;
    public RefreshButton RefreshButton;
    public static bool WorkingisSprite = false;
    public static RawImage WorkingGraphic;
    public Texture2D WorkingBGTexture;
    public Texture2D WorkingTexture;
    public static string WorkingGFXFile;
    public static Text DumpGraphicText;
    public static Text LoadGraphicText;
    public Vector3 MD5bounds;
    public GameObject CustomBackgroundGO;
    public Material CustomBackground;
    public bool knockOutSky = false;
    public int SkyColor;
    public Camera SkyBGCam;
    public BGTile Sky;
    public int tilesChanged = 0;
    public int tilesCounted = 0;
    public int totalX = 0;
    public int totalY = 0;
    public int prvTotalX = 0;
    public int prvTotalY = 0;
    public int fineTotalX = 0;
    public int fineTotalY = 0;
    public string mostCommonTile = "";
    public string prevMostCommonTile = "";
    public GameObject Space;
    public Vector3 NewFontOffset = new Vector3(0.5f, -0.5f, 0);
    public Vector3 NewFontBGOffset = new Vector3(0.5f, -0.5f, -0.01f);
    public List<GameObject> newLettersOnScreen = new List<GameObject>();
    public GameObject NewTextPrefab;
    public WindowsVoice tts;
    public Text TranslationTextBox;
    public static string completeSentence = "";
    public static string translatedSentence = "";
    public List<string> RecientlySpoken = new List<string>();
    public static string OST = "";
    public static string previousOST = "";
    public string publicOST = "";
    public static List<AlphabetIndex> alphabet = new List<AlphabetIndex>();
    public string[] ABC;
    public Canvas MainMenu;
    public static string persistentDataPath;
    public static Image ADTCheckmark;
    public static Image PAUSECheckmark;
    public List<String[]> Tile_ini = new List<String[]>();
    public int GizXPixAdj = 4;
    public int GizYPixAdj = -4;
    public static bool wasPaused = false;
    public static bool dumpingEnabled = false;
    public static bool pauseToggle = false;
    public static int[] spriteBuffer;
    public static int[] backgroundBuffer;
    public Color[] flippedfirstP1;
    public Color[] flippedfirstP2;
    public Color[] flippedfirstP3;
    public Color[] flippedfirstP4;
    public Texture2D flippyP1;
    public Texture2D flippyP2;
    public Texture2D flippyP3;
    public Texture2D flippyP4;
    public Camera SpriteCamera;
    public static bool inited = false;
    public bool pauseagainnextframe = false;
    public float TXADJ = 0.0f;
    public float TYADJ = 2.5f;
    public static bool dumpFrame = false;
    public static bool dumpActive = true;
    public float dumpTimer = 0f;
    public Texture2D tempComb;
    public Texture2D todump;
    public Texture2D crop;
    public Texture2D CroppedDump;
    public float sceneTimer = 0f;
    public double PixelsSolidPercent = 1;
    public double PixelsSolid = 0;
    public Color FirstPixel;
    public bool SolidColor = false;
    public bool BetweenScenes = false;
    public TextAsset NESDB;
    public Text DEBUGTEXT;
    public Text SCENENAME;
    JSONObject pyxelJSON = new JSONObject();
    JSONObject animationsJSON = new JSONObject();
    JSONObject tilesetJSON = new JSONObject();
    JSONObject settingsJSON = new JSONObject();
    JSONObject canvasJSON = new JSONObject();
    JSONObject layersJSON = new JSONObject();
    JSONObject layer0JSON = new JSONObject();
    JSONObject tilerefsJSON = new JSONObject();
    public JSONObject[] nodeJSON = new JSONObject[960];
    List<string> pyxelFiles = new List<string>();
    List<string> pyxelNames = new List<string>();
    public static string currentRomName = "Unknown";
    public static int currentRom = 0;
    public string currentRomMD5Sum = "";
    public static List<RomInfo> romInfo;
    public static GameObject TilePrefab;
    public GameObject CombinedSpritePrefab;
    public GameObject OBJPrefab;
    public bool BABtn = false;
    public static bool audioout = false;
    public TextAsset defaultROM;
    public static bool frameskip = false;
    public static bool flip = false;
    public GameObject Display;
    public Renderer DisplayRenderer;
    public static Color[] RawScreen = new Color[256 * 240];
    public static Color[] spritetexcolorsP1 = new Color[256 * 240];
    public static Color[] spritetexcolorsP2 = new Color[256 * 240];
    public static Color[] spritetexcolorsP3 = new Color[256 * 240];
    public static Color[] spritetexcolorsP4 = new Color[256 * 240];
    public static Texture2D spritetextureP1;
    public static Texture2D spritetextureP2;
    public static Texture2D spritetextureP3;
    public static Texture2D spritetextureP4;
    public static int[] dotBufferUpdate;
    float minx = float.MaxValue;
    float miny = float.MaxValue;
    float maxx = float.MinValue;
    float maxy = float.MinValue;
    public static string newmd5;
    public static string shortMD5;
    public static string tilefilename;
    public string testmd5;
    public static int recognizedTileCount = 0;
    public GameObject SpriteCombineNode;
    public Vector3 modelPlacement = new Vector3(0.0f, -1.0f, 0.0f);
    public static GameObject[] sprite = new GameObject[64];
    public float CSPRXAdj = 0;
    public float CSPRYAdj = 0;
    public bool[] spriteIsTall = new bool[64];
    public static GameObject[] spriteTile = new GameObject[64];
    public int[] spritePal = new int[64];
    public static GameObject[] Tile = new GameObject[960];
    public static string[] PrevFrameT = new string[960];
    public static List<int> TXMove = new List<int>();
    public static List<int> TYMove = new List<int>();
    public int TXM = 0;
    public int TYM = 0;
    public static Color[,] tileColorz = new Color[962, 64];
    public static string[] tileHash = new string[960];
    public Vector3[] BGTileRawXY = new Vector3[960];
    public static List<BGTile> BGTiles = new List<BGTile>();
    public static List<CombinedSprite> CombinedSprites = new List<CombinedSprite>();
    public static List<CombinedSprite> previousFrameCombinedSprites = new List<CombinedSprite>();
    public static Texture2D[] TileTexture = new Texture2D[960];
    public static GameObject[] TileModels;
    public static GameObject Model;
    public static int[] tileint = new int[8 * 8];
    public static Color[] tileColors = new Color[8 * 8];
    public Color[] tileColorsPublic = new Color[8 * 32];
    public static Vector3 tileSpawn;
    public static Vector3[] spritePos = new Vector3[64];
    public static string[] spriteHash = new string[64];
    public static int[] cachedPos = new int[960];
    public static int[] cachedPosBuffer = new int[960];
    public static int[] TilePixelCoords = new int[32 * 30];
    public static Vector3[] TileWorldCoords = new Vector3[32 * 30];
    public static int[] TilePixelCoordsBuffer = new int[32 * 30];
    public static Vector3[] TileWorldCoordsBuffer = new Vector3[32 * 30];
    public List<string> BATCHFILE = new List<string>();
    public List<BGTile> dumpedTilez = new List<BGTile>();
    public static bool passed = false;
    public static bool enhance = true;
    public int minBGX = 0;
    public int minBGY = 0;
    public int maxBGX = 0;
    public int maxBGY = 0;
    public int frameMaxBGX = 0;
    public int frameMaxBGY = 0;
    public int exportWidth = 0;
    public int exportHeight = 0;
    public int exportedWidth = 0;
    public int exportedHeight = 0;
    public int exportTilesWide = 0;
    public int index = 0;
    public int til = 0;
    public static string rand = "";
    public int tnum = 0;
    public List<string> screenshotMD5 = new List<string>();
    public bool wasInDB = false;
    public Texture2D RawScreenTexture;
    public Texture2D BGReplaceMap;

    private Thread thread;
    public static string AppPath;
    public static string WorkingFolder;
    public static int[] main_buffer;
    public static short[] audio_shorts;
    public static bool IsPlaying = true;
    public IJoypadConnecter joy1;
    Texture2D objtexture;
    Texture2D dottexture;
    static Texture2D dumpTexture;
    static Texture2D dumpTileTexture;
    static Texture2D squareDumpTexture;
    static Texture2D tallDumpTexture;
    public bool switchingScenes = false;
    public GameObject spriteParent;
    public GameObject BGParent;
    public GameObject spritePrefab;
    public Mesh squareSprite;
    public Mesh tallSprite;
    public bool dumpMaps = false;
    public bool UploadToggle = false;
    public static FtpWebRequest request;
    public static FtpWebResponse response;
    public string username = @"KugiZuki@2depth.com";
    public string password = "200lander";
    public static int uploadCount = 0;
    public static Thread t;
    public static string usernum;
    public static string colorSumTemp;
    public static int[] pix = new int[32 * 32];
    public Texture2D tileDump;
    public static GameObject DontDestroy;
    public RenderTexture WipBGMap;
    public Texture2D[] squareSpriteTexture = new Texture2D[64];
    public Texture2D[] tallSpriteTexture = new Texture2D[64];
    public static Texture2D texture;
    public static Texture2D textureAlpha;
    public Texture2D T2D4x;
    public Texture2D T2D4xAlpha;
    public static RenderTexture texture4x;
    public static RenderTexture texture4xAlpha;
    public static Material xMat;
    public static List<Texture2D> TextureUpdateColors = new List<Texture2D>();
    public static List<String> TileTextureColorsHash = new List<String>();
    public static List<Texture2D> StockTextures = new List<Texture2D>();
    public static List<String> StockTextureHash = new List<String>();
    public static List<string> TextureUpdateHash = new List<string>();
    public static List<string> JustDumped = new List<string>();
    public static string[] CustomPNGNames;
    public static string[] StockPNGNames;
    string[] PNGHashes;
    public static bool[] hasUpdate = new bool[960];
    public static bool[] hasModelLoaded;
    public static Color[] objcolors;
    public static Color[] bgcolors;
    public static Color[] bgcolorsAlpha;
    public static Color[] ppucolors;
    public static Color[] dotcolors;
    public static string[] romlist;

    public static Board bandai;
    public static Board eprom;
    public static Board ffe;
    public static Board mmc2;
    public static Board namcot106;
    public static Board mapper000;
    public static Board mapper001;
    public static Board mapper002;
    public static Board mapper003;
    public static Board mapper004;
    public static Board mapper005;
    public static Board mapper006;
    public static Board mapper007;
    public static Board mapper008;
    public static Board mapper009;
    public static Board mapper010;
    public static Board mapper011;
    public static Board mapper012;
    public static Board mapper013;
    public static Board mapper014;
    public static Board mapper015;
    public static Board mapper016;
    public static Board mapper017;
    public static Board mapper018;
    public static Board mapper019;
    public static Board mapper020;
    public static Board mapper021;
    public static Board mapper022;
    public static Board mapper023;
    public static Board mapper024;
    public static Board mapper025;
    public static Board mapper026;
    public static Board mapper027;
    public static Board mapper028;
    public static Board mapper029;
    public static Board mapper030;
    public static Board mapper031;
    public static Board mapper032;
    public static Board mapper033;
    public static Board mapper034;
    public static Board mapper035;
    public static Board mapper036;
    public static Board mapper037;
    public static Board mapper038;
    public static Board mapper039;
    public static Board mapper040;
    public static Board mapper041;
    public static Board mapper042;
    public static Board mapper043;
    public static Board mapper044;
    public static Board mapper045;
    public static Board mapper046;
    public static Board mapper047;
    public static Board mapper048;
    public static Board mapper049;
    public static Board mapper050;
    public static Board mapper051;
    public static Board mapper052;
    public static Board mapper053;
    public static Board mapper054;
    public static Board mapper055;
    public static Board mapper056;
    public static Board mapper057;
    public static Board mapper058;
    public static Board mapper059;
    public static Board mapper060;
    public static Board mapper061;
    public static Board mapper062;
    public static Board mapper063;
    public static Board mapper064;
    public static Board mapper065;
    public static Board mapper066;
    public static Board mapper067;
    public static Board mapper068;
    public static Board mapper069;
    public static Board mapper070;
    public static Board mapper071;
    public static Board mapper072;
    public static Board mapper073;
    public static Board mapper074;
    public static Board mapper075;
    public static Board mapper076;
    public static Board mapper077;
    public static Board mapper078;
    public static Board mapper079;
    public static Board mapper080;
    public static Board mapper081;
    public static Board mapper082;
    public static Board mapper083;
    public static Board mapper084;
    public static Board mapper085;
    public static Board mapper086;
    public static Board mapper087;
    public static Board mapper088;
    public static Board mapper089;
    public static Board mapper090;
    public static Board mapper091;
    public static Board mapper092;
    public static Board mapper093;
    public static Board mapper094;
    public static Board mapper095;
    public static Board mapper096;
    public static Board mapper097;
    public static Board mapper098;
    public static Board mapper099;
    public static Board mapper100;
    public static Board mapper101;
    public static Board mapper102;
    public static Board mapper103;
    public static Board mapper104;
    public static Board mapper105;
    public static Board mapper106;
    public static Board mapper107;
    public static Board mapper108;
    public static Board mapper109;
    public static Board mapper110;
    public static Board mapper111;
    public static Board mapper112;
    public static Board mapper113;
    public static Board mapper114;
    public static Board mapper115;
    public static Board mapper116;
    public static Board mapper117;
    public static Board mapper118;
    public static Board mapper119;
    public static Board mapper120;
    public static Board mapper121;
    public static Board mapper122;
    public static Board mapper123;
    public static Board mapper124;
    public static Board mapper125;
    public static Board mapper126;
    public static Board mapper127;
    public static Board mapper128;
    public static Board mapper129;
    public static Board mapper130;
    public static Board mapper131;
    public static Board mapper132;
    public static Board mapper133;
    public static Board mapper134;
    public static Board mapper135;
    public static Board mapper136;
    public static Board mapper137;
    public static Board mapper138;
    public static Board mapper139;
    public static Board mapper140;
    public static Board mapper141;
    public static Board mapper142;
    public static Board mapper143;
    public static Board mapper144;
    public static Board mapper145;
    public static Board mapper146;
    public static Board mapper147;
    public static Board mapper148;
    public static Board mapper149;
    public static Board mapper150;
    public static Board mapper151;
    public static Board mapper152;
    public static Board mapper153;
    public static Board mapper154;
    public static Board mapper155;
    public static Board mapper156;
    public static Board mapper157;
    public static Board mapper158;
    public static Board mapper159;
    public static Board mapper160;
    public static Board mapper161;
    public static Board mapper162;
    public static Board mapper163;
    public static Board mapper164;
    public static Board mapper165;
    public static Board mapper166;
    public static Board mapper167;
    public static Board mapper168;
    public static Board mapper169;
    public static Board mapper170;
    public static Board mapper171;
    public static Board mapper172;
    public static Board mapper173;
    public static Board mapper174;
    public static Board mapper175;
    public static Board mapper176;
    public static Board mapper177;
    public static Board mapper178;
    public static Board mapper179;
    public static Board mapper180;
    public static Board mapper181;
    public static Board mapper182;
    public static Board mapper183;
    public static Board mapper184;
    public static Board mapper185;
    public static Board mapper186;
    public static Board mapper187;
    public static Board mapper188;
    public static Board mapper189;
    public static Board mapper190;
    public static Board mapper191;
    public static Board mapper192;
    public static Board mapper193;
    public static Board mapper194;
    public static Board mapper195;
    public static Board mapper196;
    public static Board mapper197;
    public static Board mapper198;
    public static Board mapper199;
    public static Board mapper200;
    public static Board mapper201;
    public static Board mapper202;
    public static Board mapper203;
    public static Board mapper204;
    public static Board mapper205;
    public static Board mapper206;
    public static Board mapper207;
    public static Board mapper208;
    public static Board mapper209;
    public static Board mapper210;
    public static Board mapper211;
    public static Board mapper212;
    public static Board mapper213;
    public static Board mapper214;
    public static Board mapper215;
    public static Board mapper216;
    public static Board mapper217;
    public static Board mapper218;
    public static Board mapper219;
    public static Board mapper220;
    public static Board mapper221;
    public static Board mapper222;
    public static Board mapper223;
    public static Board mapper224;
    public static Board mapper225;
    public static Board mapper226;
    public static Board mapper227;
    public static Board mapper228;
    public static Board mapper229;
    public static Board mapper230;
    public static Board mapper231;
    public static Board mapper232;
    public static Board mapper233;
    public static Board mapper234;
    public static Board mapper235;
    public static Board mapper236;
    public static Board mapper237;
    public static Board mapper238;
    public static Board mapper239;
    public static Board mapper240;
    public static Board mapper241;
    public static Board mapper242;
    public static Board mapper243;
    public static Board mapper244;
    public static Board mapper245;
    public static Board mapper246;
    public static Board mapper247;
    public static Board mapper248;
    public static Board mapper249;
    public static Board mapper250;
    public static Board mapper251;
    public static Board mapper252;
    public static Board mapper253;
    public static Board mapper254;
    public static Board mapper255;

    public static void TogglePlayPause(bool paused)
    {

        IsPlaying = paused;
    }

    public static void GetIsPlaying(out bool playing)
    {
        playing = IsPlaying;
    }

    public string Md5Num(byte[] bytes)
    {

        System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
        byte[] hashBytes = md5.ComputeHash(bytes);

        string hashString = "";

        for (int i = 0; i < hashBytes.Length; i++)
        {
            hashString += System.Convert.ToString(hashBytes[i], 16).PadLeft(2, '0');
        }

        return hashString.PadLeft(32, '0');
    }
    public static string colorSumSprite(Color[] colors)
    {

        colorSumTemp = "";

        for (int x = 0; x < 8; x++)
        {
            for (int y = 0; y < 8; y++)
            {

                float rVal = colors[x + (y * 8)].r;
                float gVal = colors[x + (y * 8)].g;
                float bVal = colors[x + (y * 8)].b;
                float aVal = colors[x + (y * 8)].a;
                if (x == 0 || x == 4)
                    pix[x + (y * 8)] = (int)(rVal * 256);

                if (x == 1 || x == 5)
                    pix[x + (y * 8)] = (int)(gVal * 256);

                if (x == 2 || x == 6)
                    pix[x + (y * 8)] = (int)(bVal * 256);

                if (x == 3 || x == 7)
                    pix[x + (y * 8)] = (int)(aVal * 256);

            }
        }
        colorSumTemp = GetHashCode(pix).ToString();
        return colorSumTemp;

    }
    private string GetMacAddress()
    {
        const int MIN_MAC_ADDR_LENGTH = 12;
        string macAddress = string.Empty;
        long maxSpeed = -1;

        foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
        {
            UnityEngine.Debug.Log(
                "Found MAC Address: " + nic.GetPhysicalAddress() +
                " Type: " + nic.NetworkInterfaceType);

            string tempMac = nic.GetPhysicalAddress().ToString();
            if (nic.Speed > maxSpeed &&
                !string.IsNullOrEmpty(tempMac) &&
                tempMac.Length >= MIN_MAC_ADDR_LENGTH)
            {
                UnityEngine.Debug.Log("New Max Speed = " + nic.Speed + ", MAC: " + tempMac);
                maxSpeed = nic.Speed;
                macAddress = tempMac;
            }
        }

        return macAddress;
    }

    public string setScript = "http://www.morethanagame.xyz/transl8.php?";

    public void SetValues(string Language, string Text, string Translation)
    {
        string url = string.Format("{0}Game={1}&Language={2}&Text={3}&Translation={4}&User={5}", setScript, currentRomMD5Sum, Language, Text, Translation, usernum);

        WWW www = new WWW(url);
    }

    public string checkScript = "http://www.morethanagame.xyz/check4.php?";

    public IEnumerator checkValues(string Language, string Text, string Translation)
    {
        string url = string.Format("{0}Game={1}&Language={2}&Text={3}&Translation={4}&User={5}", checkScript, currentRomMD5Sum, Language, Text, Translation, usernum);

        WWW www = new WWW(url);

        yield return www;

        if (www.text.Contains("Needs Data!@#$") == true)
        {
            UnityEngine.Debug.Log("Needs Data.. Translating");
            StartCoroutine(Translate());

        } else
        {
            UnityEngine.Debug.Log("Translation : " + www.text);
            translatedSentence = www.text;
            if (RxScriptInit.subsLanguage != "NONE")
            {
                if (RxScriptInit.subsLanguage == "FRENCH")
                {
                    TranslationTextBox.text = translatedSentence;
                }
                if (RxScriptInit.subsLanguage == "ENGLISH")
                {
                    TranslationTextBox.text = completeSentence;
                }
            }
            if (RxScriptInit.TTSLanguage != "NONE")
            {
                if (RxScriptInit.TTSLanguage == "FRENCH")
                {

                    tts.theVoice.speak("<voice required=\"Language=C0C\">" + translatedSentence + "</voice>");

                }
                if (RxScriptInit.TTSLanguage == "ENGLISH")
                {
                    tts.theVoice.speak("<voice required=\"Language=409\">" + completeSentence + "</voice>");
                }
            }
        }

    }

    public static string colorSumScene(Color[] colors)
    {

        colorSumTemp = "";
        int[] hashing = new int[colors.Length];

        for (int x = 25; x < 232; x++)
        {
            for (int y = 25; y < 215; y++)
            {

                float rVal = colors[x + (y * 8)].r;
                float gVal = colors[x + (y * 8)].g;
                float bVal = colors[x + (y * 8)].b;
                float aVal = colors[x + (y * 8)].a;
                if (x < colors.Length / 3)
                    hashing[x + (y * 8)] = (int)(rVal * 256);

                if (x > colors.Length / 3 && x < (colors.Length / 3) * 2)
                    hashing[x + (y * 8)] = (int)(gVal * 256);

                if (x > (colors.Length / 3) * 2)
                    hashing[x + (y * 8)] = (int)(bVal * 256);

            }
        }
        colorSumTemp = GetHashCode(hashing).ToString();
        return colorSumTemp;

    }

    public static string colorSumTile(int[] tuint)
    {

        colorSumTemp = "";

        colorSumTemp = GetHashCodeTile(tuint).ToString();
        return colorSumTemp;

    }
    public static string shortFileName(string fn)
    {

        colorSumTemp = "";

        colorSumTemp = GetHashCodeFileName(fn);
        return colorSumTemp;

    }
    static int GetHashCode(int[] values)
    {
        int result = 0;
        int shift = 0;
        for (int i = 0; i < values.Length; i++)
        {
            shift = (shift + 11) % 21;
            result ^= (values[i] + 1024) << shift;
        }
        return result;
    }
    static string GetHashCodeFileName(string values)
    {
        int result = 0;
        int shift = 0;
        foreach (char c in values)
        {
            shift = (shift + 11) % 21;
            result ^= ((char.ToUpper(c) - 64) + 1024) << shift;
        }
        return result.ToString();
    }
    static int GetHashCodeTile(int[] values)
    {
        int result = 0;
        int shift = 0;
        for (int i = 0; i < values.Length; i++)
        {
            shift = (shift + 11) % 21;
            result ^= ((int)values[i] + 1024) << shift;
        }
        return result;
    }
    static bool GetBit(byte b, int bitNumber)
    {
        return (b & (1 << bitNumber)) != 0;
    }
    static int GetHashCodeTileColors(Color[] pixels)
    {
        int result = 0;
        int shift = 0;
        for (int i = 0; i < pixels.Length; i++)
        {
            if (pixels[i].a > 0.2f)
            {
                shift = (shift + 11) % 21;
                result ^= ((int)pixels[i].r + (int)pixels[i].g + (int)pixels[i].b + 1024) << shift;
            }
        }
        return result;
    }

    public static void AbortThreads()
    {

    }
    void OnApplicationQuit()
    {
        if (t != null)
        {
            StopUploadThread();
        }
        MyNes.NesEmu.ShutDown();
    }

    public void OnScriptLoaded()
    {
        newTexture = new Texture2D(32, 32, TextureFormat.RGBA32, false);
        //actionCam = GameObject.Find("Action Camera").GetComponent<ActionCam>();
        actionTransform = GameObject.Find("ActionTarget").GetComponent<Transform>();
        RefreshButton = GameObject.Find("LoadBtn").GetComponent<RefreshButton>();
        DumpButton = GameObject.Find("DumpBtn").GetComponent<DumpButton>();
        WorkingGraphic = GameObject.Find("WorkingGraphic").GetComponent<RawImage>();
        DumpGraphicText = GameObject.Find("DumpGraphicText").GetComponent<Text>();
        LoadGraphicText = GameObject.Find("LoadGraphicText").GetComponent<Text>();
        todump = new Texture2D(32, 32);
        crop = new Texture2D(32, 32);
        CroppedDump = new Texture2D(32, 32);
        CustomBackgroundGO = GameObject.Find("CustomBackground");
        CustomBackground = CustomBackgroundGO.GetComponent<Renderer>().material;
        SkyBGCam = GameObject.Find("SkyCamera").GetComponent<Camera>();
        tts = gameObject.AddComponent<WindowsVoice>();
        TranslationTextBox = GameObject.Find("Translation").GetComponent<Text>();
        MainMenu = GameObject.Find("MainMenuCanvas").GetComponent<Canvas>();
        SpriteCamera = GameObject.Find("SpriteCamera").GetComponent<Camera>();
        NESDB = Resources.Load("NESDatabase") as TextAsset;
        DEBUGTEXT = GameObject.Find("DEBUGTEXT").GetComponent<Text>();
        SCENENAME = GameObject.Find("SCENENAME").GetComponent<Text>();
        NewTextPrefab = Resources.Load("NewTextPrefab") as GameObject;
        CombinedSpritePrefab = Resources.Load("CombinedSpritePrefab") as GameObject;
        OBJPrefab = Resources.Load("OBJPrefab") as GameObject;
        defaultROM = Resources.Load("Game") as TextAsset;
        Display = GameObject.Find("NewCurvedScreen");
        DisplayRenderer = Display.GetComponent<Renderer>();
        SpriteCombineNode = GameObject.Find("SpriteCombineNode");

        spriteParent = GameObject.Find("Sprites");
        spritePrefab = Resources.Load("spritePrefab") as GameObject;
        BGParent = GameObject.Find("BGTiles");
        ADTCheckmark = GameObject.Find("ADTCheckmark").GetComponent<Image>();
        PAUSECheckmark = GameObject.Find("PAUSECheckmark").GetComponent<Image>();
        MainMenu.enabled = false;
        flippyP1 = new Texture2D(256, 240);
        flippyP2 = new Texture2D(256, 240);
        flippyP3 = new Texture2D(256, 240);
        flippyP4 = new Texture2D(256, 240);
        //spritetextureP1 = new Texture2D(256, 240);
        //spritetextureP2 = new Texture2D(256, 240);
        //spritetextureP3 = new Texture2D(256, 240);
        //spritetextureP4 = new Texture2D(256, 240);
        persistentDataPath = Application.persistentDataPath;
        AppPath = Application.persistentDataPath;
        WorkingFolder = Application.persistentDataPath;
        Debug.Log("AppPath = " + AppPath);
        if (Directory.Exists(AppPath + "/Roms/") == false)
        {
            System.IO.Directory.CreateDirectory(AppPath + "/Roms/");
            System.IO.Directory.CreateDirectory(AppPath + "/Sav/");
        }
        if (File.Exists(AppPath + "/Roms/Game.nes") == false)
        {
            byte[] rom = defaultROM.bytes;
            File.WriteAllBytes(AppPath + "/Roms/Game.nes", rom);
        }
        RawScreenTexture = new Texture2D(256, 240);

        AppPath = Application.persistentDataPath;
        WorkingFolder = Application.persistentDataPath;
        usernum = GetMacAddress();
        UnityEngine.Debug.Log("User Number = " + usernum);
        tileDump = new Texture2D(64, 64);
        if (Application.platform == RuntimePlatform.WindowsEditor || Application.platform == RuntimePlatform.WindowsPlayer)
        {
            persistentDataPath = Application.dataPath + "/../";
        }
        else
        {
            persistentDataPath = Application.persistentDataPath;
        }

        if (DontDestroy == null)
        {
            DontDestroy = Instantiate(Resources.Load("DontDestroyOnLoad", typeof(GameObject))) as GameObject;
            DontDestroy.name = "DontDestroyOnLoad";
        }
        else
        {
            DontDestroy = GameObject.Find("DontDestroyOnLoad");
        }
        currentRom = EngineReload.currentRom;
        if (dumpMaps == true)
        {
            WipBGMap = new RenderTexture(4000, 4000, 0, RenderTextureFormat.ARGB32);
            WipBGMap.Create();
        }
        romInfo = new List<RomInfo>();
        if (Directory.Exists(persistentDataPath + "/Graphics/") == true)
        {
            Directory.Move(persistentDataPath + "/Graphics/", persistentDataPath + "/Enhancements/");
        }
        Application.targetFrameRate = 60;
        TilePrefab = Instantiate(Resources.Load("TilePrefab", typeof(GameObject))) as GameObject;

        DirectoryInfo rdir = new DirectoryInfo(persistentDataPath + "/Roms/");
        FileInfo[] roms = rdir.GetFiles("*.nes");
        romlist = new string[roms.Length];
        int romcount = 0;
        foreach (FileInfo r in roms)
        {

            romlist[romcount++] = r.Name;
        }
        romcount = 0;
        TilePrefab.transform.position = new Vector3(100, 100, 100);
        Texture2D UnFlipped = new Texture2D(8, 8, TextureFormat.ARGB32, false);
        dumpTexture = new Texture2D(256 * 8, 240 * 8, TextureFormat.RGBA32, false);
        BGReplaceMap = new Texture2D(32, 32, TextureFormat.RGBA32, false);
        dumpTileTexture = new Texture2D(8 * 8, 8 * 8, TextureFormat.RGBA32, false);
        tallDumpTexture = new Texture2D(32, 64, TextureFormat.RGBA32, false);
        objtexture = new Texture2D(256, 240, TextureFormat.ARGB32, false);
        texture = new Texture2D(256, 240, TextureFormat.ARGB32, false);
        textureAlpha = new Texture2D(256, 240, TextureFormat.ARGB32, false);
        myTexture2D = new Texture2D(32, 32);
        texture.filterMode = FilterMode.Point;
        texture4x = new RenderTexture((int)(256 * 4), (int)(240 * 4), 16, RenderTextureFormat.ARGB32);
        texture4xAlpha = new RenderTexture((int)(256 * 4), (int)(240 * 4), 16, RenderTextureFormat.ARGB32);
        dottexture = new Texture2D(256, 240, TextureFormat.ARGB32, false);
        String NESDBString = NESDB.text;
        string[] fLines = Regex.Split(NESDBString, "\n");
        foreach (string line in fLines)
        {
            string[] nameMd5 = Regex.Split(line, ">");
            string p1 = nameMd5[0].ToString().TrimEnd(System.Environment.NewLine.ToCharArray());
            string p2 = nameMd5[1].ToString().TrimEnd(System.Environment.NewLine.ToCharArray());
            romInfo.Add(new RomInfo(p1, p2));
        }
        for (int i = 0; i < sprite.Length; i++)
        {
            spritePos[i] = Vector3.zero;
            sprite[i] = GameObject.Instantiate(spritePrefab, Vector3.zero, Quaternion.identity) as GameObject;
            spriteTile[i] = sprite[i].transform.Find("mesh").gameObject;

            sprite[i].transform.SetParent(spriteParent.transform, false);
        }
        Vector3[] verts = new Vector3[4];

        verts[0] = new Vector3(0, 1, 0);
        verts[1] = new Vector3(1, 1, 0);
        verts[2] = new Vector3(0, 0, 0);
        verts[3] = new Vector3(1, 0, 0);

        int[] tris = new int[6] {
            0, 1, 2,
            1, 3, 2
        };

        Vector2[] uvs = new Vector2[4];

        uvs[0] = new Vector2(0, 1);
        uvs[1] = new Vector2(1, 1);
        uvs[2] = new Vector2(0, 0);
        uvs[3] = new Vector2(1, 0);

        Mesh mesh = new Mesh();

        mesh.vertices = verts;
        mesh.triangles = tris;
        mesh.uv = uvs;

        mesh.RecalculateNormals();
        squareSprite = mesh;

        verts = new Vector3[4];

        verts[0] = new Vector3(0, 2, 0);
        verts[1] = new Vector3(1, 2, 0);
        verts[2] = new Vector3(0, 0, 0);
        verts[3] = new Vector3(1, 0, 0);

        tris = new int[6] {
            0, 1, 2,
            1, 3, 2
        };

        uvs = new Vector2[4];

        uvs[0] = new Vector2(0, 1);
        uvs[1] = new Vector2(1, 1);
        uvs[2] = new Vector2(0, 0);
        uvs[3] = new Vector2(1, 0);

        Mesh meshtall = new Mesh();

        meshtall.vertices = verts;
        meshtall.triangles = tris;
        meshtall.uv = uvs;

        meshtall.RecalculateNormals();
        tallSprite = meshtall;
        flippedfirstP1 = new Color[256 * 240];
        flippedfirstP2 = new Color[256 * 240];
        flippedfirstP3 = new Color[256 * 240];
        flippedfirstP4 = new Color[256 * 240];
        StartRom();

    }

    public void StartRom()
    {
        xMat = new Material(Shader.Find("Pixel Art Filters/4xBRZ"));
        RxScriptInit.dumpingEnabled = false;
        if (romlist.Length > 0)
        {


            for (int i = 0; i < sprite.Length; i++)
            {
                spritePos[i] = Vector3.zero;
                squareSpriteTexture[i] = null;
                squareSpriteTexture[i] = new Texture2D(8, 8, TextureFormat.ARGB32, false);

                squareSpriteTexture[i].filterMode = FilterMode.Point;
                squareSpriteTexture[i].wrapMode = TextureWrapMode.Clamp;
                spriteTile[i].GetComponent<Renderer>().enabled = false;
                tallSpriteTexture[i] = null;
                tallSpriteTexture[i] = new Texture2D(8, 16, TextureFormat.ARGB32, false);
                tallSpriteTexture[i].filterMode = FilterMode.Point;
                tallSpriteTexture[i].wrapMode = TextureWrapMode.Clamp;

            }
            FileStream rfs = new FileStream(System.IO.Path.Combine(persistentDataPath + "/Roms/", romlist[currentRom]), FileMode.Open, FileAccess.Read);
            UnityEngine.Debug.Log(persistentDataPath + "/Roms/" + romlist[currentRom]);
            byte[] romfile = new byte[rfs.Length];
            rfs.Read(romfile, 0, (int)rfs.Length);
            currentRomMD5Sum = Hash.Md5Sum(romfile);
            bool md5Match = false;
            for (int ri = 0; ri < romInfo.Count; ri++)
            {
                if (romInfo[ri].MD5Sum == currentRomMD5Sum)
                {
                    currentRomName = romInfo[ri].RomName;
                    UnityEngine.Debug.Log("Autodetected : " + currentRomName);
                    md5Match = true;
                }
            }

            if (md5Match == false)
            {

                currentRomName = romlist[currentRom];
                UnityEngine.Debug.Log("Could not recognize : " + currentRomName + " with it's MD5Sum : " + currentRomMD5Sum);
            }
            if (romlist[currentRom] != currentRomName)
            {
                if (Directory.Exists(persistentDataPath + "/Enhancements/" + romlist[currentRom] + "/") == true)
                {
                    Directory.Move(persistentDataPath + "/Enhancements/" + romlist[currentRom] + "/", persistentDataPath + "/Enhancements/" + currentRomName + "/");
                }
            }
            if (Directory.Exists(persistentDataPath + "/Enhancements/" + currentRomName + "/Customs/") == true)
            {
                Directory.Move(persistentDataPath + "/Enhancements/" + currentRomName + "/Customs/", persistentDataPath + "/Enhancements/" + currentRomName + "/-MyPackage-/");
            }
            if (File.Exists(persistentDataPath + "/Enhancements/" + currentRomName + "/") == false)
            {
                System.IO.Directory.CreateDirectory(persistentDataPath + "/Enhancements/" + currentRomName + "/");
                System.IO.Directory.CreateDirectory(persistentDataPath + "/Enhancements/" + currentRomName + "/-MyPackage-/");
                System.IO.Directory.CreateDirectory(persistentDataPath + "/Enhancements/" + currentRomName + "/InProgress/");
            }
            if (File.Exists(persistentDataPath + "/Enhancements/" + currentRomName + "/InProgress/") == false)
            {
                System.IO.Directory.CreateDirectory(persistentDataPath + "/Enhancements/" + currentRomName + "/InProgress/");
            }
            if (File.Exists(persistentDataPath + "/Enhancements/" + currentRomName + "/Sprites/") == true)
            {
                System.IO.Directory.Move(persistentDataPath + "/Enhancements/" + currentRomName + "/Sprites/", persistentDataPath + "/Enhancements/" + currentRomName);
            }
            if (File.Exists(persistentDataPath + "/Enhancements/" + currentRomName + "/-MyPackage-/Sprites/") == true)
            {
                System.IO.Directory.Move(persistentDataPath + "/Enhancements/" + currentRomName + "/-MyPackage-/Sprites/", persistentDataPath + "/Enhancements/" + currentRomName + "/-MyPackage-/");
            }

            CustomPNGNames = null;
            PNGHashes = null;
            hasUpdate = null;
            bgcolors = new Color[256 * 240];
            bgcolorsAlpha = new Color[256 * 240];
            objcolors = new Color[256 * 240];
            TextureUpdateColors.Clear();
            TextureUpdateHash.Clear();
            StockTextures.Clear();
            StockTextureHash.Clear();
            hasModelLoaded = null;

            for (int x = 0; x < 32; x++)
            {
                for (int y = 0; y < 30; y++)
                {
                    Destroy(Tile[(uint)(x + (y * 32))]);
                    TileTexture[(uint)(x + (y * 32))] = null;

                }
            }

            for (int x = 0; x < Tile.Length; x++)
            {
                if (Tile[x] == null)
                {
                    Tile[x] = GameObject.Instantiate(TilePrefab, tileSpawn, Quaternion.identity) as GameObject;
                    if (Tile[x].transform.Find("DemoPlane") != null)
                    {
                        Tile[x].transform.Find("DemoPlane").GetComponent<Renderer>().enabled = false;
                    }
                    Tile[x].transform.localScale = new Vector3(1.0f, 1.0f, 1.0f);
                    Tile[x].name = "Non-Used Tile";
                    Tile[x].tag = "Tile";
                    Tile[x].transform.SetParent(BGParent.transform, false);
                }
            }

            DirectoryInfo stockdir = new DirectoryInfo(persistentDataPath + "/Enhancements/" + currentRomName + "/");
            FileInfo[] stockinfo = stockdir.GetFiles("*.png");
            if (stockinfo.Length > 0)
            {

                int count = 0;
                foreach (FileInfo s in stockinfo)
                {

                    string[] split = s.Name.Split("_"[0]);

                    StockTextureHash.Add(split[0]);

                    count++;
                }
            }
            if (File.Exists(persistentDataPath + "/Enhancements/" + currentRomName + "/-MyPackage-/" + "Alphabet.ini") == true)
            {
                string[] lines = File.ReadAllLines(persistentDataPath + "/Enhancements/" + currentRomName + "/-MyPackage-/" + "Alphabet.ini");
                foreach (string line in lines)
                {
                    string[] sinfo = Regex.Split(line, "=");
                    alphabet.Add(new AlphabetIndex(sinfo[0], sinfo[1]));
                }
            }

            CustomPNGNames = new string[0];
            PNGHashes = new string[0];
            hasModelLoaded = new bool[0];
            TileModels = new GameObject[0];
            foreach (string d in Directory.GetDirectories(persistentDataPath + "/Enhancements/" + currentRomName + "/-MyPackage-/"))
            {
                string directory = d.Replace(persistentDataPath, "").Replace("/Enhancements/" + currentRomName + "/-MyPackage-/", "");
                Debug.Log("Reading Directory : " + directory);
                DirectoryInfo dir = new DirectoryInfo(persistentDataPath + "/Enhancements/" + currentRomName + "/-MyPackage-/" + directory + "/");
                FileInfo[] info = dir.GetFiles("*.png");

                if (info.Length > 0)
                {
                    Array.Resize(ref CustomPNGNames, (int)(CustomPNGNames.Length + info.Length));
                    Array.Resize(ref PNGHashes, (int)(PNGHashes.Length + info.Length));
                    Array.Resize(ref hasModelLoaded, (int)(hasModelLoaded.Length + info.Length));
                    Array.Resize(ref TileModels, (int)(TileModels.Length + info.Length));
                    int count = 0;

                    if (File.Exists(persistentDataPath + "/Enhancements/" + currentRomName + "/-MyPackage-/" + directory + "/" + directory + ".png"))
                    {
                        foreach (FileInfo f in info)
                        {

                            string split = f.Name.Replace("_.png", "").Replace(".png", "");
                            if (File.Exists(persistentDataPath + "/Enhancements/" + currentRomName + "/-MyPackage-/" + directory + "/" + directory + "-Model/" + directory + ".obj") == true)
                            {
                                TileModels[count] = GameObject.Instantiate(OBJPrefab, new Vector3(-1, 1, 0), Quaternion.identity) as GameObject;

                                TileModels[count].SendMessage("LoadOBJ", "file:///" + persistentDataPath + "/Enhancements/" + currentRomName + "/-MyPackage-/" + directory + "/" + directory + "-Model/" + directory + ".obj");

                                UnityEngine.Debug.Log("File :" + persistentDataPath + "/Enhancements/" + currentRomName + "/-MyPackage-/" + directory + "/" + directory + "-Model/" + directory + ".obj");

                                hasModelLoaded[count] = true;
                            }

                            FileStream fs = new FileStream(persistentDataPath + "/Enhancements/" + currentRomName + "/-MyPackage-/" + directory + "/" + directory + ".png", FileMode.Open, FileAccess.Read);
                            byte[] imageData = new byte[fs.Length];
                            fs.Read(imageData, 0, (int)fs.Length);

                            Texture2D Loading = new Texture2D(64, 64, TextureFormat.ARGB32, false);

                            Loading.LoadImage(imageData);
                            if (f.Name.Contains("Spr") == true)
                            {
                                Loading = MirrorTexture(Loading, false, true);
                            }
                            TextureUpdateColors.Add(Loading);
                            TextureUpdateHash.Add(split);

                            CustomPNGNames[count] = directory + ".png";
                            PNGHashes[count] = split;
                            count++;
                        }
                    }
                }
            }
            /* DirectoryInfo dumpdir = new DirectoryInfo(persistentDataPath + "/Enhancements/" + currentRomName + "/");
             FileInfo[] dumpinfo = dumpdir.GetFiles("*.png");
             if (dumpinfo.Length > 0)
             {
                 int i = 0;
                 StockPNGNames = new string[dumpinfo.Length];
                 foreach (FileInfo f in dumpinfo)
                 {
                     string split = f.Name.Replace(".png", "");
                     TileTextureColorsHash.Add(split);
                     StockPNGNames[i] = f.Name;
                 }
             }*/

            joy1 = new JoypadGameControllerConnecter();
            NesEmu.SetupControllersP1(joy1);
            NesEmu.Initialize();

            NesEmu.Boards = new List<Board>();
            bandai = new Bandai();
            ffe = new FFE();
            mmc2 = new MMC2();
            namcot106 = new Namcot106();
            mapper000 = new Mapper000();
            mapper001 = new Mapper001();
            mapper002 = new Mapper002();
            mapper003 = new Mapper003();
            mapper004 = new Mapper004();
            mapper005 = new Mapper005();
            mapper006 = new Mapper006();
            mapper007 = new Mapper007();
            mapper008 = new Mapper008();
            mapper009 = new Mapper009();
            mapper010 = new Mapper010();
            mapper011 = new Mapper011();
            mapper013 = new Mapper013();
            mapper015 = new Mapper015();
            mapper016 = new Mapper016();
            mapper017 = new Mapper017();
            mapper018 = new Mapper018();
            mapper019 = new Mapper019();
            mapper021 = new Mapper021();
            mapper022 = new Mapper022();
            mapper023 = new Mapper023();
            mapper024 = new Mapper024();
            mapper025 = new Mapper025();
            mapper026 = new Mapper026();
            mapper032 = new Mapper032();
            mapper033 = new Mapper033();
            mapper034 = new Mapper034();
            mapper041 = new Mapper041();
            mapper042 = new Mapper042();
            mapper044 = new Mapper044();
            mapper045 = new Mapper045();
            mapper046 = new Mapper046();
            mapper047 = new Mapper047();
            mapper048 = new Mapper048();
            mapper049 = new Mapper049();
            mapper050 = new Mapper050();
            mapper051 = new Mapper051();
            mapper052 = new Mapper052();
            mapper053 = new Mapper053();
            mapper056 = new Mapper056();
            mapper057 = new Mapper057();
            mapper058 = new Mapper058();
            mapper060 = new Mapper060();
            mapper061 = new Mapper061();
            mapper062 = new Mapper062();
            mapper064 = new Mapper064();
            mapper065 = new Mapper065();
            mapper066 = new Mapper066();
            mapper067 = new Mapper067();
            mapper068 = new Mapper068();
            mapper069 = new Mapper069();
            mapper070 = new Mapper070();
            mapper071 = new Mapper071();
            mapper072 = new Mapper072();
            mapper073 = new Mapper073();
            mapper074 = new Mapper074();
            mapper075 = new Mapper075();
            mapper076 = new Mapper076();
            mapper077 = new Mapper077();
            mapper078 = new Mapper078();
            mapper079 = new Mapper079();
            mapper080 = new Mapper080();
            mapper082 = new Mapper082();
            mapper085 = new Mapper085();
            mapper086 = new Mapper086();
            mapper087 = new Mapper087();
            mapper088 = new Mapper088();
            mapper089 = new Mapper089();
            mapper090 = new Mapper090();
            mapper091 = new Mapper091();
            mapper092 = new Mapper092();
            mapper093 = new Mapper093();
            mapper094 = new Mapper094();
            mapper095 = new Mapper095();
            mapper096 = new Mapper096();
            mapper097 = new Mapper097();
            mapper105 = new Mapper105();
            mapper107 = new Mapper107();
            mapper112 = new Mapper112();
            mapper113 = new Mapper113();
            mapper115 = new Mapper115();
            mapper118 = new Mapper118();
            mapper119 = new Mapper119();
            mapper133 = new Mapper133();
            mapper140 = new Mapper140();
            mapper152 = new Mapper152();

            mapper154 = new Mapper154();

            mapper163 = new Mapper163();
            mapper164 = new Mapper164();
            mapper165 = new Mapper165();

            mapper180 = new Mapper180();

            mapper182 = new Mapper182();

            mapper184 = new Mapper184();
            mapper185 = new Mapper185();

            mapper189 = new Mapper189();

            mapper191 = new Mapper191();
            mapper192 = new Mapper192();
            mapper193 = new Mapper193();
            mapper194 = new Mapper194();

            mapper200 = new Mapper200();
            mapper201 = new Mapper201();
            mapper202 = new Mapper202();
            mapper203 = new Mapper203();
            mapper204 = new Mapper204();
            mapper205 = new Mapper205();
            mapper206 = new Mapper206();
            mapper207 = new Mapper207();

            mapper209 = new Mapper209();

            mapper212 = new Mapper212();
            mapper213 = new Mapper213();
            mapper214 = new Mapper214();

            mapper216 = new Mapper216();

            mapper222 = new Mapper222();

            mapper225 = new Mapper225();
            mapper226 = new Mapper226();
            mapper227 = new Mapper227();
            mapper228 = new Mapper228();
            mapper229 = new Mapper229();
            mapper230 = new Mapper230();
            mapper231 = new Mapper231();
            mapper232 = new Mapper232();
            mapper233 = new Mapper233();

            mapper240 = new Mapper240();

            mapper242 = new Mapper242();
            mapper243 = new Mapper243();

            mapper245 = new Mapper245();
            mapper246 = new Mapper246();

            mapper255 = new Mapper255();

            NesEmu.Boards.Add(bandai);
            NesEmu.Boards.Add(ffe);
            NesEmu.Boards.Add(mmc2);
            NesEmu.Boards.Add(namcot106);
            NesEmu.Boards.Add(mapper000);
            NesEmu.Boards.Add(mapper001);
            NesEmu.Boards.Add(mapper002);
            NesEmu.Boards.Add(mapper003);
            NesEmu.Boards.Add(mapper004);
            NesEmu.Boards.Add(mapper005);
            NesEmu.Boards.Add(mapper006);
            NesEmu.Boards.Add(mapper007);
            NesEmu.Boards.Add(mapper008);
            NesEmu.Boards.Add(mapper009);
            NesEmu.Boards.Add(mapper010);
            NesEmu.Boards.Add(mapper011);

            NesEmu.Boards.Add(mapper013);

            NesEmu.Boards.Add(mapper015);
            NesEmu.Boards.Add(mapper016);
            NesEmu.Boards.Add(mapper017);
            NesEmu.Boards.Add(mapper018);

            NesEmu.Boards.Add(mapper021);
            NesEmu.Boards.Add(mapper022);
            NesEmu.Boards.Add(mapper023);
            NesEmu.Boards.Add(mapper024);
            NesEmu.Boards.Add(mapper025);
            NesEmu.Boards.Add(mapper026);

            NesEmu.Boards.Add(mapper032);
            NesEmu.Boards.Add(mapper033);
            NesEmu.Boards.Add(mapper034);

            NesEmu.Boards.Add(mapper041);
            NesEmu.Boards.Add(mapper042);

            NesEmu.Boards.Add(mapper044);
            NesEmu.Boards.Add(mapper045);
            NesEmu.Boards.Add(mapper046);
            NesEmu.Boards.Add(mapper047);
            NesEmu.Boards.Add(mapper048);
            NesEmu.Boards.Add(mapper049);
            NesEmu.Boards.Add(mapper050);
            NesEmu.Boards.Add(mapper051);
            NesEmu.Boards.Add(mapper052);
            NesEmu.Boards.Add(mapper053);

            NesEmu.Boards.Add(mapper056);
            NesEmu.Boards.Add(mapper057);
            NesEmu.Boards.Add(mapper058);

            NesEmu.Boards.Add(mapper060);
            NesEmu.Boards.Add(mapper061);
            NesEmu.Boards.Add(mapper062);

            NesEmu.Boards.Add(mapper064);
            NesEmu.Boards.Add(mapper065);
            NesEmu.Boards.Add(mapper066);
            NesEmu.Boards.Add(mapper067);
            NesEmu.Boards.Add(mapper068);
            NesEmu.Boards.Add(mapper069);
            NesEmu.Boards.Add(mapper070);
            NesEmu.Boards.Add(mapper071);
            NesEmu.Boards.Add(mapper072);
            NesEmu.Boards.Add(mapper073);
            NesEmu.Boards.Add(mapper074);
            NesEmu.Boards.Add(mapper075);
            NesEmu.Boards.Add(mapper076);
            NesEmu.Boards.Add(mapper077);
            NesEmu.Boards.Add(mapper078);
            NesEmu.Boards.Add(mapper079);
            NesEmu.Boards.Add(mapper080);

            NesEmu.Boards.Add(mapper082);

            NesEmu.Boards.Add(mapper085);
            NesEmu.Boards.Add(mapper086);
            NesEmu.Boards.Add(mapper087);
            NesEmu.Boards.Add(mapper088);
            NesEmu.Boards.Add(mapper089);
            NesEmu.Boards.Add(mapper090);
            NesEmu.Boards.Add(mapper091);
            NesEmu.Boards.Add(mapper092);
            NesEmu.Boards.Add(mapper093);
            NesEmu.Boards.Add(mapper094);
            NesEmu.Boards.Add(mapper095);
            NesEmu.Boards.Add(mapper096);
            NesEmu.Boards.Add(mapper097);

            NesEmu.Boards.Add(mapper105);

            NesEmu.Boards.Add(mapper107);

            NesEmu.Boards.Add(mapper112);
            NesEmu.Boards.Add(mapper113);

            NesEmu.Boards.Add(mapper115);

            NesEmu.Boards.Add(mapper118);
            NesEmu.Boards.Add(mapper119);

            NesEmu.Boards.Add(mapper133);

            NesEmu.Boards.Add(mapper140);

            NesEmu.Boards.Add(mapper152);

            NesEmu.Boards.Add(mapper154);

            NesEmu.Boards.Add(mapper163);
            NesEmu.Boards.Add(mapper164);
            NesEmu.Boards.Add(mapper165);

            NesEmu.Boards.Add(mapper180);

            NesEmu.Boards.Add(mapper182);

            NesEmu.Boards.Add(mapper184);
            NesEmu.Boards.Add(mapper185);

            NesEmu.Boards.Add(mapper189);

            NesEmu.Boards.Add(mapper191);
            NesEmu.Boards.Add(mapper192);
            NesEmu.Boards.Add(mapper193);
            NesEmu.Boards.Add(mapper194);

            NesEmu.Boards.Add(mapper200);
            NesEmu.Boards.Add(mapper201);
            NesEmu.Boards.Add(mapper202);
            NesEmu.Boards.Add(mapper203);
            NesEmu.Boards.Add(mapper204);
            NesEmu.Boards.Add(mapper205);
            NesEmu.Boards.Add(mapper206);
            NesEmu.Boards.Add(mapper207);

            NesEmu.Boards.Add(mapper212);
            NesEmu.Boards.Add(mapper213);
            NesEmu.Boards.Add(mapper214);

            NesEmu.Boards.Add(mapper216);

            NesEmu.Boards.Add(mapper222);

            NesEmu.Boards.Add(mapper225);
            NesEmu.Boards.Add(mapper226);
            NesEmu.Boards.Add(mapper227);
            NesEmu.Boards.Add(mapper228);
            NesEmu.Boards.Add(mapper229);
            NesEmu.Boards.Add(mapper230);
            NesEmu.Boards.Add(mapper231);
            NesEmu.Boards.Add(mapper232);
            NesEmu.Boards.Add(mapper233);

            NesEmu.Boards.Add(mapper240);

            NesEmu.Boards.Add(mapper242);
            NesEmu.Boards.Add(mapper243);

            NesEmu.Boards.Add(mapper245);
            NesEmu.Boards.Add(mapper246);

            NesEmu.Boards.Add(mapper255);

            foreach (Board brd in NesEmu.Boards)
            {
                Tracer.WriteLine("Board added: " + brd.Name + " [ Mapper " + brd.MapperNumber + "]");
            }

            bool success = false;
            NesEmu.SoundEnabled = true;
            NesEmu.SetupRenderingMethods(SubmitVideoFrame, SubmitAudioFrame, TogglePlayPause, GetIsPlaying);

            NesEmu.LoadGame(persistentDataPath + "/Roms/" + romlist[currentRom], out success, true);
            Debug.Log("LoadGame Success = " + success);
            RxScriptInit.dumpingEnabled = false;
            //GameObject.Find("MidiPlayer").AddComponent<UnityMidi.MidiPlayer>();
            inited = true;

        }
        else
        {
            DEBUGTEXT.text = ("NO ROMS IN : " + persistentDataPath + "/Roms/");

        }

    }

    void RefreshGFX()
    {
        UnityEngine.Debug.Log("Refreshing Enhanced Graphics!");
        foreach (Transform everything in spriteParent.transform)
        {
            if (everything != spriteParent.transform)
            {
                DestroyImmediate(everything.gameObject);
            }
        }
        foreach (GameObject everythingelse in GameObject.FindGameObjectsWithTag("Tile"))
        {
            DestroyImmediate(everythingelse);
        }
        if (romlist != null && romlist.Length > 0)
        {
            for (int i = 0; i < sprite.Length; i++)
            {
                spritePos[i] = Vector3.zero;
                squareSpriteTexture[i] = null;
                squareSpriteTexture[i] = new Texture2D(8, 8, TextureFormat.ARGB32, false);
                squareSpriteTexture[i].wrapMode = TextureWrapMode.Clamp;
                if (spriteTile[i] == null)
                {

                    spritePos[i] = Vector3.zero;
                    sprite[i] = GameObject.Instantiate(spritePrefab, Vector3.zero, Quaternion.identity) as GameObject;
                    spriteTile[i] = sprite[i].transform.Find("mesh").gameObject;

                    sprite[i].transform.SetParent(spriteParent.transform, false);

                }
                if (spriteTile[i].GetComponent<Renderer>() == null)
                {
                    spriteTile[i].AddComponent<Renderer>();
                }
                if (spriteTile[i].GetComponent<Renderer>().material != null && spriteTile[i].GetComponent<Renderer>().material.mainTexture != null)
                {
                    spriteTile[i].GetComponent<Renderer>().material.mainTexture.filterMode = FilterMode.Point;
                    spriteTile[i].GetComponent<Renderer>().material.mainTexture.wrapMode = TextureWrapMode.Clamp;
                    spriteTile[i].GetComponent<Renderer>().enabled = false;
                }
                tallSpriteTexture[i] = null;
                tallSpriteTexture[i] = new Texture2D(8, 16, TextureFormat.ARGB32, false);
                tallSpriteTexture[i].wrapMode = TextureWrapMode.Clamp;
            }

            if (romlist[currentRom] != currentRomName)
            {
                if (Directory.Exists(persistentDataPath + "/Enhancements/" + romlist[currentRom] + "/") == true)
                {
                    Directory.Move(persistentDataPath + "/Enhancements/" + romlist[currentRom] + "/", persistentDataPath + "/Enhancements/" + currentRomName + "/");
                }
            }
            if (Directory.Exists(persistentDataPath + "/Enhancements/" + currentRomName + "/Customs/") == true)
            {
                Directory.Move(persistentDataPath + "/Enhancements/" + currentRomName + "/Customs/", persistentDataPath + "/Enhancements/" + currentRomName + "/-MyPackage-/");
            }
            if (File.Exists(persistentDataPath + "/Enhancements/" + currentRomName + "/") == false)
            {
                System.IO.Directory.CreateDirectory(persistentDataPath + "/Enhancements/" + currentRomName + "/");
                System.IO.Directory.CreateDirectory(persistentDataPath + "/Enhancements/" + currentRomName + "/-MyPackage-/");
                System.IO.Directory.CreateDirectory(persistentDataPath + "/Enhancements/" + currentRomName + "/InProgress/");
            }
            if (File.Exists(persistentDataPath + "/Enhancements/" + currentRomName + "/InProgress/") == false)
            {
                System.IO.Directory.CreateDirectory(persistentDataPath + "/Enhancements/" + currentRomName + "/InProgress/");
            }
            if (File.Exists(persistentDataPath + "/Enhancements/" + currentRomName + "/Sprites/") == true)
            {
                System.IO.Directory.Move(persistentDataPath + "/Enhancements/" + currentRomName + "/Sprites/", persistentDataPath + "/Enhancements/" + currentRomName);
            }
            if (File.Exists(persistentDataPath + "/Enhancements/" + currentRomName + "/-MyPackage-/Sprites/") == true)
            {
                System.IO.Directory.Move(persistentDataPath + "/Enhancements/" + currentRomName + "/-MyPackage-/Sprites/", persistentDataPath + "/Enhancements/" + currentRomName + "/-MyPackage-/");
            }

            TextureUpdateColors = new List<Texture2D>();
            TextureUpdateHash = new List<string>();
            StockTextures = new List<Texture2D>();
            StockTextureHash = new List<string>();

            for (int x = 0; x < 32; x++)
            {
                for (int y = 0; y < 30; y++)
                {
                    TileTexture[(uint)(x + (y * 32))] = null;

                }
            }
            for (int x = 0; x < Tile.Length; x++)
            {

                Tile[x] = null;
                if (TilePrefab == null)
                {
                    TilePrefab = Instantiate(Resources.Load("TilePrefab", typeof(GameObject))) as GameObject;
                }
                Tile[x] = GameObject.Instantiate(TilePrefab, tileSpawn, Quaternion.identity) as GameObject;
                Tile[x].transform.Find("DemoPlane").GetComponent<Renderer>().enabled = false;
                Tile[x].transform.localScale = new Vector3(1.0f, 1.0f, 1.0f);
                Tile[x].name = "Non-Used Tile";
                Tile[x].transform.SetParent(BGParent.transform, false);
                Tile[x].tag = "Tile";

            }
            DirectoryInfo stockdir = new DirectoryInfo(persistentDataPath + "/Enhancements/" + currentRomName + "/");
            FileInfo[] stockinfo = stockdir.GetFiles("*.png");
            if (stockinfo.Length > 0)
            {
                int count = 0;
                foreach (FileInfo s in stockinfo)
                {

                    string[] split = s.Name.Split("_"[0]);
                    StockTextureHash.Add(split[0]);
                    count++;
                }
            }
            CustomPNGNames = new string[0];
            PNGHashes = new string[0];
            hasModelLoaded = new bool[0];
            TileModels = new GameObject[0];
            foreach (string d in Directory.GetDirectories(persistentDataPath + "/Enhancements/" + currentRomName + "/-MyPackage-/"))
            {
                string directory = d.Replace(persistentDataPath, "").Replace("/Enhancements/" + currentRomName + "/-MyPackage-/", "");
                Debug.Log("Reading Directory : " + directory);
                DirectoryInfo dir = new DirectoryInfo(persistentDataPath + "/Enhancements/" + currentRomName + "/-MyPackage-/" + directory + "/");
                FileInfo[] info = dir.GetFiles("*.png");
                if (info.Length > 0)
                {


                    Array.Resize(ref CustomPNGNames, (int)(CustomPNGNames.Length + info.Length));
                    Array.Resize(ref PNGHashes, (int)(PNGHashes.Length + info.Length));
                    Array.Resize(ref hasModelLoaded, (int)(hasModelLoaded.Length + info.Length));
                    Array.Resize(ref TileModels, (int)(TileModels.Length + info.Length));
                    int count = 0;
                    foreach (FileInfo f in info)
                    {

                        if (File.Exists(persistentDataPath + "/Enhancements/" + currentRomName + "/-MyPackage-/" + directory + "/" + directory + ".png")) {
                            string split = f.Name.Replace("_.png", "").Replace(".png", "");

                            if (File.Exists(persistentDataPath + "/Enhancements/" + currentRomName + "/-MyPackage-/" + directory + "/" + directory + "-Model/" + directory + ".obj") == true)
                            {
                                TileModels[count] = GameObject.Instantiate(OBJPrefab, new Vector3(-1, 1, 0), Quaternion.identity) as GameObject;

                                TileModels[count].SendMessage("LoadOBJ", "file:///" + persistentDataPath + "/Enhancements/" + currentRomName + "/-MyPackage-/" + directory + "/" + directory + "-Model/" + directory + ".obj");

                                UnityEngine.Debug.Log("File :" + persistentDataPath + "/Enhancements/" + currentRomName + "/-MyPackage-/" + directory + "/" + directory + "-Model/" + directory + ".obj");

                                hasModelLoaded[count] = true;
                            }

                            FileStream fs = new FileStream(persistentDataPath + "/Enhancements/" + currentRomName + "/-MyPackage-/" + directory + "/" + directory + ".png", FileMode.Open, FileAccess.Read);
                            byte[] imageData = new byte[fs.Length];
                            fs.Read(imageData, 0, (int)fs.Length);

                            Texture2D Loading = new Texture2D(32, 32, TextureFormat.ARGB32, false);

                            Loading.LoadImage(imageData);
                            if (f.Name.Contains("Spr") == true)
                            {
                                Loading = MirrorTexture(Loading, false, true);
                            }
                            TextureUpdateColors.Add(Loading);
                            TextureUpdateHash.Add(split);

                            CustomPNGNames[count] = directory + ".png";
                            PNGHashes[count] = split;
                            count++;
                        }
                    }
                }
            }
            DirectoryInfo dumpdir = new DirectoryInfo(persistentDataPath + "/Enhancements/" + currentRomName + "/");
            FileInfo[] dumpinfo = dumpdir.GetFiles("*.png");
            if (dumpinfo.Length > 0)
            {
                int i = 0;
                StockPNGNames = new string[dumpinfo.Length];
                foreach (FileInfo f in dumpinfo)
                {
                    string[] split = f.Name.Split("_"[0]);
                    TileTextureColorsHash.Add(split[0]);
                    StockPNGNames[i] = f.Name;
                }
            }

        }
        else
        {
            UnityEngine.Debug.Log("NO ROMS IN : " + persistentDataPath + "/Roms/");
        }
    }

    public void UpdateTexture()
    {

        tilesChanged = 0;
        tilesCounted = 0;
        int i = 0;
        PixelsSolid = 0;
        SolidColor = true;
        BetweenScenes = false;
        int clearIndex = 0;
        int clearCount = 0;
        TXMove.Clear();
        TYMove.Clear();
        /*if (MyNes.NesEmu.backgroundBufferfb[i] == SkyColor && knockOutSky == true)
        {
            DisplayRenderer.material.SetColor("_KeyColor", IntToColor(SkyColor));
        }*/
        i = 0;
        MyNes.NesEmu.PAUSED = true;
        for (int fy = 0; fy < 240; fy++)
        {
            for (int fx = 0; fx < 256; fx++)
            {
                if (fx >= 1 && fx < 248 && fy >= 1 && fy < 232)
                {

                    if (MyNes.NesEmu.dotBufferfb[i] == 0x009566)
                    {
                        processAdjacentTiles((fx - (fx % 8)) / 8, (fy - (fy % 8)) / 8, i, fx * 0.125f, fy * 0.125f);

                    }

                }

                i++;
            }
        }
        i = 0;
        for (int fy = 0; fy < 240; fy++)
        {
            for (int fx = 0; fx < 256; fx++)
            {

                bgcolors[fx + (fy * 256)] = IntToColor(MyNes.NesEmu.backgroundBufferfb[i]);
                //if (MyNes.NesEmu.backgroundBufferfb[i] == SkyColor){
                //    bgcolors[fx + (fy * 256)] = Color.clear;
                //}// else
                //{
                //    bgcolorsAlpha[fx + (fy * 256)] = Color.white;
                //}
                /*
                spritetexcolorsP1[fx + (fy * 256)] = IntToColor(MyNes.NesEmu.spriteBufferfbP1[i]);
                spritetexcolorsP2[fx + (fy * 256)] = IntToColor(MyNes.NesEmu.spriteBufferfbP2[i]);
                spritetexcolorsP3[fx + (fy * 256)] = IntToColor(MyNes.NesEmu.spriteBufferfbP3[i]);
                spritetexcolorsP4[fx + (fy * 256)] = IntToColor(MyNes.NesEmu.spriteBufferfbP4[i]);
                */
                /*if (bgcolors[fx + (fy * 256)] == bgcolors[120 + (128 * 256)])
                {
                    PixelsSolid += 1;

                }*/
                i++;
            }
        }
        i = 0;
        for (int fy = 0; fy < 240; fy++)
        {
            for (int fx = 0; fx < 256; fx++)
            {
                if (fx >= 1 && fx < 247 && fy >= 1 && fy < 231)
        {

            if (MyNes.NesEmu.dotBufferfb[i] == 0x009566)
            {
                processTile((fx - (fx % 8)) / 8, (fy - (fy % 8)) / 8, i, fx * 0.125f, fy * 0.125f);
                //dotCount++;
            }

        }
                i++;
    }
}
        MyNes.NesEmu.PAUSED = RxScriptInit.wasPaused;
        //if (knockOutSky == true)
        //{
        SkyBGCam.backgroundColor = IntToColor(SkyColor);
            //} else
            //{
              //  SkyBGCam.backgroundColor = Color.black;
            //}

            mostCommonTile = tileHash.ToArray().GroupBy(item => item).OrderByDescending(g => g.Count()).Select(g => g.Key).First();
           /*  TXM = TXMove.ToArray().GroupBy(item => item).OrderByDescending(g => g.Count()).Select(g => g.Key).First();

            TYM = TYMove.ToArray().GroupBy(item => item).OrderByDescending(g => g.Count()).Select(g => g.Key).First();
            if (TXM == -1)
            {
                totalX -= 8;
            }
            if (TXM == +1)
            {
                totalX += 8;
            }
            if (TYM == -1)
            {
                totalY -= 8;
            }
            if (TYM == +1)
            {
                totalY += 8;
            }
            fineTotalX = (totalX + prvTotalX) / 2;
            fineTotalY = (totalY + prvTotalY) / 2;
            DEBUGTEXT.text = "X : " + totalX + " / Y : " + totalY;*/
            
			
            int index = 0;

            index++;
            texture.SetPixels(bgcolors);
            //textureAlpha.SetPixels(bgcolorsAlpha);
            //textureAlpha.Apply();
            /*spritetextureP1.SetPixels(spritetexcolorsP1);
            spritetextureP1.Apply();
			spritetextureP2.SetPixels(spritetexcolorsP2);
            spritetextureP2.Apply();
			spritetextureP3.SetPixels(spritetexcolorsP3);
            spritetextureP3.Apply();
			spritetextureP4.SetPixels(spritetexcolorsP4);
            spritetextureP4.Apply();*/
            texture.filterMode = FilterMode.Point;
            
            if (pauseagainnextframe == true)
            {
                MyNes.NesEmu.PAUSED = true;
            }

       
    }
    public void processAdjacentTiles(int x, int y, int location, float worldx, float worldy)
    {
        int foundMatch = 0;
        modelPlacement = Vector3.zero;
        if (x < minBGY)
        {
            minBGY = x;
        }
        if (y < minBGX)
        {
            minBGX = y;
        }
        if (x > maxBGY)
        {
            maxBGY = x;
        }
        if (y > maxBGX)
        {
            maxBGX = y;
        }
        
        bool disableDemoPlane = false;
        if (Tile[(uint)(x + (y * 32))].transform.Find("DemoPlane") != null)
        {
            Tile[(uint)(x + (y * 32))].transform.Find("DemoPlane").transform.localPosition = Vector3.zero;
        }
        bool found = false;
        wasInDB = false;
        newmd5 = null;
        shortMD5 = null;
        
        BGTileRawXY[(uint)(x + (y * 32))] = new Vector3(x, y, 0.0025f);

        for (int blx = 0; blx < 8; blx++)
        {
            for (int bly = 0; bly < 8; bly++)
            {

                tileint[blx + (bly * 8)] = MyNes.NesEmu.backgroundBufferfb[location + blx + (bly * 256)];

            }
        }

        tileHash[(uint)(x + (y * 32))] = (colorSumTile(tileint));

        PrevFrameT[(uint)(x + (y * 32))] = tileHash[(uint)(x + (y * 32))];

    }
    public void processTile(int x, int y, int location, float worldx, float worldy)
    {
        if (x < 32 && y < 30 && location < 256 * 240) { 
        int foundMatch = 0;
        modelPlacement = Vector3.zero;
        if (x < minBGY)
        {
            minBGY = x;
        }
        if (y < minBGX)
        {
            minBGX = y;
        }
        if (x > maxBGY)
        {
            maxBGY = x;
        }
        if (y > maxBGX)
        {
            maxBGX = y;
        }
        bool justShortMD5 = false;
        if (x > 1)
        {
            left = PrevFrameT[(uint)((x - 1) + (y * 32))];
        }
        else
        {
            left = "null";
            justShortMD5 = true;
        }
        if (x < 30)
        {
            right = PrevFrameT[(uint)((x + 1) + (y * 32))];
        }
        else
        {
            right = "null";
            justShortMD5 = true;
        }
        if (y > 1)
        {
            up = PrevFrameT[(uint)(x + ((y - 1) * 32))];
        }
        else
        {
            up = "null";
            justShortMD5 = true;
        }
        if (y < 28)
        {
            down = PrevFrameT[(uint)(x + ((y + 1) * 32))];
        }
        else
        {
            down = "null";
            justShortMD5 = true;
        }
        if (x > 1 && y > 1)
        {
            upleft = PrevFrameT[(uint)((x - 1) + ((y - 1) * 32))];
        }
        else
        {
            upleft = "null";
            justShortMD5 = true;
        }
        if (x < 30 && y > 0)
        {
            upright = PrevFrameT[(uint)((x + 1) + ((y - 1) * 32))];
        }
        else
        {
            upright = "null";
            justShortMD5 = true;
        }
        if (x > 1 && y > 1)
        {
            downleft = PrevFrameT[(uint)((x - 1) + ((y + 1) * 32))];
        }
        else
        {
            downleft = "null";
            justShortMD5 = true;
        }
        if (x < 30 && y < 28)
        {
            downright = PrevFrameT[(uint)((x + 1) + ((y + 1) * 32))];
        }
        else
        {
            downright = "null";
            justShortMD5 = true;
        }
        if (RxScriptInit.dumpConnected == true)
        {
            justShortMD5 = true;
        }

        bool disableDemoPlane = false;
        if (Tile[(uint)(x + (y * 32))].transform.Find("DemoPlane") != null)
        {
            Tile[(uint)(x + (y * 32))].transform.Find("DemoPlane").transform.localPosition = Vector3.zero;
        }
        bool found = false;
        wasInDB = false;
        newmd5 = null;
        shortMD5 = null;
        BGTileRawXY[(uint)(x + (y * 32))] = new Vector3(x, y, 0.0025f);

        for (int blx = 0; blx < 8; blx++)
        {
            for (int bly = 0; bly < 8; bly++)
            {

                tileint[blx + (bly * 8)] = MyNes.NesEmu.backgroundBufferfb[location + blx + (bly * 256)];

            }
        }

        tileSpawn = new Vector3(worldx + RxScriptInit.OffsetX, -worldy + RxScriptInit.OffsetY, 1);
        /*
        BGTile BGdbTile = BGTiles.Find(t => (t.TileInt == tileint));
        
        if (BGdbTile != null)
            {
                if (BGdbTile.MD5Sum == null)
                {

                    wasInDB = false;
                    
                    shortMD5 = colorSumTile(tileint);

                    newmd5 = shortMD5;
                    tileHash[(uint)(x + (y * 32))] = newmd5;
                    //UnityEngine.Debug.Log(MD5bounds.x + " / " + MD5bounds.y);
                }
                else
                {
                    shortMD5 = BGdbTile.MD5Sum;
                newmd5 = shortMD5;

                wasInDB = true;
                    tileHash[(uint)(x + (y * 32))] = newmd5;
                }



            if (BGdbTile.TileTexture != null)
            {
                if (Tile[(uint)(x + (y * 32))] != null)
                {
                    if (Tile[(uint)(x + (y * 32))].transform.childCount > 0)
                    {
                        Tile[(uint)(x + (y * 32))].transform.Find("DemoPlane").GetComponent<Renderer>().enabled = true;
                        Tile[(uint)(x + (y * 32))].transform.Find("DemoPlane").GetComponent<Renderer>().material.mainTexture = BGdbTile.TileTexture;
                        Tile[(uint)(x + (y * 32))].transform.Find("DemoPlane").GetComponent<Renderer>().material.mainTexture.filterMode = FilterMode.Point;
                        Tile[(uint)(x + (y * 32))].transform.Find("DemoPlane").GetComponent<Renderer>().material.mainTexture.wrapMode = TextureWrapMode.Clamp;
                        Tile[(uint)(x + (y * 32))].transform.Find("DemoPlane").transform.localScale = new Vector3(BGdbTile.TileTexture.width / 64, BGdbTile.TileTexture.height / 64, 1.0f);
                        /*if (BGdbTile.TileTexture.width > 65 && BGdbTile.TileTexture.height > 65)
                        {
                            Tile[(uint)(x + (y * 32))].transform.Find("DemoPlane").transform.localPosition = new Vector3(((BGdbTile.TileTexture.width / 64) / 2) - 0.5f, ((BGdbTile.TileTexture.height / 64) / 2) + 0.5f, 0);
                        }
                        else
                        {
                            Tile[(uint)(x + (y * 32))].transform.Find("DemoPlane").transform.localPosition = new Vector3(((BGdbTile.TileTexture.width / 64) / 2) + 0.5f, ((BGdbTile.TileTexture.height / 64) / 2) - 0.5f, 0);

                        }
					}
				}
			}
			
                        Tile[(uint)(x + (y * 32))].name = shortMD5;

                        if (BGdbTile.Model != null)
                        {
if (Tile[(uint)(x + (y * 32))] != null)
                {
                    
                            if (Tile[(uint)(x + (y * 32))].transform.Find(newmd5 + "Model") == null)
                            {
                                Model = GameObject.Instantiate(BGdbTile.Model, tileSpawn, Quaternion.identity) as GameObject;
                                foreach (Renderer rend in Model.GetComponentsInChildren<Renderer>())
                                {
                                    if (rend.gameObject.name != "DemoPlane")
                                    {
                                        rend.enabled = true;
                                    }
                                    else
                                    {
                                        rend.enabled = false;
                                    }
                                }
                                Model.transform.localScale = new Vector3(-1f, -1f, 1f);
                                Model.transform.localPosition = new Vector3(0f, 0f, 0f);
                                Model.name = newmd5 + "Model";
                                Model.transform.parent = Tile[(uint)(x + (y * 32))].transform;
                                Tile[(uint)(x + (y * 32))].transform.Find("DemoPlane").GetComponent<Renderer>().enabled = false;
                            }
                            foreach (Transform child in Tile[(uint)(x + (y * 32))].transform)
                            {
                                if (child.gameObject.name != newmd5 + "Model" && child.gameObject.name != "DemoPlane")
                                {
                                    Destroy(child.gameObject);
                                }

                            }
						
			}
                        }

                        else
                        {
                            Tile[(uint)(x + (y * 32))].transform.Find("DemoPlane").GetComponent<Renderer>().enabled = true;
                        }

                        foreach (Transform model in Tile[(uint)(x + (y * 32))].transform)
                        {
                            if (model.gameObject.name == newmd5 + "Model")
                            {
                                model.transform.localPosition = modelPlacement;
                            }
                        }
                    


                
				
            } else
        {*/
        wasInDB = false;
        shortMD5 = tileHash[(uint)(x + (y * 32))];
        //MD5bounds = new Vector3((int)(((prvTotalX + ((x*8)%32) / 8)) % 4), ((((int)(prvTotalY + ((y*8)%32) / 8)) % 4)));
        //newmd5 = shortMD5 + "-" + MD5bounds.x + "-" + MD5bounds.y;
        newmd5 = shortFileName(shortMD5 + "_" + up + "_" + left + "_" + right + "_" + down + "_" + upleft + "_" + upright + "_" + downleft + "_" + downright);
        //tileHash[(uint)(x + (y * 32))] = newmd5;

        //}
        MD5bounds = new Vector2((int)(((4 + (prvTotalX - (prvTotalX % 8)) / 8)) + (x)), ((int)(((4 + ((prvTotalY - (prvTotalY % 8)) / 8)) - (y)))));
        tilefilename = newmd5;


        /*if (newmd5 == mostCommonTile)
        {
            knockOutSky = true;
            for (int c = 0; c < tileint.Length; c++)
            {
                if (tileint[c] != tileint[0])
                {
                    knockOutSky = false;
                }
            }
            if (knockOutSky == true)
            {
                SkyColor = tileint[0];
            }
        }
        */
        if (Tile[(uint)(x + (y * 32))] != null)
        {

            Tile[(uint)(x + (y * 32))].transform.position = tileSpawn;
        }
        /*
        if (newmd5 == mostCommonTile)
        {
            knockOutSky = true;
            for (int c = 0; c < tileint.Length; c++)
            {
                if (tileint[c] != tileint[0])
                {
                    knockOutSky = false;
                }
            }
            if (knockOutSky == true)
            {
                SkyColor = tileint[0];
            }
        }*/



        //MD5bounds = new Vector3((int)(((prvTotalX + ((x*8)%32) / 8)) % 4), ((((int)(prvTotalY + ((y*8)%32) / 8)) % 4)));
        //newmd5 = shortMD5 + "-" + MD5bounds.x + "-" + MD5bounds.y;

        //tileHash[(uint)(x + (y * 32))] = newmd5;
        //UnityEngine.Debug.Log(MD5bounds.x + " / " + MD5bounds.y);
        foreach (Transform child in Tile[(uint)(x + (y * 32))].transform)
        {

            if (child.gameObject.name != "DemoPlane")
            {
                Destroy(child.gameObject);
            }
        }
        if (dumpFrame == true)
        {
            tileColors = new Color[8 * 8];
            for (int blx = 0; blx < 8; blx++)
            {
                for (int bly = 0; bly < 8; bly++)
                {

                    tileColors[blx + (bly * 8)] = IntToColor(MyNes.NesEmu.backgroundBufferfb[location + blx + (bly * 256)]);
                    /*if (tileint[blx + (bly * 8)] == SkyColor && knockOutSky == true)
                    {
                        tileColors[blx + (bly * 8)] = Color.clear;
                    }*/
                }
            }
        }
        passed = false;
        if (TextureUpdateHash.Count > 0)
        {
            for (int t = 0; t < TextureUpdateHash.Count; t++)
            {
                //dirSplit = TextureUpdateHash[t].Split('_');
                //if (dirSplit.Length == 5)
                //{
                //if (dirSplit[0] == shortMD5 || dirSplit[0] == "null" && dirSplit[1] == up || dirSplit[1] == "null" && dirSplit[2] == left || dirSplit[2] == "null" && dirSplit[3] == right || dirSplit[3] == "null" && dirSplit[4] == down || dirSplit[4] == "null")
                if (TextureUpdateHash[t] == shortMD5)
                { // + "_" + up + "_" + left + "_" + right + "_" + down;
                    passed = true;
                    foundMatch = t;

                    //}
                }
            }
            for (int t = 0; t < TextureUpdateHash.Count; t++)
            {
                if (TextureUpdateHash[t] == newmd5)
                { // + "_" + up + "_" + left + "_" + right + "_" + down;
                    passed = true;
                    foundMatch = t;

                    //}
                }
            }
        }



        tileSpawn = new Vector3(worldx + RxScriptInit.OffsetX, -worldy + RxScriptInit.OffsetY, 1);

        if (passed == false && Tile[(uint)(x + (y * 32))] != null && Tile[(uint)(x + (y * 32))].transform.Find("DemoPlane") != null)
        {
            Tile[(uint)(x + (y * 32))].transform.Find("DemoPlane").GetComponent<Renderer>().enabled = true;
        }

        if (passed == true)
        {
            for (int blx = 0; blx < 8; blx++)
            {
                for (int bly = 0; bly < 8; bly++)
                {
                    if (location + blx + (bly * 256) < 256 * 240)
                    {
                        bgcolors[location + blx + (bly * 256)] = Color.clear;
                    }
                }
            }
            if (TileTexture[(uint)(x + (y * 32))] == null)
            {
                TileTexture[(uint)(x + (y * 32))] = new Texture2D(32, 32);

            }
            if (Tile[(uint)(x + (y * 32))].name != newmd5)
            {

                Tile[(uint)(x + (y * 32))].name = newmd5;
                ///tileHash[(uint)(x + (y * 32))] = newmd5;

                recognizedTileCount++;

                if (enhance == true)
                {



                    found = true;
                    recognizedTileCount++;
                    TileTexture[(uint)(x + (y * 32))] = (TextureUpdateColors[foundMatch]);
                    Tile[(uint)(x + (y * 32))].transform.Find("DemoPlane").GetComponent<Renderer>().material.mainTexture = TileTexture[(uint)(x + (y * 32))];
                    Tile[(uint)(x + (y * 32))].transform.Find("DemoPlane").GetComponent<Renderer>().material.mainTexture.wrapMode = TextureWrapMode.Clamp;
                    Tile[(uint)(x + (y * 32))].transform.Find("DemoPlane").transform.localScale = new Vector3(TileTexture[(uint)(x + (y * 32))].width / 64, TileTexture[(uint)(x + (y * 32))].height / 64, 1.0f);
                    /*
                    if (TileTexture[(uint)(x + (y * 32))].width > 65 && TileTexture[(uint)(x + (y * 32))].height > 65)
                    {
                        Tile[(uint)(x + (y * 32))].transform.Find("DemoPlane").transform.localPosition = new Vector3(((TileTexture[(uint)(x + (y * 32))].width / 64) / 2) - 0.5f, ((TileTexture[(uint)(x + (y * 32))].height / 64) / 2) + 0.5f, 0);
                    }
                    else
                    {
                        Tile[(uint)(x + (y * 32))].transform.Find("DemoPlane").transform.localPosition = new Vector3(((TileTexture[(uint)(x + (y * 32))].width / 64) / 2) + 0.5f, ((TileTexture[(uint)(x + (y * 32))].height / 64) / 2) - 0.5f, 0);

                    }*/
                    if (hasModelLoaded[foundMatch] == true)
                    {

                        disableDemoPlane = true;
                        if (Tile[(uint)(x + (y * 32))].transform.Find(newmd5 + "Model") == null)
                        {
                            Model = GameObject.Instantiate(TileModels[foundMatch], tileSpawn, Quaternion.identity) as GameObject;
                            foreach (Renderer rend in Model.GetComponentsInChildren<Renderer>())
                            {
                                if (rend.gameObject.name != "DemoPlane")
                                {
                                    rend.enabled = true;
                                }
                                else
                                {
                                    rend.enabled = false;
                                }
                            }
                            Model.transform.localScale = new Vector3(-1f, -1f, 1f);
                            Model.transform.localPosition = new Vector3(0f, 0f, 0f);
                            Model.name = newmd5 + "Model";

                                Model.transform.SetParent(Tile[(uint)(x + (y * 32))].transform, false);
                            Tile[(uint)(x + (y * 32))].transform.Find("DemoPlane").GetComponent<Renderer>().enabled = false;

                            //BGTiles.Add(new BGTile(tileint, tileColors, newmd5, TextureUpdateColors[foundMatch], TileModels[foundMatch]));

                        }
                        foreach (Transform child in Tile[(uint)(x + (y * 32))].transform)
                        {
                            if (child.gameObject.name != newmd5 + "Model" && child.gameObject.name != "DemoPlane")
                            {
                                Destroy(child.gameObject);
                            }

                        }

                    }
                    else
                    {
                        //BGTiles.Add(new BGTile(tileint, tileColors, newmd5, TextureUpdateColors[foundMatch], null));

                        Tile[(uint)(x + (y * 32))].transform.Find("DemoPlane").GetComponent<Renderer>().enabled = true;
                        foreach (Transform child in Tile[(uint)(x + (y * 32))].transform)
                        {

                            if (child.gameObject.name != newmd5 + "Model" && child.gameObject.name != "DemoPlane")
                            {
                                Destroy(child.gameObject);
                            }
                        }
                        if (Tile[(uint)(x + (y * 32))].transform.Find("DemoPlane") != null)
                        {
                            Tile[(uint)(x + (y * 32))].transform.Find("DemoPlane").GetComponent<Renderer>().enabled = true;
                            Tile[(uint)(x + (y * 32))].transform.Find("DemoPlane").GetComponent<Renderer>().material.mainTexture = TileTexture[(uint)(x + (y * 32))];
                            Tile[(uint)(x + (y * 32))].transform.Find("DemoPlane").GetComponent<Renderer>().material.mainTexture.wrapMode = TextureWrapMode.Clamp;
                            //Tile[(uint)(x + (y * 32))].transform.Find("DemoPlane").GetComponent<Renderer>().material.mainTexture.filterMode = FilterMode.Point;
                        }
                    }
                }

            }
        }
        else
        {
            Tile[(uint)(x + (y * 32))].name = newmd5;
            foreach (Transform child in Tile[(uint)(x + (y * 32))].transform)
            {
                if (child.gameObject.name != newmd5 + "Model" && child.gameObject.name != "DemoPlane")
                {
                    Destroy(child.gameObject);
                }
                Tile[(uint)(x + (y * 32))].transform.Find("DemoPlane").GetComponent<Renderer>().enabled = false;
            }



        }



        Tile[(uint)(x + (y * 32))].transform.position = tileSpawn;
        foreach (Transform model in Tile[(uint)(x + (y * 32))].transform)
        {
            if (model.gameObject.name == newmd5 + "Model")
            {
                model.transform.localPosition = modelPlacement;
            }
        }



        if (newmd5 == WorkingGFXFile && clickedFrame == true)
        {
            for (int blx = 0; blx < 8; blx++)
            {
                for (int bly = 0; bly < 8; bly++)
                {

                    tileColors[blx + (bly * 8)] = IntToColor(MyNes.NesEmu.backgroundBufferfb[location + blx + (bly * 256)]);

                }
            }
            if (WorkingTexture == null)
            {
                WorkingTexture = new Texture2D(64, 64);
            }
            WorkingTexture.Resize(64, 64);
            WorkingTexture.SetPixels(resizePixels(tileColors, 8, 8, 64, 64));
            WorkingTexture = MirrorTexture(WorkingTexture, false, true);
            WorkingTexture.Apply();

        }



        if (Tile[(uint)(x + (y * 32))].transform.parent != BGParent.transform)
        {
            Tile[(uint)(x + (y * 32))].transform.SetParent(BGParent.transform, false);

        }
        Tile[(uint)(x + (y * 32))].tag = "Tile";

        if (dumpFrame == true)
        {
                int[] t_int = new int[8 * 8];
                Array.Copy(tileint, t_int, tileint.Length);
            for (int blx = 0; blx < 8; blx++)
            {
                for (int bly = 0; bly < 8; bly++)
                {

                    tileColors[blx + (bly * 8)] = IntToColor(MyNes.NesEmu.backgroundBufferfb[location + blx + (bly * 256)]);

                }
            }
            Texture2D MemTile = new Texture2D(64, 64);
            MemTile.SetPixels(resizePixels(tileColors, 8, 8, 64, 64));
            MemTile.Apply();
            if (justShortMD5 == false)
            {
                dumpedTilez.Add(new BGTile(t_int, tileColors, newmd5, MemTile, null));
            }
            else
            {
                dumpedTilez.Add(new BGTile(t_int, tileColors, shortMD5, MemTile, null));
            }

        }
            

    }



        /*
if (Tile[(uint)((x) + (y * 32))].name != mostCommonTile)
{
    tilesCounted++;
    if (Tile[(uint)((x) + (y * 32))].name == PrevFrameT[(uint)((x) + (y * 32))])
    {
        TXMove.Add(0);
        TYMove.Add(0);
    } else
    {
        tilesChanged++;

    if (Tile[(uint)((x - 1) + (y * 32))].name != PrevFrameT[(uint)((x) + (y * 32))] && PrevFrameT[(uint)((x - 1) + (y * 32))] == newmd5)
    {
        TXMove.Add(-1);
    }
    if (Tile[(uint)((x + 1) + (y * 32))].name != PrevFrameT[(uint)((x) + (y * 32))] && PrevFrameT[(uint)((x + 1) + (y * 32))] == newmd5)
    {
        TXMove.Add(+1);
    }
    if (Tile[(uint)(x + ((y - 1) * 32))].name != PrevFrameT[(uint)(x + ((y) * 32))] && PrevFrameT[(uint)(x + ((y - 1) * 32))] == newmd5)
    {
        TYMove.Add(-1);
    }
    if (Tile[(uint)(x + ((y + 1) * 32))].name != PrevFrameT[(uint)(x + ((y) * 32))] && PrevFrameT[(uint)(x + ((y + 1) * 32))] == newmd5)
    {
        TYMove.Add(+1);
    }
    }
}*/
        //PrevFrameT[(uint)(x + (y * 32))] = shortMD5;

    }

    public void NewLetters(){
		foreach (GameObject nL in newLettersOnScreen.ToArray()){
				newLettersOnScreen.Remove(nL);
				DestroyImmediate(nL);
		}
		for (int si = 0; si < Tile.Length; si++)
		{

			for (int sl = 0; sl < alphabet.Count; sl++)
			{
				if (Tile[si].name == alphabet[sl].MD5Sum)
				{
					if (alphabet[sl].Text == " "){
						Space = Tile[si];
					}
				}
			}
		}
		for (int i = 0; i < Tile.Length; i++)
            {

                for (int l = 0; l < alphabet.Count; l++)
                {
                    if (Tile[i].name == alphabet[l].MD5Sum)
                    {
						if (alphabet[l].Text == " "){
							Space = Tile[i];
						}
					
                        OST += alphabet[l].Text;
                    }
					if (i != 0 && i % 32 == 0)
                    {
                        OST += Environment.NewLine;
                    }
                }
			}
			if (previousOST != OST){
			for (int i = 0; i < Tile.Length; i++)
            {

                for (int l = 0; l < alphabet.Count; l++)
                {
                    if (Tile[i].name == alphabet[l].MD5Sum)
                    {
						
						GameObject NewTextLetter = GameObject.Instantiate(NewTextPrefab, Vector3.zero, Quaternion.identity) as GameObject;
						NewTextLetter.transform.position = Tile[i].transform.position + NewFontOffset;
						NewTextLetter.GetComponent<TextMeshPro>().text = alphabet[l].Text;
						newLettersOnScreen.Add(NewTextLetter);
                        
                    }
					if (i != 0 && i % 32 == 0)
                    {
                       
                    }
                }
			}
			previousOST = OST;
			}
			for (int i2 = 0; i2 < Tile.Length; i2++)
			{

				for (int l2 = 0; l2 < alphabet.Count; l2++)
				{
					if (Tile[i2].name == alphabet[l2].MD5Sum)
					{
						GameObject phil = GameObject.Instantiate(Space, Tile[i2].transform.position + NewFontBGOffset, Quaternion.identity) as GameObject;
					newLettersOnScreen.Add(phil);
					}
				}
			}
			
	}
    public void SpeakText()
    {
		
        RecientlySpoken.Clear();
        List<string> toSay = new List<string>();
        OST = "";

        if (alphabet.Count > 0)
        {
            
			for (int i = 0; i < Tile.Length; i++)
            {

                for (int l = 0; l < alphabet.Count; l++)
                {
                    if (Tile[i].name == alphabet[l].MD5Sum)
                    {
                        OST += alphabet[l].Text;
                    }
					if (i != 0 && i % 32 == 0)
                    {
                        OST += Environment.NewLine;
                    }
                }
			}
		
		
            OST = Regex.Replace(OST, "  ", " ");
            OST = Regex.Replace(OST, "  ", " ");
            OST = Regex.Replace(OST, "  ", " ");
            string[] WOST = Regex.Split(OST, Environment.NewLine);
            bool saidAnyOfIt = false;
            foreach (string txt in WOST)
            {
                //

                toSay.Add(txt);

            }
            completeSentence = "";
            foreach (string part in toSay)
            {
                if (RecientlySpoken.Contains(part) == false)
                {
                    completeSentence += part;
                }
            }
            RecientlySpoken.Add(completeSentence);

            StartCoroutine(checkValues("French", completeSentence, "WhatADumbPickle"));

        }
    }

    IEnumerator Translate()
    {
        string text = WWW.EscapeURL(completeSentence);
        WWW www = new WWW(@"https://api.multillect.com/translate/json/1.0/660?method=translate/api/translate&from=en&to=fr&text=" + text + "&sig=55a24f4c49eef63f9a405be66f59dcc7");
        yield return www;
        string encodedString = Encoding.UTF8.GetString(www.bytes);

        JSONObject data = new JSONObject(encodedString);
        accessData(data);

            SetValues("French", completeSentence, translatedSentence);

        if (RxScriptInit.subsLanguage != "NONE")
        {
            if (RxScriptInit.subsLanguage == "FRENCH")
            {
                TranslationTextBox.text = translatedSentence;
            }
            if (RxScriptInit.subsLanguage == "ENGLISH")
            {
                TranslationTextBox.text = completeSentence;
            }
        } else
        {
            TranslationTextBox.text = "";
        }
        if (RxScriptInit.TTSLanguage != "NONE")
        {
                if (RxScriptInit.TTSLanguage == "FRENCH")
                {
                    
					tts.theVoice.speak("<voice required=\"Language=C0C\">" + translatedSentence + "</voice>");
					
                }
                if (RxScriptInit.TTSLanguage == "ENGLISH")
                {
                    tts.theVoice.speak("<voice required=\"Language=409\">" + completeSentence + "</voice>");
                }
        }

    }
    static string EncodeNonAsciiCharacters(string value)
    {
        StringBuilder sb = new StringBuilder();
        foreach (char c in value)
        {
            if (c > 127)
            {
                // This character is too big for ASCII
                string encodedValue = "\\u" + ((int)c).ToString("x4");
                sb.Append(encodedValue);
            }
            else
            {
                sb.Append(c);
            }
        }
        return sb.ToString();
    }

    static string DecodeEncodedNonAsciiCharacters(string value)
    {
        return Regex.Replace(
            value,
            @"\\u(?<Value>[a-zA-Z0-9]{4})",
            m => {
                return ((char)int.Parse(m.Groups["Value"].Value, NumberStyles.HexNumber)).ToString();
            });
    }

    void accessData(JSONObject obj)
    {
        int count = -1;
        switch (obj.type)
        {
            case JSONObject.Type.OBJECT:
                for (int i = 0; i < obj.list.Count; i++)
                {
                    string key = (string)obj.keys[i];
                    JSONObject j = (JSONObject)obj.list[i];
                    
                    if (key == "result")
                    {
                        accessData(j);
                    }
                    if (key == "translated")
                    {
                        accessData(j);
                        string encoded = EncodeNonAsciiCharacters(j.str);
                        //UnityEngine.Debug.Log(encoded);

                        string decoded = DecodeEncodedNonAsciiCharacters(encoded);
                        //UnityEngine.Debug.Log(decoded);

                        translatedSentence = decoded;
                        UnityEngine.Debug.Log(translatedSentence);
                    }
                }
                break;
        }
    }
    public static void PPUTilePixel(int x, int y)
    {
        for (int blx = 0; blx < 8; blx++)
        {
            for (int bly = 0; bly < 8; bly++)
            {
                tileColorz[x + (y * 32), blx + (bly * 8)] = IntToColor(MyNes.NesEmu.backgroundBufferfb[cachedPos[x + (y * 32)] + blx + (bly * 256)]);

            }
        }
    }
    public static void WorldPos(int x, int y, int H, int V)
    {
        TileWorldCoords[x + (y * 32)] = new Vector3(-(V % 8) * 0.125f, ((H % 8) * 0.125f), 0.01f);
    }
    
    public void ProcessSprites()
    {
        
        actionPosition.Clear();
        ActionCam.targets.Clear();
        for (int i = 0; i < sprite.Length; i++)
        {
            //DestroyImmediate(sprite[i]);
            if (sprite[i] == null)
            {
                sprite[i] = GameObject.Instantiate(spritePrefab, Vector3.zero, Quaternion.identity) as GameObject;
                
            } else
            {
                sprite[i].name = "spritePrefab";
            }
            spriteTile[i] = sprite[i].transform.Find("mesh").gameObject;
            sprite[i].GetComponent<Renderer>().enabled = true;


            foreach (Transform child in sprite[i].transform.GetComponentInChildren<Transform>())
            {
                child.gameObject.GetComponent<Renderer>().enabled = true;

            }

            sprite[i].transform.SetParent(spriteParent.transform, false);

            Color[] spriteColors;
            
                int flippedHoz = 0;
                int flippedVert = 0;
                int posx = 0;
                int posy = 0;
                int spriteTileNumber = 0;

                Color firstPixel;
                firstPixel = new Color();

                for (int pos = 0; pos < 4; pos++)
                {
                    if (pos == 0)
                    {
                        posy = (int)MyNes.NesEmu.ppu_oam_bankfb[(i * 4) + pos];
                    }
                    if (pos == 1)
                    {
                        spriteTileNumber = (int)MyNes.NesEmu.ppu_oam_bankfb[(i * 4) + pos];

                    }
                    if (pos == 2)
                    {
                        spritePal[i] = (int)MyNes.NesEmu.ppu_oam_bankfb[(i * 4) + pos] & 3;
                        if (GetBit((byte)MyNes.NesEmu.ppu_oam_bankfb[(i * 4) + pos], 6) == true)
                        {
                            flippedHoz = 1;
                        }
                        if (GetBit((byte)MyNes.NesEmu.ppu_oam_bankfb[(i * 4) + pos], 7) == true)
                        {
                            flippedVert = 1;
                        }
                    }
                    if (pos == 3)
                    {
                        posx = (int)MyNes.NesEmu.ppu_oam_bankfb[(i * 4) + pos];
                    }
                }

                spritePos[i] = new Vector3(posx * 0.125f, (-posy * 0.125f) + 30, -0.25f + (-0.0015f * i));
                bool clear = true;
                if (posx > 0 && posx < 248 && posy > 0 && posy < 225)
                {

                    if (MyNes.NesEmu.isTall[spriteTileNumber] == false)
                    {
                        spriteIsTall[i] = false;
                        spriteTile[i].GetComponent<MeshFilter>().mesh = squareSprite;
                        spriteColors = new Color[8 * 8];
                        for (int blx = 0; blx < 8; blx++)
                        {
                            for (int bly = 0; bly < 8; bly++)
                            {
                                if (spritePal[i] == 0)
                                {
                                    spriteColors[blx + (bly * 8)] = IntToColor(MyNes.NesEmu.spriteBufferfbP1[posx + blx + ((bly + posy) * 256)]);
                                }
                                if (spritePal[i] == 1)
                                {
                                    spriteColors[blx + (bly * 8)] = IntToColor(MyNes.NesEmu.spriteBufferfbP2[posx + blx + ((bly + posy) * 256)]);
                                }
                                if (spritePal[i] == 2)
                                {
                                    spriteColors[blx + (bly * 8)] = IntToColor(MyNes.NesEmu.spriteBufferfbP3[posx + blx + ((bly + posy) * 256)]);
                                }
                                if (spritePal[i] == 3)
                                {
                                    spriteColors[blx + (bly * 8)] = IntToColor(MyNes.NesEmu.spriteBufferfbP4[posx + blx + ((bly + posy) * 256)]);
                                }
                                objcolors[posx + blx + ((bly + posy) * 256)] = spriteColors[blx + (bly * 8)];
                                if (objcolors[posx + blx + ((bly + posy) * 256)].a > 0.5f)
                                {
                                    clear = false;
                                }

                                if (blx == 0 && bly == 0)
                                {
                                    firstPixel = spriteColors[blx + (bly * 8)];
                                }

                            }
                        }
                        squareSpriteTexture[i].SetPixels(spriteColors);
                        squareSpriteTexture[i].Apply();
                        squareSpriteTexture[i].filterMode = FilterMode.Point;
                        spriteTile[i].GetComponent<Renderer>().material.mainTexture = squareSpriteTexture[i];

                        testmd5 = colorSumSprite(spriteColors);

                    }
                    if (MyNes.NesEmu.isTall[spriteTileNumber] == true)
                    {
                        spriteIsTall[i] = true;
                        spriteTile[i].GetComponent<MeshFilter>().mesh = tallSprite;
                        spriteColors = new Color[8 * 16];
                        for (int blx = 0; blx < 8; blx++)
                        {
                            for (int bly = 0; bly < 16; bly++)
                            {

                                if (spritePal[i] == 0)
                                {
                                    spriteColors[blx + (bly * 8)] = IntToColor(MyNes.NesEmu.spriteBufferfbP1[posx + blx + ((bly + posy) * 256)]);
                                }
                                if (spritePal[i] == 1)
                                {
                                    spriteColors[blx + (bly * 8)] = IntToColor(MyNes.NesEmu.spriteBufferfbP2[posx + blx + ((bly + posy) * 256)]);
                                }
                                if (spritePal[i] == 2)
                                {
                                    spriteColors[blx + (bly * 8)] = IntToColor(MyNes.NesEmu.spriteBufferfbP3[posx + blx + ((bly + posy) * 256)]);
                                }
                                if (spritePal[i] == 3)
                                {
                                    spriteColors[blx + (bly * 8)] = IntToColor(MyNes.NesEmu.spriteBufferfbP4[posx + blx + ((bly + posy) * 256)]);
                                }
                                objcolors[posx + blx + ((bly + posy) * 256)] = spriteColors[blx + (bly * 8)];
                                if (objcolors[posx + blx + ((bly + posy) * 256)].a > 0.5f)
                                {
                                    clear = false;
                                }

                                if (blx == 0 && bly == 0)
                                {
                                    firstPixel = spriteColors[blx + (bly * 8)];
                                }

                            }
                        }

                        tallSpriteTexture[i].SetPixels(spriteColors);
                        tallSpriteTexture[i].Apply();
                        tallSpriteTexture[i].filterMode = FilterMode.Point;
                        spriteTile[i].GetComponent<Renderer>().material.mainTexture = tallSpriteTexture[i];

                        testmd5 = colorSumSprite(spriteColors);

                    }

                    if (clear == true)
                    {
                        foreach (Renderer rend in sprite[i].GetComponentsInChildren<Renderer>())
                        {
                            rend.enabled = false;
                        }
                    }

                    if (TextureUpdateHash.Contains(testmd5))
                    {
                        passed = true;
                        newmd5 = testmd5;

                    }
                    else
                    {
                        passed = false;
                        newmd5 = testmd5;
                        /* foreach (Transform child in spriteTile[i].transform)
                        {

                            if (child.gameObject.name.Contains("Model") == false && child.gameObject.name != newmd5)
                            {
                                Destroy(child.gameObject);
                            }
                        } */

                    }
                    if (clear == true)
                    {
                        foreach (Renderer rend in sprite[i].GetComponentsInChildren<Renderer>())
                        {
                            rend.enabled = false;
                        }
                        testmd5 = "clear";
                    }
                    spriteHash[i] = newmd5;
                    /*
                    if (RxScriptInit.dumpingEnabled == true)
                    {
                         if (!TileTextureColorsHash.Contains("Spr-" + newmd5))
                        {

                            if (MyNes.NesEmu.isTall[spriteTileNumber] == false)
                            {

                                byte[] pbh = (MirrorTexture(squareSpriteTexture[i], false, true)).EncodeToPNG();
                                File.WriteAllBytes(persistentDataPath + "/Enhancements/" + currentRomName + "/Spr-" + newmd5 + ".png", pbh);
                            }
                            else if (MyNes.NesEmu.isTall[spriteTileNumber] == true)
                            {

                                byte[] pbh = (MirrorTexture(tallSpriteTexture[i], false, true)).EncodeToPNG();
                                File.WriteAllBytes(persistentDataPath + "/Enhancements/" + currentRomName + "/Spr-" + newmd5 + ".png", pbh);
                            }

                            TileTextureColorsHash.Add("Spr-" + newmd5);
                        } 

                    }*/
                }
                else
                {
                    sprite[i].GetComponent<Renderer>().enabled = false;
                    foreach (Transform child in sprite[i].transform)
                    {

                        child.GetComponent<Renderer>().enabled = false;

                    }
                }

                bool found = false;

                for (int t = 0; t < TextureUpdateHash.Count; t++)
                {
                    if (found == false)
                    {

                        if (TextureUpdateHash[t].Contains("Spr-" + newmd5))
                        {
                            found = true;
                            spriteTile[i].GetComponent<Renderer>().material.mainTexture = TextureUpdateColors[t];

                            spriteTile[i].GetComponent<Renderer>().material.mainTexture.wrapMode = TextureWrapMode.Clamp;
                            /*
                            if (newmd5 == WorkingGFXFile)
                            {
                                
                                    WorkingTexture = TextureUpdateColors[t];
                                    
                                
                            }
                            */
                            if (hasModelLoaded[t] == true)
                            {
                            }
                            else
                            {
                            }
                        }
                    }
                }
                /*
                if (found == false)
                {
                    if (newmd5 == WorkingGFXFile)
                    {
                        if (MyNes.NesEmu.isTall[spriteTileNumber] == false)
                        {
                            WorkingTexture.Resize(8, 8);
                            WorkingTexture = squareSpriteTexture[i];
                        }
                        if (MyNes.NesEmu.isTall[spriteTileNumber] == true)
                        {
                            WorkingTexture.Resize(8, 16);
                            WorkingTexture = tallSpriteTexture[i];
                        }
                    }
                }*/

                sprite[i].transform.position = spritePos[i];

                if (clear != true)
                {
                    sprite[i].name = spriteTileNumber + "_" + spritePal[i] + "_" + newmd5 + "_" + flippedHoz + "_" + flippedVert;
                    //spriteTile[i].name = newmd5 + "Model";
                }
                else
                {
                    sprite[i].name = "clear" + "_" + spritePal[i] + "_" + "clear" + "_" + "clear" + "_" + "clear";
                    //spriteTile[i].name = "clear" + "Model";
                }
                if (posy >= 248)
                {
                    spriteTile[i].GetComponent<Renderer>().enabled = false;
                    foreach (Transform child in sprite[i].transform.GetComponentInChildren<Transform>())
                    {
                        child.gameObject.GetComponent<Renderer>().enabled = false;

                    }
                }
                if (spriteTile[i].GetComponent<Renderer>().enabled == true)
                {
                    actionPosition.Add(spritePos[i]);
                }
            
        }
        float px = 0;
        float py = 0;
        float sax = 0;
        float say = 0;
        if (actionPosition.Count > 0)
        {
            for (int p = 0; p < actionPosition.Count; p++)
            {
                ActionCam.targets.Add(actionPosition[p]);
                px += actionPosition[p].x;
                py += actionPosition[p].y;
            }

            if (smoothAction.Count > 7)
            {
                smoothAction.RemoveAt(0);
            }
            smoothAction.Add(new Vector3(px / actionPosition.Count, py / actionPosition.Count, 0));
            if (smoothAction.Count > 0)
            {
                for (int sa = 0; sa < smoothAction.Count; sa++)
                {
                    sax += smoothAction[sa].x;
                    say += smoothAction[sa].y;
                }
                actionTransform.position = new Vector3(sax / smoothAction.Count, say / smoothAction.Count, 0);
            }
        }
    }


    public void CombineSprites()
    {
        /*previousFrameCombinedSprites.Clear();
        foreach (CombinedSprite cs in CombinedSprites)
        {
            
            previousFrameCombinedSprites.Add(cs);
        }*/
        CombinedSprites.Clear();
        for (int Count = 0; Count < sprite.Length; Count++)
        {
            if (sprite[Count] != null)
            {

                sprite[Count].transform.SetParent(spriteParent.transform, false);

            }
        }
        GameObject[] Cspr = GameObject.FindGameObjectsWithTag("CombinedSprite");
        for (int c = Cspr.Length - 1; c >= 0; c--)
        {
            Destroy(Cspr[c]);
        }

        for (int Count = 0; Count < sprite.Length; Count++)
        {
            if (sprite[Count] != null && sprite[Count].transform != null && !sprite[Count].name.Contains("clear"))
            {

                for (int otherCount = sprite.Length - 1; otherCount >= 0; otherCount--)
                {
                    if (sprite[otherCount] != null && sprite[otherCount].transform != null)

                    {

                        if (!sprite[otherCount].name.Contains("clear"))
                        {
                            if (spritePal[Count] == spritePal[otherCount] && sprite[Count].GetComponent<Renderer>().enabled == true)
                            {
                                if (Math.Abs((int)sprite[Count].transform.position.x - (int)sprite[otherCount].transform.position.x) <= 1.6f && Math.Abs((int)sprite[Count].transform.position.y - (int)sprite[otherCount].transform.position.y) <= 1.6f)
                                {
                                    /*bool found = false;
                                    bool exactAdjacent = false;
                                    for (int csc = 0; csc < CombinedSprites.Count; csc++)
                                    {
                                        for (int st = 0; st < CombinedSprites[csc].SubTiles.Count; st++)
                                        {

                                            /*if (CombinedSprites[csc].SubTiles[st].name.Split('_')[0] == sprite[Count].name.Split('_')[0])
                                            {
                                                found = true;
                                            }
                                            if (sprite[otherCount].name.Contains("clear"))
                                            {
                                                found = true;
                                            }
                                            if (sprite[Count].name.Contains("clear"))
                                            {
                                                found = true;
                                            }
                                            if (CombinedSprites[csc].SubTiles[st].name.Contains("clear"))
                                            {
                                                found = true;
                                            }


                                        }




                                    }
                                    if (sprite[otherCount].name.Split('_')[1] == sprite[Count].name.Split('_')[1])
                                    {
                                        if (Mathf.Abs(sprite[otherCount].transform.position.x - sprite[Count].transform.position.x) == 1 && sprite[otherCount].transform.position.y == sprite[Count].transform.position.y)
                                        {
                                            exactAdjacent = true;
                                        }
                                        else if (Mathf.Abs(sprite[otherCount].transform.position.y - sprite[Count].transform.position.y) == 1 && sprite[otherCount].transform.position.x == sprite[Count].transform.position.x)
                                        {
                                            exactAdjacent = true;
                                        }
                                    }
                                    exactAdjacent = true;
                                    if (found == false)
                                    {*/
                                    Bounds bounds = new Bounds(sprite[otherCount].transform.position, Vector3.zero);
                                    foreach (Renderer render in sprite[otherCount].transform.GetComponentsInChildren<Renderer>())
                                    {

                                        if (render.enabled != false && render.gameObject.transform.parent == sprite[otherCount].transform)
                                        {


                                            bounds.Encapsulate(render.bounds);
                                            render.enabled = false;
                                        }
                                    }

                                    CombinedSprites.Add(new CombinedSprite(bounds, spritePal[Count], true, null, true));
                                    if (!CombinedSprites[CombinedSprites.Count - 1].SubTiles.Contains(sprite[otherCount]))
                                    {
                                        CombinedSprites[CombinedSprites.Count - 1].SubTiles.Add(sprite[otherCount]);
                                    }
                                    if (!CombinedSprites[CombinedSprites.Count - 1].SubTiles.Contains(sprite[Count]))
                                    {
                                        CombinedSprites[CombinedSprites.Count - 1].SubTiles.Add(sprite[Count]);
                                    }
                                    //}

                                    
                                }
                            }

                        }

                    }
                }

            }
        }
        if (CombinedSprites.Count > 0)
        {


            foreach (CombinedSprite b in CombinedSprites)
            {
                foreach (CombinedSprite c in CombinedSprites)
                {
                    if (b != null && c != null)
                    {
                        if (b.Palette == c.Palette)
                        {
                            if ((Mathf.Abs(b.Boundz.ClosestPoint(c.Boundz.center).x - c.Boundz.ClosestPoint(b.Boundz.center).x) <= 1.75f && Mathf.Abs(b.Boundz.ClosestPoint(c.Boundz.center).y - c.Boundz.ClosestPoint(b.Boundz.center).y) <= 1.75f) || (Mathf.Abs(b.Boundz.ClosestPoint(c.Boundz.center).y - c.Boundz.ClosestPoint(b.Boundz.center).y) <= 0.5f && Mathf.Abs(b.Boundz.ClosestPoint(c.Boundz.center).x - c.Boundz.ClosestPoint(b.Boundz.center).x) <= 0.5f) && b.Unique == true)
                            {


                                c.Destroy = false;
                                for (int s = b.SubTiles.Count - 1; s >= 0; s--)
                                {
                                    if (!c.SubTiles.Contains(b.SubTiles[s]))
                                    {
                                        c.SubTiles.Add(b.SubTiles[s]);

                                    }
                                    foreach (Renderer render in b.SubTiles[s].transform.GetComponentsInChildren<Renderer>())
                                    {
                                        b.Boundz.Encapsulate(render.bounds);
                                        c.Boundz.Encapsulate(render.bounds);
                                        render.enabled = true;
                                    }
                                }
                                for (int s = c.SubTiles.Count - 1; s >= 0; s--)
                                {
                                    if (!b.SubTiles.Contains(c.SubTiles[s]))
                                    {
                                        b.SubTiles.Add(c.SubTiles[s]);

                                    }
                                    foreach (Renderer render in c.SubTiles[s].transform.GetComponentsInChildren<Renderer>())
                                    {
                                        b.Boundz.Encapsulate(render.bounds);
                                        c.Boundz.Encapsulate(render.bounds);
                                        render.enabled = true;
                                    }

                                }

                                /*
                                if (b.Holding != null && c.Holding == null)
                                {
                                    c.Holding = b.Holding;
                                }*/
                            }
                        }
                    }
                }
            }

        }


        /* 
            else
            {
                //Bounds contractedBounds = new Bounds(CombinedSprites[c].Boundz.center, Vector3.zero);

                for (int s = CombinedSprites[c].SubTiles.Count - 1; s >= 0; s--)
                {
                    CombinedSprites[c].SubTiles[s].GetComponent<Renderer>().enabled = true;
                    //contractedBounds.Encapsulate(CombinedSprites[c].SubTiles[s].GetComponent<Renderer>().bounds);
                    //CombinedSprites[c].SubTiles[s].GetComponent<Renderer>().enabled = false;
                    
                }
                //CombinedSprites[c].Boundz = contractedBounds;
                //CombinedSprites[c].Boundz.Expand(3f);
            }
        }/*
        for (int c = previousFrameCombinedSprites.Count - 1; c >= 0; c--)
        {
            //previousFrameCombinedSprites[c].Boundz.Expand(7.25f);
            previousFrameCombinedSprites[c].Destroy = true;
        }*/
        if (CombinedSprites.Count > 0)
        {
            foreach (CombinedSprite cs in CombinedSprites)
            {
                cs.Boundz.Expand(1f);
                if (cs.Destroy == false)
                {

                    if (cs.Palette == 0)
                    {
                        if (cs.Boundz.size.x >= 1 && cs.Boundz.size.y >= 1 && cs.Boundz.min.x > 2 && cs.Boundz.max.x + todump.width < 245 && cs.Boundz.min.y > 2 && cs.Boundz.max.y + todump.height < 239 && ((cs.Boundz.min.x) * 8) + todump.width < 245 && (int)Math.Ceiling(((cs.Boundz.min.y) * 8) - 4) > 0)
                        {

                           if ((int)Math.Ceiling(((cs.Boundz.max.x) * 8)) < 250 && (int)Math.Ceiling(((cs.Boundz.max.y) * 8)) < 235)
                            {


                                todump.Resize((int)(cs.Boundz.size.x + 1) * 8, (int)((cs.Boundz.size.y + 1) * 8));

                                todump.SetPixels(flippyP1.GetPixels((int)Math.Ceiling(((cs.Boundz.min.x) * 8)), (int)Math.Ceiling(((cs.Boundz.min.y) * 8)), todump.width, todump.height));

                                todump.Apply();
                                tempcspr = null;

                                toCrop = flippyP1.GetPixels((int)Math.Ceiling(((cs.Boundz.min.x) * 8)), (int)Math.Ceiling(((cs.Boundz.min.y) * 8)), todump.width, todump.height);
                                Vector2 min = new Vector2(todump.width, todump.height);
                                Vector2 max = new Vector2(0, 0);
                                for (int x = 0; x < todump.width; x++)
                                {
                                    for (int y = 0; y < todump.height; y++)
                                    {
                                        Color pixelColor = toCrop[x + (y * todump.width)];
                                        if (pixelColor.a > 0.2f)
                                        {
                                            if (x <= (int)min.x) min.x = x;
                                            if (y <= (int)min.y) min.y = y;

                                            if (x >= (int)max.x) max.x = x;
                                            if (y >= (int)max.y) max.y = y;
                                        }
                                    }
                                }

                                if (max.x < min.x)
                                {
                                    int swap = (int)max.x;
                                    max.x = (int)min.x;
                                    min.x = swap;
                                }
                                if (max.y < min.y)
                                {
                                    int swap = (int)max.y;
                                    max.y = (int)min.y;
                                    min.y = swap;
                                }
                                if ((int)Math.Abs(max.x - min.x) == 0)
                                {
                                    max.x += 8;

                                }
                                if ((int)Math.Abs(max.y - min.y) == 0)
                                {
                                    max.y += 8;
                                }

                                if (min.x != max.x && min.y != max.y)
                                {

                                    crop.Resize((int)Math.Abs(max.x - min.x), (int)Math.Abs(max.y - min.y));

                                    crop.SetPixels(todump.GetPixels((int)min.x, (int)min.y, (int)Math.Abs(max.x - min.x), (int)Math.Abs(max.y - min.y)));
                                    crop.Apply();
                                    //int cnt = 0;
                                    //for (int x = (int)min.x; x < (int)max.x; x++)
                                    //{
                                    //    for (int y = (int)min.y; y < (int)max.y; y++)
                                    ///    {
                                    //        crop[cnt++] = toCrop[x + (y * todump.width)];

                                    //    }
                                    //}



                                    bool notsolid = false;
                                    tempcspr = crop.GetPixels();
                                    for (int cm = 1; cm < tempcspr.Length; cm++)
                                    {
                                        if (tempcspr[cm] != tempcspr[0])
                                        {
                                            notsolid = true;
                                        }
                                    }
                                    /* foreach (GameObject n in cs.SubTiles)
                                    {

                                        if (n.GetComponentInChildren<Renderer>() != null)
                                        {
                                            foreach (Renderer render in n.transform.GetComponentsInChildren<Renderer>())
                                            {
                                                if (render.enabled != false && render.gameObject.transform.parent == n.transform)
                                                {

                                                    int intname = 0;
                                                    int.TryParse(n.name, out intname);
                                                    if (intname != 0)
                                                    {
                                                        names.Add(intname);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    int[] nameArray = names.ToArray();
                                    Array.Sort(nameArray);
                                    string md = GetHashCodeTile(nameArray).ToString(); */
                                    //string md = GetHashCodeTile(nameArray).ToString(); */
                                    md = "_";
                                    stNames.Clear();
                                    for (int st = 0; st < cs.SubTiles.Count; st++)
                                    {
                                        if (cs.SubTiles[st].name.Contains("_") && !md.Contains("_" + cs.SubTiles[st].name.Split('_')[0] + "_" + cs.SubTiles[st].name.Split('_')[1]))
                                        {
                                            stNames.Add(cs.SubTiles[st].name.Split('_')[0] + "_" + cs.SubTiles[st].name.Split('_')[3] + "_" + cs.SubTiles[st].name.Split('_')[4]);
                                        }
                                    }
                                    stNames.Sort();
                                    for (int st = 0; st < stNames.Count; st++)
                                    {
                                        md += stNames[st] + "_";
                                    }
                                    fallBack = cs.Palette + "_" + GetHashCodeFileName(md);
                                    imghash = "h" + GetHashCodeTileColors(tempcspr);
                                    md = fallBack + "_" + imghash;
                                    //string md = cs.Palette + "_" + GetHashCodeTileColors(tempcspr).ToString();

                                    if (notsolid == true)
                                    {
                                        if (RxScriptInit.dumpingEnabled == true)
                                        {
                                            if (JustDumped.Contains(md) == false && !TextureUpdateHash.Contains("Spr-" + md))
                                            {

                                                //CroppedDump.Resize(crop.width * 8, crop.height * 8);

                                                //CroppedDump.SetPixels(resizePixels(todump.GetPixels((int)min.x, (int)min.y, (int)Math.Abs(max.x - min.x), (int)Math.Abs(max.y - min.y)), crop.width, crop.height, crop.width * 8, crop.height * 8));
                                                //CroppedDump.Apply();
                                                output3 = crop.EncodeToPNG();
                                                if (File.Exists(persistentDataPath + "/Enhancements/" + currentRomName + "/Spr-" + md + ".png") == false)
                                                {
                                                    MyNes.NesEmu.PAUSED = true;
                                                    File.WriteAllBytes(persistentDataPath + "/Enhancements/" + currentRomName + "/Spr-" + md + ".png", output3);
                                                    Debug.Log("DUMPED : " + persistentDataPath + "/Enhancements/" + currentRomName + "/Spr-" + md + ".png");
                                                    MyNes.NesEmu.PAUSED = false;
                                                    JustDumped.Add(md);
                                                }
                                                else
                                                {
                                                    JustDumped.Add(md);
                                                }

                                            }
                                        }
                                    }

                                    bool found = false;

                                    if (cs.Palette == 0)
                                    {
                                        for (int t = 0; t < TextureUpdateHash.Count; t++)
                                        {
                                            if (found == false)
                                            {
                                                /*if (Cspr.Length > 0)
                                                {

                                                    if (!TextureUpdateHash[t].Contains("Spr-" + md))
                                                    {

                                                        for (int c = Cspr.Length - 1; c >= 0; c--)
                                                        {
                                                            if (cs.Boundz.Contains(Cspr[c].transform.position))
                                                            {
                                                                if (Cspr[c] != spriteParent)
                                                                {
                                                                    Cspr[c].transform.position = new Vector3(cs.Boundz.center.x + 0.25f, cs.Boundz.center.y - 0.50f, -2.97f + (cs.Boundz.center.x * -0.015f));

                                                                    for (int s = 0; s < cs.SubTiles.Count; s++)
                                                                    {
                                                                        if (cs.SubTiles[s].GetComponentInChildren<Renderer>() != null)
                                                                        {
                                                                            foreach (Renderer render in cs.SubTiles[s].transform.GetComponentsInChildren<Renderer>())
                                                                            {
                                                                                render.enabled = false;
                                                                            }
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                                bool inside = false;
                                                                foreach (CombinedSprite s in CombinedSprites)
                                                                {

                                                                    if (s.Boundz.Contains(Cspr[c].transform.position))
                                                                    {
                                                                        inside = true;
                                                                    }
                                                                }
                                                                if (inside == false)
                                                                {
                                                                    Destroy(Cspr[c]);
                                                                }

                                                        }

                                                    }
                                                    else if (TextureUpdateHash[t].Contains("Spr-" + md))
                                                    {

                                                        for (int c = Cspr.Length - 1; c >= 0; c--)
                                                        {
                                                            if (cs.Boundz.Contains(Cspr[c].transform.position))
                                                            {
                                                                if (Cspr[c] != spriteParent)
                                                                {
                                                                    //Destroy(Cspr[c]);
                                                                }
                                                            }
                                                        }

                                                        found = true;
                                                        GameObject CombinedSprite = GameObject.Instantiate(CombinedSpritePrefab, new Vector3(cs.Boundz.center.x + 0.25f, cs.Boundz.center.y - 0.50f, -2.97f + (cs.Boundz.center.x * -0.015f)), Quaternion.identity) as GameObject;
                                                        TextureUpdateColors[t].wrapMode = TextureWrapMode.Clamp;
                                                        CombinedSprite.GetComponent<Renderer>().material.mainTexture = TextureUpdateColors[t];
                                                        CombinedSprite.transform.localScale = new Vector3((TextureUpdateColors[t].width / 8) * 0.125f, -(TextureUpdateColors[t].height / 8) * 0.125f, 1); CombinedSprite.tag = "CombinedSprite";
                                                        CombinedSprite.name = "CSpr-" + md;
                                                        for (int s = 0; s < cs.SubTiles.Count; s++)
                                                        {
                                                            if (cs.SubTiles[s].GetComponentInChildren<Renderer>() != null)
                                                            {
                                                                foreach (Renderer render in cs.SubTiles[s].transform.GetComponentsInChildren<Renderer>())
                                                                {
                                                                    render.enabled = false;
                                                                }
                                                            }
                                                        }
                                                        if (t < hasModelLoaded.Length && hasModelLoaded[t] == true)
                                                        {
                                                            Model = GameObject.Instantiate(TileModels[t], new Vector3(CombinedSprite.transform.position.x, CombinedSprite.transform.position.y - 1.5f, CombinedSprite.transform.position.z), Quaternion.identity) as GameObject;
                                                            Model.name = md + "Model";
                                                            Model.transform.SetParent(CombinedSprite.transform, false);
                                                            CombinedSprite.GetComponent<Renderer>().enabled = false;
                                                            foreach (Transform child in Model.transform)
                                                            {
                                                                child.GetComponent<Renderer>().enabled = true;
                                                                child.gameObject.layer = LayerMask.NameToLayer("Sprites");
                                                            }
                                                        }
                                                    }

                                                }
                                                else
                                                {*/
                                                if (TextureUpdateHash[t].Contains("Spr-" + md))
                                                {
                                                    found = true;
                                                    GameObject CombinedSprite = GameObject.Instantiate(CombinedSpritePrefab, new Vector3(cs.Boundz.center.x + 0.25f, cs.Boundz.center.y - 0.50f, -2.97f + (cs.Boundz.center.x * -0.015f)), Quaternion.identity) as GameObject;
                                                    TextureUpdateColors[t].wrapMode = TextureWrapMode.Clamp;
                                                    CombinedSprite.GetComponent<Renderer>().material.mainTexture = TextureUpdateColors[t];
                                                    CombinedSprite.transform.localScale = new Vector3((TextureUpdateColors[t].width / 8) * 0.125f, -(TextureUpdateColors[t].height / 8) * 0.125f, 1); CombinedSprite.tag = "CombinedSprite";
                                                    CombinedSprite.name = "CSpr-" + md;
                                                    for (int s = 0; s < cs.SubTiles.Count; s++)
                                                    {
                                                        if (cs.SubTiles[s].GetComponentInChildren<Renderer>() != null)
                                                        {
                                                            foreach (Renderer render in cs.SubTiles[s].transform.GetComponentsInChildren<Renderer>())
                                                            {
                                                                render.enabled = false;
                                                            }
                                                        }
                                                    }
                                                    if (t < hasModelLoaded.Length && hasModelLoaded[t] == true)
                                                    {
                                                        Model = GameObject.Instantiate(TileModels[t], new Vector3(CombinedSprite.transform.position.x, CombinedSprite.transform.position.y - 1.5f, CombinedSprite.transform.position.z), Quaternion.identity) as GameObject;
                                                        Model.name = md + "Model";
                                                        Model.transform.SetParent(CombinedSprite.transform, false);
                                                        CombinedSprite.GetComponent<Renderer>().enabled = false;
                                                        foreach (Transform child in Model.transform)
                                                        {
                                                            child.GetComponent<Renderer>().enabled = true;
                                                            child.gameObject.layer = LayerMask.NameToLayer("Sprites");
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                        if (found == false)
                                        {
                                            for (int t = 0; t < TextureUpdateHash.Count; t++)
                                            {
                                                if (found == false)
                                                {
                                                    if (TextureUpdateHash[t].Contains(imghash))
                                                    {
                                                        found = true;
                                                        GameObject CombinedSprite = GameObject.Instantiate(CombinedSpritePrefab, new Vector3(cs.Boundz.center.x + 0.25f, cs.Boundz.center.y - 0.50f, -2.97f + (cs.Boundz.center.x * -0.015f)), Quaternion.identity) as GameObject;
                                                        TextureUpdateColors[t].wrapMode = TextureWrapMode.Clamp;
                                                        CombinedSprite.GetComponent<Renderer>().material.mainTexture = TextureUpdateColors[t];
                                                        CombinedSprite.transform.localScale = new Vector3((TextureUpdateColors[t].width / 8) * 0.125f, -(TextureUpdateColors[t].height / 8) * 0.125f, 1); CombinedSprite.tag = "CombinedSprite";
                                                        CombinedSprite.name = "CSpr-" + imghash;
                                                        for (int s = 0; s < cs.SubTiles.Count; s++)
                                                        {
                                                            if (cs.SubTiles[s].GetComponentInChildren<Renderer>() != null)
                                                            {
                                                                foreach (Renderer render in cs.SubTiles[s].transform.GetComponentsInChildren<Renderer>())
                                                                {
                                                                    render.enabled = false;
                                                                }
                                                            }
                                                        }
                                                        if (t < hasModelLoaded.Length && hasModelLoaded[t] == true)
                                                        {
                                                            Model = GameObject.Instantiate(TileModels[t], new Vector3(CombinedSprite.transform.position.x, CombinedSprite.transform.position.y - 1.5f, CombinedSprite.transform.position.z), Quaternion.identity) as GameObject;
                                                            Model.name = md + "Model";
                                                            Model.transform.SetParent(CombinedSprite.transform, false);
                                                            CombinedSprite.GetComponent<Renderer>().enabled = false;
                                                            foreach (Transform child in Model.transform)
                                                            {
                                                                child.GetComponent<Renderer>().enabled = true;
                                                                child.gameObject.layer = LayerMask.NameToLayer("Sprites");
                                                            }
                                                        }
                                                    }

                                                }
                                            }
                                        }
                                        if (found == false)
                                        {
                                            for (int t = 0; t < TextureUpdateHash.Count; t++)
                                            {
                                                if (found == false)
                                                {
                                                    if (TextureUpdateHash[t].Contains("Spr-" + fallBack + "_"))
                                                    {
                                                        found = true;
                                                        GameObject CombinedSprite = GameObject.Instantiate(CombinedSpritePrefab, new Vector3(cs.Boundz.center.x + 0.25f, cs.Boundz.center.y - 0.50f, -2.97f + (cs.Boundz.center.x * -0.015f)), Quaternion.identity) as GameObject;
                                                        TextureUpdateColors[t].wrapMode = TextureWrapMode.Clamp;
                                                        CombinedSprite.GetComponent<Renderer>().material.mainTexture = TextureUpdateColors[t];
                                                        CombinedSprite.transform.localScale = new Vector3((TextureUpdateColors[t].width / 8) * 0.125f, -(TextureUpdateColors[t].height / 8) * 0.125f, 1); CombinedSprite.tag = "CombinedSprite";
                                                        CombinedSprite.name = "CSpr-" + fallBack;
                                                        for (int s = 0; s < cs.SubTiles.Count; s++)
                                                        {
                                                            if (cs.SubTiles[s].GetComponentInChildren<Renderer>() != null)
                                                            {
                                                                foreach (Renderer render in cs.SubTiles[s].transform.GetComponentsInChildren<Renderer>())
                                                                {
                                                                    render.enabled = false;
                                                                }
                                                            }
                                                        }
                                                        if (t < hasModelLoaded.Length && hasModelLoaded[t] == true)
                                                        {
                                                            Model = GameObject.Instantiate(TileModels[t], new Vector3(CombinedSprite.transform.position.x, CombinedSprite.transform.position.y - 1.5f, CombinedSprite.transform.position.z), Quaternion.identity) as GameObject;
                                                            Model.name = md + "Model";
                                                            Model.transform.SetParent(CombinedSprite.transform, false);
                                                            CombinedSprite.GetComponent<Renderer>().enabled = false;
                                                            foreach (Transform child in Model.transform)
                                                            {
                                                                child.GetComponent<Renderer>().enabled = true;
                                                                child.gameObject.layer = LayerMask.NameToLayer("Sprites");
                                                            }
                                                        }
                                                    }

                                                }
                                                //}
                                            }
                                        }
                                    }

                                }
                            }
                        }
                    }
                    else if (cs.Palette == 1)
                    {
                        if (cs.Boundz.size.x >= 1 && cs.Boundz.size.y >= 1 && cs.Boundz.min.x > 2 && cs.Boundz.max.x + todump.width < 245 && cs.Boundz.min.y > 2 && cs.Boundz.max.y + todump.height < 239 && ((cs.Boundz.min.x) * 8) + todump.width < 245 && (int)Math.Ceiling(((cs.Boundz.min.y) * 8) - 4) > 0)
                        {
                            if ((int)Math.Ceiling(((cs.Boundz.max.x) * 8)) < 250 && (int)Math.Ceiling(((cs.Boundz.max.y) * 8)) < 235)
                            {


                                todump.Resize((int)(cs.Boundz.size.x + 1) * 8, (int)((cs.Boundz.size.y + 1) * 8));

                            todump.SetPixels(flippyP2.GetPixels((int)Math.Ceiling(((cs.Boundz.min.x) * 8)), (int)Math.Ceiling(((cs.Boundz.min.y) * 8)), todump.width, todump.height));

                            todump.Apply();
                            tempcspr = null;

                            toCrop = flippyP2.GetPixels((int)Math.Ceiling(((cs.Boundz.min.x) * 8)), (int)Math.Ceiling(((cs.Boundz.min.y) * 8)), todump.width, todump.height);
                            Vector2 min = new Vector2(todump.width, todump.height);
                            Vector2 max = new Vector2(0, 0);
                            for (int x = 0; x < todump.width; x++)
                            {
                                for (int y = 0; y < todump.height; y++)
                                {
                                    Color pixelColor = toCrop[x + (y * todump.width)];
                                    if (pixelColor.a > 0.2f)
                                    {
                                        if (x <= (int)min.x) min.x = x;
                                        if (y <= (int)min.y) min.y = y;

                                        if (x >= (int)max.x) max.x = x;
                                        if (y >= (int)max.y) max.y = y;
                                    }
                                }
                            }

                            if (max.x < min.x)
                            {
                                int swap = (int)max.x;
                                max.x = (int)min.x;
                                min.x = swap;
                            }
                            if (max.y < min.y)
                            {
                                int swap = (int)max.y;
                                max.y = (int)min.y;
                                min.y = swap;
                            }
                            if ((int)Math.Abs(max.x - min.x) == 0)
                            {
                                max.x += 8;

                            }
                            if ((int)Math.Abs(max.y - min.y) == 0)
                            {
                                max.y += 8;
                            }
                                if (min.x != max.x && min.y != max.y)
                                {

                                    crop.Resize((int)Math.Abs(max.x - min.x), (int)Math.Abs(max.y - min.y));

                                    crop.SetPixels(todump.GetPixels((int)min.x, (int)min.y, (int)Math.Abs(max.x - min.x), (int)Math.Abs(max.y - min.y)));
                                    crop.Apply();
                                    //int cnt = 0;
                                    //for (int x = (int)min.x; x < (int)max.x; x++)
                                    //{
                                    //    for (int y = (int)min.y; y < (int)max.y; y++)
                                    ///    {
                                    //        crop[cnt++] = toCrop[x + (y * todump.width)];

                                    //    }
                                    //}



                                    bool notsolid = false;
                                    tempcspr = crop.GetPixels();
                                    for (int cm = 1; cm < tempcspr.Length; cm++)
                                    {
                                        if (tempcspr[cm] != tempcspr[0])
                                        {
                                            notsolid = true;
                                        }
                                    }
                                    /* foreach (GameObject n in cs.SubTiles)
                                    {

                                        if (n.GetComponentInChildren<Renderer>() != null)
                                        {
                                            foreach (Renderer render in n.transform.GetComponentsInChildren<Renderer>())
                                            {
                                                if (render.enabled != false && render.gameObject.transform.parent == n.transform)
                                                {

                                                    int intname = 0;
                                                    int.TryParse(n.name, out intname);
                                                    if (intname != 0)
                                                    {
                                                        names.Add(intname);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    int[] nameArray = names.ToArray();
                                    Array.Sort(nameArray);
                                    string md = GetHashCodeTile(nameArray).ToString(); */
                                    //string md = GetHashCodeTileColors(todump.GetPixels()).ToString();
                                    md = "_";
                                    stNames.Clear();
                                    for (int st = 0; st < cs.SubTiles.Count; st++)
                                    {
                                        if (cs.SubTiles[st].name.Contains("_") && !md.Contains("_" + cs.SubTiles[st].name.Split('_')[0] + "_" + cs.SubTiles[st].name.Split('_')[1]))
                                        {
                                            stNames.Add(cs.SubTiles[st].name.Split('_')[0] + "_" + cs.SubTiles[st].name.Split('_')[3] + "_" + cs.SubTiles[st].name.Split('_')[4]);
                                        }
                                    }
                                    stNames.Sort();
                                    for (int st = 0; st < stNames.Count; st++)
                                    {
                                        md += stNames[st] + "_";
                                    }
                                    fallBack = cs.Palette + "_" + GetHashCodeFileName(md);
                                    imghash = "h" + GetHashCodeTileColors(tempcspr);
                                    md = fallBack + "_" + imghash;
                                    //string md = cs.Palette + "_" + GetHashCodeTileColors(tempcspr).ToString();
                                    if (notsolid == true)
                                    {
                                        if (RxScriptInit.dumpingEnabled == true)
                                        {
                                            if (JustDumped.Contains(md) == false && !TextureUpdateHash.Contains("Spr-" + md))
                                            {


                                                //CroppedDump.Resize(crop.width * 8, crop.height * 8);

                                                //CroppedDump.SetPixels(resizePixels(todump.GetPixels((int)min.x, (int)min.y, (int)Math.Abs(max.x - min.x), (int)Math.Abs(max.y - min.y)), crop.width, crop.height, crop.width * 8, crop.height * 8));
                                                //CroppedDump.Apply();
                                                output3 = crop.EncodeToPNG();
                                                if (File.Exists(persistentDataPath + "/Enhancements/" + currentRomName + "/Spr-" + md + ".png") == false)
                                                {
                                                    MyNes.NesEmu.PAUSED = true;
                                                    File.WriteAllBytes(persistentDataPath + "/Enhancements/" + currentRomName + "/Spr-" + md + ".png", output3);
                                                    Debug.Log("DUMPED : " + persistentDataPath + "/Enhancements/" + currentRomName + "/Spr-" + md + ".png");
                                                    MyNes.NesEmu.PAUSED = false;
                                                    JustDumped.Add(md);
                                                }

                                                else
                                                {
                                                    JustDumped.Add(md);
                                                }

                                            }
                                        }
                                    }
                                    bool found = false;
                                    for (int t = 0; t < TextureUpdateHash.Count; t++)
                                    {
                                        if (found == false)
                                        {
                                            /*if (Cspr.Length > 0)
                                            {

                                                if (!TextureUpdateHash[t].Contains("Spr-" + md))
                                                {

                                                    for (int c = Cspr.Length - 1; c >= 0; c--)
                                                    {

                                                        if (cs.Boundz.Contains(Cspr[c].transform.position))
                                                        {
                                                            if (Cspr[c] != spriteParent)
                                                            {
                                                                Cspr[c].transform.position = new Vector3(cs.Boundz.center.x + 0.25f, cs.Boundz.center.y - 0.50f, -2.97f + (cs.Boundz.center.x * -0.015f));
                                                                for (int s = 0; s < cs.SubTiles.Count; s++)
                                                                {
                                                                    if (cs.SubTiles[s].GetComponentInChildren<Renderer>() != null)
                                                                    {
                                                                        foreach (Renderer render in cs.SubTiles[s].transform.GetComponentsInChildren<Renderer>())
                                                                        {
                                                                            render.enabled = false;
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }/*
                                                            bool inside = false;
                                                            foreach (CombinedSprite s in CombinedSprites)
                                                            {

                                                                if (s.Boundz.Contains(Cspr[c].transform.position))
                                                                {
                                                                    inside = true;
                                                                }
                                                            }
                                                            if (inside == false)
                                                            {
                                                                //Destroy(Cspr[c]);
                                                            }
                                                    }
                                                }
                                                else if (TextureUpdateHash[t].Contains("Spr-" + md))
                                                {/*

                                                    for (int c = Cspr.Length - 1; c >= 0; c--)
                                                    {

                                                        if (cs.Boundz.Contains(Cspr[c].transform.position))
                                                        {
                                                            if (Cspr[c] != spriteParent)
                                                            {
                                                                //Destroy(Cspr[c]);
                                                            }
                                                        }
                                                    }
                                                    found = true;
                                                    GameObject CombinedSprite = GameObject.Instantiate(CombinedSpritePrefab, new Vector3(cs.Boundz.center.x + 0.25f, cs.Boundz.center.y - 0.50f, -2.97f + (cs.Boundz.center.x * -0.015f)), Quaternion.identity) as GameObject;
                                                    TextureUpdateColors[t].wrapMode = TextureWrapMode.Clamp;

                                                    CombinedSprite.GetComponent<Renderer>().material.mainTexture = TextureUpdateColors[t];
                                                    CombinedSprite.transform.localScale = new Vector3((TextureUpdateColors[t].width / 8) * 0.125f, -(TextureUpdateColors[t].height / 8) * 0.125f, 1); CombinedSprite.tag = "CombinedSprite";
                                                    CombinedSprite.name = "CSpr-" + md;
                                                    for (int s = 0; s < cs.SubTiles.Count; s++)
                                                    {
                                                        if (cs.SubTiles[s].GetComponentInChildren<Renderer>() != null)
                                                        {
                                                            foreach (Renderer render in cs.SubTiles[s].transform.GetComponentsInChildren<Renderer>())
                                                            {
                                                                render.enabled = false;
                                                            }
                                                        }
                                                    }
                                                    if (t < hasModelLoaded.Length && hasModelLoaded[t] == true)
                                                    {
                                                        Model = GameObject.Instantiate(TileModels[t], new Vector3(CombinedSprite.transform.position.x, CombinedSprite.transform.position.y - 1.5f, CombinedSprite.transform.position.z), Quaternion.identity) as GameObject;
                                                        Model.name = md + "Model";
                                                        Model.transform.SetParent(CombinedSprite.transform, false);
                                                        CombinedSprite.GetComponent<Renderer>().enabled = false;
                                                        foreach (Transform child in Model.transform)
                                                        {
                                                            child.GetComponent<Renderer>().enabled = true;
                                                            child.gameObject.layer = LayerMask.NameToLayer("Sprites");
                                                        }
                                                    }
                                                }


                                            }
                                            else
                                            {*/
                                            if (TextureUpdateHash[t].Contains("Spr-" + md))
                                            {

                                                found = true;
                                                GameObject CombinedSprite = GameObject.Instantiate(CombinedSpritePrefab, new Vector3(cs.Boundz.center.x + 0.25f, cs.Boundz.center.y - 0.50f, -2.97f + (cs.Boundz.center.x * -0.015f)), Quaternion.identity) as GameObject;
                                                TextureUpdateColors[t].wrapMode = TextureWrapMode.Clamp;

                                                CombinedSprite.GetComponent<Renderer>().material.mainTexture = TextureUpdateColors[t];
                                                CombinedSprite.transform.localScale = new Vector3((TextureUpdateColors[t].width / 8) * 0.125f, -(TextureUpdateColors[t].height / 8) * 0.125f, 1); CombinedSprite.tag = "CombinedSprite";
                                                CombinedSprite.name = "CSpr-" + md;
                                                for (int s = 0; s < cs.SubTiles.Count; s++)
                                                {
                                                    if (cs.SubTiles[s].GetComponentInChildren<Renderer>() != null)
                                                    {
                                                        foreach (Renderer render in cs.SubTiles[s].transform.GetComponentsInChildren<Renderer>())
                                                        {
                                                            render.enabled = false;
                                                        }
                                                    }
                                                }
                                                if (t < hasModelLoaded.Length && hasModelLoaded[t] == true)
                                                {
                                                    Model = GameObject.Instantiate(TileModels[t], new Vector3(CombinedSprite.transform.position.x, CombinedSprite.transform.position.y - 1.5f, CombinedSprite.transform.position.z), Quaternion.identity) as GameObject;
                                                    Model.name = md + "Model";
                                                    Model.transform.SetParent(CombinedSprite.transform, false);
                                                    CombinedSprite.GetComponent<Renderer>().enabled = false;
                                                    foreach (Transform child in Model.transform)
                                                    {
                                                        child.GetComponent<Renderer>().enabled = true;
                                                        child.gameObject.layer = LayerMask.NameToLayer("Sprites");
                                                    }
                                                }
                                            }
                                            //}
                                        }
                                    }
                                    if (found == false)
                                    {
                                        for (int t = 0; t < TextureUpdateHash.Count; t++)
                                        {
                                            if (found == false)
                                            {
                                                if (TextureUpdateHash[t].Contains(imghash))
                                                {
                                                    found = true;
                                                    GameObject CombinedSprite = GameObject.Instantiate(CombinedSpritePrefab, new Vector3(cs.Boundz.center.x + 0.25f, cs.Boundz.center.y - 0.50f, -2.97f + (cs.Boundz.center.x * -0.015f)), Quaternion.identity) as GameObject;
                                                    TextureUpdateColors[t].wrapMode = TextureWrapMode.Clamp;
                                                    CombinedSprite.GetComponent<Renderer>().material.mainTexture = TextureUpdateColors[t];
                                                    CombinedSprite.transform.localScale = new Vector3((TextureUpdateColors[t].width / 8) * 0.125f, -(TextureUpdateColors[t].height / 8) * 0.125f, 1); CombinedSprite.tag = "CombinedSprite";
                                                    CombinedSprite.name = "CSpr-" + imghash;
                                                    for (int s = 0; s < cs.SubTiles.Count; s++)
                                                    {
                                                        if (cs.SubTiles[s].GetComponentInChildren<Renderer>() != null)
                                                        {
                                                            foreach (Renderer render in cs.SubTiles[s].transform.GetComponentsInChildren<Renderer>())
                                                            {
                                                                render.enabled = false;
                                                            }
                                                        }
                                                    }
                                                    if (t < hasModelLoaded.Length && hasModelLoaded[t] == true)
                                                    {
                                                        Model = GameObject.Instantiate(TileModels[t], new Vector3(CombinedSprite.transform.position.x, CombinedSprite.transform.position.y - 1.5f, CombinedSprite.transform.position.z), Quaternion.identity) as GameObject;
                                                        Model.name = md + "Model";
                                                        Model.transform.SetParent(CombinedSprite.transform, false);
                                                        CombinedSprite.GetComponent<Renderer>().enabled = false;
                                                        foreach (Transform child in Model.transform)
                                                        {
                                                            child.GetComponent<Renderer>().enabled = true;
                                                            child.gameObject.layer = LayerMask.NameToLayer("Sprites");
                                                        }
                                                    }
                                                }

                                            }
                                            //}
                                        }
                                    }
                                    if (found == false)
                                    {
                                        for (int t = 0; t < TextureUpdateHash.Count; t++)
                                        {
                                            if (found == false)
                                            {
                                                if (TextureUpdateHash[t].Contains("Spr-" + fallBack + "_"))
                                                {
                                                    found = true;
                                                    GameObject CombinedSprite = GameObject.Instantiate(CombinedSpritePrefab, new Vector3(cs.Boundz.center.x + 0.25f, cs.Boundz.center.y - 0.50f, -2.97f + (cs.Boundz.center.x * -0.015f)), Quaternion.identity) as GameObject;
                                                    TextureUpdateColors[t].wrapMode = TextureWrapMode.Clamp;
                                                    CombinedSprite.GetComponent<Renderer>().material.mainTexture = TextureUpdateColors[t];
                                                    CombinedSprite.transform.localScale = new Vector3((TextureUpdateColors[t].width / 8) * 0.125f, -(TextureUpdateColors[t].height / 8) * 0.125f, 1); CombinedSprite.tag = "CombinedSprite";
                                                    CombinedSprite.name = "CSpr-" + fallBack;
                                                    for (int s = 0; s < cs.SubTiles.Count; s++)
                                                    {
                                                        if (cs.SubTiles[s].GetComponentInChildren<Renderer>() != null)
                                                        {
                                                            foreach (Renderer render in cs.SubTiles[s].transform.GetComponentsInChildren<Renderer>())
                                                            {
                                                                render.enabled = false;
                                                            }
                                                        }
                                                    }
                                                    if (t < hasModelLoaded.Length && hasModelLoaded[t] == true)
                                                    {
                                                        Model = GameObject.Instantiate(TileModels[t], new Vector3(CombinedSprite.transform.position.x, CombinedSprite.transform.position.y - 1.5f, CombinedSprite.transform.position.z), Quaternion.identity) as GameObject;
                                                        Model.name = md + "Model";
                                                        Model.transform.SetParent(CombinedSprite.transform, false);
                                                        CombinedSprite.GetComponent<Renderer>().enabled = false;
                                                        foreach (Transform child in Model.transform)
                                                        {
                                                            child.GetComponent<Renderer>().enabled = true;
                                                            child.gameObject.layer = LayerMask.NameToLayer("Sprites");
                                                        }
                                                    }
                                                }

                                            }
                                            //}
                                        }
                                    }
                                }


                            }
                        }
                    }
                    else if (cs.Palette == 2)
                    {
                        if (cs.Boundz.size.x >= 1 && cs.Boundz.size.y >= 1 && cs.Boundz.min.x > 2 && cs.Boundz.max.x + todump.width < 245 && cs.Boundz.min.y > 2 && cs.Boundz.max.y + todump.height < 239 && ((cs.Boundz.min.x) * 8) + todump.width < 245 && (int)Math.Ceiling(((cs.Boundz.min.y) * 8) - 4) > 0)
                        {
                            if ((int)Math.Ceiling(((cs.Boundz.max.x) * 8)) < 250 && (int)Math.Ceiling(((cs.Boundz.max.y) * 8)) < 235)
                            {


                                todump.Resize((int)(cs.Boundz.size.x + 1) * 8, (int)((cs.Boundz.size.y + 1) * 8));

                            todump.SetPixels(flippyP3.GetPixels((int)Math.Ceiling(((cs.Boundz.min.x) * 8)), (int)Math.Ceiling(((cs.Boundz.min.y) * 8)), todump.width, todump.height));

                            todump.Apply();
                            tempcspr = null;

                            toCrop = flippyP3.GetPixels((int)Math.Ceiling(((cs.Boundz.min.x) * 8)), (int)Math.Ceiling(((cs.Boundz.min.y) * 8)), todump.width, todump.height);
                            Vector2 min = new Vector2(todump.width, todump.height);
                            Vector2 max = new Vector2(0, 0);
                            for (int x = 0; x < todump.width; x++)
                            {
                                for (int y = 0; y < todump.height; y++)
                                {
                                    Color pixelColor = toCrop[x + (y * todump.width)];
                                    if (pixelColor.a > 0.2f)
                                    {
                                        if (x <= (int)min.x) min.x = x;
                                        if (y <= (int)min.y) min.y = y;

                                        if (x >= (int)max.x) max.x = x;
                                        if (y >= (int)max.y) max.y = y;
                                    }
                                }
                            }

                            if (max.x < min.x)
                            {
                                int swap = (int)max.x;
                                max.x = (int)min.x;
                                min.x = swap;
                            }
                            if (max.y < min.y)
                            {
                                int swap = (int)max.y;
                                max.y = (int)min.y;
                                min.y = swap;
                            }
                            if ((int)Math.Abs(max.x - min.x) == 0)
                            {
                                max.x += 8;

                            }
                            if ((int)Math.Abs(max.y - min.y) == 0)
                            {
                                max.y += 8;
                            }
                                if (min.x != max.x && min.y != max.y)
                                {

                                    crop.Resize((int)Math.Abs(max.x - min.x), (int)Math.Abs(max.y - min.y));

                                    crop.SetPixels(todump.GetPixels((int)min.x, (int)min.y, (int)Math.Abs(max.x - min.x), (int)Math.Abs(max.y - min.y)));
                                    crop.Apply();
                                    //int cnt = 0;
                                    //for (int x = (int)min.x; x < (int)max.x; x++)
                                    //{
                                    //    for (int y = (int)min.y; y < (int)max.y; y++)
                                    ///    {
                                    //        crop[cnt++] = toCrop[x + (y * todump.width)];

                                    //    }
                                    //}



                                    bool notsolid = false;
                                    tempcspr = crop.GetPixels();
                                    for (int cm = 1; cm < tempcspr.Length; cm++)
                                    {
                                        if (tempcspr[cm] != tempcspr[0])
                                        {
                                            notsolid = true;
                                        }
                                    }
                                    /* foreach (GameObject n in cs.SubTiles)
                                    {

                                        if (n.GetComponentInChildren<Renderer>() != null)
                                        {
                                            foreach (Renderer render in n.transform.GetComponentsInChildren<Renderer>())
                                            {
                                                if (render.enabled != false && render.gameObject.transform.parent == n.transform)
                                                {

                                                    int intname = 0;
                                                    int.TryParse(n.name, out intname);
                                                    if (intname != 0)
                                                    {
                                                        names.Add(intname);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    int[] nameArray = names.ToArray();
                                    Array.Sort(nameArray);
                                    string md = GetHashCodeTile(nameArray).ToString(); */
                                    //string md = GetHashCodeTileColors(todump.GetPixels()).ToString();
                                    md = "_";
                                    stNames.Clear();
                                    for (int st = 0; st < cs.SubTiles.Count; st++)
                                    {
                                        if (cs.SubTiles[st].name.Contains("_") && !md.Contains("_" + cs.SubTiles[st].name.Split('_')[0] + "_" + cs.SubTiles[st].name.Split('_')[1]))
                                        {
                                            stNames.Add(cs.SubTiles[st].name.Split('_')[0] + "_" + cs.SubTiles[st].name.Split('_')[3] + "_" + cs.SubTiles[st].name.Split('_')[4]);
                                        }
                                    }
                                    stNames.Sort();
                                    for (int st = 0; st < stNames.Count; st++)
                                    {
                                        md += stNames[st] + "_";
                                    }
                                    fallBack = cs.Palette + "_" + GetHashCodeFileName(md);
                                    imghash = "h" + GetHashCodeTileColors(tempcspr);
                                    md = fallBack + "_" + imghash;
                                    //string md = cs.Palette + "_" + GetHashCodeTileColors(tempcspr).ToString();
                                    if (notsolid == true)
                                    {
                                        if (RxScriptInit.dumpingEnabled == true)
                                        {
                                            if (JustDumped.Contains(md) == false && !TextureUpdateHash.Contains("Spr-" + md))
                                            {


                                                //CroppedDump.Resize(crop.width * 8, crop.height * 8);

                                                //CroppedDump.SetPixels(resizePixels(todump.GetPixels((int)min.x, (int)min.y, (int)Math.Abs(max.x - min.x), (int)Math.Abs(max.y - min.y)), crop.width, crop.height, crop.width * 8, crop.height * 8));
                                                //CroppedDump.Apply();
                                                output3 = crop.EncodeToPNG();
                                                if (File.Exists(persistentDataPath + "/Enhancements/" + currentRomName + "/Spr-" + md + ".png") == false)
                                                {
                                                    MyNes.NesEmu.PAUSED = true;
                                                    File.WriteAllBytes(persistentDataPath + "/Enhancements/" + currentRomName + "/Spr-" + md + ".png", output3);
                                                    Debug.Log("DUMPED : " + persistentDataPath + "/Enhancements/" + currentRomName + "/Spr-" + md + ".png");
                                                    MyNes.NesEmu.PAUSED = false;
                                                    JustDumped.Add(md);
                                                }

                                                else
                                                {
                                                    JustDumped.Add(md);
                                                }

                                            }
                                        }
                                    }
                                    bool found = false;
                                    for (int t = 0; t < TextureUpdateHash.Count; t++)
                                    {
                                        if (found == false)
                                        {
                                            /* if (Cspr.Length > 0)
                                             {

                                                 if (!TextureUpdateHash[t].Contains("Spr-" + md))
                                                 {

                                                     for (int c = Cspr.Length - 1; c >= 0; c--)
                                                     {

                                                         if (cs.Boundz.Contains(Cspr[c].transform.position))
                                                         {
                                                             if (Cspr[c] != spriteParent)
                                                             {
                                                                 Cspr[c].transform.position = new Vector3(cs.Boundz.center.x + 0.25f, cs.Boundz.center.y - 0.50f, -2.97f + (cs.Boundz.center.x * -0.015f));
                                                                 for (int s = 0; s < cs.SubTiles.Count; s++)
                                                                 {
                                                                     if (cs.SubTiles[s].GetComponentInChildren<Renderer>() != null)
                                                                     {
                                                                         foreach (Renderer render in cs.SubTiles[s].transform.GetComponentsInChildren<Renderer>())
                                                                         {
                                                                             render.enabled = false;
                                                                         }
                                                                     }
                                                                 }
                                                             }
                                                         }

                                                         /*
                                                             bool inside = false;
                                                             foreach (CombinedSprite s in CombinedSprites)
                                                             {

                                                                 if (s.Boundz.Contains(Cspr[c].transform.position))
                                                                 {
                                                                     inside = true;
                                                                 }
                                                             }
                                                             if (inside == false)
                                                             {
                                                                 //Destroy(Cspr[c]);
                                                             }

                                                     }
                                                 }
                                                 else if (TextureUpdateHash[t].Contains("Spr-" + md))
                                         {

                                                     for (int c = Cspr.Length - 1; c >= 0; c--)
                                                     {

                                                         if (cs.Boundz.Contains(Cspr[c].transform.position))
                                                         {
                                                             if (Cspr[c] != spriteParent)
                                                             {
                                                                 //Destroy(Cspr[c]);
                                                             }
                                                         }
                                                     }
                                             found = true;
                                                     GameObject CombinedSprite = GameObject.Instantiate(CombinedSpritePrefab, new Vector3(cs.Boundz.center.x + 0.25f, cs.Boundz.center.y - 0.50f, -2.97f + (cs.Boundz.center.x * -0.015f)), Quaternion.identity) as GameObject;
                                                     TextureUpdateColors[t].wrapMode = TextureWrapMode.Clamp;

                                                     CombinedSprite.GetComponent<Renderer>().material.mainTexture = TextureUpdateColors[t];
                                                     CombinedSprite.transform.localScale = new Vector3((TextureUpdateColors[t].width / 8) * 0.125f, -(TextureUpdateColors[t].height / 8) * 0.125f, 1); CombinedSprite.tag = "CombinedSprite";
                                                     CombinedSprite.name = "CSpr-" + md;
                                                     for (int s = 0; s < cs.SubTiles.Count; s++)
                                                     {
                                                         if (cs.SubTiles[s].GetComponentInChildren<Renderer>() != null)
                                                         {
                                                             foreach (Renderer render in cs.SubTiles[s].transform.GetComponentsInChildren<Renderer>())
                                                             {
                                                                 render.enabled = false;
                                                             }
                                                         }
                                                     }
                                                     if (t < hasModelLoaded.Length && hasModelLoaded[t] == true)
                                                     {
                                                         Model = GameObject.Instantiate(TileModels[t], new Vector3(CombinedSprite.transform.position.x, CombinedSprite.transform.position.y - 1.5f, CombinedSprite.transform.position.z), Quaternion.identity) as GameObject;
                                                         Model.name = md + "Model";
                                                         Model.transform.SetParent(CombinedSprite.transform, false);
                                                         CombinedSprite.GetComponent<Renderer>().enabled = false;
                                                         foreach (Transform child in Model.transform)
                                                         {
                                                             child.GetComponent<Renderer>().enabled = true;
                                                             child.gameObject.layer = LayerMask.NameToLayer("Sprites");
                                                         }
                                                     }
                                                 }


                                             }
                                             else
                                             {*/
                                            if (TextureUpdateHash[t].Contains("Spr-" + md))
                                            {

                                                found = true;
                                                GameObject CombinedSprite = GameObject.Instantiate(CombinedSpritePrefab, new Vector3(cs.Boundz.center.x + 0.25f, cs.Boundz.center.y - 0.50f, -2.97f + (cs.Boundz.center.x * -0.015f)), Quaternion.identity) as GameObject;
                                                TextureUpdateColors[t].wrapMode = TextureWrapMode.Clamp;

                                                CombinedSprite.GetComponent<Renderer>().material.mainTexture = TextureUpdateColors[t];
                                                CombinedSprite.transform.localScale = new Vector3((TextureUpdateColors[t].width / 8) * 0.125f, -(TextureUpdateColors[t].height / 8) * 0.125f, 1); CombinedSprite.tag = "CombinedSprite";
                                                CombinedSprite.name = "CSpr-" + md;
                                                for (int s = 0; s < cs.SubTiles.Count; s++)
                                                {
                                                    if (cs.SubTiles[s].GetComponentInChildren<Renderer>() != null)
                                                    {
                                                        foreach (Renderer render in cs.SubTiles[s].transform.GetComponentsInChildren<Renderer>())
                                                        {
                                                            render.enabled = false;
                                                        }
                                                    }
                                                }
                                                if (t < hasModelLoaded.Length && hasModelLoaded[t] == true)
                                                {
                                                    Model = GameObject.Instantiate(TileModels[t], new Vector3(CombinedSprite.transform.position.x, CombinedSprite.transform.position.y - 1.5f, CombinedSprite.transform.position.z), Quaternion.identity) as GameObject;
                                                    Model.name = md + "Model";
                                                    Model.transform.SetParent(CombinedSprite.transform, false);
                                                    CombinedSprite.GetComponent<Renderer>().enabled = false;
                                                    foreach (Transform child in Model.transform)
                                                    {
                                                        child.GetComponent<Renderer>().enabled = true;
                                                        child.gameObject.layer = LayerMask.NameToLayer("Sprites");
                                                    }
                                                }
                                            }
                                            //}
                                        }
                                    }
                                    if (found == false)
                                    {
                                        for (int t = 0; t < TextureUpdateHash.Count; t++)
                                        {
                                            if (found == false)
                                            {
                                                if (TextureUpdateHash[t].Contains(imghash))
                                                {
                                                    found = true;
                                                    GameObject CombinedSprite = GameObject.Instantiate(CombinedSpritePrefab, new Vector3(cs.Boundz.center.x + 0.25f, cs.Boundz.center.y - 0.50f, -2.97f + (cs.Boundz.center.x * -0.015f)), Quaternion.identity) as GameObject;
                                                    TextureUpdateColors[t].wrapMode = TextureWrapMode.Clamp;
                                                    CombinedSprite.GetComponent<Renderer>().material.mainTexture = TextureUpdateColors[t];
                                                    CombinedSprite.transform.localScale = new Vector3((TextureUpdateColors[t].width / 8) * 0.125f, -(TextureUpdateColors[t].height / 8) * 0.125f, 1); CombinedSprite.tag = "CombinedSprite";
                                                    CombinedSprite.name = "CSpr-" + imghash;
                                                    for (int s = 0; s < cs.SubTiles.Count; s++)
                                                    {
                                                        if (cs.SubTiles[s].GetComponentInChildren<Renderer>() != null)
                                                        {
                                                            foreach (Renderer render in cs.SubTiles[s].transform.GetComponentsInChildren<Renderer>())
                                                            {
                                                                render.enabled = false;
                                                            }
                                                        }
                                                    }
                                                    if (t < hasModelLoaded.Length && hasModelLoaded[t] == true)
                                                    {
                                                        Model = GameObject.Instantiate(TileModels[t], new Vector3(CombinedSprite.transform.position.x, CombinedSprite.transform.position.y - 1.5f, CombinedSprite.transform.position.z), Quaternion.identity) as GameObject;
                                                        Model.name = md + "Model";
                                                        Model.transform.SetParent(CombinedSprite.transform, false);
                                                        CombinedSprite.GetComponent<Renderer>().enabled = false;
                                                        foreach (Transform child in Model.transform)
                                                        {
                                                            child.GetComponent<Renderer>().enabled = true;
                                                            child.gameObject.layer = LayerMask.NameToLayer("Sprites");
                                                        }
                                                    }
                                                }

                                            }
                                            //}
                                        }
                                    }
                                    if (found == false)
                                    {
                                        for (int t = 0; t < TextureUpdateHash.Count; t++)
                                        {
                                            if (found == false)
                                            {
                                                if (TextureUpdateHash[t].Contains("Spr-" + fallBack + "_"))
                                                {
                                                    found = true;
                                                    GameObject CombinedSprite = GameObject.Instantiate(CombinedSpritePrefab, new Vector3(cs.Boundz.center.x + 0.25f, cs.Boundz.center.y - 0.50f, -2.97f + (cs.Boundz.center.x * -0.015f)), Quaternion.identity) as GameObject;
                                                    TextureUpdateColors[t].wrapMode = TextureWrapMode.Clamp;
                                                    CombinedSprite.GetComponent<Renderer>().material.mainTexture = TextureUpdateColors[t];
                                                    CombinedSprite.transform.localScale = new Vector3((TextureUpdateColors[t].width / 8) * 0.125f, -(TextureUpdateColors[t].height / 8) * 0.125f, 1); CombinedSprite.tag = "CombinedSprite";
                                                    CombinedSprite.name = "CSpr-" + fallBack;
                                                    for (int s = 0; s < cs.SubTiles.Count; s++)
                                                    {
                                                        if (cs.SubTiles[s].GetComponentInChildren<Renderer>() != null)
                                                        {
                                                            foreach (Renderer render in cs.SubTiles[s].transform.GetComponentsInChildren<Renderer>())
                                                            {
                                                                render.enabled = false;
                                                            }
                                                        }
                                                    }
                                                    if (t < hasModelLoaded.Length && hasModelLoaded[t] == true)
                                                    {
                                                        Model = GameObject.Instantiate(TileModels[t], new Vector3(CombinedSprite.transform.position.x, CombinedSprite.transform.position.y - 1.5f, CombinedSprite.transform.position.z), Quaternion.identity) as GameObject;
                                                        Model.name = md + "Model";
                                                        Model.transform.SetParent(CombinedSprite.transform, false);
                                                        CombinedSprite.GetComponent<Renderer>().enabled = false;
                                                        foreach (Transform child in Model.transform)
                                                        {
                                                            child.GetComponent<Renderer>().enabled = true;
                                                            child.gameObject.layer = LayerMask.NameToLayer("Sprites");
                                                        }
                                                    }
                                                }

                                            }
                                            //}
                                        }
                                    }
                                }


                            }
                        }
                    }
                    else if (cs.Palette == 3)
                    {
                        if (cs.Boundz.size.x >= 1 && cs.Boundz.size.y >= 1 && cs.Boundz.min.x > 2 && cs.Boundz.max.x + todump.width < 245 && cs.Boundz.min.y > 2 && cs.Boundz.max.y + todump.height < 239 && ((cs.Boundz.min.x) * 8) + todump.width < 245 && (int)Math.Ceiling(((cs.Boundz.min.y) * 8) - 4) > 0)
                        {

                            if ((int)Math.Ceiling(((cs.Boundz.max.x) * 8)) < 250 && (int)Math.Ceiling(((cs.Boundz.max.y) * 8)) < 235)
                            {


                                todump.Resize((int)(cs.Boundz.size.x + 1) * 8, (int)((cs.Boundz.size.y + 1) * 8));

                                todump.SetPixels(flippyP4.GetPixels((int)Math.Ceiling(((cs.Boundz.min.x) * 8)), (int)Math.Ceiling(((cs.Boundz.min.y) * 8)), todump.width, todump.height));

                                todump.Apply();
                                tempcspr = null;

                                toCrop = flippyP4.GetPixels((int)Math.Ceiling(((cs.Boundz.min.x) * 8)), (int)Math.Ceiling(((cs.Boundz.min.y) * 8)), todump.width, todump.height);
                                Vector2 min = new Vector2(todump.width, todump.height);
                                Vector2 max = new Vector2(0, 0);
                                for (int x = 0; x < todump.width; x++)
                                {
                                    for (int y = 0; y < todump.height; y++)
                                    {
                                        Color pixelColor = toCrop[x + (y * todump.width)];
                                        if (pixelColor.a > 0.2f)
                                        {
                                            if (x <= (int)min.x) min.x = x;
                                            if (y <= (int)min.y) min.y = y;

                                            if (x >= (int)max.x) max.x = x;
                                            if (y >= (int)max.y) max.y = y;
                                        }
                                    }
                                }

                                if (max.x < min.x)
                                {
                                    int swap = (int)max.x;
                                    max.x = (int)min.x;
                                    min.x = swap;
                                }
                                if (max.y < min.y)
                                {
                                    int swap = (int)max.y;
                                    max.y = (int)min.y;
                                    min.y = swap;
                                }

                                if ((int)Math.Abs(max.x - min.x) == 0)
                                {
                                    max.x += 8;

                                }
                                if ((int)Math.Abs(max.y - min.y) == 0)
                                {
                                    max.y += 8;
                                }

                                if (min.x != max.x && min.y != max.y)
                                {

                                    crop.Resize((int)Math.Abs(max.x - min.x), (int)Math.Abs(max.y - min.y));

                                    crop.SetPixels(todump.GetPixels((int)min.x, (int)min.y, (int)Math.Abs(max.x - min.x), (int)Math.Abs(max.y - min.y)));
                                    crop.Apply();
                                    //int cnt = 0;
                                    //for (int x = (int)min.x; x < (int)max.x; x++)
                                    //{
                                    //    for (int y = (int)min.y; y < (int)max.y; y++)
                                    ///    {
                                    //        crop[cnt++] = toCrop[x + (y * todump.width)];

                                    //    }
                                    //}



                                    bool notsolid = false;
                                    tempcspr = crop.GetPixels();
                                    for (int cm = 1; cm < tempcspr.Length; cm++)
                                    {
                                        if (tempcspr[cm] != tempcspr[0])
                                        {
                                            notsolid = true;
                                        }
                                    }
                                    /* foreach (GameObject n in cs.SubTiles)
                                    {

                                        if (n.GetComponentInChildren<Renderer>() != null)
                                        {
                                            foreach (Renderer render in n.transform.GetComponentsInChildren<Renderer>())
                                            {
                                                if (render.enabled != false && render.gameObject.transform.parent == n.transform)
                                                {

                                                    int intname = 0;
                                                    int.TryParse(n.name, out intname);
                                                    if (intname != 0)
                                                    {
                                                        names.Add(intname);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    int[] nameArray = names.ToArray();
                                    Array.Sort(nameArray);
                                    string md = GetHashCodeTile(nameArray).ToString(); */
                                    //string md = GetHashCodeTileColors(todump.GetPixels()).ToString();
                                    md = "_";
                                    stNames.Clear();
                                    for (int st = 0; st < cs.SubTiles.Count; st++)
                                    {
                                        if (cs.SubTiles[st].name.Contains("_") && !md.Contains("_" + cs.SubTiles[st].name.Split('_')[0] + "_" + cs.SubTiles[st].name.Split('_')[1]))
                                        {
                                            stNames.Add(cs.SubTiles[st].name.Split('_')[0] + "_" + cs.SubTiles[st].name.Split('_')[3] + "_" + cs.SubTiles[st].name.Split('_')[4]);
                                        }
                                    }
                                    stNames.Sort();
                                    for (int st = 0; st < stNames.Count; st++)
                                    {
                                        md += stNames[st] + "_";
                                    }
                                    fallBack = cs.Palette + "_" + GetHashCodeFileName(md);
                                    imghash = "h" + GetHashCodeTileColors(tempcspr);
                                    md = fallBack + "_" + imghash;
                                    //string md = cs.Palette + "_" + GetHashCodeTileColors(tempcspr).ToString();
                                    if (notsolid == true)
                                    {
                                        if (RxScriptInit.dumpingEnabled == true)
                                        {
                                            if (JustDumped.Contains(md) == false && !TextureUpdateHash.Contains("Spr-" + md))
                                            {


                                                //CroppedDump.Resize(crop.width * 8, crop.height * 8);

                                                //CroppedDump.SetPixels(resizePixels(todump.GetPixels((int)min.x, (int)min.y, (int)Math.Abs(max.x - min.x), (int)Math.Abs(max.y - min.y)), crop.width, crop.height, crop.width * 8, crop.height * 8));
                                                //CroppedDump.Apply();
                                                output3 = crop.EncodeToPNG();
                                                if (File.Exists(persistentDataPath + "/Enhancements/" + currentRomName + "/Spr-" + md + ".png") == false)
                                                {
                                                    MyNes.NesEmu.PAUSED = true;
                                                    File.WriteAllBytes(persistentDataPath + "/Enhancements/" + currentRomName + "/Spr-" + md + ".png", output3);
                                                    Debug.Log("DUMPED : " + persistentDataPath + "/Enhancements/" + currentRomName + "/Spr-" + md + ".png");
                                                    MyNes.NesEmu.PAUSED = false;
                                                    JustDumped.Add(md);
                                                }

                                                else
                                                {
                                                    JustDumped.Add(md);
                                                }

                                            }
                                        }
                                    }
                                    bool found = false;
                                    for (int t = 0; t < TextureUpdateHash.Count; t++)
                                    {
                                        if (found == false)
                                        {
                                            /* if (Cspr.Length > 0)
                                             {

                                                 if (!TextureUpdateHash[t].Contains("Spr-" + md))
                                                 {

                                                     for (int c = Cspr.Length - 1; c >= 0; c--)
                                                     {

                                                         if (cs.Boundz.Contains(Cspr[c].transform.position))
                                                         {
                                                             if (Cspr[c] != spriteParent)
                                                             {
                                                                 Cspr[c].transform.position = new Vector3(cs.Boundz.center.x + 0.25f, cs.Boundz.center.y - 0.50f, -2.97f + (cs.Boundz.center.x * -0.015f));
                                                                 for (int s = 0; s < cs.SubTiles.Count; s++)
                                                                 {
                                                                     if (cs.SubTiles[s].GetComponentInChildren<Renderer>() != null)
                                                                     {
                                                                         foreach (Renderer render in cs.SubTiles[s].transform.GetComponentsInChildren<Renderer>())
                                                                         {
                                                                             render.enabled = false;
                                                                         }
                                                                     }
                                                                 }
                                                             }
                                                         }
                                                         /*
                                                         bool inside = false;
                                                         foreach (CombinedSprite s in CombinedSprites)
                                                         {

                                                             if (s.Boundz.Contains(Cspr[c].transform.position))
                                                             {
                                                                 inside = true;
                                                             }
                                                         }
                                                         if (inside == false)
                                                         {
                                                             //Destroy(Cspr[c]);
                                                         }
                                                     }
                                                 }
                                                 else if (TextureUpdateHash[t].Contains("Spr-" + md))
                                                 {
             /*

                                                     for (int c = Cspr.Length - 1; c >= 0; c--)
                                                     {
                                                         if (cs.Boundz.Contains(Cspr[c].transform.position))
                                                         {
                                                             if (Cspr[c] != spriteParent)
                                                             {
                                                                 //Destroy(Cspr[c]);
                                                             }
                                                         }
                                                     }
                                                     found = true;
                                                     GameObject CombinedSprite = GameObject.Instantiate(CombinedSpritePrefab, new Vector3(cs.Boundz.center.x + 0.25f, cs.Boundz.center.y - 0.50f, -2.97f + (cs.Boundz.center.x * -0.015f)), Quaternion.identity) as GameObject;
                                                     TextureUpdateColors[t].wrapMode = TextureWrapMode.Clamp;

                                                     CombinedSprite.GetComponent<Renderer>().material.mainTexture = TextureUpdateColors[t];
                                                     CombinedSprite.transform.localScale = new Vector3((TextureUpdateColors[t].width / 8) * 0.125f, -(TextureUpdateColors[t].height / 8) * 0.125f, 1);
                                                     CombinedSprite.tag = "CombinedSprite";
                                                     CombinedSprite.name = "CSpr-" + md;
                                                     for (int s = 0; s < cs.SubTiles.Count; s++)
                                                     {
                                                         if (cs.SubTiles[s].GetComponentInChildren<Renderer>() != null)
                                                         {
                                                             foreach (Renderer render in cs.SubTiles[s].transform.GetComponentsInChildren<Renderer>())
                                                             {
                                                                 render.enabled = false;
                                                             }
                                                         }
                                                     }
                                                     if (t < hasModelLoaded.Length && hasModelLoaded[t] == true)
                                                     {
                                                         Model = GameObject.Instantiate(TileModels[t], new Vector3(CombinedSprite.transform.position.x, CombinedSprite.transform.position.y - 1.5f, CombinedSprite.transform.position.z), Quaternion.identity) as GameObject;
                                                         Model.name = md + "Model";
                                                         Model.transform.SetParent(CombinedSprite.transform, false);
                                                         CombinedSprite.GetComponent<Renderer>().enabled = false;
                                                         foreach (Transform child in Model.transform)
                                                         {
                                                             child.GetComponent<Renderer>().enabled = true;
                                                             child.gameObject.layer = LayerMask.NameToLayer("Sprites");
                                                         }
                                                     }
                                                 }


                                             }
                                             else
                                             {*/
                                            if (TextureUpdateHash[t].Contains("Spr-" + md))
                                            {

                                                found = true;
                                                GameObject CombinedSprite = GameObject.Instantiate(CombinedSpritePrefab, new Vector3(cs.Boundz.center.x + 0.25f, cs.Boundz.center.y - 0.50f, -2.97f + (cs.Boundz.center.x * -0.015f)), Quaternion.identity) as GameObject;
                                                TextureUpdateColors[t].wrapMode = TextureWrapMode.Clamp;

                                                CombinedSprite.GetComponent<Renderer>().material.mainTexture = TextureUpdateColors[t];
                                                CombinedSprite.transform.localScale = new Vector3((TextureUpdateColors[t].width / 8) * 0.125f, -(TextureUpdateColors[t].height / 8) * 0.125f, 1);
                                                CombinedSprite.tag = "CombinedSprite";
                                                CombinedSprite.name = "CSpr-" + md;
                                                for (int s = 0; s < cs.SubTiles.Count; s++)
                                                {
                                                    if (cs.SubTiles[s].GetComponentInChildren<Renderer>() != null)
                                                    {
                                                        foreach (Renderer render in cs.SubTiles[s].transform.GetComponentsInChildren<Renderer>())
                                                        {
                                                            render.enabled = false;
                                                        }
                                                    }
                                                }
                                                if (t < hasModelLoaded.Length && hasModelLoaded[t] == true)
                                                {
                                                    Model = GameObject.Instantiate(TileModels[t], new Vector3(CombinedSprite.transform.position.x, CombinedSprite.transform.position.y - 1.5f, CombinedSprite.transform.position.z), Quaternion.identity) as GameObject;
                                                    Model.name = md + "Model";
                                                    Model.transform.SetParent(CombinedSprite.transform, false);
                                                    CombinedSprite.GetComponent<Renderer>().enabled = false;
                                                    foreach (Transform child in Model.transform)
                                                    {
                                                        child.GetComponent<Renderer>().enabled = true;
                                                        child.gameObject.layer = LayerMask.NameToLayer("Sprites");
                                                    }
                                                }
                                            }
                                            //}
                                        }
                                    }
                                    if (found == false)
                                    {
                                        for (int t = 0; t < TextureUpdateHash.Count; t++)
                                        {
                                            if (found == false)
                                            {
                                                if (TextureUpdateHash[t].Contains(imghash))
                                                {
                                                    found = true;
                                                    GameObject CombinedSprite = GameObject.Instantiate(CombinedSpritePrefab, new Vector3(cs.Boundz.center.x + 0.25f, cs.Boundz.center.y - 0.50f, -2.97f + (cs.Boundz.center.x * -0.015f)), Quaternion.identity) as GameObject;
                                                    TextureUpdateColors[t].wrapMode = TextureWrapMode.Clamp;
                                                    CombinedSprite.GetComponent<Renderer>().material.mainTexture = TextureUpdateColors[t];
                                                    CombinedSprite.transform.localScale = new Vector3((TextureUpdateColors[t].width / 8) * 0.125f, -(TextureUpdateColors[t].height / 8) * 0.125f, 1); CombinedSprite.tag = "CombinedSprite";
                                                    CombinedSprite.name = "CSpr-" + imghash;
                                                    for (int s = 0; s < cs.SubTiles.Count; s++)
                                                    {
                                                        if (cs.SubTiles[s].GetComponentInChildren<Renderer>() != null)
                                                        {
                                                            foreach (Renderer render in cs.SubTiles[s].transform.GetComponentsInChildren<Renderer>())
                                                            {
                                                                render.enabled = false;
                                                            }
                                                        }
                                                    }
                                                    if (t < hasModelLoaded.Length && hasModelLoaded[t] == true)
                                                    {
                                                        Model = GameObject.Instantiate(TileModels[t], new Vector3(CombinedSprite.transform.position.x, CombinedSprite.transform.position.y - 1.5f, CombinedSprite.transform.position.z), Quaternion.identity) as GameObject;
                                                        Model.name = md + "Model";
                                                        Model.transform.SetParent(CombinedSprite.transform, false);
                                                        CombinedSprite.GetComponent<Renderer>().enabled = false;
                                                        foreach (Transform child in Model.transform)
                                                        {
                                                            child.GetComponent<Renderer>().enabled = true;
                                                            child.gameObject.layer = LayerMask.NameToLayer("Sprites");
                                                        }
                                                    }
                                                }

                                            }
                                            //}
                                        }
                                    }
                                    if (found == false)
                                    {
                                        for (int t = 0; t < TextureUpdateHash.Count; t++)
                                        {
                                            if (found == false)
                                            {
                                                if (TextureUpdateHash[t].Contains("Spr-" + fallBack + "_"))
                                                {
                                                    found = true;
                                                    GameObject CombinedSprite = GameObject.Instantiate(CombinedSpritePrefab, new Vector3(cs.Boundz.center.x + 0.25f, cs.Boundz.center.y - 0.50f, -2.97f + (cs.Boundz.center.x * -0.015f)), Quaternion.identity) as GameObject;
                                                    TextureUpdateColors[t].wrapMode = TextureWrapMode.Clamp;
                                                    CombinedSprite.GetComponent<Renderer>().material.mainTexture = TextureUpdateColors[t];
                                                    CombinedSprite.transform.localScale = new Vector3((TextureUpdateColors[t].width / 8) * 0.125f, -(TextureUpdateColors[t].height / 8) * 0.125f, 1); CombinedSprite.tag = "CombinedSprite";
                                                    CombinedSprite.name = "CSpr-" + fallBack;
                                                    for (int s = 0; s < cs.SubTiles.Count; s++)
                                                    {
                                                        if (cs.SubTiles[s].GetComponentInChildren<Renderer>() != null)
                                                        {
                                                            foreach (Renderer render in cs.SubTiles[s].transform.GetComponentsInChildren<Renderer>())
                                                            {
                                                                render.enabled = false;
                                                            }
                                                        }
                                                    }
                                                    if (t < hasModelLoaded.Length && hasModelLoaded[t] == true)
                                                    {
                                                        Model = GameObject.Instantiate(TileModels[t], new Vector3(CombinedSprite.transform.position.x, CombinedSprite.transform.position.y - 1.5f, CombinedSprite.transform.position.z), Quaternion.identity) as GameObject;
                                                        Model.name = md + "Model";
                                                        Model.transform.SetParent(CombinedSprite.transform, false);
                                                        CombinedSprite.GetComponent<Renderer>().enabled = false;
                                                        foreach (Transform child in Model.transform)
                                                        {
                                                            child.GetComponent<Renderer>().enabled = true;
                                                            child.gameObject.layer = LayerMask.NameToLayer("Sprites");
                                                        }
                                                    }
                                                }

                                            }
                                            //}
                                        }
                                    }
                                }
                            }

                        }
                    }/*
                if (CombinedSprites.Count > 0)
                {
                    foreach (CombinedSprite s in CombinedSprites)
                    {
                        if (previousFrameCombinedSprites.Count > 0)
                        {
                            foreach (CombinedSprite p in previousFrameCombinedSprites)
                            {
                                if (s.Holding != null && s.Holding.name.Contains("CSpr-") && s.Holding == p.Holding)
                                {
                                    if (p.Boundz.Contains(s.Boundz.ClosestPoint(p.Boundz.center)))
                                    {
                                        s.Destroy = false;
                                        p.Destroy = false;
                                    }
                                }
                            }
                        }
                    }*/
                }
                //}
                /*for (int c = CombinedSprites.Count - 1; c >= 0; c--)
                {
                    if (CombinedSprites[c] != null && CombinedSprites[c].Destroy == true)
                    {

                        if (CombinedSprites[c].Holding != null)
                        {
                            Destroy(CombinedSprites[c].Holding);
                        }

                        CombinedSprites.RemoveAt(c);
                    }

                }

                for (int c = previousFrameCombinedSprites.Count - 1; c >= 0; c--)
                {
                    if (previousFrameCombinedSprites[c] != null && previousFrameCombinedSprites[c].Destroy == true)
                    {
                        if (previousFrameCombinedSprites[c].Holding != null)
                        {
                            Destroy(previousFrameCombinedSprites[c].Holding);
                        }

                        previousFrameCombinedSprites.RemoveAt(c);
                    }

                }

                for (int c = Cspr.Length - 1; c >= 0; c--)
                {
                    bool destroy = true;
                    for (int p = previousFrameCombinedSprites.Count - 1; p >= 0; p--)
                    {
                        for (int cs = CombinedSprites.Count - 1; cs >= 0; cs--)
                        {
                            if (Cspr[c] == CombinedSprites[cs].Holding || Cspr[c] == previousFrameCombinedSprites[p].Holding)
                            {
                                destroy = false;
                            }
                        }
                    }
                    if (destroy == true)
                    {
                        DestroyImmediate(Cspr[c]);
                    }
                    foreach (CombinedSprite cs in CombinedSprites)
                    {
                        for (int s = 0; s < cs.SubTiles.Count; s++)
                        {
                            if (cs.SubTiles[s].GetComponentInChildren<Renderer>() != null)
                            {
                                foreach (Renderer render in cs.SubTiles[s].transform.GetComponentsInChildren<Renderer>())
                                {
                                    render.enabled = false;
                                }
                            }
                        }
                    }
                    foreach (CombinedSprite cs in previousFrameCombinedSprites)
                    {
                        for (int s = 0; s < cs.SubTiles.Count; s++)
                        {
                            if (cs.SubTiles[s].GetComponentInChildren<Renderer>() != null)
                            {
                                foreach (Renderer render in cs.SubTiles[s].transform.GetComponentsInChildren<Renderer>())
                                {
                                    render.enabled = false;
                                }
                            }
                        }
                    }
                }
            }
        }*/

            }
            
        }
        
    }
    private void OnDrawGizmos()
    {
        /*for (int x = 0; x < 32; x++)
        {
            for (int y = 0; y < 30; y++)
            {
                Vector2 MD5boundsgiz = new Vector2((int)(((4 - (prvTotalX - (prvTotalX % 8)) / 8) % 4) + (x % 4)), ((int)(((4 - ((prvTotalY - (prvTotalY % 8)) / 8) % 4) + (y % 4)))));
                Gizmos.DrawWireCube(MD5boundsgiz, new Vector3(1, 1, 1));
            }
        }*/
        foreach (CombinedSprite cs in CombinedSprites)
        {
            Gizmos.DrawWireCube(new Vector3(cs.Boundz.center.x + (GizXPixAdj * 0.125f), cs.Boundz.center.y + (GizYPixAdj * 0.125f), 0), new Vector3(cs.Boundz.size.x, cs.Boundz.size.y, cs.Boundz.size.z));
        }
        /*foreach (CombinedSprite cs in previousFrameCombinedSprites)
        {
            Gizmos.DrawWireCube(new Vector3(cs.Boundz.center.x + (GizXPixAdj * 0.125f), cs.Boundz.center.y + (GizYPixAdj * 0.125f), 0), new Vector3(cs.Boundz.size.x, cs.Boundz.size.y, cs.Boundz.size.z));
        }*/
        //Gizmos.DrawWireCube(MD5bounds, new Vector3(1, 1, 1));
    }


    public IEnumerator FrameAdvance()
    {
        if (MyNes.NesEmu.PAUSED == true)
        {
            MyNes.NesEmu.PAUSED = false;
            yield return new WaitForEndOfFrame();
            MyNes.NesEmu.PAUSED = true;
        }
    }
    void Update()
    {
       
        if (inited == true)
        {
			
            if (RxScriptInit.dump == true)
            {
                dumpFrame = true;
                
            }
            if (Input.GetKeyUp(KeyCode.R) == true || RefreshButton.isClicked == true)
            {
                
                RefreshGFX();
                
            }
            if (Input.GetKey(KeyCode.Tab))
            {
                StartCoroutine(FrameAdvance());
            }
			if (Input.GetKey(KeyCode.G))
            {
                GC.Collect();
            }
                BATCHFILE.Clear();
            screenshotMD5.Clear();
            dumpedTilez.Clear();

            dotCount = 0;

            tnum = 0;
            exportWidth = 0;
            exportHeight = 0;
            exportedWidth = 0;
            exportedHeight = 0;
            minBGX = 30;
            minBGY = 30;
            maxBGX = 0;
            maxBGY = 0;

            if (Input.GetButton("A"))
            {
                JoypadGameControllerConnecter.buttonActive[0] = true;
            }
            else
            {
                JoypadGameControllerConnecter.buttonActive[0] = false;
            }
            if (Input.GetButton("B"))
            {
                JoypadGameControllerConnecter.buttonActive[1] = true;
            }
            else
            {
                JoypadGameControllerConnecter.buttonActive[1] = false;
            }

            if (Input.GetButton("Select"))
            {
                JoypadGameControllerConnecter.buttonActive[2] = true;
            }
            else
            {
                JoypadGameControllerConnecter.buttonActive[2] = false;
            }
            if (Input.GetButton("Start"))
            {
                JoypadGameControllerConnecter.buttonActive[3] = true;
            }
            else
            {
                JoypadGameControllerConnecter.buttonActive[3] = false;
            }

            if (Input.GetAxis("Vertical") <= -0.025f)
            {
                JoypadGameControllerConnecter.buttonActive[4] = true;
            }
            else
            {
                JoypadGameControllerConnecter.buttonActive[4] = false;
            }

            if (Input.GetAxis("Vertical") >= 0.025f)
            {
                JoypadGameControllerConnecter.buttonActive[5] = true;
            }
            else
            {
                JoypadGameControllerConnecter.buttonActive[5] = false;
            }

            if (Input.GetAxis("Horizontal") <= -0.025f)
            {
                JoypadGameControllerConnecter.buttonActive[6] = true;
            }
            else
            {
                JoypadGameControllerConnecter.buttonActive[6] = false;
            }

            if (Input.GetAxis("Horizontal") >= 0.025f)
            {
                JoypadGameControllerConnecter.buttonActive[7] = true;
            }
            else
            {
                JoypadGameControllerConnecter.buttonActive[7] = false;
            }

            dumpTimer += 0.0001f;
            if (dumpTimer > float.MaxValue - 83)
            {
                dumpTimer = 0;
            }
            sceneTimer += 0.0001f;

            recognizedTileCount = 0;

            if (objcolors == null)
            {
                objcolors = new Color[256 * 240];
            }
            for (int cy = 0; cy < 240; cy++)
            {
                for (int cx = 256; cx > 0; cx--)
                {
                    if (cx + ((((240 + 1) - cy) * 256)) > 1 && cx + ((((240 + 1) - cy) * 256)) < 256 * 240)
                    {
                        if (cx + (cy * 256) > 0 && cx + (cy * 256) < 256 * 240)
                        {
                            objcolors[cx + ((((240 + 1) - cy) * 256))] = Color.clear;
                        }
                    }
                }
            }
			MyNes.NesEmu.isUpdating = true;
            if (Input.GetMouseButton(0) == true)
            {
                
                Vector3 p = new Vector3();
                Camera c = Camera.main;
                //Event e = Event.current;
                Vector2 mousePos = new Vector2();

                mousePos.x = Input.mousePosition.x;
                mousePos.y = Input.mousePosition.y;

                p = c.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, 0.0f));

                RaycastHit hit;
                Ray ray = SpriteCamera.ScreenPointToRay(Input.mousePosition);
                if (Physics.Raycast(ray, out hit, 10000.0f))
                {
                    if (hit.transform.gameObject.tag == "Tile")
                    {
                        WorkingGFXFile = hit.transform.gameObject.name.ToString();
                        clickedFrame = true;
                    }
                    if (hit.transform.gameObject.tag == "Sprite")
                    {
                        WorkingGFXFile = hit.transform.gameObject.name.ToString();
                        clickedFrame = true;
                    }
                }
            }
            UpdateTexture();
            ProcessSprites();
			MyNes.NesEmu.isUpdating = false;
			//NewLetters();
            for (int cy = 0; cy < 240; cy++)
            {
                for (int cx = 256; cx > 0; cx--)
                {
                    if (cx + ((((240 + 1) - cy) * 256)) > 1 && cx + ((((240 + 1) - cy) * 256)) < flippedfirstP1.Length - 1)
                    {
                        if (cx + (cy * 256) > 0 && cx + (cy * 256) < flippedfirstP1.Length)
                        {
                            flippedfirstP1[cx + (cy * 256)] = IntToColor(MyNes.NesEmu.spriteBufferfbP1[cx + ((((240 + 1) - cy) * 256))]);
							flippedfirstP2[cx + (cy * 256)] = IntToColor(MyNes.NesEmu.spriteBufferfbP2[cx + ((((240 + 1) - cy) * 256))]);
                            flippedfirstP3[cx + (cy * 256)] = IntToColor(MyNes.NesEmu.spriteBufferfbP3[cx + ((((240 + 1) - cy) * 256))]);
                            flippedfirstP4[cx + (cy * 256)] = IntToColor(MyNes.NesEmu.spriteBufferfbP4[cx + ((((240 + 1) - cy) * 256))]);
                        }
                    }
                }
            }

            flippyP1.SetPixels(flippedfirstP1);
            flippyP1.Apply();
			flippyP2.SetPixels(flippedfirstP2);
            flippyP2.Apply();
			flippyP3.SetPixels(flippedfirstP3);
            flippyP3.Apply();
			flippyP4.SetPixels(flippedfirstP4);
            flippyP4.Apply();
            //
            CombineSprites();
			
            texture.Apply();
			if (Input.GetMouseButton(0) == true)
            {

                Vector3 p = new Vector3();
                Camera c = Camera.main;
                //Event e = Event.current;
                Vector2 mousePos = new Vector2();

                mousePos.x = Input.mousePosition.x;
                mousePos.y = Input.mousePosition.y;

                p = c.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, 0.0f));

                RaycastHit hit;
                Ray ray = SpriteCamera.ScreenPointToRay(Input.mousePosition);
                if (Physics.Raycast(ray, out hit, 10000.0f))
                {
                    //WorkingGFXFile = hit.transform.gameObject.name.ToString();
                    if (hit.transform.gameObject.tag == "Tile")
                    {
                        DEBUGTEXT.text = "BG Tile = " + hit.transform.gameObject.name;
                        if (Input.GetKey(KeyCode.LeftShift) == true)
                        {
                            GUIUtility.systemCopyBuffer = hit.transform.gameObject.name;
                        }
                        WorkingisSprite = false;
                        if (hit.transform.GetChild(0).gameObject.GetComponent<Renderer>().enabled == true)
                        {
                            WorkingTexture.Resize(hit.transform.GetChild(0).gameObject.GetComponent<Renderer>().material.mainTexture.width, hit.transform.GetChild(0).gameObject.GetComponent<Renderer>().material.mainTexture.height);
                            WorkingTexture.SetPixels((hit.transform.GetChild(0).gameObject.GetComponent<Renderer>().material.mainTexture as Texture2D).GetPixels());
                            WorkingTexture.Apply();
                            DumpGraphicText.text = "DUMP " + hit.transform.gameObject.name.ToString();
                            LoadGraphicText.text = "MIGRATE " + hit.transform.gameObject.name.ToString();
                            WorkingGraphic.texture = WorkingTexture;
                            WorkingGraphic.mainTexture.filterMode = FilterMode.Point;
                        } else
                        {
                            DumpGraphicText.text = "DUMP " + hit.transform.gameObject.name.ToString();
                            LoadGraphicText.text = "MIGRATE " + hit.transform.gameObject.name.ToString();
                            WorkingGraphic.texture = WorkingTexture;
                            WorkingGraphic.mainTexture.filterMode = FilterMode.Point;
                        }
                        
                    }
                    if (hit.transform.gameObject.tag == "Sprite")
                    {
                        DEBUGTEXT.text = "Sprite = " + hit.transform.gameObject.name;
                        if (Input.GetKey(KeyCode.LeftShift) == true)
                        {
                            GUIUtility.systemCopyBuffer = hit.transform.gameObject.name;
                        }
                        WorkingisSprite = true;
                        WorkingTexture.Resize(GameObject.Find(hit.transform.gameObject.name + "Model").GetComponent<Renderer>().material.mainTexture.width, GameObject.Find(hit.transform.gameObject.name + "Model").GetComponent<Renderer>().material.mainTexture.height);
                        WorkingTexture.SetPixels((GameObject.Find(hit.transform.gameObject.name + "Model").GetComponent<Renderer>().material.mainTexture as Texture2D).GetPixels());
                        
                        WorkingTexture = MirrorTexture(WorkingTexture, false, true);
                        WorkingTexture.Apply();
                        //WorkingTexture.SetPixels(resizeTile(WorkingTexture.GetPixels(), WorkingTexture.width, WorkingTexture.height, WorkingTexture.width * 8, WorkingTexture.height * 8));
                        //WorkingTexture.Apply();
                        DumpGraphicText.text = "DUMP " + hit.transform.gameObject.name.ToString();
                        LoadGraphicText.text = "MIGRATE " + hit.transform.gameObject.name.ToString();
                        WorkingGraphic.texture = WorkingTexture;
                        WorkingGraphic.mainTexture.filterMode = FilterMode.Point;
                    }
                    /*if (hit.transform.gameObject.tag == "CombinedSprite")
                    {
                        DEBUGTEXT.text = "Sprite = " + hit.transform.gameObject.name;
                        if (Input.GetKey(KeyCode.LeftShift) == true)
                        {
                            GUIUtility.systemCopyBuffer = hit.transform.gameObject.name;
                        }
                        WorkingisSprite = true;
                        WorkingTexture = hit.transform.gameObject.GetComponent<Renderer>().material.mainTexture as Texture2D;
                        WorkingTexture = MirrorTexture(WorkingTexture, false, true);
                        WorkingTexture.Apply();
                    }*/


    }
                
                clickedFrame = false;
            }
            
            //if (Display.GetComponent<DisplaceY>() != null)
            //{

            //  Display.GetComponent<DisplaceY>().Textur = texture;
            //}
            //if (Input.GetMouseButtonDown(0))
            //{
            //    RaycastHit hit;
            //    Ray ray = SpriteCamera.ScreenPointToRay(Input.mousePosition);
            //    if (Physics.Raycast(ray, out hit, 10000.0f))
            //    {
            //        if (hit.transform.gameObject.tag == "CombinedSprite")
            //        {

            //            if (Application.platform == RuntimePlatform.WindowsEditor || Application.platform == RuntimePlatform.WindowsPlayer)
            //            {
            //                if (File.Exists(persistentDataPath + "/Enhancements/" + currentRomName + "/-MyPackage-/Spr-" + hit.transform.name + ".png") == true)
            //                {
            //                    Application.OpenURL(persistentDataPath + "/Enhancements/" + currentRomName + "/-MyPackage-/Spr-" + hit.transform.name + ".png");
            //                }
            //                else
            //                {
            //                    Texture2D temp = hit.transform.gameObject.GetComponent<Renderer>().material.mainTexture as Texture2D;
            //                    Color[] pixels = temp.GetPixels();
            //                    Color[] resize = resizePixels(pixels, temp.width, temp.height, temp.width * 8, temp.height * 8);
            //                    Texture2D temp2 = new Texture2D(temp.width * 8, temp.height * 8);

            //                    temp2.SetPixels(resize);
            //                    temp2.Apply();
            //                    byte[] pbh = (MirrorTexture(temp2, false, true)).EncodeToPNG();

            //                    File.WriteAllBytes(persistentDataPath + "/Enhancements/" + currentRomName + "/-MyPackage-/Spr-" + hit.transform.name + ".png", pbh);

            //                    Application.OpenURL(persistentDataPath + "/Enhancements/" + currentRomName + "/-MyPackage-/Spr-" + hit.transform.name + ".png");
            //                }
            //            }
            //            else
            //            {
            //                if (File.Exists(persistentDataPath + "/Enhancements/" + currentRomName + "/Spr-" + hit.transform.name + ".png") == true)
            //                {
            //                    Application.OpenURL(persistentDataPath + "/Enhancements/" + currentRomName + "/Spr-" + hit.transform.name + ".png");
            //                }
            //                else
            //                {
            //                    Texture2D temp = hit.transform.gameObject.GetComponent<Renderer>().material.mainTexture as Texture2D;
            //                    Color[] pixels = temp.GetPixels();
            //                    Color[] resize = resizePixels(pixels, temp.width, temp.height, temp.width * 8, temp.height * 8);
            //                    Texture2D temp2 = new Texture2D(temp.width * 8, temp.height * 8);

            //                    temp2.SetPixels(resize);
            //                    temp2.Apply();
            //                    byte[] pbh = (MirrorTexture(temp2, false, true)).EncodeToPNG();

            //                    File.WriteAllBytes(persistentDataPath + "/Enhancements/" + currentRomName + "/-MyPackage-/Spr-" + hit.transform.name + ".png", pbh);
            //                    Application.OpenURL(persistentDataPath + "/Enhancements/" + currentRomName + "/Spr-" + hit.transform.name + ".png");
            //                }
            //            }

            //        }
            //        Debug.Log("You selected the " + hit.transform.name);

            //    }
            //}
            //xMat.SetTexture("decal", texture);
            //Graphics.Blit(texture, texture4x, xMat);
            //xMat.SetTexture("decal", textureAlpha);
            //Graphics.Blit(textureAlpha, texture4xAlpha, xMat);

            //DisplayRenderer.material.SetTexture("_AlphaTex", texture4xAlpha);

            //RenderTexture.active = texture4xAlpha;
            //if (T2D4xAlpha == null)
            //{
            //    T2D4xAlpha = new Texture2D(texture4xAlpha.width, texture4xAlpha.height);
            // }
            //T2D4xAlpha.ReadPixels(new Rect(0, 0, texture4xAlpha.width, texture4xAlpha.height), 0, 0);
            //T2D4xAlpha.Apply();

            //RenderTexture.active = texture4x;
            //if (T2D4x == null)
            //{
            //     T2D4x = new Texture2D(texture4x.width, texture4x.height);
            //}
            //T2D4x.ReadPixels(new Rect(0, 0, texture4x.width, texture4x.height), 0, 0);
            //merge = T2D4x.GetPixels();
            //mergeAlpha = T2D4xAlpha.GetPixels();
            //for (int p = 0; p < merge.Length; p++)
            // {
            //   if (mergeAlpha[p].r > 0.874f)
            // {
            ///   merge[p] = new Color(merge[p].r, merge[p].g, merge[p].b, 1);
            // } else
            // {
            //     merge[p] = new Color(merge[p].r, merge[p].g, merge[p].b, 0);
            // }
            //}
            //T2D4x.SetPixels(merge);
            //T2D4x.Apply();

            DisplayRenderer.material.mainTexture = texture;

            frameMaxBGX = maxBGX;
            frameMaxBGY = maxBGY;
            exportWidth = frameMaxBGY - minBGY + 1;
            exportHeight = frameMaxBGX - minBGX + 1;
            if (dumpFrame == true)
            {
                pyxelFiles.Clear();
                pyxelNames.Clear();
                    rand = DateTime.Now.ToFileTime().ToString();
                    if (Directory.Exists(persistentDataPath + "/Enhancements/" + currentRomName + "/PyxelScreen" + rand + "/layer0.png") == false)
                    {
                        Directory.CreateDirectory(persistentDataPath + "/Enhancements/" + currentRomName + "/PyxelScreen" + rand + "/");
                    }
                    if (File.Exists(persistentDataPath + "/Enhancements/" + currentRomName + "/PyxelScreen" + rand + "/layer0.png") == false)
                    {

                        int heightOffset = MyNes.NesEmu.ppu_vram_finey;
                        int widthOffset = MyNes.NesEmu.ppu_vram_finex;
                        int widthCalc = MyNes.NesEmu.ppu_vram_finex;
                        int heightCalc = MyNes.NesEmu.ppu_vram_finey;
                        Texture2D tempTexture = new Texture2D(((exportWidth) * 64), ((exportHeight) * 64));

                        int count = 0;
                        BGTile[] dump = dumpedTilez.ToArray();
                        UnityEngine.Debug.Log("Dumping " + dump.Length + " tiles to : " + exportWidth + " x " + exportHeight + " Grid");
                        for (int y = 0; y < (int)(tempTexture.height / 64); y++)
                        {
                            for (int x = 0; x < (int)(tempTexture.width / 64); x++)
                            {
                                if (count < dump.Length - 1)
                                {

                                    if (screenshotMD5.Contains(dump[count].MD5Sum) == false)
                                    {
                                        if (File.Exists(persistentDataPath + "/Enhancements/" + currentRomName + "/PyxelScreen" + rand + "/tile" + tnum + ".png") == false)
                                        {

                                            try
                                            {
                                            byte[] pbh2;
                                            if (File.Exists(persistentDataPath + "/Enhancements/" + currentRomName + "/-MyPackage-/" + dump[count].MD5Sum + "/" + dump[count].MD5Sum + ".png") == false)
                                            {
                                                pbh2 = MirrorTexture(dump[count].TileTexture, false, true).EncodeToPNG();
                                            } else
                                            {
                                                pbh2 = File.ReadAllBytes(persistentDataPath + "/Enhancements/" + currentRomName + "/-MyPackage-/" + dump[count].MD5Sum + "/" + dump[count].MD5Sum + ".png");
                                            }

                                                File.WriteAllBytes(persistentDataPath + "/Enhancements/" + currentRomName + "/PyxelScreen" + rand + "/tile" + tnum + ".png", pbh2);
                                            pyxelFiles.Add(persistentDataPath + "/Enhancements/" + currentRomName + "/PyxelScreen" + rand + "/tile" + tnum + ".png");
                                            pyxelNames.Add("/tile" + tnum + ".png");
                                                DEBUGTEXT.text = (persistentDataPath + "/Enhancements/" + currentRomName + "/PyxelScreen" + rand + "/tile" + tnum + ".png");

                                            BATCHFILE.Add("if exist " + "tile" + tnum + ".png" + " mkdir " + dump[count].MD5Sum);
                                            BATCHFILE.Add("if exist " + "tile" + tnum + ".png" + " xcopy " + "tile" + tnum + ".png" + " " + "\"" + persistentDataPath + "/Enhancements/" + currentRomName + "/PyxelScreen" + rand + "/" + dump[count].MD5Sum + "/" + dump[count].MD5Sum + ".png*" + "\"" + Environment.NewLine);
                                            screenshotMD5.Add(dump[count].MD5Sum);
                                                tnum++;
                                            }
                                            catch (Exception e)
                                            {

                                                UnityEngine.Debug.Log(e.Message);
                                            }

                                        }

                                    }

                                    if (((x + 1) * 64) <= (tempTexture.width) && ((y + 1) * 64) <= (tempTexture.height))
                                    {

                                        tempTexture.SetPixels(((x) * 64), ((y) * 64), 64, 64, resizePixels(MirrorTexture(dump[count].TileTexture, false, true).GetPixels(), 8, 8, 64, 64));

                                    }
                                    count++;
                                }
                            }
                        }

                        tempTexture.Apply();

                        exportedWidth = tempTexture.width;
                        exportedHeight = tempTexture.height;

                        byte[] pbh = (MirrorTexture(tempTexture, false, true)).EncodeToPNG();

                        File.WriteAllBytes(persistentDataPath + "/Enhancements/" + currentRomName + "/PyxelScreen" + rand + "/layer0.png", pbh);
                    pyxelFiles.Add(persistentDataPath + "/Enhancements/" + currentRomName + "/PyxelScreen" + rand + "/layer0.png");
                    pyxelNames.Add("/layer0.png");
                    }
                
            
            bool found = false;
            
                
                    pyxelJSON = new JSONObject(JSONObject.Type.OBJECT);
                    int clrnum = 0;

                    pyxelJSON.AddField("canvas", delegate (JSONObject canvasJSON)
                    {
                        canvasJSON.AddField("tileHeight", 64);
                        canvasJSON.AddField("width", exportedWidth);

                        canvasJSON.AddField("layers", delegate (JSONObject layersJSON)
                        {
                            layersJSON.AddField("0", delegate (JSONObject layer0JSON)
                            {
                                layer0JSON.AddField("name", "Layer 0");
                                layer0JSON.AddField("alpha", 255);

                                layer0JSON.AddField("tileRefs", delegate (JSONObject tilerefsJSON)
                                {

                                    til = 0;

                                    bool md5found = false;
                                    foreach (BGTile tile in dumpedTilez)
                                    {
                                        index = 0;
                                        foreach (string md5 in screenshotMD5)
                                        {

                                            if (tile.MD5Sum == md5)
                                            {
                                                md5found = true;
                                                nodeJSON[til] = new JSONObject();
                                                if (nodeJSON[til] != null)
                                                {

                                                    tilerefsJSON.AddField(til.ToString(), nodeJSON[til]);

                                                    nodeJSON[til].AddField("index", index);
                                                    nodeJSON[til].AddField("rot", 0);
                                                    nodeJSON[til].AddField("flipX", false);

                                                }
                                            }
                                            index++;
                                        }

                                        if (md5found == false)
                                        {
                                            nodeJSON[til] = new JSONObject();
                                            tilerefsJSON.AddField(til.ToString(), nodeJSON[til]);

                                            nodeJSON[til].AddField("index", 0);
                                            nodeJSON[til].AddField("rot", 0);
                                            nodeJSON[til].AddField("flipX", false);
                                        }
                                        til++;
                                    }
                                });
                                layer0JSON.AddField("blendMode", "normal");
                                layer0JSON.AddField("hidden", false);
                            });
                        });
                        canvasJSON.AddField("height", exportedHeight);
                        canvasJSON.AddField("numLayers", 1);
                        canvasJSON.AddField("tileWidth", 64);
                    });

                    tilesetJSON = new JSONObject();
                    pyxelJSON.AddField("tileset", delegate (JSONObject tilesetJSON)
                    {
                        tilesetJSON.AddField("tileHeight", 64);
                        tilesetJSON.AddField("tilesWide", exportWidth);
                        tilesetJSON.AddField("numTiles", tnum);
                        tilesetJSON.AddField("tileWidth", 64);
                        tilesetJSON.AddField("fixedWidth", false);

                    });
                    pyxelJSON.AddField("name", "Untitled");

                    pyxelJSON.AddField("palette", delegate (JSONObject paletteJSON)
                    {
                        paletteJSON.AddField("numColors", MyNes.NesEmu.Nes_Palette.Length);
                        paletteJSON.AddField("colors", delegate (JSONObject colorsJSON)
                        {

                            foreach (int clr in MyNes.NesEmu.Nes_Palette)
                            {
                                colorsJSON.AddField(clrnum++.ToString(), "ff" + ColorUtility.ToHtmlStringRGB(IntToColor(clr)).ToLower());
                            }

                        });
                        paletteJSON.AddField("width", 12);

                        paletteJSON.AddField("height", 5);

                    });
                    settingsJSON = new JSONObject();
                    pyxelJSON.AddField("settings", delegate (JSONObject settingsJSON)
                    {

                    });
                    animationsJSON = new JSONObject();
                    pyxelJSON.AddField("animations", delegate (JSONObject animationsJSON)
                    {

                    });

                    pyxelJSON.AddField("version", "0.4.5");

            
                
                    string outputA = pyxelJSON.Print(true).Replace(("animations':null,").Replace("'", "\""), ("animations':{},").Replace("'", "\""));
                    string outputB = outputA.Replace(("settings':null,").Replace("'", "\""), ("settings':{},").Replace("'", "\""));
                    string outputC = outputB.Replace(":", ": ");
                    char tab = '\u0009';
                    string notabs = outputC.Replace(tab.ToString(), "  ");
                    foreach (string line in BATCHFILE)
                    {
                        File.WriteAllLines(persistentDataPath + "/Enhancements/" + currentRomName + "/PyxelScreen" + rand + "/RENAME_FILES.BAT", BATCHFILE.ToArray());
                    }
                    File.WriteAllText(persistentDataPath + "/Enhancements/" + currentRomName + "/PyxelScreen" + rand + "/docData.json", notabs);
                pyxelFiles.Add(persistentDataPath + "/Enhancements/" + currentRomName + "/PyxelScreen" + rand + "/docData.json");
                pyxelNames.Add("/docData.json");
                lzip.compress_File_List(9, persistentDataPath + "/Enhancements/" + currentRomName + "/PyxelScreen" + rand + "/PyxelScreen" + rand + ".pyxel", pyxelFiles.ToArray(), null, false, pyxelNames.ToArray(), null);
                Application.OpenURL(persistentDataPath + "/Enhancements/" + currentRomName + "/PyxelScreen" + rand + "/PyxelScreen" + rand + ".pyxel");
                Application.OpenURL(persistentDataPath + "/Enhancements/" + currentRomName + "/PyxelScreen" + rand + "/");
            }
            if (Input.GetKeyUp(KeyCode.S) == true)
            {
                //SpeakText();
            }
            dumpFrame = false;
			
            if (tilesCounted == 0)
            {
                totalX = 0;
                totalY = 0;
				fineTotalX = 0;
				fineTotalY = 0;
				
            } else {
				
			}
			prvTotalX = totalX;
			prvTotalY = totalY;
            MyNes.NesEmu.PAUSED = RxScriptInit.wasPaused;

            if (DumpButton.isClicked == true)
            {
                if (WorkingTexture != null)
                {
                    byte[] pbh = WorkingTexture.EncodeToPNG();
                    if (WorkingisSprite == true)
                    {
                        File.WriteAllBytes(persistentDataPath + "/Enhancements/" + currentRomName + "/InProgress/Spr-" + WorkingGFXFile + ".png", pbh);
                        Application.OpenURL(persistentDataPath + "/Enhancements/" + currentRomName + "/InProgress/Spr-" + WorkingGFXFile + ".png");
                    }
                    else
                    {
                        File.WriteAllBytes(persistentDataPath + "/Enhancements/" + currentRomName + "/InProgress/" + WorkingGFXFile + ".png", pbh);
                        Application.OpenURL(persistentDataPath + "/Enhancements/" + currentRomName + "/InProgress/" + WorkingGFXFile + ".png");
                    }
                }
                DumpButton.isClicked = false;
            }
            if (RefreshButton.isClicked == true)
            {
                if (WorkingisSprite == true)
                {
                    if (File.Exists(persistentDataPath + "/Enhancements/" + currentRomName + "/InProgress/Spr-" + WorkingGFXFile + ".png"))
                    {
                        File.Copy(persistentDataPath + "/Enhancements/" + currentRomName + "/InProgress/Spr-" + WorkingGFXFile + ".png", persistentDataPath + "/Enhancements/" + currentRomName + "/-MyPackage-/Spr-" + WorkingGFXFile + ".png", true);
                    }
                }
                else
                {
                    if (File.Exists(persistentDataPath + "/Enhancements/" + currentRomName + "/InProgress/" + WorkingGFXFile + ".png"))
                    {
                        File.Copy(persistentDataPath + "/Enhancements/" + currentRomName + "/InProgress/" + WorkingGFXFile + ".png", persistentDataPath + "/Enhancements/" + currentRomName + "/-MyPackage-/" + WorkingGFXFile + ".png", true);
                    }
                }
                RefreshButton.isClicked = false;
            }
        }


    }

    public static Color IntToColor(int color)
    {
        if (color == 0)
        {
            return RxScriptInit._QuickPalette[0];
        }
        else if (color == -4473925)
        {
            return RxScriptInit._QuickPalette[1];
        }
        else if (color == -1)
        {
            return RxScriptInit._QuickPalette[2];
        }
        else if (color == -11382190)
        {
            return RxScriptInit._QuickPalette[3];
        }
        else if (color == -16774996)
        {
            return RxScriptInit._QuickPalette[4];
        }
        else if (color == -16756993)
        {
            return RxScriptInit._QuickPalette[5];
        }
        else if (color == -13188609)
        {
            return RxScriptInit._QuickPalette[6];
        }
        else if (color == -3538945)
        {
            return RxScriptInit._QuickPalette[7];
        }
        else if (color == -16776983)
        {
            return RxScriptInit._QuickPalette[8];
        }
        else if (color == -1118977)
        {
            return RxScriptInit._QuickPalette[9];
        }
        else if (color == -14935553)
        {
            return RxScriptInit._QuickPalette[10];
        }
        else if (color == -7698945)
        {
            return RxScriptInit._QuickPalette[11];
        }
        else if (color == -14548766)
        {
            return RxScriptInit._QuickPalette[12];
        }
        else if (color == -9043713)
        {
            return RxScriptInit._QuickPalette[13];
        }
        else if (color == -1222657)
        {
            return RxScriptInit._QuickPalette[14];
        }
        else if (color == -9985)
        {
            return RxScriptInit._QuickPalette[15];
        }
        else if (color == -10878823)
        {
            return RxScriptInit._QuickPalette[16];
        }
        else if (color == -3735297)
        {
            return RxScriptInit._QuickPalette[17];
        }
        else if (color == -48897)
        {
            return RxScriptInit._QuickPalette[18];
        }
        else if (color == -12545)
        {
            return RxScriptInit._QuickPalette[19];
        }
        else if (color == -8781782)
        {
            return RxScriptInit._QuickPalette[20];
        }
        else if (color == -786303)
        {
            return RxScriptInit._QuickPalette[21];
        }
        else if (color == -47111)
        {
            return RxScriptInit._QuickPalette[22];
        }
        else if (color == -11777)
        {
            return RxScriptInit._QuickPalette[23];
        }
        else if (color == -9043968)
        {
            return RxScriptInit._QuickPalette[24];
        }
        else if (color == -7982)
        {
            return RxScriptInit._QuickPalette[25];
        }
        else if (color == -1179136)
        {
            return RxScriptInit._QuickPalette[26];
        }
        else if (color == -38583)
        {
            return RxScriptInit._QuickPalette[27];
        }
        else if (color == -11599872)
        {
            return RxScriptInit._QuickPalette[28];
        }
        else if (color == -4706560)
        {
            return RxScriptInit._QuickPalette[29];
        }
        else if (color == -24832)
        {
            return RxScriptInit._QuickPalette[30];
        }
        else if (color == -2156)
        {
            return RxScriptInit._QuickPalette[31];
        }
        else if (color == -15395072)
        {
            return RxScriptInit._QuickPalette[32];
        }
        else if (color == -10328576)
        {
            return RxScriptInit._QuickPalette[33];
        }
        else if (color == -2630656)
        {
            return RxScriptInit._QuickPalette[34];
        }
        else if (color == -141)
        {
            return RxScriptInit._QuickPalette[35];
        }
        else if (color == -16763136)
        {
            return RxScriptInit._QuickPalette[36];
        }
        else if (color == -16018176)
        {
            return RxScriptInit._QuickPalette[37];
        }
        else if (color == -9109760)
        {
            return RxScriptInit._QuickPalette[38];
        }
        else if (color == -1704073)
        {
            return RxScriptInit._QuickPalette[39];
        }
        else if (color == -16759040)
        {
            return RxScriptInit._QuickPalette[40];
        }
        else if (color == -16733184)
        {
            return RxScriptInit._QuickPalette[41];
        }
        else if (color == -14090496)
        {
            return RxScriptInit._QuickPalette[42];
        }
        else if (color == -3997794)
        {
            return RxScriptInit._QuickPalette[43];
        }
        else if (color == -16734974)
        {
            return RxScriptInit._QuickPalette[44];
        }
        else if (color == -16760064)
        {
            return RxScriptInit._QuickPalette[45];
        }
        else if (color == -16515223)
        {
            return RxScriptInit._QuickPalette[46];
        }
        else if (color == -5177376)
        {
            return RxScriptInit._QuickPalette[47];
        }
        else if (color == -16766399)
        {
            return RxScriptInit._QuickPalette[48];
        }
        else if (color == -16743773)
        {
            return RxScriptInit._QuickPalette[49];
        }
        else if (color == -16188673)
        {
            return RxScriptInit._QuickPalette[50];
        }
        else if (color == -5046273)
        {
            return RxScriptInit._QuickPalette[51];
        }
        else if (color == -16777216)
        {
            return RxScriptInit._QuickPalette[52];
        }
        else if (color == -13487566)
        {
            return RxScriptInit._QuickPalette[53];
        }
        else if (color == -3684409)
        {
            return RxScriptInit._QuickPalette[54];
        }

        else if (color <= 16777215)
        {
            byte r = (byte)(color >> 16);
            byte g = (byte)(color >> 8);
            byte b = (byte)(color >> 0);
            //IntColors.Add(new IntColor(color, new Color(r / 255f, g / 255f, b / 255f, 1)));
            //File.AppendAllText(AppPath + "/Palette.cfg", "else if (color" + " == " + color + ") {" + Environment.NewLine + "return RxScriptInit._QuickPalette[" + palCount + "];" + Environment.NewLine + "}" + Environment.NewLine);
            //palCount++;
            return new Color(r / 255f, g / 255f, b / 255f, 1);
        }
        else
        {
            return RxScriptInit._QuickPalette[55];
        }

    }
    public static void SubmitVideoFrame(ref int[] buffer)
    {
        
    }

    public static void SubmitAudioFrame(ref short[] samples)
    {

        if (MyNES_Audio.audio_shorts == null)
        {
            MyNES_Audio.audio_shorts = new short[samples.Length];
        }
        MyNES_Audio.audio_shorts = samples;
        MyNES_Audio.audioout = true;
    }

    public static Color[] MirrorTextureColorArray(Texture2D originalTexture, bool horizontal, bool vertical)
    {
        newPixels = new Color[originalTexture.GetPixels(0).Length];
        originalPixels = originalTexture.GetPixels(0);
        newPixels = originalTexture.GetPixels(0);
        for (int y = 0; y < originalTexture.height; y++)
        {
            for (int x = 0; x < originalTexture.width; x++)
            {
                int newX = horizontal ? (originalTexture.width - 1 - x) : x;
                int newY = vertical ? (originalTexture.height - 1 - y) : y;
                newPixels[(newY * originalTexture.width) + newX] = originalPixels[(y * originalTexture.width) + x];
            }
        }
        return newPixels;
    }

    public static Texture2D MirrorTexture(Texture2D originalTexture, bool horizontal, bool vertical)
    {
        newTexture.Resize(originalTexture.width, originalTexture.height);
        originalPixels = originalTexture.GetPixels(0);
        newPixels = newTexture.GetPixels(0);
        for (int y = 0; y < originalTexture.height; y++)
        {
            for (int x = 0; x < originalTexture.width; x++)
            {
                int newX = horizontal ? (originalTexture.width - 1 - x) : x;
                int newY = vertical ? (originalTexture.height - 1 - y) : y;
                newPixels[(newY * newTexture.width) + newX] = originalPixels[(y * originalTexture.width) + x];
            }
        }
        newTexture.SetPixels(newPixels, 0);
        newTexture.Apply();
        return newTexture;
    }
    public static Color[] MirrorColors(Color[] originalColors, int width, int height, bool horizontal, bool vertical)
    {
        Color[] newColors = new Color[originalColors.Length];

        for (int y = 0; y < height; y++)
        {
            for (int x = 0; x < width; x++)
            {
                int newX = horizontal ? (width - 1 - x) : x;
                int newY = vertical ? (height - 1 - y) : y;
                newColors[(newY * width) + newX] = originalColors[(y * width) + x];
            }
        }

        return newColors;
    }
    public static Color[] resizePixels(Color[] pixels, int w1, int h1, int w2, int h2)
    {
        tempcolor = new Color[w2 * h2];
        int x_ratio = (int)((w1 << 16) / w2) + 1;
        int y_ratio = (int)((h1 << 16) / h2) + 1;
        int x2, y2;
        for (int i = 0; i < h2; i++)
        {
            for (int j = 0; j < w2; j++)
            {
                x2 = ((j * x_ratio) >> 16);
                y2 = ((i * y_ratio) >> 16);
                tempcolor[(i * w2) + j] = pixels[(y2 * w1) + x2];
            }
        }
        return tempcolor;
    }
    public static Color[] resizeTile(Color[] pixels, int w1, int h1, int w2, int h2)
    {
        Color[] temp = new Color[w2 * h2];
        int x_ratio = (int)((w1 << 16) / w2) + 1;
        int y_ratio = (int)((h1 << 16) / h2) + 1;
        int x2, y2;
        for (int i = 0; i < h2; i++)
        {
            for (int j = 0; j < w2; j++)
            {
                x2 = ((j * x_ratio) >> 16);
                y2 = ((i * y_ratio) >> 16);
                temp[(i * w2) + j] = pixels[(y2 * w1) + x2];
            }
        }
        return temp;
    }

    public static bool FtpDirectoryExists(string directory)
    {
        bool IsExists = false;
        try
        {
            UnityEngine.Debug.Log("Checking if Directory Exists.");
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(directory);
            request.Credentials = new NetworkCredential(@"KugiZuki@2depth.com", "200lander");
            request.Method = WebRequestMethods.Ftp.MakeDirectory;

            FtpWebResponse response = (FtpWebResponse)request.GetResponse();
            UnityEngine.Debug.Log(response.StatusDescription);
        }
        catch (WebException ex)
        {
            IsExists = true;
        }
        return IsExists;
    }

    public static bool FtpFileExists(string filePath)
    {
        bool IsExists = true;

        UnityEngine.Debug.Log("Checking if File Exists.");
        request = (FtpWebRequest)WebRequest.Create(filePath);
        request.Credentials = new NetworkCredential(@"KugiZuki@2depth.com", "200lander");
        request.Method = WebRequestMethods.Ftp.GetFileSize;
        try
        {
            response = (FtpWebResponse)request.GetResponse();

        }
        catch (WebException ex)
        {
            response = (FtpWebResponse)ex.Response;
            if (response.StatusCode ==
                FtpStatusCode.ActionNotTakenFileUnavailable)
            {
                IsExists = false;
            }

        }

        return IsExists;
    }

    public static string[] GetFileList(string uri)
    {
        string[] downloadFiles;
        StringBuilder result = new StringBuilder();

        try
        {
            UnityEngine.Debug.Log("Getting File List...");
            request = (FtpWebRequest)FtpWebRequest.Create(uri);
            request.UseBinary = true;
            request.Credentials = new NetworkCredential(@"KugiZuki@2depth.com", "200lander");
            request.Method = WebRequestMethods.Ftp.ListDirectory;
            request.UseBinary = true;

            WebResponse webresponse = request.GetResponse();
            StreamReader reader = new StreamReader(webresponse.GetResponseStream());

            string line = reader.ReadLine();
            while (line != null)
            {
                UnityEngine.Debug.Log(line);
                result.Append(line);
                result.Append("\n");
                line = reader.ReadLine();
            }
            result.Remove(result.ToString().LastIndexOf('\n'), 1);
            reader.Close();
            return result.ToString().Split('\n');
        }
        catch (Exception ex)
        {
            downloadFiles = null;
            return downloadFiles;
        }
    }
    public static void StartUploadThread()
    {
        t = new Thread(new ThreadStart(Go));

        t.Start();
    }

    public static void StopUploadThread()
    {
        t.Abort();

        UnityEngine.Debug.Log("Thread Aborted!");
    }

    public static bool UploadThreadActive()
    {
        if (t == null)
        {
            UnityEngine.Debug.Log("Thread is/was not Active!");
            return false;
        }
        else
        {
            UnityEngine.Debug.Log("Thread is/was Active!");
            return t.IsAlive;
        }
    }

    static void Go()
    {

        UnityEngine.Debug.Log("Upload Thread is Active!");
        if (FtpDirectoryExists(@"ftp://www.2depth.com/" + currentRomName) == false)
        {

        }
        if (FtpDirectoryExists(@"ftp://www.2depth.com/" + currentRomName + "/" + usernum) == false)
        {

        }
        string[] fileListing = GetFileList(@"ftp://www.2depth.com/" + currentRomName + "/" + usernum);
        bool[] stillExists = new bool[fileListing.Length];
        for (int l = 0; l < fileListing.Length; l++)
        {
            UnityEngine.Debug.Log(fileListing[l]);
            if (fileListing[l] != "." && fileListing[l] != "..")
            {
                if (fileListing[l].EndsWith(".mtl") || fileListing[l].EndsWith(".obj") || fileListing[l].EndsWith(".png"))
                {
                    if (!File.Exists(persistentDataPath + "/Enhancements/" + currentRomName + "/-MyPackage-/" + fileListing[l]))
                    {
                        UnityEngine.Debug.Log("File : " + persistentDataPath + "/Enhancements/" + currentRomName + "/-MyPackage-/" + fileListing[l] + " does NOT Exist LOCALLY.. Sooo...");
                        FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(new Uri(@"ftp://www.2depth.com/" + currentRomName + "/" + usernum + "/" + fileListing[l]));
                        request.Method = WebRequestMethods.Ftp.DeleteFile;
                        request.Credentials = new NetworkCredential(@"KugiZuki@2depth.com", "200lander");
                        FtpWebResponse response = (FtpWebResponse)request.GetResponse();
                        UnityEngine.Debug.Log(response.StatusDescription);
                        response.Close();
                        UnityEngine.Debug.Log("File: " + persistentDataPath + "/Enhancements/" + currentRomName + " /-MyPackage-/ " + fileListing[l] + " was REMOVED from the SERVER! :)");
                    }
                    else
                    {
                        UnityEngine.Debug.Log("File " + persistentDataPath + "/Enhancements/" + currentRomName + "/-MyPackage-/" + fileListing[l] + " still Exists LOCALLY & ON THE SERVER! :)");
                    }
                }
            }
            Thread.Sleep(2000);
        }

        DirectoryInfo directory = new DirectoryInfo(persistentDataPath + "/Enhancements/" + currentRomName + "/-MyPackage-/");

        DirectoryInfo[] subDirectories = directory.GetDirectories();
        foreach (DirectoryInfo dirInfo in subDirectories)
        {
            UnityEngine.Debug.Log("Subfolder : " + dirInfo.Name);
            if (FtpDirectoryExists(@"ftp://www.2depth.com/" + currentRomName + "/" + usernum + "/" + dirInfo.Name) == false)
            {

            }

            string[] subfileListing = GetFileList(@"ftp://www.2depth.com/" + currentRomName + "/" + usernum + "/" + dirInfo.Name + "/");
            bool[] substillExists = new bool[subfileListing.Length];
            for (int l = 0; l < subfileListing.Length; l++)
            {
                UnityEngine.Debug.Log(subfileListing[l]);
                if (subfileListing[l] != "." && subfileListing[l] != "..")
                {
                    if (subfileListing[l].EndsWith(".mtl") || subfileListing[l].EndsWith(".obj") || subfileListing[l].EndsWith(".png"))
                    {
                        if (!File.Exists(persistentDataPath + "/Enhancements/" + currentRomName + "/-MyPackage-/" + dirInfo.Name + "/" + subfileListing[l]))
                        {
                            UnityEngine.Debug.Log("File : " + persistentDataPath + "/Enhancements/" + currentRomName + "/-MyPackage-/" + dirInfo.Name + "/" + subfileListing[l] + " does NOT Exist LOCALLY.. Soooo...");
                            FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(new Uri(@"ftp://www.2depth.com/" + currentRomName + "/" + usernum + "/" + dirInfo.Name + "/" + subfileListing[l]));
                            request.Method = WebRequestMethods.Ftp.DeleteFile;
                            request.Credentials = new NetworkCredential(@"KugiZuki@2depth.com", "200lander");
                            FtpWebResponse response = (FtpWebResponse)request.GetResponse();
                            UnityEngine.Debug.Log(response.StatusDescription);
                            response.Close();
                            UnityEngine.Debug.Log("File : " + persistentDataPath + "/Enhancements/" + currentRomName + "/-MyPackage-/" + dirInfo.Name + "/" + subfileListing[l] + " was REMOVED from the SERVER! :)");
                        }
                        else
                        {
                            UnityEngine.Debug.Log("File : " + persistentDataPath + "/Enhancements/" + currentRomName + "/-MyPackage-/" + dirInfo.Name + "/" + subfileListing[l] + " STILL Exists LOCALLY & ON THE SERVER! :)");
                        }
                    }
                }
                Thread.Sleep(2000);
            }

            FileInfo[] subfiles = dirInfo.GetFiles("*.*");
            foreach (FileInfo subfileInfo in subfiles)
            {

                bool IsExists = true;

                UnityEngine.Debug.Log("Checking if " + @"ftp://www.2depth.com/" + currentRomName + "/" + usernum + "/" + dirInfo.Name + "/" + subfileInfo.Name + " Exists.");
                request = (FtpWebRequest)WebRequest.Create(new Uri(@"ftp://www.2depth.com/" + currentRomName + "/" + usernum + "/" + dirInfo.Name + "/" + subfileInfo.Name));
                request.Credentials = new NetworkCredential(@"KugiZuki@2depth.com", "200lander");
                request.Method = WebRequestMethods.Ftp.GetDateTimestamp;
                try
                {
                    response = (FtpWebResponse)request.GetResponse();

                }
                catch (WebException ex)
                {
                    response = (FtpWebResponse)ex.Response;
                    if (response.StatusCode ==
                        FtpStatusCode.ActionNotTakenFileUnavailable)
                    {
                        IsExists = false;
                        UnityEngine.Debug.Log(@"ftp://www.2depth.com/" + currentRomName + "/" + usernum + "/" + dirInfo.Name + "/" + subfileInfo.Name + " DOES NOT Exist on the SERVER..");
                    }
                    else
                    {
                        UnityEngine.Debug.Log(@"ftp://www.2depth.com/" + currentRomName + "/" + usernum + "/" + dirInfo.Name + "/" + subfileInfo.Name + " NOW Exists LOCALLY & ON THE SERVER!");
                    }

                }
                response.Close();
                if (IsExists == true)
                {

                    request = (FtpWebRequest)WebRequest.Create(new Uri(@"ftp://www.2depth.com/" + currentRomName + "/" + usernum + "/" + dirInfo.Name + "/" + subfileInfo.Name));
                    request.Method = WebRequestMethods.Ftp.GetDateTimestamp;
                    request.Credentials = new NetworkCredential(@"KugiZuki@2depth.com", "200lander");
                    response = (FtpWebResponse)request.GetResponse();
                    string DateString = (response.StatusDescription).Split(' ')[1];
                    response.Close();
                    DateTime DateValue;
                    DateValue = DateTime.ParseExact(DateString, "yyyyMMddHHmmss", CultureInfo.InvariantCulture.DateTimeFormat);

                    FileInfo dinfo = new FileInfo(subfileInfo.FullName);

                    if (dinfo.LastWriteTime != DateValue)
                    {
                        UnityEngine.Debug.Log("...But has a different Date/Time :)");
                        request = (FtpWebRequest)FtpWebRequest.Create(new Uri(@"ftp://www.2depth.com/" + currentRomName + "/" + usernum + "/" + dirInfo.Name + "/" + subfileInfo.Name));
                        request.Method = WebRequestMethods.Ftp.DeleteFile;
                        request.Credentials = new NetworkCredential(@"KugiZuki@2depth.com", "200lander");
                        response = (FtpWebResponse)request.GetResponse();
                        UnityEngine.Debug.Log("Deleted old File!");
                        response.Close();

                        UnityEngine.Debug.Log("Uploading File : " + subfileInfo.FullName);
                        request = (FtpWebRequest)FtpWebRequest.Create(new Uri(@"ftp://www.2depth.com/" + currentRomName + "/" + usernum + "/" + dirInfo.Name + "/" + subfileInfo.Name));
                        request.Proxy = null;
                        request.Method = WebRequestMethods.Ftp.UploadFile;
                        request.Credentials = new NetworkCredential(@"KugiZuki@2depth.com", "200lander");
                        request.UseBinary = true;
                        request.UsePassive = true;

                        using (Stream fileStream = File.OpenRead(subfileInfo.FullName))
                        {
                            using (Stream ftpStream = request.GetRequestStream())
                            {
                                fileStream.CopyTo(ftpStream);
                            }
                        }
                        UnityEngine.Debug.Log("Completed Uploading " + subfileInfo.Name);
                        uploadCount += 1;
                        response = (FtpWebResponse)request.GetResponse();
                        response.Close();

                        request = (FtpWebRequest)WebRequest.Create(new Uri(@"ftp://www.2depth.com/" + currentRomName + "/" + usernum + "/" + dirInfo.Name + "/" + subfileInfo.Name));
                        request.Method = WebRequestMethods.Ftp.GetDateTimestamp;
                        request.Credentials = new NetworkCredential(@"KugiZuki@2depth.com", "200lander");
                        response = (FtpWebResponse)request.GetResponse();
                        string FTPDateString = (response.StatusDescription).Split(' ')[1];
                        response.Close();

                        DateTime FTPDateValue;
                        FTPDateValue = DateTime.ParseExact(FTPDateString, "yyyyMMddHHmmss", CultureInfo.InvariantCulture.DateTimeFormat);

                        File.SetLastWriteTime(subfileInfo.FullName, FTPDateValue);

                    }
                    else
                    {
                        UnityEngine.Debug.Log("File : " + subfileInfo.FullName + " does NOT need to be Updated/Uploaded!");
                    }
                }
                else
                {
                    UnityEngine.Debug.Log("Uploading File : " + subfileInfo.FullName);
                    request = (FtpWebRequest)FtpWebRequest.Create(new Uri(@"ftp://www.2depth.com/" + currentRomName + "/" + usernum + "/" + dirInfo.Name + "/" + subfileInfo.Name));
                    request.Proxy = null;
                    request.Method = WebRequestMethods.Ftp.UploadFile;
                    request.Credentials = new NetworkCredential(@"KugiZuki@2depth.com", "200lander");
                    request.UseBinary = true;
                    request.UsePassive = true;

                    using (Stream fileStream = File.OpenRead(subfileInfo.FullName))
                    {
                        using (Stream ftpStream = request.GetRequestStream())
                        {
                            fileStream.CopyTo(ftpStream);
                        }
                    }
                    uploadCount += 1;
                    UnityEngine.Debug.Log("Completed Uploading " + subfileInfo.Name);
                    response = (FtpWebResponse)request.GetResponse();
                    response.Close();

                    request = (FtpWebRequest)WebRequest.Create(new Uri(@"ftp://www.2depth.com/" + currentRomName + "/" + usernum + "/" + dirInfo.Name + "/" + subfileInfo.Name));
                    request.Method = WebRequestMethods.Ftp.GetDateTimestamp;
                    request.Credentials = new NetworkCredential(@"KugiZuki@2depth.com", "200lander");
                    response = (FtpWebResponse)request.GetResponse();
                    string FTPDateString = (response.StatusDescription).Split(' ')[1];
                    response.Close();

                    DateTime FTPDateValue;
                    FTPDateValue = DateTime.ParseExact(FTPDateString, "yyyyMMddHHmmss", CultureInfo.InvariantCulture.DateTimeFormat);

                    File.SetLastWriteTime(subfileInfo.FullName, FTPDateValue);
                }

                Thread.Sleep(2000);
            }
        }
        FileInfo[] files = directory.GetFiles("*.*");
        foreach (FileInfo fileInfo in files)
        {

            bool IsExists = true;

            UnityEngine.Debug.Log("Checking if " + @"ftp://www.2depth.com/" + currentRomName + "/" + usernum + "/" + fileInfo.Name + " Exists.");
            request = (FtpWebRequest)WebRequest.Create(new Uri(@"ftp://www.2depth.com/" + currentRomName + "/" + usernum + "/" + fileInfo.Name));
            request.Credentials = new NetworkCredential(@"KugiZuki@2depth.com", "200lander");
            request.Method = WebRequestMethods.Ftp.GetDateTimestamp;
            try
            {
                response = (FtpWebResponse)request.GetResponse();

            }
            catch (WebException ex)
            {
                response = (FtpWebResponse)ex.Response;
                if (response.StatusCode ==
                    FtpStatusCode.ActionNotTakenFileUnavailable)
                {
                    IsExists = false;
                    UnityEngine.Debug.Log(@"ftp://www.2depth.com/" + currentRomName + "/" + usernum + "/" + fileInfo.Name + " DOES NOT Exist..");
                }
                else
                {
                    UnityEngine.Debug.Log(@"ftp://www.2depth.com/" + currentRomName + "/" + usernum + "/" + fileInfo.Name + " Exists!");
                }

            }
            response.Close();
            if (IsExists == true)
            {
                request = (FtpWebRequest)WebRequest.Create(new Uri(@"ftp://www.2depth.com/" + currentRomName + "/" + usernum + "/" + fileInfo.Name));
                request.Method = WebRequestMethods.Ftp.GetDateTimestamp;
                request.Credentials = new NetworkCredential(@"KugiZuki@2depth.com", "200lander");
                response = (FtpWebResponse)request.GetResponse();
                string DateString = (response.StatusDescription).Split(' ')[1];
                response.Close();
                DateTime DateValue;
                DateValue = DateTime.ParseExact(DateString, "yyyyMMddHHmmss", CultureInfo.InvariantCulture.DateTimeFormat);

                FileInfo dinfo = new FileInfo(fileInfo.FullName);

                if (dinfo.LastWriteTime != DateValue)
                {
                    UnityEngine.Debug.Log("...But has a different Date/Time :)");
                    request = (FtpWebRequest)FtpWebRequest.Create(new Uri(@"ftp://www.2depth.com/" + currentRomName + "/" + usernum + "/" + fileInfo.Name));
                    request.Method = WebRequestMethods.Ftp.DeleteFile;
                    request.Credentials = new NetworkCredential(@"KugiZuki@2depth.com", "200lander");
                    response = (FtpWebResponse)request.GetResponse();
                    UnityEngine.Debug.Log("Deleted old File!");
                    response.Close();
                    UnityEngine.Debug.Log("Uploading File : " + fileInfo.FullName);
                    request = (FtpWebRequest)FtpWebRequest.Create(new Uri(@"ftp://www.2depth.com/" + currentRomName + "/" + usernum + "/" + fileInfo.Name));
                    request.Proxy = null;
                    request.Method = WebRequestMethods.Ftp.UploadFile;
                    request.Credentials = new NetworkCredential(@"KugiZuki@2depth.com", "200lander");
                    request.UseBinary = true;
                    request.UsePassive = true;

                    using (Stream fileStream = File.OpenRead(fileInfo.FullName))
                    {
                        using (Stream ftpStream = request.GetRequestStream())
                        {
                            fileStream.CopyTo(ftpStream);
                        }
                    }
                    response = (FtpWebResponse)request.GetResponse();
                    response.Close();

                    request = (FtpWebRequest)WebRequest.Create(new Uri(@"ftp://www.2depth.com/" + currentRomName + "/" + usernum + "/" + fileInfo.Name));
                    request.Method = WebRequestMethods.Ftp.GetDateTimestamp;
                    request.Credentials = new NetworkCredential(@"KugiZuki@2depth.com", "200lander");
                    response = (FtpWebResponse)request.GetResponse();

                    string FTPDateString = (response.StatusDescription).Split(' ')[1];
                    response.Close();
                    DateTime FTPDateValue;
                    FTPDateValue = DateTime.ParseExact(FTPDateString, "yyyyMMddHHmmss", CultureInfo.InvariantCulture.DateTimeFormat);

                    File.SetLastWriteTime(fileInfo.FullName, FTPDateValue);
                    uploadCount += 1;
                    UnityEngine.Debug.Log("Completed Uploading " + fileInfo.Name);
                }
                else
                {
                    UnityEngine.Debug.Log("File : " + fileInfo.FullName + " does NOT need to be Updated/Uploaded!");
                }

            }
            else
            {
                UnityEngine.Debug.Log("Uploading File : " + fileInfo.FullName);
                request = (FtpWebRequest)FtpWebRequest.Create(new Uri(@"ftp://www.2depth.com/" + currentRomName + "/" + usernum + "/" + fileInfo.Name));
                request.Proxy = null;
                request.Method = WebRequestMethods.Ftp.UploadFile;
                request.Credentials = new NetworkCredential(@"KugiZuki@2depth.com", "200lander");
                request.UseBinary = true;
                request.UsePassive = true;

                using (Stream fileStream = File.OpenRead(fileInfo.FullName))
                {
                    using (Stream ftpStream = request.GetRequestStream())
                    {
                        fileStream.CopyTo(ftpStream);
                    }
                }
                uploadCount += 1;
                UnityEngine.Debug.Log("Completed Uploading " + fileInfo.Name);
                response = (FtpWebResponse)request.GetResponse();
                response.Close();

                request = (FtpWebRequest)WebRequest.Create(new Uri(@"ftp://www.2depth.com/" + currentRomName + "/" + usernum + "/" + fileInfo.Name));
                request.Method = WebRequestMethods.Ftp.GetDateTimestamp;
                request.Credentials = new NetworkCredential(@"KugiZuki@2depth.com", "200lander");
                response = (FtpWebResponse)request.GetResponse();
                string FTPDateString = (response.StatusDescription).Split(' ')[1];
                response.Close();

                DateTime FTPDateValue;
                FTPDateValue = DateTime.ParseExact(FTPDateString, "yyyyMMddHHmmss", CultureInfo.InvariantCulture.DateTimeFormat);

                File.SetLastWriteTime(fileInfo.FullName, FTPDateValue);
            }
            Thread.Sleep(2000);
        }
        response.Close();
        UnityEngine.Debug.Log("Completed Uploading " + uploadCount + " Graphic Files!");
    }
}
