File: flasm.c

package info (click to toggle)
flasm 1.62-7
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd, stretch
  • size: 740 kB
  • ctags: 1,060
  • sloc: ansic: 8,966; yacc: 2,416; makefile: 38
file content (1854 lines) | stat: -rw-r--r-- 44,176 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
/*
flasm, command line assembler & disassembler of flash actionscript bytecode
Copyright (c) 2001 Opaque Industries, (c) 2002-2007 Igor Kogan, (c) 2005 Wang Zhen
All rights reserved. See LICENSE.TXT for terms of use.
*/

#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <ctype.h>
#include <time.h>
#include <unistd.h>

#ifdef MEMWATCH
#include "memwatch.h"
#endif

#ifdef __MINGW32__
#include <conio.h>
#include <windows.h>
#endif
#ifdef __APPLE__
#include <mach-o/dyld.h>
#endif

#include "zlib.h"
#include "util.h"
#include "flasm.h"

extern FILE *yyin;
extern void skipProtected(FILE * f, unsigned long int length);
extern void disassembleSWF(FILE * in, char *fname);

int swfVersion;

char *inputName;				/* actual command-line parameter */
static char *updateName = NULL;	/* swf file name found in disassembly's first line (movie foo.swf...) */
static char *flmName = NULL;	/* temporary disassembly during update */
static char *backupName = NULL;	/* foo.$wf if foo.swf is updated */
static FILE *updateFile = NULL;
static FILE *tempFile = NULL;
static FILE *inputFile = NULL;
static FILE *logFile = NULL;

static char swfHeader[4];
static long int flength = 0;
static char backupCreated = 0;

char wasCompressed = 0;
char compressAfter = 0;
int mode;

/* ini entries */
int showoffset = 0, hexoffset = 0, boutput = 0, literalconstants = 0, literalregisters = 1, clearregisterargs = 1, logmode = 0;
static char *logto = NULL, *flaplayer = NULL, *flabrowser = NULL, *flatest = NULL;
static char flapath[MAX_PATH_LEN];

void yyerror(char *s);
void warning(char *s);
int yyparse(void);

static byte *output = NULL;

static void decompressSWF(FILE * f, char *fname);
static void compressSWF(FILE * f, char *fname);

static long int defineMCLengthPos = 0;
static long int buttonLengthPos = 0;
static long int buttonLastOffsetPos = 0;
static long int placeMCLengthPos = 0;
static long int MCAllEventsPos = 0;
static long int len;

static unsigned int nLabels = 0;
struct _label {
	char *name;
	/* offset >=0 if actual label definition, -1 if predefinition from branch */
	long int offset;
};
static struct _label *labels = NULL;

static void waitUserInput(void)
{
#ifdef __MINGW32__
	/* make sure we have kbhit(), otherwise do nothing */
	fprintf(stderr, "Hit any key to continue..");
	while (!kbhit()) {

	}
#endif
}

unsigned long int nStrings = 0;
char **aStrings = NULL;

static void mexit(int msg)
{
	unsigned long int i;
	for (i = 0; i < nStrings; ++i)
		free(aStrings[i]);

	if (output != NULL)
		free(output);

	if (aStrings != NULL)
		free(aStrings);

	if (nLabels > 0 && labels != NULL)
		free(labels);

	exit(msg);
}

static void copyFileContents(FILE* srcFile, FILE* destFile)
{
    char buf[65535];
    size_t readCount = 0;
    while ((readCount = fread((void *) buf, sizeof(char), sizeof(buf), srcFile)) != 0) {
        fwrite(buf, sizeof(char), readCount, destFile);
    }
}

void tellUser(int isError, char *s, ...)
{
	va_list ap;
	static int usestderr = 1;
	static int firsttime = 1;

	if (logto != NULL && firsttime == 1) {
		firsttime = 0;
		if (logmode == 0)
			logFile = fopen(logto, "ab");
		else
			logFile = fopen(logto, "wb");

		if (logFile == NULL)
			fprintf(stderr, "Couldn't write to log file %s\nUsing stderr instead\n", logto);
		else {
			usestderr = 0;
			if (logmode == 0) {
				time_t now;
				time(&now);
				fprintf(logFile, "________________________\n%.24s\n\n", ctime(&now));
			}
		}
	}

	if (s != NULL && strlen(s) > 0) {
		va_start(ap, s);
		if (usestderr) {
			vfprintf(stderr, s, ap);
			fputc('\n', stderr);
		}
		else {
			vfprintf(logFile, s, ap);
			fputc('\n', logFile);
		}
		va_end(ap);
	}

	if (isError) {
		if (mode >= MODE_IDE && usestderr)
			waitUserInput();

		if (tempFile != NULL)
			fclose(tempFile);

		if (updateFile != NULL)
			fclose(updateFile);

		if (wasCompressed && backupCreated && updateName != NULL && access(backupName, R_OK) == 0) {
			remove(updateName);
			rename(backupName, updateName);
		}

		if (logFile != NULL)
			fclose(logFile);
	
		mexit(EXIT_FAILURE);
	}
}

char *mstrdup(const char *String)
{
	SUREALLOC(nStrings, aStrings, sizeof (char *));

	if (String == NULL) {
		if ((aStrings[nStrings] = malloc(256)) == NULL)
			tellUser(1, "Not enough memory to allocate a string");
	}
	else {
		size_t slen = strlen(String);

		if ((aStrings[nStrings] = malloc(slen + 1)) != NULL)
			memcpy(aStrings[nStrings], String, slen + 1);
		else
			tellUser(1, "Not enough memory to allocate a string");
	}

	return aStrings[nStrings++];
}

static unsigned int newLabel(char *name, long int offset)
{
	unsigned int i = nLabels;

	/* first search if label exists, and update offset if needed */
	if (name != NULL && nLabels>0) {
		do {
			i--;
			if (labels[i].name != NULL && strcmp(name, labels[i].name) == 0) {
				if (offset >= 0) {
					if (labels[i].offset == -1)
						labels[i].offset = offset;
					else
						yyerror("Label defined twice");
				}
				return i;
			}
		} while (i>0);
	}

	SUREALLOC(nLabels, labels, sizeof (struct _label));
	labels[nLabels].name = name;
	labels[nLabels].offset = offset;
	return (nLabels++);
}

void addLabel(char *label)
{
	newLabel(label, len);
}

int branchTarget(char *label)
{
	return writeShort(newLabel(label, -1));
}

int addNumLabel(int numLabel)
{
	/* numerical offset given in a branch */

	if (len + numLabel + 2 < 0)
		yyerror("Branch target out of range");

	return writeShort(newLabel(NULL, len + numLabel + 2));
}

