#!/usr/bin/perl -W
#
# gas2fasm.pl - Skrypt konwertujacy kod w skladni GAS (GNU as) na kod w skladni FASMa
# gas2fasm.pl - A script which converts GAS (GNU as) code to FASM code.
#
#	Copyright (C) 2006-2007 Bogdan 'bogdro' Drozdowski, http://rudy.mif.pg.gda.pl/~bogdro/inne/
#		(bogdandr AT op.pl, bogdro AT rudy.mif.pg.gda.pl)
#
#	Licencja / Licence:
#	Powszechna Licencja Publiczna GNU v2 / GNU General Public Licence v2
#
#	Ostatnia modyfikacja / Last modified : 2007-02-02
#
#	Sposob uzycia / Syntax:
#		./gas2fasm.pl xxx.s [yyy.asm]
#
# Jesli nazwa pliku wyjsciowego nie zostanie podana, jest brana taka sama jak pliku
#	wejsciowego (tylko rozszerzenie sie zmieni na .asm). Jesli za nazwe
#	pliku wejsciowego podano "-", czytane jest standardowe wejscie.
#	Jesli nazwa pliku wyjsciowego to "-" (lub nie ma jej, gdy wejscie to stdin),
#	wynik bedzie na standardowym wyjsciu.
#
# If there's no output filename, then it is assumed to be the same as the
#	input filename (only the extension will be changed to .asm). If the
#	input filename is "-", standard input will be read. If the
#	output filename is "-" (or missing, when input is stdin),
#	the result will be written to the standard output.
#
#    Niniejszy program jest wolnym oprogramowaniem; mozesz go
#    rozprowadzac dalej i/lub modyfikowac na warunkach Powszechnej
#    Licencji Publicznej GNU, wydanej przez Fundacje Wolnego
#    Oprogramowania - wedlug wersji 2-giej tej Licencji lub ktorejs
#    z pozniejszych wersji.
#
#    Niniejszy program rozpowszechniany jest z nadzieja, iz bedzie on
#    uzyteczny - jednak BEZ JAKIEJKOLWIEK GWARANCJI, nawet domyslnej
#    gwarancji PRZYDATNOSCI HANDLOWEJ albo PRZYDATNOSCI DO OKRESLONYCH
#    ZASTOSOWAN. W celu uzyskania blizszych informacji - Powszechna
#    Licencja Publiczna GNU.
#
#    Z pewnoscia wraz z niniejszym programem otrzymales tez egzemplarz
#    Powszechnej Licencji Publicznej GNU (GNU General Public License);
#    jesli nie - napisz do Free Software Foudation:
#		Free Software Foundation
#		51 Franklin Street, Fifth Floor
#		Boston, MA 02110-1301
#		USA
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foudation:
#		Free Software Foundation
#		51 Franklin Street, Fifth Floor
#		Boston, MA 02110-1301
#		USA

use strict;
use warnings;
use Getopt::Long;

my ($wyj, @instr);

# instrukcje do zmiany (instructions to be changed)
@instr = (	"mov" , "and" , "or"  , "not", "xor", "neg", "cmp", "add" ,
		"sub" , "push", "test", "lea", "pop", "inc", "dec", "idiv",
		"imul", "sbb" , "sal" , "shl", "sar", "shr", "adc", "sbb"
	);

my @instrukcje = ("aaa", "aad", "aam", "aas", "adc", "add", "addpd", "addps", "addsd", "addss",
"addsubpd", "addsubps", "and", "andnpd", "andnps", "andpd", "andps", "arpl", "bound", "bsf",
"bsr", "bswap", "bt", "btc", "btr", "bts", "call", "cbw", "cwde", "cwd",
"cdq", "cdqe", "cqo", "clc", "cld", "clgi", "cli", "clts", "clflush", "cmc",
"cmova", "cmovae", "cmovb", "cmovbe", "cmovc", "cmove", "cmovg", "cmovge", "cmovl", "cmovle",
"cmovna", "cmovnae", "cmovnb", "cmovnbe", "cmovnc", "cmovne", "cmovng", "cmovnge", "cmovnl", "cmovnle",
"cmovno", "cmovnp", "cmovns", "cmovnz", "cmovo", "cmovp", "cmovpe", "cmovpo", "cmovs", "cmovz",
"cmp", "cmpeqpd", "cmpeqps", "cmpeqsd", "cmpeqss", "cmplepd", "cmpleps", "cmplesd", "cmpless", "cmpltpd",
"cmpltps", "cmpltsd", "cmpltss", "cmpneqpd", "cmpneqps", "cmpneqsd", "cmpneqss", "cmpnlepd", "cmpnleps", "cmpnlesd",
"cmpnless", "cmpnltpd", "cmpnltps", "cmpnltsd", "cmpnltss", "cmpordpd", "cmpordps", "cmpordsd", "cmpordss", "cmppd",
"cmpps", "cmps", "cmpsb", "cmpsd", "cmpsq", "cmpss", "cmpsw", "cmpunordpd", "cmpunordps", "cmpunordsd",
"cmpunordss", "cmpxchg", "cmpxchg486", "cmpxchg8b", "cmpxchg16b", "comisd", "comiss", "cpuid", "cvtdq2pd", "cvtdq2ps",
"cvtpd2dq", "cvtpd2pi", "cvtpd2ps", "cvtpi2pd", "cvtpi2ps", "cvtps2dq", "cvtps2pd", "cvtps2pi", "cvtsd2si", "cvtsd2ss",
"cvtsi2sd", "cvtsi2ss", "cvtss2sd", "cvtss2si", "cvttpd2dq", "cvttpd2pi", "cvttps2dq", "cvttps2pi", "cvttsd2si", "cvttss2si",
"daa", "das", "dec", "div", "divpd", "divps", "divsd", "divss", "emms", "enter",
"f2xm1", "fabs", "fadd", "faddp", "fbld", "fbstp", "fchs", "fclex", "fnclex", "fcmovb",
"fcmovbe", "fcmove", "fcmovnb", "fcmovnbe", "fcmovne", "fcmovnu", "fcmovu", "fcom", "fcomp", "fcompp",
"fcomi", "fcomip", "fcos", "fdecstp", "fdisi", "feni", "fdiv", "fdivr", "fdivp", "fdivrp",
"femms", "ffree", "ffreep", "fiadd", "ficom", "ficomp", "fidiv", "fidivr", "fild", "fimul",
"fincstp", "finit", "fist", "fistp", "fisttp", "fisub", "fisubr", "fld", "fld1", "fldl2e",
"fldl2t", "fldlg2", "fldln2", "fldcw", "fldenv", "fldpi", "fldz", "fmul", "fmulp", "fndisi",
"fneni", "fninit", "fnop", "fnsave", "fnstcw", "fnstenv", "fnstsw", "fnwait", "fpatan", "fptan",
"fprem", "fprem1", "frndint", "frstor", "frstpm", "fsave", "fscale", "fsetpm", "fsin", "fsincos",
"fsqrt", "fst", "fstp", "fstcw", "fstenv", "fstsw", "fsub", "fsubr", "fsubp", "fsubrp",
"ftst", "fucom", "fucomp", "fucompp", "fucomi", "fucomip", "fwait", "fxam", "fxch", "fxrstor",
"fxsave", "fxtract", "fyl2x", "fyl2xp1", "haddpd", "haddps", "hlt", "hsubpd", "hsubps", "ibts",
"icebp", "idiv", "imul", "in", "inc", "ins", "insb", "insd", "insw", "int",
"int1", "int3", "into", "invd", "invlpg", "invlpga", "iret", "iretd", "iretq", "iretw",
"ja", "jae", "jb", "jbe", "jc", "jcxz", "je", "jecxz", "jg", "jge",
"jl", "jle", "jmp", "jna", "jnae", "jnb", "jnbe", "jnc", "jne", "jng",
"jnge", "jnl", "jnle", "jno", "jnp", "jns", "jnz", "jo", "jp", "jpe",
"jpo", "jrcxz", "js", "jz", "lahf", "lar", "lddqu", "ldmxcsr", "lds", "les",
"lea", "leave", "lfence", "lfs", "lgdt", "lgs", "lidt", "lldt", "lmsw", "loadall",
"loadall286", "loadall386", "lock", "lods", "lodsb", "lodsd", "lodsq", "lodsw", "loop", "loopd",
"loope", "looped", "loopeq", "loopew", "loopne", "loopned", "loopneq", "loopnew", "loopnz", "loopnzd",
"loopnzq", "loopnzw", "loopq", "loopw", "loopz", "loopzd", "loopzq", "loopzw", "lsl", "lss",
"ltr", "maskmovdqu", "maskmovq", "maxpd", "maxps", "maxsd", "maxss", "mfence", "minpd", "minps",
"minsd", "minss", "monitor", "mov", "movapd", "movaps", "movd", "movddup", "movdq2q", "movdqa",
"movdqu", "movhlps", "movhpd", "movhps", "movlhps", "movlpd", "movlps", "movmskpd", "movmskps", "movntdq",
"movnti", "movntpd", "movntps", "movntq", "movq", "movq2dq", "movs", "movsb", "movsd", "movshdup",
"movsldup", "movsq", "movss", "movsx", "movsxd", "movsw", "movupd", "movups", "movzx", "mul",
"mulpd", "mulps", "mulsd", "mulss", "mwait", "neg", "nop", "not", "or", "orpd",
"orps", "out", "outs", "outsb", "outsw", "outsd", "pabsb", "pabsd", "pabsw", "packssdw",
"packsswb", "packuswb", "paddb", "paddd", "paddq", "paddsb", "paddsw", "paddusb", "paddusw", "paddw",
"palignr", "pand", "pandn", "pause", "pavgb", "pavgusb", "pavgw", "pcmpeqb", "pcmpeqw", "pcmpeqd",
"pcmpgtb", "pcmpgtw", "pcmpgtd", "pdistib", "pextrw", "pf2id", "pf2iw", "pfacc", "pfadd", "pfcmpeq",
"pfcmpge", "pfcmpgt", "pfmax", "pfmin", "pfmul", "pfnacc", "pfpnacc", "pfrcp", "pfrcpit1", "pfrcpit2",
"pfrsqit1", "pfrsqrt", "pfsub", "pfsubr", "phaddd", "phaddsw", "phaddw", "phsubd", "phsubsw", "phsubw",
"pi2fd", "pi2fw", "pinsrw", "pmachriw", "pmaddwd", "pmaddubsw", "pmagw", "pmaxsw", "pmaxub", "pminsw",
"pminub", "pmovmskb", "pmulhrw", "pmulhrsw", "pmulhuw", "pmulhw", "pmullw", "pmuludq", "pmvgezb", "pmvlzb",
"pmvnzb", "pmvzb", "pop", "popa", "popaw", "popad", "popd", "popf", "popfw", "popfd",
"popfq", "popq", "popw", "por", "prefetch", "prefetchnta", "prefetcht0", "prefetcht1", "prefetcht2", "prefetchw",
"psadbw", "pshufb", "pshufd", "pshufhw", "pshuflw", "pshufw", "psignb", "psignd", "psignw", "pslld",
"pslldq", "psllq", "psllw", "psrad", "psraw", "psrld", "psrldq", "psrlq", "psrlw", "psubb",
"psubd", "psubq", "psubsb", "psubsiw", "psubsw", "psubusb", "psubusw", "psubw", "pswapd", "punpckhbw",
"punpckhdq", "punpckhqdq", "punpckhwd", "punpcklbw", "punpckldq", "punpcklqdq", "punpcklwd", "push", "pusha", "pushad",
"pushaw", "pushd", "pushf", "pushfd", "pushfq", "pushfw", "pushq", "pushw", "pxor", "rcl",
"rcr", "rcpps", "rcpss", "rdmsr", "rdmsrq", "rdpmc", "rdshr", "rdtsc", "rdtscp", "rep",
"repe", "repne", "repnz", "repz", "ret", "retd", "retf", "retfd", "retfq", "retfw",
"retn", "retnd", "retnq", "retnw", "retq", "retw", "rol", "ror", "rsdc", "rsldt",
"rsm", "rsqrtps", "rsqrtss", "rsts", "sahf", "sal", "sar", "salc", "sbb", "scas",
"scasb", "scasd", "scasq", "scasw", "seta", "setae", "setalc", "setb", "setbe", "setc",
"sete", "setg", "setge", "setl", "setle", "setna", "setnae", "setnb", "setnbe", "setnc",
"setne", "setng", "setnge", "setnl", "setnle", "setno", "setnp", "setns", "setnz", "seto",
"setp", "setpe", "setpo", "sets", "setz", "sfence", "sgdt", "shl", "shld", "shr",
"shrd", "shufpd", "shufps", "sidt", "skinit", "sldt", "smi", "smint", "smintold", "smsw",
"sqrtpd", "sqrtps", "sqrtsd", "sqrtss", "stc", "std", "stgi", "sti", "stmxcsr", "stos",
"stosb", "stosd", "stosq", "stosw", "str", "sub", "subpd", "subps", "subsd", "subss",
"svdc", "svldt", "svts", "swapgs", "syscall", "sysenter", "sysexit", "sysexitq", "sysret", "sysretq",
"test", "ucomisd", "ucomiss", "ud0", "ud1", "ud2", "umov", "unpckhpd", "unpckhps", "unpcklpd",
"unpcklps", "verr", "verw", "vmcall", "vmclear", "vmlaunch", "vmload", "vmmcall", "vmptrld", "vmptrst",
"vmread", "vmresume", "vmrun", "vmsave", "vmwrite", "vmxoff", "vmxon", "wait", "wbinvd", "wrmsr",
"wrmsrq", "wrshr", "xadd", "xbts", "xchg", "xlat", "xlatb", "xor", "xorpd", "xorps",
"cltd", "cwtd", "cwtl", "cbtw", "lcall", "ljmp",
		);

sub is_instr {

	my $elem = shift;
	foreach(@instrukcje) {
		$elem =~ /(\b$_[lbwd]{0,2}\b)/i;
		return 1 if $elem eq $1;
	}
	return 0;
}

my ($help, $lic, $help_msg, $lic_msg);

$help_msg = "$0: Konwerter z GNU as do FASMa / GNU as-to-FASM converter.\nAutor/Author: Bogdan Drozdowski, ".
	"http://rudy.mif.pg.gda.pl/~bogdro/inne/\n".
	"Skladnia/Syntax: $0 [--help] [--license] xxx.s [yyy.asm]\n\n
 Jesli nazwa pliku wyjsciowego nie zostanie podana, jest brana taka sama jak
pliku wejsciowego (tylko rozszerzenie sie zmieni na .asm). Jesli za nazwe
pliku wejsciowego podano \"-\", czytane jest standardowe wejscie.
 Jesli nazwa pliku wyjsciowego to \"-\" (lub nie ma jej, gdy wejscie to stdin),
wynik bedzie na standardowym wyjsciu.

 If there's no output filename, then it is assumed to be the same as the
input filename (only the extension will be changed to .asm). If the
input filename is \"-\", standard input will be read.
 If the output filename is \"-\" (or missing, when input is stdin),
the result will be written to the standard output.\n";

$lic_msg = "$0: Konwerter z GNU as do FASMa / GNU as-to-FASM converter.\nAutor/Author: Bogdan Drozdowski, ".
	"http://rudy.mif.pg.gda.pl/~bogdro/inne/\n\n".
	"    Niniejszy program jest wolnym oprogramowaniem; mozesz go
    rozprowadzac dalej i/lub modyfikowac na warunkach Powszechnej
    Licencji Publicznej GNU, wydanej przez Fundacje Wolnego
    Oprogramowania - wedlug wersji 2-giej tej Licencji lub ktorejs
    z pozniejszych wersji.

    Niniejszy program rozpowszechniany jest z nadzieja, iz bedzie on
    uzyteczny - jednak BEZ JAKIEJKOLWIEK GWARANCJI, nawet domyslnej
    gwarancji PRZYDATNOSCI HANDLOWEJ albo PRZYDATNOSCI DO OKRESLONYCH
    ZASTOSOWAN. W celu uzyskania blizszych informacji - Powszechna
    Licencja Publiczna GNU.

    Z pewnoscia wraz z niniejszym programem otrzymales tez egzemplarz
    Powszechnej Licencji Publicznej GNU (GNU General Public License);
    jesli nie - napisz do Free Software Foudation:
		Free Software Foundation
		51 Franklin Street, Fifth Floor
		Boston, MA 02110-1301
		USA

 This program is free software; you can redistribute it and/or
 modify it under the terms of the GNU General Public License
 as published by the Free Software Foundation; either version 2
 of the License, or (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software Foudation:
		Free Software Foundation
		51 Franklin Street, Fifth Floor
		Boston, MA 02110-1301
		USA\n";

if ( @ARGV == 0 ) {
	print $help_msg;
	exit 1;
}

Getopt::Long::Configure ( "ignore_case", "ignore_case_always" );

if ( ! GetOptions(
	'h|help|?'		=>	\$help,
	'license|licence|L'	=>	\$lic
	)
   ) {

	print $help_msg;
	exit 1;
}

if ( $lic ) {
	print $lic_msg;
	exit 1;
}

if ( @ARGV == 0 || $help ) {
	print $help_msg;
	exit 1;
}

if ( @ARGV > 1 && $ARGV[0] ne "-" && $ARGV[0] eq $ARGV[1] ) {

	print "$0: Plik wejsciowy i wyjsciowy NIE moga byc takie same.\n";
	print "$0: Input file and output file must NOT be the same.\n";
	exit 4;
}


##########################################################
# Otwieranie plikow (opening the files)

if ( !open ( WE, $ARGV[0] ) ) {
#	$! jest trescia bledu. ($! is the error message)
	print "$0: $ARGV[0]: $!\n";
	exit 2;
}

if ( @ARGV > 1 )  {
	$wyj = $ARGV[1];

} else {
	# bierzemy tylko nazwe pliku (take only the filename)
	($wyj = $ARGV[0]) =~ s/[\w\-\/\s]+\/([\w\-]+)/$1/;
# 	Zmieniamy rozszerzenie z .s na .asm (change the extension from .s to .asm)
	$wyj =~ s/\.s$/\.asm/;
#	Zmieniamy spacje na podkreslenia (change spaces to underlines)
	$wyj =~ s/\s+/_/g;

	if ( $wyj eq $ARGV[0] && $wyj ne "-" ) { $wyj .= ".asm"; }
}

if ( !open ( WY, "> $wyj" ) ) {
	print "$0: $wyj: $!\n";
	close WE;
	exit 3;
}


##########################################################
# Przetwarzanie (processing):

CZYTAJ: while ( <WE> ) {

	#	puste linie przepisujemy (empty lines go without change)
	if (/^\s*$/) {
		print WY "\n";
		next;
	}

	# zmiana komentarzy (change the comments)
	&komen;

	# sprawdzamy, czy komentarz jest jedyny na linii (check if a comment is the only thing on this line)
	if ( /^\s*;.*$/ ) { next; }

	# przetwarzanie dyrektyw kompilacji warunkowej (processing of conditional compiling directives)
	&kom_war(0);





	# ==================== Etykiety (labels)
	# zmiana ".Lnnn" na "_Lnnn", zeby etykiety byly widzialne globalnie
	# (changing ".Lnnn" to "_Lnnn", so the labels are globally visible)
	s/\.L([a-zA-Z])(\d+)/_L$1$2/g;
	s/\.L(\d+)/_L$1/g;

	# jesli sama w wierszu (if the only thing on a line)
	if ( /^\s*([\w\.]+)\s*:\s*$/ ) 	{ s/\s*(\w+)\s*:\s*$/$1:\n/; print WY; next; }

	# jesli za nia cos jest (if there's something following it)
	s/^\s*([\w\.]+)\s*:\s*(.*)$/$1:\n\t$2/;


	# ==================== Dyrektywy (directives)
	if ( /^\s*\.globa?l/i )	 	{ s/^\s*\.globa?l\s*(.*)/public\t$1/i; print WY; next; }

	if ( /^\s*\.includei/ ) 	{ s/^\s*\.include\s*(.*)/include\t$1/i; print WY; next; }

	# "xxx .equ yyy"
	if ( /^\s*\w+\.(set|equ)/i ) 	{ s/^\s*(\w+)\.(set|equ)\s*(\w+)\s*/$1\tequ\t$3/i; print WY; next; }
	# ".equ xxx, yyy" - to uwzglednia 'equiv' ( - this includes 'equiv'):
	if ( /^\s*\.(set|equ)/i ) 	{ s/^\s*\.(set|equ)\s*(\w+)\s*,\s*(\w+)/$2\tequ\t$3/i; print WY; next; }

	if ( /^\s*\.b?align[wl]?/i ) 	{ s/^\s*\.b?align[wl]?\s+(\d+)\s*(,.*)?/align $1\n/i; print WY; next; }

	if ( /^\s*\.l?comm\s*(.*),(.*),(.*)/i )	{ s/^\s*\.l?comm\s*(.*),(.*),(.*)/section ".data" writeable align 4096\nalign $3\n$1: times $2 db 0/i; print WY; next; }
	if ( /^\s*\.l?comm\s*(.*),(.*)/i ) 	{ s/^\s*\.l?comm\s*(.*),(.*)/section ".data" writeable align 4096\n$1: times $2 db 0/i; print WY; next; }

	if ( /^\s*\.desc/i ) 		{ print WY "\n"; next; }

		# pomijamy blok .def (skip over a .def block)
	if ( /^\s*\.def/i )		{

		while ( <WE> ) {

			if ( /\.endef/i ) { next CZYTAJ; }
		}
	}

	if ( /^\s*\.break/i ) 		{ print WY "\n"; next; }

	if ( /^\s*\.(app-)?file/i ) 	{ print WY "\n"; next; }

	if ( /^\s*\.extern/i ) 		{ s/^\s*\.extern\s*(.*)/extrn\t$1/i; print WY; next; }

	if ( /^\s*\.fill\s*(.*),(.*),(.*)/i ) 	{ s/^\s*\.fill\s*(.*),(.*),(.*)/times $1*$2 db $3/i; print WY; next; }
	if ( /^\s*\.fill\s*(.*),(.*)/i ) 	{ s/^\s*\.fill\s*(.*),(.*)/times $1*$2 db 0/i; print WY; next; }
	if ( /^\s*\.fill\s*(.*)/i ) 		{ s/^\s*\.fill\s*(.*)/times $1 db 0/i; print WY; next; }

	if ( /^\s*\.ident/i ) 		{ print WY "\n"; next; }

	# $repeat mowi, czy jestesmy w bloku 'repeat' (= 1), czy w 'irp/s' (= 0)
	# ($repeatsays, whether we're in a 'repeat' (= 1) or a 'irp/s' (= 0) block)
	my $repeat = 0;

	if ( /^\s*\.irpc/i ) 		{ s/^\s*\.irp\s*(.*)/irps $1 {/i;    $repeat = 0; print WY; next; }
	if ( /^\s*\.irp/i  ) 		{ s/^\s*\.irp\s*(.*)/irp $1 {/i;     $repeat = 0; print WY; next; }
	if ( /^\s*\.rept/i ) 		{ s/^\s*\.rept\s*(.*)/repeat $1 {/i; $repeat = 1; print WY; next; }

	if ( /^\s*\.endr/i )		{

		# irp/irpc { ... }
		if ( ! $repeat ) {

			s/^\s*\.endr.*$/}\n/i;

		# repeat ... end repeat
		} else {

			s/^\s*\.endr.*$/end repeat\n/i;
		}
		print WY;
		next;
	}

	if ( /^\s*\.lflags/i ) 		{ print WY "\n"; next; }

	if ( /^\s*\.(line|ln)/i )	{ print WY "\n"; next; }

	if ( /^\s*\.linkonce/i )	{ print WY "\n"; next; }

	if ( /^\s*\.mri/i )		{ print WY "\n"; next; }

	if ( /^\s*\.(no)?list/i )	{ print WY "\n"; next; }

	if ( /^\s*\.macro/i )		{

		# usuwamy domyslne wartosci argumentow (remove arguments' default values)
		s/(\w+)\s*=\s*\w+/$1 /g;

		# argumenty makra moga byc oddzielone tylko spacjami
		# (macro arguments may be separated only by spaces)
		s/^\s*\.macro\s+(\w+)\s+([\w,\s]+)/.macro $1 $2/i;

		my $args = $2;
		# zmiana spacji na przecinki (change spaces to commas)
		$args =~ s/(\w+)\s+(\w+)/$1, $2/g;

		s/^\s*\.macro\s+(\w+).*/macro\t$1 $args {\n/i;
		print WY;
		next;
	}

	if ( /^\s*\.endm/i )		{ s/^\s*\.endm.*$/}\n/i; print WY; next; }

	if ( /^\s*\.org/i )		{ s/^\s*\.org(.*)(,.*)?$/org\t$1/i; print WY; next; }

	if ( /^\s*\.psize/i )		{ print WY "\n"; next; }

	if ( /^\s*\.sbttl/i )		{ print WY "\n"; next; }

	if ( /^\s*\.section/i ) 	{ s/^\s*\.section\s*([\w\-\.]+).*$/section "$1" align 32/i; print WY; next; }

	if ( /^\s*\.(skip|space)\s*(.*),(.*)$/i ) 	{ s/^\s*\.(skip|space)\s*(.*),(.*)$/times $1 db $2/i; print WY; next; }
	if ( /^\s*\.(skip|space)\s*(.*)$/i ) 		{ s/^\s*\.(skip|space)\s*(.*)$/times $1 db 0/i; print WY; next; }

	if ( /^\s*\.stab[dns]/i )	{ print WY "\n"; next; }

	if ( /^\s*\.symver/i )		{ print WY "\n"; next; }

	if ( /^\s*\.title/i )		{ print WY "\n"; next; }

	if ( /^\s*\.code\d{2}/i ) 	{ s/^\s*\.code(\d{2})/use $1/i; print WY; next; }

	if ( /^\s*\.type/i )		{ print WY "\n"; next; }

	if ( /^\s*\.size/i )		{ print WY "\n"; next; }

	if ( /^\s*\.p2align/i )		{ s/^\s*\.p2align\s*(\d+)\s*,.*/align 2 shl $1/i; print WY; next; }





	# ==================== Sekcje (sections)
	if ( /^\s*\.data/i ) 		{ s/\s*\.data\s*.*$/section ".data" writeable align 4096\n/i; print WY; next; }

	if ( /^\s*\.text/i ) 		{ s/\s*\.text\s*.*$/section ".text" writeable executable align 4096\n/i; print WY; next; }

	if ( /^\s*\.bss/i ) 		{ s/\s*\.bss\s*.*$/section ".bss" writeable align 4096\n/i; print WY; next; }


	# ==================== Dane (data)
	if ( /\s*\.byte/i ) 		{ s/\s*\.byte\s*(.*)/ db $1/i; print WY; next; }

	if ( /\s*\.(h?word|short)/i ) 	{ s/\s*\.(h?word|short)\s*(.*)/ dw $2/i; print WY; next; }

	if ( /\s*\.double/i ) 		{ s/\s*\.double\s*(.*)/ dq $1/i; print WY; next; }

	if ( /\s*\.(float|single)/i ) 	{ s/\s*\.(float|single)\s*(.*)/ dd $2/i; print WY; next; }

	if ( /\s*\.(int|long)/i )	{ s/\s*\.(int|long)\s*(.*)/ dd $2/i; print WY; next; }

	# FASM nie ma 'ddq', wiec wyswietli sie blad. Nie wolno tego przepuscic z mniejszym rozmiarem
	# (no 'ddq' in FASM, so an error will occur. We mustn't let this through with a smaller size)
	if ( /\s*\.octa/i ) 		{ s/\s*\.octa\s*(.*)/ ddq $1/i; print WY; next; }

	if ( /\s*\.quad/i ) 		{ s/\s*\.quad\s*(.*)/ dq $1/i; print WY; next; }

	if ( /\s*\.zero/i ) 		{ s/\s*\.zero\s*(\d+)/ rb $1/i; print WY; next; }

	if ( /\s*\.(s|u)leb128/i ) 	{ print WY "\n"; next; }

	if ( /\s*\.tfloat/i ) 		{ s/\s*\.tfloat\s*(.*)/ dt $1/i; print WY; next; }

	if ( /\s*\.(string|ascii?z)/i )	{

		s/\n//g;
		s/\\n/", 10, "/g;
		s/\\r/", 13, "/g;
		s/\\t/", 9, "/g;
		s/\\a/", 7, "/g;
		s/\s*\.(string|ascii?z)\s*//i;
		# konczymy zerem (end with a zero)
		print WY " db\t$_, 0\n";
		next;
	}

	if ( /\s*\.ascii/i )		{

		s/\n//g;
		s/\\n/", 10, "/g;
		s/\\r/", 13, "/g;
		s/\\t/", 9, "/g;
		s/\\a/", 7, "/g;
		s/\s*\.ascii\s*//i;
		# nie konczymy zerem (don't end with a zero)
		print WY " db\t$_\n";
		next;
	}



	# ==================== Instrukcje (instructions)

	# zmiana "xxx" na "[xxx]", jesli nie ma '$' lub '%'
	# (changing "xxx" to "[xxx]", if there's no '$' or '%')

	# elementy argumentow pamieciowych nie moga byc brane jako argumenty instrukcji, wiec nie ma tu '()'
	# (elements of memory operands mustn't be taken as instruction operands, so there are no '()'s here)
	if ( /^\s*(\w+)\s+([\$\%\w\+\-]+)\s*,\s*([\$\%\w\+\-]+)\s*,\s*([\$\%\w\+\-]+)/ ) {

		my ($a1, $a2, $a3, $a4);

		$a1 = $1;
		$a2 = $2;
		$a3 = $3;
		$a4 = $4;

		# nie ruszamy "call/jmp xxx" (don't touch "call/jmp xxx")
		if ( $a1 !~ /call/i && $a1 !~ /^\s*j[a-z]{1,3}/i ) {

			# nie wolno zamieniac cyfr and %st(n) (we mustn't change digits and %st(n))
			if ( $a2 !~ /\$/ && $a2 !~ /\%/ && $a2 !~ /_L\d+/ && $a2 =~ /[a-zA-Z_\.]/ ) {

				$a2 = "[$a2]";
			}
			if ( $a3 !~ /\$/ && $a3 !~ /\%/ && $a3 !~ /_L\d+/ && $a3 =~ /[a-zA-Z_\.]/ ) {

				$a3 = "[$a3]";
			}
			if ( $a4 !~ /\$/ && $a4 !~ /\%/ && $a4 !~ /_L\d+/ && $a4 =~ /[a-zA-Z_\.]/ ) {

				$a4 = "[$a4]";
			}

			# UWAGA: zmiana kolejnosci argumentow bedzie pozniej
			# (ATTENTION: operand order will be changed later)
			$_ = "\t$a1\t$a2, $a3, $a4\n";
		}
	}

	if ( /^\s*(\w+)\s+([\$\%\w\+\-]+)\s*,\s*([\$\%\w\+\-]+)\s*$/ ) {

		my ($a1, $a2, $a3);

		$a1 = $1;
		$a2 = $2;
		$a3 = $3;

		# nie ruszamy "call/jmp xxx" (don't touch "call/jmp xxx")
		if ( $a1 !~ /call/i && $a1 !~ /^\s*j[a-z]{1,3}/i ) {

			# nie wolno zamieniac cyfr and %st(n) (we mustn't change digits and %st(n))
			if ( $a2 !~ /\$/ && $a2 !~ /\%/ && $a2 !~ /_L\d+/ && $a2 =~ /[a-zA-Z_\.]/ ) {

				$a2 = "[$a2]";
			}
			if ( $a3 !~ /\$/ && $a3 !~ /\%/ && $a3 !~ /_L\d+/ && $a3 =~ /[a-zA-Z_\.]/ ) {

				$a3 = "[$a3]";
			}

			# UWAGA: zmiana kolejnosci argumentow bedzie pozniej
			# (ATTENTION: operand order will be changed later)
			$_ = "\t$a1\t$a2, $a3\n";
		}
	}

	if ( /^\s*(\w+)\s+([\$\%\w\+\-]+)\s*\s*$/ ) {

		my ($a1, $a2);

		$a1 = $1;
		$a2 = $2;

		# nie ruszamy "call/jmp xxx" (don't touch "call/jmp xxx")
		if ( $a1 !~ /call/i && $a1 !~ /^\s*j[a-z]{1,3}/i ) {

			# nie wolno zamieniac cyfr and %st(n) (we mustn't change digits and %st(n))
			if ( $a2 !~ /\$/ && $a2 !~ /\%/ && $a2 !~ /_L\d+/ && $a2 =~ /[a-zA-Z_\.]/ ) {

				$a2 = "[$a2]";
			}

			# UWAGA: zmiana kolejnosci argumentow bedzie pozniej
			# (ATTENTION: operand order will be changed later)
			$_ = "\t$a1\t$a2\n";
		}
	}

	# usuwanie znakow dolara (removing dollar chars)
	s/\$//g;
	# usuwanie znakow procenta (removing percent chars)
	s/%//g;
	# usuwanie znakow gwiazdki (removing asterisk chars)
	s/\*//g;

	# zmiana odnoszenia sie do pamieci (changing memory references):
	# seg: disp(base, index, scale)
	s/(\w+\s*:\s*)([\w\+\-\(\)]+)\s*\(\s*(\w+)\s*,\s*(\w+)\s*,\s*(\d)\s*\)/[$1$3+$5*$4+$2]/;
	s/(\w+\s*:\s*)([\w\+\-\(\)]+)\s*\(\s*(\w+)\s*,\s*(\w+)\s*,?\s*\)/[$1$3+$4+$2]/;
	s/(\w+\s*:\s*)\(\s*(\w+)\s*,\s*(\w+)\s*,\s*(\d)\s*\)/[$1$2+$3*$4]/;
	s/(\w+\s*:\s*)\(\s*(\w+)\s*,\s*(\w+)\s*,?\s*\)/[$1$2+$3]/;
	s/(\w+\s*:\s*)([\w\+\-\(\)]+)\s*\(\s*,\s*1\s*\)/[$1$2]/;
	s/(\w+\s*:\s*)([\w\+\-\(\)]+)\s*\(\s*,\s*(\w+)\s*,\s*(\d)\s*\)/[$1$3*$4+$2]/;
	s/(\w+\s*:\s*)([\w\+\-\(\)]+)\s*\(\s*(\w+)\s*\)/[$1$3+$2]/;
	s/(\w+\s*:\s*)\(\s*(\w+)\s*\)/[$1$2]/;

	# disp(base, index, scale)
	s/([\w\+\-\(\)]+)\(\s*(\w+)\s*,\s*(\w+)\s*,\s*(\d)\s*\)/[$2+$3*$4+$1]/;
	s/([\w\+\-\(\)]+)\(\s*(\w+)\s*,\s*(\w+)\s*,?\s*\)/[$2+$3+$1]/;
	s/\s*\(\s*(\w+)\s*,\s*(\w+)\s*,\s*(\d)\s*\)/\t[$1+$2*$3]/;
	s/\s*\(\s*(\w+)\s*,\s*(\w+)\s*,?\s*\)/\t[$1+$2]/;
	s/([\w\+\-\(\)]+)\(\s*,\s*(\w+)\s*,\s*(\d)\s*\)/[$2*$3+$1]/;

	# disp(, index)
	s/([\w\-\+\(\)]+)\(\s*,\s*1\s*\)/[$1]/;
	s/([\w\-\+\(\)]+)\(\s*,\s*(\w+)\s*\)/[$2+$1]/;

	# (base, index)
	s/\(\s*,\s*1\s*\)/[$1]/;
	s/\(\s*,\s*(\w+)\s*\)/[$1]/;

	# disp(base)
	s/([\w\-\+\(\)]+)\(\s*(\w+)\s*\)/[$2+$1]/ unless /st\(\d\)/i;
	s/\(\s*(\w+)\s*\)/[$1]/;

	# zmiana "st[N]" na "stN" (changing "st[N]" to "stN")
	s/(\s)st\[(\d)\]/$1 st$2/g;
	# zmiana "st" na "st0" (changing "st" to "st0")
	s/(\s)st(\s|,)/$1 st0$2/g;


	# zmiana kolejnosci argumentow (changing operands' order):
	if ( 		 /^\s*(\w+)\s+(\[?[:\.\w\*\+\-\(\)]+\]?)\s*,\s*(\[?[:\.\w\*\+\-\(\)]+\]?)\s*,\s*(\[?[:\.\w\*\+\-\(\)]+\]?)/ ) {
		if ( is_instr($1) ) {
			s/^\s*(\w+)\s+(\[?[:\.\w\*\+\-\(\)]+\]?)\s*,\s*(\[?[:\.\w\*\+\-\(\)]+\]?)\s*,\s*(\[?[:\.\w\*\+\-\(\)]+\]?)/\t$1\t$4, $3, $2/;
		}
	}
	if ( 		 /^\s*(\w+)\s+(\[?[:\.\w\*\+\-\(\)]+\]?)\s*,\s*(\[?[:\.\w\*\+\-\(\)]+\]?)([^,]*(;.*)?)$/ ) {
		if ( is_instr($1) ) {
			s/^\s*(\w+)\s+(\[?[:\.\w\*\+\-\(\)]+\]?)\s*,\s*(\[?[:\.\w\*\+\-\(\)]+\]?)([^,]*(;.*)?)$/\t$1\t$3, $2$4/ ;
		}
	}
	if ( 		 /^\s*(\w+)\s+(\[?[:\.\w\*\+\-\(\)]+\]?)([^,]*(;.*)?)$/ ) {
		if ( is_instr($1) ) {
			s/^\s*(\w+)\s+(\[?[:\.\w\*\+\-\(\)]+\]?)([^,]*(;.*)?)$/\t$1\t$2$3/;
		}
	}

	foreach my $i (@instr) {

		s/^\s*$i[b]\s*(.*)$/\t$i\tbyte $1/i;
		s/^\s*$i[w]\s*(.*)$/\t$i\tword $1/i;
		s/^\s*$i[l]\s*(.*)$/\t$i\tdword $1/i;
	}

	s/^\s*movsbw\s+(.*)\s*,\s*(.*)$/\tmovsx\t$1, byte $2\n/i;
	s/^\s*movsbl\s+(.*)\s*,\s*(.*)$/\tmovsx\t$1, byte $2\n/i;
	s/^\s*movswl\s+(.*)\s*,\s*(.*)$/\tmovsx\t$1, word $2\n/i;
	s/^\s*movzbw\s+(.*)\s*,\s*(.*)$/\tmovzx\t$1, byte $2\n/i;
	s/^\s*movzbl\s+(.*)\s*,\s*(.*)$/\tmovzx\t$1, byte $2\n/i;
	s/^\s*movzwl\s+(.*)\s*,\s*(.*)$/\tmovzx\t$1, word $2\n/i;

	s/^\s*l?(jmp|call)\s*(\[[\w\*\+\-\s]+\])/\t$1\tdword $2/i;
	s/^\s*l?(jmp|call)\s*([\w\*\+\-]+)/\t$1\tdword $2/i;
	s/^\s*l?(jmp|call)\s*(\w+)\s*,\s*(\w+)/\t$1\t$2:$3/i;
	s/^\s*lret\s*(.*)$/\tret\t$1\t/i;

	s/^\s*cbtw\s*/\tcbw\t/i;
	s/^\s*cwtl\s*/\tcwde\t/i;
	s/^\s*cwtd\s*/\tcwd\t/i;
	s/^\s*cltd\s*/\tcdq\t/i;

	s/^\s*f(\w+)s\s+(.*)$/\tf$1\tdword $2/i unless /fchs\s/i;
	s/^\s*f(\w+)l\s+(.*)$/\tf$1\tqword $2/i unless /fmul\s/i;
	s/^\s*f(\w+)q\s+(.*)$/\tf$1\tqword $2/i;
	s/^\s*f(\w+)t\s+(.*)$/\tf$1\ttword $2/i unless /fst\s/i;

	# REP**: usuwamy znak konca linii (REP**: removing the end of line char)
	s/^\s*(rep[enz]{0,2})\s*/\t$1/i;

	# usuwanie znakow '#' z dyrektyw kompilacji warunkowej
	# (removing the '#' chars form conditional compiling directives)
	s/\#//g;

	print WY;
}


##########################################################
# Zmiana komentarzy (changing the comments).
# GAS ma takie same komentarze, jak C (GAS has the same comments as C)

sub	komen {

	#	Komentarze jednolinijkowe (one-line comments):
	if ( /^(.+)\/\*(.*)\*\/(.+)$/ )	{ s/(.+)\/\*(.*)\*\/(.+)$/$1 $3 ; $2/g;	return $_; }
	if ( /^\/\*(.*)\*\/(.+)$/ )	{ s/\/\*(.*)\*\/(.+)$/$2 ; $1/g;	return $_; }
	if ( /^(.+)\/\*(.*)\*\/$/ )	{ s/(.+)\/\*(.*)\*\/$/$1 ; $2/g;	return $_; }
	if ( /^(.+)#(.*)$/ )		{ s/^(.+)#(.*)$/$1 ; $2/g;		return $_; }

	# Jesli komentarz jest jedyna rzecza w wierszu, to od razu go wypisujemy i idziemy dalej
	# (if the comment is the only thing on this line, we print it to the file and go further)
	if ( /^\/\*(.*)\*\/$/ )		{ s/\/\*(.*)\*\/$/; $1/g; print WY;	return $_; }
	if ( /^#.*$/ )			{ s/^#(.*)$/; $1/g; print WY;	return $_; }

	# Komentarze wielolinijkowe (multi-line comments)
	if ( /^(.*)\/\*(.*)$/ ) {

		# wyrzucamy /* z zachowaniem tego, co bylo przed tym
		# (we remove the /*, saving whatever was in front of it)
		s/^(.*)\/\*(.*)$/$1; $2/;
		print WY;

		while ( <WE> ) {

			# po prostu stawiamy srednik przed kazda linia
			# (we simply add a semicolon in front of every line)
			s/^(.*)$/; $1/;

			# jak trafimy na */, to go kasujemy i przerywamy ta petle
			# (when we find */, we remove it and stop this loop)
			if ( /\*\// ) {

				s/\*\///;
				print WY;
				return $_;
			}
			print WY;
		}
	}

}

##########################################################
# Kompilacja warunkowa (conditional compiling)

sub	kom_war {

	# parametr = 0 => nie ma drukowania (when the parameter is 0, there will be no printing)
	my $drukuj = shift;

	# UWAGA: na poczatku dajemy '#', zeby nie zostalo wziete do obrobki pozniej
	# ATTENTION: we put a '#' in front, so these won't be affected by further processing

	#	Kompilacja warunkowa (conditional compiling)
	if ( /^\s*\.ifdef/i ) {

		s/^\s*\.ifdef(.*)$/#if defined $1/i;
		if ( $drukuj ) { print WY; }
	}

	if ( /^\s*\.ifn(ot)?def/i ) {

		# zgodnie z podrecznikiem (according to the manual)
		s/^\s*\.ifn(ot)?def(.*)$/#if ~defined $1 | defined \@f\n\@\@:/i;
		if ( $drukuj ) { print WY; }
	}

	if ( /^\s*\.endif/i ) {

		s/^\s*\.endif.*$/#end if/i;
		if ( $drukuj ) { print WY; }
	}

	if ( /^\s*\.elseif/i ) {

	#	Operatory logiczne, mod i div (logical operators, mod and div):
		s/&&/&/g;
		s/\|\|/|/g;
		s/!/~/g;
		s/%/mod/g;
		s/\//div/g;
		s/<</shl/g;
		s/>>/shr/g;

		s/^\s*\.elseif(.*)$/#else if $1/i;
		if ( $drukuj ) { print WY; }
	}

	if ( /^\s*\.else/i ) {

		s/^\s*\.else(.*)$/#else $1/i;
		if ( $drukuj ) { print WY; }
	}

	if ( /^\s*\.if/i ) {

	#	Operatory logiczne, mod i div (logical operators, mod and div):
		s/&&/&/g;
		s/\|\|/|/g;
		s/!/~/g;
		s/%/mod/g;
		s/\//div/g;
		s/<</shl/g;
		s/>>/shr/g;

		s/^\s*\.if(.*)$/#if $1/i;
		# XXX: zostawiam tu "!defined" (I leave "!defined" here)
		# s/!\s*defined\s+(\w+)/(~defined $1 | defined \@f)/g;
		# if ( /~defined/ )	{ s/$/\n\@\@:\n/; };
		if ( $drukuj ) { print WY; }
	}

	if ( /\s*\.err/i ) {

		s/\s*\.err(.*)$/#display "$1"/i;
		if ( $drukuj ) { print WY; }
	}

}


##########################################################
# Koniec (the end):

close WY;
close WE;

