module disk(mclk28, read_disk_data, c6_io, reset,  
	addr, wr,  ram_addr, track,disk_phase);
    input mclk28,c6_io,reset,read_disk_data;
   input [7:0] addr;
   input       wr;
   output [12:0] ram_addr;
   output [5:0]   track;
   output [3:0]   disk_phase;

   reg [1:0] 	  last_phase_on;
   reg 		  last_odd_phase;			// 0 is 1, 1 is 3
   reg [3:0] 	  phase;
   reg [3:0] 	  prev_phase;
   reg 		  drive_sel;
   reg 		  drive_on;
   reg 		  f1, write;
   reg [5:0] 	  track_num; //up to 34
   reg [12:0] 	  byte_cntr; // 1a00 total

   wire [35:0] 	  P;

   
   assign 	  ram_addr = byte_cntr;
   assign 	  disk_phase = phase;
   assign 	  track = track_num;

   always @(posedge mclk28) begin
      if(reset) 
	byte_cntr  <= 0;
      else if(read_disk_data) 
	begin
	   if(byte_cntr  == 'h1a00)
	     byte_cntr  <= 0;
	   else
	     byte_cntr  <= byte_cntr + 1;
	end
   end

   always @(posedge mclk28) begin
      if(reset) begin
	 track_num <= 0;
      end else begin

	 if(phase[0] & ! prev_phase[0]) begin
	    //	if(phase[3] && (track_num != 34)) begin
	    if(last_odd_phase && (track_num != 34)) begin
	       track_num <= track_num + 1;
	    end
	    else if (~last_odd_phase && (track_num != 0))
	      begin //((last_phase_on == 1)  && (track_num != 0))
		 track_num <= track_num - 1;
	      end
	 end
	 if(phase[2] & ! prev_phase[2]) begin
	    if(~last_odd_phase  && (track_num != 34)) begin
	       track_num <= track_num + 1;
	    end
	    else if (last_odd_phase && (track_num != 0)) //((last_phase_on == 3)  && (track_num != 0))
	      begin
		 track_num <= track_num - 1;
	      end
	 end

	 if(phase[1] & ! prev_phase[1])
	   last_odd_phase <= 0;

	 if(phase[3] & ! prev_phase[3])
	   last_odd_phase <= 1;

	 prev_phase <= phase;
      end	// not reset
   end // always

   always @(posedge mclk28) begin
      if(reset) begin
	 phase <= 4'b0;
	 drive_sel <= 0;
	 drive_on  <= 0;
	 f1 <= 0;
	 write <= 0;
      end
      else 	 	
	if(c6_io)  begin

//	   prev_phase <= phase;

	   case(addr[3:1])
	     3'b000:  	phase[0] <= addr[0];
	     3'b001: 	phase[1] <= addr[0];
	     3'b010: 	phase[2] <= addr[0];
	     3'b011:	phase[3] <= addr[0];
	     3'b100: 	drive_on <= addr[0];
	     3'b101: 	drive_sel <= addr[0];
	     3'b110: 	f1 <= addr[0];
	     3'b111: 	write <= addr[0];
	   endcase
 	end //if(c6_io)
   end
endmodule
