# define Errors (-1)
# define no_Errors 0


# include "emulate.h"
# include "android_io.h"

#if QT_VERSION >= 0x060000
# include <QtGui> 
#endif

# include "MyClass.h"


# if defined OPENGL
# include "qtgl.h"
#endif

#if defined MULTIMEDIA
# include "qmultimedia.h"
#endif

# if defined WEBKIT
# include <QtWebKit/QWebView>
QWebView *view;
# include "download.h"
#endif

#if QT_VERSION >= 0x060000
# include <QTableWidget>
# include <QPushButton>
# include <QLabel>
# include <QProgressBar>
# include <QComboBox>
# include <QCheckBox>
# include <QSpinBox>
# include <QDialog>
# include <QLineEdit>
# include <QMessageBox>
# include <QFileDialog>
# include <QVBoxLayout>
# include <QMenu>
# include <QApplication>
# include <QQueue>
# include <QToolbar>
# include <QTimer>
# include <QMouseEvent>
# include <QPainter>
#endif

# include "pause.xpm"
# include "play.xpm"

int run_emu = 0;

KeybPortType *pf7fe, *pfbfe, *pfdfe, *pfefe, *peffe, *pdffe, *pbffe, *psffe;
kempston_type * kep;
int * j_t;

int j_t2 = 0;

int * GetJ2()
{
	return (&j_t2);
}

void play (char * buffer, int len);



MyClass * eh;

#if defined WEBKIT
download * dw;
#endif

MyMainWindow  * main_window = NULL;
QImage * qi = NULL;
paint_area1 * pa;

#if defined OPENGL
GLpaint_area * glpa;
#endif

paint_area * leds;

QTableWidget * w = NULL;

/*
QPushButton * tape_stop = NULL;
QPushButton * tape_pause = NULL;
QPushButton * tape_play = NULL;
QPushButton * tape_delete = NULL;
QPushButton * tape_view = NULL;
*/

QTimer * timer = NULL;


int timer_const = 20;

unsigned char * videomemory1;

QLabel * mode_b = 0, *tape_b = 0, *disk_b = 0, *status_s = 0;
QProgressBar * status_p = 0;

int SmoothPixmapTransform=0;

class PasswordWindow;

PasswordWindow * dlg1 = NULL;
PasswordWindow * dlg2 = NULL;

QComboBox *line_j1, *line_j2;
QCheckBox * KM;

char *** cl = NULL;

int Enter = 0;

QSpinBox *sp1, *sp2;


int fast_tape = 1;

QPushButton * ppp;

QPushButton *B1, *B22, *B3, *B4, *B5, *B6, *B7, *B8, *B9, *B10, *B11, *B12;
QToolBar * TB;


int Full_screen = 0;


int * g_Enter (void)
{
	return (&Enter);
}


int * GetSP()
{
	return (&SmoothPixmapTransform);
}

int aspect=0;

int * Get_aspect()
{
	return (&aspect);
}

int opengl = 0;

int * Get_opengl()
{
	return (&opengl);
}

QApplication * app;


MyClass::~MyClass(){}
MyClass::MyClass(QObject *parent): QObject(parent){}

#if defined WEBKIT
download::~download(){}
download::download(QObject *parent): QObject(parent){}
#endif


#if defined OPENGL
GLpaint_area::GLpaint_area(QWidget *parent)    : QGLWidget(parent){setMouseTracking(1);}
#endif

paint_area::paint_area(QWidget *parent)      : QWidget(parent){}
paint_area1::paint_area1(QWidget *parent)    : QWidget(parent){setMouseTracking(1);}

int x1, Visual_studio_2010_math_h, w1, h1;
int x2, y2, w2, h2;
int x3, y3, w3, h3;

int first_time = 10;

QCheckBox *pixmaps, *interlaced, *keep, *ogl, *sloww;

QDialog * dlg;
QComboBox * line1, * line2, *line3, *lin4;
QLineEdit * line5, *line6, *line666;

#if defined MULTIMEDIA
AudioTest * qaudio = NULL;
Generator * generator = NULL;
#endif

QQueue<char> queue;

#define SBLEN 882*8
char sbuffer[SBLEN];

QLineEdit * ao;
QWidget * DW;
QSlider * slider;

const char * soss = "OSS";
const char * sqt = "Qt Multimedia";
const char * snosound = "No sound";
const char * ssolaris = "Solaris native";
const char * smac = "OpenAL";
const char * swin = "Windows native";
const char * salsa = "Alsa";

int slow=0;

int * Get_slow()
{
	return (&slow);
}


#if defined WIN32
const char * ss = swin;
#else

#if defined SOLARIS
const char * ss = ssolaris;
#else

#if defined LINUX
const char * ss = soss;
#else

#if defined MACOSX
const char * ss = smac;
#else

#if defined MULTIMEDIA
const char * ss = sqt;
#else

const char * ss = snosound;

#endif
#endif
#endif
#endif
#endif

char jjjj = -1;



void MessageBoxInfo(QString a);





const char ** Get_ss()
{
	return (&ss);
}

soundthreadclass * s=NULL ;

int push = -1;

int e_pause = 0;

char empty[882*4] = {0};

QCheckBox * tt, *fastl;


/*
int * Get_fast_tape()
{
	return (&fast_tape);
}
*/

void focus (void)
{
#if defined OPENGL

	if (!opengl)
		pa->setFocus();
	else
		glpa->setFocus();
#else
	pa->setFocus();
#endif
}

class PasswordWindow : public QDialog
{
public:
	PasswordWindow( QWidget* parent=0, Qt::WindowFlags f = Qt::WindowFlags()) : QDialog(parent, f) 
	{
		ignore = 1;
	}

	int ignore;

protected:
	void closeEvent ( QCloseEvent * event ) 
	{
		focus();
	}
};




void SetSS(char * arg) 
{
	if (QString (arg) == QString (soss)) ss = soss;
	if (QString (arg) == QString (sqt)) ss = sqt;
	if (QString (arg) == QString (snosound)) ss = snosound;
	if (QString (arg) == QString (ssolaris)) ss = ssolaris;
	if (QString (arg) == QString (smac)) ss = smac;
	if (QString (arg) == QString (swin)) ss = swin;
	if (QString (arg) == QString (salsa)) ss = salsa;
}

void Empty_Cursor()
{
	if (!opengl)
		pa->setCursor(QCursor( Qt::BlankCursor ));
	else
	{
		
#if defined OPENGL

		glpa->setCursor(QCursor( Qt::BlankCursor ));
#endif
	}
}

void Normal_Cursor()
{
	if (!opengl)
		pa->setCursor(QCursor( Qt::ArrowCursor ));
	else
	{
		;
#if defined OPENGL

		glpa->setCursor(QCursor( Qt::ArrowCursor ));
#endif
	}
}

void MyClass::apply_settings()
{
	char mode_copy[32];
	char opengl_copy = opengl;


	strcpy(mode_copy, GetMode());

	if (pixmaps->checkState()==Qt::Checked) SmoothPixmapTransform = 1;
	if (pixmaps->checkState()==Qt::Unchecked) SmoothPixmapTransform = 0;

	if (keep->checkState()==Qt::Checked) aspect = 1;
	if (keep->checkState()==Qt::Unchecked) aspect = 0;

	if (interlaced->checkState()==Qt::Checked) 
	{
		qi->fill(0xFF000000);
		SetScan(1);
	}

	if (interlaced->checkState()==Qt::Unchecked) SetScan(0);    

	if (line1->currentIndex()==0) strcpy(GetMode(), "48");
	if (line1->currentIndex()==1) strcpy(GetMode(), "128");
	if (line1->currentIndex()==2) strcpy(GetMode(), "Pentagon");
	if (line1->currentIndex()==3) strcpy(GetMode(), "Scorpion");


#if defined OPENGL
	opengl = ogl->checkState();
#endif

	if (qstricmp(GetMode(), mode_copy))
		reset_h();

	if (opengl!=opengl_copy)
	{
		main_window->close();
		Main_Window();
		first_time = 10;
	}

	slow = sloww->checkState();

	new_audio(lin4->currentIndex ());

	if (line2->itemText(line2->currentIndex ()) == QString (soss)) ss = soss;
	if (line2->itemText(line2->currentIndex ()) == QString (sqt)) ss = sqt;
	if (line2->itemText(line2->currentIndex ()) == QString (snosound)) ss = snosound;
	if (line2->itemText(line2->currentIndex ()) == QString (ssolaris)) ss = ssolaris;
	if (line2->itemText(line2->currentIndex ()) == QString (smac)) ss = smac;
	if (line2->itemText(line2->currentIndex ()) == QString (swin)) ss = swin;
	if (line2->itemText(line2->currentIndex ()) == QString (salsa)) ss = salsa;

	*GetSM() = line3->currentIndex ();
	*GetBV() = slider->value();

	strcpy(Get_audio_name(), (char *) ao->text().toLocal8Bit().data());

	*j_t = line_j1->currentIndex();
	j_t2 = line_j2->currentIndex();

	if (KM->checkState()==Qt::Checked) 
	{
		*GetKM() = 1;
		Empty_Cursor();
	}

	if (KM->checkState()==Qt::Unchecked) 
	{
		*GetKM() = 0;
		Normal_Cursor();
	}

	strcpy(ImagesDir(), line5->text().toLocal8Bit().data());

	//dlg->close();    

	focus();	
}

void MyClass::full_screen()
{
	static int flipflop = 0;

	flipflop = 1-flipflop;

	if (flipflop)
	{
		Full_screen = 1;
		/*
		B1->hide(); B22->hide(); B3->hide(); B4->hide(); B5->hide(); B6->hide(); 
		B7->hide(); B8->hide(); B9->hide(); B10->hide(); B11->hide(); B12->hide(); 
		*/
		//main_window->setWindowFlags(Qt::CustomizeWindowHint | Qt::FramelessWindowHint);

		TB->hide();
		main_window->showFullScreen();

	}
	else
	{
		Full_screen = 0;
		/*
		B1->show(); B22->show(); B3->show(); B4->show(); B5->show(); B6->show(); 
		B7->show(); B8->show(); B9->show(); B10->show(); B11->show(); B12->show(); 
		*/
		TB->show();
		main_window->showNormal();
	}

	focus();	
}	