int writeByte(byte num)
{
	if (len % OUTPUT_INC == 0)
		output = realloc(output, len + OUTPUT_INC);

	output[len++] = num;
	return 1;
}

int writeShort(unsigned int num)
{
	writeByte(num & 0xff);
	writeByte((num >> 8) & 0xff);
	return 2;
}

int writeFloat(float num)
{
	byte *p = (byte *) &num;

	if (byteorder == FLASM_BIG_ENDIAN) {
		writeByte(p[3]);
		writeByte(p[2]);
		writeByte(p[1]);
		writeByte(p[0]);
	}
	else {
		writeByte(p[0]);
		writeByte(p[1]);
		writeByte(p[2]);
		writeByte(p[3]);
	}

	return 4;
}

int writeDouble(double num)
{
	byte *p = (byte *) &num;

	if (byteorder == FLASM_BIG_ENDIAN) {
		writeByte(p[3]);
		writeByte(p[2]);
		writeByte(p[1]);
		writeByte(p[0]);
		writeByte(p[7]);
		writeByte(p[6]);
		writeByte(p[5]);
		writeByte(p[4]);
	}
	else {
		writeByte(p[4]);
		writeByte(p[5]);
		writeByte(p[6]);
		writeByte(p[7]);
		writeByte(p[0]);
		writeByte(p[1]);
		writeByte(p[2]);
		writeByte(p[3]);
	}

	return 8;
}

int writeLongInt(long int num)
{
	byte *p = (byte *) &num;

	if (byteorder == FLASM_BIG_ENDIAN) {
		writeByte(p[3]);
		writeByte(p[2]);
		writeByte(p[1]);
		writeByte(p[0]);
	}
	else {
		writeByte(p[0]);
		writeByte(p[1]);
		writeByte(p[2]);
		writeByte(p[3]);
	}

	return 4;
}

int writeString(char *str)
{
	int i;

	for (i = 0; str[i] != '\0'; ++i)
		writeByte((byte) str[i]);

	writeByte(0);

	return i + 1;
}

unsigned int nConstants = 0;
static char *constants[MAX_CONSTANTS];

void addConstant(char *str)
{
	constants[nConstants] = str;
	++nConstants;

	if (nConstants > MAX_CONSTANTS)
		yyerror("Too many constants");
}

unsigned int writeConstants(void)
{
	unsigned int i;
	unsigned long int clen = 2;

	writeByte(SWFACTION_CONSTANTPOOL);
	/* length */
	writeShort(0);
	writeShort(nConstants);

	for (i = 0; i < nConstants; ++i)
		clen += writeString(constants[i]);

	if (clen < 65533)
		patchLength((unsigned int) clen, (unsigned int) clen);
	else
		tellUser(1, "Constant pool exceeds 64k");

	return (unsigned int) clen + 3;
}

unsigned int writePushString(char *str)
{
	unsigned int i;

	for (i = 0; i < nConstants; ++i) {
		if (strcmp(constants[i], str) == 0)
			break;
	}

	if (i < nConstants) {
		if (i < 256) {
			/* constant, 1-byte reference */
			writeByte(0x08);
			writeByte((byte) i);
			return 2;
		}
		else {
			/* constant, 2-byte reference */
			writeByte(0x09);
			writeShort(i);
			return 3;
		}
	}

	/* string */
	writeByte(0);
	return writeString(str) + 1;
}

static void patchTargets(void)
{
	long int i = 0;

	while (i < len) {
		Action op = (Action) output[i++];
		if (op & 0x80) {
			unsigned int blocklen = S16(output + i);
			i += 2;

			if (op == SWFACTION_BRANCHALWAYS || op == SWFACTION_BRANCHIFTRUE) {
				long int offset;
				unsigned int target = S16(output+i);

				if (labels[target].offset < 0) {
					char msg[256] = "Label not found: ";
					yyerror(strcat(msg, labels[target].name));
				}

				offset = labels[target].offset - (i + 2);
				if (offset > 32767 || offset < -32768) {
					char msg[256] = "Label too far away from branch: ";
					yyerror(strcat(msg, labels[target].name));
				}

				output[i] = (byte) (offset & 0xff);
				output[i+1] = (byte) ((offset >> 8) & 0xff);
			}
			i += blocklen;	
		}
	}
}

static int flput(char b)
{
	++flength;
	return fputc(b, tempFile);
}

static void flputShort(unsigned int w)
{
	fputc(0xff & w, tempFile);
	fputc(0xff & (w >> 8), tempFile);
	flength += 2;
}

static void flputLong(unsigned long int l)
{
	fputc(0xff & l, tempFile);
	fputc(0xff & (l >> 8), tempFile);
	fputc(0xff & (l >> 16), tempFile);
	fputc(0xff & (l >> 24), tempFile);
	flength += 4;
}

static void flputString(char *s)
{
	fwrite(s, strlen(s)+1, 1, tempFile);
	flength += strlen(s)+1;
}

static int dupByte(void)
{
	return flput(fgetc(updateFile));
}

static unsigned int dupWord(void)
{
	int b1, b2;
	b1 = fgetc(updateFile);
	flput(b1);
	b2 = fgetc(updateFile);
	flput(b2);
	return ((unsigned int) b1 + ((unsigned int) b2 << 8));
}

static unsigned long int dupLong(void)
{
	return ((unsigned long int) dupWord() + ((unsigned long int) dupWord() << 16));
}

static void dupBuffered(unsigned long int length)
{
	static byte dupBuffer[MAX_BUFFER];

	flength += length;

	while (length > MAX_BUFFER) {
		if (fread(dupBuffer, 1, MAX_BUFFER, updateFile) == MAX_BUFFER) {
			fwrite(dupBuffer, 1, MAX_BUFFER, tempFile);
			length -= MAX_BUFFER;
		}
		else
			yyerror("Couldn't update because of unexpected SWF structure");
	}

	if (length > 0) {
		if (fread(dupBuffer, 1, length, updateFile) == length)
			fwrite(dupBuffer, 1, length, tempFile);
		else
			yyerror("Couldn't update because of unexpected SWF structure");
	}
}

void patchLength(unsigned int back, unsigned int blen)
{
	output[len - back - 1] = (blen >> 8) & 0xff;
	output[len - back - 2] = blen & 0xff;
}

void patchFlag(unsigned int back, byte flag)
{
	output[len - back - 1] = flag;
}

void patchFrameLoaded(unsigned int back, int numActions)
{
	if (numActions > 0 || numActions < 256)
		output[len - back - 1] = (byte) numActions;
	else
		yyerror("IfFrameLoaded block larger then 255 bytes is not allowed");
}

