/*************************************************************************** * __________ __ ___. * Open \______ \ ____ ____ | | _\_ |__ _______ ___ * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ / * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < < * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \ * \/ \/ \/ \/ \/ * $Id$ * * Copyright (C) 2007-2008 Michael Sevakis (jhMikeS) * Copyright (C) 2006-2007 Adam Gashlin (hcs) * Copyright (C) 2004-2007 Shay Green (blargg) * Copyright (C) 2002 Brad Martin * * 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 software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ****************************************************************************/ /* lovingly ripped off from Game_Music_Emu 0.5.2. http://www.slack.net/~ant/ */ /* DSP Based on Brad Martin's OpenSPC DSP emulator */ /* tag reading from sexyspc by John Brawn (John_Brawn@yahoo.com) and others */ #ifndef _SPC_CODEC_H_ #define _SPC_CODEC_H_ /* rather than comment out asserts, just define NDEBUG */ #ifndef NDEBUG #define NDEBUG #endif #include /** Basic configuration options **/ #ifndef ARM_ARCH #define ARM_ARCH 0 #endif #define SPC_DUAL_CORE 1 #if !defined(SPC_DUAL_CORE) || NUM_CORES == 1 #undef SPC_DUAL_CORE #define SPC_DUAL_CORE 0 #endif /* TGB is the only target fast enough for gaussian and realtime BRR decode */ /* echo is almost fast enough but not quite */ #if defined(TOSHIBA_GIGABEAT_F) || defined(TOSHIBA_GIGABEAT_S) ||\ (CONFIG_PLATFORM & PLATFORM_HOSTED) || MEMORYSIZE <= 2 /* Don't cache BRR waves */ #define SPC_BRRCACHE 0 /* Allow gaussian interpolation */ #define SPC_NOINTERP 0 /* Allow echo processing */ #define SPC_NOECHO 0 #elif defined(CPU_COLDFIRE) /* Cache BRR waves */ #define SPC_BRRCACHE 1 /* Disable gaussian interpolation */ #define SPC_NOINTERP 1 /* Allow echo processing */ #define SPC_NOECHO 0 #elif defined (CPU_PP) && SPC_DUAL_CORE /* Cache BRR waves */ #define SPC_BRRCACHE 1 /* Disable gaussian interpolation */ #define SPC_NOINTERP 1 /* Allow echo processing */ #define SPC_NOECHO 0 #else /* Cache BRR waves */ #define SPC_BRRCACHE 1 /* Disable gaussian interpolation */ #define SPC_NOINTERP 1 /* Disable echo processing */ #define SPC_NOECHO 1 #endif #ifdef CPU_ARM #if CONFIG_CPU != PP5002 #undef ICODE_ATTR #define ICODE_ATTR #undef IDATA_ATTR #define IDATA_ATTR #undef ICONST_ATTR #define ICONST_ATTR #undef IBSS_ATTR #define IBSS_ATTR #endif #if SPC_DUAL_CORE #undef SHAREDBSS_ATTR #define SHAREDBSS_ATTR __attribute__ ((section(".ibss"))) #undef SHAREDDATA_ATTR #define SHAREDDATA_ATTR __attribute__((section(".idata"))) #endif #endif /* Samples per channel per iteration */ #if defined(CPU_PP) && NUM_CORES == 1 #define WAV_CHUNK_SIZE 2048 #else #define WAV_CHUNK_SIZE 1024 #endif /**************** Little-endian handling ****************/ static inline unsigned get_le16( void const* p ) { return ((unsigned char const*) p) [1] * 0x100u + ((unsigned char const*) p) [0]; } static inline int get_le16s( void const* p ) { return ((signed char const*) p) [1] * 0x100 + ((unsigned char const*) p) [0]; } static inline void set_le16( void* p, unsigned n ) { ((unsigned char*) p) [1] = (unsigned char) (n >> 8); ((unsigned char*) p) [0] = (unsigned char) n; } #define GET_LE16( addr ) get_le16( addr ) #define GET_LE16A( addr ) get_le16( addr ) #define SET_LE16( addr, data ) set_le16( addr, data ) #define INT16A( addr ) (*(uint16_t*) (addr)) #define INT16SA( addr ) (*(int16_t*) (addr)) #ifdef ROCKBOX_LITTLE_ENDIAN #define GET_LE16SA( addr ) (*( int16_t*) (addr)) #define SET_LE16A( addr, data ) (void) (*(uint16_t*) (addr) = (data)) #else #define GET_LE16SA( addr ) get_le16s( addr ) #define SET_LE16A( addr, data ) set_le16 ( addr, data ) #endif struct Spc_Emu; #define THIS struct Spc_Emu* const this /* The CPU portion (shock!) */ struct cpu_regs_t { long pc; /* more than 16 bits to allow overflow detection */ uint8_t a; uint8_t x; uint8_t y; uint8_t status; uint8_t sp; }; struct src_dir { uint16_t start; uint16_t loop; }; struct cpu_ram_t { union { uint8_t padding1 [0x100]; uint16_t align; } padding1 [1]; union { uint8_t ram [0x10000]; struct src_dir sd [0x10000/sizeof(struct src_dir)]; }; uint8_t padding2 [0x100]; }; #undef RAM #define RAM ram.ram extern struct cpu_ram_t ram; long CPU_run( THIS, long start_time ) ICODE_ATTR; void CPU_Init( THIS ); /* The DSP portion (awe!) */ enum { VOICE_COUNT = 8 }; enum { REGISTER_COUNT = 128 }; struct raw_voice_t { int8_t volume [2]; uint8_t rate [2]; uint8_t waveform; uint8_t adsr [2]; /* envelope rates for attack, decay, and sustain */ uint8_t gain; /* envelope gain (if not using ADSR) */ int8_t envx; /* current envelope level */ int8_t outx; /* current sample */ int8_t unused [6]; }; struct globals_t { int8_t unused1 [12]; int8_t volume_0; /* 0C Main Volume Left (-.7) */ int8_t echo_feedback; /* 0D Echo Feedback (-.7) */ int8_t unused2 [14]; int8_t volume_1; /* 1C Main Volume Right (-.7) */ int8_t unused3 [15]; int8_t echo_volume_0; /* 2C Echo Volume Left (-.7) */ uint8_t pitch_mods; /* 2D Pitch Modulation on/off for each voice */ int8_t unused4 [14]; int8_t echo_volume_1; /* 3C Echo Volume Right (-.7) */ uint8_t noise_enables; /* 3D Noise output on/off for each voice */ int8_t unused5 [14]; uint8_t key_ons; /* 4C Key On for each voice */ uint8_t echo_ons; /* 4D Echo on/off for each voice */ int8_t unused6 [14]; uint8_t key_offs; /* 5C key off for each voice (instantiates release mode) */ uint8_t wave_page; /* 5D source directory (wave table offsets) */ int8_t unused7 [14]; uint8_t flags; /* 6C flags and noise freq */ uint8_t echo_page; /* 6D */ int8_t unused8 [14]; uint8_t wave_ended; /* 7C */ uint8_t echo_delay; /* 7D ms >> 4 */ char unused9 [2]; }; enum state_t { /* -1, 0, +1 allows more efficient if statements */ state_decay = -1, state_sustain = 0, state_attack = +1, state_release = 2 }; struct cache_entry_t { int16_t const* samples; unsigned end; /* past-the-end position */ unsigned loop; /* number of samples in loop */ unsigned start_addr; }; enum { BRR_BLOCK_SIZE = 16 }; enum { BRR_CACHE_SIZE = 0x20000 + 32} ; struct voice_t { #if SPC_BRRCACHE int16_t const* samples; long wave_end; int wave_loop; #else int16_t samples [3 + BRR_BLOCK_SIZE + 1]; int block_header; /* header byte from current block */ #endif uint8_t const* addr; short volume [2]; long position;/* position in samples buffer, with 12-bit fraction */ short envx; short env_mode; short env_timer; short key_on_delay; }; #if SPC_BRRCACHE /* a little extra for samples that go past end */ extern int16_t BRRcache [BRR_CACHE_SIZE]; #endif enum { FIR_BUF_HALF = 8 }; #if defined(CPU_COLDFIRE) /* global because of the large aligment requirement for hardware masking - * L-R interleaved 16-bit samples for easy loading and mac.w use. */ enum { FIR_BUF_CNT = FIR_BUF_HALF, FIR_BUF_SIZE = FIR_BUF_CNT * sizeof ( int32_t ), FIR_BUF_ALIGN = FIR_BUF_SIZE * 2, FIR_BUF_MASK = ~((FIR_BUF_ALIGN / 2) | (sizeof ( int32_t ) - 1)) }; #elif defined (CPU_ARM) #if ARM_ARCH >= 6 enum { FIR_BUF_CNT = FIR_BUF_HALF * 2, FIR_BUF_SIZE = FIR_BUF_CNT * sizeof ( int32_t ), FIR_BUF_ALIGN = FIR_BUF_SIZE, FIR_BUF_MASK = ~((FIR_BUF_ALIGN / 2) | (sizeof ( int32_t ) - 1)) }; #else enum { FIR_BUF_CNT = FIR_BUF_HALF * 2 * 2, FIR_BUF_SIZE = FIR_BUF_CNT * sizeof ( int32_t ), FIR_BUF_ALIGN = FIR_BUF_SIZE, FIR_BUF_MASK = ~((FIR_BUF_ALIGN / 2) | (sizeof ( int32_t ) * 2 - 1)) }; #endif /* ARM_ARCH */ #endif /* CPU_* */ struct Spc_Dsp { union { struct raw_voice_t voice [VOICE_COUNT]; uint8_t reg [REGISTER_COUNT]; struct globals_t g; int16_t align; } r; unsigned echo_pos; int keys_down; int noise_count; uint16_t noise; /* also read as int16_t */ #if defined(CPU_COLDFIRE) /* FIR history is interleaved. Hardware handles wrapping by mask. * |LR|LR|LR|LR|LR|LR|LR|LR| */ int32_t *fir_ptr; /* wrapped address just behind current position - allows mac.w to increment and mask fir_ptr */ int32_t *last_fir_ptr; /* copy of echo FIR constants as int16_t for use with mac.w */ int16_t fir_coeff [VOICE_COUNT]; #elif defined (CPU_ARM) /* fir_buf [i + 8] == fir_buf [i], to avoid wrap checking in FIR code */ int32_t *fir_ptr; #if ARM_ARCH >= 6 /* FIR history is interleaved with guard to eliminate wrap checking * when convolving. * |LR|LR|LR|LR|LR|LR|LR|LR|--|--|--|--|--|--|--|--| */ /* copy of echo FIR constants as int16_t, loaded as int32 for * halfword, packed multiples */ int16_t fir_coeff [VOICE_COUNT]; #else /* FIR history is interleaved with guard to eliminate wrap checking * when convolving. * |LL|RR|LL|RR|LL|RR|LL|RR|LL|RR|LL|RR|LL|RR|LL|RR|... * |--|--|--|--|--|--|--|--|--|--|--|--|--|--|--|--| */ /* copy of echo FIR constants as int32_t, for faster access */ int32_t fir_coeff [VOICE_COUNT]; #endif /* ARM_ARCH */ #else /* Unoptimized CPU */ /* fir_buf [i + 8] == fir_buf [i], to avoid wrap checking in FIR code */ int fir_pos; /* (0 to 7) */ int fir_buf [FIR_BUF_HALF * 2] [2]; /* copy of echo FIR constants as int, for faster access */ int fir_coeff [VOICE_COUNT]; #endif struct voice_t voice_state [VOICE_COUNT]; #if SPC_BRRCACHE uint8_t oldsize; struct cache_entry_t wave_entry [256]; struct cache_entry_t wave_entry_old [256]; #endif }; void DSP_run_( struct Spc_Dsp* this, long count, int32_t* out_buf ) ICODE_ATTR; void DSP_reset( struct Spc_Dsp* this ); static inline void DSP_run( struct Spc_Dsp* this, long count, int32_t* out ) { /* Should we just fill the buffer with silence? Flags won't be cleared */ /* during this run so it seems it should keep resetting every sample. */ if ( this->r.g.flags & 0x80 ) DSP_reset( this ); DSP_run_( this, count, out ); } /**************** SPC emulator ****************/ /* 1.024 MHz clock / 32000 samples per second */ enum { CLOCKS_PER_SAMPLE = 32 }; enum { EXTRA_CLOCKS = CLOCKS_PER_SAMPLE / 2 }; /* using this disables timer (since this will always be in the future) */ enum { TIMER_DISABLED_TIME = 127 }; enum { ROM_SIZE = 64 }; enum { ROM_ADDR = 0xFFC0 }; enum { TIMER_COUNT = 3 }; struct Timer { long next_tick; int period; int count; int shift; int enabled; int counter; }; void Timer_run_( struct Timer* t, long time ) ICODE_ATTR; static inline void Timer_run( struct Timer* t, long time ) { if ( time >= t->next_tick ) Timer_run_( t, time ); } struct Spc_Emu { uint8_t cycle_table [0x100]; struct cpu_regs_t r; int32_t* sample_buf; long next_dsp; int rom_enabled; int extra_cycles; struct Timer timer [TIMER_COUNT]; /* large objects at end */ struct Spc_Dsp dsp; uint8_t extra_ram [ROM_SIZE]; uint8_t boot_rom [ROM_SIZE]; }; enum { SPC_FILE_SIZE = 0x10180 }; struct spc_file_t { char signature [27]; char unused [10]; uint8_t pc [2]; uint8_t a; uint8_t x; uint8_t y; uint8_t status; uint8_t sp; char unused2 [212]; uint8_t ram [0x10000]; uint8_t dsp [128]; uint8_t ipl_rom [128]; }; void SPC_Init( THIS ); int SPC_load_spc( THIS, const void* data, long size ); /**************** DSP interaction ****************/ void DSP_write( struct Spc_Dsp* this, int i, int data ) ICODE_ATTR; static inline int DSP_read( struct Spc_Dsp* this, int i ) { assert( (unsigned) i < REGISTER_COUNT ); return this->r.reg [i]; } void SPC_run_dsp_( THIS, long time ) ICODE_ATTR; static inline void SPC_run_dsp( THIS, long time ) { if ( time >= this->next_dsp ) SPC_run_dsp_( this, time ); } int SPC_read( THIS, unsigned addr, long const time ) ICODE_ATTR; void SPC_write( THIS, unsigned addr, int data, long const time ) ICODE_ATTR; /**************** Sample generation ****************/ int SPC_play( THIS, long count, int32_t* out ) ICODE_ATTR; #endif /* _SPC_CODEC_H_ */ id='n299' href='#n299'>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
/*  _______         ____    __         ___    ___
 * \    _  \       \    /  \  /       \   \  /   /       '   '  '
 *  |  | \  \       |  |    ||         |   \/   |         .      .
 *  |  |  |  |      |  |    ||         ||\  /|  |
 *  |  |  |  |      |  |    ||         || \/ |  |         '  '  '
 *  |  |  |  |      |  |    ||         ||    |  |         .      .
 *  |  |_/  /        \  \__//          ||    |  |
 * /_______/ynamic    \____/niversal  /__\  /____\usic   /|  .  . ibliotheque
 *                                                      /  \
 *                                                     / .  \
 * itread.c - Code to read an Impulse Tracker         / / \  \
 *            module from an open file.              | <  /   \_
 *                                                   |  \/ /\   /
 * Based on the loader from an IT player by Bob.      \_  /  > /
 * Adapted for DUMB by entheh.                          | \ / /
 *                                                      |  ' /
 *                                                       \__/
 */

