#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void keys(FILE* f, FILE* g, int* keyLenght, int* keyIndex)
{
int keyFlag = 1, stringFlag = 0, currentKeyLength = 0;
char x = 0, string[100000];
string[0] = '\0';
while(x != '}'){
x = getc(f);
while(x == ' ' && !stringFlag){
x = getc(f);
}
//if a key follows
if(x == ','){
keyFlag = 1;
currentKeyLength = 0;
string[strlen(string)] = ',';
}
//if the value of a key follows
else if(x == ':'){
keyFlag = 0;
fprintf(g, ",");
keyLenght[*keyIndex] = currentKeyLength;
(*keyIndex)++;
}
//if a string begins or ends
else if(x == '"'){
stringFlag ^= 1;
}
//if x is a char
else if(keyFlag && stringFlag){
fprintf(g, "%c", x);
currentKeyLength++;
}
else if(!keyFlag){
if(stringFlag){
string[strlen(string)] = x;
}
else if(x != '\n' && x != ' '){
string[strlen(string)] = x;
}
}
}
string[strlen(string) - 1] = ',';
string[strlen(string)] = '\0';
fprintf(g, "\n");
fprintf(g, "%s", string);
}
void CSV(FILE* f, FILE* g, int* keyLenght, int keyIndex)
{
int valueFlag = 0, objectFlag = 0, stringFlag = 0, currentObjectKey = 0;
char x = 0, buffer[1000];
while(x != ']'){
x = getc(f);
while(x == ' ' && !stringFlag){
x = getc(f);
}
if(x == '{'){
objectFlag = 1;
currentObjectKey = 0;
}
else if(x == '}'){
objectFlag = 0;
fprintf(g, ",");
}
else if(x == '"'){
stringFlag ^= 1;
if(stringFlag && !valueFlag){
fread(buffer, sizeof(char), keyLenght[currentObjectKey], f);
}
}
else if(x == ':'){
valueFlag = 1;
}
else if(x == ','){
valueFlag = 0;
currentObjectKey++;
if(objectFlag){
fprintf(g, ",");
}
else{
fprintf(g, "\n");
}
}
else if (valueFlag && x != '\n' && x != ']'){
if(stringFlag){
fprintf(g, "%c", x);
}
else if(x != ' '){
fprintf(g, "%c", x);
}
}
}
}
int main()
{
//open the files
FILE* f = fopen("convertor.in", "r");
FILE* g = fopen("convertor.out", "w");
//get the keys
int keyLenght[10100], keyIndex = 0;
//keyLenght = (int*)malloc(200 * sizeof(int));
keys(f, g, keyLenght, &keyIndex);
//start getting the objects and teir values
//CSV(f, g, keyLenght, keyIndex);
//close the files
fclose(f);
fclose(g);
return 0;
}