unit Impascii;

interface

uses
  SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
  Forms, Dialogs, StdCtrls, TabNotBk, maths, shared, global, fileio;

type
  TImportFrm = class(TForm)
    bOK: TButton;
    bCancel: TButton;
    tnImportType: TTabbedNotebook;
    mePreview: TMemo;
    GroupBox1: TGroupBox;
    Label1: TLabel;
    Label2: TLabel;
    Label4: TLabel;
    Label6: TLabel;
    edIgnore: TEdit;
    EdDt: TEdit;
    edNumChannels: TEdit;
    EdTimeColumn: TEdit;
    cbTUnits: TComboBox;
    Label5: TLabel;
    Label3: TLabel;
    edNumSamples: TEdit;
    procedure FormShow(Sender: TObject);
    procedure bOKClick(Sender: TObject);
  private
    { Private declarations }
    procedure InspectASCIIFile ;
    procedure ImportASCIIData ;
  public
    { Public declarations }
    FileName : string ;
  end;

var
  ImportFrm: TImportFrm;

implementation

{$R *.DFM}

var
   F : TextFile ;
   MaxValues : Array[0..20] of single ;

procedure TImportFrm.FormShow(Sender: TObject);
{ -----------------------------------
  Display first 10 lines of data file
  -----------------------------------}
begin

     cbTUnits.Clear ;
     cbTUnits.Items.Add('s') ;
     cbTUnits.Items.Add('ms') ;
     cbTUnits.Items.Add('us') ;
     cbTUnits.ItemIndex := 1 ;
     InspectASCIIFile ;
         end ;


procedure TImportFrm.InspectASCIIFile ;
var
   i,Col,nCols,nColsOld,nSamples,MaxSamples : Integer ;
   nLines : LongInt ;
   T,TOld : single ;
   Values : Array[0..20] of Single ;
   s : string ;
begin

     { Open file for reading as text }
     AssignFile( F, ImportFrm.FileName ) ;
     Reset(F) ;

     { Initialise counters }
     for Col := 0 to High(MaxValues) do MaxValues[Col] := -1E30 ;
     nSamples := 0 ;
     MaxSamples := 0 ;
     nLines := 0 ;

     { Put first 10 lines into memo box }
     mePreview.Clear ;
     while not EOF(F) do begin

         ReadLn( F,s ) ;
         if nLines < 10 then mePreview.Lines.Add( s ) ;
         Inc(nLines) ;

         { Number of columns }
         nCols := ExtractListOfFloats( s, Values, False ) ;
         if nCols = nColsOld then begin
            edNumChannels.text := format( ' %d ', [nCols-1] ) ;
            end ;
         nColsOld := nCols ;

         { Determine maximum absolute values within data columns }
         for Col := 0 to nCols-1 do begin
              MaxValues[Col] := MaxFlt( [Abs(Values[Col]),MaxValues[Col]] ) ;
              end ;

         { Sampling interval }
         if nCols > 1 then begin
            Inc(nSamples) ;
            MaxSamples := MaxInt( [nSamples,MaxSamples] ) ;
            T := Values[0] ;
            edDT.text := format( ' %.4g %s', [T-TOld, cbTUnits.text] ) ;
            TOld := T ;
            edTimeColumn.text := ' 1 ' ;
            if T < Told then nSamples := 0 ;
            end ;

         end ;

     edNumChannels.text := format( ' %d ', [nCols-1] ) ;
     MaxSamples := (((MaxSamples-1) div 256)+1)*256 ;
     edNumSamples.text := format( ' %d ',[MaxSamples]) ;

     CloseFile(F) ;
     end;





procedure TImportFrm.bOKClick(Sender: TObject);
begin

     if tnImportType.Pages[tnImportType.PageIndex] = 'ASCII' then ImportASCIIData ;

     end;

procedure TImportFrm.ImportASCIIData ;
var
   Values,Scale : Array[0..20] of Single ;
   s : string ;
   Col,nCols,TCol,n,nSamples,NumSamplesPerRecord,ch,i : Integer ;
   T,TOld,TScale : single ;
   RH : ^TRecHeader ;
   Buf : ^TIntArray ;
   SaveRecord : Boolean ;
