#include <stdio.h>
#include <stdlib.h>
#include <netcdf.h>


#define X 3
#define Y 3
#define Z 3


int indexof(int x, int y, int z) {
    int a = 0;
    int n = 1;
    a += z * n;
    n *= Z;
    a += y * n;
    n *= Y;
    a += x * n;
    n *= X;
    return a;
}

int main() {/* create a.nc */

    int  stat;  /* return status */
    int  ncid;  /* netCDF id */

    /* dimension ids */
    int x_dim;
    int y_dim;
    int z_dim;

    int x, y, z;
    int j;


    /* variable ids */
    int x_id;
    int y_id;
    int z_id;
    int f_id;


    /* variable shapes */
    int x_dims[1];
    int y_dims[1];
    int z_dims[1];
    int f_dims[3];


    double x_data[X] ;
    double y_data[Y];
    double z_data[Z] ;
    double f_data[X * Y * Z];

    /* enter define mode */
    nc_create("test.nc", NC_CLOBBER, &ncid);

    /* define dimensions */
    nc_def_dim(ncid, "x", X, &x_dim);
    nc_def_dim(ncid, "y", Y, &y_dim);
    nc_def_dim(ncid, "z", Z, &z_dim);

    /* define variables */


    x_dims[0] = x_dim;
    nc_def_var(ncid, "x", NC_DOUBLE, 1, x_dims, &x_id);

    y_dims[0] = y_dim;
    nc_def_var(ncid, "y", NC_DOUBLE, 1, y_dims, &y_id);

    z_dims[0] = z_dim;
    nc_def_var(ncid, "z", NC_DOUBLE, 1, z_dims, &z_id);



    f_dims[0] = x_dim;
    f_dims[1] = y_dim;
    f_dims[2] = z_dim;
    nc_def_var(ncid, "f", NC_DOUBLE, 3, f_dims, &f_id);


    // nc_put_att_text(ncid, f_id, "coordinates", 3, "y x");


    nc_enddef(ncid);

    for (x = 0; x < X; x++) {
        x_data[x] = 100 + x;
    }
    nc_put_var_double(ncid, x_id,  x_data);
    for (y = 0; y < Y; y++) {
        y_data[y] = 200 + y;
    }
    nc_put_var_double(ncid, y_id,  y_data);
    for (z = 0; z < Z; z++) {
        z_data[z] = 300 + z;
    }
    nc_put_var_double(ncid, z_id,  z_data);

    j = 0;
    for (x = 0; x < X; x++) {
        for (y = 0; y < Y; y++) {
            for (z = 0; z < Z; z++) {
                int i = indexof(x, y, z);
                // f_data[i] = 1000.0 + x * 100 + y * 10 + z;
                f_data[i] = j++;
            }
        }
    }



    nc_put_var_double(ncid, f_id, f_data);


    nc_close(ncid);
    return 0;
}
