First you have to find out which snapshot was used for cycle X. Use (cycle# * blocksPerCycle + 1) to get the hash of the first block of that cycle. Then you can query:
This gets you information about the snapshots for this cycle. From this info, grab the RollSnapShot value. This tells you which of the several snapshots taken during this cycle was used for calculations.
Calculate the block hash for that snapshot:
((cycle - PreservedCycles - 2) * BlocksPerCycle) + (RollSnapShot + 1) * 256
Now that you have that hash, you can get bakers staking balance:
And each delegate's balance:
If you are familiar with Go, check out this library: