unit empripmain;
{*
 * EMPRIP Windows CD Audio extraction and MP3 Encoder
 * (C) 2003 Matthew J. Smith, Librarysmith Software
 * Based on AKRIP (http://akrip.sourceforge.net) cddb and audio extraction library
 * and the LAME projects (http://wwww.mp3dev.org) LAME_ENC.DLL.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published
 * by the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 *}

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
  StdCtrls,akrip32,global,verifyform, artworkform, ComCtrls,registry,
  Menus,albumartist,nolamedialog,lamenc_nice_interface, bitmapprogress,
  bitmapactionbutton, ExtCtrls,
  mydialog,isconnected, DdeMan,
  id3, tspinningglobe, bitmapcheckbox,windowsversion,resourceskins;

type
  Tripmain = class(TForm)
    go: TButton;
    cdselect: TGroupBox;
    cds: TComboBox;
    Label2: TLabel;
    mainmenu: TMainMenu;
    filemenu: TMenuItem;
    fileit: TMenuItem;
    optionsmenu: TMenuItem;
    optionsPreferences: TMenuItem;
    Helpmenu: TMenuItem;
    helpabout: TMenuItem;
    curpath: TLabel;
    inf: TLabel;
    progress: TBitmapProgress;
    cancel: TBitmapActionButton;
    log: TMemo;
    toptitle: TLabel;
    bg: TImage;
    encprogress: TBitmapProgress;
    jbcontrolpanel: TPanel;
    reject: TBitmapActionButton;
    mute: TBitmapActionButton;
    volup: TBitmapActionButton;
    voldown: TBitmapActionButton;
    labreject: TLabel;
    labmute: TLabel;
    labvolume: TLabel;
    jbshape1: TShape;
    jbautoplay: TBitmapCheckbox;
    toptitleshape: TShape;
    procedure goClick(Sender: TObject);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
    procedure FormCreate(Sender: TObject);
    procedure cancelClick(Sender: TObject);
    procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
    procedure logKeyPress(Sender: TObject; var Key: Char);
    procedure cdsChange(Sender: TObject);
    procedure fileitClick(Sender: TObject);
    procedure optionsPreferencesClick(Sender: TObject);
    procedure helpaboutClick(Sender: TObject);
    procedure FormActivate(Sender: TObject);
    procedure quitClick(Sender: TObject);
    procedure FormResize(Sender: TObject);
    procedure FormShow(Sender: TObject);
    procedure rejectClick(Sender: TObject);
    procedure muteClick(Sender: TObject);
    procedure jbautoplayClick(Sender: TObject);
    procedure volupMouseDown(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
    procedure volupMouseUp(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
    procedure voldownMouseDown(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);
    procedure voldownMouseUp(Sender: TObject; Button: TMouseButton;
      Shift: TShiftState; X, Y: Integer);

  private
    { Private declarations }
  public
    { Public declarations }
  end;

procedure sizeform(form : tform;caption : string;emposkneeded : boolean);
procedure dobg(form : tform);




Const SS_COMP = 1;
  FONTCOL = {viewgit}{/viewgit}00C6F7;
  WUM_AREYOUTHERE = 100;
  WUM_IMHERE = 101;
  WUM_CONNECTED = 102;
  WUM_EXIT = 103;

  type tid3titles = record
  count : integer;
  track : array of string;
  artist : string;
  album : string;
  end;

var
  ripmain: Tripmain;
  cancelop : boolean;
  tempfilename : string;
  cddrives : CDLIST;
  currentcd : integer;
  retry : boolean;
  manualentry : boolean = false;
  id3titles : tid3titles;
  apic : tbitmap;
  mres : integer;
  aspectx,aspecty : real;
  Sectiontitle : string ='Extract Compact Disk';
  spinglobe : TSpinglobe;
  starttime : ttime;
  enclastprog : dword;


function unaspx(x : integer) : integer;
function unaspy(y : integer) : integer;
function aspx(x : integer) : integer;
function aspy(y : integer) : integer;



procedure logent(m : string);
procedure closecd(cdhandle : integer);
procedure die;
function doedit(al : integer) : integer;
procedure rip_go;


implementation
uses multiple,editmenuform,threadedencode, jukeboxform;

var
enc : tmp3encode;

{$R *.DFM}

procedure rip_go;
var
freespace,scrap : tLargeInteger;
begin
getdiskfreespaceex(pchar(config.path),freespace,scrap,nil);
if freespace<629145600 then begin
   ripmain.show;
   md('There is not enough disk space available to complete this request.','Go Back','','',false);
   ripmain.close;
   exit;
end;
ripmain.show;
application.processmessages;
ripmain.goclick(nil);
end;


function unaspx(x : integer) : integer;
begin
result:=round(x/aspectx);
end;

function unaspy(y : integer) : integer;
begin
result:=round(y/aspecty);
end;


function aspx(x : integer) : integer;
begin
result:=round((x*aspectx));
end;

function aspy(y : integer) : integer;
begin
result:=round((y*aspecty));
end;

procedure die;
begin
osk(false,false);
ripmain.close;
application.ProcessMessages;
end;


procedure sizeform(form : tform;caption : string;emposkneeded : boolean);
begin
if ripmain=nil  then exit;

ripmain.toptitle.caption:=caption;

if emposkneeded=true then begin
form.width:=ripmain.width;
form.top:=ripmain.toptitle.top+ripmain.toptitle.height;
form.height:=((ripmain.height div 3)*2)-form.top;
form.left:=ripmain.left;
end else begin
form.width:=ripmain.width;
form.height:=ripmain.height-(ripmain.toptitle.top+ripmain.toptitle.height);
form.top:=ripmain.toptitle.top+ripmain.toptitle.height;
form.left:=ripmain.left;

end;

{for n:=0 to form.ControlsCount do begin
if propertyexists(form.controls[n],'font') then begin
form.controls[n].font.size:=aspx(form.controls[n].font.size);
end;
 }

end;

procedure dobg(form : tform);
var
str,dtr : trect;
begin

str.top:=form.top;
str.left:=form.left;
str.right:=form.width+str.left;
str.bottom:=form.height+str.top;

dtr.left:=0;
dtr.top:=0;
dtr.right:=form.width;
dtr.bottom:=form.height;



form.Canvas.CopyRect(dtr,ripmain.bg.canvas,str);
end;


procedure enumcddrives;
var
i : integer;

begin
//allocmem(sizeof(cd));
ripmain.cds.items.clear;
cddrives.max := MAXCDLIST;
fillchar(cddrives,sizeof(cddrives),0);
AKGetCDList( cddrives );
for i:=0 to cddrives.num-1 do begin
if (trim(string(cddrives.cd[i].info.vendor+cddrives.cd[i].info.prodId))<>'') then ripmain.cds.items.add(string(cddrives.cd[i].info.vendor+' '+cddrives.cd[i].info.prodId));
if ripmain.cds.items.count=0 then begin
md('Cannot find any CD-ROM drives.'#13#10'Check you have wnaspi32.dll installed correctly.'#13#10'See the EmpRip website for more information.','Try again','','Install problem',true);
end;
ripmain.cds.itemindex:=0;
end;


end;



procedure stopit(cdhandle : integer);
begin
spinglobe.stop;

if cdhandle<>0 then closecd(cdhandle);
screen.cursor:=crDefault;
ripmain.go.enabled:=true;
ripmain.cancel.visible:=false;
ripmain.cdselect.enabled:=true;
ripmain.progress.visible:=false;
ripmain.encprogress.visible:=false;

end;



procedure closecd(cdhandle : integer);
begin
if cdhandle<>0 then begin
   AKclosecdhandle(cdhandle);
end;
end;


procedure logent(m : string);
begin
ripmain.log.lines.add(m);
application.processmessages;
end;

{procedure writeWaveHeader(len : dword);
var
wav : TWAVEHDR;
begin
  wav.riff[0]:=ord('R');
  wav.riff[1]:=ord('I');
  wav.riff[2]:=ord('F');
  wav.riff[3]:=ord('F');
  wav.len := len + 44 - 8;
  wav.cWavFmt[0]:=ord('W');
  wav.cWavFmt[1]:=ord('A');
  wav.cWavFmt[2]:=ord('V');
  wav.cWavFmt[3]:=ord('E');
  wav.cWavFmt[4]:=ord('f');
  wav.cWavFmt[5]:=ord('m');
  wav.cWavFmt[6]:=ord('t');
  wav.cWavFmt[7]:=ord(' ');
  wav.dwHdrLen := 16;
  wav.wFormat := 1;
  wav.wNumChannels := 2;
  wav.dwSampleRate := 44100;
  wav.dwBytesPerSec := 44100*2*2;
  wav.wBlockAlign := 4;
  wav.wBitsPerSample := 16;
  wav.cData[0]:=ord('d');
  wav.cData[1]:=ord('a');
  wav.cData[2]:=ord('t');
  wav.cData[3]:=ord('a');
  wav.dwDataLen:= len;
  f.seek(0,soFromBeginning);
  f.write( wav, sizeof(wav));
end;

 }
procedure MSB2DWORD(var d : dword;b : quad);
var
ret : dword;
begin
ret:=dword(b[0]);
ret:=(ret shl 8) + dword(b[1]);
ret:=(ret shl 8) + dword(b[2]);
ret:=(ret shl 8) + dword(b[3]);
d:=ret;
end;

function newtrackbuf (numframes : dword) : PTRACKBUF;
var
numalloc : integer;
t : ptrackbuf;
begin
numalloc:=(integer(numFrames)*2352)*TRACKBUFEXTRA;
t:=ptrackbuf(allocmem(numalloc));
t.startFrame:=0;
t.numframes:=0;
t.maxlen:=numframes *2352;
t.len:=0;
t.status:=0;
t.startOffset:=0;
result:=t;
end;




procedure rip(fn : string;trck : integer);
var
tc : TOC;
dwstart : dword;
dwlen : longint;
num2rip : integer;
retries : integer;
status : dword;
//numWritten : dword;
t : PTRACKBUF;
progressunit : real;
laststart:dword;
errcount : integer;
f : tfilestream;
begin
errcount:=0;

ripmain.toptitle.caption:='Extracting';

if cdhandle <> 0 then begin
fillchar(tc,sizeof(tc),0);
AKModifyCDParms(cdhandle,CDP_MSF,0);
if AKReadToc(cdhandle,tc) <> SS_COMP then begin
mres:=md('Unable to read Table of Contents from CD.'#13#10'Try cleaning the disk.','Try Again','Exit','CD Error',false);
 if mres=mrCancel then begin
    die;
 end;
 exit;
end;


ripmain.progress.visible:=true;

MSB2DWORD(dwStart,tc.tracks[trck].addr);
MSB2DWORD(dword(dwLen),tc.tracks[trck+1].addr);

//laststart:=dwlen;
dwLen:=dwLen-dwStart;

progressunit:=100 / (dwlen+1);
ripmain.progress.max:=100;
//main.progress.min:=0;
ripmain.progress.position:=0;





laststart:=dwstart;
f:=tfilestream.create(fn,fmCreate);

t:=newtrackbuf(26);

//writewaveheader(0);{pops at beginning of file}
starttime:=now;
logent('Extracting data for track '+inttostr(trck+1)+' - "'+tracks[trck]+'"');
application.processmessages;

//c:=0;
num2rip:=26;



while (dwLen>0) and (cancelop=false) do begin
//inc(c);
//if not((c mod 5) = 0) then logent(inttostr(dwStart)+' '+inttostr(dwLen));
application.processmessages;
if (longint(dwLen)<num2rip) then num2rip:=dwlen;

retries:=5;
status := 0;
while (retries>0 ) and (Status <> SS_COMP) and (cancelop=false) do begin

      t.numFrames := num2rip;
      t.startOffset:=0;
      t.len:=0;
      t.StartFrame:=dwStart;
      application.processmessages;
      Status := AKReadCDAudioLBA(cdhandle,t);
      dec(retries);
      application.processmessages;
end;
ripmain.progress.position:=round((dwstart*progressunit)-(laststart*progressunit));
if enc<>nil then begin
   if enc.position>enclastprog then begin
    ripmain.encprogress.position:=enc.position;
    enclastprog:=enc.position;
   end;
end;

application.processmessages;

if (Status = SS_COMP) then begin
    f.write(t.buf,t.len-4);
//    f.write(t.startOffset,4);
//    numWritten :=numWritten + t.len;
  end
else begin
logent('CD Read Error.  (at:'+inttostr(dwStart)+'. code: '+inttostr(AKGetAspiLibError)+'). Continuing. Cancel and try cleaning the disk?');
inc(errcount);
if errcount>20 then begin
logent('Too many errors. Aborting. Possibly a data track?');
f.free;
ripmain.progress.visible:=false;
exit;
end;
end;
dwStart:=dwStart+dword(num2rip);
dwLen:=dwLen-dword(num2rip);
end;

//writeWaveHeader(numWritten);(pops at beginning of file}
f.free;
freemem(t);
ripmain.progress.max:=100;
//main.progress.min:=0;
ripmain.progress.position:=0;
ripmain.progress.visible:=false;
application.processmessages;

end;

end;


procedure Tripmain.goClick(Sender: TObject);
var
  n : integer;
  GCDHandle : GETCDHAND;
  query : TCDDBQUERY;
  cdID : array[0..99] of dword;
  qi : CDDBQUERYITEMS;
  cddbtext: array [0..104800] of char;
  albs : talbums;
  lines : array of string;
  linescount : integer;
  scrap,l,r : string;
  temppath: array[0..255] of char;
  tc : TOC;
  ms : string;
  meslevel : integer;
  mes : string;




procedure mywaitfor;
begin
while(enc.finished=false) do begin
if enc.position>enclastprog then encprogress.position:=enc.position;
   enclastprog:=enc.position;
   application.processmessages;
end;
//enc:=nil;
end;


procedure doripping;
var
n : integer;
begin
jukebox.lcd3.running:=false;
   spinglobe.stop;

   cancel.visible:=true;

   ripmain.log.visible:=true;
   jbcontrolpanel.visible:=true;

   inf.caption:='Extracting and Encoding';
   starttime:=now;

   progress.position:=1;
   progress.repaint;

   application.ProcessMessages;



   //GetTempPath(sizeof(temppath),temppath);

   cancelop:=false;
   enc:=nil;
   application.processmessages;
   for n:=0 to trackscount-1 do begin

                                  if cancelop=true then begin
                                  stopit(cdhandle);
                                  jukebox.lcd3.running:=true;
                                  application.processmessages;
                                  exit;
                                  end;

                                  strpcopy(temppath,cachepath);
                                  tempfilename:=temppath+'\track'+inttostr(n)+'.tmp';

                                  rip(tempfilename,n);
                                     if cancelop=true then begin
                                        stopit(cdhandle);
                                        jukebox.lcd3.running:=true;
                                        application.processmessages;
                                        exit;
                                  end;

                                  if enc<>nil then begin
                                  //  enc.WaitFor;
                                    mywaitfor;
                                  end;

                                  if cancelop=true then begin
                                        stopit(cdhandle);
                                        jukebox.lcd3.running:=true;
                                        application.processmessages;
                                        exit;
                                  end;

                                  application.processmessages;

                                  enclastprog:=0;
                                  enc:=tmp3encode.create(true);
                                  if getwindowsversion>2 then enc.priority:=tpNormal else enc.Priority:=tpHigher;
                                  enc.infile:=tempfilename;
                                  enc.outfile:=config.path+albumpath+'\track'+format('%.2d',[n+1])+'.mp3';
                                  enc.trackname:=id3titles.track[n];
                                  enc.artistname:=id3titles.artist;
                                  enc.albumname:=id3titles.album;
                                  enc.tracknumber:=n+1;
                                  enc.FreeOnTerminate:=true;
                                  enc.resume;
                                  application.processmessages;
                                  end;




  //enc.waitfor;
  mywaitfor;

progress.visible:=false;
ripmain.progress.position:=0;
jukebox.lcd3.running:=true;
application.ProcessMessages;

end;


procedure gettracks(alb : integer);
var
n : integer;
begin

       application.processmessages;
       fillchar(cddbtext,length(cddbtext),0);
       AKCDDBGetDiskInfo(qi.items[alb],cddbtext,104800);
       // split into lines
       scrap:='';
       linescount:=0;
       for n:=1 to length(cddbtext)-1 do begin
         if (cddbtext[n]<>#13) and (cddbtext[n]<>#10) then scrap:=scrap+cddbtext[n];
         if  (cddbtext[n]=#13) then begin
             inc(linescount);
             setlength(lines,linescount);
             lines[linescount-1]:=scrap;
             scrap:='';
         end;
       end;
       //split into tracks
       trackscount:=0;
       for n:=0 to linescount-1 do begin
       split(lines[n],'=',l,r);
       scrap:=copy(l,1,6);
       if uppercase(scrap)='TTITLE' then begin
                                         inc(trackscount);
                                         setlength(tracks,trackscount);
                                         tracks[trackscount-1]:=r;
                                         end;

       end;
end;


begin
cdselect.enabled:=false;
cancelop:=false;
cancel.color:=clBlack;
cancel.caption:='Cancel';
log.lines.clear;
go.enabled:=false;
screen.cursor:=crHourglass;
fillchar(Gcdhandle,sizeof(Gcdhandle),0);
Gcdhandle.size:=sizeof(Gcdhandle);
Gcdhandle.ver:=1;
Gcdhandle.ha:=cddrives.cd[currentcd].ha;
Gcdhandle.tgt:=cddrives.cd[currentcd].tgt;
Gcdhandle.lun:=cddrives.cd[currentcd].lun;
Gcdhandle.readtype:=CDR_ANY;
Gcdhandle.jitterCorr:=false;
Gcdhandle.numJitter:=1;
Gcdhandle.numOverlap:=3;
trackscount:=0;

cdhandle:=AKgetcdhandle(Gcdhandle);
if (cdhandle=0) then begin
AKgetaspiliberror;
md('Could not open the CD drive.','Exit','','Hardware Error',false);
stopit(cdhandle);
die;
exit;
end;

meslevel:=-1;
mes:='Insert a CD and hit contine';
retry:=true;
while (retry=true) do begin
 if AKReadToc(cdhandle,tc) <> SS_COMP then begin
 inc(meslevel);
 if meslevel>0 then begin
    mes:='Unable to read CD.'#13#10'You may need to wait to for the CD to spin up.'#13#10'Click continue when ready.';
    meslevel:=1;
    end;
 if md(mes,'Continue','Exit','CD Extraction - Insert CD',false)=mrCancel then begin
    retry:=false;
    stopit(cdhandle);
    die;
    exit;
   end;
 end else retry:=false;
end;


retry:=true;
if Checkhost('8.8.8.8')=false then begin
while (retry=true) do begin
  mres:=md('A connection to the internet is needed to find album information.','Try Again','Manually enter information','Internet Connection',true);
  if mres=idAbort then begin
                       screen.cursor:=crDefault;
                       die;
                       exit;
                       end;
  if mres=mrCancel then begin
    retry:=false;
    manualentry:=true;
    //stopit(cdhandle);
   end
  else begin
 retry:=true;
//if runprogram('rasdialr.exe',0,false) = true then begin
 //ms:='';
 //while ((ms<>'connected') and (ms<>'exit')) do begin
 //ms:=readmailslot;
 //application.processmessages;
 //retry:=false;
 //end;
 //end;
 end;
 end;
end;

spinglobe.left:=((Width div 2) - (spinglobe.height div 2));
spinglobe.top:=((height div 2) - (spinglobe.height div 2));

application.processmessages;
spinglobe.start;
application.processmessages;
spinglobe.start;
application.processmessages;


toptitle.caption:='Getting CDDB Server Information';
application.processmessages;


//Go online to myjukebox.co.uk and figure out what CDD server to use.
// But Only if string is empty
//if config.cddbserver='' then  getfreedbserver;


toptitle.caption:='Getting Album Information';
application.processmessages;
fillchar(query,sizeof(query),0);
fillchar(qi,sizeof(qi),0);
query.num:=5;
query.q := @qi;
AKCDDBSetOption(CDDB_OPT_SERVER, pchar(config.cddbserver), 0 );
AKCDDBSetOption(CDDB_OPT_CGI,pchar(config.cddbcgi) , 0 );
AKCDDBSetOption(CDDB_OPT_USER, pchar(config.email), 0 );
AKCDDBSetOption(CDDB_OPT_AGENT, pchar(apptitle+' '+appversion), 0 );
AKCDDBSetOption(7,'80',80);
AKCDDBSetOption(8,'',0);
application.processmessages;
AKGetCDDBDiskID( cdhandle,cdID, sizeof(cdID));

AKModifyCDParms(cdhandle,CDP_MSF,0);
if AKCDDBQuery(cdhandle,query)=SS_COMP then begin
n:=0;
albs.count:=0;
   if (query.num>0) then begin
       if query.num>0 then begin
        for n:=0 to query.num-1 do begin
           application.processmessages;
            inc(albs.count);
            setlength(albs.titles,albs.count);
            setlength(albs.artists,albs.count);
            albs.artists[n]:=qi.items[n].artist;
            albs.titles[n]:=qi.items[n].title;//stripnulls(qi[n].title);
         end;

      toptitle.caption:='Getting Track Information';

      spinglobe.left:=((Width div 2) - (spinglobe.height div 2));
      spinglobe.top:=((height div 2) - (spinglobe.height div 2));
      spinglobe.start;

      n:=query.num;
      trackscount:=0;
      while trackscount=0 do begin
      application.processmessages;
      n:=multipledialog(albs);


         if n=-1 then begin
            stopit(cdhandle);
            die;
            exit;
         end;

        if n<>-4 then gettracks(n) else begin
         trackscount:=0;
         break;
        end;




        if trackscount=0 then begin
           mres:=md('Internet CDDB returned no track information. Disk ID '+IntToHex(cdID[0], 8)+#13#10'Using server path: '+config.cddbserver+config.cddbcgi+#13#10'Enter album information manually?'#13#10#13#10'Select Manual to enter album information manually or Try Again to reselect the album.','Manual','Try again','Information Aquisition',true);
           if mres=idAbort then begin
           die;
           exit;
           end;
           if mres=mrYes then break;
        end;
      end;
      end;


if trackscount>0 then begin
    artist:=stripnulls(qi.items[n].artist);
    title:=stripnulls(qi.items[n].title);
    id3titles.artist:=artist;
    id3titles.album:=title;

   spinglobe.stop;
   ripmain.caption:=apptitle+': '+artist+'-'+title;
   if doverify(0)=mrcancel then begin
   stopit(cdhandle);
   //goclick(nil);
   die;
   exit;
   end;


   if doartwork(0)=mrcancel then begin
   stopit(cdhandle);
   die;
   exit;
   end;




   doripping;
   closecd(cdhandle);

end;
end
else begin



     if manualentry=false then begin
     mres:=md('Could not query CD database.'#13#10'The CD is not recognised, there is a problem with your Internet connection.(Disk ID '+IntToHex(cdID[0], 8)+')'#13#10'Using server path: '+config.cddbserver+config.cddbcgi+#13#10' or the CD is not in the internet database.'#13#10#13#10'Select Manual to enter album information manually.','Manual','Cancel','CD Database',false);
     if mres=idAbort then begin
     die;
     exit;
     end;
     if mres=mrCancel then begin
          die;
          screen.cursor:=crDefault;
          exit;
     end;
     end;
end;


if trackscount=0 then begin
   if AKReadToc(cdhandle,tc) <> SS_COMP then begin
      md('Unable to read Table of Contents from CD:'+inttostr(AKgetaspiliberror),'','Cancel','CD Error',true);
      stopit(cdhandle);
      exit;
      end;
    trackscount:=0;
    for n:=0 to tc.lastTrack-1 do begin
       inc(trackscount);
       setlength(tracks,trackscount);
       tracks[trackscount-1]:='Track '+inttostr(n+1);
     end;

     title:='';
     artist:='';
     spinglobe.stop;
  mres:=getuseralbumtitle(title,artist);
  if mres=idAbort then begin
    die;
    exit;
  end;
  if mres=mrcancel then begin
    stopit(cdhandle);
    //goclick(nil);
    die;
    exit;
  end;
  spinglobe.stop;
  if doverify(0)=mrcancel then begin
    stopit(cdhandle);
    //goclick(nil);
    die;
    exit;
  end;


retry:=true;
if Checkhost('8.8.8.8')=false then begin
  while (retry=true) do begin
    mres:=md('A connection to the internet is needed to find artwork.','Connect to Internet','Use manual information','Artwork Aquision',true);
    if mres=idAbort then begin
               die;
               exit;
   end;
    if mres=mrCancel then begin
      retry:=false;
      manualentry:=true;
      //stopit(cdhandle);
    end
    else begin
    //Old modem dialer
      retry:=true;
      runprogram('rasdialr.exe',0,false);
      ms:='';
       while ((ms<>'connected') and (ms<>'exit')) do begin
        ms:=readmailslot;
        application.processmessages;
      end;
      retry:=true;
      if ms='connected' then retry:=false;
    end;
  end;
end;


  if doartwork(0)=mrcancel then begin
    stopit(cdhandle);
    die;
    exit;
  end;

   doripping;
end;
closecd(cdhandle);
end;

stopit(cdhandle);
logent('Completed.');
addalbum(artist,title);
die;
end;

procedure Tripmain.FormClose(Sender: TObject; var Action: TCloseAction);
begin
//UnLoadLameEncDLL;
closecd(cdhandle);
end;



procedure Tripmain.FormCreate(Sender: TObject);
var
emppath : string;
sysdir : array [0..255] of char;
cdpic : tbitmap;
a : tbitmap;
tr : trect;

begin
aspectx:=(screen.width/800);
aspecty:=(screen.height/600);

if mshand=0 then initmailslot;

sizeform(self,'Compact Disk Extraction',false);

bg.top:=0;
bg.left:=0;



//kiosk
ripmain.doublebuffered:=true;
ripmain.width:=screen.width;
ripmain.height:=screen.height;
bg.width:=ripmain.width;
bg.height:=ripmain.height;


a:=LoadSkinResource('ADMINBACKDROP','',clNone,true);
tr.top:=0;
tr.left:=0;
tr.bottom:=bg.height;
tr.right:=bg.width;
bg.canvas.StretchDraw(tr,a);

spinglobe:=tspinglobe.create(self);
spinglobe.stop;

spinglobe.left:=((Width div 2) - (spinglobe.height div 2));
spinglobe.top:=((height div 2) - (spinglobe.height div 2));

toptitle.font.size:=aspx(24);
toptitle.Font.color:=clWhite;
ripmain.toptitle.autosize:=true;
toptitle.Caption:=SectionTitle;
ripmain.toptitle.autosize:=false;
{$IFDEF kiosk}
ripmain.borderstyle:=bsNone;
{$ENDIF}
ripmain.toptitle.left:=aspx(10);
ripmain.toptitle.alignment:=taCenter;
ripmain.toptitle.top:=aspy(28);
ripmain.toptitle.width:=width-aspx(20);

toptitleshape.pen.color:=FONTCOL;
//toptitleshape.SendToBack;
toptitleshape.pen.width:=2;
toptitleshape.top:=toptitle.top-2;
toptitleshape.left:=toptitle.left-2;
toptitleshape.width:=toptitle.width+4;
toptitleshape.height:=toptitle.height+2;






cdpic:=tbitmap.create;
cdpic.loadfromresourcename (hinstance,'cd');
progress.assignbackground(cdpic);
cdpic.free;

cdpic:=tbitmap.create;
cdpic.loadfromresourcename (hinstance,'dataprog');
encprogress.assignbackground(cdpic);
cdpic.free;

encprogress.radius:=aspx(100);
encprogress.startradius:=0;
encprogress.max:=100;
encprogress.position:=100;
encprogress.Refresh;

progress.radius:=aspx(100);
progress.startradius:=aspx(36);

cancel.visible:=false;


cdselect.visible:=false;
log.visible:=false;
jbcontrolpanel.visible:=false;
go.Visible:=false;
curpath.visible:=false;
ripmain.color:=clblack;
//kiosk
inf.autosize:=false;
inf.width:=ripmain.width;
inf.height:=100;
inf.left:=0;
inf.top:=10;
inf.Font.size:=aspx(18);
inf.Font.name:=JUKEBOXFONT;
inf.font.color:=clLime;
inf.caption:='Get CD Information';
inf.Alignment:=tacenter;
cancel.visible:=false;

//maintitle.font.size:=18;
//maintitle.font.color:=clred;
//maintitle.font.name:='';
//maintitle.top:=28;
//maintitle.left:=329;
//maintitle.height:=32;
//maintitle.width:=66;

progress.visible:=false;
encprogress.visible:=false;






if LoadLameEncDLL=false then begin
//see if the lamewin32 package is installed (http://www.mp3-tech.org/encoders_win.html)

if fileexists('C:\PROGRAM FILES\LAME\LAME_ENC.DLL') then begin
 getsystemdirectory(sysdir,sizeof(sysdir));
 copyfile(pchar('C:\PROGRAM FILES\LAME\LAME_ENC.DLL'),pchar(sysdir+'\LAME_ENC.DLL'),true);
end;

if LoadLameEncDLL=false then donolame;
end;
firstrun:=false;
emppath:='';
firstrun:=true;

ripmain.caption:='EmpRip';
screen.cursor:=crhourglass;
//Taken out because casuing a delay on Vista Machine (possibly my hardware) PUT BACK!!
enumcddrives;
screen.cursor:=crdefault;
ripmain.left:=(screen.width div 2) - (ripmain.width div 2);
ripmain.top:=(screen.height div 2) - (ripmain.height div 2);
end;

procedure Tripmain.cancelClick(Sender: TObject);
begin
cancelop:=true;
if enc<>nil then enc.terminate;
end;

procedure Tripmain.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
cancelop:=true;
end;

procedure Tripmain.logKeyPress(Sender: TObject; var Key: Char);
begin
Key:=#0;
end;

procedure Tripmain.cdsChange(Sender: TObject);
begin
currentcd:=cds.itemindex;
end;

procedure Tripmain.fileitClick(Sender: TObject);
begin
cancelop:=true;
die;
end;

procedure Tripmain.optionsPreferencesClick(Sender: TObject);
begin
cancelop:=true;
//showprefs(false);
end;

procedure Tripmain.helpaboutClick(Sender: TObject);
begin
//showabout;
end;

procedure Tripmain.FormActivate(Sender: TObject);
begin
ripmain.Menu:=nil;
currentcd:=0;
end;

function doedit(al : integer) : integer;
begin
ripmain.show;
//loadtitles(tracks,album);
result:=goeditmenu(al);
end;


procedure Tripmain.quitClick(Sender: TObject);
begin
die;

end;

procedure Tripmain.FormResize(Sender: TObject);
begin
 log.top:=inf.top+inf.height+10;
   log.color:=$D8E2BA;
   log.height:=(ripmain.width div 4);
   log.width:=round(ripmain.width / 1.5);
   log.left:=(ripmain.width div 2)-(log.width div 2);

   log.font.size:=aspx(12);
   log.font.color:=clBlack;
   log.font.name:=DEFAULTFONT;
   log.font.name:='Garamond';
   cancel.width:=150;
   cancel.left:=(ripmain.width div 2)-(cancel.width div 2);

   cancel.font.color:=FONTCOL;
   cancel.font.name:=JUKEBOXFONT;
   cancel.font.size:=aspx(18);



   progress.DoubleBuffered:=true;
   encprogress.DoubleBuffered:=true;
   progress.width:=aspy(200);
   progress.height:=progress.width;
   progress.left:=(ripmain.width div 2) - (progress.width);
   progress.top:=log.top+log.height+10;

   encprogress.left:=(ripmain.width div 2);
   encprogress.top:=log.top+log.height+10;
   encprogress.width:=progress.width;
   encprogress.height:=progress.height;

   jbcontrolpanel.width:=jbautoplay.width+aspx(40);
   jbcontrolpanel.left:=(width-(jbcontrolpanel.width+aspx(10)));
   jbcontrolpanel.top:=log.top;

   if jukebox.autoplaycb.checked=false then jbautoplay.checked:=false else jbautoplay.checked:=true;


   jbshape1.Pen.color:=FONTCOL;
   labreject.font.color:=FONTCOL;
   labreject.font.size:=aspy(8);
   labmute.font.color:=labreject.font.color;
   labmute.font.size:=labreject.font.size;
   labvolume.font.color:=labreject.font.color;
   labvolume.font.size:=labreject.font.size;
   jbautoplay.font.color:=labreject.font.color;
   jbautoplay.font.size:=labreject.font.size;


   reject.top:=aspy(10);
   mute.top:=aspy(10);
   reject.width:=40;
   mute.width:=40;
   volup.width:=40;
   voldown.width:=40;

   reject.left:=((jbcontrolpanel.width div 2) div 2) - (reject.width div 2);
   voldown.left:=reject.left;
   mute.left:=reject.left+(jbcontrolpanel.width div 2);
   volup.left:=mute.left;

   labreject.caption:='Reject';
   labmute.caption:='Mute';
   labvolume.caption:='Volume Control';
   jbautoplay.caption:='Auto-play on';

   labreject.width:=jbcontrolpanel.width div 2;
   labmute.width:=labreject.width-2;
   labvolume.width:=jbcontrolpanel.width-2;

   labreject.alignment:=taCenter;
   labmute.alignment:=taCenter;
   labvolume.alignment:=taCenter;


   labreject.top:=reject.top+reject.height;
   labmute.top:=labreject.top;

   volup.top:=labreject.top+labreject.height+aspy(10);
   labvolume.top:=volup.top+volup.height;
   voldown.top:=volup.top;

   labreject.left:=1;
   labvolume.left:=1;
   labmute.left:=jbcontrolpanel.width div 2;

   jbautoplay.left:=aspx(10);
   jbautoplay.top:=labvolume.top+labvolume.height+aspy(10);


   jbcontrolpanel.height:=jbautoplay.top+jbautoplay.height+aspy(10);

   labmute.sendtoback;
   labvolume.sendtoback;
   labreject.sendtoback;











   cancel.top:=progress.top+progress.height+aspy(10);

end;

procedure Tripmain.FormShow(Sender: TObject);
begin
log.visible:=false;
jbcontrolpanel.visible:=false;
if mshand<>0 then begin
   if closehandle(mshand)<>false then mshand:=0;
   initmailslot;
end;
//formcreate(nil);  // Creates a large delay when button clicked, is is necesary?
end;

procedure Tripmain.rejectClick(Sender: TObject);
begin
if (enc<>nil) then if (enc.finished=false) then enc.Priority:=tpLower;
jukebox.panelshapeMouseDown(jukebox.rejectshape2,mbleft,[], 0, 0);
jukebox.panelshapeMouseUp(jukebox.rejectshape2,mbleft,[], 0, 0);
if (enc<>nil) then if (enc.finished=false) then enc.Priority:=tpHigher;
end;

procedure Tripmain.muteClick(Sender: TObject);
begin
if (enc<>nil) then if (enc.finished=false) then enc.Priority:=tpLower;
jukebox.panelshapeMouseDown(jukebox.muteshape2,mbleft,[], 0, 0);
jukebox.panelshapeMouseUp(jukebox.muteshape2,mbleft,[], 0, 0);
if (enc<>nil) then if (enc.finished=false) then enc.Priority:=tpHigher;
end;





procedure Tripmain.jbautoplayClick(Sender: TObject);
begin
if (enc<>nil) then if (enc.finished=false) then enc.Priority:=tpLower;
jukebox.autoplaycb.checked:=jbautoplay.checked;
jukebox.autoplaycbclick(nil);
if (enc<>nil) then if (enc.finished=false) then enc.Priority:=tpHigher;
application.processmessages;
end;

procedure Tripmain.volupMouseDown(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
begin
beep;
if (enc<>nil) then if (enc.finished=false) then enc.Priority:=tpLower;
jukebox.panelshapeMouseDown(jukebox.volumeupshape2,mbleft,[], 0, 0);
if  (enc<>nil) then if (enc.finished=false)  then enc.Priority:=tpHigher;
end;

procedure Tripmain.volupMouseUp(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
begin
if (enc<>nil) then if (enc.finished=false) then enc.Priority:=tpLower;
jukebox.panelshapeMouseUp(jukebox.volumeupshape2,mbleft,[], 0, 0);
if (enc<>nil) then if (enc.finished=false) then enc.Priority:=tpHigher;
end;

procedure Tripmain.voldownMouseDown(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
begin
if (enc<>nil) then if (enc.finished=false) then enc.Priority:=tpLower;
jukebox.panelshapeMouseDown(jukebox.volumedownshape2,mbleft,[], 0, 0);
if (enc<>nil) then if (enc.finished=false) then enc.Priority:=tpHigher;
end;

procedure Tripmain.voldownMouseUp(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
begin
if (enc<>nil) then if (enc.finished=false) then enc.Priority:=tpLower;
jukebox.panelshapeMouseUp(jukebox.volumedownshape2,mbleft,[], 0, 0);
if (enc<>nil) then if (enc.finished)=false  then enc.Priority:=tpHigher;
end;

end.