#include <stdlib.h>
#include <string.h>//might not be necessary later; required for memset

#include "dumb.h"
#include "internal/it.h"



#define INVESTIGATE_OLD_INSTRUMENTS



static int it_seek(DUMBFILE *f, long offset)
{
	long pos = dumbfile_pos(f);

	if (pos > offset)
		return -1;

	if (pos < offset)
		if (dumbfile_skip(f, offset - pos))
			return -1;

	return 0;
}



typedef unsigned char byte;
typedef unsigned short word;
typedef unsigned long dword;



static unsigned char *sourcebuf = NULL;
static unsigned char *sourcepos = NULL;
static unsigned char *sourceend;
static int rembits = 0;



static int readblock(DUMBFILE *f)
{
	long size;
	int c;

	size = dumbfile_igetw(f);
	if (size < 0)
		return size;

	sourcebuf = malloc(size);
	if (!sourcebuf)
		return -1;

	c = dumbfile_getnc((char *)sourcebuf, size, f);
	if (c < size) {
		free(sourcebuf);
		sourcebuf = NULL;
		return -1;
	}

	sourcepos = sourcebuf;
	sourceend = sourcebuf + size;
	rembits = 8;
	return 0;
}



static void freeblock(void)
{
	free(sourcebuf);
	sourcebuf = NULL;
}