static void updateTmpLength(long int lenpos, long int reallen)
{
	long int curpos;
	curpos = ftell(tempFile);

	fseek(tempFile, lenpos, SEEK_SET);

	/* update long length */
	/* dont use flput to not affect the file size calculation */
	fputc((reallen & 0xff), tempFile);
	fputc((reallen >> 8) & 0xff, tempFile);
	fputc((reallen >> 16) & 0xff, tempFile);
	fputc((reallen >> 24) & 0xff, tempFile);

	fseek(tempFile, curpos, SEEK_SET);
}

static void updateShort(long int lenpos, unsigned int reallen)
{
	long int curpos = ftell(tempFile);

	fseek(tempFile, lenpos, SEEK_SET);

	/* update short length */
	/* dont use flput to not affect the file size calculation */
	fputc(reallen & 0xff, tempFile);
	fputc((reallen >> 8) & 0xff, tempFile);

	fseek(tempFile, curpos, SEEK_SET);
}

static void flushOutput(void)
{
	patchTargets();

	if (fwrite(output, 1, (size_t) len, tempFile) != (size_t) len)
		tellUser(1, "Error writing action block");

	flength += len;

	len = 0;

	if (nLabels > 0) {
		nLabels = 0;
		free(labels);
		labels = NULL;
	}

	nConstants = 0;
}

static void writeTagHeader(unsigned int type, unsigned long int length)
{
	if (length >= 63
		|| type == TAG_DEFINEBITSLOSSLESS
		|| type == TAG_DEFINEBITSLOSSLESS2
		|| type == TAG_SOUNDSTREAMBLOCK
		|| type == TAG_DEFINEBITS
		|| type == TAG_DEFINEBITSJPEG2
		|| type == TAG_DEFINEBITSJPEG3) {
		/*
		   long length, and also workaround for a really strange bug in flash player:
		   the above tags must always have long length to work
		 */
		flputShort((type << 6) + 63);
		flputLong(length);
	}
	else {
		/* short length */
		flputShort((type << 6) + length);
	}
}

static int handledTag(unsigned int tag)
{
	return (tag == TAG_PROTECT
			|| tag == TAG_ENABLEDEBUGGER
			|| tag == TAG_ENABLEDEBUGGER2
			|| tag == TAG_SCRIPTLIMITS
			|| tag == TAG_FILEATTRIBUTES
			|| tag == TAG_METADATA);
}

static unsigned long int findNextTag(unsigned int typeneeded)
{
	/*
	   dumps all tags of the updateFile to the tempFile
	   until required tag is found, returns its length 
	 */
	unsigned int type;
	unsigned long int length;

	while (!feof(updateFile)) {
		parseTagHeader(updateFile, &type, &length);
		if (type == typeneeded)
			return length;
		if (handledTag(type))
			skipProtected(updateFile, length);
		else {
			writeTagHeader(type, length);
			dupBuffered(length);
		}
	}
	tellUser(1, "Couldn't update because of unexpected SWF structure:\nunexpected end of SWF looking for Tag %04x", typeneeded);
	return (0);
}

static unsigned long int findNextTags(unsigned int *typefound, int numtypes, ...)
{
	/*
	   dumps all blocks of the updateFile to the tempFile
	   until one of the required tags is found, returns its length 
	 */
	va_list typelist;
	unsigned int type;
	unsigned long int length;
	int i;

	while (!feof(updateFile)) {
		parseTagHeader(updateFile, &type, &length);
		va_start(typelist, numtypes);
		for (i = 1; i <= numtypes; i++) {
			if (type == va_arg(typelist, unsigned int)) {
				*typefound = type;
				va_end(typelist);
				return length;
			}
		}
		va_end(typelist);

		if (handledTag(type))
			skipProtected(updateFile, length);
		else {
			writeTagHeader(type, length);
			dupBuffered(length);
		}
	}
	tellUser(1, "Couldn't update because of unexpected SWF structure:\nunexpected end of SWF.");
	return (0);
}

void writeDoAction()
{
	unsigned long int oldLength = findNextTag(TAG_DOACTION);

	/* skip old action  */
	skipProtected(updateFile, oldLength);

	writeTagHeader(TAG_DOACTION, len);

	/* write bison output from buffer to file and empty buffer */
	flushOutput();
}

void writeInitMC(unsigned int clipID)
{
	unsigned int oldID;
	unsigned long int oldLength = findNextTag(TAG_INITMOVIECLIP);

	writeTagHeader(TAG_INITMOVIECLIP, len + 2);

	oldID = dupWord();
	if (oldID != clipID)
		tellUser(1, "Couldn't update because of unexpected SWF structure:\nold initMovieClip ID %u doesn't match new ID %u", oldID, clipID);

	skipProtected(updateFile, oldLength - 2);

	flushOutput();
}

static unsigned int bitPos;
static unsigned int bitBuf;

static unsigned int dupBits(unsigned int n)
{
	unsigned long int v = 0;

	while (n > bitPos) {
		n -= bitPos;
		v |= bitBuf << n;
		bitBuf = (unsigned int) dupByte();
		bitPos = 8;
	}

	bitPos -= n;
	v |= bitBuf >> bitPos;
	bitBuf &= 0xff >> (8 - bitPos);
	/* never need more than 16 bits */
	return (unsigned int) v;
}

static void dupMatrix(void)
{
	bitPos = 8;
	bitBuf = (unsigned int) dupByte();

	if (dupBits(1))
		dupBits(dupBits(5) * 2);
	if (dupBits(1))
		dupBits(dupBits(5) * 2);
	dupBits(dupBits(5) * 2);
}

static void dupColorTransform(void)
{
	unsigned int needAdd, needMul, nBits;

	bitPos = 8;
	bitBuf = (unsigned int) dupByte();

	needAdd = dupBits(1);
	needMul = dupBits(1);
	nBits = dupBits(4);
	if (needMul)
		dupBits(nBits * 4);
	if (needAdd)
		dupBits(nBits * 4);
}

static void dupFilters(void)
{
	byte numfilters = dupByte();
	while(numfilters--)
		switch(dupByte()){
			case FILTER_DROPSHADOW:
				dupBuffered(23);
				break;
			case FILTER_BLUR:
				dupBuffered(9);
				break;
			case FILTER_GLOW:
				dupBuffered(15);
				break;
			case FILTER_BEVEL:
				dupBuffered(27);
				break;
			case FILTER_GRADIENTGLOW:
				dupBuffered(dupByte()*5 + 19);
				break;
			case FILTER_ADJUSTCOLOR:
				dupBuffered(80);
				break;
			case FILTER_GRADIENTBEVEL:
				dupBuffered(dupByte()*5 + 19);
				break;
			default:
				tellUser(1, "Unknown filter");
		}
}

