#include <iostream>
#include <cstdlib>
#include <cstdint>
#include <cstring>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>

#include "shm_keys.hpp"

using namespace std;

int main(int argc, char** argv)
{
    if (argc != 4)
    {
        cout << "Usage: ./shm_print F H W\n";
        return 1;
    }

    int F = atoi(argv[1]);
    int H = atoi(argv[2]);
    int W = atoi(argv[3]);

    if (F <= 0 || H <= 0 || W <= 0)
    {
        cerr << "Invalid dimensions.\n";
        return 1;
    }

    int shmid = shmget(SHM_KEY_ORIGINAL, 1, 0666);
    if (shmid == -1)
    {
        cerr << "Could not attach original shared memory. Run ./shm_generator first.\n";
        return 1;
    }

    void* base = shmat(shmid, nullptr, 0);
    if (base == reinterpret_cast<void*>(-1))
    {
        cerr << "shmat failed.\n";
        return 1;
    }

    uint8_t* A = static_cast<uint8_t*>(base);

    cout << "First row of frame 0:\n";
    for (int j = 0; j < W; ++j)
    {
        cout << static_cast<unsigned int>(A[j]) << " ";
    }
    cout << "\n";

    shmdt(base);
    return 0;
}