static int readbits(int bitwidth)
{
	int val = 0;
	int b = 0;

	if (sourcepos >= sourceend) return val;

	while (bitwidth > rembits) {
		val |= *sourcepos++ << b;
		if (sourcepos >= sourceend) return val;
		b += rembits;
		bitwidth -= rembits;
		rembits = 8;
	}

	val |= (*sourcepos & ((1 << bitwidth) - 1)) << b;
	*sourcepos >>= bitwidth;
	rembits -= bitwidth;

	return val;
}



/** WARNING - do we even need to pass `right`? */
/** WARNING - why bother memsetting at all? The whole array is written... */
// if we do memset, dumb_silence() would be neater...
static int decompress8(DUMBFILE *f, sample_t *left, sample_t *right, int len, int cmwt)
{
	int blocklen, blockpos;
	byte bitwidth;
	word val;
	char d1, d2;

	memset(left, 0, len * sizeof(*left));
	if (right) {
		memset(right, 0, len * sizeof(*right));
		len <<= 1;
	}

	while (len > 0) {
		//Read a block of compressed data:
		if (readblock(f))
			return -1;
		//Set up a few variables
		blocklen = (len < 0x8000) ? len : 0x8000; //Max block length is 0x8000 bytes
		blockpos = 0;
		bitwidth = 9;
		d1 = d2 = 0;
		//Start the decompression:
		while (blockpos < blocklen) {
			//Read a value:
			val = (word)readbits(bitwidth);
			//Check for bit width change:

			if (bitwidth < 7) { //Method 1:
				if (val == (1 << (bitwidth - 1))) {
					val = (word)readbits(3) + 1;
					bitwidth = (val < bitwidth) ? val : val + 1;
					continue;
				}
			}
			else if (bitwidth < 9) { //Method 2
				byte border = (0xFF >> (9 - bitwidth)) - 4;

				if (val > border && val <= (border + 8)) {
					val -= border;
					bitwidth = (val < bitwidth) ? val : val + 1;
					continue;
				}
			}
			else if (bitwidth == 9) { //Method 3
				if (val & 0x100) {
					bitwidth = (val + 1) & 0xFF;
					continue;
				}
			}
			else { //Illegal width, abort ?
				freeblock();
				return -1;
			}

			//Expand the value to signed byte:
			{
				char v; //The sample value:
				if (bitwidth < 8) {
					byte shift = 8 - bitwidth;
					v = (val << shift);
					v >>= shift;
				}
				else
					v = (char)val;

				//And integrate the sample value
				//(It always has to end with integration doesn't it ? ;-)
				d1 += v;
				d2 += d1;
			}

			//Store !
			/* Version 2.15 was an unofficial version with hacked compression
			 * code. Yay, better compression :D
			 */
			if (right && (len & 1))
				*right++ = (int)(signed char)(cmwt == 0x215 ? d2 : d1) << 16;
			else
				*left++ = (int)(signed char)(cmwt == 0x215 ? d2 : d1) << 16;
			len--;
			blockpos++;
		}
		freeblock();
	}
	return 0;
}



