Skip to content

Instantly share code, notes, and snippets.

@PJK
Last active January 4, 2016 03:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PJK/59be9c6036e7f2a22cbb to your computer and use it in GitHub Desktop.
Save PJK/59be9c6036e7f2a22cbb to your computer and use it in GitHub Desktop.
Disclaimer: tenhle program zdaleka není korektní! Existuje spousta vstupů, které jsou korektní a budou špatně parsovány. Třeba 'COMMENT = ...'. V ukázkových datech se ale takové věci nevyskytují.
#include <string>
#include <vector>
#include <iostream>
#include <fstream>
#include <sstream>
#include <regex>
#include <numeric>
using namespace std;
struct BlockInfo {
int naxis, bitpix;
vector<int> axes;
};
regex simple_block("SIMPLE =.*");
regex extension_block("XTENSION= '([\\w+]*)'.*");
regex segment("(\\S+)\\s*\\=\\s*([^' ]+|'[^']+')\\s*(\\/.*)?");
regex axes_info("NAXIS(\\d+)");
string readSegment(istream & in) {
char buffer[81];
in.read(buffer, 80);
buffer[80] = '\0';
return string(buffer);
}
int toInt(string s) {
int tmp;
stringstream(s) >> tmp;
return tmp;
}
void printSegment(string seg, BlockInfo & bi) {
smatch res;
if (regex_match(seg, res, segment)) {
cout << res[1] << "=" << res[2] << endl;
if (res[1] == "NAXIS") {
bi.naxis = toInt(res[2]);
} else if (regex_match(string(res[1]), axes_info)) {
bi.axes.push_back(toInt(res[2]));
} else if (res[1] == "BITPIX") {
bi.bitpix = toInt(res[2]);
}
}
}
void handleBlock(istream & in) {
BlockInfo bi;
smatch res;
string first = readSegment(in);
if (regex_match(first, simple_block))
cout << "Primary" << endl;
else if (regex_match(first, res, extension_block))
cout << "Extension" << endl;
printSegment(first, bi);
string segment;
int read = 1;
while (segment.find("END") != 0) {
segment = readSegment(in);
printSegment(segment, bi);
++read;
}
in.ignore(80 * (36 - read % 36));
cout << endl;
int skip = 0;
if (bi.naxis)
skip= abs(bi.bitpix/8) * accumulate(bi.axes.begin(), bi.axes.end(), 1, std::multiplies<int>());
cout << "Data content: " << skip << "B" << endl;
skip = (skip / 2880) + (skip % 2880 ? 1 : 0);
if (skip)
for (int i = 0; i < skip; ++i)
//WTF WTF WTF
for (int i=0; i<36; i++) readSegment(in);
cout << endl;
}
int main(int argc, char * * argv) {
vector<string> params(argv, argv + argc);
ifstream in; in.open(params[1], ifstream::binary);
in.exceptions(istream::failbit | istream::badbit);
try { while (1) { handleBlock(in); } }
catch (ios_base::failure) {}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment