#include "message.h"
#include <iostream>
#define all(a) a.begin(), a.end()
#define popcount(x) __builtin_popcountll(x)
using namespace std;
void send_message(vector<bool> message, vector<bool> C) {
int i, ptr = 0;
vector<int> pos;
while (ptr < 31) {
if (pos.empty()) {
send_packet(vector<bool>(31, C[ptr]));
if (C[ptr] == 0) {
pos.push_back(ptr);
}
ptr++;
continue;
}
int k = pos.size();
vector<bool> packet(31);
for (i = 0; ptr + i < 31 && i < k; i++) {
packet[pos[i]] = C[ptr + i];
if (C[ptr + i] == 0) pos.push_back(ptr + i);
}
send_packet(packet);
ptr += k;
}
for (i = 0; i < message.size(); i += 16) {
vector<bool> packet(31);
int j = i;
for (int p : pos) if (j < message.size()) {
packet[p] = message[j++];
}
send_packet(packet);
}
vector<bool> packet(31);
for (i = 0; i < 4; i++) {
packet[pos[i]] = (message.size() % 16) >> i & 1;
}
send_packet(packet);
}
vector<bool> receive_message(vector<vector<bool>> packets) {
vector<int> C(31), pos;
int i, ptr = 0;
for (i = 0; i < packets.size() && ptr < 31; i++) {
if (pos.empty()) {
int cnt[2] = {};
for (auto b : packets[i]) {
cnt[b]++;
}
C[ptr] = cnt[0] > cnt[1] ? 0 : 1;
if (C[ptr] == 0)
pos.push_back(ptr);
ptr++;
continue;
}
int k = pos.size();
for (int j = 0; j < k && ptr + j < 31; j++) {
C[ptr + j] = packets[i][pos[j]];
if (C[ptr + j] == 0) pos.push_back(ptr + j);
}
ptr += k;
}
vector<bool> message;
for (; i < packets.size() - 2; i++) {
for (int j : pos) {
message.push_back(packets[i][j]);
}
}
int to_read = 0;
for (i = 0; i < 4; i++) {
to_read |= packets.back()[pos[i]] << i;
}
if (to_read == 0) to_read = 16;
for (i = 0; i < to_read; i++) {
message.push_back(packets[packets.size() - 2][pos[i]]);
}
return message;
}