static int decompress16(DUMBFILE *f, sample_t *left, sample_t *right, int len, int cmwt)
{
	int blocklen, blockpos;
	byte bitwidth;
	long val;
	short d1, d2;

	memset(left, 0, len * sizeof(*left));
	if (right) {
		memset(right, 0, len * sizeof(*right));
		len <<= 1;
	}

	while (len > 0) {
		//Read a block of compressed data:
		if (readblock(f))
			return -1;
		//Set up a few variables
		blocklen = (len < 0x4000) ? len : 0x4000; // Max block length is 0x4000 bytes
		blockpos = 0;
		bitwidth = 17;
		d1 = d2 = 0;
		//Start the decompression:
		while (blockpos < blocklen) {
			val = readbits(bitwidth);
			//Check for bit width change:

			if (bitwidth < 7) { //Method 1:
				if (val == (1 << (bitwidth - 1))) {
					val = readbits(4) + 1;
					bitwidth = (val < bitwidth) ? val : val + 1;
					continue;
				}
			}
			else if (bitwidth < 17) { //Method 2
				word border = (0xFFFF >> (17 - bitwidth)) - 8;

				if (val > border && val <= (border + 16)) {
					val -= border;
					bitwidth = val < bitwidth ? val : val + 1;
					continue;
				}
			}
			else if (bitwidth == 17) { //Method 3
				if (val & 0x10000) {
					bitwidth = (val + 1) & 0xFF;
					continue;
				}
			}
			else { //Illegal width, abort ?
				freeblock();
				return -1;
			}

			//Expand the value to signed byte:
			{
				short v; //The sample value:
				if (bitwidth < 16) {
					byte shift = 16 - bitwidth;
					v = (short)(val << shift);
					v >>= shift;
				}
				else
					v = (short)val;

				//And integrate the sample value
				//(It always has to end with integration doesn't it ? ;-)
				d1 += v;
				d2 += d1;
			}

			//Store !
			/* Version 2.15 was an unofficial version with hacked compression
			 * code. Yay, better compression :D
			 */
			if (right && (len & 1))
				*right++ = (int)(signed short)(cmwt == 0x215 ? d2 : d1) << 8;
			else
				*left++ = (int)(signed short)(cmwt == 0x215 ? d2 : d1) << 8;
			len--;
			blockpos++;
		}
		freeblock();
	}
	return 0;
}



static int it_read_envelope(IT_ENVELOPE *envelope, DUMBFILE *f)
{
	int n;

	envelope->flags = dumbfile_getc(f);
	envelope->n_nodes = dumbfile_getc(f);
	envelope->loop_start = dumbfile_getc(f);
	envelope->loop_end = dumbfile_getc(f);
	envelope->sus_loop_start = dumbfile_getc(f);
	envelope->sus_loop_end = dumbfile_getc(f);
	for (n = 0; n < envelope->n_nodes; n++) {
		envelope->node_y[n] = dumbfile_getc(f);
		envelope->node_t[n] = dumbfile_igetw(f);
	}
	dumbfile_skip(f, 75 - envelope->n_nodes * 3 + 1);

	return dumbfile_error(f);
}