void writePlaceMCStart(unsigned int clipID)
{
	unsigned int oldID = 0;
	unsigned int typefound;
	unsigned int flags;
	unsigned long int length, eventLength;

	/* skip all mcs without onClipEvent actions */
	do {
		length = findNextTags(&typefound, 2, TAG_PLACEOBJECT2, TAG_PLACEOBJECT3);
		if (typefound == TAG_PLACEOBJECT2) {
			flags = fgetc(updateFile);
			if (flags & PF_ONCLIPEVENTS)
				break;
			writeTagHeader(TAG_PLACEOBJECT2, length);
			flput(flags);
			/* copy the rest of the placeobject2 */
			dupBuffered(length - 1);
		}
		else {
			flags = getWord(updateFile);
			if (flags & PF_ONCLIPEVENTS)
				break;
			writeTagHeader(TAG_PLACEOBJECT3, length);
			flputShort(flags);
			/* copy the rest of the placeobject3 */
			dupBuffered(length - 2);
		}
	} while (1);

	/* placemc header, temporary long length, save length pos */
	writeTagHeader(typefound, 0xFF);
	placeMCLengthPos = ftell(tempFile) - 4;

	if (typefound == TAG_PLACEOBJECT3)
		flputShort(flags);
	else
		flput(flags);

	/* character depth */
	dupWord();

	if (flags & PF_CHARACTER)
		oldID = dupWord();
	else
		tellUser(1, "Couldn't update because of unexpected SWF structure:\nold placeMovieClip ID missing, new ID %u", clipID);
	if (oldID != clipID)
		tellUser(1, "Couldn't update because of unexpected SWF structure:\nold placeMovieClip ID %u doesn't match new ID %u", oldID, clipID);

	if (flags & PF_MATRIX)
		dupMatrix();
	if (flags & PF_COLORTRANSFORM)
		dupColorTransform();
	if (flags & PF_RATIO)
		dupWord();
	if (flags & PF_NAME)
		while (dupByte() != 0);
	if (flags & PF_DEFINECLIP)
		dupWord();
	if (flags & PF_FILTERS)
		dupFilters();
	if (flags & PF_BLENDMODE)
		dupByte();
	if (flags & PF_BITMAPCACHING)
		dupByte();

	/* reserved: always 0 */
	dupWord();

	/* save the pos for logical or of all events */
	MCAllEventsPos = ftell(tempFile);

	/* skip old events */
	if (swfVersion <= 5) {
		/* dup logical or of all events - temporary */
		dupWord();
		while (getWord(updateFile) > 0) {
			eventLength = getDoubleWord(updateFile);
			skipProtected(updateFile, eventLength);
		}
	}
	else if (swfVersion >= 6) {
		/* dup logical or of all events - temporary */
		dupLong();
		while (getDoubleWord(updateFile) > 0) {
			eventLength = getDoubleWord(updateFile);
			skipProtected(updateFile, eventLength);
		}
	}
}

void writePlaceMCEnd(unsigned long int flags)
{
	/* write empty event */
	flputShort(0);
	if (swfVersion >= 6)
		flputShort(0);

	updateTmpLength(placeMCLengthPos, ftell(tempFile) - placeMCLengthPos - 4);

	if (swfVersion <= 5) {
		updateShort(MCAllEventsPos, (unsigned int) flags);
	}
	else if (swfVersion >= 6) {
		updateShort(MCAllEventsPos, (unsigned int) (flags & 0xFFFF));
		updateShort(MCAllEventsPos + 2, (unsigned int) ((flags >> 16) & 0xFFFF));
	}

	placeMCLengthPos = 0;
	MCAllEventsPos = 0;
}

void writeOnClipEvent(unsigned long int flag)
{
	/* write event flag */
	flputShort(flag);
	if (swfVersion >= 6)
		flputShort((unsigned int) (flag >> 16));

	/* write action length */
	flputLong(len);

	flushOutput();
}

void writeButtonStart(unsigned int buttonID)
{
	int trackAsMenu;
	unsigned int oldID, actionOffset;
	unsigned long int length;

	/* skip all buttons without actions */
	do {
		length = findNextTag(TAG_DEFINEBUTTON2);
		oldID = getWord(updateFile);
		trackAsMenu = fgetc(updateFile);
		actionOffset = getWord(updateFile);

		if (actionOffset > 0)
			break;

		writeTagHeader(TAG_DEFINEBUTTON2, length);
		flputShort(oldID);
		flput(trackAsMenu);
		/* put action offset = 0 */
		flputShort(0);
		/* copy the rest of the button */
		dupBuffered(length - 5);
	} while(1);

	if (oldID != buttonID)
		tellUser(1, "Couldn't update because of unexpected SWF structure:\nold defineButton ID %u doesn't match new ID %u", oldID, buttonID);

	/* defineButton2 header, temporary long length, save length pos */
	writeTagHeader(TAG_DEFINEBUTTON2, 0xFF);
	buttonLengthPos = ftell(tempFile) - 4;

	flputShort(oldID);
	flput(trackAsMenu);
	flputShort(actionOffset);

	/* copy button visual part */
	dupBuffered(actionOffset - 2);

	/* skip old button actions part */
	skipProtected(updateFile, length - 3 - actionOffset);
}

void writeButtonEnd(void)
{
	updateTmpLength(buttonLengthPos, ftell(tempFile) - buttonLengthPos - 4);

	/* last offset is always 0 */
	updateShort(buttonLastOffsetPos, 0);

	buttonLengthPos = 0;
	buttonLastOffsetPos = 0;
}

void writeButtonEvent(unsigned int flags)
{
	/* write offset to the next condition */
	buttonLastOffsetPos = ftell(tempFile);
	flputShort(len+4);

	/* write button event flags */
	flputShort(flags);
	flushOutput();
}

void writeDefineMCStart(unsigned int clipID)
{
	unsigned int oldID;

	findNextTag(TAG_DEFINEMOVIECLIP);

	/* defineMovieClip header, temporary long length, save length pos */
	writeTagHeader(TAG_DEFINEMOVIECLIP, 0xFF);
	defineMCLengthPos = ftell(tempFile) - 4;

	oldID = dupWord();
	if (oldID != clipID)
		tellUser(1, "Couldn't update because of unexpected SWF structure:\nold defineMovieClip ID %u doesn't match new ID %u", oldID, clipID);
	
	/* frames total */
	dupWord();
}

