function Index2Casefile(index_file, casefilename)

% Index2Casefile(index_file, casefilename)
%
% Process data in index_file to generate a Netica casefile.  Index file is a text file,
% each column representing a field, each row a new observation.

% Liam Pedersen, NASA ARC/CMU 1998

%**************************
%initialize variables etc.
%**************************

%************************************************************
% spectral feature extraction global data

% spectral range of interest.
lambda_min = 400;      
lambda_max = 2500;      % ASDI FieldSpec FR spectrometer
%lambda_max = 1000;       % OceanOptics S2000 spectrometer

% create spectral templates T and define wavelength range.
l = lambda_min:lambda_max;
%[T, ltmin, m, SpecLabels] = OOIS2000_SpecFeatureTemplates(1);
[T, ltmin, m, SpecLabels] = ASDIFR_SpecFeatureTemplates(1);

% spectral filters
load rgb.mat % loads vectors R, G, B and l_rgb.  RGB filter fns + wavelength range.
SpectralFeatureLabels = [SpecLabels 'Red Green Intensity '];

% Number of spectral features
NSpecFeatures = length(ltmin) + 3;

%************************************************************
% image feature extraction global data

% POMM data for image segmentation
load PixFeatureStats
% loads invCov and Pox
Pxx = [.8 .2; .03 .97];

% ice and rock examples for NN feature extraction
load rock;	% load rock example pixels 'rock'
load ice		% load ice example pixels 'ice'
invPixFeatureCov = invCov;

% Image feature labels
HistFeatureLabels = 'CRed CGreen CIntensity CRedStd CGreenStd CIntensityStd CRedEntropy CGreenEntropy CIntensityEntropy ';
BoundaryFeatureLabels = 'Area Compactness BendingEnergy ';

% metal detector feaures
MetalDetectorLabels = 'metal  ';

% casefile header labels
label1 = 'IDnum  sample_id  basic_class  classification  formation  ';
CaseFileLabels = [label1 SpectralFeatureLabels HistFeatureLabels BoundaryFeatureLabels MetalDetectorLabels];

NImageFeatures = 12;

%*****************************************************************
%*****************************************************************

% open CASE file for output.
casefile = OpenCaseFile(casefilename, CaseFileLabels);

% Open INDEX file and process each line
Err = 0; i = 1;
fid = OpenDataFile(index_file, 3);
L = readline(fid);

while (L > 0)
   S = ParseDataFileLineII(L);
   
   % write first fields of S
   fprintf(casefile,'%d\t', S.idnum);
   fprintf(casefile,'%s\t', S.sample_id,S.basic_class,S.classification, S.formation);
   
   %********************************
   % Process SPECTRUM (if possible).
   
   if (S.specfile(1) ~= '*')
      % load spectra and extract feature vector: (local function)
      [spectrum,lambda] = ReadSpectrum(S.specfile, 'ast');
      if (spectrum ~= -1)  % spectrum read successfully!
         SFV = SpectralFeatureVector(spectrum,lambda,T,ltmin, m, R,G,B,l_rgb,lambda_min,lambda_max);
      
         % write to case file
         fprintf(casefile,'%g  ',SFV);  
      
         % update output matrix
%         SO = [SO; S.idnum SFV];
      else
         disp('Unable to read spectral file');
         S.specfile
         for i = 1:NSpecFeatures
            fprintf(casefile,'*  ');
         end
      end
   else
      for i = 1:NSpecFeatures
         fprintf(casefile,'*  ');
      end
   end  % spectrum processing
   
   %****************************
   % Process IMAGE (if possible)
   
   image_err = 1;
   if (S.imagefile(1) ~= '*')
      
      % Load image, segment it, and return feature vector: (local fn)
		[IFV, image_err] = ProcessImage(S.imagefile,S.origin,S.scale,rock,ice,invPixFeatureCov,Pxx,Pox);
      
      if (image_err == 0)
	      % update casefile
   	   fprintf(casefile,'%g  ', IFV);
      
      	% update output matrix