static int it_read_old_instrument(IT_INSTRUMENT *instrument, DUMBFILE *f)
{
	int n;

	if (dumbfile_mgetl(f) != IT_INSTRUMENT_SIGNATURE)
		return -1;

	/* Skip DOS Filename. */
	dumbfile_skip(f, 13);

	instrument->volume_envelope.flags = dumbfile_getc(f);
	instrument->volume_envelope.loop_start = dumbfile_getc(f);
	instrument->volume_envelope.loop_end = dumbfile_getc(f);
	instrument->volume_envelope.sus_loop_start = dumbfile_getc(f);
	instrument->volume_envelope.sus_loop_end = dumbfile_getc(f);

	/* Skip two unused bytes. */
	dumbfile_skip(f, 2);

	/* In the old instrument format, fadeout ranges from 0 to 64, and is
	 * subtracted at intervals from a value starting at 512. In the new
	 * format, all these values are doubled. Therefore we double when loading
	 * from the old instrument format - that way we don't have to think about
	 * it later.
	 */
	instrument->fadeout = dumbfile_igetw(f) << 1;
	instrument->new_note_action = dumbfile_getc(f);
	instrument->dup_check_type = dumbfile_getc(f);
	instrument->dup_check_action = DCA_NOTE_CUT; // This might be wrong!
	/** WARNING - what is the duplicate check action for old-style instruments? */

	/* Skip Tracker Version and Number of Samples. These are only used in
	 * separate instrument files. Also skip unused bytes and Instrument Name.
	 */
	dumbfile_skip(f, 36);

	instrument->pp_separation = 0;
	instrument->pp_centre = 60;
	instrument->global_volume = 128;
	/** WARNING - should global_volume be 64 or something? */
	instrument->default_pan = 32;
	/** WARNING - should default_pan be 128, meaning don`t use? */
	instrument->random_volume = 0;
	instrument->random_pan = 0;

	for (n = 0; n < 120; n++) {
		instrument->map_note[n] = dumbfile_getc(f);
		instrument->map_sample[n] = dumbfile_getc(f);
	}

	/* Skip "Volume envelope (200 bytes)". */
	// - need to know better what this is for though.
	dumbfile_skip(f, 200);

#if defined(INVESTIGATE_OLD_INSTRUMENTS) && 0
	fprintf(stderr, "Inst %02d Env:", n);
#endif

	for (n = 0; n < 25; n++)
	{
		instrument->volume_envelope.node_t[n] = dumbfile_getc(f);
		instrument->volume_envelope.node_y[n] = dumbfile_getc(f);

#if defined(INVESTIGATE_OLD_INSTRUMENTS) && 0
		fprintf(stderr, " %d,%d",
				instrument->volume_envelope.node_t[n],
				instrument->volume_envelope.node_y[n]);
#endif

		// This loop is unfinished, as we can probably escape from it before
		// the end if we want to. Hence the otherwise useless dumbfile_skip()
		// call below.
	}
	dumbfile_skip(f, 50 - (n << 1));
	instrument->volume_envelope.n_nodes = n;

#if defined(INVESTIGATE_OLD_INSTRUMENTS) && 0
	fprintf(stderr, "\n");
#endif

	if (dumbfile_error(f))
		return -1;

	instrument->filter_cutoff = 127;
	instrument->filter_resonance = 0;

	instrument->pan_envelope.flags = 0;
	instrument->pitch_envelope.flags = 0;

	return 0;
}



static int it_read_instrument(IT_INSTRUMENT *instrument, DUMBFILE *f)
{
	int n;

	if (dumbfile_mgetl(f) != IT_INSTRUMENT_SIGNATURE)
		return -1;

	/* Skip DOS Filename. */
	dumbfile_skip(f, 13);

	instrument->new_note_action = dumbfile_getc(f);
	instrument->dup_check_type = dumbfile_getc(f);
	instrument->dup_check_action = dumbfile_getc(f);
	instrument->fadeout = dumbfile_igetw(f);
	instrument->pp_separation = dumbfile_getc(f);
	instrument->pp_centre = dumbfile_getc(f);
	instrument->global_volume = dumbfile_getc(f);
	instrument->default_pan = dumbfile_getc(f);
	instrument->random_volume = dumbfile_getc(f);
	instrument->random_pan = dumbfile_getc(f);

	/* Skip Tracker Version and Number of Samples. These are only used in
	 * separate instrument files. Also skip unused byte and Instrument Name.
	 */
	dumbfile_skip(f, 30);

	instrument->filter_cutoff = dumbfile_getc(f);
	instrument->filter_resonance = dumbfile_getc(f);

	/* Skip MIDI Channel, Program and Bank. */
	dumbfile_skip(f, 4);

	for (n = 0; n < 120; n++) {
		instrument->map_note[n] = dumbfile_getc(f);
		instrument->map_sample[n] = dumbfile_getc(f);
	}

	if (dumbfile_error(f))
		return -1;

	if (it_read_envelope(&instrument->volume_envelope, f)) return -1;
	if (it_read_envelope(&instrument->pan_envelope, f)) return -1;
	if (it_read_envelope(&instrument->pitch_envelope, f)) return -1;

	return 0;
}



static int it_read_sample_header(IT_SAMPLE *sample, unsigned char *convert, long *offset, DUMBFILE *f)
{
	if (dumbfile_mgetl(f) != IT_SAMPLE_SIGNATURE)
		return -1;

	/* Skip DOS Filename. */
	dumbfile_skip(f, 13);

	sample->global_volume = dumbfile_getc(f);
	sample->flags = dumbfile_getc(f);
	sample->default_volume = dumbfile_getc(f);

	/* Skip Sample Name. */
	dumbfile_skip(f, 26);

	*convert = dumbfile_getc(f);
	sample->default_pan = dumbfile_getc(f);
	sample->length = dumbfile_igetl(f);
	sample->loop_start = dumbfile_igetl(f);
	sample->loop_end = dumbfile_igetl(f);
	sample->C5_speed = dumbfile_igetl(f);
	sample->sus_loop_start = dumbfile_igetl(f);
	sample->sus_loop_end = dumbfile_igetl(f);

#ifdef STEREO_SAMPLES_COUNT_AS_TWO
	if (sample->flags & IT_SAMPLE_STEREO) {
		sample->length >>= 1;
		sample->loop_start >>= 1;
		sample->loop_end >>= 1;
		sample->C5_speed >>= 1;
		sample->sus_loop_start >>= 1;
		sample->sus_loop_end >>= 1;
	}
#endif

	if (sample->flags & IT_SAMPLE_EXISTS) {
		if (sample->length <= 0)
			sample->flags &= ~IT_SAMPLE_EXISTS;
		else {
			if ((unsigned int)sample->loop_end > (unsigned int)sample->length)
				sample->flags &= ~IT_SAMPLE_LOOP;
			else if ((unsigned int)sample->loop_start >= (unsigned int)sample->loop_end)
				sample->flags &= ~IT_SAMPLE_LOOP;

			if ((unsigned int)sample->sus_loop_end > (unsigned int)sample->length)
				sample->flags &= ~IT_SAMPLE_SUS_LOOP;
			else if ((unsigned int)sample->sus_loop_start >= (unsigned int)sample->sus_loop_end)
				sample->flags &= ~IT_SAMPLE_SUS_LOOP;

			/* We may be able to truncate the sample to save memory. */
			if (sample->flags & IT_SAMPLE_LOOP) {
				if ((sample->flags & IT_SAMPLE_SUS_LOOP) && sample->sus_loop_end >= sample->loop_end)
					sample->length = sample->sus_loop_end;
				else
					sample->length = sample->loop_end;
			}
		}
	}

	*offset = dumbfile_igetl(f);

	sample->vibrato_speed = dumbfile_getc(f);
	sample->vibrato_depth = dumbfile_getc(f);
	sample->vibrato_rate = dumbfile_getc(f);
	sample->vibrato_waveform = dumbfile_getc(f);

	return dumbfile_error(f);
}