void writeDefineMCEnd(void)
{
	/* dump the rest of movie clip */
	findNextTag(TAG_END);

	/* write movie clip end tag */
	flputShort(0);

	updateTmpLength(defineMCLengthPos, ftell(tempFile) - defineMCLengthPos - 4);

	defineMCLengthPos = 0;
}

void writeScriptLimits(unsigned int recursion, unsigned int timeout)
{
	writeTagHeader(TAG_SCRIPTLIMITS, 4);
	flputShort(recursion);
	flputShort(timeout);
}

void writeProtect(char *str)
{
	if (strlen(str) == 0) {
		/* no password */
		writeTagHeader(TAG_PROTECT, 0);
	}
	else {
		/* password found */
		writeTagHeader(TAG_PROTECT, strlen(str) + 3);
		flputShort(0);
		flputString(str);
	}
}

void writeEnableDebugger(char *str)
{
	if (strlen(str) == 0) {
		/* no password, probably impossible? */
		writeTagHeader(TAG_ENABLEDEBUGGER, 0);
	}
	else {
		/* password found */
		writeTagHeader(TAG_ENABLEDEBUGGER, strlen(str) + 3);
		flputShort(0);
		flputString(str);
	}
}

void writeEnableDebugger2(char *str)
{
	if (strlen(str) == 0) {
		/* no password, probably impossible? */
		writeTagHeader(TAG_ENABLEDEBUGGER2, 0);
	}
	else {
		/* password found */
		writeTagHeader(TAG_ENABLEDEBUGGER2, strlen(str) + 3);
		flputShort(0);
		flputString(str);
	}
}

void writeMetadata(char *str)
{
	writeTagHeader(TAG_METADATA, strlen(str) + 1);
	flputString(str);
}

void writeFileAttrs(unsigned long int attrs)
{
	writeTagHeader(TAG_FILEATTRIBUTES, 4);
	flputLong(attrs);
}

void writeImportAssets(char *from, unsigned int numAssets)
{
	if (numAssets>0) {
		unsigned int typefound;
		skipProtected(updateFile, findNextTags(&typefound, 2, TAG_IMPORTASSETS, TAG_IMPORTASSETS2));
		if (typefound == TAG_IMPORTASSETS) {
			writeTagHeader(TAG_IMPORTASSETS, len + strlen(from) + 3);
			flputString(from);
			flputShort(numAssets);
		}
		else {
			writeTagHeader(TAG_IMPORTASSETS2, len + strlen(from) + 5);
			flputString(from);
			/* Reserved: always 1 */
			flputShort(1);
			flputShort(numAssets);
		}
		if (fwrite(output, 1, (size_t) len, tempFile) != (size_t) len)
			tellUser(1, "Error writing importAssets");
		flength += len;
	}
	len = 0;
}

void writeExportAssets(unsigned int numAssets)
{
	if (numAssets>0) {
		skipProtected(updateFile, findNextTag(TAG_EXPORTASSETS));
		writeTagHeader(TAG_EXPORTASSETS, len+2);
		flputShort(numAssets);

		if (fwrite(output, 1, (size_t) len, tempFile) != (size_t) len)
			tellUser(1, "Error writing exportAssets");

		flength += len;
	}
	len = 0;
}

static void finalizeTemporaryFile(char *name)
{
	FILE* targetFile;

	if (!backupCreated) {
		backupName = mstrdup(name);
		backupCreated = 1;
		strcpy(backupName + strlen(backupName) - 4, ".$wf");
		/* remove evtl. existing previous backup foo.$wf */
		remove(backupName);
		/* foo.swf -> foo.$wf */
		if (rename(name, backupName) != 0)
			tellUser(1, "couldn't update: file %s is in use", name);
	}
	else {
		/* backup already here, just make temp file our final file */
		if (remove(name) != 0)
			tellUser(1, "couldn't update: file %s is in use", name);
	}

	targetFile = fopen(name, "wb");
	rewind(tempFile);
	copyFileContents(tempFile, targetFile);
	fclose(targetFile);
}

static void getSWFHeader(FILE * f)
{
	fread(swfHeader, 1, 3, f);
	swfHeader[3] = '\0';
}

static void createTemporaryFile(void);

void startUpdate(char *outputName)
{
	int b, i, bitstotal;

	if ((updateFile = fopen(outputName, "rb")) == NULL)
		tellUser(1, "Couldn't open file %s for update", outputName);

	getSWFHeader(updateFile);

	if (strcmp(swfHeader, "FWS") != 0) {
		if (strcmp(swfHeader, "CWS") == 0) {
			/* decompresses foo.swf, foo.$wf backup is created */
			decompressSWF(updateFile, outputName);
			updateFile = fopen(outputName, "rb");
			/* now we are just after the header in decompressed file */
			getSWFHeader(updateFile);
		}
		else
			tellUser(1, "Input file %s doesn't appear to be an SWF file", outputName);
	}

	flength = 0;

	updateName = mstrdup(outputName);

	createTemporaryFile();

	/* SWF header */
	flput('F');
	flput('W');
	flput('S');

	/* version */
	flput(swfVersion = fgetc(updateFile));

	/* file length - temporary! */
	flput(fgetc(updateFile));
	flput(fgetc(updateFile));
	flput(fgetc(updateFile));
	flput(fgetc(updateFile));

	/* movie bounds */
	b = fgetc(updateFile);
	bitstotal = 5 + 4 * ((b & 0xf8) >> 3);
	flput(b);
	for (i = 0; i < (bitstotal + 7) / 8 - 1; ++i)
		flput(fgetc(updateFile));

	/* frame rate and # of frames */
	flput(fgetc(updateFile));
	flput(fgetc(updateFile));
	flput(fgetc(updateFile));
	flput(fgetc(updateFile));
}

void finishUpdate(void)
{
	/* dump the rest of SWF */
	findNextTag(0);
	/* write movie end */
	flputShort(0);

	updateTmpLength(4, flength);

	fclose(updateFile);

	finalizeTemporaryFile(updateName);

	if (compressAfter) {
		updateFile = fopen(updateName, "rb");
		getSWFHeader(updateFile);
		compressSWF(updateFile, updateName);
	}

	if (mode == MODE_UPDATE)
		tellUser(0, "%s successfully updated, %li bytes", updateName, flength);
	else if (mode == MODE_ASSEMBLE)
		tellUser(0, "%s successfully assembled to %s, %li bytes", inputName, updateName, flength);
}

void writeASBytecode(void)
{
	long int n = 0;
	patchTargets();

	if (nLabels > 0) {
		nLabels = 0;
		free(labels);
		labels = NULL;
	}
	
	if (boutput == 0) {
		printf("%s", "__bytecode__(\"");
		while(n++ < len)
			printf("%02x", *(output+n-1));
		printf("%s", "\");\n");
	}
	else
		fwrite(output, 1, len, stdout);
}

