*LSQ.CMD  Finds least squares fit for x vs. y
*
SET TALK OFF
STORE ' ' TO XVAR
STORE ' ' TO YVAR
STORE 0 TO NN
STORE 0 TO SMM
STORE 0 TO SSQ
STORE 0 TO XSUM
STORE 0 TO YSUM
STORE 0 TO X2SUM
STORE 0 TO Y2SUM
STORE 0 TO XYSUM
*
?
STORE 'X' TO LOOKFOR
DO WHILE LOOKFOR='X'
  ACCEPT 'Enter X variable name (? for lest)->' TO XVAR
    IF XVAR=' '
      RELEASE ALL
      RETURN
    ENDIF
    IF XVAR='?'
      DISP STRU
      LOOP
    ENDIF
    IF TYPE(&XVAR)<>'N'
      DISP OFF 'Non numeric variable, or no match in file.  Try again.'
      LOOP
    ENDIF
  STORE 'Y' TO LOOKFOR
ENDDO
*
DO WHILE LOOKFOR='Y'
  ACCEPT 'Enter Y variable name (? for list)->' TO YVAR
    IF YVAR=' '
      RELEASE ALL
      RETURN
    ENDIF
    IF YVAR='?'
      DISP STRU
      LOOP
    ENDIF
    IF TYPE(&YVAR)<>'N'
      DISP OFF 'Non numeric variable, or no match in file.  Try again.'
      LOOP
    ENDIF
  STORE 'DONE' TO LOOKFOR
ENDDO
?
* First pass for least squares fie
GO TOP
DO WHILE .NOT. EOF
  IF .NOT. *
    STORE NN+1 TO NN
    STORE (&XVAR+XSUM) TO XSUM
    STORE (&YVAR+YSUM) TO YSUM
    STORE (&XVAR*&YVAR+XYSUM) TO XYSUM
    STORE (&XVAR*&XVAR+X2SUM) TO X2SUM
    STORE (&YVAR*&YVAR+Y2SUM) TO Y2SUM
  ENDIF
  SKIP
ENDDO
*
* Data in, do least squares calcs
STORE XYSUM-(XSUM*YSUM/NN) TO NOM
STORE X2SUM-(XSUM*XSUM/NN) TO DNOM
STORE NOM/DNOM TO B
STORE (YSUM/NN)-(B*XSUM/NN) TO A
STORE (NOM*NOM)/(DNOM*(Y2SUM-(YSUM*YSUM)/NN)) TO R2
* 
* Initialize for pass two
GO TOP
DO WHILE .NOT. EOF
  IF .NOT. *
    STORE (A+B*&XVAR) TO YBAR
    STORE &YVAR-YBAR TO DELY
    STORE SMM+DELY TO SMM
    STORE DELY*DELY+SSQ TO SSQ
  ENDIF
  SKIP
ENDDO
* Compute variance for estimate
STORE (SSQ-(SMM*SMM)/NN)/(NN-1) TO VARI
*
* Display results
STOR '%' TO HARDCOPY
DO WHILE T
  ?
  DISP OFF 'Best fit:'
  DISP OFF YVAR,' = ' ,STR(A,12,4),' + ',STR(B,12,4),' * ',XVAR
  DISP OFF 'Index of determination (r2)=',STR(R2,6,4)
  DISP OFF 'Variance of the estimate =  ',STR(VARI,12,4)
  ?
  SET PRINT OFF
  IF HARDCOPY<>'%'
    RELEASE ALL
    RETURN
  ENDIF
  ACCEPT 'Hardcopy (Y/N)->' TO HARDCOPY
*
* Loop for hard copy if desired
  IF !(HARDCOPY)='Y'
    SET PRINT ON
    LOOP
  ENDIF
?
  SET TALK ON
  RELEASE ALL
RETURN