static long it_read_sample_data(int cmwt, IT_SAMPLE *sample, unsigned char convert, DUMBFILE *f)
{
	long n;

	sample->left = malloc(sample->length * sizeof(*sample->left));
	if (!sample->left)
		return -1;

	if (sample->flags & IT_SAMPLE_STEREO) {
		sample->right = malloc(sample->length * sizeof(*sample->right));
		if (!sample->right)
			return -1;
	}

	if (sample->flags & 8) {
		/* If the sample is packed, then we must unpack it. */

		/** WARNING - unresolved business here... test with ModPlug? */

		if (sample->flags & IT_SAMPLE_STEREO)
                    return -1;
                
/*
//#ifndef STEREO_SAMPLES_COUNT_AS_TWO
		ASSERT(!(sample->flags & IT_SAMPLE_STEREO));
//#endif
*/
		if (sample->flags & IT_SAMPLE_16BIT)
			decompress16(f, sample->left, sample->right, sample->length, cmwt);
		else
			decompress8(f, sample->left, sample->right, sample->length, cmwt);
	} else if (sample->flags & IT_SAMPLE_STEREO) {
		if (sample->flags & IT_SAMPLE_16BIT) {
			if (convert & 2) {
				for (n = 0; n < sample->length; n++) {
					sample->left[n] = (int)(signed short)dumbfile_mgetw(f) << 8;
					sample->right[n] = (int)(signed short)dumbfile_mgetw(f) << 8;
				}
			} else {
				for (n = 0; n < sample->length; n++) {
					sample->left[n] = (int)(signed short)dumbfile_igetw(f) << 8;
					sample->right[n] = (int)(signed short)dumbfile_igetw(f) << 8;
				}
			}
		} else {
			for (n = 0; n < sample->length; n++) {
				sample->left[n] = (int)(signed char)dumbfile_getc(f) << 16;
				sample->right[n] = (int)(signed char)dumbfile_getc(f) << 16;
			}
		}
	} else if (sample->flags & IT_SAMPLE_16BIT) {
		if (convert & 2)
			for (n = 0; n < sample->length; n++)
				sample->left[n] = (int)(signed short)dumbfile_mgetw(f) << 8;
		else
			for (n = 0; n < sample->length; n++)
				sample->left[n] = (int)(signed short)dumbfile_igetw(f) << 8;
	} else
		for (n = 0; n < sample->length; n++)
			sample->left[n] = (int)(signed char)dumbfile_getc(f) << 16;

	if (dumbfile_error(f))
		return -1;

	if (!(convert & 1)) {
		/* Convert to signed. */
		for (n = 0; n < sample->length; n++)
			sample->left[n] ^= 0xFF800000;

		if (sample->right)
			for (n = 0; n < sample->length; n++)
				sample->right[n] ^= 0xFF800000;
	}

	/* NOT SUPPORTED:
	 *
	 * convert &  4 - Samples stored as delta values
	 * convert & 16 - Samples stored as TX-Wave 12-bit values
	 * convert & 32 - Left/Right/All Stereo prompt
	 */

	return 0;
}



#define DETECT_DUPLICATE_CHANNELS
#ifdef DETECT_DUPLICATE_CHANNELS
#include <stdio.h>
#endif
static int it_read_pattern(IT_PATTERN *pattern, DUMBFILE *f, unsigned char *buffer)
{
	unsigned char cmask[DUMB_IT_N_CHANNELS];
	unsigned char cnote[DUMB_IT_N_CHANNELS];
	unsigned char cinstrument[DUMB_IT_N_CHANNELS];
	unsigned char cvolpan[DUMB_IT_N_CHANNELS];
	unsigned char ceffect[DUMB_IT_N_CHANNELS];
	unsigned char ceffectvalue[DUMB_IT_N_CHANNELS];
#ifdef DETECT_DUPLICATE_CHANNELS
	IT_ENTRY *dupentry[DUMB_IT_N_CHANNELS];
#endif

	int n_entries = 0;
	int buflen;
	int bufpos = 0;

	IT_ENTRY *entry;

	unsigned char channel;
	unsigned char mask;

	memset(cmask, 0, sizeof(cmask));
	memset(cnote, 0, sizeof(cnote));
	memset(cinstrument, 0, sizeof(cinstrument));
	memset(cvolpan, 0, sizeof(cvolpan));
	memset(ceffect, 0, sizeof(ceffect));
	memset(ceffectvalue, 0, sizeof(ceffectvalue));
#ifdef DETECT_DUPLICATE_CHANNELS
	{
		int i;
		for (i = 0; i < DUMB_IT_N_CHANNELS; i++) dupentry[i] = NULL;
	}
#endif

	buflen = dumbfile_igetw(f);
	pattern->n_rows = dumbfile_igetw(f);

	/* Skip four unused bytes. */
	dumbfile_skip(f, 4);

	if (dumbfile_error(f))
		return -1;

	/* Read in the pattern data. */
	dumbfile_getnc((char *)buffer, buflen, f);

	if (dumbfile_error(f))
		return -1;

	/* Scan the pattern data, and work out how many entries we need room for. */
	while (bufpos < buflen) {
		unsigned char b = buffer[bufpos++];

		if (b == 0) {
			/* End of row */
			n_entries++;
			continue;
		}

		channel = (b - 1) & 63;

		if (b & 128)
			cmask[channel] = mask = buffer[bufpos++];
		else
			mask = cmask[channel];

		{
			static const unsigned char used[16] = {0, 1, 1, 2, 1, 2, 2, 3, 2, 3, 3, 4, 3, 4, 4, 5};
			n_entries += (mask != 0);
			bufpos += used[mask & 15];
		}
	}

	pattern->n_entries = n_entries;

	pattern->entry = malloc(n_entries * sizeof(*pattern->entry));

	if (!pattern->entry)
		return -1;

	bufpos = 0;
	memset(cmask, 0, sizeof(cmask));

	entry = pattern->entry;

	while (bufpos < buflen) {
		unsigned char b = buffer[bufpos++];

		if (b == 0) {
			/* End of row */
			IT_SET_END_ROW(entry);
			entry++;
#ifdef DETECT_DUPLICATE_CHANNELS
			{
				int i;
				for (i = 0; i < DUMB_IT_N_CHANNELS; i++) dupentry[i] = NULL;
			}
#endif
			continue;
		}

		channel = (b - 1) & 63;

		if (b & 128)
			cmask[channel] = mask = buffer[bufpos++];
		else
			mask = cmask[channel];

		if (mask) {
			entry->mask = (mask & 15) | (mask >> 4);
			entry->channel = channel;

			if (mask & IT_ENTRY_NOTE)
				cnote[channel] = entry->note = buffer[bufpos++];
			else if (mask & (IT_ENTRY_NOTE << 4))
				entry->note = cnote[channel];

			if (mask & IT_ENTRY_INSTRUMENT)
				cinstrument[channel] = entry->instrument = buffer[bufpos++];
			else if (mask & (IT_ENTRY_INSTRUMENT << 4))
				entry->instrument = cinstrument[channel];

			if (mask & IT_ENTRY_VOLPAN)
				cvolpan[channel] = entry->volpan = buffer[bufpos++];
			else if (mask & (IT_ENTRY_VOLPAN << 4))
				entry->volpan = cvolpan[channel];

			if (mask & IT_ENTRY_EFFECT) {
				ceffect[channel] = entry->effect = buffer[bufpos++];
				ceffectvalue[channel] = entry->effectvalue = buffer[bufpos++];
			} else {
				entry->effect = ceffect[channel];
				entry->effectvalue = ceffectvalue[channel];
			}

#if defined( DETECT_DUPLICATE_CHANNELS) && 0
			if (dupentry[channel]) {
				FILE *f = fopen("dupentry.txt", "a");
				if (!f) abort();
				fprintf(f, "Two events on channel %d:", channel);
				fprintf(f, "  Event #1:");
				if (dupentry[channel]->mask & IT_ENTRY_NOTE      ) fprintf(f, " %03d", dupentry[channel]->note      ); else fprintf(f, " ...");
				if (dupentry[channel]->mask & IT_ENTRY_INSTRUMENT) fprintf(f, " %03d", dupentry[channel]->instrument); else fprintf(f, " ...");
				if (dupentry[channel]->mask & IT_ENTRY_VOLPAN    ) fprintf(f, " %03d", dupentry[channel]->volpan    ); else fprintf(f, " ...");
				if (dupentry[channel]->mask & IT_ENTRY_EFFECT) fprintf(f, " %c%02X\n", 'A' - 1 + dupentry[channel]->effect, dupentry[channel]->effectvalue); else fprintf(f, " ...\n");
				fprintf(f, "  Event #2:");
				if (entry->mask & IT_ENTRY_NOTE      ) fprintf(f, " %03d", entry->note      ); else fprintf(f, " ...");
				if (entry->mask & IT_ENTRY_INSTRUMENT) fprintf(f, " %03d", entry->instrument); else fprintf(f, " ...");
				if (entry->mask & IT_ENTRY_VOLPAN    ) fprintf(f, " %03d", entry->volpan    ); else fprintf(f, " ...");
				if (entry->mask & IT_ENTRY_EFFECT) fprintf(f, " %c%02X\n", 'A' - 1 + entry->effect, entry->effectvalue); else fprintf(f, " ...\n");
				fclose(f);
			}
			dupentry[channel] = entry;
#endif

			entry++;
		}
	}

	ASSERT(entry == pattern->entry + n_entries);

	return 0;
}



/* Currently we assume the sample data are stored after the sample headers in
 * module files. This assumption may be unjustified; let me know if you have
 * trouble.
 */

#define IT_COMPONENT_INSTRUMENT 1
#define IT_COMPONENT_PATTERN    2
#define IT_COMPONENT_SAMPLE     3

typedef struct IT_COMPONENT
{
	unsigned char type;
	unsigned char n;
	long offset;
	short sampfirst; /* component[sampfirst] = first sample data after this */
	short sampnext; /* sampnext is used to create linked lists of sample data */
}
IT_COMPONENT;



static int it_component_compare(const void *e1, const void *e2)
{
	return ((const IT_COMPONENT *)e1)->offset -
	       ((const IT_COMPONENT *)e2)->offset;
}