static void createTemporaryFile(void)
{
	if ((tempFile = tmpfile()) == NULL)
		tellUser(1, "Couldn't create temporary file");
}

static void decompressSWF(FILE *f, char *fname)
{
	z_stream stream;
	static byte inputBuffer[MAX_BUFFER], outputBuffer[MAX_BUFFER];
	int status, count;

	flength = 0;
	createTemporaryFile();

	/* SWF header */
	flput('F');
	flput('W');
	flput('S');

	/* version */
	flput(fgetc(f));

	flput(fgetc(f));
	flput(fgetc(f));
	flput(fgetc(f));
	flput(fgetc(f));

	stream.avail_in = 0;
	stream.next_in = inputBuffer;
	stream.next_out = outputBuffer;
	stream.zalloc = (alloc_func) NULL;
	stream.zfree = (free_func) NULL;
	stream.opaque = (voidpf) 0;
	stream.avail_out = MAX_BUFFER;

	status = inflateInit(&stream);
	if (status != Z_OK)
		tellUser(0, "Error %i decompressing SWF: %s\n", status, stream.msg);

	do {
		if (stream.avail_in == 0) {
			stream.next_in = inputBuffer;
			stream.avail_in = fread(inputBuffer, 1, MAX_BUFFER, f);
		}

		if (stream.avail_in == 0)
			break;

		status = inflate(&stream, Z_SYNC_FLUSH);

		count = MAX_BUFFER - stream.avail_out;
		if (count) {
			fwrite(outputBuffer, 1, count, tempFile);
			flength += count;
		}

		stream.next_out = outputBuffer;
		stream.avail_out = MAX_BUFFER;
	}
	while (status == Z_OK);

	if (status != Z_STREAM_END && status != Z_OK)
		tellUser(0, "Error %i decompressing SWF: %s\n", status, stream.msg);

	status = inflateEnd(&stream);
	if (status != Z_OK)
		tellUser(0, "Error %i decompressing SWF: %s\n", status, stream.msg);

	fclose(f);

	if (mode != MODE_DISASSEMBLE)
		finalizeTemporaryFile(fname);

	if (mode == MODE_DECOMPRESS)
		tellUser(0, "%s successfully decompressed, %li bytes", fname, flength);

	wasCompressed = 1;
}

static void compressSWF(FILE *f, char *fname)
{
	z_stream stream;
	static byte inputBuffer[MAX_BUFFER], outputBuffer[MAX_BUFFER];
	int status, count;

	flength = 0;
	createTemporaryFile();

	/* SWF header  */
	flput('C');
	flput('W');
	flput('S');

	/* version */
	flput(fgetc(f));

	flput(fgetc(f));
	flput(fgetc(f));
	flput(fgetc(f));
	flput(fgetc(f));

	stream.avail_in = 0;
	stream.next_out = outputBuffer;
	stream.avail_out = MAX_BUFFER;
	stream.zalloc = (alloc_func) NULL;
	stream.zfree = (free_func) NULL;
	stream.opaque = (voidpf) 0;
	stream.next_in = inputBuffer;

	status = deflateInit(&stream, Z_BEST_COMPRESSION);

	if (status != Z_OK)
		tellUser(1, "Error %i compressing SWF: %s\n", status, stream.msg);

	while (1) {
		if (stream.avail_in == 0) {
			stream.next_in = inputBuffer;
			stream.avail_in = fread(inputBuffer, 1, MAX_BUFFER, f);
		}

		if (stream.avail_in == 0)
			break;

		status = deflate(&stream, Z_NO_FLUSH);
		if (status != Z_OK)
			tellUser(1, "Error %i compressing SWF: %s\n", status, stream.msg);

		count = MAX_BUFFER - stream.avail_out;
		if (count) {
			fwrite(outputBuffer, 1, count, tempFile);
			flength += count;
		}

		stream.next_out = outputBuffer;
		stream.avail_out = MAX_BUFFER;
	}

	stream.next_out = outputBuffer;
	stream.avail_out = MAX_BUFFER;

	do {
		status = deflate(&stream, Z_FINISH);

		count = MAX_BUFFER - stream.avail_out;
		if (count) {
			fwrite(outputBuffer, 1, count, tempFile);
			flength += count;
		}

		stream.next_out = outputBuffer;
		stream.avail_out = MAX_BUFFER;
	}
	while (status == Z_OK);

	if (status != Z_STREAM_END)
		tellUser(1, "Error %i compressing SWF: %s\n", status, stream.msg);

	status = deflateEnd(&stream);
	if (status != Z_OK)
		tellUser(1, "Error %i compressing SWF: %s\n", status, stream.msg);

	fclose(f);

	finalizeTemporaryFile(fname);

	if (mode == MODE_COMPRESS)
		tellUser(0, "%s successfully compressed, %li bytes", fname, flength);

}

extern int yydebug;

static void usage(void)
{
	printf("\nFlasm %s build %s", FLASM_VERSION, __DATE__);
	// printf(" (zlib %s)", ZLIB_VERSION);
	puts("");
	puts("");
	puts("(c) 2001 Opaque Industries, (c) 2002-2007 Igor Kogan, (c) 2005 Wang Zhen");
	puts("All rights reserved. See LICENSE.TXT for terms of use.");
	puts("");
	puts("Usage: flasm [command] filename");
	puts("");
	puts("Commands:");
	puts("   -d     Disassemble SWF file to the console");
	puts("   -a     Assemble Flasm project (FLM)");
	puts("   -u     Update SWF file, replace Flasm macros");
	puts("   -b     Assemble actions to __bytecode__ instruction or byte sequence");
	puts("   -z     Compress SWF with zLib");
	puts("   -x     Decompress SWF");
	puts("");
	puts("Backups with $wf extension are created for altered SWF files.");
	puts("");
	puts("To save disassembly or __bytecode__ to file, redirect it:");
	puts("flasm -d foo.swf > foo.flm");
	puts("flasm -b foo.txt > foo.as");
	puts("");
	puts("Read flasm.html for more information.");

	mexit(EXIT_FAILURE);
}

static void unescapePath(char *argument)
{
	int n = 0;
	char esc[3];
	char *s = argument;

	inputName = mstrdup(NULL);

	while ((inputName[n] = *s++) != 0) {
		if ((inputName[n] == '.') && (*s == 'h') && (*(s + 1) == 't') && (*(s + 2) == 'm'))
			/* extension found */
			break;

		if (inputName[n] == '%') {
			/* unescape URL encoded char */
			esc[0] = *s++;
			esc[1] = *s++;
			esc[2] = 0;

			inputName[n] = (char) (xtoi(esc));
		}
		n++;
	}

	inputName[n] = '\0';
	strcat(inputName, ".swf");
}