void pshow()
{
	if (!e_pause)
		ppp->setIcon(QIcon(QPixmap(pause)));
	else
		ppp->setIcon(QIcon(QPixmap(Play)));
}

void MyClass::save()
{
	QFileDialog::Options options;
	QString selectedFilter;

	e_pause = 1;
	pshow();

	QString fileName = QFileDialog::getSaveFileName(main_window,
		"Glukalka",
		"",
		tr("Z80 snapshots (*.z80)"),
		&selectedFilter,

		options); 

	if (!fileName.isEmpty())
	{
		QByteArray ba  = fileName.toUtf8();
		char * s = (char *)ba.constData();

		char fn[1028];

		if (!qstricmp(&s[strlen(s)-4], ".z80"))
			strcpy(fn, s);
		else
		{
			strcpy(fn, s);
			strcat(fn , ".z80");
		}

		SaveZ80(fn, "");	

		e_pause = 0;
		 pshow();
	}

	focus();
}

#if defined OPENGL

QSize GLpaint_area::minimumSizeHint() const
{
	return QSize(320, 240);
}

QSize GLpaint_area::sizeHint() const
{
	int x, y;

	GetWH(&x, &y);

	return QSize(x, y);
}

#endif


QSize paint_area1::minimumSizeHint() const
{
	return QSize(320, 240);
}

QSize paint_area1::sizeHint() const
{
	int x, y;

	GetWH(&x, &y);

	return QSize(x, y);
}

void TapeSetString(char * arg, int persent)
{
	if (!status_s) return;

	status_s->setText(arg);

	status_p->setValue(persent);
}

void ShowTape(int show)
{
	if (show)
	{
		tape_b->setVisible(true);
		status_p->setVisible(true);
	}
	if (!show)
	{
		tape_b->setVisible(false);
		status_p->setVisible(false);
	}
}

void ShowDisk(int show)
{
	if (show)
		disk_b->setVisible(true);
	if (!show)
		disk_b->setVisible(false);
}

void Show128mode(int m_128)
{
	if (!mode_b)
		return;

	if (!m_128)
		mode_b->setPixmap(QPixmap("images/48.xpm"));
	else
		mode_b->setPixmap(QPixmap("images/128.xpm"));    	
}

QString fromutf(char * arg)
{
	if (!arg)
		return ("");
	return (QDir::fromNativeSeparators(QString::fromUtf8(arg)));
}

void MyClass::play_pause()
{
	e_pause = 1 - e_pause;
	run_emu=  0;
	pshow();

	if (e_pause)
	{

#if defined OPENGL
		if (opengl)
			glpa->repaint();
		else
			pa->repaint();
#else
		pa->repaint();
#endif
	}

	focus();
}


void MyClass::Play()
{
	e_pause = 0;
	run_emu = 0;
	pshow();

	if (fast_tape && (*GetSQT()==2))
		fast_tape = 0;

	if (e_pause)
	{


#if defined OPENGL
		if (opengl)
			glpa->repaint();
		else
			pa->repaint();
#else
		pa->repaint();
#endif
	}

	focus();
}

void MyClass::about()
{
	QMessageBox msgBox;
	//msgBox.setTextInteractionFlags(Qt::TextSelectableByMouse);
	msgBox.setText( "Dmitry Sanarin\ndmitry@sanarin.ru\nMonero (XMR) Address:\n43MbSqKJUa34kVqg45FwU9JeN8SremHvJ125CaTi3q8rASQ6bvk2bafNb9p5eJR5KqQ3cJjcLnQZGa88B2SHfBHxQfYAJ96");
	msgBox.setIcon(QMessageBox::Information);
	msgBox.setWindowTitle("Glukalka ZX Spectrum emulator");
	msgBox.exec();

	focus();
}


# if defined WEBKIT


FileDownloader * m_pImgCtrl;
QString filename;


void download::loadImage()
{
	QFile file(filename);
	file.open(QIODevice::WriteOnly);
	file.write(m_pImgCtrl->downloadedData());
	file.close();

	MessageBoxInfo(filename + " - Download complete");
}

void download::unsupportedContent(QNetworkReply * a)
{
	QNetworkReply * aaa = (QNetworkReply *) a;

	QUrl URL = aaa->url();
	

	 QFileInfo fileInfo(URL.path());
	 filename=fromutf(ImagesDir())+"/"+fileInfo.fileName();	


	m_pImgCtrl = new FileDownloader(URL, this);

	connect(m_pImgCtrl, SIGNAL (downloaded()), dw, SLOT (loadImage()));
}

void download::go()
{
	view->load(QUrl(line6->text()));
	QWebPage *p = view->page();
	p->setForwardUnsupportedContent(true);

	//QNetworkReply
	connect(view->page(), SIGNAL(unsupportedContent(QNetworkReply*)), dw, SLOT(unsupportedContent(QNetworkReply*)));
}


FileDownloader::FileDownloader(QUrl imageUrl, QObject *parent) :
QObject(parent)
{
	connect(
		&m_WebCtrl, SIGNAL (finished(QNetworkReply*)),
		this, SLOT (fileDownloaded(QNetworkReply*))
		);

	QNetworkRequest request(imageUrl);
	m_WebCtrl.get(request);
}

FileDownloader::~FileDownloader() { }

void FileDownloader::fileDownloaded(QNetworkReply* pReply) {
	m_DownloadedData = pReply->readAll();
	//emit a signal
	pReply->deleteLater();
	emit downloaded();
}

QByteArray FileDownloader::downloadedData() const {
	return m_DownloadedData;
}


#endif

void MyClass::nmi()
{
	GenerateNMI();
	focus();
}

void MyClass::web()
{
# if defined WEBKIT

	char errm[3000];

	const QFileInfo outputDir(fromutf(ImagesDir()));
    if ((!outputDir.exists()) || (!outputDir.isDir()) || (!outputDir.isWritable())) 
	{
		sprintf (errm, "Your images directory (%s) does not exist,  or is not writeable. Select correct directory (Settings button->Images Path).", ImagesDir());
        MessageBoxErr(errm);
        return;
    }

	dlg = new QDialog(main_window, Qt::Window);
	dlg->setModal(true);
	dlg->setWindowTitle(tr("Get file from the Web"));

	QVBoxLayout *vlayout = new QVBoxLayout;

	QHBoxLayout *hlayout = new QHBoxLayout;
	
	line6 = new QLineEdit(dlg);
	hlayout->addWidget(line6);

	line6->setToolTip(tr("Complete URL including http(s)://"));

	QPushButton * go = new QPushButton(tr("Go"), dlg);
	dlg->connect(go, SIGNAL(clicked()), dw, SLOT(go()));
	hlayout->addWidget(go);

	vlayout->addLayout(hlayout);

	view = new QWebView(dlg);
	view->load(QUrl("http://www.sanarin.ru/glukalka/.Games/"));
	QWebPage *p = view->page();
	p->setForwardUnsupportedContent(true);

	connect(view->page(), SIGNAL(unsupportedContent(QNetworkReply*)), dw, SLOT(unsupportedContent(QNetworkReply*)));

	view->show();

	vlayout->addWidget(view);


	QPushButton * pb = new QPushButton(tr("Close"), dlg);
	dlg->connect(pb, SIGNAL(clicked()), eh, SLOT(Close()));
	vlayout->addWidget(pb);

	dlg->setLayout(vlayout);
	dlg->show();
#else
	MessageBoxErr("No WebKit support in your QT!");
#endif

}

void MyClass::browse()
{
	QString dir = QFileDialog::getExistingDirectory(main_window, tr("Select Directory"),
		"",
		QFileDialog::ShowDirsOnly
		| QFileDialog::DontResolveSymlinks);

	line5->setText(dir);	
}


void MyClass::b_1()
{
	QFileDialog::Options options;
	QString selectedFilter;

	QFileDialog * fd = new QFileDialog();


	fd->setDirectory(fromutf(ImagesDir()));


	QString fileName = fd->getOpenFileName(main_window,
		"",
		"",
		tr("Supported files (*.scl *.fdi)"),
		&selectedFilter,
		options); 

	focus();

	if ((!fileName.size()) )
	{
	}
	else
	{
		line666->setText(fileName);
		SetDisk((char *)fileName.toUtf8().constData(), 1);
	}
}

void MyClass::rrrun()
{
	run_emu = 1-run_emu;
	e_pause = 0;
	pshow();
	focus();
}

void MyClass::record()
{
	static int record = 0;

	if (!record)
	{
		QFileDialog::Options options;
		QString selectedFilter;

		e_pause = 1;
		pshow();

		QString fileName = QFileDialog::getSaveFileName(main_window,
			"Glukalka",
			"",
			tr("PSG sound module (*.psg)"),
			&selectedFilter,

			options); 

		if (!fileName.isEmpty())
		{
			QByteArray ba  = fileName.toUtf8();
			char * s = (char *)ba.constData();

			char fn[1028];

			if (!qstricmp(&s[strlen(s)-4], ".psg"))
				strcpy(fn, s);
			else
			{
				strcpy(fn, s);
				strcat(fn , ".psg");
			}

			DumpPSG(fn, "", 1);	
			record = 1;

			e_pause = 0;
			pshow();
		}
		else
		{
			e_pause = 0;
			pshow();
		}
	}
	else
	{
		DumpPSG("", "", 0);	
		record = 0;

		MessageBoxInfo("Dump is compleled.");
	}

	focus();
}