static sigdata_t *it_load_sigdata(DUMBFILE *f)
{
	DUMB_IT_SIGDATA *sigdata;

	int cwt, cmwt;
	int special;

	IT_COMPONENT *component;
	int n_components = 0;

	unsigned char sample_convert[256];

	int n;

	unsigned char *buffer;

	if (dumbfile_mgetl(f) != IT_SIGNATURE)
		return NULL;

	sigdata = malloc(sizeof(*sigdata));

	if (!sigdata)
		return NULL;

	sigdata->order = NULL;
	sigdata->instrument = NULL;
	sigdata->sample = NULL;
	sigdata->pattern = NULL;
	sigdata->midi = NULL;
	sigdata->checkpoint = NULL;

	/* Skip song name and pattern row highlight info. */
	dumbfile_skip(f, 28);

	sigdata->n_orders = dumbfile_igetw(f);
	sigdata->n_instruments = dumbfile_igetw(f);
	sigdata->n_samples = dumbfile_igetw(f);
	sigdata->n_patterns = dumbfile_igetw(f);

	cwt = dumbfile_igetw(f);
	cmwt = dumbfile_igetw(f);

	sigdata->flags = dumbfile_igetw(f);
	special = dumbfile_igetw(f);

	sigdata->global_volume = dumbfile_getc(f);
	sigdata->mixing_volume = dumbfile_getc(f);
	sigdata->speed = dumbfile_getc(f);
	if (sigdata->speed == 0) sigdata->speed = 6; // Should we? What about tempo?
	sigdata->tempo = dumbfile_getc(f);
	sigdata->pan_separation = dumbfile_getc(f); /** WARNING: use this */

	/* Skip Pitch Wheel Depth, Message Length, Message Offset and Reserved. */
	dumbfile_skip(f, 11);

	dumbfile_getnc((char *)sigdata->channel_pan, DUMB_IT_N_CHANNELS, f);
	dumbfile_getnc((char *)sigdata->channel_volume, DUMB_IT_N_CHANNELS, f);

	if (dumbfile_error(f) || sigdata->n_orders <= 0 || sigdata->n_instruments > 256 || sigdata->n_samples > 256 || sigdata->n_patterns > 256) {
		_dumb_it_unload_sigdata(sigdata);
		return NULL;
	}

	sigdata->order = malloc(sigdata->n_orders);
	if (!sigdata->order) {
		_dumb_it_unload_sigdata(sigdata);
		return NULL;
	}

	if (sigdata->n_instruments) {
		sigdata->instrument = malloc(sigdata->n_instruments * sizeof(*sigdata->instrument));
		if (!sigdata->instrument) {
			_dumb_it_unload_sigdata(sigdata);
			return NULL;
		}
	}

	if (sigdata->n_samples) {
		sigdata->sample = malloc(sigdata->n_samples * sizeof(*sigdata->sample));
		if (!sigdata->sample) {
			_dumb_it_unload_sigdata(sigdata);
			return NULL;
		}
		for (n = 0; n < sigdata->n_samples; n++)
			sigdata->sample[n].right = sigdata->sample[n].left = NULL;
	}

	if (sigdata->n_patterns) {
		sigdata->pattern = malloc(sigdata->n_patterns * sizeof(*sigdata->pattern));
		if (!sigdata->pattern) {
			_dumb_it_unload_sigdata(sigdata);
			return NULL;
		}
		for (n = 0; n < sigdata->n_patterns; n++)
			sigdata->pattern[n].entry = NULL;
	}

	dumbfile_getnc((char *)sigdata->order, sigdata->n_orders, f);
	sigdata->restart_position = 0;

	component = malloc(768 * sizeof(*component));
	if (!component) {
		_dumb_it_unload_sigdata(sigdata);
		return NULL;
	}

	for (n = 0; n < sigdata->n_instruments; n++) {
		component[n_components].type = IT_COMPONENT_INSTRUMENT;
		component[n_components].n = n;
		component[n_components].offset = dumbfile_igetl(f);
		component[n_components].sampfirst = -1;
		n_components++;
	}

	for (n = 0; n < sigdata->n_samples; n++) {
		component[n_components].type = IT_COMPONENT_SAMPLE;
		component[n_components].n = n;
		component[n_components].offset = dumbfile_igetl(f);
		component[n_components].sampfirst = -1;
		n_components++;
	}

	for (n = 0; n < sigdata->n_patterns; n++) {
		long offset = dumbfile_igetl(f);
		if (offset) {
			component[n_components].type = IT_COMPONENT_PATTERN;
			component[n_components].n = n;
			component[n_components].offset = offset;
			component[n_components].sampfirst = -1;
			n_components++;
		} else {
			/* Empty 64-row pattern */
			sigdata->pattern[n].n_rows = 64;
			sigdata->pattern[n].n_entries = 0;
		}
	}

	if (dumbfile_error(f)) {
		free(component);
		_dumb_it_unload_sigdata(sigdata);
		return NULL;
	}

	if (!(sigdata->flags & 128) != !(special & 8)) {
#if 0
		fprintf(stderr, "Flags   Bit 7 (\"Request embedded MIDI configuration\"): %s\n", sigdata->flags & 128 ? "=SET=" : "clear");
		fprintf(stderr, "Special Bit 3     (\"MIDI configuration embedded\")    : %s\n", special        &   8 ? "=SET=" : "clear");
		fprintf(stderr, "entheh would like to investigate this IT file.\n");
		fprintf(stderr, "Please contact him! entheh@users.sf.net\n");
#endif
	}

	if (special & 8) {
		/* MIDI configuration is embedded. */
		unsigned char mididata[32];
		int i;
		sigdata->midi = malloc(sizeof(*sigdata->midi));
		if (!sigdata->midi) {
			free(component);
			_dumb_it_unload_sigdata(sigdata);
			return NULL;
			// Should we be happy with this outcome in some situations?
		}
		// What are we skipping?
		i = dumbfile_igetw(f);
		if (dumbfile_error(f) || dumbfile_skip(f, 8*i)) {
			free(component);
			_dumb_it_unload_sigdata(sigdata);
			return NULL;
		}
		/* Read embedded MIDI configuration */
		// What are the first 9 commands for?
		if (dumbfile_skip(f, 32*9)) {
			free(component);
			_dumb_it_unload_sigdata(sigdata);
			return NULL;
		}
		for (i = 0; i < 16; i++) {
			unsigned char len = 0;
			int j, leftdigit = -1;
			if (dumbfile_getnc((char *)mididata, 32, f) < 32) {
				free(component);
				_dumb_it_unload_sigdata(sigdata);
				return NULL;
			}
			sigdata->midi->SFmacroz[i] = 0;
			for (j = 0; j < 32; j++) {
				if (leftdigit >= 0) {
					if (mididata[j] == 0) {
						sigdata->midi->SFmacro[i][len++] = leftdigit;
						break;
					} else if (mididata[j] == ' ')
						sigdata->midi->SFmacro[i][len++] = leftdigit;
					else if (mididata[j] >= '0' && mididata[j] <= '9')
						sigdata->midi->SFmacro[i][len++] = (leftdigit << 4) | (mididata[j] - '0');
					else if (mididata[j] >= 'A' && mididata[j] <= 'F')
						sigdata->midi->SFmacro[i][len++] = (leftdigit << 4) | (mididata[j] - 'A' + 0xA);
					leftdigit = -1;
				} else if (mididata[j] == 0)