Help in playing chiptunes with a real SN76489

I connected an atmega168A to SN76489.
I clocked the atmega with a 3.579545 MHz crystal, and use the same clock for the PSG.

I took some VGMs (from alex kidd, sonic, lucky dime caper starring donald duck), and dump their content (the data part).
In detail I made a program that takes the data part and writes it as a (ascii) .h file, declaring a big

unsigned char data[] PROGMEM={.0x50,0xe5,0x50,0x8e...}


The data are essentially simply read from the vgm and wrote in the .h file in ascii format . The only exception is the "variable wait" (command 0x61). Since I use a 16 bit timer in the atmega (timer1) clocked by the system clock ( 3.579545) with a prescaler of 8, I converted the waiting times as

(int)round(clock/sampling*wait)

where

static const int prescaler=8;
static const double clock=3579545.0/prescaler;
static const double sampling=44100;

For reading the wait times (Intel order) I use

int readInt(const unsigned char* buffer,int n=2){
int r=0;
int mult=1;
for (int i=0;i<n;i++){
r+=mult*buffer;
mult=mult*256;
}
return r;
}

and for writing the converted data back I use

out<<std::hex<<"0x"<<(int)buffer[loc-1]<<","
<<"0x"<<(v%256)<<","
<<"0x"<<( v/256)<<",";


The code running on the atmega is then the following
http://pastebin.com/0YMm86XF

I also tested this version, which subtracts the time spent into writing data to the next delay by simply resetting the timer after wait operations, while letting it run during the writes

http://pastebin.com/KG6DypeQ

The problem is that the timings are very odd. Please listen to these files I recorded
https://minbox.com/g/dONPYJ7nIQ


Do you have any idea of what I am doing wrong?
​

Original thread: https://assemblergames.com/threads/help-in-playing-chiptunes-with-a-real-sn76489.47890/