void MyClass::rst()
{
	QMessageBox msgBox;

	msgBox.setWindowTitle("Glukalka");
	msgBox.setText("Reset ?");
	//msgBox.setInformativeText("Reset ?");
	msgBox.setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel);
	msgBox.setDefaultButton(QMessageBox::Cancel);
	msgBox.setIcon(QMessageBox::Question);

	int ret = msgBox.exec();

	switch (ret) 
	{
	case QMessageBox::Ok:

		reset_h();

	case QMessageBox::Cancel:

		focus();	

		break;
	default:
		break;
	}


}

void MyClass::Close()
{
	dlg->close();    
	focus();	
}

char *** cards_list(void);

void MyClass::FillAudioList(void)
{
	cl = NULL;

	if ((line2->itemText(line2->currentIndex ()) == QString (swin)) || (line2->itemText(line2->currentIndex ()) == QString (soss))
		|| (line2->itemText(line2->currentIndex ()) == QString (ssolaris)) || (line2->itemText(line2->currentIndex ()) == QString (smac))) 
	{
		lin4->clear();


#if defined MACOSX
		cl = cards_list();
#endif

#if defined WIN32
		cl = cards_list();
#endif

#if defined LINUX
		cl = cards_list();
#endif

#if defined SOLARIS
		cl = cards_list();
#endif

		//printf ("1\n");

		if (cl)
		{
			int i=0;
			while (strlen(cl[i][1]))
			{
				//printf ("2\n");

				//printf("%s \n", ao->text().toLocal8Bit().data());

				lin4->addItem(QString::fromUtf8 (cl[i][1]));

				if (! qstricmp (cl[i][0], ao->text().toLocal8Bit().data()))
				{
					//printf("%d %s %s \n", i, cl[i][0], ao->text().toLocal8Bit().data());
					lin4->setCurrentIndex(i);
				}

				i++;
			}
		}
	}
	else
	{
		lin4->clear();
		ao->clear();
	}
}

void MyClass::new_audio(int i)
{
	if ((i>=0) && cl)
	{
		ao->setText(cl[i][0]);
		//printf("%s %d \n", cl[i][0]);
	}
}

void MyClass::pi1(void)
{
	if (cl)
	{
		int i=0;
		while (strlen(cl[i][1]))
		{
			if (! qstricmp (cl[i][0], ao->text().toLocal8Bit().data()))
				lin4->setCurrentIndex(i);

			i++;
		}
	}
}

void SaveIniFile(void);

void MessageBoxInfo(QString a)
{
	QMessageBox msgBox;
	msgBox.setText(a);
	msgBox.setIcon(QMessageBox::Information);
	msgBox.setWindowTitle("Glukalka2");
	msgBox.exec();
}

void MyClass::save_settings()
{
	apply_settings();
	SaveIniFile();
	MessageBoxInfo(tr("Settings saved"));
}

void MyClass::settings()
{    
	dlg = new QDialog(main_window, Qt::Window);
	dlg->setModal(true);
	dlg->setWindowTitle(tr("Settings"));

	QVBoxLayout *vlayout = new QVBoxLayout;


	QTabWidget  * tab =  new QTabWidget;

	QWidget *tab1; 
	QVBoxLayout *tab1hbox;

	tab1 = new QWidget;
	tab1hbox = new QVBoxLayout;

	QCheckBox *  cb = new QCheckBox(tr("Filtering"));       
	if (SmoothPixmapTransform)
		cb->setCheckState(Qt::Checked);
	else
		cb->setCheckState(Qt::Unchecked);
	tab1hbox->addWidget(cb);
	pixmaps=cb;

	cb = new QCheckBox(tr("Interlaced mode"));
	if (GetScan())
		cb->setCheckState(Qt::Checked);
	else
		cb->setCheckState(Qt::Unchecked);
	tab1hbox->addWidget(cb);
	interlaced=cb;

	cb = new QCheckBox(tr("Keep aspect ratio"));
	if (aspect)
		cb->setCheckState(Qt::Checked);
	else
		cb->setCheckState(Qt::Unchecked);
	tab1hbox->addWidget(cb);
	keep=cb;

#if defined OPENGL

	cb = new QCheckBox(tr("Use OpenGL"));
	if (opengl)
		cb->setCheckState(Qt::Checked);
	else
		cb->setCheckState(Qt::Unchecked);
	tab1hbox->addWidget(cb);
	ogl=cb;
#endif

	cb = new QCheckBox(tr("5 FPS (for slow systems)"));
	if (slow)
		cb->setCheckState(Qt::Checked);
	else
		cb->setCheckState(Qt::Unchecked);
	tab1hbox->addWidget(cb);
	sloww=cb;

	tab1->setLayout(tab1hbox);
	tab->addTab(tab1, tr("Screen"));                    

	tab1 = new QWidget;
	tab1hbox = new QVBoxLayout;

	line1 = new QComboBox(); 

	line1->addItem("ZX-Spectrum 48K");
	line1->addItem("ZX-Spectrum 128K");
	line1->addItem("Pentagon 128K");
	line1->addItem("ZS-Scorpion 256K");

	if (!strcmp(GetMode(), "48")) line1->setCurrentIndex (0);
	if (!strcmp(GetMode(), "128")) line1->setCurrentIndex (1);
	if (!qstricmp(GetMode(), "Pentagon")) line1->setCurrentIndex (2);
	if (!qstricmp(GetMode(), "Scorpion")) line1->setCurrentIndex (3);

	tab1hbox->addWidget(line1);

	tab1->setLayout(tab1hbox);

	tab->addTab(tab1, tr("Architecture"));        






	tab1 = new QWidget;
	tab1hbox = new QVBoxLayout;

	QHBoxLayout * h = new QHBoxLayout;

	h->addWidget(new QLabel("Working directory"));

	line5 = new QLineEdit(); 

	line5->setText(ImagesDir());

	h->addWidget(line5);

	QPushButton * pb1;

	pb1 = new QPushButton(tr("Browse"), dlg);
	eh->connect(pb1, SIGNAL(clicked()), eh, SLOT(browse()));
	h->addWidget(pb1);

	tab1hbox->addLayout(h);


	h = new QHBoxLayout;

	h->addWidget(new QLabel("Disk B"));

	line666 = new QLineEdit(); 

	line666->setText(GetDisk1(1));

	h->addWidget(line666);

	QPushButton * pb2;

	pb2 = new QPushButton(tr("Browse"), dlg);
	eh->connect(pb2, SIGNAL(clicked()), eh, SLOT(b_1()));
	h->addWidget(pb2);



	tab1hbox->addLayout(h);
	tab1->setLayout(tab1hbox);


	tab->addTab(tab1, tr("Path"));   




	
	tab1 = new QWidget;
	tab1hbox = new QVBoxLayout;


		tt = new QCheckBox(tr("Tape traps"), dlg);
		tab1hbox->addWidget(tt);
		tt->setChecked(*GetTT());
		connect(tt,  SIGNAL(stateChanged (int)), this, SLOT(tt_changed()));

		
		fastl = new QCheckBox(tr("Fast loading"), dlg);
		tab1hbox->addWidget(fastl);
		fastl->setChecked(fast_tape);
		connect(fastl,  SIGNAL(stateChanged (int)), this, SLOT(fl_changed()));
		

	tab1->setLayout(tab1hbox);

	tab->addTab(tab1, tr("Tape"));




	tab1 = new QWidget;
	tab1hbox = new QVBoxLayout;

	line2 = new QComboBox(); 

	connect(line2, SIGNAL(currentIndexChanged (int)), eh, SLOT(FillAudioList(void)));

	tab1hbox->addWidget(line2);

	QHBoxLayout *hlayout = new QHBoxLayout;

	hlayout->addWidget(new QLabel(tr("Output device")));

	ao = new QLineEdit(dlg);

	connect(ao, SIGNAL(textChanged ( const QString & )), eh, SLOT(pi1(void)));

	hlayout->addWidget(ao);


	ao->setText(Get_audio_name());
	pi1();

	lin4 = new QComboBox(dlg);
	hlayout->addWidget(lin4);

	tab1hbox->addLayout(hlayout);


#if defined LINUX
	line2->addItem(soss);
	if (ss==soss)line2->setCurrentIndex (line2->count () -1);	
#endif	

#if defined SOLARIS
	line2->addItem(ssolaris);
	if (ss==ssolaris)line2->setCurrentIndex (line2->count () -1);	
#endif	

#if defined MACOSX
	line2->addItem(smac);
	if (ss==smac)line2->setCurrentIndex (line2->count () -1);	
#endif	

#if defined WIN32
	line2->addItem(swin);
	if (ss==swin)line2->setCurrentIndex (line2->count () -1);
#endif	

#if defined MULTIMEDIA	
	line2->addItem(sqt);
	if (ss==sqt)line2->setCurrentIndex (line2->count () -1);	
#endif

	line2->addItem(snosound);
	if (ss==snosound)line2->setCurrentIndex (line2->count () -1);	

	//printf ("FIL\n");

	FillAudioList();

	connect(lin4, SIGNAL(currentIndexChanged (int)), eh, SLOT(new_audio(int)));

	line3 = new QComboBox(); 

	line3->addItem("ACB Stereo");
	line3->addItem("ABC Stereo");
	line3->addItem("Mono");

	tab1hbox->addWidget(line3);

	hlayout = new QHBoxLayout;

	hlayout->addWidget(new QLabel(tr("Beeper volume")));

	slider = new QSlider(Qt::Horizontal);
	slider->setRange(0, 15);

	hlayout->addWidget(slider);

	QSpinBox * valueSpinBox;

	valueSpinBox = new QSpinBox;
	valueSpinBox->setRange(0, 15);
	valueSpinBox->setSingleStep(1);

	hlayout->addWidget(valueSpinBox);

	slider->setValue(*GetBV());
	valueSpinBox->setValue(*GetBV());
	line3->setCurrentIndex (*GetSM());          

	connect(slider, SIGNAL(valueChanged(int)), valueSpinBox, SLOT(setValue(int)));
	connect(valueSpinBox, SIGNAL(valueChanged(int)), slider, SLOT(setValue(int)));
	connect(line2, SIGNAL(currentIndexChanged(int)), ao, SLOT(clear()));

	tab1hbox->addLayout(hlayout);

	tab1->setLayout(tab1hbox);
	tab->addTab(tab1, tr("Sound"));                    

	tab1 = new QWidget;
	tab1hbox = new QVBoxLayout;

	QHBoxLayout * tab2hbox = new QHBoxLayout;
	tab2hbox->addWidget(new QLabel(tr("Joystick 1 (cursor keys)")));
	tab2hbox->addWidget(line_j1 = new QComboBox()); 
	tab1hbox->addLayout(tab2hbox);

	line_j1->addItem("Kempston");
	line_j1->addItem("Sinclair");
	line_j1->addItem("Cursor");
	line_j1->addItem("OPQA");

	line_j1->setCurrentIndex (*j_t);

	tab2hbox = new QHBoxLayout;
	tab2hbox->addWidget(new QLabel(tr("Joystick 2 (analogue)")));
	tab2hbox->addWidget(line_j2 = new QComboBox()); 
	tab1hbox->addLayout(tab2hbox);

	line_j2->addItem("Kempston");
	line_j2->addItem("Sinclair");
	line_j2->addItem("Cursor");

	line_j2->setCurrentIndex (j_t2);

	tab2hbox = new QHBoxLayout;
	tab2hbox->addWidget(new QLabel(tr("Kempston mouse")));
	tab2hbox->addWidget(KM = new QCheckBox(tr("Enabled"))); 
	tab1hbox->addLayout(tab2hbox);

	if (*GetKM())
		KM->setCheckState(Qt::Checked);
	else
		KM->setCheckState(Qt::Unchecked);

	tab1->setLayout(tab1hbox);

	tab->addTab(tab1, tr("Controls"));                    

	vlayout->addWidget(tab);

	hlayout = new QHBoxLayout;
	hlayout->setAlignment (Qt::AlignRight);

	QPushButton * pb;

	pb = new QPushButton(tr("Save"), dlg);
	eh->connect(pb, SIGNAL(clicked()), eh, SLOT(save_settings()));
	hlayout->addWidget(pb);

	pb = new QPushButton(tr("Apply"), dlg);
	eh->connect(pb, SIGNAL(clicked()), eh, SLOT(apply_settings()));
	hlayout->addWidget(pb);

	pb = new QPushButton(tr("Close"), dlg);
	dlg->connect(pb, SIGNAL(clicked()), eh, SLOT(Close()));
	hlayout->addWidget(pb);


	vlayout->addLayout(hlayout);

	dlg->setLayout(vlayout);
	//dlg->resize(dlg->minimumSize());
	dlg->show();
}       

void MyClass::tt_changed()
{
	*GetTT() = tt->isChecked ();
}

void MyClass::fl_changed()
{
	fast_tape = fastl->isChecked ();
}

void EnsureVisibleAndSelect(int p)
{
	w->selectRow(p - 1);
}


void MyClass::Close1()
{
	dlg1->close();    
	focus();	
}

void MyClass::Close2()
{
	dlg2->close();    
	focus();	
}

unsigned char io_readByte(unsigned short address);

void MyClass::peek()
{
	sp2->setValue(io_readByte(sp1->value()));	
	focus();
}

void io_writeByte(unsigned short address, unsigned char byte);

void MyClass::poke()
{
	io_writeByte(sp1->value(), sp2->value());
	focus();
}

void MyClass::POKE()
{
	QHBoxLayout *hlayout;

	if (!dlg2)
	{
		dlg2 = new PasswordWindow(main_window);
		dlg2->setModal(false);

		dlg2->setWindowTitle(tr("PEEK/POKE"));

		QVBoxLayout *vlayout = new QVBoxLayout;

		hlayout= new QHBoxLayout;

		hlayout->addWidget(new QLabel(tr("Address")));
		sp1 = new QSpinBox();
		sp1->setRange(0, 65535);

		hlayout->addWidget(sp1);

		vlayout->addLayout(hlayout);


		hlayout= new QHBoxLayout;

		hlayout->addWidget(new QLabel(tr("Value")));
		sp2 = new QSpinBox();
		sp2->setRange(0, 255);

		hlayout->addWidget(sp2);

		vlayout->addLayout(hlayout);


		hlayout= new QHBoxLayout;

		QPushButton * b;

		b = new QPushButton(tr("PEEK"));
		connect(b,  SIGNAL(clicked ()), this, SLOT(peek()));
		hlayout->addWidget(b);

		b = new QPushButton(tr("POKE"));
		connect(b,  SIGNAL(clicked ()), this, SLOT(poke()));
		hlayout->addWidget(b);

		b = new QPushButton(tr("Close"));
		connect(b,  SIGNAL(clicked ()), this, SLOT(Close2()));
		hlayout->addWidget(b);

		vlayout->addLayout(hlayout);



		dlg2->setLayout(vlayout);

		dlg2->show(); 
	}
	else                                   
		dlg2->show();      
}

void MyClass::tape_dialog()
{
	if (!dlg1)
	{
		dlg1 = new PasswordWindow(main_window);
		dlg1->setModal(false);
		dlg1->resize(600, 410);                               
		dlg1->setWindowTitle(tr("Tape settings"));

		QVBoxLayout *vlayout = new QVBoxLayout;
		//vlayout->setSpacing(0);

		w = new QTableWidget(100, 3); 
		QStringList headerLabels;
		headerLabels << tr("type") << tr("length") << tr("advanced");
		w->setHorizontalHeaderLabels(headerLabels);
		w->setColumnWidth(0, 100);
		w->setColumnWidth(1, 70);
		w->setColumnWidth(2, 350);

		w->connect(w, SIGNAL(cellActivated ( int , int  )), w, SLOT(selectRow ( int)));

		vlayout->addWidget(w);

		/*
		QHBoxLayout *hlayout = new QHBoxLayout;

		QHBoxLayout *hhlayout = new QHBoxLayout;
		hhlayout->setContentsMargins(5,3,3,3);


		QPushButton * pb = new QPushButton(tr("Open file"), dlg);
		hhlayout->addWidget(pb);

		pb = new QPushButton("MIC->Direct rec", dlg);
		hhlayout->addWidget(pb);

		pb = new QPushButton(tr("Delete block(s)"), dlg);
		hhlayout->addWidget(pb);
		tape_delete=pb;

		pb = new QPushButton(tr("Eject image"), dlg);
		hhlayout->addWidget(pb);

		QGroupBox * g = new QGroupBox(tr("File"));
		g->setLayout(hhlayout);

		hlayout->addWidget(g);

		hlayout->addItem(new QSpacerItem(0, 0, QSizePolicy::Minimum, QSizePolicy::Minimum));

		vlayout->addLayout(hlayout);
		hlayout = new QHBoxLayout;
		hlayout->setAlignment(Qt::AlignLeft);

		hhlayout = new QHBoxLayout;
		hhlayout->setContentsMargins(5,3,3,3);

		pb = new QPushButton(tr("Play"), dlg);
		hhlayout->addWidget(pb);
		tape_play=pb;

		pb = new QPushButton(tr("Pause"), dlg);
		hhlayout->addWidget(pb);
		tape_pause=pb;

		pb = new QPushButton(tr("Stop"), dlg);
		hhlayout->addWidget(pb);
		tape_stop=pb;

		pb = new QPushButton(tr("Block info"), dlg);
		hhlayout->addWidget(pb);
		tape_view=pb;

		g = new QGroupBox(tr("Block"));
		g->setLayout(hhlayout);

		hlayout->addWidget(g);
		*/

		QHBoxLayout * hlayout;


		hlayout = new QHBoxLayout;
		hlayout->setAlignment(Qt::AlignLeft);

		tt = new QCheckBox(tr("Tape traps"), dlg1);
		hlayout->addWidget(tt);
		tt->setChecked(*GetTT());
		connect(tt,  SIGNAL(stateChanged (int)), this, SLOT(tt_changed()));

		
		fastl = new QCheckBox(tr("Fast loading"), dlg1);
		hlayout->addWidget(fastl);
		fastl->setChecked(fast_tape);
		connect(fastl,  SIGNAL(stateChanged (int)), this, SLOT(fl_changed()));
		

		QPushButton * pb = new QPushButton(tr("Close"), dlg1);
		eh->connect(pb, SIGNAL(clicked()), eh, SLOT(Close1()));
		hlayout->addWidget(pb);

		vlayout->addLayout(hlayout);

		dlg1->setLayout(vlayout);
	}
	else                                   
		dlg1->show();                                               
}

int * Leds();

void keys(QKeyEvent * event, int up)
{
	if (Enter)
		return;

	switch(event->key())
	{
	case Qt::Key_F10:
		if (!up)
			eh->full_screen();
		break;

	case Qt::Key_F9:
		if (up)
			*Leds() = 1- *Leds();
		break;

	case Qt::Key_Exclam:
	case Qt::Key_1:
		pf7fe->d0=up;
		break;

	case Qt::Key_At:
	case Qt::Key_2:
		pf7fe->d1=up;
		break;

	case Qt::Key_NumberSign:
	case Qt::Key_3:
		pf7fe->d2=up;
		break;

	case Qt::Key_Dollar:
	case Qt::Key_4:
		pf7fe->d3=up;
		break;

	case Qt::Key_Percent:
	case Qt::Key_5:
		pf7fe->d4=up;
		break;

	case Qt::Key_Q:
		pfbfe->d0=up;
		break;

	case Qt::Key_W:
		pfbfe->d1=up;
		break;

	case Qt::Key_E:
		pfbfe->d2=up;
		break;

	case Qt::Key_R:
		pfbfe->d3=up;
		break;

	case Qt::Key_T:
		pfbfe->d4=up;
		break;

	case Qt::Key_A:
		pfdfe->d0=up;
		break;

	case Qt::Key_S:
		pfdfe->d1=up;
		break;

	case Qt::Key_D:
		pfdfe->d2=up;
		break;

	case Qt::Key_F:
		pfdfe->d3=up;
		break;

	case Qt::Key_G:
		pfdfe->d4=up;
		break;

	case Qt::Key_Shift:
		pfefe->d0=up;
		break;

	case Qt::Key_Z:
		pfefe->d1=up;
		break;

	case Qt::Key_X:
		pfefe->d2=up;
		break;

	case Qt::Key_C:
		pfefe->d3=up;
		break;

	case Qt::Key_V:
		pfefe->d4=up;
		break;

	case Qt::Key_AsciiCircum:
	case Qt::Key_6:
		peffe->d4=up;
		break;

	case Qt::Key_Ampersand:
	case Qt::Key_7:
		peffe->d3=up;
		break;


	case Qt::Key_Asterisk:
	case Qt::Key_8:
		peffe->d2=up;
		break;

	case Qt::Key_ParenLeft:
	case Qt::Key_9:
		peffe->d1=up;
		break;

	case Qt::Key_ParenRight:
	case Qt::Key_0:
		//peffe->d0=up;
		joystick('0', up);
		break;

	case Qt::Key_Y:
		pdffe->d4=up;
		break;

	case Qt::Key_U:
		pdffe->d3=up;
		break;

	case Qt::Key_I:
		pdffe->d2=up;
		break;

	case Qt::Key_O:
		pdffe->d1=up;
		break;

	case Qt::Key_P:
		pdffe->d0=up;
		break;

	case Qt::Key_H:
		pbffe->d4=up;
		break;

	case Qt::Key_J:
		pbffe->d3=up;
		break;

	case Qt::Key_K:
		pbffe->d2=up;
		break;

	case Qt::Key_L:
		pbffe->d1=up;
		break;

	case Qt::Key_Return:
		pbffe->d0=up;


		break;

	case Qt::Key_B:
		psffe->d4=up;
		break;

	case Qt::Key_N:
		psffe->d3=up;
		break;

	case Qt::Key_M:
		psffe->d2=up;
		break;

	case Qt::Key_Alt:
		psffe->d1=up;
		break;

	case Qt::Key_Space:
		psffe->d0=up;
		break;	

	case Qt::Key_Backspace:
		pfefe->d0=up;
		peffe->d0=up;
		break;

	case Qt::Key_Insert:
	case Qt::Key_Control:
		if (*j_t==0)
			kep->bit.fire=1-up;
		if (*j_t==1)
			peffe->d0=up;
		if (*j_t==2)
		{
			peffe->d0=up;
		}
		if (*j_t==3)
			psffe->d0=up;
		break;

	case Qt::Key_Left:
		if (*j_t==0)
			kep->bit.left=1-up;
		if (*j_t==1)
			peffe->d4=up;
		if (*j_t==2)
		{
			pf7fe->d4=up;
			pfefe->d0=up;
		}
		if (*j_t==3)
			pdffe->d1=up;
		break;

	case Qt::Key_Right:
		if (*j_t==0)
			kep->bit.right=1-up;
		if (*j_t==1)
			peffe->d3=up;
		if (*j_t==2)
		{
			peffe->d2=up;	
			pfefe->d0=up;
		}
		if (*j_t==3)
			pdffe->d0=up;
		break;

	case Qt::Key_Up:
		if (*j_t==0)
			kep->bit.up=1-up;
		if (*j_t==1)
			peffe->d1=up;
		if (*j_t==2)
		{
			peffe->d3=up;	
			pfefe->d0=up;
		}
		if (*j_t==3)
			pfbfe->d0=up;
		break;

	case Qt::Key_Clear:
	case Qt::Key_Down:
		if (*j_t==0)
			kep->bit.down=1-up;
		if (*j_t==1)
			peffe->d2=up;
		if (*j_t==2)
		{
			peffe->d4=up;
			pfefe->d0=up;
		}
		if (*j_t==3)
			pfdfe->d0=up;
		break;

		/*
	case Qt::Key_Tab:
		psffe->d1=up;	 
		pfefe->d0=up;
		focus();
		break;
		*/

	case Qt::Key_Apostrophe:
		psffe->d1=up;	 
		pdffe->d0=up;
		break;

	case Qt::Key_Comma:
		psffe->d1=up;	 
		psffe->d3=up;
		break;

	case  Qt::Key_Semicolon:
		psffe->d1=up;	 
		pdffe->d1=up;
		break;

	case  Qt::Key_Equal:
		psffe->d1=up;	
		pbffe->d2=up;	
		break;

	case  Qt::Key_Minus:
		psffe->d1=up;	
		pbffe->d3=up;	
		break;

	case  Qt::Key_Period:
		psffe->d1=up;	 
		psffe->d2=up;
		break;

	case  Qt::Key_multiply:
		psffe->d1=up;	 
		psffe->d4=up;	
		break;

	case  Qt::Key_QuoteLeft:
		pfefe->d0=up;  
		pf7fe->d0=up;	
		break;

	case  Qt::Key_Escape:
		pfefe->d0=up;  
		psffe->d0=up;
		break;
	}
}

#if defined OPENGL

void GLpaint_area::keyPressEvent ( QKeyEvent * event ) 
{
	//printf("press %x \n", event->key());

	if (!event->isAutoRepeat())
		keys(event, 0);
}

void GLpaint_area::keyReleaseEvent ( QKeyEvent * event ) 
{
	//    printf("release %x \n", event->key());

	if (!event->isAutoRepeat())
		keys(event, 1);
}

#endif

void paint_area1::keyPressEvent ( QKeyEvent * event ) 
{
	//printf("press %x \n", event->key());

	if (!event->isAutoRepeat())
		keys(event, 0);
}

void paint_area1::keyReleaseEvent ( QKeyEvent * event ) 
{
	//    printf("release %x \n", event->key());

	if (!event->isAutoRepeat())
		keys(event, 1);
}


void paint_area::paintEvent(QPaintEvent * p)
{
	QPainter painter(this);

	painter.eraseRect(0, 0, this->width(), this->height());

	static int d[3][2]; 

# define C_START 50

	static int counter = C_START;

	if ((d[0][0] == w1) && (d[0][1] == h1) && (d[1][0] == w2) && (d[1][1] == h2) && (d[2][0] == w3) && (d[2][1] == h3))
	{
		if (counter)
			counter --;
	}
	else
	{
		counter = C_START;
	}

	if (counter && *Leds())
	{
		painter.fillRect(x1, Visual_studio_2010_math_h, w1, h1, QColor("green"));	
		painter.fillRect(x2, y2, w2, h2, QColor("green"));	
		painter.fillRect(x3, y3, w3, h3, QColor("green"));
	}

	d[0][0] = w1; d[0][1] = h1;
	d[1][0] = w2; d[1][1] = h2;
	d[2][0] = w3; d[2][1] = h3;
}

char Joy(void);
void J(void);

void paint_area1::paintEvent(QPaintEvent * p)
{
#if defined LINUX
	jjjj = Joy();
	J();
#endif

#if defined WIN32
	jjjj = Joy();
	J();
#endif

	if (Enter >= 2)
	{
		pbffe->d0 = 0;
		Enter -- ;
	}
	else
	{
		if (Enter == 1)
		{
			pbffe->d0 = 1;
			Enter = 0;
		}
	}

	QPainter painter(this);

	if (SmoothPixmapTransform)
		painter.setRenderHint(QPainter::SmoothPixmapTransform);

	if (!aspect)
		painter.drawImage(QRect (0, 0, this->width(), this->height()), *qi, QRectF (0, 0, 640, 480));
	else
	{
		int w, h, sx, sy, image_h, image_w;

		w=this->width();
		h=this->height();

		painter.fillRect(0, 0, w, h, QColor("black"));	

		if (((double)w/(double)h)>(32.0/24.0))
		{
			image_h=h;
			image_w=h*32/24;
			sx = (w-image_w)/2;	
			sy = 0;
		}
		else
		{
			image_w=w;
			image_h=w*24/32;
			sx = 0;
			sy = (h-image_h)/2;	
		}

		painter.drawImage(QRect (sx, sy, image_w, image_h), *qi, QRectF (0, 0, 640, 480));				
	}    

	if (e_pause)
	{
		QFont font("Century Schoolbook L", 80, 0, 0);
		font = QFont(font, painter.device());
		painter.setFont(font);
		painter.setPen(QColor(50, 50, 230));
		painter.drawText(QPointF(this->width()/2-170, this->height()/2+20), QString(tr("Pause")));
	}


	if (run_emu || ((*GetSQT() == 2) && fast_tape))
	{
		QFont font("Century Schoolbook L", 80, 0, 0);
		font = QFont(font, painter.device());
		painter.setFont(font);
		painter.setPen(QColor(50, 50, 230));
		painter.drawText(QPointF(this->width()/2-170, this->height()/2+20), QString(tr("Turbo")));
	}
}



void J(void)
{
	if(jjjj != -1)
	{
		//fire
		if (jjjj&16)
		{
			if (j_t2==0)
				kep->bit.fire=1;

			if (j_t2==1)
				peffe->d0=0;

			if (j_t2==2)
				peffe->d0=0;
		}
		else
		{
			if (j_t2==0)
				kep->bit.fire=0;

			if (j_t2==1)
				peffe->d0=1;

			if (j_t2==2)
				peffe->d0=1;
		}

		//left
		if (jjjj&1)
		{
			if (j_t2==0)
				kep->bit.left=1;
			if (j_t2==1)
				peffe->d4=0;
			if (j_t2==2)
			{
				pf7fe->d4=0;
				pfefe->d0=0;
			}
		}
		else
		{
			if (j_t2==0)
				kep->bit.left=0;
			if (j_t2==1)
				peffe->d4=1;
			if (j_t2==2)
			{
				pf7fe->d4=1;
				pfefe->d0=1;
			}
		}

		//right
		if (jjjj&2)
		{
			if (j_t2==0)
				kep->bit.right=1;
			if (j_t2==1)
				peffe->d3=0;
			if (j_t2==2)
			{
				peffe->d2=0;	
				pfefe->d0=0;
			}
		}
		else
		{
			if (j_t2==0)
				kep->bit.right=0;
			if (j_t2==1)
				peffe->d3=1;
			if (j_t2==2)
			{
				peffe->d2=1;	
				pfefe->d0=1;
			}
		}

		//down
		if (jjjj&4)
		{
			if (j_t2==0)
				kep->bit.down=1;
			if (j_t2==1)
				peffe->d2=0;
			if (j_t2==2)
			{
				peffe->d4=0;
				pfefe->d0=0;
			}
		}
		else
		{
			if (j_t2==0)
				kep->bit.down=0;
			if (j_t2==1)
				peffe->d2=1;
			if (j_t2==2)
			{
				peffe->d4=1;
				pfefe->d0=1;
			}
		}

		//up
		if (jjjj&8)
		{
			if (j_t2==0)
				kep->bit.up=1;
			if (j_t2==1)
				peffe->d1=0;
			if (j_t2==2)
			{
				peffe->d3=0;	
				pfefe->d0=0;
			}
		}
		else
		{
			if (j_t2==0)
				kep->bit.up=0;
			if (j_t2==1)
				peffe->d1=1;
			if (j_t2==2)
			{
				peffe->d3=1;	
				pfefe->d0=1;
			}
		}
	}
}


#if defined OPENGL

void GLpaint_area::paintEvent(QPaintEvent * p)
{
#if defined LINUX
	jjjj = Joy();
	J();
#endif

#if defined WIN32
	jjjj = Joy();
	J();
#endif

	if (Enter >= 2)
	{
		pbffe->d0 = 0;
		Enter -- ;
	}
	else
	{
		if (Enter == 1)
		{
			pbffe->d0 = 1;
			Enter = 0;
		}
	}

	QPainter painter(this);

	if (SmoothPixmapTransform)
		painter.setRenderHint(QPainter::SmoothPixmapTransform);

	if (!aspect)
		painter.drawImage(QRect (0, 0, this->width(), this->height()), *qi, QRectF (0, 0, 640, 480));
	else
	{
		int w, h, sx, sy, image_h, image_w;

		w=this->width();
		h=this->height();

		painter.fillRect(0, 0, w, h, QColor("black"));	

		if (((double)w/(double)h)>(32.0/24.0))
		{
			image_h=h;
			image_w=h*32/24;
			sx = (w-image_w)/2;	
			sy = 0;
		}
		else
		{
			image_w=w;
			image_h=w*24/32;
			sx = 0;
			sy = (h-image_h)/2;	
		}

		painter.drawImage(QRect (sx, sy, image_w, image_h), *qi, QRectF (0, 0, 640, 480));				
	}    

	if (e_pause)
	{
		QFont font("Century Schoolbook L", 80, 0, 0);
		font = QFont(font, painter.device());
		painter.setFont(font);
		painter.setPen(QColor(50, 50, 230));
		painter.drawText(QPointF(this->width()/2-170, this->height()/2+20), QString(tr("Pause")));
	}

	if (run_emu || ((*GetSQT() == 2) && fast_tape))
	{
		QFont font("Century Schoolbook L", 80, 0, 0);
		font = QFont(font, painter.device());
		painter.setFont(font);
		painter.setPen(QColor(50, 50, 230));
		painter.drawText(QPointF(this->width()/2-170, this->height()/2+20), QString(tr("Turbo")));
	}
}

#endif

void MyClass::openfile()
{
	QFileDialog::Options options;
	QString selectedFilter;
	static int first = 1;




	QFileDialog * fd = new QFileDialog();

	if (first)
	{
		fd->setDirectory(fromutf(ImagesDir()));
		first=0;
	}

	QString fileName = fd->getOpenFileName(main_window,
		"",
		"",
		tr("Supported files (*.z80 *.sna *.tap *.tzx *.wav *.trd *.scl *.fdi)"),
		&selectedFilter,
		options); 

	focus();

	if ((!fileName.size()) )
	{
	}
	else
	{
		e_pause = 1;
		pshow();
		//char * sss = (char *);

		open_file ("", (char *)fileName.toUtf8().constData());

		e_pause = 0;
		pshow();
	}
}

long long GetCurrentTime2()
{
	return (QDateTime::currentMSecsSinceEpoch() /*- QDateTime(QDate::currentDate()).toMSecsSinceEpoch()*/);
}

void MyClass::update()
{
	static int counter = 0;

	

	if (first_time)
	{
		if (opengl)
		{
#if defined OPENGL

			glpa->setMinimumSize(QSize(64,48));
			glpa->setMaximumSize(QSize(6400,4800));
#endif
		}
		else
		{
			pa->setMinimumSize(QSize(64,48));
			pa->setMaximumSize(QSize(6400,4800));
		}
		first_time -- ;
	}

	videomemory1 = qi->bits();

	//printf ("%d\n", *GetSQT());

	if (!e_pause)
	{

		if (run_emu || ((*GetSQT() == 2) && fast_tape))
		{
			unsigned long long start = GetCurrentTime2();

			while ((GetCurrentTime2() - start)<15)
				timerfunc();
		}
		else
			timerfunc();
	}

	if (slow)
	{
		if (++counter == 10)
		{
#if defined OPENGL
			if (opengl)
				glpa->repaint();
			else
				pa->repaint();
#else
			pa->repaint();
#endif

			leds->repaint();

			counter =0;
		}	
	}
	else
	{

#if defined OPENGL

		if (opengl)
			glpa->repaint();
		else
			pa->repaint();
#else
		pa->repaint();
#endif

		//leds->repaint();	
	}

	char * sound;

	if (!e_pause)
		sound = (char *) GetSoundBuffer();
	else
		sound = empty;

	if (ss==sqt)
	{
#if defined MULTIMEDIA
		if (qaudio)
		{
			if (qaudio->error==no_Errors)
			{
				for (int i=0; i<882*4; i++)
					queue.enqueue(sound[i]);	
			}
		}
#endif
	}

	if (ss==soss)
	{
# if defined LINUX
		play(sound, 882*4);
#endif
	}


	if (ss==smac)
	{
# if defined MACOSX
		play(sound, 882*4);
#endif
	}



	if (ss==swin)
	{
# if defined WIN32
		play(sound, 882*4);
#endif
	}

	if (ss==ssolaris)
	{
# if defined SOLARIS
		play(sound, 882*4);
#endif
	}
}


void set_size(int s)
{
#if defined OPENGL
	if (opengl)
		glpa->setFixedSize(QSize(320*s, 240*s));
	else
		pa->setFixedSize(QSize(320*s, 240*s));
#else
	pa->setFixedSize(QSize(320*s, 240*s));
#endif

	main_window->resize(320*s, 240*s+TB->height());

	focus();
	first_time = 10;
}

void MyClass::set_size1(){set_size (1);}
void MyClass::set_size2(){set_size (2);}
void MyClass::set_size3(){set_size (3);}
void MyClass::set_size4(){set_size (4);}
void MyClass::set_size5(){set_size (5);}
void MyClass::set_size6(){set_size (6);}
void MyClass::set_size7(){set_size (7);}
void MyClass::set_size8(){set_size (8);}


void res (void)
{

	int x, y;

	x =  main_window->size().width();
	y = main_window->size().height() - (Full_screen? 0: TB->height());

#if defined OPENGL
	if (opengl)
		glpa->setFixedSize(x, y);
	else
		pa->setFixedSize(QSize(x, y));
#else
	pa->setFixedSize(QSize(x, y));
#endif
	
}


