function _writeInFormat(varName, data){
  var varNameLen = varName.length;
  var dataLen = data.byteLength;

  var totalLength = 8 + varNameLen + dataLen;

  var retBuf = new ArrayBuffer(totalLength);

  new DataView(retBuf, 0, 4).setUint32(0, varNameLen, false);
  new DataView(retBuf, 4+varNameLen, 4).setUint32(0, dataLen, false);

  new Uint8Array(retBuf, 4, varNameLen).set(new TextEncoder().encode(varName), 0);
  new Uint8Array(retBuf, 8+varNameLen, dataLen).set(data, 0);

  return retBuf;
}

function _readInFormat(data){
  var variables = {};
  var i = 0
  while (i < data.byteLength){
    var varNameLen = new DataView(data, i, 4).getUint32(0, false);
    var dataLen = new DataView(data, i+4+varNameLen, 4).getUint32(0, false);

    var varName = new TextDecoder("utf-8").decode(new Uint8Array(data, i+4, varNameLen));
    
    var dataBuf2 = new ArrayBuffer(dataLen);
    var dataBuf = new Uint8Array(dataBuf2);
    dataBuf.set(new Uint8Array(data, i+8+varNameLen, dataLen), 0);

    variables[varName] = dataBuf2;

    i += 8 + varNameLen + dataLen
  }
  return variables;
}

function readAndParseFormat(data){
  var formatted = _readInFormat(data);

  // TODO: add the type to the datastream e.g. uint32, uint8array, etc
  if(formatted.devicename != undefined) formatted.devicename = new TextDecoder().decode(formatted.devicename);
  if(formatted.therm_data != undefined) formatted.therm_data = formatted.therm_data;
  if(formatted.hd_data != undefined) formatted.hd_data = formatted.hd_data;
  if(formatted.therm_w != undefined) formatted.therm_w = new DataView(formatted.therm_w, 0, 4).getUint32(0, false);
  if(formatted.therm_h != undefined) formatted.therm_h = new DataView(formatted.therm_h, 0, 4).getUint32(0, false);
  if(formatted.hd_w != undefined) formatted.hd_w = new DataView(formatted.hd_w, 0, 4).getUint32(0, false);
  if(formatted.hd_h != undefined) formatted.hd_h = new DataView(formatted.hd_h, 0, 4).getUint32(0, false);

  if(formatted.gps_lat != undefined) formatted.gps_lat = new TextDecoder().decode(formatted.gps_lat) || 60.185244;
  if(formatted.gps_long != undefined) formatted.gps_long = new TextDecoder().decode(formatted.gps_long) || 24.822284;
 
  return formatted;
}