static int readINI(char *exepath, char *names, char *types, ...)
{
	/* slightly changed INITVARS from SNIPPETS collection, public domain by Raymond Gardner, Sept. 1991 */
	FILE *iniFile;
	char ln[256], *p, *namep, *typep, name[40], *e;
	va_list arglist;
	void *argp;
	int k;

	if ((iniFile = fopen("flasm.ini", "r")) == NULL) {
		/* flasm.ini not found in current directory, look at executable's path */
		int pathlen = strlen(exepath);
		char inipath[pathlen + 10], *inipathptr;
		if (exepath == NULL || *exepath == '\0')
			return -1;
		strcpy(inipath, exepath);
		inipathptr = inipath + pathlen;
		while (*inipathptr != '\\' && *inipathptr != '/' && *inipathptr != ':' && inipathptr>=inipath)
			inipathptr--;

		strcpy(inipathptr + 1, "flasm.ini");
		if ((iniFile = fopen(inipath, "r")) == NULL)
#ifdef CONFIG_PATH
			/* flasm.ini not found in current directory, look at config path */
			if ((iniFile = fopen(CONFIG_PATH, "r")) == NULL)
#endif
				return -1;
	}

	while (fgets(ln, 256, iniFile)) {													 /* read ini file */
		while (isspace(ln[0]))															 /* drop leading whitespace */
			memmove(ln, ln + 1, strlen(ln));
		if (ln[0] == '\0' || ln[0] == '#')												 /* skip if blank line or comment */
			continue;

		p = strchr(ln, '=');															 /* find equal sign */
		if (p == NULL)																	 /* error if none */
			tellUser(1, "Error parsing flasm.ini: %s", ln);

		while (p > ln && isspace(p[-1])) {												 /* remove whitespace before eq sign */
			memmove(p - 1, p, strlen(p - 1));
			--p;
		}
		*p++ = '\0';																	 /* plug EOS over eq sign */

		while (isspace(p[0]))															 /* remove leading space on init string */
			memmove(p, p + 1, strlen(p));

		k = strlen(p) - 1;																 /* init string length */
		if (k < 0)
			tellUser(1, "Error parsing flasm.ini: %s", ln);

		if (p[k] == '\n')
			p[k] = '\0';																 /* plug EOS over newline */
		else if (feof(iniFile))															 /* '\n' is missing - last line or buffer exceeded? */
			p[k + 1] = '\0';
		else
			tellUser(1, "Line too long in flasm.ini: %s", ln);

		va_start(arglist, types);														 /* setup for arglist search */

		namep = names;																	 /* init ptr to var names */
		typep = types;																	 /* init ptr to var types */

		while (*namep == ' ')															 /* skip blanks before namelist */
			++namep;

		while (*typep) {																 /* while any typelist items left... */
			argp = (void *) va_arg(arglist, void *);									 /* get var arg */

			k = strcspn(namep, " ");													 /* length of namelist entry */
			memmove(name, namep, k);													 /* put into name hold area */
			name[k] = '\0';																 /* terminate it */
			if (strIcmp(name, ln) != 0) {												 /* if it doesn't match... */
				namep += k;																 /* get next name */
				while (*namep == ' ')
					++namep;
				++typep;																 /* get next type */
			}
			else {																		 /* else name is found... */
				if (*typep == 'i') {													 /* if it's an int, init it */
					*(int *) argp = atoi(p);
				}
				else if (*typep == 's' || *typep == 'p') {
					if (*p == '"') {													 /* is string in quotes? */
						++p;															 /* skip leading quote, and */
						e = strchr(p, '"');												 /* look for trailing quote */
						if (e)															 /* terminate string if found */
							*e = '\0';
					}
					if (*typep == 'p')													 /* if it's a char *ptr */
						*(char **) argp = mstrdup(p);
					else																 /* must be char array */
						strcpy(argp, p);												 /* copy in string */
				}
				else
					tellUser(1, "Contact developer: bad argument type in readINI() call");

				break;																	 /* break search; get next line */
			}
		}
		va_end(arglist);
	}

	fclose(iniFile);
	return 0;
}

static char *executablePath(void) {
	char path[MAX_PATH_LEN];
#ifdef __MINGW32__
	if(GetModuleFileName(NULL, path, MAX_PATH_LEN - 1))
		return mstrdup(path);
#elif defined(__APPLE__)
	uint32_t pathlen = MAX_PATH_LEN - 1;
	if (_NSGetExecutablePath(path, &pathlen) == 0)
		return mstrdup(path);
#else
	int length = readlink("/proc/self/exe", path, sizeof(path));
	if (length > 0 && length < sizeof(path)) {
		 path[length] = '\0';
		 return mstrdup(path);
	}
#endif
	return NULL;
}