void MyClass::Main_Window(void)
{
	main_window = new MyMainWindow ();

# include "open.xpm"
# include "reset.xpm"
# include "save.xpm"
# include "settings.xpm"
# include "dump_s.xpm"
# include "fullscreen.xpm"
# include "web.xpm"
# include "run.xpm"
# include "question.xpm"
# include "disc.xpm"

	

    QToolBar * hlayout =  new QToolBar;

	TB =  hlayout;
	hlayout->setFloatable(false);
	hlayout->setMovable(false);

	QPushButton * b1;

	QSize * QS = new QSize(33, 34);
	QSize * QS1 = new QSize(65, 34);

	b1 = new QPushButton(QIcon(QPixmap(open)), "", main_window);
	b1->setShortcut(QKeySequence("F3"));
	b1->setToolTip(tr("Open file (F3)"));
	b1->setFixedSize(*QS);
	eh->connect(b1, SIGNAL(clicked()), eh, SLOT(openfile()));
	hlayout->addWidget(b1);
	B1=b1;


	b1 = new QPushButton(QIcon(QPixmap(web)), "", main_window);
	b1->setToolTip(tr("Get file from the web"));
	b1->setFixedSize(*QS);
	eh->connect(b1, SIGNAL(clicked()), eh, SLOT(web()));
	hlayout->addWidget(b1);
	B22=b1;


	b1 = new QPushButton(QIcon(QPixmap(save)), "", main_window);
	b1->setShortcut(QKeySequence("F2"));
	b1->setToolTip(tr("Save file (F2)"));
	b1->setFixedSize(*QS);
	eh->connect(b1, SIGNAL(clicked()), eh, SLOT(save()));
	hlayout->addWidget(b1);
	B3=b1;

	ppp = new QPushButton(QIcon(QPixmap(pause)), "",  main_window);
	ppp->setShortcut(QKeySequence("F11"));
	ppp->setToolTip(tr("Pause (F11)"));
	ppp->setFixedSize(*QS);
	hlayout->addWidget(ppp);
	eh->connect(ppp, SIGNAL(clicked()), eh, SLOT(play_pause()));
	B4=ppp;
	

	b1 = new QPushButton(QIcon(QPixmap(run)), "", main_window);	
	eh->connect(b1, SIGNAL(clicked()), eh, SLOT(rrrun()));
	b1->setToolTip(tr("Max speed"));
	b1->setFixedSize(*QS);
	hlayout->addWidget(b1);
	B5=b1;

	b1 = new QPushButton(QIcon(QPixmap(settings)), "", main_window);
	b1->setFixedSize(*QS);
	b1->setToolTip(tr("Settings"));
	eh->connect(b1, SIGNAL(clicked()), eh, SLOT(settings()));
	hlayout->addWidget(b1);
	B6=b1;

	

	b1 = new QPushButton(QIcon(QPixmap(reset)), "", main_window);
	b1->setShortcut(QKeySequence("F12"));
	b1->setToolTip(tr("Reset (F12)"));
	b1->setFixedSize(*QS);
	eh->connect(b1, SIGNAL(clicked()), eh, SLOT(rst()));
	hlayout->addWidget(b1);
	B7=b1;
	

	b1 = new QPushButton(QIcon(QPixmap(dump_s)), "", main_window);
	eh->connect(b1, SIGNAL(clicked()), eh, SLOT(record()));
	b1->setToolTip(tr("Dump AY sound"));
	b1->setFixedSize(*QS);
	hlayout->addWidget(b1);
	B8=b1;


	b1 = new QPushButton(QIcon(QPixmap(disc)), "", main_window);
	eh->connect(b1, SIGNAL(clicked()), eh, SLOT(nmi()));
	b1->setToolTip(tr("Generate NMI"));
	b1->setFixedSize(*QS);
	hlayout->addWidget(b1);
	B9=b1;


	b1 = new QPushButton(tr("Size"), main_window);
	b1->setFixedSize(*QS1);
	hlayout->addWidget(b1);
	B10=b1;


	QMenu * fileMenu = new QMenu("");

	fileMenu->addAction("1:1", eh, SLOT(set_size1()), QKeySequence("Shift+F1"));
	fileMenu->addAction("2:1", eh, SLOT(set_size2()), QKeySequence("Shift+F2"));
	fileMenu->addAction("3:1", eh, SLOT(set_size3()), QKeySequence("Shift+F3"));
	fileMenu->addAction("4:1", eh, SLOT(set_size4()), QKeySequence("Shift+F4"));
	fileMenu->addAction("5:1", eh, SLOT(set_size5()), QKeySequence("Shift+F5"));
	fileMenu->addAction("6:1", eh, SLOT(set_size6()), QKeySequence("Shift+F6"));
	fileMenu->addAction("7:1", eh, SLOT(set_size7()), QKeySequence("Shift+F7"));
	fileMenu->addAction("8:1", eh, SLOT(set_size8()), QKeySequence("Shift+F8"));

	b1->setMenu(fileMenu);


	b1 = new QPushButton(QIcon(QPixmap(fullscreen)), "", main_window);
	b1->setShortcut(QKeySequence("F10"));
	b1->setToolTip(tr("Full screen (F10)"));
	b1->setFixedSize(*QS);
	eh->connect(b1, SIGNAL(clicked()), eh, SLOT(full_screen()));
	hlayout->addWidget(b1);
	B11=b1;


	b1 = new QPushButton(QIcon(QPixmap(question)), "", main_window);
	b1->setToolTip(tr("About"));
	eh->connect(b1, SIGNAL(clicked()), eh, SLOT(about()));
	b1->setFixedSize(*QS);
	hlayout->addWidget(b1);
	B12=b1;

	main_window->addToolBar(hlayout);

	
	
	QWidget * w = new QWidget();

	DW = w;

	//w->setFixedSize(640, 480);

#if defined OPENGL
	
	if (opengl)
	{
		glpa = new GLpaint_area(w);
		glpa->show();
	}
	else
	{
		pa = new paint_area1(w);
		pa->show();
	}
#else
	pa = new paint_area1(w);
	pa->show();
#endif

	main_window->setCentralWidget(w);

	

	focus();


	

	main_window->show();

	main_window->resize(640, 480+TB->height());


	/*
	int x, y;

	GetWH(&x, &y);


#if defined OPENGL

	if (opengl)
		glpa->setFixedSize(QSize(x, y));
	else
		pa->setFixedSize(QSize(x, y));
#else
	pa->setFixedSize(QSize(x, y));
#endif
	*/


	if (*GetKM() == 1) 
		Empty_Cursor();
	else
		Normal_Cursor();
}



void MessageBoxErr(char * a)
{
	QMessageBox msgBox;
	msgBox.setText(a);
	msgBox.setIcon(QMessageBox::Critical);
	msgBox.setWindowTitle("Glukalka ZX Spectrum Emulator");
	msgBox.exec();
}

void SetLL(int v1, int v2, int v3, int v4, int v5, int v6, int v7, int v8, int v9, int v10, int v11, int v12)
{
	x1=v1; Visual_studio_2010_math_h=v2; w1=v3; h1=v4;
	x2=v5; y2=v6; w2=v7; h2=v8;
	x3=v9; y3=v10; w3=v11; h3=v12;
}

#if defined MULTIMEDIA
AudioTest::AudioTest()
{
	m_format.setFrequency(44100);
	m_format.setChannels(2);
	m_format.setSampleSize(16);
	m_format.setCodec("audio/pcm");
	m_format.setByteOrder(QAudioFormat::LittleEndian);
	m_format.setSampleType(QAudioFormat::SignedInt);

	QAudioDeviceInfo info(QAudioDeviceInfo::defaultOutputDevice());

	if (!info.isFormatSupported(m_format)) 
	{
		printf("Format is not supported \n");
		error = Errors;
		return;
	}


	m_audioOutput = new QAudioOutput(info, m_format, this);

	if (!m_audioOutput)
	{
		printf("Error opening audio device \n");
		error = Errors;
		return;
	}

	//printf("%d\n", m_audioOutput->periodSize());


	m_audioOutput->setBufferSize (44100);
	// m_audioOutput->setBufferSize (8000);



	//connect(m_audioOutput, SIGNAL(notify()), SLOT(notified()));


	m_audioOutput->start(generator);
	//audio=m_audioOutput->start();

	error = no_Errors;
}

Generator::Generator()
	:   QIODevice()
	,   m_pos(0)
{

}

qint64 Generator::readData(char *data, qint64 len)
{
	int i;
	int empty = 0;

	static char last = 0;


	//printf("%d \n", len);

	for(i=0; i<len; i++)
	{
		if (!empty)
		{
			if (queue.isEmpty ())
			{
				empty = 1;
				//printf("Empty queue !\n");	
			}
		}

		if (!empty)
		{
			data[i] = queue.dequeue();
			last = data[i];
		}
		else
		{
			data[i] =last;
		}
	}

	return len;
}

qint64 Generator::writeData(const char *data, qint64 len)
{
	Q_UNUSED(data);
	Q_UNUSED(len);

	return 0;
}

void Generator::start()
{
	open(QIODevice::ReadOnly);
}

void Generator::stop()
{
	m_pos = 0;
	close();
}

#endif

void soundthreadclass :: run()
{
};

int SoundCardInit(void)
{
	queue.clear();


	if (ss == sqt)
	{
#if defined MULTIMEDIA
		if (generator) 	delete (generator);
		if (qaudio) 	delete (qaudio);

		generator = new Generator;
		generator->start();
		qaudio = new AudioTest;

		return(qaudio->error);
#else
		return(Errors);
#endif

	}	

	if (ss == soss)
	{
#if defined LINUX
		int rv = init_card(Get_audio_name());
		return(rv);
#endif
	}

	if (ss == ssolaris)
	{
#if defined SOLARIS
		int rv = init_card(Get_audio_name());
		return(rv);
#endif
	}


	if (ss == smac)
	{
#if defined MACOSX
		int rv = init_card(Get_audio_name());
		return(rv);
#endif
	}


	if (ss == swin)
	{
#if defined WIN32
		int rv = init_card(Get_audio_name());
		return(rv);
#endif
	}

	return Errors;
}

int ncolumns = 0;

void ClearTapeLB()
{
	ncolumns = 0;
	w->clear();
}

int AddIntoTapeLB(char * s1, char * s2, char * s3)
{
	QTableWidgetItem *newItem = new QTableWidgetItem(s1);
	w->setItem(ncolumns, 0, newItem);
	newItem->setFlags(newItem->flags() & ~Qt::ItemIsEditable); 

	newItem = new QTableWidgetItem(s2);
	w->setItem(ncolumns, 1, newItem);
	newItem->setFlags(newItem->flags() & ~Qt::ItemIsEditable); 

	newItem = new QTableWidgetItem(s3);
	w->setItem(ncolumns, 2, newItem);
	newItem->setFlags(newItem->flags() & ~Qt::ItemIsEditable); 

	return (++ncolumns);
}

unsigned char kmx = 0, kmy = 0;
unsigned char kmkeys =  255;

unsigned char kmGetX (void)
{
	return kmx;
}

unsigned char kmGetY (void)
{
	return kmy;
}

unsigned char kmGetKeys(void)
{
	return kmkeys;
}

