% Solution to BTM Lab 05, exercise 2
% Author: Ronni Grapenthin
%
% Your job is it to write a script, read in the whole file (FAIR.pfiles) 
% and write column epoch, lon, lat, and height into a new file FAIR2.dat. 
%
% I recommend against using dlmread to read the data since it's rather
% tricky (many whitespaces separate the data). I give sample solutions
% using textread and textscan for reading the data and dlmwrite and fprintf
% to write the data.

% the usual preamble
clear all;
close all;
clc;

% setting the input and output files as a variables to allow for easier 
% conversion of the scipt into a function
in_file = 'FAIR.pfiles';
out_file_dlmwrite = 'FAIR2_from_dlmwrite.dat';
out_file_fprintf  = 'FAIR2_from_fprintf.dat';

%%%%
% solution using textread and dlmwrite
% ------------------------------------

% reading the data is really cumbersome using textread in this case since 
% all input fields need to be assigned to local variables
[epoch, gps_site, tie_site, lon, lat, height, s_e, s_n, s_v, ...
  cov_en, cov_eu, cov_nu, path_to_soln] = textread(in_file, '%f%s%s%f%f%f%f%f%f%f%f%f%s');

% writing the requested data EPOCH, LAT, LON, HEIGHT using dlmwrite and a
% tabulator as a delimiter ... dlmwrite takes a string as a file name
% You need to set precision otherwise the output is being truncated.
dlmwrite(out_file_dlmwrite, [epoch lat lon height], 'delimiter', ' ', 'precision', 10);

%%%%
% solution using textscan and fprintf
% ------------------------------------

% textscan takes not the filname string but a file id created with fopen.
fid_in = fopen(in_file, 'r');
data_cell = textscan(fid_in, '%f%s%s%f%f%f%f%f%f%f%f%f%s');
fclose(fid_in);                 % close immediately after reading is done to avoid having
                                % dangling file pointers

% writing to file -- remember that fprintf takes a column from the data 
% matrix it is handed to write a row of data to the file. We know that 
% we have data_cell contains our data in column form. But we need to create
% this format:
%
% T1 T2 T3 T4 ... Tn            %epochs as a row
% A1 A2 A3 A4 ... An            %lats as a row
% L1 L2 L3 L4 ... Ln            %lons as a row
% H1 H2 H3 H4 ... Hn            %heights as a row
% 
% to get the desired output format:
%
% T1 A1 L1 H1 
% T2 A2 L2 H2
% T3 A3 L3 H3 
% T4 A4 L4 H4
% ... ... ...
% Tn An Ln Hn 

% create the output array of the correct format, note that rows are
% separated by a ';' as well as the apostrophe to transpose the column
% vectors to row vectors.
data_out = [data_cell{1}'; data_cell{5}'; data_cell{4}'; data_cell{6}'];

% open outfile for writing, again, preserve precision using correct
% formatting
fid_out = fopen(out_file_fprintf, 'w');
fprintf(fid_out, '%.10f %.10f %.10f %.10f\n', data_out);
fclose(fid_out);