static void parseArgs(int argc, char *argv[])
{
	int ini;
	char *exepath;

	if (argv[1] == NULL)
		usage();

	exepath = executablePath();
	if (exepath == NULL)
		exepath = argv[0];

	ini = readINI(exepath,
			"logto flabrowser flaplayer flatest showoffset hexoffset boutput literalconstants literalregisters clearregisterargs logmode",
			"ppppiiiiiii",
			&logto, &flabrowser, &flaplayer, &flatest, &showoffset, &hexoffset, &boutput, &literalconstants, &literalregisters, &clearregisterargs, &logmode);

	if (ini != 0)
		tellUser(0, "Flasm configuration file flasm.ini not found, using default values");

	if ((strstr(argv[1], ".htm") != NULL) || (strstr(argv[1], "http://") != NULL)) {
		mode = MODE_IDE;

		if ((strIstr(argv[1], "ContextHelp") != NULL) || (strIstr(argv[1], "http://") != NULL)) {
			/* an attempt to access flash help */
			mode = MODE_FLASH_HELP;

			if (strlen(flabrowser) == 0)
				tellUser(1, "You must define 'flabrowser' value in flasm.ini to access flash help");

			if (access(flabrowser, X_OK) != 0)
				tellUser(1, "Couldn't start browser: %s", flabrowser);

			strcpy(flapath, flabrowser);
			strcat(flapath, " ");
			strcat(flapath, argv[1]);
			return;
		}

		if (strIstr(flatest, "FLAPLAYER") != NULL)
			strcpy(flapath, flaplayer);
		else if (strIstr(flatest, "FLABROWSER") != NULL)
			strcpy(flapath, flabrowser);
		else
			tellUser(1, "Invalid or missing 'flatest' value in flasm.ini");

		if (strlen(flapath) == 0)
			tellUser(1, "You must define '%s' value in flasm.ini for debugging", flatest);

		if (access(flapath, X_OK) != 0)
			tellUser(1, "Couldn't start: %s", flapath);

		if (strstr(argv[1], "file:///") != NULL)
			/* skip "file:///" (8 chars) */
			unescapePath(argv[1] + 8);
		else
			unescapePath(argv[1]);

		if ((inputFile = fopen(inputName, "rb")) == NULL)
			tellUser(1, "Couldn't open input file %s for reading", inputName);

		strcat(flapath, " ");
		strcat(flapath, argv[1]);

		if (strIstr(flatest, "FLAPLAYER") != NULL)
			strcpy(strstr(flapath, ".htm"), ".swf\0");

		return;
	}

	if (argv[1][0] == '-') {
		int i;
		if (argc < 3)
			usage();
		inputName = mstrdup(NULL);
		strcpy(inputName, argv[2]);

		/* join all arguments into one string - to support spaces in file names */
		for (i = 3; i < argc; i++) {
			strcat(inputName, " ");
			strcat(inputName, argv[i]);
		}

		switch (argv[1][1]) {
			case 'd':
				mode = MODE_DISASSEMBLE;
				break;

			case 'a':
				mode = MODE_ASSEMBLE;
				break;

			case 'u':
				mode = MODE_UPDATE;
				break;

			case 'b':
				mode = MODE_ASBYTECODE;
				break;

			case 'x':
				mode = MODE_DECOMPRESS;
				break;

			case 'z':
				mode = MODE_COMPRESS;
				break;

			default:
				usage();
		}
	}
	else {
		int i;
		inputName = mstrdup(NULL);
		strcpy(inputName, argv[1]);

		/* join all arguments into one string - to support spaces in file names */
		for (i = 2; i < argc; i++) {
			strcat(inputName, " ");
			strcat(inputName, argv[i]);
		}

		if (strIstr(inputName, ".swf") != NULL) {
			flmName = mstrdup(inputName);
			strcpy(strIstr(flmName, ".swf"), ".flm");
			/* redirect stdout to inputName.flm; should close it later? */
			if (freopen(flmName, "wb", stdout) == NULL)
				tellUser(1, "Couldn't open output file %s for writing", flmName);

			mode = MODE_DISASSEMBLE;
		}
		else if (strIstr(inputName, ".flm") != NULL) {
			mode = MODE_ASSEMBLE;
		}
		else
			usage();
	}

	if (inputName == NULL)
		usage();

	if ((inputFile = fopen(inputName, "rb")) == NULL)
		tellUser(1, "Couldn't open input file %s for reading", inputName);
}

int main(int argc, char *argv[])
{
	yydebug = 0;

#ifdef MEMWATCH
	mwStatistics(2);
#endif

	checkByteOrder();

	parseArgs(argc, argv);

	if (mode == MODE_DISASSEMBLE) {
		getSWFHeader(inputFile);
		if (strcmp(swfHeader, "FWS") != 0) {
			if (strcmp(swfHeader, "CWS") == 0) {
				decompressSWF(inputFile, inputName);
				/* skip SWF header, we know it's 'FWS' */
				fseek(tempFile, 3, SEEK_SET);
				disassembleSWF(tempFile, inputName);
			}
			else
				tellUser(1, "Input file doesn't appear to be an SWF file..");
		}
		else
			disassembleSWF(inputFile, inputName);

		mexit(EXIT_SUCCESS);
	}

	if (mode == MODE_DECOMPRESS) {
		getSWFHeader(inputFile);
		if (strcmp(swfHeader, "CWS") != 0) {
			if (strcmp(swfHeader, "FWS") == 0)
				tellUser(1, "Know what, the SWF isn't compressed");
			else
				tellUser(1, "Input file doesn't appear to be an SWF file..");
		}
		decompressSWF(inputFile, inputName);
		mexit(EXIT_SUCCESS);
	}

	if (mode == MODE_COMPRESS) {
		getSWFHeader(inputFile);
		if (strcmp(swfHeader, "FWS") != 0) {
			if (strcmp(swfHeader, "CWS") == 0)
				tellUser(1, "Know what, the SWF is already compressed");
			else
				tellUser(1, "Input file doesn't appear to be an SWF file..");
		}
		compressSWF(inputFile, inputName);
		mexit(EXIT_SUCCESS);
	}

	if (mode == MODE_ASSEMBLE || mode == MODE_ASBYTECODE) {
		yyin = inputFile;
		yyparse();
		fclose(inputFile);
		mexit(EXIT_SUCCESS);
	}

	if ((mode >= MODE_UPDATE) && (mode != MODE_FLASH_HELP)) {
		FILE *stdoutTempFile;
		getSWFHeader(inputFile);
		
		/* overwrite user settings */
		showoffset = 0;
		literalconstants = 1;
		literalregisters = 0;

		if (strcmp(swfHeader, "FWS") != 0) {
			if (strcmp(swfHeader, "CWS") == 0) {
				decompressSWF(inputFile, inputName);
				inputFile = fopen(inputName, "rb");
				getSWFHeader(inputFile);
			}
			else
				tellUser(1, "Input file doesn't appear to be an SWF file..");
		}

		flmName = mstrdup(inputName);
		strcpy(strIstr(flmName, ".swf"), ".$lm");

		/* redirect stdout to inputName.flm */
		stdoutTempFile = freopen(flmName, "wb", stdout);

		if (stdoutTempFile == NULL)
			tellUser(1, "Couldn't create temporary file");

		disassembleSWF(inputFile, inputName);
		fclose(stdoutTempFile);

		inputFile = fopen(flmName, "rb");
		inputName = mstrdup(flmName);
		yyin = inputFile;
		yyparse();

		fclose(inputFile);
		remove(flmName);
	}

	if (mode >= MODE_IDE) {
		if (system(flapath) == -1)
			tellUser(1, "Couldn't execute: %s", flapath);
	}

	mexit(EXIT_SUCCESS);
	/* to make compiler happy */
	exit(0);
}

/* indent -l200 --ignore-newlines -bap -nbc -fc1 -npsl -sob -ncdb -brs -br -nce -cdw -npcs -i4 -ts4 -c60 -cd30 -cli4 -cbi4 -bs -nss flasm.c */
/* splint -retvalint +posixlib -boolops -retvalother -realcompare -predboolint unflasm.c flasm.c util.c assembler.tab.c > flasm.lint */