home *** CD-ROM | disk | FTP | other *** search
/ Large Pack of OldSkool DOS MOD Trackers / goattracker_2.72.zip / src / greloc.c < prev    next >
C/C++ Source or Header  |  2011-07-03  |  55KB  |  2,126 lines

  1. //
  2. // GOATTRACKER v2 packer/relocator
  3. //
  4.  
  5. #define GRELOC_C
  6.  
  7. #include "goattrk2.h"
  8. #include "membuf.h"
  9. #include "parse.h"
  10.  
  11. char *playeroptname[] =
  12. {
  13.   "Buffered SID-writes",
  14.   "Sound effect support",
  15.   "Volume change support",
  16.   "Store author-info",
  17.   "Use zeropage ghostregs",
  18.   "Disable optimization"
  19. };
  20.  
  21. char *tableleftname[] = {
  22.   "mt_wavetbl",
  23.   "mt_pulsetimetbl",
  24.   "mt_filttimetbl",
  25.   "mt_speedlefttbl"};
  26.  
  27. char *tablerightname[] = {
  28.   "mt_notetbl",
  29.   "mt_pulsespdtbl",
  30.   "mt_filtspdtbl",
  31.   "mt_speedrighttbl"};
  32.  
  33. unsigned char chnused[MAX_CHN];
  34. unsigned char pattused[MAX_PATT];
  35. unsigned char pattmap[MAX_PATT];
  36. unsigned char instrused[MAX_INSTR];
  37. unsigned char instrmap[MAX_INSTR];
  38. unsigned char tableused[MAX_TABLES][MAX_TABLELEN+1];
  39. unsigned char tablemap[MAX_TABLES][MAX_TABLELEN+1];
  40. int pattoffset[MAX_PATT];
  41. int pattsize[MAX_PATT];
  42. int songoffset[MAX_SONGS][MAX_CHN];
  43. int songsize[MAX_SONGS][MAX_CHN];
  44. int tableerror;
  45. int channels;
  46. int fixedparams;
  47. int simplepulse;
  48. int firstnote;
  49. int lastnote;
  50. int patternlastnote;
  51. int nofilter;
  52. int nofiltermod;
  53. int nopulse;
  54. int nopulsemod;
  55. int nowavedelay;
  56. int norepeat;
  57. int notrans;
  58. int noportamento;
  59. int notoneporta;
  60. int novib;
  61. int noinsvib;
  62. int nosetad;
  63. int nosetsr;
  64. int nosetwave;
  65. int nosetwaveptr;
  66. int nosetpulseptr;
  67. int nosetfiltptr;
  68. int nosetfiltcutoff;
  69. int nosetfiltctrl;
  70. int nosetmastervol;
  71. int nofunktempo;
  72. int noglobaltempo;
  73. int nochanneltempo;
  74. int nogate;
  75. int noeffects;
  76. int nowavecmd;
  77. int nofirstwavecmd;
  78. int nocalculatedspeed;
  79. int nonormalspeed;
  80. int nozerospeed;
  81.  
  82. struct membuf src = STATIC_MEMBUF_INIT;
  83. struct membuf dest = STATIC_MEMBUF_INIT;
  84.  
  85. void relocator(void)
  86. {
  87.   char packedsongname[MAX_FILENAME];
  88.   char packedfilter[MAX_FILENAME];
  89.   unsigned char *packeddata = NULL;
  90.   char *playername = "player.s";
  91.  
  92.   int tableerrortype = TYPE_NONE;
  93.   int tableerrorcause = CAUSE_NONE;
  94.   int tableerrorsource1 = 0;
  95.   int tableerrorsource2 = 0;
  96.   int patterns = 0;
  97.   int songs = 0;
  98.   int instruments = 0;
  99.   int numlegato = 0;
  100.   int numnohr = 0;
  101.   int numnormal = 0;
  102.   int freenormal;
  103.   int freenohr;
  104.   int freelegato;
  105.   int transuprange = 0;
  106.   int transdownrange = 0;
  107.   int pattdatasize = 0;
  108.   int patttblsize = 0;
  109.   int songdatasize = 0;
  110.   int songtblsize = 0;
  111.   int instrsize = 0;
  112.   int wavetblsize = 0;
  113.   int pulsetblsize = 0;
  114.   int filttblsize = 0;
  115.   int speedtblsize = 0;
  116.   int playersize = 0;
  117.   int packedsize = 0;
  118.  
  119.   FILE *songhandle = NULL;
  120.   int selectdone;
  121.   int opt = 0;
  122.   unsigned char speedcode[] = {0xa2,0x00,0x8e,0x04,0xdc,0xa2,0x00,0x8e,0x05,0xdc};
  123.  
  124.   int c,d,e;
  125.  
  126.   unsigned char patttemp[512];
  127.   unsigned char *songwork = NULL;
  128.   unsigned char *pattwork = NULL;
  129.   unsigned char *instrwork = NULL;
  130.  
  131.   channels = 3;
  132.   fixedparams = 1;
  133.   simplepulse = 1;
  134.   firstnote = MAX_NOTES-1;
  135.   lastnote = 0;
  136.   patternlastnote = 0;
  137.   noeffects = 1;
  138.   nogate = 1;
  139.   nofilter = 1;
  140.   nofiltermod = 1;
  141.   nopulse = 1;
  142.   nopulsemod = 1;
  143.   nowavedelay = 1;
  144.   nowavecmd = 1;
  145.   norepeat = 1;
  146.   notrans = 1;
  147.   noportamento = 1;
  148.   notoneporta = 1;
  149.   novib = 1;
  150.   noinsvib = 1;
  151.   nosetad = 1;
  152.   nosetsr = 1;
  153.   nosetwave = 1;
  154.   nosetwaveptr = 1;
  155.   nosetpulseptr = 1;
  156.   nosetfiltptr = 1;
  157.   nosetfiltcutoff = 1;
  158.   nosetfiltctrl = 1;
  159.   nosetmastervol = 1;
  160.   nofunktempo = 1;
  161.   noglobaltempo = 1;
  162.   nochanneltempo = 1;
  163.   nofirstwavecmd = 1;
  164.   nocalculatedspeed = 1;
  165.   nonormalspeed = 1;
  166.   nozerospeed = 1;
  167.  
  168.   stopsong();
  169.  
  170.   memset(pattused, 0, sizeof pattused);
  171.   memset(instrused, 0, sizeof instrused);
  172.   memset(chnused, 0, sizeof chnused);
  173.   memset(tableused, 0, sizeof tableused);
  174.   memset(tablemap, 0, sizeof tablemap);
  175.   tableerror = 0;
  176.  
  177.   membuf_free(&src);
  178.   membuf_free(&dest);
  179.  
  180.   // Process song-orderlists
  181.   countpatternlengths();
  182.   // Calculate amount of songs with nonzero length
  183.   for (c = 0; c < MAX_SONGS; c++)
  184.   {
  185.     if ((songlen[c][0]) &&
  186.         (songlen[c][1]) &&
  187.         (songlen[c][2]))
  188.     {
  189.       // See which patterns are used in this song
  190.       for (d = 0; d < MAX_CHN; d++)
  191.       {
  192.         songdatasize += songlen[c][d]+2;
  193.         for (e = 0; e < songlen[c][d]; e++)
  194.         {
  195.           if (songorder[c][d][e] < REPEAT)
  196.           {
  197.             int f;
  198.             int num = songorder[c][d][e];
  199.  
  200.             pattused[num] = 1;
  201.             for (f = 0; f < pattlen[num]; f++)
  202.             {
  203.               if ((pattern[num][f*4] != REST) || (pattern[num][f*4+1]) || (pattern[num][f*4+2]))
  204.                 chnused[d] = 1;
  205.             }
  206.           }
  207.           else
  208.           {
  209.             if (songorder[c][d][e] >= TRANSDOWN)
  210.             {
  211.               notrans = 0;
  212.               if (songorder[c][d][e] < TRANSUP)
  213.               {
  214.                 int newtransdownrange = -(songorder[c][d][e] - TRANSUP);
  215.                 if (newtransdownrange > transdownrange) transdownrange = newtransdownrange;
  216.               }
  217.               else
  218.               {
  219.                 int newtransuprange = songorder[c][d][e] - TRANSUP;
  220.                 if (newtransuprange > transuprange) transuprange = newtransuprange;
  221.               }
  222.             }
  223.             else norepeat = 0;
  224.           }
  225.         }
  226.         if (songorder[c][d][songlen[c][d]+1] >= songlen[c][d])
  227.         {
  228.           sprintf(textbuffer, "ILLEGAL SONG RESTART POSITION! (SUBTUNE %02X, CHANNEL %d)", c, d+1);
  229.           clearscreen();
  230.           printtextc(MAX_ROWS/2, 15, textbuffer);
  231.           fliptoscreen();
  232.           waitkeynoupdate();
  233.           goto PRCLEANUP;
  234.         }
  235.       }
  236.       songs++;
  237.     }
  238.   }
  239.  
  240.   // Optimize amount of used channels
  241.   if (!chnused[2])
  242.     channels = 2;
  243.   if ((!chnused[1]) && (!chnused[2]))
  244.     channels = 1;
  245.  
  246.   if (!songs)
  247.   {
  248.     clearscreen();
  249.     printtextc(MAX_ROWS/2, CTITLE, "NO SONGS, NO DATA TO SAVE!");
  250.     fliptoscreen();
  251.     waitkeynoupdate();
  252.     goto PRCLEANUP;
  253.   }
  254.  
  255.   // Build the pattern-mapping
  256.   // Instrument 1 is always used
  257.   instrused[1] = 1;
  258.   for (c = 0; c < MAX_PATT; c++)
  259.   {
  260.     if (pattused[c])
  261.     {
  262.       pattmap[c] = patterns;
  263.       patterns++;
  264.  
  265.       // See which instruments/tablecommands are used
  266.       for (d = 0; d < pattlen[c]; d++)
  267.       {
  268.         tableerror = 0;
  269.  
  270.         if ((pattern[c][d*4] == KEYOFF) || (pattern[c][d*4] == KEYON))
  271.           nogate = 0;
  272.         if (pattern[c][d*4+1])
  273.           instrused[pattern[c][d*4+1]] = 1;
  274.         if (pattern[c][d*4+2])
  275.           noeffects = 0;
  276.         if ((pattern[c][d*4+2] >= CMD_SETWAVEPTR) && (pattern[c][d*4+2] <= CMD_SETFILTERPTR))
  277.           exectable(pattern[c][d*4+2] - CMD_SETWAVEPTR, pattern[c][d*4+3]);
  278.         if ((pattern[c][d*4+2] >= CMD_PORTAUP) && (pattern[c][d*4+2] <= CMD_VIBRATO))
  279.         {
  280.           exectable(STBL, pattern[c][d*4+3]);
  281.           calcspeedtest(pattern[c][d*4+3]);
  282.         }
  283.         if (pattern[c][d*4+2] == CMD_FUNKTEMPO)
  284.           exectable(STBL, pattern[c][d*4+3]);
  285.         if (pattern[c][d*4+2] == CMD_FUNKTEMPO)
  286.         {
  287.           nofunktempo = 0;
  288.           noglobaltempo = 0;
  289.         }
  290.         if ((pattern[c][d*4+2] == CMD_SETTEMPO) && ((pattern[c][d*4+3] & 0x7f) < 3)) nofunktempo = 0;
  291.  
  292.         // See, which are the highest/lowest notes used
  293.         if ((pattern[c][d*4] >= FIRSTNOTE) && (pattern[c][d*4] <= LASTNOTE))
  294.         {
  295.           int newfirstnote = pattern[c][d*4] - FIRSTNOTE - transdownrange;
  296.           int newlastnote = pattern[c][d*4] - FIRSTNOTE + transuprange;
  297.           if (newfirstnote < 0) newfirstnote = 0;
  298.           if (newlastnote > MAX_NOTES-1) newlastnote = MAX_NOTES-1;
  299.  
  300.           if (newfirstnote < firstnote) firstnote = newfirstnote;
  301.           if (newlastnote > lastnote)
  302.           {
  303.             patternlastnote = newlastnote;
  304.             lastnote = newlastnote;
  305.           }
  306.           if (newfirstnote > lastnote)
  307.           {
  308.             patternlastnote = newfirstnote;
  309.             lastnote = newfirstnote;
  310.           }
  311.         }
  312.         if ((tableerror) && (!tableerrortype))
  313.         {
  314.           tableerrortype = tableerror;
  315.           tableerrorcause = CAUSE_PATTERN;
  316.           tableerrorsource1 = c;
  317.           tableerrorsource2 = d;
  318.         }
  319.       }
  320.     }
  321.   }
  322.  
  323.   // Count amount of normal, nohr, and legato instruments
  324.   // Also see if special first wave parameters are used
  325.   for (c = 0; c < MAX_INSTR; c++)
  326.   {
  327.     if (instrused[c])
  328.     {
  329.       if (instr[c].gatetimer & 0x40) numlegato++;
  330.       else
  331.       {
  332.         if (instr[c].gatetimer & 0x80) numnohr++;
  333.         else numnormal++;
  334.       }
  335.       if ((!instr[c].firstwave) || (instr[c].firstwave >= 0xfe))
  336.         nofirstwavecmd = 0;
  337.     }
  338.   }
  339.   freenormal = 1;
  340.   freenohr = freenormal + numnormal;
  341.   freelegato = freenohr + numnohr;
  342.  
  343.   // Build the instrument-mapping
  344.   for (c = 0; c < MAX_INSTR; c++)
  345.   {
  346.     if (instrused[c])
  347.     {
  348.       if (instr[c].gatetimer & 0x40) instrmap[c] = freelegato++;
  349.       else
  350.       {
  351.         if (instr[c].gatetimer & 0x80) instrmap[c] = freenohr++;
  352.         else instrmap[c] = freenormal++;
  353.       }
  354.       instruments++;
  355.       for (d = 0; d < MAX_TABLES; d++)
  356.       {
  357.         tableerror = 0;
  358.         exectable(d, instr[c].ptr[d]);
  359.         if (d == STBL) calcspeedtest(instr[c].ptr[d]);
  360.         if ((tableerror) && (!tableerrortype))
  361.         {
  362.           tableerrortype = tableerror;
  363.           tableerrorcause = CAUSE_INSTRUMENT;
  364.           tableerrorsource1 = c;
  365.           tableerrorsource2 = d;
  366.         }
  367.       }
  368.     }
  369.   }
  370.  
  371.   // Execute tableprograms invoked from wavetable commands
  372.   for (c = 0; c < MAX_TABLELEN; c++)
  373.   {
  374.     if (tableused[WTBL][c+1])
  375.     {
  376.       if ((ltable[WTBL][c] >= WAVECMD) && (ltable[WTBL][c] <= WAVELASTCMD))
  377.       {
  378.         d = -1;
  379.         tableerror = 0;
  380.  
  381.         switch(ltable[WTBL][c] - WAVECMD)
  382.         {
  383.           case CMD_PORTAUP:
  384.           case CMD_PORTADOWN:
  385.           case CMD_TONEPORTA:
  386.           case CMD_VIBRATO:
  387.           d = STBL;
  388.           calcspeedtest(rtable[WTBL][c]);
  389.           break;
  390.  
  391.           case CMD_SETPULSEPTR:
  392.           d = PTBL;
  393.           nopulse = 0;
  394.            break;
  395.            
  396.            case CMD_SETFILTERPTR:
  397.            d = FTBL;
  398.           nofilter = 0;
  399.           break;
  400.  
  401.           case CMD_DONOTHING:
  402.           case CMD_SETWAVEPTR:
  403.           case CMD_FUNKTEMPO:
  404.           sprintf(textbuffer, "ILLEGAL WAVETABLE COMMAND (ROW %02X, COMMAND %X)", c+1, ltable[WTBL][c] - WAVECMD);
  405.           clearscreen();
  406.           printtextc(MAX_ROWS/2, 15, textbuffer);
  407.           fliptoscreen();
  408.           waitkeynoupdate();
  409.           goto PRCLEANUP;
  410.         }
  411.  
  412.         if (d != -1) exectable(d, rtable[WTBL][c]);
  413.  
  414.         if ((tableerror) && (!tableerrortype))
  415.         {
  416.           tableerrortype = tableerror;
  417.           tableerrorcause = CAUSE_WAVECMD;
  418.           tableerrorsource1 = c+1;
  419.           tableerrorsource2 = d;
  420.         }
  421.       }
  422.     }
  423.   }
  424.  
  425.   // Build the table-mapping
  426.   for (c = 0; c < MAX_TABLES; c++)
  427.   {
  428.     int e = 1;
  429.     for (d = 0; d < MAX_TABLELEN; d++)
  430.     {
  431.       if (tableused[c][d+1])
  432.       {
  433.         tablemap[c][d+1] = e;
  434.         e++;
  435.       }
  436.     }
  437.   }
  438.  
  439.   // Check for table errors
  440.   if (tableerrorcause)
  441.   {
  442.     clearscreen();
  443.     switch(tableerrortype)
  444.     {
  445.       case TYPE_JUMP:
  446.       sprintf(textbuffer, "TABLE POINTER POINTS TO A JUMP! ");
  447.       break;
  448.  
  449.       case TYPE_OVERFLOW:
  450.       sprintf(textbuffer, "TABLE EXECUTION OVERFLOWS! ");
  451.       break;
  452.     }
  453.     switch (tableerrorcause)
  454.     {
  455.       case CAUSE_PATTERN:
  456.       sprintf(textbuffer + strlen(textbuffer), "(PATTERN %02X, ROW %02d)", tableerrorsource1, tableerrorsource2);
  457.       break;
  458.  
  459.       case CAUSE_WAVECMD:
  460.       sprintf(textbuffer + strlen(textbuffer), "WAVETABLE CMD (ROW %02X, ", tableerrorsource1);
  461.       goto TABLETYPE;
  462.  
  463.       case CAUSE_INSTRUMENT:
  464.       sprintf(textbuffer + strlen(textbuffer), "(INSTRUMENT %02X, ", tableerrorsource1);
  465.       TABLETYPE:
  466.       switch (tableerrorsource2)
  467.       {
  468.         case WTBL:
  469.         strcat(textbuffer, "WAVE");
  470.         break;
  471.  
  472.         case PTBL:
  473.         strcat(textbuffer, "PULSE");
  474.         break;
  475.  
  476.         case FTBL:
  477.         strcat(textbuffer, "FILTER");
  478.         break;
  479.       }
  480.       strcat(textbuffer, ")");
  481.       break;
  482.     }
  483.     printtextc(MAX_ROWS/2, 15, textbuffer);
  484.  
  485.     fliptoscreen();
  486.     waitkeynoupdate();
  487.     goto PRCLEANUP;
  488.   }
  489.  
  490.   // Find duplicate ranges in tables
  491.   for (c = 0; c < MAX_TABLES; c++)
  492.     findtableduplicates(c);
  493.  
  494.   // Select playroutine options
  495.   clearscreen();
  496.   printblankc(0, 0, 15+16, MAX_COLUMNS);
  497.   if (!strlen(loadedsongfilename))
  498.     sprintf(textbuffer, "%s Packer/Relocator", programname);
  499.   else
  500.     sprintf(textbuffer, "%s Packer/Relocator - %s", programname, loadedsongfilename);
  501.   textbuffer[MAX_COLUMNS] = 0;
  502.   printtext(0, 0, 15+16, textbuffer);
  503.   printtext(1, 2, CTITLE, "SELECT PLAYROUTINE OPTIONS: (CURSORS=MOVE/CHANGE, ENTER=ACCEPT, ESC=CANCEL)");
  504.   selectdone = 0;
  505.   while (!selectdone)
  506.   {
  507.     for (c = 0; c < MAX_OPTIONS; c++)
  508.     {
  509.       int color = CNORMAL;
  510.       if (opt == c) color = CEDIT;
  511.  
  512.       printtext(1, 3+c, color, playeroptname[c]);
  513.       if (playerversion & (PLAYER_BUFFERED << c))
  514.         printtext(24, 3+c, color, "Yes");
  515.       else
  516.         printtext(24, 3+c, color, "No ");
  517.     }
  518.     fliptoscreen();
  519.     waitkeynoupdate();
  520.  
  521.     if (win_quitted)
  522.     {
  523.       exitprogram = 1;
  524.       goto PRCLEANUP;
  525.     }
  526.  
  527.     switch(rawkey)
  528.     {
  529.       case KEY_LEFT:
  530.       case KEY_RIGHT:
  531.       case KEY_SPACE:
  532.       playerversion ^= (PLAYER_BUFFERED << opt);
  533.       if (opt)
  534.       {
  535.         if ((playerversion & PLAYER_SOUNDEFFECTS) || (playerversion & PLAYER_ZPGHOSTREGS))
  536.           playerversion |= PLAYER_BUFFERED;
  537.       }
  538.       else
  539.       {
  540.         if (!(playerversion & PLAYER_BUFFERED))
  541.         {
  542.           playerversion &= ~PLAYER_SOUNDEFFECTS;
  543.           playerversion &= ~PLAYER_ZPGHOSTREGS;
  544.         }
  545.       }
  546.       break;
  547.  
  548.       case KEY_UP:
  549.       opt--;
  550.       if (opt < 0) opt = MAX_OPTIONS-1;
  551.       break;
  552.  
  553.       case KEY_DOWN:
  554.       opt++;
  555.       if (opt >= MAX_OPTIONS) opt = 0;
  556.       break;
  557.  
  558.       case KEY_ESC:
  559.       selectdone = -1;
  560.       break;
  561.  
  562.       case KEY_ENTER:
  563.       selectdone = 1;
  564.       break;
  565.     }
  566.   }
  567.   if (selectdone == -1) goto PRCLEANUP;
  568.  
  569.   // Disable optimizations if necessary
  570.   if (playerversion & PLAYER_NOOPTIMIZATION)
  571.   {
  572.     fixedparams = 0;
  573.     if (!numlegato) numlegato++;
  574.  
  575.     simplepulse = 0;
  576.     firstnote = 0;
  577.     lastnote = MAX_NOTES-1;
  578.     nogate = 0;
  579.     noeffects = 0;
  580.     nofilter = 0;
  581.     nofiltermod = 0;
  582.     nopulse = 0;
  583.     nopulsemod = 0;
  584.     nowavedelay = 0;
  585.     nowavecmd = 0;
  586.     norepeat = 0;
  587.     notrans = 0;
  588.     noportamento = 0;
  589.     notoneporta = 0;
  590.     novib = 0;
  591.     noinsvib = 0;
  592.     nosetad = 0;
  593.     nosetsr = 0;
  594.     nosetwave = 0;
  595.     nosetwaveptr = 0;
  596.     nosetpulseptr = 0;
  597.     nosetfiltptr = 0;
  598.     nosetfiltcutoff = 0;
  599.     nosetfiltctrl = 0;
  600.     nosetmastervol = 0;
  601.     nofunktempo = 0;
  602.     noglobaltempo = 0;
  603.     nochanneltempo = 0;
  604.     nofirstwavecmd = 0;
  605.     nocalculatedspeed = 0;
  606.     nonormalspeed = 0;
  607.     nozerospeed = 0;
  608.   }
  609.  
  610.   // Make sure buffering is used if it is needed
  611.   if ((playerversion & PLAYER_SOUNDEFFECTS) || (playerversion & PLAYER_ZPGHOSTREGS))
  612.     playerversion |= PLAYER_BUFFERED;
  613.  
  614.   // Sound effect or ghostreg players always use full 3 channels
  615.   if ((playerversion & PLAYER_SOUNDEFFECTS) || (playerversion & PLAYER_ZPGHOSTREGS))
  616.     channels = 3;
  617.  
  618.   // Allocate memory for song-orderlists
  619.   songtblsize = songs*6;
  620.   songwork = malloc(songdatasize);
  621.   if (!songwork)
  622.   {
  623.     clearscreen();
  624.     printtextc(MAX_ROWS/2, CTITLE, "OUT OF MEMORY IN PACKER/RELOCATOR!");
  625.     fliptoscreen();
  626.     waitkeynoupdate();
  627.     goto PRCLEANUP;
  628.   }
  629.  
  630.   // Generate songorderlists & songtable
  631.   songdatasize = 0;
  632.   for (c = 0; c < songs; c++)
  633.   {
  634.     if ((songlen[c][0]) &&
  635.         (songlen[c][1]) &&
  636.         (songlen[c][2]))
  637.     {
  638.       for (d = 0; d < MAX_CHN; d++)
  639.       {
  640.         songoffset[c][d] = songdatasize;
  641.         songsize[c][d] = songlen[c][d] + 2;
  642.  
  643.         for (e = 0; e < songlen[c][d]; e++)
  644.         {
  645.           // Pattern
  646.           if (songorder[c][d][e] < REPEAT)
  647.             songwork[songdatasize++] = pattmap[songorder[c][d][e]];
  648.           else
  649.           {
  650.             // Transpose
  651.             if (songorder[c][d][e] >= TRANSDOWN)
  652.             {
  653.               songwork[songdatasize++] = songorder[c][d][e];
  654.             }
  655.             // Repeat sequence: must be swapped
  656.             else
  657.             {
  658.               // See that repeat amount is more than 1
  659.               if (songorder[c][d][e] > REPEAT)
  660.               {
  661.                 // Insanity check that a pattern indeed follows
  662.                 if (songorder[c][d][e+1] < REPEAT)
  663.                 {
  664.                   songwork[songdatasize++] = pattmap[songorder[c][d][e+1]];
  665.                   songwork[songdatasize++] = songorder[c][d][e];
  666.                   e++;
  667.                 }
  668.                 else
  669.                   songwork[songdatasize++] = songorder[c][d][e];
  670.               }
  671.             }
  672.           }
  673.         }
  674.         // Endmark & repeat position
  675.         songwork[songdatasize++] = songorder[c][d][e++];
  676.         songwork[songdatasize++] = songorder[c][d][e++];
  677.       }
  678.     }
  679.     else
  680.     {
  681.       for (d = 0; d < MAX_CHN; d++)
  682.       {
  683.         songoffset[c][d] = songdatasize;
  684.         songsize[c][d] = 0;
  685.       }
  686.     }
  687.   }
  688.  
  689.   // Calculate total size of patterns
  690.   for (c = 0; c < MAX_PATT; c++)
  691.   {
  692.     if (pattused[c])
  693.     {
  694.       int result = packpattern(patttemp, pattern[c], pattlen[c]);
  695.  
  696.       if (result < 0)
  697.       {
  698.         clearscreen();
  699.         sprintf(textbuffer, "PATTERN %02X IS TOO COMPLEX (OVER 256 BYTES PACKED)!", c);
  700.         printtextc(MAX_ROWS/2, 15, textbuffer);
  701.         fliptoscreen();
  702.         waitkeynoupdate();
  703.         goto PRCLEANUP;
  704.       }
  705.       pattdatasize += result;
  706.     }
  707.   }
  708.  
  709.   patttblsize = patterns*2;
  710.   pattwork = malloc(pattdatasize);
  711.   if (!pattwork)
  712.   {
  713.     clearscreen();
  714.     printtextc(MAX_ROWS/2, CTITLE, "OUT OF MEMORY IN PACKER/RELOCATOR!");
  715.     fliptoscreen();
  716.     waitkeynoupdate();
  717.     goto PRCLEANUP;
  718.   }
  719.  
  720.   // This time pack the patterns for real
  721.   pattdatasize = 0;
  722.   d = 0;
  723.   for (c = 0; c < MAX_PATT; c++)
  724.   {
  725.     if (pattused[c])
  726.     {
  727.       pattoffset[d] = pattdatasize;
  728.       pattsize[d] = packpattern(&pattwork[pattdatasize], pattern[c], pattlen[c]);
  729.       pattdatasize += pattsize[d];
  730.       d++;
  731.     }
  732.   }
  733.  
  734.   // Then process instruments
  735.   instrsize = instruments*9;
  736.   instrwork = malloc(instrsize);
  737.   if (!instrwork)
  738.   {
  739.     clearscreen();
  740.     printtextc(MAX_ROWS/2, CTITLE, "OUT OF MEMORY IN PACKER/RELOCATOR!");
  741.     fliptoscreen();
  742.     waitkeynoupdate();
  743.     goto PRCLEANUP;
  744.   }
  745.  
  746.   for (c = 1; c < MAX_INSTR; c++)
  747.   {
  748.     if (instrused[c])
  749.     {
  750.       d = instrmap[c] - 1;
  751.       instrwork[d] = instr[c].ad;
  752.       instrwork[d+instruments] = instr[c].sr;
  753.       instrwork[d+instruments*2] = tablemap[WTBL][instr[c].ptr[WTBL]];
  754.       instrwork[d+instruments*3] = tablemap[PTBL][instr[c].ptr[PTBL]];
  755.       instrwork[d+instruments*4] = tablemap[FTBL][instr[c].ptr[FTBL]];
  756.       if (instr[c].vibdelay)
  757.       {
  758.         instrwork[d+instruments*5] = tablemap[STBL][instr[c].ptr[STBL]];
  759.         instrwork[d+instruments*6] = instr[c].vibdelay - 1;
  760.       }
  761.       else
  762.       {
  763.         instrwork[d+instruments*5] = 0;
  764.         instrwork[d+instruments*6] = 0;
  765.       }
  766.       instrwork[d+instruments*7] = instr[c].gatetimer & 0x3f;
  767.       instrwork[d+instruments*8] = instr[c].firstwave;
  768.  
  769.       if (instr[c].ptr[STBL])
  770.       {
  771.         novib = 0;
  772.         noinsvib = 0;
  773.       }
  774.       if (instr[c].ptr[PTBL])
  775.         nopulse = 0;
  776.       if (instr[c].ptr[FTBL])
  777.         nofilter = 0;
  778.  
  779.       // See if all instruments use same gatetimer & firstwave parameters
  780.       if ((instr[c].gatetimer != instr[1].gatetimer) ||
  781.           (instr[c].firstwave != instr[1].firstwave))
  782.         fixedparams = 0;
  783.       // or if special firstwave commands are in use
  784.       if ((!instr[c].firstwave) || (instr[c].firstwave >= 0xfe))
  785.         fixedparams = 0;
  786.     }
  787.   }
  788.  
  789.   // Disable sameparam optimization for multispeed stability
  790.   if (multiplier > 1)
  791.   {
  792.     fixedparams = 0;
  793.     numlegato++;
  794.     numnohr++;
  795.   }
  796.  
  797.   if (fixedparams) instrsize -= instruments*2;
  798.   if (noinsvib) instrsize -= instruments*2;
  799.   if (nopulse) instrsize -= instruments;
  800.   if (nofilter) instrsize -= instruments;
  801.  
  802.   // Process tables
  803.   for (c = 0; c < MAX_TABLELEN; c++)
  804.   {
  805.     if (tableused[WTBL][c+1])
  806.     {
  807.       wavetblsize += 2;
  808.       if ((ltable[WTBL][c] >= WAVEDELAY) && (ltable[WTBL][c] <= WAVELASTDELAY)) nowavedelay = 0;
  809.       if ((ltable[WTBL][c] >= WAVECMD) && (ltable[WTBL][c] <= WAVELASTCMD))
  810.       {
  811.         nowavecmd = 0;
  812.         noeffects = 0;
  813.         switch (ltable[WTBL][c] - WAVECMD)
  814.         {
  815.           case CMD_PORTAUP:
  816.           case CMD_PORTADOWN:
  817.           noportamento = 0;
  818.           break;
  819.  
  820.           case CMD_TONEPORTA:
  821.           notoneporta = 0;
  822.           break;
  823.  
  824.           case CMD_VIBRATO:
  825.           novib = 0;
  826.           break;
  827.  
  828.           case CMD_SETAD:
  829.           nosetad = 0;
  830.           break;
  831.  
  832.           case CMD_SETSR:
  833.           nosetsr = 0;
  834.           break;
  835.  
  836.           case CMD_SETWAVE:
  837.           nosetwave = 0;
  838.           break;
  839.  
  840.           case CMD_SETPULSEPTR:
  841.           nosetpulseptr = 0;
  842.           break;
  843.  
  844.           case CMD_SETFILTERPTR:
  845.           nosetfiltptr = 0;
  846.           break;
  847.  
  848.           case CMD_SETFILTERCUTOFF:
  849.           nosetfiltcutoff = 0;
  850.           break;
  851.  
  852.           case CMD_SETFILTERCTRL:
  853.           nosetfiltctrl = 0;
  854.           break;
  855.  
  856.           case CMD_SETMASTERVOL:
  857.           nosetmastervol = 0;
  858.           break;
  859.         }
  860.       }
  861.       if (ltable[WTBL][c] < WAVECMD)
  862.       {
  863.         if (rtable[WTBL][c] <= 0x80)
  864.         {
  865.           int newlastnote = rtable[WTBL][c] + patternlastnote;
  866.           if (newlastnote > MAX_NOTES - 1) newlastnote = MAX_NOTES - 1;
  867.           if (rtable[WTBL][c] >= 0x20) firstnote = 0;
  868.            if (newlastnote > lastnote) lastnote = newlastnote;
  869.         }
  870.         else
  871.         {
  872.           int newfirstnote = rtable[WTBL][c] & 0x7f;
  873.           int newlastnote = rtable[WTBL][c] & 0x7f;
  874.           if (newlastnote > MAX_NOTES - 1) newlastnote = MAX_NOTES - 1;
  875.           if (newfirstnote < firstnote) firstnote = newfirstnote;
  876.           if (newlastnote > lastnote) lastnote = newlastnote;
  877.         }
  878.       }
  879.     }
  880.   }
  881.   for (c = 0; c < MAX_TABLELEN; c++)
  882.   {
  883.     if (tableused[PTBL][c+1])
  884.     {
  885.       pulsetblsize += 2;
  886.       if ((ltable[PTBL][c] >= 0x80) && (ltable[PTBL][c] != 0xff))
  887.       {
  888.         if (rtable[PTBL][c] & 0xf) simplepulse = 0;
  889.       }
  890.       if (ltable[PTBL][c] < 0x80)
  891.       {
  892.         nopulsemod = 0;
  893.         if (rtable[PTBL][c] & 0xf) simplepulse = 0;
  894.       }
  895.     }
  896.   }
  897.   for (c = 0; c < MAX_TABLELEN; c++)
  898.   {
  899.     if (tableused[FTBL][c+1])
  900.     {
  901.       filttblsize += 2;
  902.       if (ltable[FTBL][c] < 0x80) nofiltermod = 0;
  903.     }
  904.   }
  905.   for (c = 0; c < MAX_TABLELEN; c++)
  906.   {
  907.     if (tableused[STBL][c+1]) speedtblsize += 2;
  908.   }
  909.   // Zero entry of speedtable
  910.   if ((!novib) || (!nofunktempo) || (!noportamento) || (!notoneporta))
  911.     speedtblsize += 2;
  912.  
  913.   if (nopulse) pulsetblsize = 0;
  914.   if (nofilter) filttblsize = 0;
  915.  
  916.   sprintf(textbuffer, "SELECT START ADDRESS: (CURSORS=MOVE, ENTER=ACCEPT, ESC=CANCEL)");
  917.   printtext(1, 10, 15, textbuffer);
  918.  
  919.   selectdone = 0;
  920.   while (!selectdone)
  921.   {
  922.     sprintf(textbuffer, "$%04X", playeradr);
  923.     printtext(1, 11, 10, textbuffer);
  924.  
  925.     fliptoscreen();
  926.     waitkeynoupdate();
  927.  
  928.     if (win_quitted)
  929.     {
  930.       exitprogram = 1;
  931.       goto PRCLEANUP;
  932.     }
  933.  
  934.     switch(rawkey)
  935.     {
  936.       case KEY_LEFT:
  937.       playeradr -= 0x0400;
  938.       playeradr &= 0xff00;
  939.       break;
  940.  
  941.       case KEY_UP:
  942.       playeradr += 0x0100;
  943.       playeradr &= 0xff00;
  944.       break;
  945.  
  946.       case KEY_RIGHT:
  947.       playeradr += 0x0400;
  948.       playeradr &= 0xff00;
  949.       break;
  950.  
  951.       case KEY_DOWN:
  952.       playeradr -= 0x0100;
  953.       playeradr &= 0xff00;
  954.       break;
  955.  
  956.       case KEY_ESC:
  957.       selectdone = -1;
  958.       break;
  959.  
  960.       case KEY_ENTER:
  961.       selectdone = 1;
  962.       break;
  963.     }
  964.   }
  965.  
  966.   if (selectdone == -1) goto PRCLEANUP;
  967.  
  968.   sprintf(textbuffer, "SELECT ZEROPAGE ADDRESS: (CURSORS=MOVE, ENTER=ACCEPT, ESC=CANCEL)");
  969.   printtext(1, 13, 15, textbuffer);
  970.  
  971.   selectdone = 0;
  972.   while (!selectdone)
  973.   {
  974.     if (playerversion & PLAYER_ZPGHOSTREGS)
  975.     {
  976.       if (zeropageadr < 0x02) zeropageadr = 0xe5;
  977.       if (zeropageadr > 0xe5) zeropageadr = 0x02;
  978.     }
  979.     else
  980.     {
  981.       if (zeropageadr < 0x02) zeropageadr = 0xfe;
  982.       if (zeropageadr > 0xfe) zeropageadr = 0x02;
  983.     }
  984.  
  985.     if (!(playerversion & PLAYER_ZPGHOSTREGS))
  986.     {
  987.       if (zeropageadr < 0x90)
  988.         sprintf(textbuffer, "$%02X-$%02X (Used by BASIC interpreter)    ", zeropageadr, zeropageadr+1);
  989.       if ((zeropageadr >= 0x90) && (zeropageadr < 0xfb))
  990.         sprintf(textbuffer, "$%02X-$%02X (Used by KERNAL routines)      ", zeropageadr, zeropageadr+1);
  991.       if ((zeropageadr >= 0xfb) && (zeropageadr < 0xfe))
  992.         sprintf(textbuffer, "$%02X-$%02X (Unused)                       ", zeropageadr, zeropageadr+1);
  993.       if (zeropageadr >= 0xfe)
  994.         sprintf(textbuffer, "$%02X-$%02X ($FF used by BASIC interpreter)", zeropageadr, zeropageadr+1);
  995.     }
  996.     else
  997.     {
  998.       sprintf(textbuffer, "$%02X-$%02X (ghostregs start at %02X)", zeropageadr, zeropageadr+26, zeropageadr);
  999.     }
  1000.  
  1001.     printtext(1, 14, 10, textbuffer);
  1002.  
  1003.     fliptoscreen();
  1004.     waitkeynoupdate();
  1005.  
  1006.     if (win_quitted)
  1007.     {
  1008.       exitprogram = 1;
  1009.       goto PRCLEANUP;
  1010.     }
  1011.  
  1012.     switch(rawkey)
  1013.     {
  1014.       case KEY_LEFT:
  1015.       zeropageadr -= 0x10;
  1016.       break;
  1017.  
  1018.       case KEY_UP:
  1019.       zeropageadr++;
  1020.       break;
  1021.  
  1022.       case KEY_RIGHT:
  1023.       zeropageadr += 0x10;
  1024.       break;
  1025.  
  1026.       case KEY_DOWN:
  1027.       zeropageadr--;
  1028.       break;
  1029.  
  1030.       case KEY_ESC:
  1031.       selectdone = -1;
  1032.       break;
  1033.  
  1034.       case KEY_ENTER:
  1035.       selectdone = 1;
  1036.       break;
  1037.     }
  1038.   }
  1039.  
  1040.   if (selectdone == -1) goto PRCLEANUP;
  1041.  
  1042.   // Validate frequencytable parameters
  1043.   if (lastnote < firstnote)
  1044.     lastnote = firstnote;
  1045.   if (firstnote < 0) firstnote = 0;
  1046.   if (!nocalculatedspeed)
  1047.     lastnote++; // Calculated speeds need the next frequency value
  1048.   if (lastnote > MAX_NOTES-1) lastnote = MAX_NOTES-1;
  1049.   // For sound effect support, always use the full table
  1050.   if (playerversion & PLAYER_SOUNDEFFECTS)
  1051.   {
  1052.     firstnote = 0;
  1053.     lastnote = MAX_NOTES-1;
  1054.   }
  1055.  
  1056.   // Insert baseaddresses
  1057.   insertdefine("base", playeradr);
  1058.   insertdefine("zpbase", zeropageadr);
  1059.   insertdefine("SIDBASE", sidaddress);
  1060.  
  1061.   // Insert conditionals
  1062.   insertdefine("SOUNDSUPPORT", (playerversion & PLAYER_SOUNDEFFECTS) ? 1 : 0);
  1063.   insertdefine("VOLSUPPORT", (playerversion & PLAYER_VOLUME) ? 1 : 0);
  1064.   insertdefine("BUFFEREDWRITES", (playerversion & PLAYER_BUFFERED) ? 1 : 0);
  1065.   insertdefine("ZPGHOSTREGS", (playerversion & PLAYER_ZPGHOSTREGS) ? 1 : 0);
  1066.   insertdefine("FIXEDPARAMS", fixedparams);
  1067.   insertdefine("SIMPLEPULSE", simplepulse);
  1068.   insertdefine("PULSEOPTIMIZATION", optimizepulse);
  1069.   insertdefine("REALTIMEOPTIMIZATION", optimizerealtime);
  1070.   insertdefine("NOAUTHORINFO", (playerversion & PLAYER_AUTHORINFO) ? 0 : 1);
  1071.   insertdefine("NOEFFECTS", noeffects);
  1072.   insertdefine("NOGATE", nogate);
  1073.   insertdefine("NOFILTER", nofilter);
  1074.   insertdefine("NOFILTERMOD", nofiltermod);
  1075.   insertdefine("NOPULSE", nopulse);
  1076.   insertdefine("NOPULSEMOD", nopulsemod);
  1077.   insertdefine("NOWAVEDELAY", nowavedelay);
  1078.   insertdefine("NOWAVECMD", nowavecmd);
  1079.   insertdefine("NOREPEAT", norepeat);
  1080.   insertdefine("NOTRANS", notrans);
  1081.   insertdefine("NOPORTAMENTO", noportamento);
  1082.   insertdefine("NOTONEPORTA", notoneporta);
  1083.   insertdefine("NOVIB", novib);
  1084.   insertdefine("NOINSTRVIB", noinsvib);
  1085.   insertdefine("NOSETAD", nosetad);
  1086.   insertdefine("NOSETSR", nosetsr);
  1087.   insertdefine("NOSETWAVE", nosetwave);
  1088.   insertdefine("NOSETWAVEPTR", nosetwaveptr);
  1089.   insertdefine("NOSETPULSEPTR", nosetpulseptr);
  1090.   insertdefine("NOSETFILTPTR", nosetfiltptr);
  1091.   insertdefine("NOSETFILTCTRL", nosetfiltctrl);
  1092.   insertdefine("NOSETFILTCUTOFF", nosetfiltcutoff);
  1093.   insertdefine("NOSETMASTERVOL", nosetmastervol);
  1094.   insertdefine("NOFUNKTEMPO", nofunktempo);
  1095.   insertdefine("NOGLOBALTEMPO", noglobaltempo);
  1096.   insertdefine("NOCHANNELTEMPO", nochanneltempo);
  1097.   insertdefine("NOFIRSTWAVECMD", nofirstwavecmd);
  1098.   insertdefine("NOCALCULATEDSPEED", nocalculatedspeed);
  1099.   insertdefine("NONORMALSPEED", nonormalspeed);
  1100.   insertdefine("NOZEROSPEED", nozerospeed);
  1101.  
  1102.   // Insert parameters
  1103.   insertdefine("NUMCHANNELS", channels);
  1104.   insertdefine("NUMSONGS", songs);
  1105.   insertdefine("FIRSTNOTE", firstnote);
  1106.   insertdefine("FIRSTNOHRINSTR", numnormal + 1);
  1107.   insertdefine("FIRSTLEGATOINSTR", numnormal + numnohr + 1);
  1108.   insertdefine("NUMHRINSTR", numnormal);
  1109.   insertdefine("NUMNOHRINSTR", numnohr);
  1110.   insertdefine("NUMLEGATOINSTR", numlegato);
  1111.   insertdefine("ADPARAM", adparam >> 8);
  1112.   insertdefine("SRPARAM", adparam & 0xff);
  1113.   if ((instr[MAX_INSTR-1].ad >= 2) && (!(instr[MAX_INSTR-1].ptr[WTBL])))
  1114.     insertdefine("DEFAULTTEMPO", instr[MAX_INSTR-1].ad - 1);
  1115.   else
  1116.     insertdefine("DEFAULTTEMPO", multiplier ? (multiplier*6-1) : 5);
  1117.  
  1118.   // Fixed firstwave & gatetimer
  1119.   if (fixedparams)
  1120.   {
  1121.     insertdefine("FIRSTWAVEPARAM", instr[1].firstwave);
  1122.     insertdefine("GATETIMERPARAM", instr[1].gatetimer & 0x3f);
  1123.   }
  1124.  
  1125.   // Insert source code of player
  1126.   if (adparam >= 0xf000)
  1127.     playername = "altplayer.s";
  1128.     
  1129.   if (!insertfile(playername))
  1130.   {
  1131.     clearscreen();
  1132.     printtextc(MAX_ROWS/2, CTITLE, "COULD NOT OPEN PLAYROUTINE!");
  1133.     fliptoscreen();
  1134.     waitkeynoupdate();
  1135.     goto PRCLEANUP;
  1136.   }
  1137.  
  1138.   // Insert frequencytable
  1139.   insertlabel("mt_freqtbllo");
  1140.   insertbytes(&freqtbllo[firstnote], lastnote-firstnote+1);
  1141.   insertlabel("mt_freqtblhi");
  1142.   insertbytes(&freqtblhi[firstnote], lastnote-firstnote+1);
  1143.  
  1144.   // Insert songtable
  1145.   insertlabel("mt_songtbllo");
  1146.   for (c = 0; c < songs*3; c++)
  1147.   {
  1148.     sprintf(textbuffer, "mt_song%d", c);
  1149.     insertaddrlo(textbuffer);
  1150.   }
  1151.   insertlabel("mt_songtblhi");
  1152.   for (c = 0; c < songs*3; c++)
  1153.   {
  1154.     sprintf(textbuffer, "mt_song%d", c);
  1155.     insertaddrhi(textbuffer);
  1156.   }
  1157.  
  1158.   // Insert patterntable
  1159.   insertlabel("mt_patttbllo");
  1160.   for (c = 0; c < patterns; c++)
  1161.   {
  1162.     sprintf(textbuffer, "mt_patt%d", c);
  1163.     insertaddrlo(textbuffer);
  1164.   }
  1165.   insertlabel("mt_patttblhi");
  1166.   for (c = 0; c < patterns; c++)
  1167.   {
  1168.     sprintf(textbuffer, "mt_patt%d", c);
  1169.     insertaddrhi(textbuffer);
  1170.   }
  1171.  
  1172.   // Insert instruments
  1173.   insertlabel("mt_insad");
  1174.   insertbytes(&instrwork[0], instruments);
  1175.   insertlabel("mt_inssr");
  1176.   insertbytes(&instrwork[instruments], instruments);
  1177.   insertlabel("mt_inswaveptr");
  1178.   insertbytes(&instrwork[instruments*2], instruments);
  1179.   if (!nopulse)
  1180.   {
  1181.     insertlabel("mt_inspulseptr");
  1182.     insertbytes(&instrwork[instruments*3], instruments);
  1183.   }
  1184.   if (!nofilter)
  1185.   {
  1186.     insertlabel("mt_insfiltptr");
  1187.     insertbytes(&instrwork[instruments*4], instruments);
  1188.   }
  1189.   if (!noinsvib)
  1190.   {
  1191.     insertlabel("mt_insvibparam");
  1192.     insertbytes(&instrwork[instruments*5], instruments);
  1193.     insertlabel("mt_insvibdelay");
  1194.     insertbytes(&instrwork[instruments*6], instruments);
  1195.   }
  1196.   if (!fixedparams)
  1197.   {
  1198.     insertlabel("mt_insgatetimer");
  1199.     insertbytes(&instrwork[instruments*7], instruments);
  1200.     insertlabel("mt_insfirstwave");
  1201.     insertbytes(&instrwork[instruments*8], instruments);
  1202.   }
  1203.  
  1204.   // Insert tables
  1205.   for (c = 0; c < MAX_TABLES; c++)
  1206.   {
  1207.     if ((c == PTBL) && (nopulse)) goto SKIPTABLE;
  1208.     if ((c == FTBL) && (nofilter)) goto SKIPTABLE;
  1209.  
  1210.     // Write table left side
  1211.     // Extra zero for speedtable
  1212.     if ((c == STBL) && ((!novib) || (!nofunktempo) || (!noportamento) || (!notoneporta))) insertbyte(0);
  1213.     // Table label
  1214.     insertlabel(tableleftname[c]);
  1215.  
  1216.     // Table data
  1217.     for (d = 0; d < MAX_TABLELEN; d++)
  1218.     {
  1219.       if (tableused[c][d+1])
  1220.       {
  1221.         switch (c)
  1222.         {
  1223.           // In wavetable, convert waveform values for the playroutine
  1224.           case WTBL:
  1225.           {
  1226.             unsigned char wave = ltable[c][d];
  1227.             if ((ltable[c][d] >= WAVESILENT) && (ltable[c][d] <= WAVELASTSILENT)) wave &= 0xf;
  1228.             if ((ltable[c][d] > WAVELASTDELAY) && (ltable[c][d] <= WAVELASTSILENT) && (!nowavedelay)) wave += 0x10;
  1229.             insertbyte(wave);
  1230.           }
  1231.           break;
  1232.  
  1233.           case PTBL:
  1234.           if ((simplepulse) && (ltable[c][d] != 0xff) && (ltable[c][d] > 0x80))
  1235.             insertbyte(0x80);
  1236.           else
  1237.             insertbyte(ltable[c][d]);
  1238.           break;
  1239.  
  1240.           // In filtertable, modify passband bits
  1241.           case FTBL:
  1242.           if ((ltable[c][d] != 0xff) && (ltable[c][d] > 0x80))
  1243.             insertbyte(((ltable[c][d] & 0x70) >> 1) | 0x80);
  1244.           else
  1245.             insertbyte(ltable[c][d]);
  1246.           break;
  1247.  
  1248.           default:
  1249.           insertbyte(ltable[c][d]);
  1250.           break;
  1251.         }
  1252.       }
  1253.     }
  1254.  
  1255.     // Write table right side, remapping jumps as necessary
  1256.     // Extra zero for speedtable
  1257.     if ((c == STBL) && ((!novib) || (!nofunktempo) || (!noportamento) || (!notoneporta))) insertbyte(0);
  1258.     // Table label
  1259.     insertlabel(tablerightname[c]);
  1260.  
  1261.     for (d = 0; d < MAX_TABLELEN; d++)
  1262.     {
  1263.       if (tableused[c][d+1])
  1264.       {
  1265.         if ((ltable[c][d] != 0xff) || (c == STBL))
  1266.         {
  1267.           switch(c)
  1268.           {
  1269.             case WTBL:
  1270.             if ((ltable[c][d] >= WAVECMD) && (ltable[c][d] <= WAVELASTCMD))
  1271.             {
  1272.               // Remap table-referencing commands
  1273.               switch (ltable[c][d] - WAVECMD)
  1274.               {
  1275.                 case CMD_PORTAUP:
  1276.                 case CMD_PORTADOWN:
  1277.                 case CMD_TONEPORTA:
  1278.                 case CMD_VIBRATO:
  1279.                 insertbyte(tablemap[STBL][rtable[c][d]]);
  1280.                 break;
  1281.  
  1282.                 case CMD_SETPULSEPTR:
  1283.                 insertbyte(tablemap[PTBL][rtable[c][d]]);
  1284.                 break;
  1285.  
  1286.                 case CMD_SETFILTERPTR:
  1287.                 insertbyte(tablemap[FTBL][rtable[c][d]]);
  1288.                 break;
  1289.  
  1290.                 default:
  1291.                 insertbyte(rtable[c][d]);
  1292.                 break;
  1293.               }
  1294.             }
  1295.             else
  1296.             {
  1297.               // For normal notes, reverse all right side high bits
  1298.               insertbyte(rtable[c][d] ^ 0x80);
  1299.             }
  1300.             break;
  1301.  
  1302.             case PTBL:
  1303.             if (simplepulse)
  1304.             {
  1305.               if (ltable[c][d] >= 0x80)
  1306.                 insertbyte((ltable[c][d] & 0x0f) | (rtable[c][d] & 0xf0));
  1307.               else
  1308.               {
  1309.                 int pulsespeed = rtable[c][d] >> 4;
  1310.                 if (rtable[c][d] & 0x80)
  1311.                 {
  1312.                   pulsespeed |= 0xf0;
  1313.                   pulsespeed--;
  1314.                 }
  1315.                 pulsespeed = swapnybbles(pulsespeed);
  1316.                 insertbyte(pulsespeed);
  1317.               }
  1318.             }
  1319.             else
  1320.               insertbyte(rtable[c][d]);
  1321.             break;
  1322.  
  1323.             default:
  1324.             insertbyte(rtable[c][d]);
  1325.             break;
  1326.           }
  1327.         }
  1328.         else
  1329.           insertbyte(tablemap[c][rtable[c][d]]);
  1330.       }
  1331.     }
  1332.  
  1333.     SKIPTABLE: ;
  1334.   }
  1335.  
  1336.   // Insert orderlists
  1337.   for (c = 0; c < songs; c++)
  1338.   {
  1339.     for (d = 0; d < MAX_CHN; d++)
  1340.     {
  1341.       sprintf(textbuffer, "mt_song%d", c*3+d);
  1342.       insertlabel(textbuffer);
  1343.       insertbytes(&songwork[songoffset[c][d]], songsize[c][d]);
  1344.     }
  1345.   }
  1346.  
  1347.   // Insert patterns
  1348.   for (c = 0; c < patterns; c++)
  1349.   {
  1350.     sprintf(textbuffer, "mt_patt%d", c);
  1351.     insertlabel(textbuffer);
  1352.     insertbytes(&pattwork[pattoffset[c]], pattsize[c]);
  1353.   }
  1354.  
  1355.   /* {
  1356.     FILE *handle = fopen("debug.s", "wb");
  1357.     fwrite(membuf_get(&src), membuf_memlen(&src), 1, handle);
  1358.     fclose(handle);
  1359.   } */
  1360.  
  1361.   // Assemble; on error fail in a rude way (the parser does so too)
  1362.   if (assemble(&src, &dest)) exit(1);
  1363.  
  1364.   packeddata = membuf_get(&dest);
  1365.   packedsize = membuf_memlen(&dest);
  1366.   playersize = packedsize - songtblsize - songdatasize - patttblsize - pattdatasize - instrsize - wavetblsize - pulsetblsize - filttblsize - speedtblsize;
  1367.  
  1368.   // Copy author info
  1369.   if (playerversion & PLAYER_AUTHORINFO)
  1370.   {
  1371.     for (c = 0; c < 32; c++)
  1372.     {
  1373.       packeddata[32+c] = authorname[c];
  1374.       // Convert 0 to space
  1375.       if (packeddata[32+c] == 0) packeddata[32+c] = 0x20;
  1376.     }
  1377.   }
  1378.  
  1379.   // Print results
  1380.   clearscreen();
  1381.   printblankc(0, 0, 15+16, MAX_COLUMNS);
  1382.   if (!strlen(loadedsongfilename))
  1383.     sprintf(textbuffer, "%s Packer/Relocator", programname);
  1384.   else
  1385.     sprintf(textbuffer, "%s Packer/Relocator - %s", programname, loadedsongfilename);
  1386.   textbuffer[80] = 0;
  1387.   printtext(0, 0, 15+16, textbuffer);
  1388.  
  1389.   sprintf(textbuffer, "PACKING RESULTS:");
  1390.   printtext(1, 2, 15, textbuffer);
  1391.  
  1392.   sprintf(textbuffer, "Playroutine:     %d bytes", playersize);
  1393.   printtext(1, 3, 7, textbuffer);
  1394.   sprintf(textbuffer, "Songtable:       %d bytes", songtblsize);
  1395.   printtext(1, 4, 7, textbuffer);
  1396.   sprintf(textbuffer, "Song-orderlists: %d bytes", songdatasize);
  1397.   printtext(1, 5, 7, textbuffer);
  1398.   sprintf(textbuffer, "Patterntable:    %d bytes", patttblsize);
  1399.   printtext(1, 6, 7, textbuffer);
  1400.   sprintf(textbuffer, "Patterns:        %d bytes", pattdatasize);
  1401.   printtext(1, 7, 7, textbuffer);
  1402.   sprintf(textbuffer, "Instruments:     %d bytes", instrsize);
  1403.   printtext(1, 8, 7, textbuffer);
  1404.   sprintf(textbuffer, "Tables:          %d bytes", wavetblsize+pulsetblsize+filttblsize+speedtblsize);
  1405.   printtext(1, 9, 7, textbuffer);
  1406.   sprintf(textbuffer, "Total size:      %d bytes", packedsize);
  1407.   printtext(1, 11, 7, textbuffer);
  1408.   fliptoscreen();
  1409.  
  1410.  
  1411.   // Now ask for fileformat
  1412.   printtext(1, 13, CTITLE, "SELECT FORMAT TO SAVE IN: (CURSORS=MOVE, ENTER=ACCEPT, ESC=CANCEL)");
  1413.  
  1414.   selectdone = 0;
  1415.  
  1416.   while (!selectdone)
  1417.   {
  1418.     switch(fileformat)
  1419.     {
  1420.       case FORMAT_SID:
  1421.       printtext(1, 14, CEDIT, "SID - SIDPlay music file format          ");
  1422.       strcpy(packedfilter, "*.sid");
  1423.       break;
  1424.  
  1425.       case FORMAT_PRG:
  1426.       printtext(1, 14, CEDIT, "PRG - C64 native format                  ");
  1427.       strcpy(packedfilter, "*.prg");
  1428.       break;
  1429.  
  1430.       case FORMAT_BIN:
  1431.       printtext(1, 14, CEDIT, "BIN - Raw binary format (no startaddress)");
  1432.       strcpy(packedfilter, "*.bin");
  1433.       break;
  1434.     }
  1435.  
  1436.     fliptoscreen();
  1437.     waitkeynoupdate();
  1438.  
  1439.     if (win_quitted)
  1440.     {
  1441.       exitprogram = 1;
  1442.       goto PRCLEANUP;
  1443.     }
  1444.  
  1445.     switch(rawkey)
  1446.     {
  1447.       case KEY_LEFT:
  1448.       case KEY_DOWN:
  1449.       fileformat--;
  1450.       if (fileformat < FORMAT_SID) fileformat = FORMAT_BIN;
  1451.       break;
  1452.  
  1453.       case KEY_RIGHT:
  1454.       case KEY_UP:
  1455.       fileformat++;
  1456.       if (fileformat > FORMAT_BIN) fileformat = FORMAT_SID;
  1457.       break;
  1458.  
  1459.       case KEY_ESC:
  1460.       selectdone = -1;
  1461.       break;
  1462.  
  1463.       case KEY_ENTER:
  1464.       selectdone = 1;
  1465.       break;
  1466.     }
  1467.   }
  1468.   if (selectdone == -1) goto PRCLEANUP;
  1469.  
  1470.   // By default, copy loaded song name up to the extension
  1471.   memset(packedsongname, 0, sizeof packedsongname);
  1472.   for (c = 0; c < strlen(loadedsongfilename); c++)
  1473.   {
  1474.     if (loadedsongfilename[c] == '.') break;
  1475.     packedsongname[c] = loadedsongfilename[c];
  1476.   }
  1477.   switch (fileformat)
  1478.   {
  1479.     case FORMAT_PRG:
  1480.     strcat(packedsongname, ".prg");
  1481.     break;
  1482.  
  1483.     case FORMAT_BIN:
  1484.     strcat(packedsongname, ".bin");
  1485.     break;
  1486.  
  1487.     case FORMAT_SID:
  1488.     strcat(packedsongname, ".sid");
  1489.     break;
  1490.   }
  1491.  
  1492.   // Now ask for filename, retry if unsuccessful
  1493.   while (!songhandle)
  1494.   {
  1495.     if (!fileselector(packedsongname, packedpath, packedfilter, "Save Music+Playroutine", 3))
  1496.       goto PRCLEANUP;
  1497.  
  1498.     if (strlen(packedsongname) < MAX_FILENAME-4)
  1499.     {
  1500.       int extfound = 0;
  1501.       for (c = strlen(packedsongname)-1; c >= 0; c--)
  1502.       {
  1503.         if (packedsongname[c] == '.') extfound = 1;
  1504.       }
  1505.       if (!extfound)
  1506.       {
  1507.         switch (fileformat)
  1508.         {
  1509.           case FORMAT_PRG:
  1510.           strcat(packedsongname, ".prg");
  1511.           break;
  1512.  
  1513.           case FORMAT_BIN:
  1514.           strcat(packedsongname, ".bin");
  1515.           break;
  1516.  
  1517.           case FORMAT_SID:
  1518.           strcat(packedsongname, ".sid");
  1519.           break;
  1520.         }
  1521.       }
  1522.     }
  1523.     songhandle = fopen(packedsongname, "wb");
  1524.   }
  1525.  
  1526.   if (fileformat == FORMAT_PRG)
  1527.   {
  1528.     fwritele16(songhandle, playeradr);
  1529.   }
  1530.   if (fileformat == FORMAT_SID)
  1531.   {
  1532.     unsigned char ident[] = {'P', 'S', 'I', 'D', 0x00, 0x02, 0x00, 0x7c};
  1533.     unsigned char byte;
  1534.     // Identification
  1535.     fwrite(ident, sizeof ident, 1, songhandle);
  1536.  
  1537.     // Load address
  1538.     byte = 0x00;
  1539.     fwrite8(songhandle, byte);
  1540.     fwrite8(songhandle, byte);
  1541.  
  1542.     // Init address
  1543.     if ((multiplier > 1) || (!multiplier))
  1544.     {
  1545.       unsigned speedvalue;
  1546.       byte = (playeradr-10) >> 8;
  1547.       fwrite8(songhandle, byte);
  1548.       byte = (playeradr-10) & 0xff;
  1549.       fwrite8(songhandle, byte);
  1550.  
  1551.       if (multiplier)
  1552.       {
  1553.         if (ntsc) speedvalue = 0x42c6/multiplier;
  1554.         else speedvalue = 0x4cc7/multiplier;
  1555.       }
  1556.       else
  1557.       {
  1558.         if (ntsc) speedvalue = 0x42c6*2;
  1559.         else speedvalue = 0x4cc7*2;
  1560.       }
  1561.       speedcode[1] = speedvalue & 0xff;
  1562.       speedcode[6] = speedvalue >> 8;
  1563.     }
  1564.     else
  1565.     {
  1566.       byte = (playeradr) >> 8;
  1567.       fwrite8(songhandle, byte);
  1568.       byte = (playeradr) & 0xff;
  1569.       fwrite8(songhandle, byte);
  1570.     }
  1571.  
  1572.     // Play address
  1573.     byte = (playeradr+3) >> 8;
  1574.     fwrite8(songhandle, byte);
  1575.     byte = (playeradr+3) & 0xff;
  1576.     fwrite8(songhandle, byte);
  1577.  
  1578.     // Number of subtunes
  1579.     byte = 0x00;
  1580.     fwrite8(songhandle, byte);
  1581.     byte = songs;
  1582.     fwrite8(songhandle, byte);
  1583.  
  1584.     // Default subtune
  1585.     byte = 0x00;
  1586.     fwrite8(songhandle, byte);
  1587.     byte = 0x01;
  1588.     fwrite8(songhandle, byte);
  1589.  
  1590.     // Song speed bits
  1591.     byte = 0x00;
  1592.     if ((ntsc) || (multiplier > 1) || (!multiplier)) byte = 0xff;
  1593.     fwrite8(songhandle, byte);
  1594.     fwrite8(songhandle, byte);
  1595.     fwrite8(songhandle, byte);
  1596.     fwrite8(songhandle, byte);
  1597.  
  1598.     // Songname etc.
  1599.     fwrite(songname, sizeof songname, 1, songhandle);
  1600.     fwrite(authorname, sizeof authorname, 1, songhandle);
  1601.     fwrite(copyrightname, sizeof copyrightname, 1, songhandle);
  1602.  
  1603.     // Flags
  1604.     byte = 0x00;
  1605.     fwrite8(songhandle, byte);
  1606.     if (ntsc) byte = 8;
  1607.       else byte = 4;
  1608.     if (sidmodel) byte |= 32;
  1609.       else byte |= 16;
  1610.     fwrite8(songhandle, byte);
  1611.  
  1612.     // Reserved longword
  1613.     byte = 0x00;
  1614.     fwrite8(songhandle, byte);
  1615.     fwrite8(songhandle, byte);
  1616.     fwrite8(songhandle, byte);
  1617.     fwrite8(songhandle, byte);
  1618.  
  1619.     // Load address
  1620.     if ((multiplier > 1) || (!multiplier))
  1621.     {
  1622.       byte = (playeradr-10) & 0xff;
  1623.       fwrite8(songhandle, byte);
  1624.       byte = (playeradr-10) >> 8;
  1625.       fwrite8(songhandle, byte);
  1626.     }
  1627.     else
  1628.     {
  1629.       byte = (playeradr) & 0xff;
  1630.       fwrite8(songhandle, byte);
  1631.       byte = (playeradr) >> 8;
  1632.       fwrite8(songhandle, byte);
  1633.     }
  1634.     if ((multiplier > 1) || (!multiplier)) fwrite(speedcode, 10, 1, songhandle);
  1635.   }
  1636.  
  1637.   fwrite(packeddata, packedsize, 1, songhandle);
  1638.   fclose(songhandle);
  1639.  
  1640.   PRCLEANUP:
  1641.   membuf_free(&src);
  1642.   membuf_free(&dest);
  1643.  
  1644.   if (pattwork) free(pattwork);
  1645.   if (songwork) free(songwork);
  1646.   if (instrwork) free(instrwork);
  1647.   printmainscreen();
  1648.   key = 0;
  1649.   rawkey = 0;
  1650. }
  1651.  
  1652. int packpattern(unsigned char *dest, unsigned char *src, int rows)
  1653. {
  1654.   unsigned char temp1[MAX_PATTROWS*4];
  1655.   unsigned char temp2[512];
  1656.   unsigned char instr = 0;
  1657.   int command = -1;
  1658.   int databyte = -1;
  1659.   int destsizeim = 0;
  1660.   int destsize = 0;
  1661.   int c, d;
  1662.  
  1663.   // First optimize instrument changes
  1664.   for (c = 0; c < rows; c++)
  1665.   {
  1666.     if ((c) && (src[c*4+1]) && (src[c*4+1] == instr))
  1667.     {
  1668.       temp1[c*4] = src[c*4];
  1669.       temp1[c*4+1] = 0;
  1670.       temp1[c*4+2] = src[c*4+2];
  1671.       temp1[c*4+3] = src[c*4+3];
  1672.     }
  1673.     else
  1674.     {
  1675.       temp1[c*4] = src[c*4];
  1676.       temp1[c*4+1] = src[c*4+1];
  1677.       temp1[c*4+2] = src[c*4+2];
  1678.       temp1[c*4+3] = src[c*4+3];
  1679.       if (src[c*4+1])
  1680.         instr = src[c*4+1];
  1681.     }
  1682.  
  1683.     switch(temp1[c*4+2])
  1684.     {
  1685.       // Remap speedtable commands
  1686.       case CMD_PORTAUP:
  1687.       case CMD_PORTADOWN:
  1688.       noportamento = 0;
  1689.       temp1[c*4+3] = tablemap[STBL][temp1[c*4+3]];
  1690.       break;
  1691.  
  1692.       case CMD_TONEPORTA:
  1693.       notoneporta = 0;
  1694.       temp1[c*4+3] = tablemap[STBL][temp1[c*4+3]];
  1695.       break;
  1696.  
  1697.       case CMD_VIBRATO:
  1698.       novib = 0;
  1699.       temp1[c*4+3] = tablemap[STBL][temp1[c*4+3]];
  1700.       break;
  1701.  
  1702.       case CMD_SETAD:
  1703.       nosetad = 0;
  1704.       break;
  1705.  
  1706.       case CMD_SETSR:
  1707.       nosetsr = 0;
  1708.       break;
  1709.  
  1710.       case CMD_SETWAVE:
  1711.       nosetwave = 0;
  1712.       break;
  1713.  
  1714.       // Remap table commands
  1715.       case CMD_SETWAVEPTR:
  1716.       nosetwaveptr = 0;
  1717.       temp1[c*4+3] = tablemap[WTBL][temp1[c*4+3]];
  1718.       break;
  1719.  
  1720.       case CMD_SETPULSEPTR:
  1721.       nosetpulseptr = 0;
  1722.       nopulse = 0;
  1723.       temp1[c*4+3] = tablemap[PTBL][temp1[c*4+3]];
  1724.       break;
  1725.  
  1726.       case CMD_SETFILTERPTR:
  1727.       nosetfiltptr = 0;
  1728.       nofilter = 0;
  1729.       temp1[c*4+3] = tablemap[FTBL][temp1[c*4+3]];
  1730.       break;
  1731.  
  1732.       case CMD_SETFILTERCTRL:
  1733.       nosetfiltctrl = 0;
  1734.       nofilter = 0;
  1735.       break;
  1736.  
  1737.       case CMD_SETFILTERCUTOFF:
  1738.       nosetfiltcutoff = 0;
  1739.       nofilter = 0;
  1740.       break;
  1741.  
  1742.       case CMD_SETMASTERVOL:
  1743.       nosetmastervol = 0;
  1744.       // If no authorinfo being saved, erase timingmarks (not supported)
  1745.       if (!(playerversion & PLAYER_AUTHORINFO))
  1746.       {
  1747.         if (temp1[c*4+3] > 0x0f)
  1748.         {
  1749.           temp1[c*4+2] = 0;
  1750.           temp1[c*4+3] = 0;
  1751.         }
  1752.       }
  1753.       break;
  1754.  
  1755.       case CMD_FUNKTEMPO:
  1756.       nofunktempo = 0;
  1757.       temp1[c*4+3] = tablemap[STBL][temp1[c*4+3]];
  1758.       break;
  1759.  
  1760.       case CMD_SETTEMPO:
  1761.       if (temp1[c*4+3] >= 0x80) nochanneltempo = 0;
  1762.       else noglobaltempo = 0;
  1763.       // Decrease databyte of all tempo commands for the playroutine
  1764.       // Do not touch funktempo
  1765.       if ((temp1[c*4+3] & 0x7f) >= 3)
  1766.         temp1[c*4+3]--;
  1767.       break;
  1768.  
  1769.     }
  1770.   }
  1771.  
  1772.   if (noeffects)
  1773.   {
  1774.     command = 0;
  1775.     databyte = 0;
  1776.   }
  1777.  
  1778.   // Write in playroutine format
  1779.   for (c = 0; c < rows; c++)
  1780.   {
  1781.     // Instrument change with mapping
  1782.     if (temp1[c*4+1])
  1783.     {
  1784.       temp2[destsizeim++] = instrmap[INSTRCHG+temp1[c*4+1]];
  1785.     }
  1786.     // Rest+FX
  1787.     if (temp1[c*4] == REST)
  1788.     {
  1789.       if ((temp1[c*4+2] != command) || (temp1[c*4+3] != databyte))
  1790.       {
  1791.         command = temp1[c*4+2];
  1792.         databyte = temp1[c*4+3];
  1793.         temp2[destsizeim++] = FXONLY+command;
  1794.         if (command)
  1795.           temp2[destsizeim++] = databyte;
  1796.       }
  1797.       else
  1798.         temp2[destsizeim++] = REST;
  1799.     }
  1800.     else
  1801.     {
  1802.       // Normal note
  1803.       if ((temp1[c*4+2] != command) || (temp1[c*4+3] != databyte))
  1804.       {
  1805.         command = temp1[c*4+2];
  1806.         databyte = temp1[c*4+3];
  1807.         temp2[destsizeim++] = FX+command;
  1808.         if (command)
  1809.           temp2[destsizeim++] = databyte;
  1810.       }
  1811.       temp2[destsizeim++] = temp1[c*4];
  1812.     }
  1813.   }
  1814.  
  1815.   // Final step: optimize long singlebyte rests with "packed rest"
  1816.   for (c = 0; c < destsizeim;)
  1817.   {
  1818.     int packok = 1;
  1819.  
  1820.     // Never pack first row or sequencer goes crazy
  1821.     if (!c) packok = 0;
  1822.     
  1823.     // There must be no instrument or command changes on the row to be packed
  1824.     if (temp2[c] < FX)
  1825.     {
  1826.       dest[destsize++] = temp2[c++];
  1827.       packok = 0;
  1828.     }
  1829.     if ((temp2[c] >= FXONLY) && (temp2[c] < FIRSTNOTE))
  1830.     {
  1831.       int fxnum = temp2[c] - FXONLY;
  1832.       dest[destsize++] = temp2[c++];
  1833.       if (fxnum) dest[destsize++] = temp2[c++];
  1834.       packok = 0;
  1835.       goto NEXTROW;
  1836.     }
  1837.     if (temp2[c] < FXONLY)
  1838.      {
  1839.       int fxnum = temp2[c] - FX;
  1840.       dest[destsize++] = temp2[c++];
  1841.       if (fxnum) dest[destsize++] = temp2[c++];
  1842.       packok = 0;
  1843.     }
  1844.  
  1845.     if (temp2[c] != REST) packok = 0;
  1846.  
  1847.     if (!packok)
  1848.       dest[destsize++] = temp2[c++];
  1849.     else
  1850.     {
  1851.       for (d = c; d < destsizeim; )
  1852.       {
  1853.         if (temp2[d] == REST)
  1854.         {
  1855.           d++;
  1856.           if (d-c == 64) break;
  1857.         }
  1858.         else break;
  1859.       }
  1860.       d -= c;
  1861.       if (d > 1)
  1862.       {
  1863.         dest[destsize++] = -d;
  1864.         c += d;
  1865.       }
  1866.       else
  1867.         dest[destsize++] = temp2[c++];
  1868.     }
  1869.     NEXTROW: {}
  1870.   }
  1871.   // See if pattern too big
  1872.   if (destsize > 256) return -1;
  1873.  
  1874.   // If less than 256 bytes, insert endmark
  1875.   if (destsize < 256)
  1876.   dest[destsize++] = 0x00;
  1877.  
  1878.   return destsize;
  1879. }
  1880.  
  1881. int testoverlap(int area1start, int area1size, int area2start, int area2size)
  1882. {
  1883.   int area1last = area1start+area1size-1;
  1884.   int area2last = area2start+area2size-1;
  1885.  
  1886.   if (area1start == area2start) return 1;
  1887.  
  1888.   if (area1start < area2start)
  1889.   {
  1890.     if (area1last < area2start) return 0;
  1891.     else return 1;
  1892.   }
  1893.   else
  1894.   {
  1895.     if (area2last < area1start) return 0;
  1896.     else return 1;
  1897.   }
  1898. }
  1899.  
  1900. unsigned char swapnybbles(unsigned char n)
  1901. {
  1902.   unsigned char highnybble = n >> 4;
  1903.   unsigned char lownybble = n & 0xf;
  1904.  
  1905.   return (lownybble << 4) | highnybble;
  1906. }
  1907.  
  1908. int insertfile(char *name)
  1909. {
  1910.   int size;
  1911.   int handle = io_open(name);
  1912.   if (handle == -1) return 0;
  1913.  
  1914.   size = io_lseek(handle, 0, SEEK_END);
  1915.   io_lseek(handle, 0, SEEK_SET);
  1916.   while (size--)
  1917.   {
  1918.     membuf_append_char(&src, io_read8(handle));
  1919.   }
  1920.   io_close(handle);
  1921.   return 1;
  1922. }
  1923.  
  1924. void inserttext(const char *text)
  1925. {
  1926.   membuf_append(&src, text, strlen(text));
  1927. }
  1928.  
  1929. void insertdefine(const char *name, int value)
  1930. {
  1931.   char insertbuffer[80];
  1932.  
  1933.   sprintf(insertbuffer, "%-16s = %d\n", name, value);
  1934.   inserttext(insertbuffer);
  1935. }
  1936.  
  1937. void insertlabel(const char *name)
  1938. {
  1939.   char insertbuffer[80];
  1940.  
  1941.   sprintf(insertbuffer, "%s:\n", name);
  1942.   inserttext(insertbuffer);
  1943. }
  1944.  
  1945. void insertbytes(const unsigned char *bytes, int size)
  1946. {
  1947.   char insertbuffer[80];
  1948.   int row = 0;
  1949.  
  1950.   while (size--)
  1951.   {
  1952.     if (!row)
  1953.     {
  1954.       inserttext("                .BYTE (");
  1955.       sprintf(insertbuffer, "$%02x", *bytes);
  1956.       inserttext(insertbuffer);
  1957.       bytes++;
  1958.       row++;
  1959.     }
  1960.     else
  1961.     {
  1962.       sprintf(insertbuffer, ",$%02x", *bytes);
  1963.       inserttext(insertbuffer);
  1964.       bytes++;
  1965.       row++;
  1966.       if (row == MAX_BYTES_PER_ROW)
  1967.       {
  1968.         inserttext(")\n");
  1969.         row = 0;
  1970.       }
  1971.     }
  1972.   }
  1973.   if (row) inserttext(")\n");
  1974. }
  1975.  
  1976. void insertbyte(unsigned char byte)
  1977. {
  1978.   char insertbuffer[80];
  1979.  
  1980.   sprintf(insertbuffer, "                .BYTE ($%02x)\n", byte);
  1981.   inserttext(insertbuffer);
  1982. }
  1983.  
  1984. void insertaddrlo(const char *name)
  1985. {
  1986.   char insertbuffer[80];
  1987.  
  1988.   sprintf(insertbuffer, "                .BYTE (%s %% 256)\n", name);
  1989.   inserttext(insertbuffer);
  1990. }
  1991.  
  1992. void insertaddrhi(const char *name)
  1993. {
  1994.   char insertbuffer[80];
  1995.  
  1996.   sprintf(insertbuffer, "                .BYTE (%s / 256)\n", name);
  1997.   inserttext(insertbuffer);
  1998. }
  1999.  
  2000. void findtableduplicates(int num)
  2001. {
  2002.   int c,d,e;
  2003.  
  2004.   if (num == STBL)
  2005.   {
  2006.     for (c = 1; c <= MAX_TABLELEN; c++)
  2007.     {
  2008.       if (tableused[num][c])
  2009.       {
  2010.         for (d = c+1; d <= MAX_TABLELEN; d++)
  2011.         {
  2012.           if (tableused[num][d])
  2013.           {
  2014.             if ((ltable[num][d-1] == ltable[num][c-1]) && (rtable[num][d-1] == rtable[num][c-1]))
  2015.             {
  2016.               // Duplicate found, remove and map to the original
  2017.               tableused[num][d] = 0;
  2018.               for (e = d; e <= MAX_TABLELEN; e++)
  2019.                 if (tableused[num][e]) tablemap[num][e]--;
  2020.               tablemap[num][d] = tablemap[num][c];
  2021.             }
  2022.           }
  2023.         }
  2024.       }
  2025.     }
  2026.   }
  2027.   else
  2028.   {
  2029.     for (c = 1; c <= MAX_TABLELEN; c++)
  2030.     {
  2031.       if (isusedandselfcontained(num, c))
  2032.       {
  2033.         for (d = c + gettablepartlen(num, c - 1); d <= MAX_TABLELEN; )
  2034.         {
  2035.           int len = gettablepartlen(num, d - 1);
  2036.  
  2037.           if (isusedandselfcontained(num, d))
  2038.           {
  2039.             for (e = 0; e < len; e++)
  2040.             {
  2041.               if (e < len-1)
  2042.               {
  2043.                 // Is table data the same?
  2044.                 if ((ltable[num][d+e-1] != ltable[num][c+e-1]) || (rtable[num][d+e-1] != rtable[num][c+e-1]))
  2045.                   break;
  2046.               }
  2047.               else
  2048.               {
  2049.                 // Do both parts have a jump in the end?
  2050.                 if (ltable[num][d+e-1] != ltable[num][c+e-1])
  2051.                   break;
  2052.                 // Do both parts end?
  2053.                 if (rtable[num][d+e-1] == 0)
  2054.                 {
  2055.                   if (rtable[num][c+e-1] != 0)
  2056.                     break;
  2057.                 }
  2058.                 else
  2059.                 {
  2060.                   // Do both parts loop in the same way?
  2061.                   if ((rtable[num][d+e-1] - d) != (rtable[num][c+e-1] - c))
  2062.                     break;
  2063.                 }
  2064.               }
  2065.             }
  2066.             if (e == len)
  2067.             {
  2068.               // Duplicate found, remove and map to the original
  2069.               for (e = 0; e < len; e++)
  2070.                 tableused[num][d+e] = 0;
  2071.               for (e = d; e < MAX_TABLELEN; e++)
  2072.                 if (tableused[num][e]) tablemap[num][e] -= len;
  2073.               for (e = 0; e < len; e++)
  2074.                 tablemap[num][d+e] = tablemap[num][c+e];
  2075.             }
  2076.           }
  2077.           d += len;
  2078.         }
  2079.       }
  2080.     }
  2081.   }
  2082. }
  2083.  
  2084. int isusedandselfcontained(int num, int start)
  2085. {
  2086.   int len = gettablepartlen(num, start - 1);
  2087.   int end = start + len - 1;
  2088.   int c;
  2089.  
  2090.   // Don't use jumps only
  2091.   if (len == 1) return 0;
  2092.  
  2093.   // Check that whole table is used
  2094.   for (c = start; c <= end; c++)
  2095.   {
  2096.     if (tableused[num][c] == 0) return 0;
  2097.   }
  2098.   // Check for jump to outside
  2099.   if (rtable[num][end-1] != 0)
  2100.   {
  2101.     if ((rtable[num][end-1] < start) || (rtable[num][end-1] > end)) return 0;
  2102.   }
  2103.   // Check for jump from outside
  2104.   for (c = 1; c < start; c++)
  2105.     if ((tableused[num][c]) && (ltable[num][c-1] == 0xff) && (rtable[num][c-1] >= start) && (rtable[num][c-1] <= end)) return 0;
  2106.   for (c = end+1; c <= MAX_TABLELEN; c++)
  2107.     if ((tableused[num][c]) && (ltable[num][c-1] == 0xff) && (rtable[num][c-1] >= start) && (rtable[num][c-1] <= end)) return 0;
  2108.  
  2109.   // OK!
  2110.   return 1;
  2111. }
  2112.  
  2113. void calcspeedtest(unsigned char pos)
  2114. {
  2115.   if (!pos) 
  2116.   {
  2117.     nozerospeed = 0;
  2118.     return;
  2119.   }
  2120.  
  2121.   if (ltable[STBL][pos-1] >= 0x80) nocalculatedspeed = 0;
  2122.   else nonormalspeed = 0;
  2123. }
  2124.  
  2125.  
  2126.