begin

     { Create buffer to hold samples }
     New(Buf) ;
     New(RH) ;

     { Close existing WCP data file }
     if RawFH.FileHandle > 0 then FileClose( RawFH.FileHandle ) ;
     { Create name of WCP file to hold ASCII data file }
     RawFH.FileName := ReplaceFileEnding( ImportFrm.FileName, '.wcp' ) ;
     { Create a new WCP file to hold converted data }
     RawFH.FileHandle := FileCreate( RawFH.FileName ) ;

     { Define size of WCP record }
     RawFH.NumRecords := 0 ;
     RawFH.NumSamples := ExtractInt( edNumSamples.text ) ;
     RawFH.NumChannels := ExtractInt( edNumChannels.text ) ;
     NumSamplesPerRecord := RawFH.NumSamples*RawFH.NumChannels ;

     { Open file for reading as text }
     AssignFile( F, ImportFrm.FileName ) ;
     Reset(F) ;

     nCols := RawFH.NumChannels + 1 ;
     TCol := ExtractInt(edTimeColumn.text) - 1 ;
     if TCol >= 0 then Inc(nCols) ;

     RawFH.ADCVoltageRange := 1.0 ;
     Ch := 0 ;
     for Col := 0 to nCols-1 do if Col <> TCol then begin
         Scale[Col] := MaxADCValue / (1.1*MaxValues[Col]) ;
         Channel[Ch].ADCScale := 1.0 / Scale[Col] ;
         Channel[ch].ADCCalibrationFactor := RawFH.ADCVoltageRange /
                          ( Channel[ch].ADCScale * (MaxADCValue+1) ) ;
         Inc(Ch) ;
         end ;

     { Channel calibration and scale factor settings }
     for ch := 0 to RawFH.NumChannels-1 do begin
         Channel[ch].ChannelOffset := ch ;
         Channel[ch].ADCAmplifierGain := 1. ;
         Channel[ch].ADCZero := 0 ;
         Channel[ch].ADCUnits := '' ;
         Channel[ch].ADCName := Format( 'Ch.%d', [ch] ) ;
         end ;

     { Set time conversion factor }
     if cbTUnits.Items[cbTUnits.ItemIndex] = 's' then TScale := 1.0
     else if cbTUnits.Items[cbTUnits.ItemIndex] = 'ms' then TScale := 1E-3
     else TScale := 1E-6 ;
     RawFH.dt := ExtractFloat(edDT.text,1.0)*TScale ;

     { Import ASCII data into .WCP file format }
     Reset(F) ;
     nSamples := 0 ;
     TOld := 0. ;
     for i := 0 to NumSamplesPerRecord-1 do Buf^[i] := 0 ;
     SaveRecord := False ;

     while (not EOF(F)) do begin

          { Read in a row of text }
          ReadLn( F,s ) ;
          { Extract samples from  row }
          nCols := ExtractListOfFloats( s, Values, False ) ;

          if TCol >= 0 then begin
              T := Values[TCol] ;
              {If time value has decreased, create a new record }
              if T < Told then SaveRecord := True ;
              TOld := T ;
              end ;

          if EOF(F) then begin
             for Col := 0 to nCols-1 do if (Col <> TCol) then begin
                 Buf^[nSamples] := Trunc( Values[Col]*Scale[Col] ) ;
                 Inc(nSamples) ;
                 end ;
             SaveRecord := True ;
             end ;

          if SaveRecord then begin
             { Save record to file }
             Inc(RawFH.NumRecords) ;
             rH^.Status := 'ACCEPTED' ;
             rH^.RecType := 'TEST' ;
             rH^.Number := RawFH.NumRecords ;
             rH^.Time := rH^.Number ;
             rH^.dt := RawfH.dt ;
             rH^.Ident := ' ' ;
             for ch := 0 to RawFH.NumChannels-1 do rH^.ADCVoltageRange[ch] :=
                                                   RawFH.ADCVoltageRange ;
             rH^.Equation.Available := False ;
             rH^.Analysis.Available := False ;

             PutRecord( RawfH, rH^, RawfH.NumRecords, Buf^ ) ;
             { Clear buffer }
             for i := 0 to NumSamplesPerRecord-1 do Buf^[i] := 0 ;
             nSamples := 0 ;
             SaveRecord := False ;
             end ;

          for Col := 0 to nCols-1 do if (Col <> TCol) then begin
              Buf^[nSamples] := Trunc( Values[Col]*Scale[Col] ) ;
              Inc(nSamples) ;
              end ;

          if (nSamples >= NumSamplesPerRecord) then SaveRecord := True ;

          end ;

     SaveHeader(RawFH) ;
     { Close and re-open WCP file }
     FileClose( RawFH.FileHandle ) ;
     RawFH.FileHandle := FileOpen( RawFH.FileName, fmOpenReadWrite ) ;

     WriteToLogFile( 'ASCII Data File : ' + ImportFrm.FileName ) ;
     WriteToLogFile( 'converted to WCP file : ' + RawFH.FileName ) ;

     Dispose(Buf) ;
     Dispose(RH) ;
     end ;

end.