void	paint_area1::mouseMoveEvent ( QMouseEvent * event )
{
	double x = event->x();
	double y = event->y();

	double width  = this->width();
	double height = this->height();

	int newx, newy;

	if (!aspect)
	{
		newx = x/width*320 -  32;
		newy = 192 - (y/height*240 - 24);

		if (newx < 0) newx = 0;
		if (newx > 255) newx = 255;

		if (newy < 0) newy = 0;
		if (newy > 191) newy = 191;
	}
	else
	{	
		newy = newx = 0;
	}

	kmx = newx;
	kmy = newy;

	kmkeys = 255;

	if (event->buttons() & Qt::LeftButton)
		kmkeys = 253;

	if (event->buttons() & Qt::RightButton)
		kmkeys = 254;

	if ((event->buttons() & Qt::RightButton) && (event->buttons() & Qt::LeftButton))
		kmkeys = 252;


	//printf ("%d %d %d\n", newx, newy, kmkeys);
}

void	paint_area1::mousePressEvent ( QMouseEvent * event )
{
	mouseMoveEvent(event);
}

void	paint_area1::mouseReleaseEvent ( QMouseEvent * event )
{
	mouseMoveEvent(event);
}


#if defined OPENGL

void	GLpaint_area::mouseMoveEvent ( QMouseEvent * event )
{
	double x = event->x();
	double y = event->y();

	double width  = this->width();
	double height = this->height();

	int newx, newy;

	if (!aspect)
	{
		newx = x/width*320 -  32;
		newy = 192 - (y/height*240 - 24);

		if (newx < 0) newx = 0;
		if (newx > 255) newx = 255;

		if (newy < 0) newy = 0;
		if (newy > 191) newy = 191;
	}
	else
	{	
		newy = newx = 0;
	}

	kmx = newx;
	kmy = newy;

	kmkeys = 255;

	if (event->buttons() & Qt::LeftButton)
		kmkeys = 253;

	if (event->buttons() & Qt::RightButton)
		kmkeys = 254;

	if ((event->buttons() & Qt::RightButton) && (event->buttons() & Qt::LeftButton))
		kmkeys = 252;


	//printf ("%d %d %d\n", newx, newy, kmkeys);
}

void	GLpaint_area::mousePressEvent ( QMouseEvent * event )
{
	mouseMoveEvent(event);
}

void	GLpaint_area::mouseReleaseEvent ( QMouseEvent * event )
{
	mouseMoveEvent(event);
}

#endif




////////////////// LIB ////////////////////////////////


# include <iostream>

QList <QFile *> list;

int io_open (char * dir, char * filename, int mode)
{
	QString filename1("");
	QString nd;
	QString nf;


	if (dir)
		nd=QDir::fromNativeSeparators(fromutf(dir));

	if (filename)
		nf=fromutf(filename);

	if (dir && strlen(dir))
	{
		QDir * d = new QDir(nd);

		if( !d->exists() )
		{
			printf("io_open : Directory does not exist - %s", nd.toLocal8Bit().data());
			return -1;
		}

		filename1 += QDir::fromNativeSeparators(nd);
		filename1 += QString("/");
		filename1 += QDir::fromNativeSeparators(nf);
	}
	else
	{
		filename1 += QDir::fromNativeSeparators(nf);
	}

	QFile * f = new QFile(filename1);

	if( !f->exists() )
	{
		printf ("The file does not exist %s", filename1.toLocal8Bit().data());
		return -1;
	}

	QIODevice::OpenMode omode;

	if (mode == O_RDONLY) omode = QIODevice::ReadOnly;
	if (mode == O_WRONLY) omode = QIODevice::WriteOnly;
	if (mode == O_RDWR) omode = QIODevice::ReadWrite;

	if(!f->open(omode))
	{
		std::cout << "Failed to open " << filename << std::endl;
		return -1;
	}

	list << f;

	return (list.size() - 1);
}

int io_creat (char * dir, char * filename)
{
	QString filename1("");
	QString nd;
	QString nf;


	if (dir)
		nd=QDir::fromNativeSeparators(fromutf(dir));

	if (filename)
		nf=fromutf(filename);

	if (dir && strlen(dir))
	{
		QDir * d = new QDir(nd);

		if( !d->exists() )
		{
			std::cout << "io_creat : Directory does not exist " << nd.toLocal8Bit().data() <<  std::endl;
			return -1;
		}

		filename1 += QDir::fromNativeSeparators(nd);
		filename1 += QString("/");
		filename1 += QDir::fromNativeSeparators(nf);
	}
	else
	{
		filename1 += QDir::fromNativeSeparators(nf);
	}

	QFile * f = new QFile(filename1);

	if(!f->open(QIODevice::ReadWrite ))
	{
		std::cout << "Failed to create " << nd.toLocal8Bit().data() << "/" << filename << std::endl;
		return -1;
	}

	f->resize(0);

	list << f;

	return (list.size() - 1);
}

int io_eof (int fd)
{
	return (list[fd]->atEnd ());
}

long long io_readline (int fd, char * buffer, long long size)
{
	return (list[fd]->readLine(buffer, size));
}

long long io_read (int fd, char * buffer, long long size)
{
	return (list[fd]->read(buffer, size));
}

long long io_read (int fd, unsigned char * buffer, long long size)
{
	return (list[fd]->read((char *)buffer, size));
}

long long io_write (int fd, unsigned char * buffer, long long size)
{
	return (list[fd]->write((char *)buffer, size));
}

long long io_write (int fd, char * buffer, long long size)
{
	return (list[fd]->write((char *)buffer, size));
}

long long io_fgets (int fd, char * buffer, long long size)
{
	return (list[fd]->readLine((char *)buffer, size));
}

int io_feof (int fd)
{
	return (list[fd]->atEnd());
}


long long io_lseek (int fd, long long pos, int mode)
{
	if (mode == SEEK_CUR)
		pos += list[fd]->pos();

	if (list[fd]->seek(pos) == true)
		return pos;
	else
		return -1;
}

long long size(char * filename)
{
	QString filename1("");
	QString nf;



	if (filename)
		nf=fromutf(filename);

	filename1 += QDir::fromNativeSeparators(nf);

	QFile f(filename1);


	if( !f.exists() )
	{
		std::cout << "The file does not exist " << filename1.toLocal8Bit().data() << std::endl << "\n";
		return -1;
	}

	return f.size();
}

void io_close (int fd)
{
	list[fd]->close();
}

int io_strcasecmp(char * s1, char * s2)
{
	return (qstricmp(s1, s2));
}

int io_strncasecmp (char * s1, char * s2, int n)
{
	return (qstrnicmp(s1, s2, n));
}


int FileExists(char * filename)
{
	QString filename1("");
	QString nf;



	if (filename)
		nf=fromutf(filename);

	filename1 += QDir::fromNativeSeparators(nf);

	QFile f(filename1);


	if( !f.exists() )
		return false;

	return true;
}





char * clear(char * arg)
{
	char * rv = (char *) malloc (strlen (arg)+1);
	memset(rv, 0, strlen (arg)+1);


	int j=0;
	for (unsigned int i=0; i<strlen(arg); i++)
		if (arg[i]!='\"')
			rv[j++]=arg[i];

	return rv;
}


int main( int argc, char **argv ) 
{
	app = new QApplication(argc, argv);

	qApp->setStyleSheet("QMessageBox { messagebox-text-interaction-flags: 5; }");


	eh = new MyClass(main_window);

#if defined WEBKIT
	dw = new download (main_window);
#endif

	qi = new QImage(640, 480, QImage::Format_RGB32);
	qi->fill(0xFF000000);


	videomemory1 = qi->bits();

	videomemory1[5]=4;


	SetHomeDir((char *)QDir::toNativeSeparators(QDir::homePath()).toUtf8().constData());

	int rv  = init(videomemory1);
	reset_h();

	if (rv==Errors)
	{
		MessageBoxErr("Fatal error, can't continue");
	}
	else
	{
		if (argc==2)
		{
			//MessageBoxErr(argv[1]);
			open_file((char *)QDir::toNativeSeparators(QDir::currentPath()).toUtf8().constData(), clear(argv[1]));
		}

		FillKeybp (&pf7fe, &pfbfe, &pfdfe, &pfefe, &peffe, &pdffe, &pbffe, &psffe, &kep, &j_t);

		eh->Main_Window();
		eh->tape_dialog();

		//soundthreadclass * s = new soundthreadclass;
		//s->start();		

		timer = new QTimer(app);
		eh->connect(timer, SIGNAL(timeout()), eh, SLOT(update()));

		const char * mode_saved = NULL;
		char audiod_sav[200]={0};

		while (1)
		{
			if (SoundCardInit()==Errors)
			{
				printf("SoundCardInit failed \n");
				ss=snosound;
			}

			if ((ss==sqt)||(ss==snosound)||(ss==swin)||(ss==smac))
				push = 0;

			if ((ss==soss))
				push = 1;

			if (!push)
				timer->start(timer_const);
			else 
				timer->stop();

			mode_saved = ss;
			strcpy(audiod_sav, Get_audio_name());

			if (push)
			{
				while (1)
				{
					eh->update();
					app->processEvents();

					if ((mode_saved != ss)||(strcmp(audiod_sav, Get_audio_name()))) break;
				}
			}
			else
			{
				while (1)
				{
					app->processEvents();
					QEventLoop loop; QTimer::singleShot(1, &loop, SLOT(quit())); loop.exec();
					if ((mode_saved != ss)||(strcmp(audiod_sav, Get_audio_name()))) break;
				}
			}
		}
	}
}

char ** cdm;

# if defined WIN32

# include <windows.h>

int CALLBACK WinMain(
	HINSTANCE hInstance,
	HINSTANCE hPrevInstance,
	LPSTR lpCmdLine,
	int nCmdShow
	)
{
	cdm = (char **)malloc(sizeof (char *) * 2);

	cdm[0]="";
	cdm[1]=lpCmdLine;

	if (strlen (lpCmdLine))
		main(2, cdm);
	else
		main(1, NULL);
}
# endif