%         IO = [IO; S.idnum IFV];
      end
   end
   if (image_err ~=0 )
		for i = 1:NImageFeatures
   	   fprintf(casefile,'*  ');
      end
   end
   
   %********************************
   % Process METAL DETECTOR (if possible).
   
   MetalErr = 1;
   if (S.metalfile(1) ~= '*')
      % load spectra and extract feature vector: (local function)
      X = ReadMetal(S.metalfile);
      if (X > -10)  % data read successfully....
         MetalErr = 0;
         
         MFV = MetalDetectorFeatures(X, 40);
           
         % write to case file
         fprintf(casefile,'%g  ',MFV);  
      
      else
         MetalErr = 1;
         disp('Unable to read metal detector data from file');
         S.specfile
      end
   else
      % simulate metal detector data - as we have insufficient.
      load c:\data\electromagnetic\nometal.mat
      y = random_obs(x,cpdf);
      fprintf(casefile,'%g  ', y);
   end
   %if (MetalErr)
   %   fprintf(casefile,'*  ');
   %end

   
   drawnow
   fprintf(casefile,'\n');
   L = readline(fid);
end

% close I/O files
fclose(fid);
fclose(casefile);





%**********************************************************************
%**********************************************************************


%*************************************************************
% Process SPECTRUM

function SFV = SpectralFeatureVector(spectrum, lambda, Templates, LT, m, R, G, B, l_rgb, lmin, lmax)

% SFV = SpectralFeatureVector(specfile, Templates, LT, m, R, G, B, l_rgb)
%		spectrum = spectra vector
%     lambda   = wavelength values for each entry in spectrum (1nm spacing assumed)
%		Templates = cell array of feature templates (1 nm spacing)
%		LT = array of starting wavelengths (nm) of feature templates
%		R, G, B, l_rgb are R,G,B filter fns, along with wavelength vector l_rgb (1nm spacing)
%		lmin, lmax = wavelength range (nm).

% Liam Pedersen, NASA ARC/CMU, August 1998

% set for plotting of spectra and spectral features.
plotspecfeatures = 1;

% get indices of wavelength limits in spectrum vector
imin = find(lambda == lmin);
imax = find(lambda == lmax);
for i = 1:length(LT)
   itmin(i) = find(lambda == LT(i));
end

% compute spectral template correlations:
SF = SpectralCorrelationII(spectrum, Templates, itmin);

% compute RGI coefficients
dl = lambda(1) - l_rgb(1);
if (dl <= 0)
   fmin = find(lambda == l_rgb(1));
   MaxIntensity = sum(sum([R G B]));
   F = FilterCoeffs(spectrum, [R G B], fmin);
else
   MaxIntensity = sum(sum([R(dl:length(R)) G(dl:length(G)) B(dl:length(B))]));
   F = FilterCoeffs(spectrum, [R(dl:length(R)) G(dl:length(G)) B(dl:length(B))], 1);
end

Intensity = sum(F);
r = F(1)/Intensity;
g = F(2)/Intensity;
b = F(3)/Intensity;
Intensity = Intensity/MaxIntensity;
   
SFV = [SF r g Intensity];

if (plotspecfeatures)
   figure(1);
   clf;
   PlotSpectralFeatures(lmin:lmax, spectrum(imin:imax), [SF r g b], m, '')
   drawnow
end
   
%****************************************************************************
%****************************************************************************
% Extract IMAGE feature vector

function [IFV, err] = ProcessImage(imagefile,origin,scale,rock_features,ice_features,invFeatureCov,Pxx,Pox)

% Loads image and return feature vector, if possible.
% cf ImageFeatureVector for documentation.
%
% returns err > 0 if failure.

plotimage = 0;
getorigin = 0;

% read image
[im, err] = ReadImage(imagefile);

if (err == 1)
   disp(['Cannot process image ' imagefile]);
   return
end

if (sum(origin) == 0)
   getorigin = 1;
end

if (plotimage | getorigin) 
   figure(2);
   clf;
   image(im);
   title(imagefile);
   if (getorigin)
		[x, y] = ginput(1);
      origin = round([x y]);
   end
   hold on
   plot(origin(1), origin(2), 'r*');
   drawnow
end

lastwarn('');
fail = 'err = 2;';
tri = '[IFV, err] =ImageFeatureVector(im,origin,scale,rock_features,ice_features,invFeatureCov,Pxx,Pox);';
eval(tri,fail);
if (~isempty(lastwarn)) err = err + 1; end
